Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
claude: log which spawn-contract fields changed on process replacement
SongYichena74a4f19b188
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.tsindex c3dc2160ab..790f322596 100644--- a/server/drivers/claude.test.ts+++ b/server/drivers/claude.test.ts@@ -25,6 +25,7 @@ import {claudeCostSnapshot,restoredCostBase,STEERED_CONTINUATION_GRACE_MS,+ spawnContractDiff,sumNativeTurnResults,turnCostFromRunningTotal,type ClaudeConfig,@@ -410,6 +411,47 @@ describe("ClaudeDriver.decodeConfig", () => {);});+describe("spawnContractDiff", () => {+ const key = (overrides: Record<string, unknown> = {}) => JSON.stringify({+ args: ["--model", "opus"],+ system: "stable",+ mcpServers: { agents: { command: "node", args: ["agents"], env: { TOKEN: "secret" } } },+ cwd: "/work",+ model: "opus",+ base: null,+ configDir: null,+ hooks: false,+ toolSearch: false,+ botSettings: "aaa",+ auth: "bbb",+ ...overrides,+ });++ it("reports nothing for identical keys", () => {+ expect(spawnContractDiff(key(), key())).toEqual([]);+ });++ it("names changed scalar fields", () => {+ expect(spawnContractDiff(key(), key({ model: "sonnet" }))).toEqual(["model"]);+ });++ it("names added and removed MCP servers without their configs", () => {+ expect(spawnContractDiff(key(), key({ mcpServers: {} }))).toEqual(["mcpServers:-agents"]);+ expect(spawnContractDiff(key({ mcpServers: {} }), key())).toEqual(["mcpServers:+agents"]);+ });++ it("names a server whose config changed, not the config", () => {+ const changed = spawnContractDiff(key(), key({ mcpServers: { agents: { command: "node", args: ["agents"], env: { TOKEN: "rotated" } } } }));+ expect(changed).toEqual(["mcpServers:~agents"]);+ expect(JSON.stringify(changed)).not.toContain("rotated");+ });++ it("reports nothing for unparseable keys", () => {+ expect(spawnContractDiff("not json", key())).toEqual([]);+ expect(spawnContractDiff(key(), "{")).toEqual([]);+ });+});+describe("ClaudeDriver turns (fake CLI)", () => {let instance: ProviderInstance;let recorder: EventRecorder;@@ -3535,6 +3577,48 @@ describe("ClaudeDriver turns (fake CLI)", () => {expect(dump.argv).toContain("claude-other");});+ it("names the changed contract fields when a warm process is replaced", async () => {+ await create();+ await instance.adapter.sendTurn({+ threadId: "t-contract-diff",+ text: "one",+ integrations: { agents: { command: "node", args: ["agents"], env: {} } },+ });+ await recorder.until((e) => e.type === "turn.completed");+ const announced = (recorder.events.find((e) => e.type === "session.started") as { sessionId: string }).sessionId;+ const second = await instance.adapter.sendTurn({+ threadId: "t-contract-diff",+ text: "two",+ resumeCursor: announced,+ });+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);+ // The native log flushes after the turn; poll for the close line instead of sleeping.+ const close = await new Promise<{ contractChanged?: string[] }>((resolve, reject) => {+ const deadline = Date.now() + 10_000;+ const log = join(NATIVE_DIR, "t-contract-diff.ndjson");+ const check = () => {+ if (Date.now() > deadline) return reject(new Error("contract-change close was never logged"));+ try {+ const lines = readFileSync(log, "utf8").split("\n").filter(Boolean);+ for (const line of lines) {+ let entry: { msg?: { close?: string; contractChanged?: string[] } };+ try {+ entry = JSON.parse(line);+ } catch {+ continue;+ }+ if (entry.msg?.close === "spawn contract changed" && entry.msg.contractChanged) return resolve(entry.msg);+ }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return reject(error);+ }+ setTimeout(check, 50);+ };+ check();+ });+ expect(close.contractChanged).toContain("mcpServers:-agents");+ }, 20_000);+it("closes an idle session after the configured window", async () => {// Ten seconds is the floor; poll the native log for the close instead of sleeping past it.process.env.OMB_CLAUDE_SESSION_IDLE_MIN_MS = "10000";diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex ebbf371017..a50bd7ba64 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -192,6 +192,42 @@ export function autoCompactWindow(env: NodeJS.ProcessEnv): string | null {const DEFAULT_AUTOCOMPACT_TOKENS = 200_000;+const isObject = (value: unknown): value is Record<string, unknown> =>+ typeof value === "object" && value !== null && !Array.isArray(value);++/** Which fields of a spawn-contract key changed between two turns, for the close line when a+ * warm process is replaced. Names only, never values: a server's config carries credentials,+ * and the two hashes already hide their inputs. */+export function spawnContractDiff(previous: string, next: string): string[] {+ let oldKey: unknown;+ let newKey: unknown;+ try {+ oldKey = JSON.parse(previous);+ newKey = JSON.parse(next);+ } catch {+ return [];+ }+ if (!isObject(oldKey) || !isObject(newKey)) return [];+ const changed: string[] = [];+ for (const field of new Set([...Object.keys(oldKey), ...Object.keys(newKey)])) {+ const oldValue = oldKey[field];+ const newValue = newKey[field];+ if (JSON.stringify(oldValue) === JSON.stringify(newValue)) continue;+ if (field === "mcpServers" && isObject(oldValue) && isObject(newValue)) {+ for (const name of Object.keys(oldValue)) {+ if (!(name in newValue)) changed.push(`mcpServers:-${name}`);+ else if (JSON.stringify(oldValue[name]) !== JSON.stringify(newValue[name])) changed.push(`mcpServers:~${name}`);+ }+ for (const name of Object.keys(newValue)) {+ if (!(name in oldValue)) changed.push(`mcpServers:+${name}`);+ }+ } else {+ changed.push(field);+ }+ }+ return changed;+}+/** 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. */@@ -909,7 +945,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {sessions.delete(threadId);session.turn = null;};- const closeSession = (threadId: string, why: string) => {+ const closeSession = (threadId: string, why: string, contractChanged?: string[]) => {const s = sessions.get(threadId);if (!s || s.closing) return;s.closing = true;@@ -920,7 +956,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {s.broker = undefined;broker?.close();s.elicit.close();- appendNative(threadId, { dir: "out", source: "claude.session", msg: { close: why } });+ appendNative(threadId, { dir: "out", source: "claude.session", msg: { close: why, ...(contractChanged?.length ? { contractChanged } : {}) } });// stdin EOF is the CLI's exit signal; give it a moment, then insisttry {s.child.stdin.end();@@ -1237,7 +1273,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {}return { turnId };}- if (live) closeSession(threadId, turn.sessionReset ? "context reset" : "spawn contract changed");+ if (live) {+ const contractChanged = turn.sessionReset ? undefined : spawnContractDiff(live.argsKey, argsKey);+ closeSession(threadId, turn.sessionReset ? "context reset" : "spawn contract changed", contractChanged);+ }// 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;