From 89af3bdc7e642d64e40679c3e68e7a9ce2c13fc8 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:34:09 -0600 Subject: [PATCH 1/5] Give The Claude Turn An Advisor Model That Never Touches Global Settings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Claude Code CLI can consult a second model as an advisor, but the way to turn that on from a chat is denied twice in the driver, because a bare /advisor opus that reached the CLI rewrote advisorModel in the owner's global ~/.claude/settings.json. The flag form has no such problem:  --advisor is per launch, so it applies to one turn and writes nothing. - ModelSelection.advisorModel and SendTurnInput.advisorModel carry the advisor, and isAdvisorModel is the one rule for what a model id is. - The shared Claude driver launches the turn with --advisor . - The driver probes claude --help for --advisor, cached the way the --strict-mcp-config probe is, and refuses the turn with a clear reason when the CLI does not announce the flag, instead of letting the turn die on an unknown option. - The bot's model selection accepts and persists advisorModel, so an advisor is set per bot or per thread and rides every turn. The turn-side tests are in server/drivers/claude.test.ts and the API test is in server/index.test.ts. The rollout note is docs/rollouts/2026-11-26-claude-advisor-per-turn.md and the recipe is docs/verification/claude-advisor.md. Fixes BF-2704 --- .../2026-11-26-claude-advisor-per-turn.md | 34 ++++++++++ docs/verification/README.md | 1 + docs/verification/claude-advisor.md | 31 ++++++++++ server/contracts.ts | 20 ++++++ server/drivers/claude.test.ts | 46 ++++++++++++++ server/drivers/claude.ts | 62 ++++++++++++++++++- server/index.test.ts | 18 ++++++ server/index.ts | 33 +++++++++- server/testing/fake-claude-cli.ts | 12 +++- 9 files changed, 253 insertions(+), 4 deletions(-) create mode 100644 docs/rollouts/2026-11-26-claude-advisor-per-turn.md create mode 100644 docs/verification/claude-advisor.md diff --git a/docs/rollouts/2026-11-26-claude-advisor-per-turn.md b/docs/rollouts/2026-11-26-claude-advisor-per-turn.md new file mode 100644 index 000000000..bc3387fdf --- /dev/null +++ b/docs/rollouts/2026-11-26-claude-advisor-per-turn.md @@ -0,0 +1,34 @@ +# The Claude Advisor Model Rides The Turn + +Refs BF-2704. + +The Claude Code CLI can consult a second model as an advisor while it answers.  The way to turn that on from a chat, the `/advisor` command, is denied twice in the driver, because a bare `/advisor opus` that reached the CLI rewrote `advisorModel` in the owner's global `~/.claude/settings.json` (server/drivers/engine-commands.ts:5-6, :48, :105). + +The flag form has no such problem:  `--advisor ` is per launch, so it applies to one turn and writes nothing. + +## What changed + +- `ModelSelection.advisorModel` and `SendTurnInput.advisorModel` (server/contracts.ts) carry the advisor, and `isAdvisorModel` is the one rule for what a model id is. +- The shared Claude driver launches the turn with `--advisor ` (server/drivers/claude.ts). +- The driver probes `claude --help` for `--advisor`, cached the way the `--strict-mcp-config` probe is, and refuses the turn with a clear reason when the CLI does not announce the flag, instead of letting the turn die on an unknown option. +- The bot's model selection accepts and persists `advisorModel` (server/index.ts), so an advisor is set per bot or per thread and rides every turn. + +## What it does not do + +- It never writes a settings file, so the owner's global Claude settings stay untouched. +- It does not choose the advisor for you:  the CLI refuses a model that does not support the advisor tool, and that refusal is the CLI's. +- The desktop and iOS pickers do not carry an advisor yet;  the API does (`PATCH /api/bots/:id` with `modelSelection.advisorModel`). + +## Evidence + +- The server's own Claude seat CLI is 2.1.330 and the Mac's is 2.1.331.  Both carry `--advisor ` and the `advisorModel` settings key. +- A live CLI run against a throwaway config accepted both `--advisor ` and `--settings '{"advisorModel":"..."}'` with no unknown-option or validation error, and wrote no settings file. +- The turn-side tests are in `server/drivers/claude.test.ts` (the turn launches with the flag, a turn without one has no flag, and a CLI that does not announce the flag is refused) and the API test is in `server/index.test.ts` (the selection keeps the advisor, and a value that is not a model id is refused). + +## Setting one + +`PATCH /api/bots/:id` takes the whole selection, the way any other selection field is set: + + {"modelSelection": {"instanceId": "claude", "model": "claude-sonnet-5-5", "advisorModel": "claude-opus-5-5"}} + +The advisor model has to be one the CLI accepts for the advisor tool, and the main model has to accept one. diff --git a/docs/verification/README.md b/docs/verification/README.md index e43a0a8fe..fc19b86a9 100644 --- a/docs/verification/README.md +++ b/docs/verification/README.md @@ -35,6 +35,7 @@ Verification uses these isolated fixtures: - [Bot On/Off switch](bot-off.md) — an Off bot starts nothing new and finishes a running turn - [Named tunnel loopback Host](named-tunnel-loopback-host.md) — proves the Access tunnel reaches the harness with loopback Host and documents the mutation gate (BF-2129) - [Optional secret store fixture](optional-secret-store-fixture.md) — the fake-credential fixture and readback for the optional secret store: primary selection, independent read and write references, and mode isolation (BF-2622) +- [Claude advisor model](claude-advisor.md) — the advisor flag on a turn, and the CLI that cannot run one - [Control disposition](control-disposition.md) — the receipt that lets Electron retire: the ruling and the landed controls measured against a commit, and the owner's Muster attestation ### Test Fixtures diff --git a/docs/verification/claude-advisor.md b/docs/verification/claude-advisor.md new file mode 100644 index 000000000..775a06503 --- /dev/null +++ b/docs/verification/claude-advisor.md @@ -0,0 +1,31 @@ +# Claude Advisor Verification + +The advisor is a launch flag on the Claude engine, so it is verified against the fake CLI that stands in for the real one, and against the real CLI's own help text. + +## The flag reaches the turn + +`server/drivers/claude.test.ts` drives the fake CLI (`server/testing/fake-claude-cli.ts`) and reads the argv the turn was launched with. + +| Case | What it proves | +| --- | --- | +| `launches the turn with the advisor model the turn asked for` | a turn with an advisor launches with `--advisor ` | +| `leaves the advisor off a turn that asked for none` | a turn without one has no `--advisor` in its argv | +| `refuses the turn when the CLI does not announce the advisor flag` | a CLI whose help does not announce `--advisor` is refused before the turn starts, not after | + +The fake answers `--help` with the flags the real CLI announces, and `FAKE_CLAUDE_ADVISOR=off` takes the flag back out, which is how the refusal case is produced. + +## The selection keeps it + +`server/index.test.ts` covers the API:  a bot's model selection keeps `advisorModel`, and a value that is not a model id is refused with a 400, because an advisor reaches the engine as one launch argument. + +## The real CLI + +The real CLI's own help is the authority on whether a CLI can run an advisor turn: + + claude --help | grep -- --advisor + +A CLI that predates the flag answers with an unknown option, so the driver refuses the turn before it starts rather than letting the launch fail. + +## What a fixture cannot prove + +A live advisor turn, where the CLI calls a second model at a key moment, needs a signed-in Claude seat.  The fleet injects seat credentials per seat, so that part is verified on a real bot rather than in a fixture. diff --git a/server/contracts.ts b/server/contracts.ts index e419267a4..d6c8d45bf 100644 --- a/server/contracts.ts +++ b/server/contracts.ts @@ -54,6 +54,18 @@ export function isEffortLevel(value: unknown): value is EffortLevel { return (EFFORT_LEVELS as readonly unknown[]).includes(value); } +/** An advisor model id: a model slug, a short alias, or an injected id. It + * reaches the engine as one launch argument, so it may not carry spaces or + * punctuation that would make it a different argument. */ +export function isAdvisorModel(value: unknown): value is string { + return ( + typeof value === "string" && + value.trim().length > 0 && + value.trim().length <= 64 && + /^[a-z0-9][a-z0-9._:/-]*$/i.test(value.trim()) + ); +} + // ── model selection ──────────────────────────────────────────────────── // "Which model" is a data value carried on the request, never a service // binding (upstream ModelSelectionWire). instanceId is the routing key. @@ -62,6 +74,10 @@ export interface ModelSelection { model: string; /** Optional: no effort means no flag, and the CLI keeps its own default. */ effort?: EffortLevel; + /** Optional: a second model the engine consults as an advisor while it + * answers. A driver passes it per turn and never writes it into a + * provider's global settings. */ + advisorModel?: string; /** Optional working-context cap in tokens (for example 524288 for 512K). * Absent means the model's full window. Only honored for a model whose * catalog row lists it in `contextCaps`. */ @@ -328,6 +344,10 @@ export interface SendTurnInput { text: string; model?: string; effort?: EffortLevel; + /** Optional: a second model the driver consults as an advisor for THIS + * turn. The driver passes it per launch, so a turn can never change a + * provider's global settings. */ + advisorModel?: string; /** The bot's chosen context cap in tokens, when its model offers one. A * driver that budgets the prompt sizes it from this (see `contextCapTokens` * in the driver config, which this overrides for the turn). */ diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts index 3ce756c33..42034790f 100644 --- a/server/drivers/claude.test.ts +++ b/server/drivers/claude.test.ts @@ -238,6 +238,7 @@ describe("ClaudeDriver turns (fake CLI)", () => { delete process.env.FAKE_CLAUDE_RETRY_SCALE; delete process.env.FAKE_CLAUDE_HELP; delete process.env.FAKE_CLAUDE_HELP_PROBES; + delete process.env.FAKE_CLAUDE_ADVISOR; delete process.env.FAKE_CLAUDE_PROMPTS; delete process.env.FAKE_CLAUDE_LIFECYCLE; delete process.env.FAKE_CLAUDE_RESULT_MARK; @@ -692,6 +693,50 @@ describe("ClaudeDriver turns (fake CLI)", () => { } }); + it("launches the turn with the advisor model the turn asked for", async () => { + await create(); + const dump = join(scratch, "advisor.json"); + process.env.FAKE_CLAUDE_DUMP = dump; + + await instance.adapter.sendTurn({ + threadId: "t-advisor", + text: "hi", + advisorModel: "claude-opus-5-5", + }); + await recorder.until((event) => event.type === "turn.completed"); + + const seen = JSON.parse(readFileSync(dump, "utf8")); + expect(seen.argv[seen.argv.indexOf("--advisor") + 1]).toBe("claude-opus-5-5"); + }); + + it("leaves the advisor off a turn that asked for none", async () => { + await create(); + const dump = join(scratch, "no-advisor.json"); + process.env.FAKE_CLAUDE_DUMP = dump; + + await instance.adapter.sendTurn({ threadId: "t-no-advisor", text: "hi" }); + await recorder.until((event) => event.type === "turn.completed"); + + const seen = JSON.parse(readFileSync(dump, "utf8")); + expect(seen.argv).not.toContain("--advisor"); + }); + + it("refuses the turn when the CLI does not announce the advisor flag", async () => { + process.env.FAKE_CLAUDE_ADVISOR = "off"; + await create(); + + await expect( + instance.adapter.sendTurn({ + threadId: "t-advisor-unsupported", + text: "hi", + advisorModel: "claude-opus-5-5", + }), + ).resolves.toMatchObject({ dispatched: false }); + expect(recorder.events).toContainEqual( + expect.objectContaining({ type: "runtime.error", message: expect.stringContaining("advisor") }), + ); + }); + it("only ever passes --permission-prompt-tool alongside the botfleet server it names — never one without the other", async () => { // acceptEdits/auto: the broker is live, so the flag and the server must // both be present, and the flag must name exactly that server's tool. @@ -2462,6 +2507,7 @@ describe("ClaudeDriver snapshot auth (fake CLI)", () => { delete process.env.FAKE_CLAUDE_AUTH_TIMEOUT_MS; delete process.env.FAKE_CLAUDE_HELP; delete process.env.FAKE_CLAUDE_HELP_PROBES; + delete process.env.FAKE_CLAUDE_ADVISOR; delete process.env.FAKE_CLAUDE_VERSION; delete process.env.ANTHROPIC_API_KEY; await instance?.dispose(); diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts index 06c9488fd..7b35dab97 100644 --- a/server/drivers/claude.ts +++ b/server/drivers/claude.ts @@ -50,7 +50,7 @@ import { STATIC_CLAUDE_MODELS } from "../claude-models.ts"; export { STATIC_CLAUDE_MODELS }; import { computerProxyEnv } from "../container-computer.ts"; import { hostToolPrefix, turnComputerMounts } from "../computer-grants.ts"; -import { newEventId, newId } from "../contracts.ts"; +import { isAdvisorModel, newEventId, newId } from "../contracts.ts"; import { awaitSeatCredentials, launchedChildCredentials, primeSeatCredentials, seatCredentialsReady } from "../child-credentials.ts"; import { CLI_LOGIN_ENV_NAMES, FLEET_BEARER_ENV_NAME } from "../secret-map.ts"; import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts"; @@ -1189,6 +1189,10 @@ export const ClaudeDriver: ProviderDriver = { } try { await requireStrictMcp(); + // The advisor is a launch flag, so the CLI has to know it before the + // turn starts: a CLI that does not announce the flag is refused here + // rather than dying on an unknown option mid-turn. + if (turn.advisorModel) await requireAdvisorSupport(turn.advisorModel); } catch (error) { preflightError = error; } finally { @@ -1261,6 +1265,10 @@ export const ClaudeDriver: ProviderDriver = { const injected = applyClaudeInject({ ...turnEnvironment }, turnModel); if (injected.model) args.push("--model", injected.model); if (turn.effort) args.push("--effort", turn.effort); + // An advisor model rides this turn only. The flag is per launch, so + // nothing here writes the owner's global Claude settings — the reason + // "/advisor" is denied in the first place. + if (turn.advisorModel) args.push("--advisor", turn.advisorModel.trim()); // Only the stable half rides the spawn contract, and so argsKey: the // volatile half (memory, mentions) is delivered inside the user turn // below, so a memory write or a mention no longer relaunches a healthy @@ -2328,6 +2336,58 @@ export const ClaudeDriver: ProviderDriver = { throw reason; }; + // The advisor tool is a launch flag (`--advisor `), so a CLI that + // does not announce it cannot run a turn that asks for one. It is probed + // the way `--strict-mcp-config` is: one answer, cached, and a probe that + // runs out of time never reads as "too old". + type AdvisorFlagAnswer = "yes" | "no" | "unknown"; + let advisorFlagProbe: { expiresAt: number; result: Promise } | undefined; + const probeAdvisorFlag = (env: NodeJS.ProcessEnv): Promise => { + if (advisorFlagProbe && advisorFlagProbe.expiresAt > Date.now()) return advisorFlagProbe.result; + const startedAt = Date.now(); + const helpTimeout = claudeHelpTimeoutMs(); + const probe = { + expiresAt: Date.now() + 30_000, + result: new Promise((resolve) => { + execCli(config.cli, ["--help"], { timeout: helpTimeout, env }, (error, stdout) => { + if (!error && /(?:^|\s)--advisor(?:\s|$)/m.test(stdout)) return resolve("yes"); + const elapsed = Date.now() - startedAt; + if (isProbeTimeout(error) || (!stdout?.trim() && elapsed >= helpTimeout)) { + logProbeFailure(instanceId, `${config.cli} --help`, error, elapsed); + return resolve("unknown"); + } + resolve("no"); + }); + }), + }; + advisorFlagProbe = probe; + void probe.result.then((answer) => { + if (answer === "yes") probe.expiresAt = Infinity; + // Not an answer: look again soon, but not on every call — each look + // is another process on an already busy engine. + else if (answer === "unknown") probe.expiresAt = Date.now() + 5_000; + }); + return probe.result; + }; + const requireAdvisorSupport = async (advisorModel: string): Promise => { + if (!isAdvisorModel(advisorModel)) { + throw new Error(`"${advisorModel}" is not a model id, so it cannot be an advisor`); + } + const env = claudeEnvironment(undefined, { ...process.env, ...input.environment }); + const support = await probeAdvisorFlag(env); + if (support === "yes") return; + // `--help` gave no answer in time: nothing says this CLI is too old, so + // the turn must not tell the user to update it. It still cannot run + // unverified, so it fails as a slow check the next turn retries. + if (support === "unknown") { + throw new Error(`${input.displayName || "Claude"} did not answer in time; try again in a moment`); + } + throw new Error( + `${input.displayName || "Claude"} on this engine does not support the advisor model. ` + + `Update Claude Code on the engine, or clear the advisor model on the bot.`, + ); + }; + // Last definitive answers, so one probe that runs out of time on a busy // Mac does not flip a working, signed-in Claude to "not installed" or // "sign-in required". diff --git a/server/index.test.ts b/server/index.test.ts index 738c7063e..33711fda4 100644 --- a/server/index.test.ts +++ b/server/index.test.ts @@ -2733,6 +2733,24 @@ describe("harness HTTP API", () => { expect(patched.body.error).toContain("not recognized"); }); + it("keeps an advisor model in the saved selection and refuses one that is not a model id", async () => { + const bot = (await api("POST", "/api/bots")).body.bot; + const patched = await api("PATCH", `/api/bots/${bot.id}`, { + modelSelection: { instanceId: "ghost", model: "ghost-1", advisorModel: "claude-opus-5-5" }, + }); + + expect(patched.status).toBe(200); + expect(patched.body.bot.modelSelection.advisorModel).toBe("claude-opus-5-5"); + + // An advisor reaches the engine as one launch argument, so a value that + // is not a model id is refused instead of being saved and passed on. + const refused = await api("PATCH", `/api/bots/${bot.id}`, { + modelSelection: { instanceId: "ghost", model: "ghost-1", advisorModel: "opus; rm -rf /" }, + }); + expect(refused.status).toBe(400); + expect(refused.body.error).toContain("advisorModel"); + }); + it("clears legacy unsupported effort from task selection without clobbering primary bot effort", async () => { const created = await api("POST", "/api/bots", { name: "EffortBot", diff --git a/server/index.ts b/server/index.ts index 72173acd6..63f2581e2 100644 --- a/server/index.ts +++ b/server/index.ts @@ -391,6 +391,7 @@ import { type InstanceConfigMap, type ModelSelection, type EffortLevel, + isAdvisorModel, type ProviderInstance, type RequestOutcome, type RuntimeEvent, @@ -2547,7 +2548,15 @@ function checkedModelSelection( if (!raw || typeof raw !== "object" || Array.isArray(raw)) { return { ok: false, status: 400, error: "modelSelection must be an object" }; } - const value = raw as { instanceId?: unknown; model?: unknown; effort?: unknown; contextCap?: unknown; maxOutputTokens?: unknown; latest?: unknown }; + const value = raw as { + instanceId?: unknown; + model?: unknown; + effort?: unknown; + contextCap?: unknown; + maxOutputTokens?: unknown; + latest?: unknown; + advisorModel?: unknown; + }; if (typeof value.instanceId !== "string" || !value.instanceId.trim()) { return { ok: false, status: 400, error: "modelSelection.instanceId is required" }; } @@ -2564,6 +2573,18 @@ function checkedModelSelection( } selection.effort = value.effort; } + // An advisor is a model id, never free text: the driver hands it to the + // engine as one launch argument. + if (value.advisorModel !== undefined && value.advisorModel !== null) { + if (!isAdvisorModel(value.advisorModel)) { + return { + ok: false, + status: 400, + error: 'modelSelection.advisorModel must be a model id such as "claude-opus-5-5"', + }; + } + selection.advisorModel = value.advisorModel.trim(); + } if (value.contextCap !== undefined && value.contextCap !== null) { const contextCap = TOKEN_LIMIT_SCHEMA.safeParse(value.contextCap); if (!contextCap.success) { @@ -7706,7 +7727,12 @@ async function startTurn( // busy flips immediately so the composer locks; the dispatch itself runs // in the background — box provisioning can take ~90s and must never // hang the HTTP request - const activeSelection: ModelSelection = { instanceId, model, effort }; + const activeSelection: ModelSelection = { + instanceId, + model, + effort, + ...(selection.advisorModel ? { advisorModel: selection.advisorModel } : {}), + }; // A turn dispatched here is the thread running again, which retires any // boot-resume failure remembered against it: the refusal exists to stop a // doomed turn being retried by every boot, never to stop a person asking. @@ -8355,6 +8381,9 @@ async function startTurn( text: remindedWakeText(wakeUserText), model, effort, + // An advisor model rides this turn: the driver passes it per launch, + // so the owner's global engine settings are never written. + ...(selection.advisorModel ? { advisorModel: selection.advisorModel } : {}), // Only a cap this model's row offers reaches a driver; a stale value // from a model the bot has since left is dropped here. ...(!boxCloud && selection.contextCap !== undefined && diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts index cef3ea49e..85ad35adf 100755 --- a/server/testing/fake-claude-cli.ts +++ b/server/testing/fake-claude-cli.ts @@ -136,7 +136,17 @@ if (argv[0] === "--help") { await new Promise((resolve) => setTimeout(resolve, 60_000)); process.exit(0); } - process.stdout.write(process.env.FAKE_CLAUDE_HELP === "unsupported" ? "Usage: claude\n" : " --strict-mcp-config Only load explicit MCP servers\n"); + // The real CLI announces the advisor flag in its help text; a CLI old + // enough to lack it is faked with FAKE_CLAUDE_ADVISOR=off. + const advisorHelp = + process.env.FAKE_CLAUDE_ADVISOR === "off" + ? "" + : " --advisor Turn on the advisor tool with this model\n"; + process.stdout.write( + process.env.FAKE_CLAUDE_HELP === "unsupported" + ? "Usage: claude\n" + : " --strict-mcp-config Only load explicit MCP servers\n" + advisorHelp, + ); process.exit(0); } From b84a96791313ea6b1500bad9bc2725235a369121 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:46:46 -0600 Subject: [PATCH 2/5] Hold The Lint Baseline: One Advisor Rule And No New Warnings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The lint baseline check counts per rule, so two of the repo's anti-slop rules caught the first pass: an unknown parameter on the advisor check, and a conditional empty object spread where the advisor rides the turn. The advisor rule now lives in its own module (server/advisor-model.ts) with a typed parameter, and the two places that carry the advisor build the object in its own statement.  The baseline check passes, and the branch adds no warning of any kind. Refs BF-2704 --- server/advisor-model.ts | 13 +++++++++++++ server/contracts.ts | 12 ------------ server/drivers/claude.ts | 5 +++-- server/index.ts | 14 ++++++++++---- 4 files changed, 26 insertions(+), 18 deletions(-) create mode 100644 server/advisor-model.ts diff --git a/server/advisor-model.ts b/server/advisor-model.ts new file mode 100644 index 000000000..b823d10eb --- /dev/null +++ b/server/advisor-model.ts @@ -0,0 +1,13 @@ +/** The advisor model id: a model slug, a short alias, or an injected id. + * + * An advisor reaches the engine as one launch argument, so a value with + * spaces or punctuation would be a different argument than the one meant. + * The rule is one place, so the API that saves one and the driver that + * passes one agree on what an id is. */ +const ADVISOR_MODEL_ID = /^[a-z0-9][a-z0-9._:/-]*$/i; + +/** True when the value is an advisor model id this fleet may pass. */ +export function isAdvisorModelId(value: string): boolean { + const trimmed = value.trim(); + return trimmed.length > 0 && trimmed.length <= 64 && ADVISOR_MODEL_ID.test(trimmed); +} diff --git a/server/contracts.ts b/server/contracts.ts index d6c8d45bf..b7aa5a143 100644 --- a/server/contracts.ts +++ b/server/contracts.ts @@ -54,18 +54,6 @@ export function isEffortLevel(value: unknown): value is EffortLevel { return (EFFORT_LEVELS as readonly unknown[]).includes(value); } -/** An advisor model id: a model slug, a short alias, or an injected id. It - * reaches the engine as one launch argument, so it may not carry spaces or - * punctuation that would make it a different argument. */ -export function isAdvisorModel(value: unknown): value is string { - return ( - typeof value === "string" && - value.trim().length > 0 && - value.trim().length <= 64 && - /^[a-z0-9][a-z0-9._:/-]*$/i.test(value.trim()) - ); -} - // ── model selection ──────────────────────────────────────────────────── // "Which model" is a data value carried on the request, never a service // binding (upstream ModelSelectionWire). instanceId is the routing key. diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts index 7b35dab97..4f4aff6dd 100644 --- a/server/drivers/claude.ts +++ b/server/drivers/claude.ts @@ -50,7 +50,8 @@ import { STATIC_CLAUDE_MODELS } from "../claude-models.ts"; export { STATIC_CLAUDE_MODELS }; import { computerProxyEnv } from "../container-computer.ts"; import { hostToolPrefix, turnComputerMounts } from "../computer-grants.ts"; -import { isAdvisorModel, newEventId, newId } from "../contracts.ts"; +import { newEventId, newId } from "../contracts.ts"; +import { isAdvisorModelId } from "../advisor-model.ts"; import { awaitSeatCredentials, launchedChildCredentials, primeSeatCredentials, seatCredentialsReady } from "../child-credentials.ts"; import { CLI_LOGIN_ENV_NAMES, FLEET_BEARER_ENV_NAME } from "../secret-map.ts"; import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts"; @@ -2370,7 +2371,7 @@ export const ClaudeDriver: ProviderDriver = { return probe.result; }; const requireAdvisorSupport = async (advisorModel: string): Promise => { - if (!isAdvisorModel(advisorModel)) { + if (!isAdvisorModelId(advisorModel)) { throw new Error(`"${advisorModel}" is not a model id, so it cannot be an advisor`); } const env = claudeEnvironment(undefined, { ...process.env, ...input.environment }); diff --git a/server/index.ts b/server/index.ts index 63f2581e2..f2da29317 100644 --- a/server/index.ts +++ b/server/index.ts @@ -391,11 +391,11 @@ import { type InstanceConfigMap, type ModelSelection, type EffortLevel, - isAdvisorModel, type ProviderInstance, type RequestOutcome, type RuntimeEvent, } from "./contracts.ts"; +import { isAdvisorModelId } from "./advisor-model.ts"; import { buildTurnTools } from "./turn-tools.ts"; import { createTurnToolHost } from "./tools/host.ts"; import { adoptGroupLedger } from "./tools/process-group.ts"; @@ -2576,7 +2576,7 @@ function checkedModelSelection( // An advisor is a model id, never free text: the driver hands it to the // engine as one launch argument. if (value.advisorModel !== undefined && value.advisorModel !== null) { - if (!isAdvisorModel(value.advisorModel)) { + if (typeof value.advisorModel !== "string" || !isAdvisorModelId(value.advisorModel)) { return { ok: false, status: 400, @@ -7727,11 +7727,14 @@ async function startTurn( // busy flips immediately so the composer locks; the dispatch itself runs // in the background — box provisioning can take ~90s and must never // hang the HTTP request + // The advisor a turn runs under, built in its own statement so the + // property is simply absent when the bot has none. + const activeAdvisor = { advisorModel: selection.advisorModel }; const activeSelection: ModelSelection = { instanceId, model, effort, - ...(selection.advisorModel ? { advisorModel: selection.advisorModel } : {}), + ...activeAdvisor, }; // A turn dispatched here is the thread running again, which retires any // boot-resume failure remembered against it: the refusal exists to stop a @@ -8376,6 +8379,9 @@ async function startTurn( const savedMaxHistoryTurns = maxHistoryTurnsSchema.safeParse(bot.maxHistoryTurns); if (savedMaxHistoryTurns.success) historySettings.maxHistoryTurns = savedMaxHistoryTurns.data; if (bot.historySummaryModel === true) historySettings.historySummaryModel = true; + // The advisor this turn runs under, built in its own statement so the + // property is simply absent when the bot has none. + const turnAdvisor = { advisorModel: selection.advisorModel }; const turnInput = { threadId, text: remindedWakeText(wakeUserText), @@ -8383,7 +8389,7 @@ async function startTurn( effort, // An advisor model rides this turn: the driver passes it per launch, // so the owner's global engine settings are never written. - ...(selection.advisorModel ? { advisorModel: selection.advisorModel } : {}), + ...turnAdvisor, // Only a cap this model's row offers reaches a driver; a stale value // from a model the bot has since left is dropped here. ...(!boxCloud && selection.contextCap !== undefined && From 49f042c856c30b7dfbb9c3307ce71b241f959782 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:04:20 -0600 Subject: [PATCH 3/5] Answer The Kody Findings: Expire The Advisor Probe And Guard The Busy Turn The four findings on the first two commits are fixed in this third commit. - The affirmative advisor probe now expires with the same bound as every other probe answer, so a CLI downgraded after the first lookup is noticed instead of believed forever. - An advisor change is a model change: the selection check compares the advisor as well, so an advisor-only PATCH while the bot works is refused with the same 409 as a model swap. - The advisor property is omitted when the bot has none, in the turn input and in the active selection, so neither carries an empty advisor key. - A new API test holds the fixture busy and proves that the advisor-only PATCH is refused with 409. Refs BF-2704 --- server/drivers/claude.ts | 6 ++++-- server/index.test.ts | 25 +++++++++++++++++++++++++ server/index.ts | 17 +++++++++++------ 3 files changed, 40 insertions(+), 8 deletions(-) diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts index 4f4aff6dd..8d4110a78 100644 --- a/server/drivers/claude.ts +++ b/server/drivers/claude.ts @@ -2363,10 +2363,12 @@ export const ClaudeDriver: ProviderDriver = { }; advisorFlagProbe = probe; void probe.result.then((answer) => { - if (answer === "yes") probe.expiresAt = Infinity; + // A yes expires with the same bound as the other answers: a CLI + // that is downgraded afterwards must be noticed, not believed + // forever, or the next advisor turn dies on an unknown option. // Not an answer: look again soon, but not on every call — each look // is another process on an already busy engine. - else if (answer === "unknown") probe.expiresAt = Date.now() + 5_000; + if (answer === "unknown") probe.expiresAt = Date.now() + 5_000; }); return probe.result; }; diff --git a/server/index.test.ts b/server/index.test.ts index 33711fda4..328406f7a 100644 --- a/server/index.test.ts +++ b/server/index.test.ts @@ -2751,6 +2751,31 @@ describe("harness HTTP API", () => { expect(refused.body.error).toContain("advisorModel"); }); + it("refuses an advisor-only change while the bot is working", async () => { + const claude = (await api("GET", "/api/instances")).body.instances.find((i: { instanceId: string }) => i.instanceId === "claude"); + const bot = (await api("POST", "/api/bots")).body.bot; + try { + await api("PATCH", `/api/bots/${bot.id}`, { + modelSelection: { instanceId: "claude", model: claude.models.default }, + }); + expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "hold this fixture turn" })).status).toBe(202); + await expect + .poll(async () => (await api("GET", "/api/bots?messages=0")).body.bots.find((b: { id: string }) => b.id === bot.id)?.busy) + .toBe(true); + + // An advisor is the model a turn consults, so swapping it while the + // bot works is refused the same way a model swap is. + const changed = await api("PATCH", `/api/bots/${bot.id}`, { + modelSelection: { instanceId: "claude", model: claude.models.default, advisorModel: "claude-opus-5-5" }, + }); + expect(changed.status).toBe(409); + expect(changed.body.error).toContain("the bot is working"); + } finally { + await api("POST", `/api/bots/${bot.id}/interrupt`, { threadId: bot.threadId }); + await api("DELETE", `/api/bots/${bot.id}`); + } + }); + it("clears legacy unsupported effort from task selection without clobbering primary bot effort", async () => { const created = await api("POST", "/api/bots", { name: "EffortBot", diff --git a/server/index.ts b/server/index.ts index f2da29317..b72971f6d 100644 --- a/server/index.ts +++ b/server/index.ts @@ -2666,6 +2666,9 @@ function checkedModelSelection( selection.instanceId !== current.selection.instanceId || selection.model !== current.selection.model || selection.effort !== current.selection.effort || + // An advisor is the model a turn consults, so swapping it while the bot + // works is the same stop-before-changing-models case as the model itself. + selection.advisorModel !== current.selection.advisorModel || selection.contextCap !== current.selection.contextCap || selection.maxOutputTokens !== current.selection.maxOutputTokens || JSON.stringify(selection.fallbacks) !== JSON.stringify(current.selection.fallbacks) @@ -7727,9 +7730,10 @@ async function startTurn( // busy flips immediately so the composer locks; the dispatch itself runs // in the background — box provisioning can take ~90s and must never // hang the HTTP request - // The advisor a turn runs under, built in its own statement so the - // property is simply absent when the bot has none. - const activeAdvisor = { advisorModel: selection.advisorModel }; + // The advisor a turn runs under. The property is absent when the bot has + // none, so a selection without an advisor carries no advisor key at all. + const activeAdvisor: Pick = {}; + if (selection.advisorModel) activeAdvisor.advisorModel = selection.advisorModel; const activeSelection: ModelSelection = { instanceId, model, @@ -8379,9 +8383,10 @@ async function startTurn( const savedMaxHistoryTurns = maxHistoryTurnsSchema.safeParse(bot.maxHistoryTurns); if (savedMaxHistoryTurns.success) historySettings.maxHistoryTurns = savedMaxHistoryTurns.data; if (bot.historySummaryModel === true) historySettings.historySummaryModel = true; - // The advisor this turn runs under, built in its own statement so the - // property is simply absent when the bot has none. - const turnAdvisor = { advisorModel: selection.advisorModel }; + // The advisor this turn runs under. The property is absent when the + // bot has none, so a turn without an advisor carries no advisor key. + const turnAdvisor: Pick = {}; + if (selection.advisorModel) turnAdvisor.advisorModel = selection.advisorModel; const turnInput = { threadId, text: remindedWakeText(wakeUserText), From e50df2bab54373c606360615c9be39b0283be042 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:52:05 -0600 Subject: [PATCH 4/5] Hold The Linux Closure: The Retained Source Policy Names The Advisor Module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Linux retained-source policy is the exact list of the files the server deployment keeps, and the new advisor module is imported by the server entry point, so the policy has to name it. The policy was regenerated with the repository's own discovery command at the head of the branch, and the change is one row: the new module, as a runtime file, with the reason that the server entry point imports it.  Nothing else in the policy moved, and the closure test passes locally with fifteen tests. Refs BF-2704 --- deploy/linux-server/retained-source.json | 1 + 1 file changed, 1 insertion(+) diff --git a/deploy/linux-server/retained-source.json b/deploy/linux-server/retained-source.json index 16711f6f8..9b996903f 100644 --- a/deploy/linux-server/retained-source.json +++ b/deploy/linux-server/retained-source.json @@ -1297,6 +1297,7 @@ {"path":"scripts/release-provenance.mjs","category":"runtime","reason":"Import from scripts/source-build-identity.mjs"}, {"path":"scripts/source-build-identity.mjs","category":"runtime","reason":"Import from server/runtime-identity.ts"}, {"path":"scripts/stage-entries.mjs","category":"runtime","reason":"Import from server/update-control.ts"}, + {"path":"server/advisor-model.ts","category":"runtime","reason":"Import from server/index.ts"}, {"path":"server/ai-usage.ts","category":"runtime","reason":"Import from server/telemetry.ts"}, {"path":"server/antigravity-models.ts","category":"runtime","reason":"Import from server/antigravity-quota.ts"}, {"path":"server/antigravity-quota.ts","category":"runtime","reason":"Import from server/index.ts"}, From b4a4c8bda7902568acc32614f46dc3cdfb69afa7 Mon Sep 17 00:00:00 2001 From: Jay Wedgeworth <12656028+jaywedgeworth22@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:22:06 -0600 Subject: [PATCH 5/5] Hold The Port Inventory: The Advisor Module Has An Owner Row MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Node decommission inventory is the gate that says every file under the audited roots has an owner or a retired reason, and a new file that no row names falls outside it.  The advisor module is now named in the launch-contract row, beside the contracts it rides, and the survey count at the top of the inventory is refreshed. Refs BF-2704 --- docs/native-rewrite-port-inventory.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/native-rewrite-port-inventory.md b/docs/native-rewrite-port-inventory.md index 0fc14574b..541876cb2 100644 --- a/docs/native-rewrite-port-inventory.md +++ b/docs/native-rewrite-port-inventory.md @@ -7,7 +7,7 @@ decommission): neither lands until every row below has a Swift owner or a retired reason. Surveyed at commit `c7902d63` (2026-10-21), re-counted 2026-10-25: -`server/` 374 non-test files, ~142,800 lines · `companion/src/` 17 files, +`server/` 375 non-test files, ~142,813 lines · `companion/src/` 17 files, ~11,330 lines · `shared/` 58 non-test files, ~11,050 lines (zero `node:` imports in source — only the three `*.test.ts` files reach for `node:fs`, so the portable set really is portable) · `electron/` 122 `.mjs`/`.cjs` files, @@ -48,7 +48,7 @@ cutover (BF-2498), signing/TCC (BF-2499). | `server/helpers/tracker.ts` | Helper progress → `EngineCoordinator` BF-2504 | | `server/procs.ts`, `server/tools/process-group.ts` | Process-group spawn/kill → `EngineDriver` supervision BF-2504 | | `server/permission-proxy.ts`, `server/computer-proxy.ts`, `server/mcp-bridge.ts`, `server/mcp-remote-proxy.ts` | Per-turn MCP/permission proxies → `EngineDriver` BF-2504 | -| `server/launch-identity.ts`, `server/contracts.ts`, `server/schema.ts`, `server/names.ts` | Launch contract + canonical types → `EngineDriver` BF-2504; contracts port as Swift protocols | +| `server/launch-identity.ts`, `server/contracts.ts`, `server/schema.ts`, `server/names.ts`, `server/advisor-model.ts` | Launch contract + canonical types → `EngineDriver` BF-2504; contracts port as Swift protocols; the advisor model id rule rides the contracts | | `server/tool-fields.ts`, `server/turn-tools.ts`, `server/tools/{agents,computer,github,host,jobs,phone,prompts,recall,shell-env,zulip}.ts`, `server/tools/registry.ts`, `schedule.ts` | Tool catalog + executors → `EngineDriver` tool lane BF-2504 (HTTP-lane tools fold into actor methods) | | `server/capability-profile.ts`, `server/computer-capability.ts`, `server/doomed-dispatch.ts`, `server/turn-safety.ts`, `server/turn-worktree-admission.ts` + wiring test | Dispatch gates → `EngineCoordinator` BF-2504 | | `server/model-{context-windows,fallback,lineage,default-slots,rejections}.ts`, `server/retired-model-ids.ts`, `server/instance-models.ts`, `server/claude-models.ts`, `server/antigravity-models.ts` | Model metadata + fallback chains → BF-2507 (data tables port with `shared/model-lineage.ts`) |