Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Codex: compact a thread in place on its kept app-server
laijsg175765491817f
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.tsindex e0851d8c76..bc6aabf84e 100644--- a/server/bot-box/env.test.ts+++ b/server/bot-box/env.test.ts@@ -27,7 +27,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set(["OMB_CLOUD_PUBLIC_HOST", "OMB_CLOUD_ROLE", "OMB_CLOUD_SECRETS_FD", "OMB_CLOUD_STAGING","OMB_CLOUD_STOPPED_HOLD_DAYS", "OMB_CLOUD_TEAM_ID", "OMB_CLOUD_TEAM_LANGUAGE", "OMB_CLOUD_TEAM_NAME","OMB_CLOUD_TRUSTED_PROXIES", "OMB_CLOUD_TUNNEL_BIN", "OMB_CLOUD_TUNNEL_TOKEN", "OMB_CLOUD_VOICE_TOKEN",- "OMB_CLOUD_VOICE_URL", "OMB_CLOUD_X_TOKEN", "OMB_CLOUD_X_URL", "OMB_CODEX_LAUNCH_SLOTS", "OMB_CODEX_SESSION_IDLE_", "OMB_CODEX_SESSION_KEEP", "OMB_COMPANION_DIR",+ "OMB_CLOUD_VOICE_URL", "OMB_CLOUD_X_TOKEN", "OMB_CLOUD_X_URL", "OMB_CODEX_COMPACT_TIMEOUT_MS", "OMB_CODEX_LAUNCH_SLOTS", "OMB_CODEX_SESSION_IDLE_", "OMB_CODEX_SESSION_KEEP", "OMB_COMPANION_DIR","OMB_COMPANION_HOSTED_URL", "OMB_COMPANION_INTERNAL_ORIGIN", "OMB_COMPANION_PORT", "OMB_COMPANION_ROUTES","OMB_COMPANION_TAILNET_NAME", "OMB_COMPOSIO_API", "OMB_COMPOSIO_BROKER", "OMB_COMPOSIO_BROKER_TOKEN","OMB_COMPOSIO_BROKER_URL", "OMB_COMPOSIO_TOOLKITS_API", "OMB_COMPUTER_CALL_ACT_WITHIN_MS",diff --git a/server/contracts.ts b/server/contracts.tsindex 714e40662b..08c1d151a4 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -341,6 +341,12 @@ export interface ProviderAdapter {hold(threadId: ThreadId, until: number | null): boolean;compact?(threadId: ThreadId, options: { instructions: string; session?: string; signal?: AbortSignal }): Promise<IdleCompactResult>;};+ /** The engine's own compaction of this thread's native session, in place, asked for by the person. `session` is the+ * resume cursor the host holds, `model` the selection the next turn would run on, and `selectionNow` the instance and model read again+ * when the engine is about to be asked. Only a kept engine process that is+ * still on that session takes it: otherwise `ok` is false and nothing was sent to the engine. `usage` is null when the+ * engine reports none for the compaction. */+ compactSession?(threadId: ThreadId, options: { botId?: string; session: string; model?: string | null; selectionNow?: () => { instanceId: string; model: string | null } | undefined; signal?: AbortSignal }): Promise<EngineCompactResult>;/** Starting a thread's engine before its first message, so that message finds it running. `start` launches the process* exactly as a turn with this input would and sends it nothing; it resolves true once the process is launched. The next* sendTurn on the thread takes that process when its launch would have been the same and it has started up (`ready`),@@ -369,6 +375,10 @@ export type IdleCompactResult =| { ok: true; session: string; sessionBefore: string; input: number; cacheRead: number; cacheWrite: number; output: number; costUsd: number | null; model: string | null }| { ok: false; reason: string; busy?: boolean; limit?: boolean };+export type EngineCompactResult =+ | { ok: true; usage: { input: number; output: number; cachedInput: number } | null; model: string | null }+ | { ok: false; reason: string };+export type SteerOutcome = "steered" | "refused" | "indeterminate";export interface ProviderSnapshot {diff --git a/server/drivers/codex-catalog.ts b/server/drivers/codex-catalog.tsindex e2bd4e6d5b..c78da32dc3 100644--- a/server/drivers/codex-catalog.ts+++ b/server/drivers/codex-catalog.ts@@ -55,6 +55,13 @@ export function decodeCodexSelection(id: string | null | undefined): {return { model: id, modelProvider: OFFICIAL_CODEX_PROVIDER };}+/** The model and provider a thread is started or resumed with: a routed (company or endpoint) instance and a ChatGPT plan+ * name their own, any other follows the model's selection. */+export function codexThreadSelection(route: { routedProvider?: string; plan: boolean }, model: string | null | undefined): { model?: string | null; modelProvider: string | null; serviceTier?: string } {+ if (route.routedProvider) return { model, modelProvider: route.routedProvider };+ return route.plan ? { model, modelProvider: "openai_chatgpt_plan" } : decodeCodexSelection(model);+}+/** Starts Codex on the chosen model's provider. codex-cli 0.167.0 refuses a turn whose thread provider differs from its* current one ("This chat uses custom, but your current provider is magpie"), whatever config.toml's model_provider says. */export function codexSelectedProviderArgs(env: Record<string, string | undefined>, modelId: string | null | undefined): string[] {diff --git a/server/drivers/codex-compact.test.ts b/server/drivers/codex-compact.test.tsnew file mode 100644index 0000000000..4ec8e7ad94--- /dev/null+++ b/server/drivers/codex-compact.test.ts@@ -0,0 +1,407 @@+import { copyFileSync, appendFileSync, chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { EngineCompactResult, ProviderInstance } from "../contracts.ts";+import { recordEvents, type EventRecorder } from "../testing/events.ts";+import { CodexDriver } from "./codex.ts";+import { flushNativeLog } from "./native.ts";+import { NATIVE_DIR } from "../config.ts";++const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-codex-app-server.ts");+const MODEL = "gpt-fake-default";++const alive = (pid: number): boolean => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+};+const until = async (condition: () => boolean, what: string, timeoutMs = 10_000) => {+ const deadline = Date.now() + timeoutMs;+ while (!condition()) {+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);+ await new Promise((wake) => setTimeout(wake, 10));+ }+};++describe("Codex's own compaction of a kept app-server's thread (fake app-server)", () => {+ let instance: ProviderInstance;+ let recorder: EventRecorder;+ let scratch: string;+ let home: string;+ let log: string;+ let cli = FAKE_CLI;+ let thread: number;++ const create = async (environment: Record<string, string> = {}, options: { cli?: string; endpoint?: { url: string; models: string[] } } = {}) => {+ instance = await CodexDriver.create({+ instanceId: "codex-compact-test", displayName: "Codex Test", enabled: true,+ environment: { HOME: scratch, USERPROFILE: scratch, CODEX_HOME: home, FAKE_CODEX_MODE: "resume", FAKE_CODEX_CALL_LOG: log, FAKE_CODEX_THREAD_IDS: "distinct",+ FAKE_CODEX_INTERRUPT_GRACE_MS: "300", ...(options.endpoint ? { OPENMAUSBOT_CODEX_API_KEY: "synthetic-endpoint-key" } : {}), ...environment },+ config: { cli: options.cli ?? cli, fullAuto: false, ...(options.endpoint ? { endpoint: options.endpoint } : {}) },+ });+ recorder = recordEvents(instance.adapter);+ };+ const calls = (method?: string): Array<{ pid: number; method: string; params: any }> =>+ (existsSync(log) ? readFileSync(log, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : []).filter((call) => !method || call.method === method);+ const runTurn = async (threadId: string, text: string, resumeCursor?: string) => {+ const { turnId } = await instance.adapter.sendTurn({ threadId, text, model: MODEL, ...(resumeCursor ? { resumeCursor } : {}) });+ const done = await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ const started = recorder.events.find((event) => event.type === "session.started" && event.turnId === turnId) as { sessionId: string } | undefined;+ return { done, session: started!.sessionId, events: recorder.events.filter((event) => event.turnId === turnId) };+ };+ const compact = (threadId: string, session: string, options: { signal?: AbortSignal; model?: string; selectionNow?: () => { instanceId: string; model: string } } = {}): Promise<EngineCompactResult> =>+ instance.adapter.compactSession!(threadId, { session, model: options.model ?? MODEL, ...(options.selectionNow ? { selectionNow: options.selectionNow } : {}), ...(options.signal ? { signal: options.signal } : {}) });+ const pidOf = () => calls("turn/start").at(-1)!.pid;+ const closes = (threadId: string) => {+ flushNativeLog(threadId);+ return readFileSync(join(NATIVE_DIR, `${threadId}.ndjson`), "utf8").trim().split("\n").map((line) => JSON.parse(line))+ .filter((entry) => entry.source === "codex.session").map((entry) => entry.msg);+ };+ const kept = async (environment: Record<string, string> = {}, options: { cli?: string } = {}) => {+ await create(environment, options);+ const threadId = `t-compact-${++thread}`;+ const first = await runTurn(threadId, "one");+ const pid = pidOf();+ await until(() => calls("config/read").filter((call) => call.pid === pid).length >= 2, "the kept process's configuration re-read");+ return { threadId, session: first.session, pid };+ };+ const authenticate = (account: string) => writeFileSync(join(home, "auth.json"), JSON.stringify({ auth_mode: "chatgpt", tokens: { account_id: account, access_token: "token" } }));++ beforeEach(() => {+ chmodSync(FAKE_CLI, 0o755);+ scratch = mkdtempSync(join(tmpdir(), "omb-codex-compact-"));+ home = join(scratch, ".codex");+ mkdirSync(home);+ mkdirSync(NATIVE_DIR, { recursive: true });+ authenticate("account-1");+ writeFileSync(join(home, "config.toml"), "model_reasoning_summary = \"none\"\n");+ log = join(scratch, "calls.ndjson");+ cli = FAKE_CLI;+ thread = 0;+ });++ afterEach(async () => {+ vi.unstubAllEnvs();+ try {+ await instance?.dispose();+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+ });++ it("compacts on the kept process with no new process, thread or handshake, and the next turn goes on in it", async () => {+ const { threadId, session, pid } = await kept();+ const before = recorder.events.length;+ await expect(compact(threadId, session)).resolves.toEqual({ ok: true, usage: null, model: MODEL });+ expect(calls("thread/compact/start")).toEqual([{ pid, method: "thread/compact/start", params: { threadId: session } }]);+ expect(recorder.events.slice(before).filter((event) => event.type === "context.compacted" || event.type === "turn.started" || event.type === "turn.completed")).toEqual([]);+ expect(alive(pid)).toBe(true);+ expect(instance.adapter.hasSession(threadId)).toBe(false);++ const second = await runTurn(threadId, "two", session);+ expect(second.done).toMatchObject({ ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });+ expect(calls("turn/start").map((call) => [call.pid, call.params.threadId])).toEqual([[pid, session], [pid, session]]);+ expect(calls("initialize").filter((call) => call.pid === pid)).toHaveLength(1);+ expect(calls("thread/start")).toHaveLength(1);+ expect(calls("thread/resume")).toHaveLength(0);+ expect(second.events.find((event) => event.type === "session.started")).toMatchObject({ sessionId: session });+ });++ it("confirms the configuration on the connection itself, after the re-read the last turn started, and before it asks to compact", async () => {+ const { threadId, session, pid } = await kept();+ await compact(threadId, session);+ const order = calls().filter((call) => call.pid === pid).map((call) => call.method);+ expect(order.slice(order.indexOf("turn/start"))).toEqual(["turn/start", "config/read", "config/read", "thread/compact/start"]);+ });++ it("serves a conversation in its own process only: a session that is not the kept one, or no kept process, sends nothing and starts nothing", async () => {+ const { threadId, session, pid } = await kept();+ const launches = () => calls("initialize").length + calls("thread/start").length;+ const before = launches();+ await expect(compact("t-nothing-kept", "codex-thread-x")).resolves.toMatchObject({ ok: false });+ expect(launches()).toBe(before);+ await expect(compact(threadId, "codex-thread-other")).resolves.toMatchObject({ ok: false });+ await expect(compact("t-another-conversation", session)).resolves.toMatchObject({ ok: false });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(launches()).toBe(before);+ expect(alive(pid)).toBe(true);+ });++ it("refuses when the account was signed into another one since the last turn, with the same configuration, sending nothing to the old process", async () => {+ const { threadId, session, pid } = await kept();+ authenticate("account-2");+ const result = await compact(threadId, session);+ expect(result).toMatchObject({ ok: false, reason: expect.stringContaining("login") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ expect(closes(threadId).at(-1)).toMatchObject({ close: expect.stringContaining("login") });+ });++ it("refuses when the account changed while its configuration was being read, before the request is sent", async () => {+ const hold = join(scratch, "config-hold");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_CONFIG_HOLD_FILE: hold });+ writeFileSync(hold, "");+ const pending = compact(threadId, session);+ await until(() => calls("config/read").filter((call) => call.pid === pid).length >= 3, "the configuration read the compaction makes");+ authenticate("account-2");+ rmSync(hold);+ expect(await pending).toMatchObject({ ok: false, reason: expect.stringContaining("login") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ });++ it("refuses when the model's provider changed while the configuration was being read, before the request is sent", async () => {+ const hold = join(scratch, "config-hold");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_CONFIG_HOLD_FILE: hold });+ writeFileSync(hold, "");+ let model = MODEL;+ const pending = compact(threadId, session, { selectionNow: () => ({ instanceId: "codex-compact-test", model }) });+ await until(() => calls("config/read").filter((call) => call.pid === pid).length >= 3, "the configuration read the compaction makes");+ model = "magpie::m1";+ rmSync(hold);+ expect(await pending).toMatchObject({ ok: false, reason: expect.stringContaining("provider") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ });++ it("refuses when the conversation moved to another engine instance with a model of the same name while the configuration was being read", async () => {+ const hold = join(scratch, "config-hold");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_CONFIG_HOLD_FILE: hold });+ writeFileSync(hold, "");+ let instanceId = "codex-compact-test";+ const pending = compact(threadId, session, { selectionNow: () => ({ instanceId, model: MODEL }) });+ await until(() => calls("config/read").filter((call) => call.pid === pid).length >= 3, "the configuration read the compaction makes");+ instanceId = "another-codex";+ rmSync(hold);+ expect(await pending).toMatchObject({ ok: false, reason: expect.stringContaining("instance") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ });++ it("holds one login across a token the CLI renewed", async () => {+ const { threadId, session } = await kept();+ writeFileSync(join(home, "auth.json"), JSON.stringify({ auth_mode: "chatgpt", tokens: { account_id: "account-1", access_token: "renewed" } }));+ await expect(compact(threadId, session)).resolves.toMatchObject({ ok: true });+ });++ it("refuses when config.toml changed since the last turn", async () => {+ const { threadId, session, pid } = await kept();+ writeFileSync(join(home, "config.toml"), "model_reasoning_summary = \"auto\"\n");+ expect(await compact(threadId, session)).toMatchObject({ ok: false, reason: expect.stringContaining("config") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ });++ it("refuses when the CLI was replaced in place since the last turn", async () => {+ cli = join(scratch, "fake-codex.ts");+ copyFileSync(FAKE_CLI, cli);+ chmodSync(cli, 0o755);+ const { threadId, session, pid } = await kept();+ appendFileSync(cli, "\n// updated in place\n");+ expect(await compact(threadId, session)).toMatchObject({ ok: false, reason: expect.stringContaining("cli") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ });++ it("refuses when the configuration the process reports now is not the one it ended its turn with", async () => {+ const rules = join(scratch, "native-rules.txt");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_INSTRUCTIONS_FILE: rules });+ writeFileSync(rules, "Native rules written after the turn.");+ expect(await compact(threadId, session)).toMatchObject({ ok: false, reason: expect.stringContaining("configuration changed") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ });++ it("treats a configuration read that fails as a check that failed, not as one that passed", async () => {+ const broken = join(scratch, "config-broken");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_CONFIG_ERROR_FILE: broken });+ writeFileSync(broken, "");+ expect(await compact(threadId, session)).toMatchObject({ ok: false, reason: expect.stringContaining("confirm") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ });++ it("refuses a model of another provider than the thread's, which the next turn would not resume", async () => {+ const { threadId, session, pid } = await kept();+ expect(await compact(threadId, session, { model: "magpie::m1" })).toMatchObject({ ok: false, reason: expect.stringContaining("provider") });+ expect(calls("thread/compact/start")).toEqual([]);+ expect(alive(pid)).toBe(false);+ const again = await runTurn(threadId, "two", session);+ expect(again.done).toMatchObject({ ok: true });+ expect(calls("thread/resume")).toHaveLength(1);+ });++ describe("a configuration read that never answers", () => {+ it.each(["deadline", "stop", "exit", "stopAll"] as const)("ends on %s with the connection closed, and the conversation's next message goes through", async (how) => {+ if (how === "deadline") vi.stubEnv("OMB_CODEX_COMPACT_TIMEOUT_MS", "300");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_CONFIG_HANG_AFTER_TURNS: "1" });+ const stop = new AbortController();+ const pending = compact(threadId, session, { signal: stop.signal });+ await until(() => instance.adapter.hasSession(threadId), "the compaction to take the thread");+ if (how === "stop") stop.abort();+ if (how === "exit") process.kill(pid, "SIGKILL");+ if (how === "stopAll") void instance.adapter.stopAll();+ await expect(pending).resolves.toMatchObject({ ok: false });+ expect(calls("thread/compact/start")).toEqual([]);+ await until(() => !alive(pid), "the connection to close");+ expect(instance.adapter.hasSession(threadId)).toBe(false);+ const next = await runTurn(threadId, "carry on", session);+ expect(next.done).toMatchObject({ ok: true });+ expect(calls("thread/resume")).toHaveLength(1);+ }, 30_000);+ });++ describe("the compaction's own configuration read never answering", () => {+ it.each(["deadline", "stop", "exit"] as const)("ends on %s with the connection closed and no request sent, and the conversation's next message goes through", async (how) => {+ if (how === "deadline") vi.stubEnv("OMB_CODEX_COMPACT_TIMEOUT_MS", "300");+ const hang = join(scratch, "config-hang");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_CONFIG_HANG_FILE: hang });+ writeFileSync(hang, "");+ const stop = new AbortController();+ const pending = compact(threadId, session, { signal: stop.signal });+ await until(() => calls("config/read").filter((call) => call.pid === pid).length >= 3, "the configuration read the compaction makes");+ if (how === "stop") stop.abort();+ if (how === "exit") process.kill(pid, "SIGKILL");+ await expect(pending).resolves.toMatchObject({ ok: false });+ expect(calls("thread/compact/start")).toEqual([]);+ await until(() => !alive(pid), "the connection to close");+ expect(instance.adapter.hasSession(threadId)).toBe(false);+ rmSync(hang);+ const next = await runTurn(threadId, "carry on", session);+ expect(next.done).toMatchObject({ ok: true });+ expect(calls("thread/resume")).toHaveLength(1);+ }, 30_000);+ });++ describe("a compaction in flight", () => {+ it("holds the thread, and is ended with its connection by stopAll", async () => {+ const { threadId, session, pid } = await kept({ FAKE_CODEX_COMPACT: "hang" });+ const pending = compact(threadId, session);+ await until(() => calls("thread/compact/start").length === 1, "the compaction request");+ expect(instance.adapter.hasSession(threadId)).toBe(true);+ expect(instance.adapter.enginePid?.(threadId)).toBe(pid);+ await instance.adapter.stopAll();+ await expect(pending).resolves.toMatchObject({ ok: false });+ expect(alive(pid)).toBe(false);+ await expect(compact(threadId, session)).resolves.toMatchObject({ ok: false });+ });++ it("is ended with its connection when the provider is removed", async () => {+ const { threadId, session, pid } = await kept({ FAKE_CODEX_COMPACT: "hang" });+ const pending = compact(threadId, session);+ await until(() => calls("thread/compact/start").length === 1, "the compaction request");+ await instance.dispose();+ await expect(pending).resolves.toMatchObject({ ok: false });+ expect(alive(pid)).toBe(false);+ await expect(compact(threadId, session)).resolves.toMatchObject({ ok: false, reason: expect.stringContaining("removed") });+ });++ it("interrupts the compaction's own turn when stopped, then closes the connection", async () => {+ const { threadId, session, pid } = await kept({ FAKE_CODEX_COMPACT: "hang" });+ const stop = new AbortController();+ const pending = compact(threadId, session, { signal: stop.signal });+ await until(() => calls("thread/compact/start").length === 1, "the compaction request");+ stop.abort();+ await expect(pending).resolves.toMatchObject({ ok: false });+ expect(calls("turn/interrupt")).toEqual([{ pid, method: "turn/interrupt", params: { threadId: session, turnId: "compact-turn-1" } }]);+ expect(alive(pid)).toBe(false);+ expect((await runTurn(threadId, "carry on", session)).done).toMatchObject({ ok: true });+ });++ it("fails at its deadline, with the connection closed", async () => {+ vi.stubEnv("OMB_CODEX_COMPACT_TIMEOUT_MS", "400");+ const { threadId, session, pid } = await kept({ FAKE_CODEX_COMPACT: "hang" });+ await expect(compact(threadId, session)).resolves.toMatchObject({ ok: false, reason: "timed out" });+ expect(alive(pid)).toBe(false);+ });++ it("fails when the process exits under it", async () => {+ const { threadId, session, pid } = await kept({ FAKE_CODEX_COMPACT: "hang" });+ const pending = compact(threadId, session);+ await until(() => calls("thread/compact/start").length === 1, "the compaction request");+ process.kill(pid, "SIGKILL");+ await expect(pending).resolves.toMatchObject({ ok: false, reason: expect.stringContaining("exited") });+ });++ it.each(["error", "unsupported"])("fails when Codex answers the request with an error (%s), and does not return the connection", async (mode) => {+ const { threadId, session, pid } = await kept({ FAKE_CODEX_COMPACT: mode });+ await expect(compact(threadId, session)).resolves.toMatchObject({ ok: false, reason: expect.stringContaining("refused") });+ expect(alive(pid)).toBe(false);+ expect(closes(threadId).at(-1)).toMatchObject({ close: expect.stringContaining("compaction not completed") });+ });+ });++ it("settles on the compaction's own turn, not on a helper thread's completion or usage", async () => {+ const hold = join(scratch, "compact-hold");+ const { threadId, session } = await kept({ FAKE_CODEX_COMPACT_HELPER: "1", FAKE_CODEX_COMPACT_HOLD_FILE: hold });+ flushNativeLog(threadId);+ rmSync(join(NATIVE_DIR, `${threadId}.ndjson`), { force: true });+ writeFileSync(hold, "");+ let finished = false;+ const pending = compact(threadId, session).then((result) => { finished = true; return result; });+ await until(() => {+ flushNativeLog(threadId);+ const file = join(NATIVE_DIR, `${threadId}.ndjson`);+ return existsSync(file) && readFileSync(file, "utf8").includes('"itemType":"marker"');+ }, "the notification the app-server sent after the helper's");+ expect(finished).toBe(false);+ rmSync(hold);+ await expect(pending).resolves.toEqual({ ok: true, usage: null, model: MODEL });+ const next = await runTurn(threadId, "two", session);+ expect(next.done).toMatchObject({ ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });+ });++ it("names a Fast turn's base model, because the compaction runs on the thread's own tier", async () => {+ await create();+ const threadId = "t-fast";+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "one", model: `${MODEL}+priority` });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ const started = recorder.events.find((event) => event.type === "session.started" && event.turnId === turnId) as { sessionId: string };+ await until(() => calls("config/read").length >= 2, "the kept process's configuration re-read");+ await expect(compact(threadId, started.sessionId, { model: `${MODEL}+priority` })).resolves.toMatchObject({ ok: true, model: MODEL });+ });++ it("keeps a custom endpoint model's +suffix whole: only a service tier a turn applied is the base model's", async () => {+ const model = "vendor/model+preview";+ await create({}, { endpoint: { url: "http://127.0.0.1:1/v1", models: [model] } });+ const threadId = "t-suffix";+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "one", model });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ const started = recorder.events.find((event) => event.type === "session.started" && event.turnId === turnId) as { sessionId: string };+ await until(() => calls("config/read").length >= 2, "the kept process's configuration re-read");+ await expect(compact(threadId, started.sessionId, { model })).resolves.toMatchObject({ ok: true, model });+ });++ it("names the model the kept process last ran, not the one selected since", async () => {+ const { threadId, session } = await kept();+ await expect(compact(threadId, session, { model: "gpt-another-model" })).resolves.toMatchObject({ ok: true, model: MODEL });+ });++ it("returns the usage Codex reported for the compaction, and the next turn counts from there", async () => {+ const { threadId, session } = await kept({ FAKE_CODEX_COMPACT_USAGE: JSON.stringify({ inputTokens: 50, outputTokens: 5, cachedInputTokens: 20 }) });+ await expect(compact(threadId, session)).resolves.toEqual({ ok: true, usage: { input: 50, output: 5, cachedInput: 20 }, model: MODEL });+ const next = await runTurn(threadId, "two", session);+ expect(next.done).toMatchObject({ ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });+ });++ it("returns no usage, and leaves the next turn's count alone, when Codex sends no usage notification at all", async () => {+ const { threadId, session } = await kept({ FAKE_CODEX_COMPACT_NO_USAGE: "1" });+ await expect(compact(threadId, session)).resolves.toEqual({ ok: true, usage: null, model: MODEL });+ const next = await runTurn(threadId, "two", session);+ expect(next.done).toMatchObject({ ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });+ });++ it("returns the connection to a pool that closes it with the rest when the provider is removed", async () => {+ const { threadId, session, pid } = await kept();+ await compact(threadId, session);+ expect(alive(pid)).toBe(true);+ await instance.dispose();+ expect(alive(pid)).toBe(false);+ });+});diff --git a/server/drivers/codex-compact.ts b/server/drivers/codex-compact.tsnew file mode 100644index 0000000000..e7011398dc--- /dev/null+++ b/server/drivers/codex-compact.ts@@ -0,0 +1,154 @@+import type { EngineCompactResult } from "../contracts.ts";+import { codexConfigDigest, codexOutsideIdentity, type CodexConnection, type CodexLease, type CodexTurnLink, type KeptCodex, type codexWarmSessions } from "./codex-warm.ts";+import { appendNative } from "./native.ts";++const DEFAULT_TIMEOUT_MS = 120_000;+const timeoutMs = (): number => Number(process.env.OMB_CODEX_COMPACT_TIMEOUT_MS) > 0 ? Number(process.env.OMB_CODEX_COMPACT_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS;+const graceMs = (): number => Math.max(1, Number(process.env.FAKE_CODEX_INTERRUPT_GRACE_MS ?? 750) || 750);+const sleep = (ms: number) => new Promise<void>((wake) => { const timer = setTimeout(wake, ms); timer.unref?.(); });++class Ended extends Error {+ readonly stopped: boolean;+ constructor(why: string, stopped = false) {+ super(why);+ this.stopped = stopped;+ }+}++class Refused extends Error {}++interface ActiveCompaction {+ stop: () => Promise<boolean>;+ turnId: string;+ asks: Map<string, unknown>;+ pid?: number;+}++export interface CodexCompactDeps<Carried> {+ instanceId: string;+ warm: ReturnType<typeof codexWarmSessions<Carried>>;+ active: Map<string, ActiveCompaction>;+ turnId: () => string;+ refusal: () => string | null;+ providerOf: (model: string | null | undefined) => string | null;+}++function changedOutside<Carried>(session: KeptCodex<Carried>): string | null {+ let was: Record<string, unknown>;+ try { was = JSON.parse(session.contract); } catch { return "contract"; }+ const now = codexOutsideIdentity(session.identity);+ return (["config", "cli", "login"] as const).find((field) => was[field] !== now[field]) ?? null;+}++/** The engine's own compaction of a thread on the app-server a completed turn left running, in place: `thread/compact/start`+ * (codex-cli 0.171.0: the request returns `{}` at once, then the thread runs a turn of its own with a `contextCompaction` item+ * that reports no token usage). Nothing here starts a process: with no kept one on this session, or any doubt that the next+ * turn would resume it, the compaction does not run. */+export function codexCompactSession<Carried>(deps: CodexCompactDeps<Carried>) {+ return async (threadId: string, options: { session: string; model?: string | null; selectionNow?: () => { instanceId: string; model: string | null } | undefined; signal?: AbortSignal }): Promise<EngineCompactResult> => {+ const fail = (reason: string): EngineCompactResult => ({ ok: false, reason });+ const refusal = deps.refusal();+ if (refusal) return fail(refusal);+ if (deps.active.has(threadId)) return fail("a turn is running on this thread");+ if (options.signal?.aborted) return fail("stopped");++ let end!: (error: Ended) => void;+ const ended = new Promise<never>((_, reject) => { end = reject; });+ ended.catch(() => undefined);+ const race = <T>(pending: Promise<T>): Promise<T> => Promise.race([pending, ended]);+ const timer = setTimeout(() => end(new Ended("timed out")), timeoutMs());+ timer.unref?.();+ const onAbort = () => end(new Ended("stopped", true));+ options.signal?.addEventListener("abort", onAbort, { once: true });++ let lease: CodexLease<Carried> | null = null;+ let registered: ActiveCompaction | undefined;+ let exited: (() => void) | undefined, attached: CodexConnection | undefined;+ let finished!: () => void;+ const done = new Promise<void>((resolve) => { finished = resolve; });+ const turn = { id: null as string | null, requested: false, compacted: false };+ let completed!: (status: string) => void, started!: () => void;+ const completion = new Promise<string>((resolve) => { completed = resolve; });+ const turnStarted = new Promise<void>((resolve) => { started = resolve; });+ try {+ lease = deps.warm.lend(threadId, options.session);+ if (!lease) throw new Refused("no kept Codex process holds this session");+ const { session } = lease;+ const { connection } = session;+ const nativeThreadId = session.nativeThreadId;+ const baseline = connection.usageTotal ?? { input: 0, output: 0, cachedInput: 0 };+ registered = { stop: async () => { end(new Ended("stopped", true)); await done; return true; }, turnId: deps.turnId(), asks: new Map(), pid: connection.child.pid };+ deps.active.set(threadId, registered);++ const link: CodexTurnLink = {+ message(message) {+ if (connection.absorb(message)) return;+ const params = message?.params ?? {};+ if (params.threadId !== nativeThreadId) return;+ appendNative(threadId, { dir: "in", source: "codex.app-server", msg: { method: message.method, ...(params.item?.type ? { itemType: params.item.type } : {}) } });+ if (message.method === "turn/started" && turn.requested && !turn.id) {+ turn.id = params.turn?.id ?? null;+ started();+ } else if (message.method === "item/completed" && turn.id && params.turnId === turn.id && params.item?.type === "contextCompaction") turn.compacted = true;+ else if (message.method === "turn/completed" && turn.id && params.turn?.id === turn.id) completed(String(params.turn.status));+ },+ error: (error) => end(new Ended(`codex failed during compaction: ${error.message}`)),+ close: (code, signal) => end(new Ended(`codex exited (${code ?? signal}) during compaction`)),+ };+ connection.attach(link);+ exited = () => end(new Ended("codex exited during compaction"));+ attached = connection;+ connection.child.once("exit", exited);++ await race(lease.settled);+ const changed = changedOutside(session);+ if (changed) throw new Refused(`the Codex ${changed} changed since its last turn`);+ if (session.provider !== deps.providerOf(options.model)) throw new Refused("the model's provider changed since its last turn");+ const read = await race(connection.ask("config/read", { cwd: session.cwd, includeLayers: false })) as { config?: unknown } | undefined;+ if (read?.config === undefined) throw new Refused("Codex could not confirm its configuration");+ if (codexConfigDigest(read.config) !== session.configDigest) throw new Refused("the Codex configuration changed since its last turn");++ const changedWhileReading = changedOutside(session);+ if (changedWhileReading) throw new Refused(`the Codex ${changedWhileReading} changed since its last turn`);+ if (options.selectionNow) {+ const now = options.selectionNow();+ if (now?.instanceId !== deps.instanceId || session.provider !== deps.providerOf(now.model)) throw new Refused("the instance or the model's provider changed while the configuration was being read");+ }+ if (lease.invalidated) throw new Refused("the Codex process was closed before the compaction");+ turn.requested = true;+ appendNative(threadId, { dir: "out", source: "codex.app-server", msg: { method: "thread/compact/start", params: { threadId: nativeThreadId } } });+ if (await race(connection.ask("thread/compact/start", { threadId: nativeThreadId })) === undefined) throw new Refused("Codex refused the compaction request");+ const status = await race(completion);+ if (status !== "completed" || !turn.compacted) throw new Refused(`the compaction turn ended ${status === "completed" ? "without compacting" : status}`);+ if (lease.invalidated) throw new Refused("the Codex process was closed during compaction");++ const now = connection.usageTotal ?? baseline;+ const usage = { input: Math.max(0, now.input - baseline.input), output: Math.max(0, now.output - baseline.output), cachedInput: Math.max(0, now.cachedInput - baseline.cachedInput) };+ connection.detach();+ await lease.release();+ lease = null;+ return { ok: true, usage: usage.input || usage.output || usage.cachedInput ? usage : null, model: session.model };+ } catch (error) {+ const reason = error instanceof Ended || error instanceof Refused ? error.message : `compaction failed: ${(error as Error).message}`;+ if (lease) {+ const connection = lease.session.connection;+ if (error instanceof Ended && error.stopped && turn.requested && connection.alive) {+ if (!turn.id) await Promise.race([turnStarted, sleep(graceMs())]);+ if (turn.id) {+ await Promise.race([connection.ask("turn/interrupt", { threadId: lease.session.nativeThreadId, turnId: turn.id }), sleep(graceMs())]);+ await Promise.race([completion, sleep(graceMs())]);+ }+ }+ lease.session.connection.detach();+ await lease.discard(`compaction not completed: ${reason}`);+ }+ return fail(reason);+ } finally {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", onAbort);+ if (exited) attached?.child.removeListener("exit", exited);+ if (registered && deps.active.get(threadId) === registered) deps.active.delete(threadId);+ finished();+ }+ };+}diff --git a/server/drivers/codex-warm.test.ts b/server/drivers/codex-warm.test.tsindex 8659f4335e..230f031f48 100644--- a/server/drivers/codex-warm.test.ts+++ b/server/drivers/codex-warm.test.ts@@ -1,10 +1,13 @@import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import { once } from "node:events";import { createInterface } from "node:readline";import { afterEach, describe, expect, it, vi } from "vitest";import * as procs from "../procs.ts";-import { CodexConnection, codexConfigDigest, codexContractDiff, codexLoginIdentity, codexSpawnContract, codexWarmSessions, type KeptCodex } from "./codex-warm.ts";+import { CodexConnection, codexConfigDigest, codexContractDiff, codexIdentityInputs, codexLoginIdentity, codexOutsideIdentity, codexOwnLogin, codexSpawnContract, codexWarmSessions, type KeptCodex } from "./codex-warm.ts";import { armedIdleCount, sessionIdlePolicy } from "./session-idle.ts";const children: ChildProcessWithoutNullStreams[] = [];@@ -15,7 +18,7 @@ const idleChild = () => {return child;};const session = (overrides: Partial<KeptCodex<null>> = {}): KeptCodex<null> => ({- connection: new CodexConnection(idleChild()), contract: "{}", nativeThreadId: "native-1", configDigest: "config", cwd: "/work", carried: null, ...overrides,+ connection: new CodexConnection(idleChild()), contract: "{}", nativeThreadId: "native-1", configDigest: "config", cwd: "/work", identity: { cli: "codex-not-installed", env: { PATH: "/nowhere", CODEX_HOME: "/nowhere" }, ownLogin: false }, provider: null, model: null, carried: null, ...overrides,});const contract = (overrides: Partial<Parameters<typeof codexSpawnContract>[0]> = {}) => codexSpawnContract({cli: "codex-not-installed", args: ["app-server", "-c", "model=\"a\""], env: { PATH: "/nowhere", CODEX_HOME: "/nowhere", TOKEN: "first-secret" }, cwd: "/work", box: {}, thread: { model: "a" }, login: null, ...overrides,@@ -46,6 +49,26 @@ describe("a Codex app-server's launch contract", () => {expect(before).not.toContain("model=");});+ it("computes what can change outside OpenMausBot, config.toml, the CLI and the login, exactly as the contract does", () => {+ const home = mkdtempSync(join(tmpdir(), "omb-identity-"));+ const write = (account: string) => writeFileSync(join(home, "auth.json"), JSON.stringify({ auth_mode: "chatgpt", tokens: { account_id: account, access_token: "t" } }));+ writeFileSync(join(home, "config.toml"), "model = \"a\"\n");+ write("account-1");+ const env = { PATH: "/nowhere", CODEX_HOME: home, SECRET: "not part of it" };+ const made = (login: string | null) => JSON.parse(codexSpawnContract({ cli: "codex-not-installed", args: [], env, cwd: "/work", box: {}, thread: {}, login }));+ const inputs = codexIdentityInputs("codex-not-installed", env, true);+ expect(inputs.env).toEqual({ CODEX_HOME: home, HOME: undefined, USERPROFILE: undefined, PATH: "/nowhere" });+ const before = codexOutsideIdentity(inputs);+ expect(before).toEqual({ config: made(codexOwnLogin(true, env)).config, cli: made(null).cli, login: made(codexOwnLogin(true, env)).login });+ expect(before.login).not.toBeNull();+ write("account-2");+ expect(codexOutsideIdentity(inputs)).toEqual({ ...before, login: codexOwnLogin(true, env) });+ expect(codexOutsideIdentity(inputs).login).not.toBe(before.login);+ writeFileSync(join(home, "config.toml"), "model = \"b\"\n");+ expect(codexOutsideIdentity(inputs).config).not.toBe(before.config);+ expect(codexOutsideIdentity(codexIdentityInputs("codex-not-installed", env, false)).login).toBeNull();+ });+it("holds one login across a renewed token, and tells accounts and sign-in kinds apart", () => {const login = (tokens: Record<string, string>, extra: Record<string, unknown> = {}) => JSON.stringify({ auth_mode: "chatgpt", tokens, last_refresh: tokens.access_token, ...extra });const first = codexLoginIdentity(login({ account_id: "account-1", access_token: "one" }));@@ -139,3 +162,196 @@ describe("kept Codex app-servers", () => {vi.unstubAllEnvs();});});++describe("a kept app-server lent for work of its own", () => {+ const answeringChild = () => {+ const child = spawn(process.execPath, ["-e", `let held = null; process.stdin.on("data", (chunk) => { for (const line of String(chunk).split("\\n").filter(Boolean)) { const message = JSON.parse(line);+ if (message.method === "config/read") held = message.id; else if (message.release && held !== null) process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: held, result: { config: { reread: true } } }) + "\\n"); } }); setInterval(() => {}, 1000);`], { stdio: ["pipe", "pipe", "pipe"] });+ children.push(child);+ return child;+ };++ it("leaves the pool while lent, keeps no idle timer, and goes back with a new one", async () => {+ const warm = codexWarmSessions<null>("lend-a");+ const armedBefore = armedIdleCount();+ const kept = session();+ warm.keep("thread-1", kept);+ expect(armedIdleCount()).toBe(armedBefore + 1);+ expect(warm.lend("thread-2", "native-1")).toBeNull();+ expect(warm.lend("thread-1", "native-other")).toBeNull();+ expect(warm.has("thread-1")).toBe(true);+ const lease = warm.lend("thread-1", "native-1")!;+ expect(lease.session).toBe(kept);+ expect(warm.has("thread-1")).toBe(false);+ expect(armedIdleCount()).toBe(armedBefore);+ expect(warm.take("thread-1", "{}", "native-1")).toBeNull();+ expect(warm.keep("thread-1", session())).toBe(false);+ await lease.release();+ expect(warm.has("thread-1")).toBe(true);+ expect(armedIdleCount()).toBe(armedBefore + 1);+ expect(kept.connection.alive).toBe(true);+ expect(warm.take("thread-1", "{}", "native-1")).toBe(kept);+ expect(armedIdleCount()).toBe(armedBefore);+ });++ it("lends nothing that is not alive", async () => {+ const warm = codexWarmSessions<null>("lend-b");+ const dying = session();+ warm.keep("thread-1", dying);+ const exited = once(dying.connection.child, "exit");+ dying.connection.child.kill("SIGKILL");+ await exited;+ expect(warm.lend("thread-1", "native-1")).toBeNull();+ });++ it("settles once the configuration re-read after the last turn has landed", async () => {+ const warm = codexWarmSessions<null>("lend-c");+ const kept = session({ connection: new CodexConnection(answeringChild()), configDigest: "from the turn" });+ warm.keep("thread-1", kept);+ const lease = warm.lend("thread-1", "native-1")!;+ let settled = false;+ void lease.settled.then(() => { settled = true; });+ await Promise.resolve();+ expect(settled).toBe(false);+ expect(kept.configDigest).toBe("from the turn");+ kept.connection.write({ release: true });+ await lease.settled;+ expect(kept.configDigest).toBe(codexConfigDigest({ reread: true }));+ await lease.release();+ await warm.closeAll("test");+ });++ it("is ended by closeAll while lent, and is not put back afterwards", async () => {+ const warm = codexWarmSessions<null>("lend-d");+ const armedBefore = armedIdleCount();+ const kept = session();+ warm.keep("thread-1", kept);+ const lease = warm.lend("thread-1", "native-1")!;+ await warm.closeAll("signed out");+ expect(lease.invalidated).toBe(true);+ expect(kept.connection.alive).toBe(false);+ await lease.release();+ expect(warm.has("thread-1")).toBe(false);+ expect(armedIdleCount()).toBe(armedBefore);+ });++ it("refuses a new loan while closeAll is closing", async () => {+ const warm = codexWarmSessions<null>("lend-e");+ const lent = session(), other = session();+ warm.keep("thread-1", lent);+ warm.keep("thread-2", other);+ const lease = warm.lend("thread-1", "native-1")!;+ const closing = warm.closeAll("signed out");+ expect(warm.lend("thread-2", "native-1")).toBeNull();+ await closing;+ expect(lease.invalidated).toBe(true);+ expect(other.connection.alive).toBe(false);+ });++ it("makes a discard wait until the tree is gone, retrying a kill that did not take, while retired() waits only for the first attempt", async () => {+ vi.stubEnv("FAKE_CODEX_STOP_RETRY_MS", "300");+ let kills = 0;+ vi.spyOn(procs, "killCliTree").mockImplementation(async (child) => {+ if (++kills === 1) return false;+ const exited = once(child, "exit");+ child.kill("SIGKILL");+ await exited;+ return true;+ });+ const warm = codexWarmSessions<null>("lend-g");+ const stubborn = session();+ warm.keep("thread-1", stubborn);+ const lease = warm.lend("thread-1", "native-1")!;+ let discarded = false;+ const discarding = lease.discard("test").then(() => { discarded = true; });+ await warm.retired();+ expect(discarded).toBe(false);+ expect(kills).toBe(1);+ await discarding;+ expect(kills).toBe(2);+ expect(stubborn.connection.alive).toBe(false);+ vi.unstubAllEnvs();+ });++ describe("a lent process whose first kill did not take", () => {+ const stubbornKill = () => {+ const state = { kills: 0 };+ vi.stubEnv("FAKE_CODEX_STOP_RETRY_MS", "300");+ vi.spyOn(procs, "killCliTree").mockImplementation(async (child) => {+ if (++state.kills === 1) return false;+ const exited = once(child, "exit");+ child.kill("SIGKILL");+ await exited;+ return true;+ });+ return state;+ };++ it("is waited for by closeAll while it is lent, but only for its first attempt by retired()", async () => {+ const state = stubbornKill();+ const warm = codexWarmSessions<null>("lend-i");+ const lent = session();+ warm.keep("thread-1", lent);+ warm.lend("thread-1", "native-1");+ let closed = false;+ const closing = warm.closeAll("signed out").then(() => { closed = true; });+ await warm.retired();+ expect(closed).toBe(false);+ expect(state.kills).toBe(1);+ await closing;+ expect(state.kills).toBe(2);+ expect(lent.connection.alive).toBe(false);+ vi.unstubAllEnvs();+ });++ it("is waited for by closeAll while a discard is already retrying, and killed once more only", async () => {+ const state = stubbornKill();+ const warm = codexWarmSessions<null>("lend-j");+ const lent = session();+ warm.keep("thread-1", lent);+ const lease = warm.lend("thread-1", "native-1")!;+ const discarding = lease.discard("test");+ await warm.retired();+ expect(state.kills).toBe(1);+ await warm.closeAll("signed out");+ expect(lent.connection.alive).toBe(false);+ expect(state.kills).toBe(2);+ await discarding;+ vi.unstubAllEnvs();+ });+ });++ it("does not retry a kill that did not take when an idle close or closeAll ends a process, as before", async () => {+ vi.stubEnv("FAKE_CODEX_STOP_RETRY_MS", "1");+ let kills = 0;+ vi.spyOn(procs, "killCliTree").mockImplementation(async () => { kills++; return false; });+ const warm = codexWarmSessions<null>("lend-h");+ const idle = session(), other = session();+ warm.keep("thread-1", idle);+ warm.keep("thread-2", other);+ await warm.close("thread-1", "idle");+ await warm.closeAll("test");+ await warm.retired();+ expect(kills).toBe(2);+ vi.unstubAllEnvs();+ });++ it("goes back to nowhere when its process exited meanwhile, and discard ends the process", async () => {+ const warm = codexWarmSessions<null>("lend-f");+ const gone = session(), thrown = session();+ warm.keep("thread-1", gone);+ warm.keep("thread-2", thrown);+ const first = warm.lend("thread-1", "native-1")!;+ const exited = once(gone.connection.child, "exit");+ gone.connection.child.kill("SIGKILL");+ await exited;+ await first.release();+ expect(warm.has("thread-1")).toBe(false);+ const second = warm.lend("thread-2", "native-1")!;+ await second.discard("test");+ expect(thrown.connection.alive).toBe(false);+ expect(warm.has("thread-2")).toBe(false);+ await second.release();+ expect(warm.has("thread-2")).toBe(false);+ });+});diff --git a/server/drivers/codex-warm.ts b/server/drivers/codex-warm.tsindex 98c8e1e545..37bbc3304f 100644--- a/server/drivers/codex-warm.ts+++ b/server/drivers/codex-warm.ts@@ -6,6 +6,8 @@ import { join } from "node:path";import { findCliCandidates } from "../env-path.ts";import { captureCliTree, killCliTree } from "../procs.ts";+import { keepStopping } from "./codex-process.ts";+import { storedCodexLogin } from "./codex-login.ts";import { appendNative } from "./native.ts";import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose } from "./session-idle.ts";@@ -118,19 +120,21 @@ export class CodexConnection {this.asked.delete(message.id);answer(message.result);} else if (this.link) this.link.message(message);- else this.unattended(message);+ else this.absorb(message);}}- /** No turn is running: a request from the app-server is refused, and only the token total is kept. */- private unattended(message: any): void {+ /** For a message no turn answers for: a request from the app-server is refused, and the token total of this connection's thread+ * is kept. True when the message was one of those. */+ absorb(message: any): boolean {if (message?.id !== undefined && message.method) {this.write({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "No OpenMausBot turn is running on this thread." } });- return;+ return true;}const total = message?.method === "thread/tokenUsage/updated" && message.params?.threadId === this.nativeThreadId? message.params.tokenUsage?.total : null;if (total) this.usageTotal = { input: total.inputTokens ?? 0, output: total.outputTokens ?? 0, cachedInput: total.cachedInputTokens ?? 0 };+ return Boolean(total);}}@@ -159,6 +163,31 @@ function cliIdentity(cli: string, path: string | undefined): string {}}+export interface CodexIdentityInputs {+ cli: string;+ env: { CODEX_HOME?: string; HOME?: string; USERPROFILE?: string; PATH?: string };+ ownLogin: boolean;+}++export const codexIdentityInputs = (cli: string, env: Record<string, string | undefined>, ownLogin: boolean): CodexIdentityInputs => ({+ cli, ownLogin, env: { CODEX_HOME: env.CODEX_HOME, HOME: env.HOME, USERPROFILE: env.USERPROFILE, PATH: env.PATH },+});++function configFileDigest(env: CodexIdentityInputs["env"]): string | null {+ try {+ return digest(readFileSync(join(env.CODEX_HOME || join(env.HOME || env.USERPROFILE || homedir(), ".codex"), "config.toml"), "utf8"));+ } catch {+ return null;+ }+}++export const codexOwnLogin = (ownLogin: boolean, env: CodexIdentityInputs["env"]): string | null =>+ codexLoginIdentity(ownLogin ? storedCodexLogin(env) : null);++export function codexOutsideIdentity(inputs: CodexIdentityInputs): { config: string | null; cli: string; login: string | null } {+ return { config: configFileDigest(inputs.env), cli: cliIdentity(inputs.cli, inputs.env.PATH), login: codexOwnLogin(inputs.ownLogin, inputs.env) };+}+/** Everything an app-server is given when it starts and when its thread starts. A kept process serves a later turn only* when all of it is unchanged. Values are hashed: arguments and environment carry credentials. */export function codexSpawnContract(parts: {@@ -170,12 +199,8 @@ export function codexSpawnContract(parts: {thread: unknown;login: string | null;}): string {- let config: string | null = null;- try {- config = digest(readFileSync(join(parts.env.CODEX_HOME || join(parts.env.HOME || parts.env.USERPROFILE || homedir(), ".codex"), "config.toml"), "utf8"));- } catch {}return JSON.stringify({- config,+ config: configFileDigest(parts.env),cli: cliIdentity(parts.cli, parts.env.PATH),args: digest(parts.args),cwd: parts.cwd,@@ -218,9 +243,20 @@ export interface KeptCodex<Carried> {* their MCP servers some time after it starts, so what it reports at start is not what it reports later. */configDigest: string;cwd: string;+ identity: CodexIdentityInputs;+ provider: string | null;+ model: string | null;carried: Carried;}+export interface CodexLease<Carried> {+ readonly session: KeptCodex<Carried>;+ readonly settled: Promise<void>;+ readonly invalidated: boolean;+ release(): Promise<void>;+ discard(why: string): Promise<void>;+}+/** `OMB_CODEX_SESSION_KEEP=0` ends every app-server with its turn. */const keepEnabled = (): boolean => process.env.OMB_CODEX_SESSION_KEEP !== "0";@@ -231,8 +267,13 @@ const keepEnabled = (): boolean => process.env.OMB_CODEX_SESSION_KEEP !== "0";*/export function codexWarmSessions<Carried>(instanceId: string) {const policy = sessionIdlePolicy("CODEX");- const kept = new Map<string, { session: KeptCodex<Carried>; idleTimer: ReturnType<typeof setTimeout> }>();- const stopping = new Set<Promise<boolean>>();+ interface Entry { session: KeptCodex<Carried>; idleTimer: ReturnType<typeof setTimeout>; reread: Promise<void> }+ const kept = new Map<string, Entry>();+ interface Loan { session: KeptCodex<Carried>; invalidated: boolean; ending?: Promise<void> }+ const lent = new Map<string, Loan>();+ const stopping = new Set<Promise<unknown>>();+ const lentEndings = new Set<Promise<void>>();+ let closing = 0;const idleKey = (threadId: string) => `${instanceId}\0${threadId}`;const forget = (threadId: string, why: string, contractChanged?: string[]) => {@@ -245,46 +286,73 @@ export function codexWarmSessions<Carried>(instanceId: string) {};/** Ends the whole tree: an app-server's MCP servers and shells can outlive it. */- const end = async (session: KeptCodex<Carried>): Promise<void> => {+ const end = async (session: KeptCodex<Carried>): Promise<boolean> => {const stopped = killCliTree(session.connection.child);stopping.add(stopped);try {- await stopped;+ return await stopped;} finally {stopping.delete(stopped);}};+ /** A lent process's one full ending, shared by whoever ends it: the first attempt, then retries while it is not gone. */+ const endLoan = (loan: Loan): Promise<void> => {+ if (loan.ending) return loan.ending;+ const ending = (async () => {+ if (!await end(loan.session)) await keepStopping(() => killCliTree(loan.session.connection.child), () => true);+ })();+ loan.ending = ending;+ lentEndings.add(ending);+ void ending.finally(() => lentEndings.delete(ending));+ return ending;+ };+const close = async (threadId: string, why: string, contractChanged?: string[]): Promise<void> => {+ const loan = lent.get(threadId);+ if (loan) {+ if (!loan.invalidated) {+ loan.invalidated = true;+ appendNative(threadId, { dir: "out", source: "codex.session", msg: { close: why } });+ }+ await endLoan(loan);+ }const session = forget(threadId, why, contractChanged);if (session) await end(session);};+ const place = (threadId: string, session: KeptCodex<Carried>, reread: Promise<void>): void => {+ const { connection } = session;+ connection.detach();+ connection.nativeThreadId = session.nativeThreadId;+ const entry: Entry = {+ session,+ reread,+ idleTimer: armIdleClose(idleKey(threadId), engineIdleMs(threadId, policy), {+ close: () => void close(threadId, "idle"),+ idle: () => kept.get(threadId)?.session === session,+ threadId,+ policy,+ }),+ };+ kept.set(threadId, entry);+ connection.exitedIdle = () => {+ if (kept.get(threadId) === entry && forget(threadId, "exited while idle")) void end(session);+ };+ };+return {/** Keeps a process whose turn completed. False when it is not kept: the caller ends it. */keep(threadId: string, session: KeptCodex<Carried>): boolean {const { connection } = session;captureCliTree(connection.child);- if (!keepEnabled() || !connection.alive || kept.has(threadId)) return false;+ if (!keepEnabled() || !connection.alive || kept.has(threadId) || lent.has(threadId)) return false;connection.detach();- connection.nativeThreadId = session.nativeThreadId;- void connection.ask("config/read", { cwd: session.cwd, includeLayers: false }).then((result) => {+ const reread = connection.ask("config/read", { cwd: session.cwd, includeLayers: false }).then((result) => {const config = (result as { config?: unknown } | undefined)?.config;if (config !== undefined) session.configDigest = codexConfigDigest(config);});- const entry = {- session,- idleTimer: armIdleClose(idleKey(threadId), engineIdleMs(threadId, policy), {- close: () => void close(threadId, "idle"),- idle: () => kept.get(threadId)?.session === session,- threadId,- policy,- }),- };- kept.set(threadId, entry);- connection.exitedIdle = () => {- if (kept.get(threadId) === entry && forget(threadId, "exited while idle")) void end(session);- };+ place(threadId, session, reread);return true;},@@ -304,15 +372,52 @@ export function codexWarmSessions<Carried>(instanceId: string) {return null;},+ lend(threadId: string, nativeThreadId: string): CodexLease<Carried> | null {+ const entry = kept.get(threadId);+ if (!entry || closing > 0 || !entry.session.connection.alive || entry.session.nativeThreadId !== nativeThreadId) return null;+ kept.delete(threadId);+ stopIdleClose(idleKey(threadId), entry.idleTimer);+ const { session } = entry;+ const loan = { session, invalidated: false };+ lent.set(threadId, loan);+ const give = () => { if (lent.get(threadId) === loan) lent.delete(threadId); };+ return {+ session,+ settled: entry.reread,+ get invalidated() { return loan.invalidated; },+ async release() {+ give();+ if (loan.invalidated) return;+ if (!keepEnabled() || !session.connection.alive || kept.has(threadId) || closing > 0) {+ await end(session);+ return;+ }+ place(threadId, session, Promise.resolve());+ },+ async discard(why) {+ give();+ loan.invalidated = true;+ appendNative(threadId, { dir: "out", source: "codex.session", msg: { close: why } });+ await endLoan(loan);+ },+ };+ },+close,- /** Every kept process being ended has exited, so a new one may load its native thread. */+ /** The first termination attempt of every ending has settled, so a new process may load a native thread. A lent+ * process's retries are not waited for here: `closeAll` and the lease's `discard` wait for those. */async retired(): Promise<void> {await Promise.all(stopping);},async closeAll(why: string): Promise<void> {- await Promise.all([...[...kept.keys()].map((threadId) => close(threadId, why)), ...stopping]);+ closing++;+ try {+ await Promise.all([...[...new Set([...kept.keys(), ...lent.keys()])].map((threadId) => close(threadId, why)), ...stopping, ...lentEndings]);+ } finally {+ closing--;+ }},has: (threadId: string): boolean => kept.has(threadId),diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 129ef7217a..1cfd1dbc1a 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -42,7 +42,7 @@ import type {TextGenerationOptions,} from "../contracts.ts";import { newEventId, newId } from "../contracts.ts";-import { codexSelectedProviderArgs, decodeCodexSelection, OFFICIAL_CODEX_PROVIDER, readCodexModelCatalog, STATIC_CODEX_MODELS } from "./codex-catalog.ts";+import { codexSelectedProviderArgs, codexThreadSelection, decodeCodexSelection, OFFICIAL_CODEX_PROVIDER, readCodexModelCatalog, STATIC_CODEX_MODELS } from "./codex-catalog.ts";import { codexBackgroundProviderArgs, codexBackgroundRoute, runCodexBackgroundRoute, runCodexOneShot } from "./codex-background-text.ts";import { augmentedPath } from "../env-path.ts";import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts";@@ -57,7 +57,7 @@ import { codexAccountEmail, codexHome } from "./codex-identity.ts";import { keepChatsOutOfCodexHistory, linkSharedCodexHome } from "./codex-shared-home.ts";import { mcpAppApprovalForm, mcpAppApprovalText, mcpElicitationDeclined, plainRecord } from "./codex-app-approval.ts";import { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, codexProviderMismatch, CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, CodexRpcError, codexSignInExpired, codexPlanModelRefused, codexPlanUnsupportedInput, codexSignInRefused, codexUserError, codexUserFailure, missingNativeCodexThread, type CodexRoute } from "./codex-errors.ts";-import { codexLoginCheck, readCodexLogin, storedCodexLogin } from "./codex-login.ts";+import { codexTierOf } from "./codex-tier.ts"; import { codexLoginCheck, readCodexLogin, storedCodexLogin } from "./codex-login.ts";import { keyRejected, noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";import { extractMcpImages } from "../mcp-tool-images.ts"; import { codexImageInputs, withoutInlineImages } from "./codex-images.ts";@@ -65,7 +65,7 @@ import { parseProtocolAskQuestions, questionChoices } from "../../shared/ask-queimport { codexQuestionReply, openAsyncQuestion, type CodexAsk } from "./codex-questions.ts";import { codexReleaseUpdate, codexUpdateCommand } from "./codex-update.ts";export { codexUpdateCommand };-import { customApprovalParams, namedApprovalParams, permissionProfileUnsupported, withResolvedSandbox, type CodexApprovalParams } from "./codex-approval-config.ts"; import { CodexConnection, codexConfigDigest, codexContractDiff, codexLoginIdentity, codexSpawnContract, codexWarmSessions } from "./codex-warm.ts"; import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts"; import { COMPUTER_PROXY_TIMEOUT_MS } from "../harness-budget.ts";+import { customApprovalParams, namedApprovalParams, permissionProfileUnsupported, withResolvedSandbox, type CodexApprovalParams } from "./codex-approval-config.ts"; import { CodexConnection, codexConfigDigest, codexContractDiff, codexIdentityInputs, codexOwnLogin, codexSpawnContract, codexWarmSessions, type CodexIdentityInputs } from "./codex-warm.ts"; import { codexCompactSession } from "./codex-compact.ts"; import { AGENTS_TOOL_TIMEOUT_SECONDS } from "./agents-tool-limit.ts"; import { COMPUTER_PROXY_TIMEOUT_MS } from "../harness-budget.ts";import { canUseMcpServer } from "../../shared/tool-scope.ts";import { assertToolScopeSupported } from "../../shared/tool-scope-support.ts";import { appMountFor, gateServer, mcpStdioServer } from "../mcp-gate-config.ts"; import { OWN_APPS_SERVER } from "../../shared/own-apps.ts";@@ -544,7 +544,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const commandCwd = permissionLaunchCwd(turn.cwd ?? homedir());// A plan login reaches its process through this turn's token or bridge, which end with the turn.const contract = plan ? null : codexSpawnContract({ cli: config.cli, args: appServerArgs, env, cwd: turn.cwd ?? homedir(), box: customBox,- login: codexLoginIdentity(ownLogin ? storedCodexLogin(env) : null), thread: { model: turn.model ?? null, approvalMode, ...selectionConfig } });+ login: codexOwnLogin(ownLogin, env), thread: { model: turn.model ?? null, approvalMode, ...selectionConfig } });const reused = contract && attempt === 0 ? warm.take(threadId, contract, typeof turn.resumeCursor === "string" ? turn.resumeCursor : null) : null;const releaseSlot = reused ? () => {} : tryCodexLaunchSlot() ?? await waitForLaunchSlot(attempt);if (!releaseSlot) return;@@ -561,7 +561,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {let startingNativeTurn = false;const earlyNotifications: any[] = [];const mcpStartup = reused ? null : mcpStartupTracker(child);- let mcpFailed = false, keepable: { configDigest: string; cwd: string; carried: { initialized: any; approvalParams: CodexApprovalParams; rolloutPath: unknown } } | null = null;+ let mcpFailed = false, keepable: { configDigest: string; cwd: string; identity: CodexIdentityInputs; provider: string | null; model: string | null; carried: { initialized: any; approvalParams: CodexApprovalParams; rolloutPath: unknown } } | null = null;const state = {settled: false,lastError: "",@@ -1250,11 +1250,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {// Codex's `never` means "do not ask to escalate", not "grant every requested permission":// only Full may synthesize approvals.autoAcceptPermissions = approvalMode === "full";- const selection: { model?: string | null; modelProvider: string | null; serviceTier?: string } = routed- ? { model: turn.model, modelProvider: routedProvider }- : config.authMode === "chatgpt-plan"- ? { model: turn.model, modelProvider: "openai_chatgpt_plan" }- : decodeCodexSelection(turn.model);+ const selection = codexThreadSelection({ routedProvider: routed ? routedProvider : undefined, plan }, turn.model);const cursor = !droppedUnsupportedSession && typeof turn.resumeCursor === "string" ? turn.resumeCursor : null;let startedModel: string | null = null;// The plan refused the dropped session before anything ran, so replaying the chat repeats no side effects.@@ -1351,7 +1347,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {];const startTurn = () => {promptSubmitted = true;- startingNativeTurn = true; keepable = { configDigest, cwd: turn.cwd ?? homedir(), carried: { initialized, approvalParams, rolloutPath: rolloutAt?.path } };+ startingNativeTurn = true; keepable = { configDigest, cwd: turn.cwd ?? homedir(), identity: codexIdentityInputs(config.cli, env, ownLogin), provider: selection.modelProvider, model: turn.model && selection.serviceTier ? codexTierOf(turn.model)?.model ?? turn.model : turn.model ?? null, carried: { initialized, approvalParams, rolloutPath: rolloutAt?.path } };return request("turn/start", {threadId: codexThreadId,input: turnInput,@@ -1556,6 +1552,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {strictResume: true, nativeCompaction: true,},sendTurn,+ compactSession: codexCompactSession({ instanceId, warm, active, turnId: newId, providerOf: (model) => codexThreadSelection({ routedProvider: routed ? routedProvider : undefined, plan }, model).modelProvider,+ refusal: () => disposed ? "this provider was removed" : planSigningOut ? "this account is being disconnected" : null }),interruptTurn: async (threadId) => {await active.get(threadId)?.stop();},diff --git a/server/drivers/idle-engine-cap.test.ts b/server/drivers/idle-engine-cap.test.tsindex e623e256ad..f5512c6459 100644--- a/server/drivers/idle-engine-cap.test.ts+++ b/server/drivers/idle-engine-cap.test.ts@@ -73,7 +73,7 @@ it("keeps the two most recently used of five idle engines across Claude and Codeconst codex = codexWarmSessions<null>(`cap-codex-${randomUUID()}`);const codexThreads = [randomUUID(), randomUUID()];const kept = codexThreads.map((threadId) => {- const session = { connection: codexProcess(), contract: "{}", nativeThreadId: `native-${threadId}`, configDigest: "config", cwd: "/work", carried: null };+ const session = { connection: codexProcess(), contract: "{}", nativeThreadId: `native-${threadId}`, configDigest: "config", cwd: "/work", identity: { cli: "codex", env: {}, ownLogin: false }, provider: null, model: null, carried: null };expect(codex.keep(threadId, session)).toBe(true);return session;});diff --git a/server/engine-homes/engine-homes.test.ts b/server/engine-homes/engine-homes.test.tsindex 42c04fb72d..7c13128488 100644--- a/server/engine-homes/engine-homes.test.ts+++ b/server/engine-homes/engine-homes.test.ts@@ -77,6 +77,25 @@ describe("engine homes at run time", () => {expect(seen).toEqual([expect.stringMatching(/^member-[0-9a-f]{16}$/), "team", expect.stringMatching(/^member-[0-9a-f]{16}$/)]);expect(seen[2]).not.toBe(seen[0]);});++ it("wrap an engine's in-place compaction in its conversation, and leave an engine without one without", async () => {+ const homes = new EngineHomes();+ homes.start(setup());+ const seen: Array<string | null> = [];+ const asked: unknown[] = [];+ const instance = withEngineHomes({ adapter: {+ sendTurn: async () => ({ turnId: "x" }),+ compactSession: async (_threadId: string, options: unknown) => { asked.push(options); seen.push(homes.scope()); return { ok: true, usage: null, model: null }; },+ } } as unknown as ProviderInstance, homes);+ const options = { session: "native-1", model: "m", botId: "b1" };+ await expect(instance.adapter.compactSession!("t-bob", options)).resolves.toEqual({ ok: true, usage: null, model: null });+ await instance.adapter.compactSession!("t-owner", { session: "native-2" });+ expect(asked[0]).toBe(options);+ expect(seen).toEqual([expect.stringMatching(/^member-[0-9a-f]{16}$/), expect.stringMatching(/^member-[0-9a-f]{16}$/)]);+ expect(seen[1]).not.toBe(seen[0]);+ const without = withEngineHomes({ adapter: { sendTurn: async () => ({ turnId: "x" }) } } as unknown as ProviderInstance, homes);+ expect(without.adapter.compactSession).toBeUndefined();+ });});posix("a bot's engine spawned on a Team Cloud", () => {diff --git a/server/engine-homes/engine-homes.ts b/server/engine-homes/engine-homes.tsindex 7a8ff52452..968b0b5034 100644--- a/server/engine-homes/engine-homes.ts+++ b/server/engine-homes/engine-homes.ts@@ -114,6 +114,7 @@ export function withEngineHomes(instance: ProviderInstance, homes: EngineHomes =(instance as { adapter: ProviderInstance["adapter"] }).adapter = {...adapter,sendTurn: (input) => homes.within(input.threadId, () => adapter.sendTurn(input), input.botId),+ ...(adapter.compactSession ? { compactSession: (threadId, options) => homes.within(threadId, () => adapter.compactSession!(threadId, options), options.botId) } : {}),...(adapter.prestart ? { prestart: { ...adapter.prestart, start: (input) => homes.within(input.threadId, () => adapter.prestart!.start(input), input.botId) } } : {}),...(warm ? { cacheKeepWarm: {...warm,diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.tsindex 9220815ffe..3f11a1464c 100755--- a/server/testing/fake-codex-app-server.ts+++ b/server/testing/fake-codex-app-server.ts@@ -66,6 +66,21 @@// FAKE_CODEX_MCP_READY_MS each `-c mcp_servers.*` mount is reported starting after the thread/start or// thread/resume reply and ready at once, as codex-cli 0.166.0 does; with this, ready only this many ms// later, and the dump records mcpReadyAtTurnStart+// FAKE_CODEX_CALL_LOG append {pid, method, params} per request, across every process launched+// FAKE_CODEX_THREAD_IDS "distinct": thread/start names its thread codex-thread-<pid>-<n>, not always codex-thread-1+// FAKE_CODEX_CONTEXT_TOKENS the context reading (last.inputTokens) turns report, 7 by default: one number, or one per finished turn+// separated by commas (the last repeats);+// FAKE_CODEX_CONTEXT_TOKENS_AFTER_COMPACT the reading once a thread/compact/start has completed+// FAKE_CODEX_COMPACT thread/compact/start: unset (compacts, as codex-cli 0.171.0 does: the request returns {}, then the thread+// runs a turn with a contextCompaction item and reports no usage) | error | unsupported (method not found) | hang (the turn+// never completes; turn/interrupt for its turn ends it); FAKE_CODEX_COMPACT_MS how long the turn takes (default 20);+// FAKE_CODEX_COMPACT_HELPER "1": a helper thread's turn/completed and token usage arrive during it;+// FAKE_CODEX_COMPACT_USAGE JSON {inputTokens, outputTokens, cachedInputTokens} added to the thread's total by it+// FAKE_CODEX_CONFIG_HANG_AFTER_TURNS config/read is never answered once this many turns have finished+// FAKE_CODEX_COMPACT_HOLD_FILE a compaction that starts while this file exists completes once it is removed+// FAKE_CODEX_COMPACT_NO_USAGE "1": the compaction sends no thread/tokenUsage/updated at all+// FAKE_CODEX_CONFIG_HOLD_FILE a config/read that arrives while this file exists is answered once it is removed+// FAKE_CODEX_CONFIG_HANG_FILE, FAKE_CODEX_CONFIG_ERROR_FILE config/read is never answered / answered with an error while the file exists// FAKE_CODEX_ROLLOUT rollout path thread/start and thread/resume report as `thread.path`; each happy turn appends a// namespace-less function_call for retry_thread and codex's "unsupported call: retry_thread" output to itimport { spawn } from "node:child_process";@@ -226,6 +241,16 @@ let nativeThreadId = "codex-thread-1";let nativeTurnId = "turn-1";let turnsStarted = 0;let turnsFinished = 0;+let threadsStarted = 0;+let compactions = 0;+/** What compactions added to the thread's token total: it is cumulative, so every later turn's total carries it. */+const compactedUsage = { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 };+let compactingTurn: string | null = null;+const startedThreadId = () => {+ threadsStarted += 1;+ if (process.env.FAKE_CODEX_THREAD_IDS === "distinct") nativeThreadId = `codex-thread-${process.pid}-${threadsStarted}`;+ return nativeThreadId;+};const notify = (method: string, params: any) => out({jsonrpc: "2.0", method,params: {@@ -386,6 +411,15 @@ const dump = () => {}};+/** The context reading each turn reports: FAKE_CODEX_CONTEXT_TOKENS names one per finished turn (the last repeats), and+ * FAKE_CODEX_CONTEXT_TOKENS_AFTER_COMPACT replaces them once a thread was compacted. */+const contextReading = (): number => {+ const afterCompact = Number(process.env.FAKE_CODEX_CONTEXT_TOKENS_AFTER_COMPACT);+ if (compactions > 0 && afterCompact > 0) return afterCompact;+ const schedule = (process.env.FAKE_CODEX_CONTEXT_TOKENS ?? "").split(",").map(Number).filter((n) => n > 0);+ return schedule[Math.min(turnsFinished, schedule.length) - 1] ?? 7;+};+const finishTurn = () => {if (process.env.FAKE_CODEX_COMPACTION === "1") {notify("item/started", { item: { id: "c1", type: "contextCompaction" } });@@ -420,8 +454,8 @@ const finishTurn = () => {notify("item/completed", { item: { id: "m1", type: "agentMessage", text: "done from fake codex" } });const carried = process.env.FAKE_CODEX_RESTORED_USAGE ? { inputTokens: 100, cachedInputTokens: 50, outputTokens: 10 } : { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 };notify("thread/tokenUsage/updated", { tokenUsage: {- total: { inputTokens: carried.inputTokens + 7 * ++turnsFinished, cachedInputTokens: carried.cachedInputTokens + 4 * turnsFinished, outputTokens: carried.outputTokens + 3 * turnsFinished },- last: { inputTokens: 7, cachedInputTokens: 4, outputTokens: 3 },+ total: { inputTokens: carried.inputTokens + 7 * ++turnsFinished + compactedUsage.inputTokens, cachedInputTokens: carried.cachedInputTokens + 4 * turnsFinished + compactedUsage.cachedInputTokens, outputTokens: carried.outputTokens + 3 * turnsFinished + compactedUsage.outputTokens },+ last: { inputTokens: contextReading(), cachedInputTokens: 4, outputTokens: 3 },modelContextWindow: 272000,} });if (process.env.FAKE_CODEX_ROLLOUT) {@@ -539,7 +573,12 @@ process.stdin.on("data", (chunk) => {continue;}- if (msg.method) calls.push({ method: msg.method, params: msg.params ?? null });+ if (msg.method && !msg.released) calls.push({ method: msg.method, params: msg.params ?? null });+ if (msg.method && !msg.released && process.env.FAKE_CODEX_CALL_LOG) {+ const entry = `${JSON.stringify({ pid: process.pid, method: msg.method, params: msg.params ?? null })}\n`;+ const log = () => appendFileSync(process.env.FAKE_CODEX_CALL_LOG!, entry);+ if (msg.method === "config/read") setImmediate(log); else log();+ }switch (msg.method) {case "initialize": {@@ -614,6 +653,21 @@ process.stdin.on("data", (chunk) => {break;case "config/read":logStartup("config/read");+ if (process.env.FAKE_CODEX_CONFIG_HOLD_FILE && existsSync(process.env.FAKE_CODEX_CONFIG_HOLD_FILE) && !msg.released) {+ const held = process.env.FAKE_CODEX_CONFIG_HOLD_FILE;+ const timer = setInterval(() => {+ if (existsSync(held)) return;+ clearInterval(timer);+ process.stdin.emit("data", `${JSON.stringify({ ...msg, released: true })}\n`);+ }, 5);+ break;+ }+ if ((process.env.FAKE_CODEX_CONFIG_HANG_FILE && existsSync(process.env.FAKE_CODEX_CONFIG_HANG_FILE))+ || (process.env.FAKE_CODEX_CONFIG_HANG_AFTER_TURNS && turnsFinished >= Number(process.env.FAKE_CODEX_CONFIG_HANG_AFTER_TURNS))) break;+ if (process.env.FAKE_CODEX_CONFIG_ERROR_FILE && existsSync(process.env.FAKE_CODEX_CONFIG_ERROR_FILE)) {+ out({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "config unavailable" } });+ break;+ }if (mode === "config-read-error") {dump();out({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "config unavailable" } });@@ -708,8 +762,56 @@ process.stdin.on("data", (chunk) => {streamTurn += 1;if (process.env.FAKE_CODEX_INTERRUPT_SILENT) break;out({ jsonrpc: "2.0", id: msg.id, result: {} });+ if (compactingTurn && msg.params?.turnId === compactingTurn) {+ notify("turn/completed", { turn: { id: compactingTurn, status: "interrupted" } });+ compactingTurn = null;+ break;+ }notify("turn/completed", { turn: { status: "interrupted" } });break;+ case "thread/compact/start": {+ dump();+ nativeThreadId = msg.params?.threadId ?? nativeThreadId;+ const compact = process.env.FAKE_CODEX_COMPACT;+ if (compact === "unsupported" || compact === "error") {+ out({ jsonrpc: "2.0", id: msg.id, error: compact === "unsupported" ? { code: -32601, message: "method not found" } : { code: -32000, message: "compaction failed" } });+ break;+ }+ out({ jsonrpc: "2.0", id: msg.id, result: {} });+ const turnId = `compact-turn-${++compactions}`;+ notify("turn/started", { turn: { id: turnId, status: "inProgress" } });+ notify("item/started", { turnId, item: { id: "compaction-1", type: "contextCompaction" } });+ if (process.env.FAKE_CODEX_COMPACT_HELPER === "1") {+ notify("thread/tokenUsage/updated", { threadId: "helper-thread", turnId: "helper-turn", tokenUsage: { total: { inputTokens: 999, outputTokens: 999 } } });+ notify("turn/completed", { threadId: "helper-thread", turn: { id: "helper-turn", status: "completed" } });+ notify("item/started", { turnId, item: { id: "after-helper", type: "marker" } });+ }+ if (compact === "hang") {+ compactingTurn = turnId;+ break;+ }+ const finishCompaction = () => {+ const added = process.env.FAKE_CODEX_COMPACT_USAGE ? JSON.parse(process.env.FAKE_CODEX_COMPACT_USAGE) : {};+ for (const key of Object.keys(compactedUsage) as Array<keyof typeof compactedUsage>) compactedUsage[key] += added[key] ?? 0;+ const carried = process.env.FAKE_CODEX_RESTORED_USAGE ? { inputTokens: 100, cachedInputTokens: 50, outputTokens: 10 } : { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 };+ notify("item/completed", { turnId, item: { id: "compaction-1", type: "contextCompaction" } });+ if (process.env.FAKE_CODEX_COMPACT_NO_USAGE !== "1") notify("thread/tokenUsage/updated", { turnId, tokenUsage: {+ total: { inputTokens: carried.inputTokens + 7 * turnsFinished + compactedUsage.inputTokens, cachedInputTokens: carried.cachedInputTokens + 4 * turnsFinished + compactedUsage.cachedInputTokens, outputTokens: carried.outputTokens + 3 * turnsFinished + compactedUsage.outputTokens },+ last: { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0 },+ modelContextWindow: 272000,+ } });+ notify("turn/completed", { turn: { id: turnId, status: "completed" } });+ };+ const held = process.env.FAKE_CODEX_COMPACT_HOLD_FILE;+ if (held && existsSync(held)) {+ const timer = setInterval(() => {+ if (existsSync(held)) return;+ clearInterval(timer);+ finishCompaction();+ }, 5);+ } else setTimeout(finishCompaction, Number(process.env.FAKE_CODEX_COMPACT_MS) || 20);+ break;+ }case "thread/start":dump();developerInstructions = msg.params?.developerInstructions ?? "";@@ -723,10 +825,10 @@ process.stdin.on("data", (chunk) => {out({ jsonrpc: "2.0", id: msg.id, error: { code: -32602, message: "experimental API required for permissions" } });} else if (process.env.FAKE_CODEX_MCP_START === "1") {// Codex starts MCP servers with the thread; one that fails leaves the thread without its tools.- const reply = { jsonrpc: "2.0", id: msg.id, result: { thread: { id: "codex-thread-1" }, model: "fake-codex-model", sandbox: resolvedSandbox(msg.params ?? {}) } };+ const reply = { jsonrpc: "2.0", id: msg.id, result: { thread: { id: startedThreadId() }, model: "fake-codex-model", sandbox: resolvedSandbox(msg.params ?? {}) } };void startMcpServers().then((startup) => { mcpStartup = startup; dump(); threadReply(reply); });} else {- threadReply({ jsonrpc: "2.0", id: msg.id, result: { thread: { id: "codex-thread-1", ...(process.env.FAKE_CODEX_ROLLOUT ? { path: process.env.FAKE_CODEX_ROLLOUT } : {}) }, model: "fake-codex-model", sandbox: resolvedSandbox(msg.params ?? {}) } });+ threadReply({ jsonrpc: "2.0", id: msg.id, result: { thread: { id: startedThreadId(), ...(process.env.FAKE_CODEX_ROLLOUT ? { path: process.env.FAKE_CODEX_ROLLOUT } : {}) }, model: "fake-codex-model", sandbox: resolvedSandbox(msg.params ?? {}) } });}break;case "turn/start": {