Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2082,10 +2082,13 @@ Use this file for global constraints. Use feature specs under `specs/` for domai
canonical claim directly.
- Keep local-model network access in the browser or the explicitly launched
loopback companion so a hosted Worker never assumes it can reach localhost.
- Configure the companion with one fixed credential-free loopback upstream and
one exact allowed browser origin. Bind it only to `127.0.0.1`, bound and
validate both sides of the request, reject redirects, and never accept a
browser-selected upstream.
- Configure the companion with one fixed upstream and one exact allowed
browser origin. Bind it only to `127.0.0.1`, bound and validate both sides of
the request, reject redirects, and select the upstream at process startup.
Credential-free forwarding uses loopback. Authenticated gateway forwarding
requires HTTPS, one configured model, a local upstream key, and a separate
tab-scoped browser token. The npm executable packages the forwarding backend
from the same source as the checkout companion.
- Supervise the configured companion alongside the local Worker under
`npm run dev`, but strip all model-specific environment variables from the
Worker child, disable Wrangler's automatic `.env` discovery, keep Worker
Expand Down
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,15 @@ the stable canary source. Generated browser assets are written to the ignored

## Configure a Writing Model

Kirjolab does not require a model API key. A revision request contains only the
selected passage, your instruction, the evidence you selected, and the model
identifier. The default path sends it directly from the browser to a
credential-free, OpenAI-compatible service running on your computer.
The default connection sends each revision request directly from your browser
to a credential-free, OpenAI-compatible service on your computer. The request
contains the selected passage, your instruction, your selected evidence, and
the model identifier.

For an HTTPS model gateway reachable from your Mac, including the Aalto LLM
Gateway over VPN, use the [npm companion setup guide](./packaging/model-companion/README.md).
The companion uses your gateway API key locally and provides the configured
model ID to Kirjolab.

If the browser cannot reach that service directly, use the optional local
companion. Configure it once, then restart the ordinary development command:
Expand Down
1 change: 1 addition & 0 deletions docs/adrs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ No accepted-but-unimplemented ADRs.

| ADR | Status | Summary |
| ----------------------------------------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------- |
| [ADR-255](./implemented/ADR-255-package-the-gateway-model-companion.md) | Implemented | Distribute the forwarding companion through npm and support one authenticated HTTPS model gateway. |
| [ADR-254](./implemented/ADR-254-summarize-the-manuscript-outline-on-demand.md) | Implemented | Add disposable reverse-outline summaries with explicit generation and bounded section inputs. |
| [ADR-253](./implemented/ADR-253-use-the-mcp-sdk-handler-directly.md) | Implemented | Use the MCP SDK's stateless handler directly and remove the Agents production build-tool dependency path. |
| [ADR-252](./implemented/ADR-252-place-navigation-restore-in-surface-controls.md) | Implemented | Place Library navigation restoration in normal-flow action and PDF rail slots under one control owner. |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# ADR-255: Package the Gateway Model Companion

**Status:** Implemented

**Date:** 2026-11-18

**Amends:** [ADR-117](./ADR-117-scope-dotenv-loading-to-the-model-companion.md)
and [ADR-234](./ADR-234-run-codex-through-the-local-companion.md)

## Context

Researchers want to use models on institutional gateways reachable from their
workstations. Aalto's gateway requires its network or VPN and restricts browser
origins. A local process can access it over the VPN. The checkout companion
already provides a bounded browser-facing interface but requires a repository
checkout and can forward only to a loopback model service.

## Decision

Package the existing OpenAI-compatible forwarding backend as the
`kirjolab-model-companion` npm executable. The package uses Node and accepts an
explicit dotenv file. The checkout launcher also loads the Codex SDK when
configured for Codex.

Keep credential-free forwarding on loopback. A configured upstream API key
enables forwarding to one HTTPS completion URL with one named model. Require
the exact Kirjolab browser origin and an independent browser bearer token for
discovery and completion. Send the upstream key only to the configured gateway.
Publish the configured model on the companion's model-list route and accept it
on completion requests. The browser stores the pairing token in session storage.
The hosted Worker continues to serve the application while model requests use
the researcher's network connection.

## Consequences

Colleagues can run the companion through npm without installing the full
development toolchain. The same workflow supports existing local model
servers. Gateway users keep a local config, need gateway network access, and
enter the companion token in each browser session. Maintainers distribute a
separate npm artifact.

## Alternatives Considered

- A browser-direct gateway connection requires the institution to allow the
deployed app's origin and each user's browser to reach the gateway.
- A shared relay requires an operator and hosting with institutional network
access.
- A browser extension requires browser-specific packaging and distribution.
24 changes: 24 additions & 0 deletions docs/development.md
Original file line number Diff line number Diff line change
Expand Up @@ -475,6 +475,30 @@ For example, an iPad browser cannot reach a companion running on a Mac through
this path. Keep Worker-only local secrets in `.dev.vars`; the companion settings
belong in `.env` and are never deployed.

#### Package the Model Companion

The [companion setup guide](../packaging/model-companion/README.md) covers npm
users and authenticated HTTPS gateways such as Aalto. The npm CLI runs the
OpenAI-compatible forwarding backend from the same source as the checkout
companion. The checkout's `npm run model:companion` also supports Codex.

Build the npm tarball with the repository's pinned Node and npm from an
installed checkout. Pass an existing destination directory explicitly.

```sh
npm run model:companion:pack -- --pack-destination /path/to/release-directory
```

The pack command stages the executable, manifest, README, and license in a
temporary directory and removes it on exit. It writes the tarball to the chosen
destination. Test the resulting tarball in a directory outside the checkout.

```sh
npm exec --package=/path/to/release-directory/kirjolab-model-companion-0.1.0.tgz -- kirjolab-model-companion --help
```

An npm release can publish that same tarball with `npm publish /path/to/release-directory/kirjolab-model-companion-0.1.0.tgz`.

The Lighthouse setup is also generic, but the Worker stub gives it a concrete local target. Use `LIGHTHOUSE_URL=http://127.0.0.1:8787 LIGHTHOUSE_SERVER_COMMAND="npm run dev" npm run lighthouse`. Reports are written to `reports/lighthouse/`.

The Node Vitest setup remains the fast home for pure logic. `vitest.config.mts`
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
"build": "npm run build:css && npm run build:browser-shell && npm run build:pdf-worker",
"build:browser-shell": "node ./scripts/build-browser-shell.mjs",
"build:css": "mkdir -p ./.generated && tailwindcss -i ./src/tailwind-input.css -o ./.generated/styles.css --minify",
"build:model-companion": "mkdir -p ./.generated && esbuild src/model-companion.ts --bundle --platform=node --format=esm --target=node24 --outfile=.generated/model-companion.mjs",
"build:model-companion": "esbuild scripts/run-model-companion.mjs --bundle --platform=node --format=esm --target=node24 --outfile=.generated/model-companion.mjs",
"build:paper-import-package": "node ./scripts/build-paper-import-package.mjs",
"build:pdf-worker": "node ./scripts/build-pdf-worker.mjs",
"check:adrs": "node ./scripts/check-adr-registry.mjs",
Expand Down Expand Up @@ -115,6 +115,7 @@
"maintenance:clean": "node ./scripts/clean-local-state.mjs",
"lint": "oxlint --max-warnings 0",
"model:companion": "npm run build:model-companion && node --env-file-if-exists=.env ./.generated/model-companion.mjs",
"model:companion:pack": "node ./scripts/pack-model-companion.mjs",
"mutation": "NODE_OPTIONS=--max-old-space-size=8192 node ./scripts/run-mutation.mjs",
"mutation:affected": "NODE_OPTIONS=--max-old-space-size=8192 stryker run --ignoreStatic --reporters clear-text,progress",
"mutation:ci": "node ./scripts/run-ci-mutation.mjs",
Expand Down
73 changes: 73 additions & 0 deletions packaging/model-companion/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Kirjolab Model Companion

The companion runs on the same Mac as your browser. It connects Kirjolab to an
OpenAI-compatible model on your computer or to an HTTPS gateway you can reach,
such as the Aalto LLM Gateway. The package requires Node.js 24 or later and npm.

## Connect to the Aalto LLM Gateway

1. Connect your Mac to the Aalto VPN. Create a personal API key from the
[Aalto LLM Gateway](https://llm-gateway.k8s.aalto.fi/) and get the exact model
ID from your colleague or the gateway.
2. Run `openssl rand -hex 32` in Terminal to generate a separate companion
token. Run `umask 077` before creating a new file named `companion.env`
in a private folder. Add these settings and replace the example values.

```dotenv
KIRJOLAB_MODEL_COMPANION_ORIGIN=https://your-kirjolab-site.example
KIRJOLAB_MODEL_UPSTREAM=https://llm-gateway.k8s.aalto.fi/api/v1/chat/completions
KIRJOLAB_MODEL_UPSTREAM_MODEL=exact-model-id
KIRJOLAB_MODEL_UPSTREAM_API_KEY=your-aalto-api-key
KIRJOLAB_MODEL_COMPANION_TOKEN=the-token-you-generated
```

The Kirjolab origin is the scheme and hostname of the page you open, plus
its port if present. Leave out the path and trailing slash. Keep the file
private and share only the gateway URL, Kirjolab origin, and model ID.

3. In Terminal, start the companion from the folder containing
`companion.env`. Leave it running while you use the model. For a release
published to npm, run this command.

```sh
npx kirjolab-model-companion@0.1.0 --env-file ./companion.env
```

If your colleague supplied an npm tarball, run this from the folder with
both files.

```sh
npm exec --package=./kirjolab-model-companion-0.1.0.tgz -- kirjolab-model-companion --env-file ./companion.env
```

4. In Kirjolab, open **Model connection** and select **Local companion**. Keep
the endpoint `http://127.0.0.1:8790/v1/chat/completions`. Enter the generated
value in **Companion token (for remote gateways)** and click **Find loaded
models**. Select **Provider default** for reasoning to use the model's usual
settings. Kirjolab selects the model ID from your config.

The Aalto API key stays in the companion. Kirjolab keeps the separate companion
token in the current tab session. The companion sends the writing request
directly to Aalto over your VPN. See [Aalto's gateway guide](https://scicomp.aalto.fi/aalto/llm-web-apis/)
for API access and available models.

The model list shows the configured ID even while the VPN is disconnected.
Try a short writing request to verify the connection. If the browser asks for
permission to reach the local network, allow it for your Kirjolab site. A
401 from the companion means to check the companion token in Kirjolab.
If Kirjolab reports that the gateway rejected the API key, check the key in
`companion.env` and restart the companion. For an unavailable gateway, check
the VPN and exact endpoint. Aalto's on-demand models may take time to start.

## Connect to a model on your Mac

Use the same npm command with an env file containing the exact Kirjolab origin
and your model server's loopback completion URL.

```dotenv
KIRJOLAB_MODEL_COMPANION_ORIGIN=https://your-kirjolab-site.example
KIRJOLAB_MODEL_UPSTREAM=http://127.0.0.1:1234/v1/chat/completions
```

Leave the companion token blank in Kirjolab and click **Find loaded models**.
The companion reads the model server's `/models` route.
16 changes: 16 additions & 0 deletions packaging/model-companion/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "kirjolab-model-companion",
"version": "0.1.0",
"description": "Loopback companion for OpenAI-compatible models in Kirjolab",
"license": "MIT",
"repository": "https://github.com/bebraw/kirjolab",
"engines": {
"node": ">=24"
},
"bin": {
"kirjolab-model-companion": "./companion.mjs"
},
"files": [
"companion.mjs"
]
}
28 changes: 28 additions & 0 deletions scripts/model-companion-bin.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { loadEnvFile } from "node:process";
import { readModelCompanionConfig, startModelCompanion } from "../src/model-companion.ts";

const args = process.argv.slice(2);
const usage = "Usage: kirjolab-model-companion [--env-file <path>]";

try {
if (args.length === 1 && (args[0] === "--help" || args[0] === "-h")) {
process.stdout.write(`${usage}\n`);
} else {
if (args.length !== 0) {
if (args.length !== 2 || args[0] !== "--env-file" || !args[1]) throw new Error(usage);
loadEnvFile(args[1]);
}
const config = readModelCompanionConfig(process.env);
if (config.kind === "codex") {
throw new Error("Select the openai-compatible provider for this package. The repository companion supports Codex.");
}
startModelCompanion(config).on("error", reportStartupError);
}
} catch (error) {
reportStartupError(error);
}

function reportStartupError(error) {
process.stderr.write(`Unable to start Kirjolab model companion: ${error instanceof Error ? error.message : String(error)}\n`);
process.exitCode = 1;
}
50 changes: 50 additions & 0 deletions scripts/pack-model-companion.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { execFile } from "node:child_process";
import { copyFile, mkdtemp, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { build } from "esbuild";

const [flag, destination, ...extra] = process.argv.slice(2);
if (flag !== "--pack-destination" || !destination || extra.length) {
throw new Error("Usage: npm run model:companion:pack -- --pack-destination <existing-directory>");
}
const packDestination = resolve(destination);
if (!(await stat(packDestination)).isDirectory()) throw new Error("The pack destination must be a directory");
const npmEntrypoint = process.env.npm_execpath;
if (!npmEntrypoint) throw new Error("Run model:companion:pack through npm");

const root = fileURLToPath(new URL("../", import.meta.url));
const staging = await mkdtemp(join(tmpdir(), "kirjolab-model-companion-"));
try {
await build({
absWorkingDir: root,
entryPoints: ["scripts/model-companion-bin.mjs"],
bundle: true,
platform: "node",
format: "esm",
target: "node24",
outfile: join(staging, "companion.mjs"),
banner: { js: "#!/usr/bin/env node" },
});
await Promise.all([
copyFile(join(root, "LICENSE"), join(staging, "LICENSE")),
copyFile(join(root, "packaging/model-companion/package.json"), join(staging, "package.json")),
copyFile(join(root, "packaging/model-companion/README.md"), join(staging, "README.md")),
]);
const { stdout } = await promisify(execFile)(process.execPath, [
npmEntrypoint,
"pack",
"--ignore-scripts",
"--json",
"--cache",
join(staging, ".npm-cache"),
"--pack-destination",
packDestination,
staging,
]);
process.stdout.write(stdout);
} finally {
await rm(staging, { recursive: true, force: true });
}
13 changes: 13 additions & 0 deletions scripts/run-model-companion.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { runModelCompanion } from "../src/model-companion.ts";

try {
const server = await runModelCompanion();
server.on("error", reportStartupError);
} catch (error) {
reportStartupError(error);
}

function reportStartupError(error) {
process.stderr.write(`Unable to start Kirjolab model companion: ${error instanceof Error ? error.message : String(error)}\n`);
process.exitCode = 1;
}
20 changes: 15 additions & 5 deletions specs/model-operations/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,19 +142,29 @@ advisory hints; it has no candidate creation or apply action.
instead of hardcoding a catalog. Discovery is explicit, bounded,
loopback-only, and available through the same optional companion when
provider CORS blocks direct browser access. Direct and forwarded local-model
discovery is credential-free; Codex companion discovery requires its bearer
token and exposes only the configured model. A saved local choice remains
discovery is credential-free. Codex and authenticated HTTPS gateway
companions require a browser-to-companion bearer token and expose the
configured model without upstream model discovery. A saved local choice remains
visible before refresh; successful discovery replaces stale choices with
identifiers reported by the configured endpoint.
- One bounded model-provider settings component owns connection, endpoint,
model, reasoning, and tab-scoped Codex companion token values, saved-value
model, reasoning, and tab-scoped companion token values, saved-value
validation, live option presentation, discovery progress, opening its
enclosing preferences menu, connection-control focus, provider construction,
and typed change and discovery intents. Only connection, endpoint, model, and
reasoning persist in local storage; the Codex token persists only in session
storage and is sent only to the loopback companion. The workspace coordinator
reasoning persist in local storage. The Codex and gateway tokens use distinct
session storage keys and go only to their corresponding loopback companion
connection. The workspace coordinator
retains generation workflows, provider failure presentation, and assistant
status policy.
- The npm companion executable accepts an explicit local env file and runs the
forwarding backend outside the checkout. The authenticated gateway profile
requires an upstream API key, a fixed HTTPS completion URL, one exact model
ID, and an independent browser token. The companion forwards validated
writing requests from the allowlisted browser origin using the local
network and upstream key. The browser uses the ordinary loopback companion
endpoint. A configured model listing establishes companion access and a
completion verifies upstream reachability and authentication.
- One bounded assistant workflow status component owns operation-specific
attribution and initial status copy, subsequent live status presentation,
selected evidence keys and their count or limit status, reconciliation
Expand Down
10 changes: 10 additions & 0 deletions src/client/assistant/model-provider-preferences.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ describe("model provider preferences", () => {
expect(session.setItem).toHaveBeenCalledWith(sessionCodexTokenStorageKey, "tab-only-token-with-at-least-24-chars");
});

it("keeps the gateway token in session storage with a separate key", () => {
const local = storage();
const session = storage();
const companionToken = "gateway-token-with-at-least-24-characters";
persistModelProviderPreferences({ ...initialModelProviderPreferences, connection: "companion", companionToken }, local, session);
expect(JSON.parse(local.getItem(modelPreferencesStorageKey) ?? "{}")).not.toHaveProperty("companionToken");
expect(readStoredModelProviderPreferences(local, session)).toMatchObject({ companionToken, codexToken: "" });
expect(readStoredModelProviderPreferences(local, storage())).not.toHaveProperty("companionToken");
});

it("falls back safely and removes malformed durable preferences", () => {
const local = storage({ [modelPreferencesStorageKey]: "{" });
expect(readStoredModelProviderPreferences(local, storage())).toEqual(initialModelProviderPreferences);
Expand Down
Loading
Loading