Public: anyone can read this; the crew can change it.

crew: a Claude account can use a self-hosted endpoint on the LAN over http, with its model #14396

opened this

Check · Review · Land · Live — It conflicts with its base. Next: builder, it conflicts with its base.

Conflicts with main

claude-local-gateway → main 2 commits

This pull asks to reach lab--forge-trevato-apps.open-platform.sh. Its preview and check reach what main reaches; the new host opens when the pull lands.

Review

Sign in to review this change.
12 files changed +166 −27
docs/MCP.md +1 −1
@@ -219,7 +219,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
219219 | `ssh_keys` | `list`, `add`, `remove` | Your SSH keys; add: key, remove: id | 250 |
220220 | `steer` | — | Say a word to one crew run by its id | 224 |
221221 | `stop` | — | Stop a crew run by its id from `now`; with no repo, the forge's own agent mid-answer | 227 |
222 | `subscription_add` | — | Admin: add a Claude login | 224 |
222 | `subscription_add` | — | Admin: add a Claude login | 250 |
223223 | `subscription_budget` | — | Admin: set an account's lifetime USD budget; null clears | 231 |
224224 | `subscription_delete` | — | Remove a subscription, with its grants | 174 |
225225 | `subscription_headroom` | — | Admin: set the % of each window the crew leaves for people | 235 |
src/actions/model_grant.ts +1
@@ -27,6 +27,7 @@ export const ADD_MESSAGES = {
2727 name_taken: "You already added your own subscription.",
2828 invalid_token: SUBSCRIPTION_WORDS.invalid_token,
2929 invalid_api_base: SUBSCRIPTION_WORDS.invalid_api_base,
30 invalid_model: SUBSCRIPTION_WORDS.invalid_model,
3031 not_allowed: "Only a person adds their own subscription.",
3132 };
3233
src/core/migration-pins/20261119120000-subscription-model.pin added +1
@@ -0,0 +1,1 @@
1 730585a0040aa36e64bbb02e0048106762fda16d7fe7e8ac4b562819c33da7ca
src/core/migrations/20261119120000-subscription-model.ts added +5
@@ -0,0 +1,5 @@
1 // A subscription may name the model its self-hosted Anthropic-compatible endpoint serves
2 // (`gpt-oss:120b` behind Ollama or vLLM on the LAN): every run on it asks for that model.
3 export default `
4 ALTER TABLE subscription ADD COLUMN model TEXT;
5 `;
src/core/subscriptions.ts +53 −14
@@ -31,6 +31,7 @@ import { err, ok, type Result } from "../kernel/result.ts";
3131 import { open, seal } from "../kernel/secret.ts";
3232 import { accountEnv, envNameOf, runnerCredentialInEnv } from "../crew/runner_env.ts";
3333 import { limitValue } from "../settings/limits.ts";
34 import { isPrivateHost } from "../actions/migrate.ts";
3435
3536 export type SubscriptionKind = "oauth" | "api_key";
3637
@@ -45,6 +46,12 @@ export interface Subscription {
4546 * `ANTHROPIC_BASE_URL` (without a trailing `/v1`; the SDK adds that).
4647 */
4748 readonly apiBase: string | null;
49 /**
50 * The model a self-hosted Anthropic-compatible endpoint serves
51 * (`gpt-oss:120b` behind Ollama or vLLM), or null: every run on the account
52 * asks for it, whatever tier the crew chose (`crew/runner_env.ts`).
53 */
54 readonly model?: string | null | undefined;
4855 /** Set while the provider's limit holds; the account is skipped until then. */
4956 readonly restingUntil: string | null;
5057 /** The provider's own words for why, one line. */
@@ -59,6 +66,7 @@ interface Row {
5966 name: string;
6067 kind: string;
6168 api_base: string | null;
69 model: string | null;
6270 resting_until: string | null;
6371 resting_said: string;
6472 last_used_at: string | null;
@@ -79,7 +87,8 @@ export type SubscriptionError =
7987 | "invalid_name"
8088 | "name_taken"
8189 | "invalid_token"
82 | "invalid_api_base";
90 | "invalid_api_base"
91 | "invalid_model";
8392
8493 /** How soon an account out of budget is looked at again. */
8594 const BUDGET_RECHECK_MS = 3_600_000;
@@ -181,6 +190,7 @@ const toSubscription = (r: Row): Subscription => ({
181190 name: r.name,
182191 kind: r.kind === "oauth" ? "oauth" : "api_key",
183192 apiBase: r.api_base && r.api_base.trim() !== "" ? r.api_base : null,
193 model: r.model && r.model.trim() !== "" ? r.model : null,
184194 restingUntil: r.resting_until,
185195 restingSaid: r.resting_said,
186196 lastUsedAt: r.last_used_at,
@@ -224,11 +234,25 @@ export function kindOfToken(token: string): SubscriptionKind | undefined {
224234 return "api_key";
225235 }
226236
237 /** Names that only resolve inside a network: `.local` (mDNS), `.internal`, `.home.arpa`, `.lan`. */
238 const LAN_NAME = /\.(local|internal|lan|home\.arpa)$/i;
239
227240 /**
228 * An Anthropic-compatible base URL for Claude Code: https, no credentials,
229 * no query or hash. Trailing slashes and a trailing `/v1` are stripped — the
230 * Anthropic SDK appends `/v1/messages` itself (OpenRouter wants
231 * `https://openrouter.ai/api`, not `…/api/v1`).
241 * Whether a base URL may be plain http: its host is loopback, a private or
242 * link-local address, or a name only a LAN resolves. A model on the same
243 * network (Ollama, vLLM on a workstation) speaks http; a public host must not
244 * see the token in clear.
245 */
246 export function isLanHost(hostname: string): boolean {
247 return isPrivateHost(hostname) || LAN_NAME.test(hostname);
248 }
249
250 /**
251 * An Anthropic-compatible base URL for Claude Code: https, or http to a host
252 * on this network (`isLanHost`); no credentials, no query or hash. Trailing
253 * slashes and a trailing `/v1` are stripped — the Anthropic SDK appends
254 * `/v1/messages` itself (OpenRouter wants `https://openrouter.ai/api`, not
255 * `…/api/v1`).
232256 */
233257 export function parseApiBase(raw: string): string | undefined {
234258 const trimmed = raw.trim();
@@ -240,15 +264,21 @@ export function parseApiBase(raw: string): string | undefined {
240264 } catch {
241265 return undefined;
242266 }
243 if (url.protocol !== "https:") return undefined;
267 if (url.protocol !== "https:" && !(url.protocol === "http:" && isLanHost(url.hostname))) return undefined;
244268 if (url.username !== "" || url.password !== "") return undefined;
245269 if (url.search !== "" || url.hash !== "") return undefined;
246270 if (url.hostname === "") return undefined;
247271 let path = url.pathname.replace(/\/+$/, "");
248272 if (path.endsWith("/v1")) path = path.slice(0, -3).replace(/\/+$/, "");
249273 return path === "" || path === "/"
250 ? `https://${url.host}`
251 : `https://${url.host}${path}`;
274 ? `${url.protocol}//${url.host}`
275 : `${url.protocol}//${url.host}${path}`;
276 }
277
278 /** A model name as an endpoint takes it (`gpt-oss:120b`, `org/model-7b`), or undefined. */
279 export function parseModelName(raw: string): string | undefined {
280 const name = raw.trim();
281 return /^[\w][\w.:/@+-]{0,199}$/.test(name) ? name : undefined;
252282 }
253283
254284 /**
@@ -277,6 +307,8 @@ export function addSubscription(
277307 token: string;
278308 /** Anthropic-compatible gateway URL; empty/omitted = Anthropic. */
279309 apiBase?: string | undefined;
310 /** The model a self-hosted endpoint serves; only with an `apiBase`. */
311 model?: string | undefined;
280312 createdBy?: string | undefined;
281313 },
282314 ): Result<Subscription, SubscriptionError> {
@@ -289,6 +321,9 @@ export function addSubscription(
289321 if (parsed === undefined) return err("invalid_api_base");
290322 apiBase = parsed;
291323 }
324 const rawModel = (input.model ?? "").trim();
325 const model = rawModel === "" ? null : (parseModelName(rawModel) ?? false);
326 if (model === false || (model !== null && apiBase === null)) return err("invalid_model");
292327 const token = normalizeToken(input.token);
293328 const kind = kindOfToken(token);
294329 if (kind === undefined) return err("invalid_token");
@@ -297,8 +332,8 @@ export function addSubscription(
297332 if (getSubscriptionByName(db, name) !== undefined) return err("name_taken");
298333 const subscriptionId = id();
299334 db.query(
300 `INSERT INTO subscription (id, name, kind, token_enc, api_base, created_by)
301 VALUES (?1, ?2, ?3, ?4, ?5, ?6)`,
335 `INSERT INTO subscription (id, name, kind, token_enc, api_base, created_by, model)
336 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`,
302337 ).run(
303338 subscriptionId,
304339 name,
@@ -306,6 +341,7 @@ export function addSubscription(
306341 seal(dataDir, token, aad(subscriptionId)),
307342 apiBase,
308343 input.createdBy ?? null,
344 model,
309345 );
310346 return ok(getSubscription(db, subscriptionId)!);
311347 }
@@ -316,7 +352,7 @@ export function getSubscription(
316352 ): Subscription | undefined {
317353 const row = db
318354 .query<Row, [string]>(
319 `SELECT id, name, kind, api_base, resting_until, resting_said, last_used_at, created_by, created_at
355 `SELECT id, name, kind, api_base, model, resting_until, resting_said, last_used_at, created_by, created_at
320356 FROM subscription WHERE id = ?1`,
321357 )
322358 .get(subscriptionId);
@@ -329,7 +365,7 @@ export function getSubscriptionByName(
329365 ): Subscription | undefined {
330366 const row = db
331367 .query<Row, [string]>(
332 `SELECT id, name, kind, api_base, resting_until, resting_said, last_used_at, created_by, created_at
368 `SELECT id, name, kind, api_base, model, resting_until, resting_said, last_used_at, created_by, created_at
333369 FROM subscription WHERE name = ?1 COLLATE NOCASE`,
334370 )
335371 .get(name.trim());
@@ -339,7 +375,7 @@ export function getSubscriptionByName(
339375 export function listSubscriptions(db: Database): Subscription[] {
340376 return db
341377 .query<Row, []>(
342 `SELECT id, name, kind, api_base, resting_until, resting_said, last_used_at, created_by, created_at
378 `SELECT id, name, kind, api_base, model, resting_until, resting_said, last_used_at, created_by, created_at
343379 FROM subscription WHERE id <> 'platform' ORDER BY name COLLATE NOCASE`,
344380 )
345381 .all()
@@ -551,6 +587,8 @@ export type Pick =
551587 readonly token: string;
552588 /** Anthropic-compatible gateway URL, or null for Anthropic itself. */
553589 readonly apiBase: string | null;
590 /** The model a self-hosted endpoint serves, or null. */
591 readonly model?: string | null | undefined;
554592 /** On a budgeted account: the most this run may spend, reserved for it. */
555593 readonly capUsd?: number;
556594 }
@@ -593,7 +631,7 @@ export function pickSubscription(
593631 },
594632 [string, string, string, string]
595633 >(
596 `SELECT g.scope_id, g.agent_id, s.id, s.name, s.kind, s.token_enc, s.api_base, s.resting_until,
634 `SELECT g.scope_id, g.agent_id, s.id, s.name, s.kind, s.token_enc, s.api_base, s.model, s.resting_until,
597635 s.resting_said, s.last_used_at, s.created_by, s.created_at, s.budget_usd,
598636 ${COMMITTED} AS spent_usd
599637 FROM subscription_grant g JOIN subscription s ON s.id = g.subscription_id
@@ -676,6 +714,7 @@ export function pickSubscription(
676714 envName: envNameOf(subscription.kind),
677715 token: opened.value,
678716 apiBase: subscription.apiBase,
717 model: subscription.model,
679718 ...(capUsd === undefined ? {} : { capUsd }),
680719 };
681720 }
src/core/subscriptions_words.ts +3 −1
@@ -16,7 +16,9 @@ export const SUBSCRIPTION_WORDS = {
1616 invalid_token:
1717 "That token is empty or over 4096 characters once spaces, line breaks and a `Bearer ` prefix are dropped. One from `claude setup-token` begins sk-ant-oat; anything else is taken as an API key (sk-ant-api…, sk-ant-usr…, sk-or-v1-…, or a gateway's own with its base URL).",
1818 invalid_api_base:
19 "The API base URL must be https, with no credentials, query, or hash. For OpenRouter use https://openrouter.ai/api (a Claude subscription token cannot use a gateway).",
19 "The API base URL must be https (http only to a loopback, private-network or .local/.lan/.internal host), with no credentials, query, or hash. For OpenRouter use https://openrouter.ai/api (a Claude subscription token cannot use a gateway).",
20 invalid_model:
21 "A model name is letters, digits and . : / @ + - _ (like gpt-oss:120b), and goes with an API base URL: it names what that endpoint serves.",
2022 headroom_range: `Headroom is a whole percent from 0 to ${HEADROOM_MAX}.`,
2123 not_found: "No such subscription.",
2224 removed:
src/crew/runner.ts +2 −1
@@ -1595,7 +1595,8 @@ async function work(
15951595 cwd: dir,
15961596 prompt,
15971597 appendSystemPrompt: systemPrompt(brief),
1598 model: chosen.model || undefined,
1598 // An account on a self-hosted endpoint serves one model, whatever tier was chosen.
1599 model: (picked.kind === "ready" ? picked.model : undefined) || chosen.model || undefined,
15991600 budgetUsd,
16001601 resume,
16011602 env,
src/crew/runner_env.ts +45 −7
@@ -24,18 +24,40 @@ export function hostOfApiBase(apiBase: string | null | undefined): string | unde
2424 }
2525 }
2626
27 /** The tier names Claude Code maps to a model, each read from its own variable. */
28 const TIER_MODEL_NAMES = ["ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL"] as const;
29
30 /**
31 * What points Claude Code at a self-hosted Anthropic-compatible endpoint
32 * serving `model` (Ollama, vLLM): the token as a bearer (`ANTHROPIC_AUTH_TOKEN`,
33 * the API key empty so it is not sent as one), every tier mapped to the one
34 * model, and Anthropic's experimental beta headers off, which such an
35 * endpoint refuses.
36 */
37 function selfHostedEnv(base: string, token: string, model: string): Record<string, string> {
38 return {
39 ANTHROPIC_BASE_URL: base,
40 ANTHROPIC_AUTH_TOKEN: token,
41 ANTHROPIC_API_KEY: "",
42 ...Object.fromEntries(TIER_MODEL_NAMES.map((n) => [n, model])),
43 CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: "1",
44 };
45 }
46
2747 /**
2848 * Variables for a picked account: the token under the variable Claude Code
2949 * reads, plus the base URL (and OpenRouter's auth-token dance) when the
30 * account has a gateway.
50 * account has a gateway, and the self-hosted set when it names a model.
3151 */
3252 export function accountEnv(a: {
3353 readonly envName: string;
3454 readonly token: string;
3555 readonly apiBase?: string | null | undefined;
56 readonly model?: string | null | undefined;
3657 }): Record<string, string> {
3758 const base = a.apiBase;
3859 if (base === null || base === undefined || base === "") return { [a.envName]: a.token };
60 if (a.model !== null && a.model !== undefined && a.model !== "") return selfHostedEnv(base, a.token, a.model);
3961 const host = hostOfApiBase(base) ?? "";
4062 if (host === "openrouter.ai" || host.endsWith(".openrouter.ai")) {
4163 // AUTH_TOKEN carries the key; API_KEY must be empty so Claude Code does
@@ -51,7 +73,14 @@ export function accountEnv(a: {
5173 */
5274 export function ownEnv(env: Env = process.env): Record<string, string> {
5375 const own: Record<string, string> = {};
54 for (const name of ["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"]) {
76 for (const name of [
77 "ANTHROPIC_API_KEY",
78 "CLAUDE_CODE_OAUTH_TOKEN",
79 "ANTHROPIC_BASE_URL",
80 "ANTHROPIC_AUTH_TOKEN",
81 ...TIER_MODEL_NAMES,
82 "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS",
83 ]) {
5584 const value = env[name];
5685 if (value !== undefined) own[name] = value;
5786 }
@@ -84,7 +113,7 @@ export function namedRunner(env: Env): string | undefined {
84113
85114 /** Whether the environment holds a model token or a signed-in runner config dir. */
86115 export function runnerCredentialInEnv(env: Env): boolean {
87 if (["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"].some((n) => (env[n] ?? "").trim() !== "")) return true;
116 if (["ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_AUTH_TOKEN"].some((n) => (env[n] ?? "").trim() !== "")) return true;
88117 return (runnerSettings(env).configDir ?? "").trim() !== "";
89118 }
90119
@@ -93,13 +122,22 @@ export function lentEnv(door: string, token: string): Record<string, string> {
93122 return { ANTHROPIC_BASE_URL: door, ANTHROPIC_API_KEY: token };
94123 }
95124
96 /** A variable that holds an address, not a secret: left readable in a run's log. */
97 export const isGatewayAddress = (name: string): boolean => name === "ANTHROPIC_BASE_URL";
125 /**
126 * A variable that holds an address or a setting, not a secret: left readable
127 * in a run's log (a model name held as a secret would blank every mention of it).
128 */
129 export const isGatewayAddress = (name: string): boolean =>
130 name === "ANTHROPIC_BASE_URL" || name === "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS" || (TIER_MODEL_NAMES as readonly string[]).includes(name);
98131
99 /** The two variables that quiet Claude Code's background traffic. */
100 export const quietEnv = (): Record<string, string> => ({
132 /**
133 * The two variables that quiet Claude Code's background traffic, and the
134 * operator's extra CA bundle (`NODE_EXTRA_CA_CERTS`), so an endpoint behind a
135 * private CA is trusted as the forge trusts it.
136 */
137 export const quietEnv = (env: Env = process.env): Record<string, string> => ({
101138 CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1",
102139 DISABLE_TELEMETRY: "1",
140 ...((env["NODE_EXTRA_CA_CERTS"] ?? "") === "" ? {} : { NODE_EXTRA_CA_CERTS: env["NODE_EXTRA_CA_CERTS"]! }),
103141 });
104142
105143 /** Where Claude Code's sandbox keeps its temp files. */
src/http/mcp/tools/subscription_add.ts +3 −2
@@ -4,11 +4,11 @@ import { good, bad, type Tool } from "../shared.ts";
44
55 export const tool: Tool = {
66 name: "subscription_add",
7 doc: "`{ name, token, apiBase? }` (forge admin): put a Claude account in the crew's pool, as the Subscriptions page does, with its refusals; answers `{ id, name, says }`; the token is never read back",
7 doc: "`{ name, token, apiBase?, model? }` (forge admin): put a Claude account in the crew's pool, as the Subscriptions page does, with its refusals; `apiBase` is https, or http to a LAN or loopback host, and `model` names what a self-hosted endpoint there serves (`gpt-oss:120b`); answers `{ id, name, says }`; the token is never read back",
88 description: "Admin: add a Claude login.",
99 inputSchema: {
1010 type: "object",
11 properties: { name: { type: "string" }, token: { type: "string" }, apiBase: { type: "string" } },
11 properties: { name: { type: "string" }, token: { type: "string" }, apiBase: { type: "string" }, model: { type: "string" } },
1212 required: ["name", "token"],
1313 },
1414 writes: true,
@@ -21,6 +21,7 @@ export const tool: Tool = {
2121 name,
2222 token: str(args["token"]).trim(),
2323 apiBase: str(args["apiBase"]).trim(),
24 model: str(args["model"]).trim(),
2425 createdBy: user.id,
2526 });
2627 if (!added.ok) return bad(added.error, addRefusal(added.error, name));
test/api-base-v1.test.ts +11
@@ -43,6 +43,17 @@ test("a base given with /v1 and trailing slashes is kept without them", () => {
4343 expect(parseApiBase("http://x")).toBeUndefined();
4444 });
4545
46 test("http is a base only on this network: loopback, private ranges and LAN names; a public host keeps https", () => {
47 expect(parseApiBase("http://192.168.1.40:11434")).toBe("http://192.168.1.40:11434");
48 expect(parseApiBase("http://10.0.0.7:8000/v1")).toBe("http://10.0.0.7:8000");
49 expect(parseApiBase("http://127.0.0.1:11434/")).toBe("http://127.0.0.1:11434");
50 expect(parseApiBase("http://localhost:11434")).toBe("http://localhost:11434");
51 expect(parseApiBase("http://[::1]:8000")).toBe("http://[::1]:8000");
52 expect(parseApiBase("http://spark.local:11434")).toBe("http://spark.local:11434");
53 expect(parseApiBase("http://openrouter.ai/api")).toBeUndefined();
54 expect(parseApiBase("http://8.8.8.8:11434")).toBeUndefined();
55 });
56
4657 test("the terminal screen shows the hint on one 80-column line", async () => {
4758 const terminal = headlessTerminal(80, 40);
4859 const { app: tui, session } = createForgeApp(
test/runner-env-confined.test.ts +18 −1
@@ -1,6 +1,6 @@
11 import { expect, test } from "bun:test";
22 import { Glob } from "bun";
3 import { accountEnv, runnerCredentialInEnv, lentEnv, oneShotEnv, ownEnv, upstreamOf } from "../src/crew/runner_env.ts";
3 import { accountEnv, isGatewayAddress, quietEnv, runnerCredentialInEnv, lentEnv, oneShotEnv, ownEnv, upstreamOf } from "../src/crew/runner_env.ts";
44
55 test("only runner_env.ts names a vendor variable in src", async () => {
66 const re = /\b(ANTHROPIC_[A-Z_]+|CLAUDE_CODE_[A-Z_]+)\b/;
@@ -23,6 +23,23 @@ test("runner_env builds each environment", () => {
2323 ANTHROPIC_AUTH_TOKEN: "t",
2424 ANTHROPIC_API_KEY: "",
2525 });
26 // A self-hosted endpoint (Ollama, vLLM) serving one model: a bearer token, every tier that model, betas off.
27 expect(accountEnv({ envName: "ANTHROPIC_API_KEY", token: "t", apiBase: "http://192.168.1.40:11434", model: "gpt-oss:120b" })).toEqual({
28 ANTHROPIC_BASE_URL: "http://192.168.1.40:11434",
29 ANTHROPIC_AUTH_TOKEN: "t",
30 ANTHROPIC_API_KEY: "",
31 ANTHROPIC_DEFAULT_OPUS_MODEL: "gpt-oss:120b",
32 ANTHROPIC_DEFAULT_SONNET_MODEL: "gpt-oss:120b",
33 ANTHROPIC_DEFAULT_HAIKU_MODEL: "gpt-oss:120b",
34 CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: "1",
35 });
36 expect(ownEnv({ ANTHROPIC_BASE_URL: "http://127.0.0.1:11434", ANTHROPIC_AUTH_TOKEN: "ollama", ANTHROPIC_DEFAULT_SONNET_MODEL: "gpt-oss:120b", CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: "1", PATH: "/bin" })).toEqual({
37 ANTHROPIC_BASE_URL: "http://127.0.0.1:11434", ANTHROPIC_AUTH_TOKEN: "ollama", ANTHROPIC_DEFAULT_SONNET_MODEL: "gpt-oss:120b", CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: "1",
38 });
39 expect(runnerCredentialInEnv({ ANTHROPIC_AUTH_TOKEN: "ollama" })).toBe(true);
40 expect(quietEnv({ NODE_EXTRA_CA_CERTS: "/etc/ca.pem" })["NODE_EXTRA_CA_CERTS"]).toBe("/etc/ca.pem");
41 expect(isGatewayAddress("ANTHROPIC_DEFAULT_OPUS_MODEL")).toBe(true);
42 expect(isGatewayAddress("ANTHROPIC_AUTH_TOKEN")).toBe(false);
2643 expect(lentEnv("http://x", "k")).toEqual({ ANTHROPIC_BASE_URL: "http://x", ANTHROPIC_API_KEY: "k" });
2744 expect(ownEnv({ ANTHROPIC_API_KEY: "a", PATH: "/bin" })).toEqual({ ANTHROPIC_API_KEY: "a" });
2845 expect(oneShotEnv({ CLAUDE_CODE_OAUTH_TOKEN: "o", ANTHROPIC_BASE_URL: "u" })).toEqual({ CLAUDE_CODE_OAUTH_TOKEN: "o" });
test/subscriptions.test.ts +23
@@ -117,6 +117,29 @@ describe("the pool", () => {
117117 expect(raw.token_enc).not.toContain(OAT);
118118 });
119119
120 test("an account on a self-hosted endpoint on the LAN takes http and a model, and every run on it asks for that model", () => {
121 const added = addSubscription(app.db, dataDir, {
122 name: "spark",
123 token: "ollama",
124 apiBase: "http://192.168.1.40:11434",
125 model: "gpt-oss:120b",
126 });
127 if (!added.ok) throw new Error(added.error);
128 expect(added.value).toMatchObject({ apiBase: "http://192.168.1.40:11434", model: "gpt-oss:120b" });
129 setGrants(app.db, "repo-spark", EVERYONE, [added.value.id]);
130 const pick = pickSubscription(app.db, dataDir, { repoId: "repo-spark", ownerId: "org-spark", agentId: "bot-spark" }, new Date("2026-10-07T12:00:00Z"));
131 if (pick.kind !== "ready") throw new Error(pick.kind);
132 expect(pick.model).toBe("gpt-oss:120b");
133 expect(credentialEnvOf(pick)).toMatchObject({
134 ANTHROPIC_BASE_URL: "http://192.168.1.40:11434",
135 ANTHROPIC_AUTH_TOKEN: "ollama",
136 ANTHROPIC_DEFAULT_SONNET_MODEL: "gpt-oss:120b",
137 });
138 expect(addSubscription(app.db, dataDir, { name: "public-http", token: "k", apiBase: "http://openrouter.ai/api" })).toEqual({ ok: false, error: "invalid_api_base" });
139 expect(addSubscription(app.db, dataDir, { name: "model-alone", token: "k", model: "gpt-oss:120b" })).toEqual({ ok: false, error: "invalid_model" });
140 expect(addSubscription(app.db, dataDir, { name: "bad-model", token: "k", apiBase: "http://127.0.0.1:8000", model: "a model; rm" })).toEqual({ ok: false, error: "invalid_model" });
141 });
142
120143 test("seals an OpenRouter key with its gateway and injects Claude Code env", () => {
121144 const added = addSubscription(app.db, dataDir, {
122145 name: "openrouter",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs