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
1 change: 1 addition & 0 deletions deploy/linux-server/retained-source.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
Expand Down
4 changes: 2 additions & 2 deletions docs/native-rewrite-port-inventory.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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`) |
Expand Down
34 changes: 34 additions & 0 deletions docs/rollouts/2026-11-26-claude-advisor-per-turn.md
Original file line number Diff line number Diff line change
@@ -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 <model>` 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 <model>` (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 <model>` and the `advisorModel` settings key.
- A live CLI run against a throwaway config accepted both `--advisor <model>` 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.
1 change: 1 addition & 0 deletions docs/verification/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions docs/verification/claude-advisor.md
Original file line number Diff line number Diff line change
@@ -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 <model>` |
| `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.
13 changes: 13 additions & 0 deletions server/advisor-model.ts
Original file line number Diff line number Diff line change
@@ -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);
}
8 changes: 8 additions & 0 deletions server/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,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`. */
Expand Down Expand Up @@ -328,6 +332,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). */
Expand Down
46 changes: 46 additions & 0 deletions server/drivers/claude.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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();
Expand Down
63 changes: 63 additions & 0 deletions server/drivers/claude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export { STATIC_CLAUDE_MODELS };
import { computerProxyEnv } from "../container-computer.ts";
import { hostToolPrefix, turnComputerMounts } from "../computer-grants.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";
Expand Down Expand Up @@ -1189,6 +1190,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
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 {
Expand Down Expand Up @@ -1261,6 +1266,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
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
Expand Down Expand Up @@ -2328,6 +2337,60 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
throw reason;
};

// The advisor tool is a launch flag (`--advisor <model>`), 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<AdvisorFlagAnswer> } | undefined;
const probeAdvisorFlag = (env: NodeJS.ProcessEnv): Promise<AdvisorFlagAnswer> => {
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<AdvisorFlagAnswer>((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) => {
// 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
Comment thread
swu-minimax[bot] marked this conversation as resolved.
Resolved
// is another process on an already busy engine.
if (answer === "unknown") probe.expiresAt = Date.now() + 5_000;
});
return probe.result;
};
const requireAdvisorSupport = async (advisorModel: string): Promise<void> => {
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 });
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".
Expand Down
Loading
Loading