Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Claude: rebuild the session when a CLI cannot refresh its recorded prompt and the soul changed

skygunner5638d70a475a
diff --git a/server/agents-bridge-switch.ts b/server/agents-bridge-switch.ts
index fc1d77dbf2..bfc386c324 100644
--- a/server/agents-bridge-switch.ts
+++ b/server/agents-bridge-switch.ts
@@ -12,7 +12,7 @@ import { bridgedCallName } from "./agents-bridge-names.ts";
import { TOOL_BRIDGE_ENV } from "./drivers/agents-bridge.ts";
import { decodeInjectId } from "./drivers/local-inject.ts";
import { onThisNetwork } from "./drivers/openai-compat.ts";
-import { claudeCliSupports, parseClaudeCliVersion, resolveClaudeConfigDir } from "./drivers/claude.ts";
+import { resolveClaudeConfigDir } from "./drivers/claude.ts"; import { claudeCliSupports, parseClaudeCliVersion } from "./drivers/claude-cli-version.ts";
import { claudeToolSearchOn, claudeToolSearchSetting } from "./drivers/claude-tool-search.ts";
import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";
diff --git a/server/drivers/claude-cli-version.ts b/server/drivers/claude-cli-version.ts
new file mode 100644
index 0000000000..e34983a7f2
--- /dev/null
+++ b/server/drivers/claude-cli-version.ts
@@ -0,0 +1,58 @@
+// What each Claude CLI release accepts, and what an Engines snapshot should tell the operator to update.
+import { parseVersionTriple, versionAtLeast } from "./acp/version-probe.ts";
+import type { ProviderSnapshot } from "../contracts.ts";
+
+/** The first Claude CLI to accept each flag; an unknown flag is a hard argument error. Checked
+ * against the published binaries (the changelog never records --autocompact): --strict-mcp-config
+ * 1.0.60, --setting-sources 1.0.122, --autocompact 2.1.122. */
+export const CLAUDE_FLAG_FLOORS = {
+ "--strict-mcp-config": [1, 0, 60],
+ "--setting-sources": [1, 0, 122],
+ "--autocompact": [2, 1, 122],
+ "--system-prompt-snapshot": [2, 1, 267],
+ // 2.1.248 takes --restricted; 2.1.257 honours blockReadsOutsideWorkingDirectories.
+ "--restricted": [2, 1, 257],
+ // Keep-warm pings only. Not bisected: both are in every 2.1 build checked.
+ "--fork-session": [2, 1, 0],
+ "--no-session-persistence": [2, 1, 0],
+ // Background calls. Not bisected: the guest path passes it from 2.1.257.
+ "--tools": [2, 1, 257],
+} as const satisfies Record<string, ClaudeCliVersion>;
+
+export type ClaudeCliVersion = readonly [number, number, number];
+
+export const CLAUDE_CONTEXT_CONTROL_MIN_VERSION: ClaudeCliVersion = CLAUDE_FLAG_FLOORS["--system-prompt-snapshot"];
+
+/** The first CLI seen to echo a stdin user message with its uuid as a model call takes it in
+ * (--replay-user-messages, 2.1.282): a steer written during a tool call is echoed after that
+ * tool's result, one written during the last model call only after the turn's `result`. */
+export const CLAUDE_REPLAY_FLOOR: ClaudeCliVersion = [2, 1, 282];
+
+/** `claude --version` prints "2.1.232 (Claude Code)". */
+export function parseClaudeCliVersion(stdout: string | null | undefined): ClaudeCliVersion | null {
+ return parseVersionTriple(stdout ?? "");
+}
+
+export function claudeCliSupports(version: ClaudeCliVersion | null, flag: keyof typeof CLAUDE_FLAG_FLOORS): boolean {
+ return version === null || versionAtLeast(version, CLAUDE_FLAG_FLOORS[flag]);
+}
+
+export function claudeCliUpdate(version: string | null, cli: string): ProviderSnapshot["update"] | undefined {
+ const parsed = parseClaudeCliVersion(version);
+ if (!parsed || versionAtLeast(parsed, CLAUDE_CONTEXT_CONTROL_MIN_VERSION)) return undefined;
+ const floor = CLAUDE_CONTEXT_CONTROL_MIN_VERSION.join(".");
+ const missing = (Object.keys(CLAUDE_FLAG_FLOORS) as (keyof typeof CLAUDE_FLAG_FLOORS)[])
+ .filter((flag) => !claudeCliSupports(parsed, flag));
+ const effects = [
+ ...(missing.includes("--autocompact") ? ["no compaction window picked by OpenMausBot"] : []),
+ ...(missing.includes("--setting-sources") ? ["bots still see this machine's own Claude Code setup"] : []),
+ ...(missing.includes("--system-prompt-snapshot") ? ["resumed turns cannot refresh stale system prompts"] : []),
+ ];
+ return {
+ title: "Update Claude Code for context controls",
+ message:
+ `Claude Code ${parsed.join(".")} predates ${floor}, so bots run without ${missing.join(", ")}: ` +
+ `${effects.join("; ")}. Update it, then refresh Engines.`,
+ command: cli === "claude" ? "claude update" : `${cli} update`,
+ };
+}
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index a9fd457a70..2e3ecb21a7 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -16,12 +16,9 @@ import { claudeHookSettings } from "./claude-hooks.ts";
import {
autoCompactWindow,
brokerSocketCandidates,
- claudeCliSupports,
- claudeCliUpdate,
ClaudeDriver,
createPermissionBroker,
hookTokenFile,
- parseClaudeCliVersion,
permissionSocketPath,
readClaudeAuthSettings,
claudeCostSnapshot,
@@ -30,6 +27,7 @@ import {
turnCostFromRunningTotal,
type ClaudeConfig,
} from "./claude.ts";
+import { claudeCliSupports, claudeCliUpdate, parseClaudeCliVersion } from "./claude-cli-version.ts";
import { spawnContractDiff } from "./claude-spawn-contract.ts";
import { sumNativeTurnResults } from "./claude-turn-result.ts";
import { TEAM_TOOLS_FAILED } from "./team-tools.ts";
@@ -1710,6 +1708,51 @@ describe("ClaudeDriver turns (fake CLI)", () => {
expect(seen.prompt.message.content).toContain("Add the new header row.");
});
+ it("does not resume a session holding a system prompt the CLI cannot refresh, and rebuilds from the recovery text", async () => {
+ const dump = join(scratch, "stale-recorded-prompt.json");
+ await create(undefined, { FAKE_CLAUDE_DUMP: dump, FAKE_CLAUDE_VERSION: "2.1.232" });
+ const first = await instance.adapter.sendTurn({ threadId: "t-stale-recorded-prompt", text: "one", system: "Always answer MARK_V1." });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === first.turnId);
+ const announced = (recorder.events.find((e) => e.type === "session.started") as { sessionId: string }).sessionId;
+
+ const rebuild = "[Your previous session for this conversation could not be resumed, so this is a new session.] one";
+ const second = await instance.adapter.sendTurn({
+ threadId: "t-stale-recorded-prompt", text: "two", system: "Always answer MARK_V2.", resumeCursor: announced, recoveryText: rebuild,
+ });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(seen.argv).not.toContain("--system-prompt-snapshot");
+ expect(seen.argv).not.toContain("--resume");
+ expect(seen.argv).toContain("--session-id");
+ expect(seen.systemPromptFile).toBe("Always answer MARK_V2.");
+ const content = seen.prompt.message.content;
+ expect(typeof content === "string" ? content : content.map((c: any) => c.text ?? "").join("")).toBe(rebuild);
+ expect(recorder.events.filter((e) => e.type === "session.started").at(-1)).toMatchObject({ rebuilt: true });
+
+ // From then on the replacement session resumes normally.
+ const replacement = (recorder.events.filter((e) => e.type === "session.started").at(-1) as { sessionId: string }).sessionId;
+ const rebuiltPid = seen.pid;
+ const third = await instance.adapter.sendTurn({ threadId: "t-stale-recorded-prompt", text: "three", effort: "high", system: "Always answer MARK_V2.", resumeCursor: replacement });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === third.turnId);
+ const resumed = JSON.parse(readFileSync(dump, "utf8"));
+ expect(resumed.pid).not.toBe(rebuiltPid);
+ expect(resumed.argv[resumed.argv.indexOf("--resume") + 1]).toBe(replacement);
+ });
+
+ it("resumes a session on a CLI without the snapshot flag when the system prompt is unchanged", async () => {
+ const dump = join(scratch, "unchanged-recorded-prompt.json");
+ await create(undefined, { FAKE_CLAUDE_DUMP: dump, FAKE_CLAUDE_VERSION: "2.1.232" });
+ const first = await instance.adapter.sendTurn({ threadId: "t-unchanged-recorded-prompt", text: "one", system: "You are Testy." });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === first.turnId);
+ const firstPid = dumpedPid(dump);
+ const announced = (recorder.events.find((e) => e.type === "session.started") as { sessionId: string }).sessionId;
+ const second = await instance.adapter.sendTurn({ threadId: "t-unchanged-recorded-prompt", text: "two", effort: "high", system: "You are Testy.", resumeCursor: announced });
+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);
+ const seen = JSON.parse(readFileSync(dump, "utf8"));
+ expect(seen.pid).not.toBe(firstPid);
+ expect(seen.argv[seen.argv.indexOf("--resume") + 1]).toBe(announced);
+ });
+
it("replaces the previous computer prompt when a normal conversation changes its place", async () => {
const dump = join(scratch, "surface-snapshot.json");
await create(undefined, { FAKE_CLAUDE_DUMP: dump, FAKE_CLAUDE_VERSION: "2.1.267" });
@@ -3811,7 +3854,7 @@ describe("ClaudeDriver turns (fake CLI)", () => {
await instance.dispose();
await create(undefined, { FAKE_CLAUDE_COST_STATE: costState });
}
- const second = await instance.adapter.sendTurn({ threadId, text: "two", system: "After.", systemStable: "After.", resumeCursor: announced });
+ const second = await instance.adapter.sendTurn({ threadId, text: "two", effort: "high", system: "Before.", systemStable: "Before.", resumeCursor: announced });
const secondDone = await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);
expect(JSON.parse(readFileSync(join(costState, `${announced}.json`), "utf8")).total).toBe(0.02);
expect([firstDone, secondDone].map((e) => (e as { cost?: unknown }).cost)).toEqual([0.01, 0.01]);
@@ -3827,10 +3870,10 @@ describe("ClaudeDriver turns (fake CLI)", () => {
const first = await instance.adapter.sendTurn({ threadId, text: "one", system: "Before.", systemStable: "Before." });
await recorder.until((e) => e.type === "turn.completed" && e.turnId === first.turnId);
const announced = (recorder.events.find((e) => e.type === "session.started") as { sessionId: string }).sessionId;
- const failed = await instance.adapter.sendTurn({ threadId, text: "two", system: "After.", systemStable: "After.", resumeCursor: announced });
+ const failed = await instance.adapter.sendTurn({ threadId, text: "two", effort: "high", system: "Before.", systemStable: "Before.", resumeCursor: announced });
expect(await recorder.until((e) => e.type === "turn.completed" && e.turnId === failed.turnId)).toMatchObject({ ok: false, cost: null });
const launch = dumpedPid(dump);
- const third = await instance.adapter.sendTurn({ threadId, text: "three", system: "After.", systemStable: "After.", resumeCursor: announced });
+ const third = await instance.adapter.sendTurn({ threadId, text: "three", effort: "high", system: "Before.", systemStable: "Before.", resumeCursor: announced });
const thirdDone = await recorder.until((e) => e.type === "turn.completed" && e.turnId === third.turnId);
expect(dumpedPid(dump)).toBe(launch);
expect(JSON.parse(readFileSync(join(costState, `${announced}.json`), "utf8")).total).toBe(0.02);
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index 2b6b42da48..853eb3a7c9 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -22,7 +22,7 @@ import { claudeOwnMcpOverHttp, withLoopbackNoProxy } from "./own-mcp-http.ts"; i
import { claudeElicitations } from "./claude-elicitation.ts"; import { claudePrestartTools, type ClaudePrestartTools } from "./claude-prestart.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts"; import { claudeContextUsage, liveContextBreakdown, writeControlFrame } from "./claude-context-usage.ts";
import { claudeCostSnapshot, readCostHistory, recordCostState, restoredCostBase, turnCostFromRunningTotal } from "./claude-cost-history.ts";
export { claudeCostSnapshot, restoredCostBase, turnCostFromRunningTotal, type ClaudeCostSnapshot } from "./claude-cost-history.ts";
-import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";
+import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts"; import { CLAUDE_REPLAY_FLOOR, type ClaudeCliVersion, claudeCliSupports, claudeCliUpdate, parseClaudeCliVersion } from "./claude-cli-version.ts";
import { ClaudeLoginController } from "./claude-login-auth.ts";
import type {
@@ -48,7 +48,7 @@ import { engineHomes } from "../engine-homes/engine-homes.ts";
import { TEAM_TOOLS_FAILED, failedCustomMcp, teamToolsFailed } from "./team-tools.ts";
import { PRESTART_IDLE_MS, armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose, stoppedForRoom } from "./session-idle.ts";
import { keyedStable, promptHalves, withRosterNote, withVolatileNote } from "./prompt-split.ts"; import { CLAUDE_OWN_MEMORY_OFF } from "./claude-own-memory.ts";
-import { parseVersionTriple, versionAtLeast } from "./acp/version-probe.ts";
+import { versionAtLeast } from "./acp/version-probe.ts";
import {
applyClaudeInject,
decodeInjectId,
@@ -193,23 +193,6 @@ export function autoCompactWindow(env: NodeJS.ProcessEnv, model?: string | null)
const DEFAULT_AUTOCOMPACT_TOKENS = 200_000;
-/** The first Claude CLI to accept each flag; an unknown flag is a hard argument error. Checked
- * against the published binaries (the changelog never records --autocompact): --strict-mcp-config
- * 1.0.60, --setting-sources 1.0.122, --autocompact 2.1.122. */
-export const CLAUDE_FLAG_FLOORS = {
- "--strict-mcp-config": [1, 0, 60],
- "--setting-sources": [1, 0, 122],
- "--autocompact": [2, 1, 122],
- "--system-prompt-snapshot": [2, 1, 267],
- // 2.1.248 takes --restricted; 2.1.257 honours blockReadsOutsideWorkingDirectories.
- "--restricted": [2, 1, 257],
- // Keep-warm pings only. Not bisected: both are in every 2.1 build checked.
- "--fork-session": [2, 1, 0],
- "--no-session-persistence": [2, 1, 0],
- // Background calls. Not bisected: the guest path passes it from 2.1.257.
- "--tools": [2, 1, 257],
-} as const satisfies Record<string, ClaudeCliVersion>;
-
const withWhy = (refusal: string, why: string | undefined) => why ? `${refusal} ${why}` : refusal;
/** Probed on Claude Code 2.1.284 in `default` mode: without this list, built-in "read-only" Bash
@@ -221,44 +204,6 @@ export const GUEST_CLAUDE_PERMISSIONS = {
deny: ["Bash", "PowerShell", "WebFetch", "Read(//proc/**)"],
} as const;
-export type ClaudeCliVersion = readonly [number, number, number];
-
-export const CLAUDE_CONTEXT_CONTROL_MIN_VERSION: ClaudeCliVersion = CLAUDE_FLAG_FLOORS["--system-prompt-snapshot"];
-
-/** The first CLI seen to echo a stdin user message with its uuid as a model call takes it in
- * (--replay-user-messages, 2.1.282): a steer written during a tool call is echoed after that
- * tool's result, one written during the last model call only after the turn's `result`. */
-export const CLAUDE_REPLAY_FLOOR: ClaudeCliVersion = [2, 1, 282];
-
-/** `claude --version` prints "2.1.232 (Claude Code)". */
-export function parseClaudeCliVersion(stdout: string | null | undefined): ClaudeCliVersion | null {
- return parseVersionTriple(stdout ?? "");
-}
-
-export function claudeCliSupports(version: ClaudeCliVersion | null, flag: keyof typeof CLAUDE_FLAG_FLOORS): boolean {
- return version === null || versionAtLeast(version, CLAUDE_FLAG_FLOORS[flag]);
-}
-
-export function claudeCliUpdate(version: string | null, cli: string): ProviderSnapshot["update"] | undefined {
- const parsed = parseClaudeCliVersion(version);
- if (!parsed || versionAtLeast(parsed, CLAUDE_CONTEXT_CONTROL_MIN_VERSION)) return undefined;
- const floor = CLAUDE_CONTEXT_CONTROL_MIN_VERSION.join(".");
- const missing = (Object.keys(CLAUDE_FLAG_FLOORS) as (keyof typeof CLAUDE_FLAG_FLOORS)[])
- .filter((flag) => !claudeCliSupports(parsed, flag));
- const effects = [
- ...(missing.includes("--autocompact") ? ["no compaction window picked by OpenMausBot"] : []),
- ...(missing.includes("--setting-sources") ? ["bots still see this machine's own Claude Code setup"] : []),
- ...(missing.includes("--system-prompt-snapshot") ? ["resumed turns cannot refresh stale system prompts"] : []),
- ];
- return {
- title: "Update Claude Code for context controls",
- message:
- `Claude Code ${parsed.join(".")} predates ${floor}, so bots run without ${missing.join(", ")}: ` +
- `${effects.join("; ")}. Update it, then refresh Engines.`,
- command: cli === "claude" ? "claude update" : `${cli} update`,
- };
-}
-
const DRIVER_KIND = "claudeAgent";
const NO_ANTHROPIC_KEY = "No Anthropic API key — open Settings → AI → Providers.";
@@ -798,6 +743,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
const sessions = new Map<string, Session>();
const warmContracts = new Map<string, KeepWarmContract>();
+ /** The system prompt each thread's native session is known to hold: a fresh session holds what it launched with, and
+ * a resumed one only when the CLI refreshed it (--system-prompt-snapshot); an older CLI's resume keeps what it started with. */
+ const recordedPrompts = new Map<string, { session: string; prompt: string }>();
const warmHolds = new Map<string, number>();
const spares = new Map<string, Promise<unknown>>(), spareTools = claudePrestartTools();
const sessionIdle = sessionIdlePolicy("CLAUDE");
@@ -929,8 +877,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (controlsHost && permissionMode === "bypassPermissions" && turn.approvalMode !== "full") {
throw new Error("local computer control requires the interactive approval broker");
}
- // Before any broker or process, so a bad attachment leaves nothing live.
- const promptMsg = claudeUserMessage(turn.text, turn.images);
let turnId = logicalTurnId ?? newId();
const retryAbort = new AbortController();
const retry = retryState.get(threadId) ?? { attempt: 0, cancelled: false };
@@ -940,8 +886,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
if (!spare) retryState.set(threadId, retry);
const retryScale = Number(process.env.FAKE_CLAUDE_RETRY_SCALE ?? "1");
- const sessionId = !turn.sessionReset && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;
- const newSessionId = sessionId ? null : newId();
+ let sessionId = !turn.sessionReset && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;
+ let newSessionId = sessionId ? null : newId();
const args = [
"-p",
@@ -982,7 +928,26 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
const compactWindow = autoCompactWindow(turnEnvironment, injected.model);
const passedAutocompact = Boolean(compactWindow) && ownCli && cliHasAutocompact === true; if (compactWindow && passedAutocompact) args.push("--autocompact", compactWindow);
// --resume keeps the recorded system prompt, so every turn refreshes it.
- if (ownCli && cliVersionChecked && claudeCliSupports(cliVersion, "--system-prompt-snapshot")) args.push("--system-prompt-snapshot", "off");
+ const refreshesRecordedPrompt = ownCli && cliVersionChecked && claudeCliSupports(cliVersion, "--system-prompt-snapshot");
+ if (refreshesRecordedPrompt) args.push("--system-prompt-snapshot", "off");
+ // Before any broker or process, so a bad attachment leaves nothing live.
+ let promptMsg = claudeUserMessage(turn.text, turn.images);
+ // A new process gets the stable half only; the volatile half rides its first message, so a relaunch reuses the cached prefix.
+ const halves = promptHalves(turn);
+ const launchSystem = halves.stable ?? turn.system;
+ // A CLI without the snapshot flag reopens a session with the prompt it recorded at launch, so a changed prompt
+ // would never reach it: rebuild the turn from the recovery text in a fresh session instead of resuming stale.
+ const recordedPrompt = createHash("sha256").update(keyedStable(turn) ?? turn.system ?? "").digest("hex");
+ const recorded = sessionId === null ? undefined : recordedPrompts.get(threadId);
+ if (sessionId !== null && !refreshesRecordedPrompt && recorded !== undefined && recorded.session === sessionId && recorded.prompt !== recordedPrompt) {
+ const recovery = recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure: "before-accept" });
+ console.error(`claude (${instanceId}): session ${sessionId} for thread ${threadId} holds a system prompt this CLI cannot refresh, starting a new one`);
+ turn = { ...turn, text: recovery.text, resumeCursor: undefined, recoveryText: undefined };
+ sessionId = null;
+ newSessionId = newId();
+ promptMsg = claudeUserMessage(turn.text, turn.images);
+ retry.rebuilt = recovery.replayed;
+ }
if (injected.model) args.push("--model", injected.model);
if (turn.effort) args.push("--effort", turn.effort);
@@ -1160,9 +1125,6 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
// The old process and its tree end before the new one starts, so two never share the session.
if (live) { closeSession(threadId, turn.sessionReset ? "context reset" : imagesOver ? "images over the request limit" : "spawn contract changed", turn.sessionReset || imagesOver ? undefined : spawnContractDiff(live.argsKey, argsKey)); await (live.spare ? stopEngineTree(live.child, 0, 0) : stopEngineTree(live.child)); } // an unused spare has nothing to save: no wait for it to leave by itself
- // A new process gets the stable half only; the volatile half rides its first message, so a relaunch reuses the cached prefix.
- const halves = promptHalves(turn);
- const launchSystem = halves.stable ?? turn.system;
// Until sessions.set() below, this turn owns every launch resource and must release it on failure.
const cleanupUnownedLaunch = () => {
@@ -1299,6 +1261,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
costTotal: undefined,
};
sessions.set(threadId, session);
+ // A fresh session holds this prompt, and so does a resumed one the CLI refreshed; an older CLI's resume keeps
+ // whatever it launched with, so it is not recorded as holding this one.
+ if (sessionId === null || refreshesRecordedPrompt) recordedPrompts.set(threadId, { session: sessionId ?? newSessionId!, prompt: recordedPrompt });
const settle = (
ok: boolean,