Skip to content

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

Perf: warm Codex turns, Claude pre-start, checkpoint read-ahead, lighter thread reads and bot creation (#6616)

Milind Soni1b10f047b179
diff --git a/docs/headless-cli.md b/docs/headless-cli.md
index 2d5f8a5ba2..d35246b35d 100644
--- a/docs/headless-cli.md
+++ b/docs/headless-cli.md
@@ -325,7 +325,9 @@ events; `--job ID` follows every conversation of that job as it grows, and
connection it resumes from where it was; the server's first line says whether
it could (`"resumed": false` means read the state again). A refusal (an
expired token, a missing scope) ends it with exit 5 instead. The output is
-always JSON lines; `--jsonl` is accepted and changes nothing.
+always JSON lines; `--jsonl` is accepted and changes nothing. A tool step's
+output longer than 1,000 characters arrives as its first 1,000 with
+`"clipped": true` on the tool, as conversation pages carry it.
## engine
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.ts
index 0cd6f0d5a1..5bfaa33bbd 100644
--- a/scripts/testing/file-size-ratchet.test.ts
+++ b/scripts/testing/file-size-ratchet.test.ts
@@ -16,7 +16,7 @@ const HARD_CAP = 2000;
const LISTED_FROM = 1000;
const LINES: Record<string, number> = {
- "server/index.ts": 15394,
+ "server/index.ts": 15385,
"src/state/store.tsx": 3288,
"electron/main.mjs": 3124,
"server/store.ts": 2265,
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index ba5d32ea9d..694a4e88cf 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_COMPANION_DIR",
+ "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_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/bot-folder.ts b/server/bot-folder.ts
index f89ed66bc6..92a4227abd 100644
--- a/server/bot-folder.ts
+++ b/server/bot-folder.ts
@@ -23,10 +23,11 @@ export function soulHash(soul: string): string {
return createHash("sha256").update(soul, "utf8").digest("hex");
}
-/** Private modes: standing instructions can describe a person's work in detail. */
-export function writeSoulMirror(botId: string, soul: string): void {
+/** Private modes: standing instructions can describe a person's work in detail. `durable: false` skips the disk sync for
+ * a mirror of text that is already saved with the bot: a power loss can then leave the file empty, which reads as drift. */
+export function writeSoulMirror(botId: string, soul: string, durable = true): void {
mkdirSync(botFolder(botId), { recursive: true, mode: 0o700 });
- writeFileAtomic(soulFile(botId), soul, { mode: 0o600 });
+ writeFileAtomic(soulFile(botId), soul, { mode: 0o600, durable });
}
export type SoulDrift = { drift: false } | { drift: true; fileText: string };
diff --git a/server/checkpoints-perf.test.ts b/server/checkpoints-perf.test.ts
index 0ed7dfb888..9ab216ca94 100644
--- a/server/checkpoints-perf.test.ts
+++ b/server/checkpoints-perf.test.ts
@@ -1,22 +1,25 @@
// Real git does the work; execFile is wrapped only to record calls and inject a timeout or object counts, readdirSync only to record calls.
import { createHash } from "node:crypto";
import { execFile as realExecFile, execFileSync } from "node:child_process";
-import { existsSync, mkdirSync, mkdtempSync, realpathSync, renameSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, utimesSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
// Shadow repos live under DATA_DIR, which server/testing/setup.ts points at a
// disposable test home before any test module imports config.ts.
-import { CHECKPOINTS_DIR, diffWorkingTree, release, snapshot } from "./checkpoints.ts";
+import { CHECKPOINTS_DIR, FAILURES_BEFORE_OFF, diffWorkingTree, prime, quiet, release, snapshot } from "./checkpoints.ts";
+import { checkpointGitSlots } from "./job-slots.ts";
import { removeTempDir } from "./testing/cleanup.ts";
import { hostTimeout } from "./testing/host-timeout.ts";
-type Injected = { error: Error; stdout?: string; stderr?: string } | { stdout: string };
+type Injected = { error: Error; stdout?: string; stderr?: string } | { stdout: string } | { until: Promise<Error | void> };
const hooks = vi.hoisted(() => ({
calls: [] as string[][],
inject: null as null | ((args: string[]) => Injected | undefined),
readdirSync: [] as string[],
+ running: 0,
+ mostRunning: 0,
}));
vi.mock("node:fs", async (importOriginal) => {
@@ -34,12 +37,32 @@ vi.mock("node:child_process", async (importOriginal) => {
if (file === "git") {
hooks.calls.push(args);
const injected = hooks.inject?.(args);
+ if (injected && "until" in injected) {
+ // Held like a slow git: it runs once `until` settles (or fails with what it settles to), or ends as Node ends a child whose signal fired.
+ const signal = (options as { signal?: AbortSignal }).signal;
+ let over = false;
+ const end = (error: Error | null) => {
+ if (over) return;
+ over = true;
+ if (error) callback(error, "", "");
+ else actual.execFile(file, args, options, callback);
+ };
+ signal?.addEventListener("abort", () => end(Object.assign(new Error("The operation was aborted"), { name: "AbortError", code: "ABORT_ERR" })), { once: true });
+ void injected.until.then((failure) => end(failure ?? null));
+ return {};
+ }
if (injected) {
setImmediate(() => callback("error" in injected ? injected.error : null, injected.stdout ?? "", "stderr" in injected ? injected.stderr ?? "" : ""));
return {};
}
}
- return actual.execFile(file, args, options, callback);
+ if (file !== "git") return actual.execFile(file, args, options, callback);
+ hooks.running += 1;
+ hooks.mostRunning = Math.max(hooks.mostRunning, hooks.running);
+ return actual.execFile(file, args, options, (...rest: unknown[]) => {
+ hooks.running -= 1;
+ callback(...rest);
+ });
};
return { ...actual, execFile };
});
@@ -144,17 +167,113 @@ describe("incremental shadow index", () => {
const { bot, cwd } = workspace();
writeFileSync(join(cwd, "a.txt"), "one");
await snapshot(bot, cwd, "first");
+ await drain(bot, cwd);
writeFileSync(join(cwd, "a.txt"), "two");
hooks.calls = [];
const changed = await snapshot(bot, cwd, "changed", undefined, { pin: "dispatch-1" });
expect(changed).toMatch(/^[0-9a-f]{40}$/);
- expect(subcommands()).toEqual(["ls-files", "log", "ls-files", "ls-files", "add", "write-tree", "commit-tree", "update-ref", "count-objects"]);
+ // The four reads start together; the pin goes on the old HEAD beside the add, then moves with HEAD.
+ expect(subcommands()).toEqual(["ls-files", "log", "ls-files", "ls-files", "update-ref", "add", "write-tree", "commit-tree", "update-ref"]);
expect(shadowGit(bot, cwd, "rev-parse", "HEAD").trim()).toBe(changed);
expect(shadowGit(bot, cwd, "for-each-ref", "--format=%(objectname)", "refs/omb-live/").trim()).toBe(changed);
+ // The loose-object count is taken behind the snapshot, not inside it.
+ await drain(bot, cwd);
+ expect(subcommands().slice(9)).toEqual(["count-objects", "update-ref"]);
+ await release(bot, cwd, "dispatch-1");
+ });
+
+ it("takes an unchanged folder's snapshot in two rounds of git calls, without writing the tree again", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ // Git reads a file again while it is as new as the index itself, and rewrites the index for it: this one is older.
+ const earlier = new Date(Date.now() - 60_000);
+ utimesSync(join(cwd, "a.txt"), earlier, earlier);
+ const first = await snapshot(bot, cwd, "first");
+ await drain(bot, cwd);
hooks.calls = [];
- expect(await snapshot(bot, cwd, "unchanged")).toBe(changed);
+ expect(await snapshot(bot, cwd, "unchanged", undefined, { pin: "dispatch-2" })).toBe(first);
+ expect(subcommands()).toEqual(["ls-files", "log", "ls-files", "ls-files", "update-ref", "add"]);
+ expect(shadowGit(bot, cwd, "for-each-ref", "--format=%(objectname)", "refs/omb-live/").trim()).toBe(first);
+ await drain(bot, cwd);
+ expect(subcommands()).not.toContain("count-objects");
+ // An edit made outside the app between two turns is in the next snapshot.
+ writeFileSync(join(cwd, "a.txt"), "edited outside the app");
+ hooks.calls = [];
+ const edited = await snapshot(bot, cwd, "edited", undefined, { pin: "dispatch-3" });
+ expect(edited).not.toBe(first);
+ expect(subcommands()).toContain("write-tree");
+ expect(shadowGit(bot, cwd, "show", `${edited}:a.txt`)).toBe("edited outside the app");
+ // The earlier turn's pin still holds its own commit.
+ expect(shadowGit(bot, cwd, "for-each-ref", "--format=%(objectname)", "refs/omb-live/").trim().split("\n").sort()).toEqual([first, edited].sort());
+ await release(bot, cwd, "dispatch-2");
+ await release(bot, cwd, "dispatch-3");
+ });
+
+ it("reads a folder ahead of a turn with the same reads and one add, and writes no ref", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ const first = await snapshot(bot, cwd, "first");
+ await drain(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "two");
+ hooks.calls = [];
+ expect(await prime(bot, cwd)).toBe(true);
expect(subcommands()).toEqual(["ls-files", "log", "ls-files", "ls-files", "add", "write-tree"]);
- await release(bot, cwd, "dispatch-1");
+ expect(shadowGit(bot, cwd, "rev-parse", "HEAD").trim()).toBe(first);
+ // A failure while reading ahead turns nothing off: the turn's own snapshot still runs.
+ hooks.inject = args => args[0] === "add" ? { error: new Error("Command failed: git add"), stderr: "fatal: unable to stat" } : undefined;
+ expect(await prime(bot, cwd)).toBe(false);
+ hooks.inject = null;
+ hooks.calls = [];
+ expect(await snapshot(bot, cwd, "the turn")).not.toBe(first);
+ expect(subcommands()).toContain("add");
+ });
+
+ it("gives up on a folder too big to read ahead in a turn's time, so no turn waits that long again", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ hooks.inject = args => args[0] === "add" ? { error: timeoutError("add") } : undefined;
+ expect(await prime(bot, cwd)).toBe(false);
+ hooks.inject = null;
+ expect(warn).toHaveBeenCalledTimes(1);
+ hooks.calls = [];
+ expect(await snapshot(bot, cwd, "the turn")).toBeNull();
+ expect(await prime(bot, cwd)).toBe(false);
+ expect(hooks.calls).toEqual([]);
+ // Stopped by its caller is not a timeout: nothing is turned off.
+ const other = workspace();
+ writeFileSync(join(other.cwd, "a.txt"), "one");
+ const stop = new AbortController();
+ stop.abort();
+ expect(await prime(other.bot, other.cwd, stop.signal)).toBe(false);
+ expect(await snapshot(other.bot, other.cwd, "the turn")).toMatch(/^[0-9a-f]{40}$/);
+ });
+
+ it("keeps every git it starts, for turns and for reading ahead alike, within the checkpoint git limit", async () => {
+ const folders = Array.from({ length: 6 }, () => {
+ const one = workspace();
+ for (let n = 0; n < 20; n += 1) writeFileSync(join(one.cwd, `file${n}.txt`), `file ${n}`);
+ return one;
+ });
+ hooks.mostRunning = 0;
+ const results = await Promise.all(folders.map(({ bot, cwd }, at) => at % 2 ? prime(bot, cwd) : snapshot(bot, cwd, "turn", undefined, { pin: `dispatch-${at}` })));
+ expect(results.every(Boolean)).toBe(true);
+ await Promise.all(folders.map(({ bot, cwd }) => snapshot(bot, cwd, "again")));
+ expect(hooks.mostRunning).toBeGreaterThan(1);
+ expect(hooks.mostRunning).toBeLessThanOrEqual(checkpointGitSlots.limit);
+ for (const [at, { bot, cwd }] of folders.entries()) if (at % 2 === 0) await release(bot, cwd, `dispatch-${at}`);
+ });
+
+ it("leaves no pin behind when the folder cannot be staged", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ const first = await snapshot(bot, cwd, "first");
+ hooks.inject = args => args[0] === "add" ? { error: new Error("Command failed: git add"), stderr: "fatal: unable to stat" } : undefined;
+ expect(await snapshot(bot, cwd, "cannot stage", undefined, { pin: "dispatch-4" })).toBeNull();
+ hooks.inject = null;
+ await drain(bot, cwd);
+ expect(shadowGit(bot, cwd, "for-each-ref", "--format=%(objectname)", "refs/omb-live/").trim()).toBe("");
+ expect(await snapshot(bot, cwd, "later")).toBe(first);
});
it("falls back to a full rebuild when the index cannot be listed", async () => {
@@ -232,6 +351,7 @@ describe("incremental shadow index", () => {
writeFileSync(join(cwd, "a.txt"), "two");
hooks.calls = [];
const before = await snapshot(bot, cwd, "collection due");
+ await drain(bot, cwd);
hooks.inject = null;
expect(subcommands()).not.toContain("gc");
// the turn writes a file; its settled diff must not queue behind GC
@@ -245,7 +365,7 @@ describe("incremental shadow index", () => {
expect(snapshotHashes(bot, cwd)).toEqual([before]);
});
- it("runs a collection left by a turn without a diff ahead of the next snapshot, once", async () => {
+ it("holds a collection left by a turn without a diff for the next turn's settled diff, never ahead of its snapshot", async () => {
const { bot, cwd } = workspace();
writeFileSync(join(cwd, "a.txt"), "one");
await snapshot(bot, cwd, "first");
@@ -258,17 +378,96 @@ describe("incremental shadow index", () => {
hooks.calls = [];
writeFileSync(join(cwd, "a.txt"), "three");
const next = await snapshot(bot, cwd, "next turn");
- const collected = subcommands().indexOf("gc");
- expect(collected).toBeGreaterThanOrEqual(0);
- expect(subcommands().indexOf("reflog")).toBeLessThan(collected);
- expect(subcommands().indexOf("add")).toBeGreaterThan(collected);
+ await drain(bot, cwd);
+ expect(subcommands()).not.toContain("gc");
writeFileSync(join(cwd, "b.txt"), "made by the turn");
expect(await diffWorkingTree(bot, cwd, next!)).toEqual({ changed: [], added: ["b.txt"], deleted: [] });
await drain(bot, cwd);
expect(subcommands().filter(command => command === "gc")).toHaveLength(1);
+ expect(subcommands().indexOf("gc")).toBeGreaterThan(hooks.calls.findIndex(args => args[0] === "diff"));
expect(snapshotHashes(bot, cwd)).toEqual([next]);
});
+ it("runs the collection of a turn that ended without a diff once its pin is released", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ await snapshot(bot, cwd, "first");
+ hooks.inject = args => args[0] === "count-objects" ? { stdout: countObjects({ count: 7000 }) } : undefined;
+ writeFileSync(join(cwd, "a.txt"), "two");
+ const stopped = await snapshot(bot, cwd, "stopped during setup", undefined, { pin: "dispatch-5" });
+ await drain(bot, cwd);
+ hooks.inject = null;
+ expect(subcommands()).not.toContain("gc");
+ await release(bot, cwd, "dispatch-5");
+ await drain(bot, cwd);
+ expect(subcommands().filter(command => command === "gc")).toHaveLength(1);
+ expect(snapshotHashes(bot, cwd)).toEqual([stopped]);
+ });
+
+ it.skipIf(process.platform === "win32")("stops a running collection for a new turn's snapshot, and runs it again behind that turn", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ await snapshot(bot, cwd, "first");
+ let collections = 0;
+ hooks.inject = (args) => {
+ if (args[0] === "count-objects") return collections === 0 ? { stdout: countObjects({ count: 7000 }) } : undefined;
+ // The first collection never ends by itself.
+ if (args[0] === "gc") return (collections += 1) === 1 ? { until: new Promise(() => {}) } : undefined;
+ return undefined;
+ };
+ writeFileSync(join(cwd, "a.txt"), "two");
+ const before = await snapshot(bot, cwd, "collection due", undefined, { pin: "dispatch-6" });
+ expect(await diffWorkingTree(bot, cwd, before!)).toEqual({ changed: [], added: [], deleted: [] });
+ void release(bot, cwd, "dispatch-6");
+ await vi.waitFor(() => expect(collections).toBe(1));
+ // The next message arrives while that collection runs: its snapshot and its digest wait for neither it nor a new one.
+ writeFileSync(join(cwd, "a.txt"), "three");
+ hooks.calls = [];
+ const next = await snapshot(bot, cwd, "next turn", undefined, { pin: "dispatch-7" });
+ expect(next).toMatch(/^[0-9a-f]{40}$/);
+ expect(subcommands()).not.toContain("gc");
+ expect(commitExists(bot, cwd, next!)).toBe(true);
+ writeFileSync(join(cwd, "b.txt"), "made by the turn");
+ expect(await diffWorkingTree(bot, cwd, next!)).toEqual({ changed: [], added: ["b.txt"], deleted: [] });
+ expect(subcommands()).not.toContain("gc");
+ await release(bot, cwd, "dispatch-7");
+ await drain(bot, cwd);
+ expect(collections).toBe(2);
+ expect(snapshotHashes(bot, cwd)).toEqual([next]);
+ expect(commitExists(bot, cwd, before!)).toBe(false);
+ });
+
+ it("keeps a running turn's pin when a digest is cut off while the folder's cache directories are listed again", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "before A");
+ const hashA = await snapshot(bot, cwd, "turn A", undefined, { pin: "dispatch-A" });
+ await drain(bot, cwd);
+ mkdirSync(join(cwd, "cache"));
+ writeFileSync(join(cwd, "cache", "CACHEDIR.TAG"), "Signature: 8a477f597d28d172789f06886806bc55\n");
+ writeFileSync(join(cwd, "cache", "blob.bin"), "cached");
+ let scans = 0;
+ hooks.inject = args => args[0] === "ls-files" && args.includes("**/CACHEDIR.TAG") && (scans += 1) === 2 ? { until: new Promise(() => {}) } : undefined;
+ const cutOff = new AbortController();
+ const digest = diffWorkingTree(bot, cwd, hashA!, cutOff.signal);
+ await vi.waitFor(() => expect(scans).toBe(2));
+ cutOff.abort();
+ expect(await digest).toBeNull();
+ // A sibling turn starts in the folder, and a collection runs behind it.
+ hooks.inject = args => args[0] === "count-objects" ? { stdout: countObjects({ count: 7000 }) } : undefined;
+ writeFileSync(join(cwd, "a.txt"), "A edited");
+ const hashB = await snapshot(bot, cwd, "turn B", undefined, { pin: "dispatch-B" });
+ await drain(bot, cwd);
+ hooks.inject = null;
+ expect(await diffWorkingTree(bot, cwd, hashB!)).toEqual({ changed: [], added: [], deleted: [] });
+ await release(bot, cwd, "dispatch-B");
+ await drain(bot, cwd);
+ expect(subcommands()).toContain("gc");
+ expect(commitExists(bot, cwd, hashA!)).toBe(true);
+ expect(shadowGit(bot, cwd, "ls-tree", "-r", "--name-only", hashB!).trim()).toBe("a.txt");
+ expect(await diffWorkingTree(bot, cwd, hashA!)).toEqual({ changed: ["a.txt"], added: [], deleted: [] });
+ await release(bot, cwd, "dispatch-A");
+ });
+
it("keeps a pinned commit through a collection and reclaims it once released", async () => {
const { bot, cwd } = workspace();
const collectionDue = () => {
@@ -281,6 +480,7 @@ describe("incremental shadow index", () => {
collectionDue();
hooks.calls = [];
const hashB = await snapshot(bot, cwd, "turn B", undefined, { pin: "dispatch-B" });
+ await drain(bot, cwd);
hooks.inject = null;
expect(await diffWorkingTree(bot, cwd, hashA!)).toEqual({ changed: ["a.txt"], added: [], deleted: [] });
await release(bot, cwd, "dispatch-A");
@@ -292,6 +492,7 @@ describe("incremental shadow index", () => {
collectionDue();
hooks.calls = [];
const hashC = await snapshot(bot, cwd, "turn C");
+ await drain(bot, cwd);
hooks.inject = null;
await diffWorkingTree(bot, cwd, hashC!);
await drain(bot, cwd);
@@ -416,3 +617,193 @@ describe("git timeout", () => {
expect(third).not.toBe(first);
});
});
+
+function shadowOf(bot: string, cwd: string): string {
+ return join(CHECKPOINTS_DIR, bot, createHash("sha256").update(realpathSync(cwd)).digest("hex").slice(0, 16));
+}
+
+describe("a shadow's first use", () => {
+ it("is not cut short by the read-ahead that started it being stopped, and leaves nothing half-made", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ let open = () => {};
+ const held = new Promise<void>((done) => { open = done; });
+ let inits = 0;
+ hooks.inject = args => args[0] === "init" && (inits += 1) === 1 ? { until: held } : undefined;
+ const stopped = new AbortController();
+ const reading = prime(bot, cwd, stopped.signal);
+ await vi.waitFor(() => expect(inits).toBe(1));
+ // The bot is moved off the folder while git is still making the shadow.
+ stopped.abort();
+ const turn = snapshot(bot, cwd, "first turn", undefined, { pin: "dispatch-1" });
+ open();
+ expect(await reading).toBe(false);
+ expect(await turn).toMatch(/^[0-9a-f]{40}$/);
+ expect(inits).toBe(1);
+ const shadow = shadowOf(bot, cwd);
+ expect(readdirSync(join(shadow, ".git")).filter((name) => name.endsWith(".lock"))).toEqual([]);
+ expect(readdirSync(join(shadow, "..")).filter((name) => name.endsWith(".new"))).toEqual([]);
+ await release(bot, cwd, "dispatch-1");
+ });
+});
+
+describe("a snapshot that fails", () => {
+ it("costs that turn its checkpoint, never the bot's other folders, and turns its own folder off only after several in a row", async () => {
+ const { bot, cwd } = workspace();
+ const other = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ writeFileSync(join(other.cwd, "a.txt"), "one");
+ expect(await snapshot(bot, cwd, "first")).toMatch(/^[0-9a-f]{40}$/);
+ await drain(bot, cwd);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ let broken = true;
+ hooks.inject = args => broken && args[0] === "commit-tree" ? { error: new Error("Command failed: git commit-tree"), stderr: "fatal: unable to write" } : undefined;
+ for (let turn = 1; turn < FAILURES_BEFORE_OFF; turn += 1) {
+ writeFileSync(join(cwd, "a.txt"), `edit ${turn}`);
+ expect(await snapshot(bot, cwd, `failing ${turn}`, undefined, { pin: `dispatch-${turn}` })).toBeNull();
+ expect(String(warn.mock.calls.at(-1)?.[0])).toContain("checkpoint not taken");
+ }
+ expect(shadowGit(bot, cwd, "for-each-ref", "--format=%(objectname)", "refs/omb-live/").trim()).toBe("");
+ // The same bot in another folder is untouched, and so is this folder once git works again.
+ broken = false;
+ expect(await snapshot(bot, other.cwd, "other folder")).toMatch(/^[0-9a-f]{40}$/);
+ expect(await snapshot(bot, cwd, "working again")).toMatch(/^[0-9a-f]{40}$/);
+ await drain(bot, cwd);
+ broken = true;
+ for (let turn = 1; turn <= FAILURES_BEFORE_OFF; turn += 1) {
+ writeFileSync(join(cwd, "a.txt"), `later edit ${turn}`);
+ expect(await snapshot(bot, cwd, `failing again ${turn}`)).toBeNull();
+ }
+ expect(String(warn.mock.calls.at(-1)?.[0])).toContain("disabled");
+ hooks.calls = [];
+ expect(await snapshot(bot, cwd, "off")).toBeNull();
+ expect(hooks.calls).toEqual([]);
+ broken = false;
+ writeFileSync(join(other.cwd, "a.txt"), "two");
+ expect(await snapshot(bot, other.cwd, "other folder still on")).toMatch(/^[0-9a-f]{40}$/);
+ });
+
+ it("tries once more without a lock that a git stopped by force left on the shadow's refs", async () => {
+ for (const lock of ["HEAD.lock", join("refs", "heads", "main.lock"), "packed-refs.lock", "config.lock"]) {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "one");
+ await snapshot(bot, cwd, "first", undefined, { pin: "dispatch-1" });
+ await drain(bot, cwd);
+ shadowGit(bot, cwd, "pack-refs", "--all", "--prune");
+ writeFileSync(join(shadow, ".git", lock), "");
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ await release(bot, cwd, "dispatch-1");
+ writeFileSync(join(cwd, "a.txt"), "two");
+ const second = await snapshot(bot, cwd, "second", undefined, { pin: "dispatch-2" });
+ expect(second, lock).toMatch(/^[0-9a-f]{40}$/);
+ expect(shadowGit(bot, cwd, "for-each-ref", "--format=%(objectname)", "refs/omb-live/").trim(), lock).toBe(second);
+ expect(warn, lock).not.toHaveBeenCalled();
+ await release(bot, cwd, "dispatch-2");
+ warn.mockRestore();
+ }
+ });
+});
+
+describe("a folder being read ahead when its turn starts", () => {
+ it("gives the turn the read-ahead's answer when the folder proves too big, without a second attempt", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ let giveUp: (failure: Error) => void = () => {};
+ const slow = new Promise<Error>((done) => { giveUp = done; });
+ hooks.inject = args => args[0] === "add" ? { until: slow } : undefined;
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const reading = prime(bot, cwd);
+ const turn = snapshot(bot, cwd, "the turn", undefined, { pin: "dispatch-1" });
+ await vi.waitFor(() => expect(subcommands()).toContain("add"));
+ giveUp(timeoutError("add"));
+ expect(await reading).toBe(false);
+ expect(await turn).toBeNull();
+ expect(subcommands().filter(command => command === "add")).toHaveLength(1);
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("collections", () => {
+ it("prune only what was unreachable before they started, and say so on disk while they run", async () => {
+ const { bot, cwd } = workspace();
+ const marker = join(shadowOf(bot, cwd), ".git", "omb-collecting");
+ writeFileSync(join(cwd, "a.txt"), "one");
+ await snapshot(bot, cwd, "first");
+ let during: string | null = null;
+ hooks.inject = (args) => {
+ if (args[0] === "count-objects") return { stdout: countObjects({ count: 7000 }) };
+ if (args[0] === "gc") during = readFileSync(marker, "utf8");
+ return undefined;
+ };
+ writeFileSync(join(cwd, "a.txt"), "two");
+ const started = Math.floor(Date.now() / 1000);
+ const hash = await snapshot(bot, cwd, "collection due");
+ await diffWorkingTree(bot, cwd, hash!);
+ await drain(bot, cwd);
+ const prune = hooks.calls.find(args => args[0] === "gc")?.find(arg => arg.startsWith("--prune="))?.slice("--prune=".length);
+ expect(Number(prune)).toBeGreaterThanOrEqual(started);
+ expect(Number(prune)).toBeLessThanOrEqual(Math.floor(Date.now() / 1000));
+ expect(during).toBe(prune);
+ expect(existsSync(marker)).toBe(false);
+ });
+
+ it("are never ended by force on Windows: one that has started runs to its end, and the turn waits for it", async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, "platform")!;
+ Object.defineProperty(process, "platform", { ...platform, value: "win32" });
+ try {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ await snapshot(bot, cwd, "first");
+ let open = () => {};
+ const held = new Promise<void>((done) => { open = done; });
+ let collections = 0;
+ hooks.inject = (args) => {
+ if (args[0] === "count-objects") return collections === 0 ? { stdout: countObjects({ count: 7000 }) } : undefined;
+ if (args[0] === "gc") return (collections += 1) === 1 ? { until: held } : undefined;
+ return undefined;
+ };
+ writeFileSync(join(cwd, "a.txt"), "two");
+ const before = await snapshot(bot, cwd, "collection due", undefined, { pin: "dispatch-1" });
+ await diffWorkingTree(bot, cwd, before!);
+ await vi.waitFor(() => expect(collections).toBe(1));
+ writeFileSync(join(cwd, "a.txt"), "three");
+ hooks.calls = [];
+ let taken = false;
+ const next = snapshot(bot, cwd, "next turn").then((hash) => { taken = true; return hash; });
+ await new Promise((turn) => setImmediate(turn));
+ expect(taken).toBe(false);
+ expect(subcommands()).not.toContain("add");
+ open();
+ expect(await next).toMatch(/^[0-9a-f]{40}$/);
+ await release(bot, cwd, "dispatch-1");
+ await drain(bot, cwd);
+ expect(collections).toBe(1);
+ } finally {
+ Object.defineProperty(process, "platform", platform);
+ }
+ });
+});
+
+describe("quiet", () => {
+ it("resolves once no git is running or waiting on the bot's shadows", async () => {
+ const { bot, cwd } = workspace();
+ writeFileSync(join(cwd, "a.txt"), "one");
+ await snapshot(bot, cwd, "first");
+ await drain(bot, cwd);
+ let open = () => {};
+ const held = new Promise<void>((done) => { open = done; });
+ hooks.inject = args => args[0] === "add" ? { until: held } : undefined;
+ const stopped = new AbortController();
+ const reading = prime(bot, cwd, stopped.signal);
+ await vi.waitFor(() => expect(subcommands()).toContain("add"));
+ let isQuiet = false;
+ const waiting = quiet(bot).then(() => { isQuiet = true; });
+ await new Promise((turn) => setImmediate(turn));
+ expect(isQuiet).toBe(false);
+ stopped.abort();
+ await waiting;
+ expect(await reading).toBe(false);
+ open();
+ });
+});
diff --git a/server/checkpoints.test.ts b/server/checkpoints.test.ts
index 6f18687aa9..f6604f20a5 100644
--- a/server/checkpoints.test.ts
+++ b/server/checkpoints.test.ts
@@ -1,12 +1,12 @@
import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process";
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, unlinkSync, utimesSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it, vi } from "vitest";
// Shadow repos live under DATA_DIR, which server/testing/setup.ts points at a disposable home before config.ts loads.
-import { CHECKPOINTS_DIR, GC_EVERY_COMMITS, diffWorkingTree, refusalReason, release, snapshot } from "./checkpoints.ts";
+import { CHECKPOINTS_DIR, GC_EVERY_COMMITS, diffWorkingTree, prime, refusalReason, release, snapshot } from "./checkpoints.ts";
import { removeTempDir } from "./testing/cleanup.ts";
const scratchDirs: string[] = [];
@@ -449,3 +449,266 @@ describe("diffWorkingTree", () => {
expect(await diffWorkingTree(bot, homedir(), hash!)).toBeNull();
});
});
+
+describe("prime", () => {
+ it("reads the folder ahead of a turn without moving the last snapshot, and the turn still snapshots what it finds", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "before the last turn");
+ const last = await snapshot(bot, cwd, "last turn");
+ writeFileSync(join(cwd, "a.txt"), "after the last turn");
+ writeFileSync(join(cwd, "b.txt"), "made by the last turn");
+ expect(await prime(bot, cwd)).toBe(true);
+ // The state before the last turn is still the newest snapshot, and nothing is pinned.
+ expect(snapshotsIn(bot, cwd).map(c => c.hash)).toEqual([last]);
+ expect(userGit(shadow, "show", `${last}:a.txt`)).toBe("before the last turn");
+ expect(userGit(shadow, "for-each-ref", "refs/omb-live/").trim()).toBe("");
+ // The person edits the folder outside the app, after the folder was read.
+ writeFileSync(join(cwd, "a.txt"), "edited outside the app");
+ const turn = await snapshot(bot, cwd, "next turn", undefined, { pin: "dispatch-P" });
+ expect(userGit(shadow, "show", `${turn}:a.txt`)).toBe("edited outside the app");
+ expect(userGit(shadow, "show", `${turn}:b.txt`)).toBe("made by the last turn");
+ writeFileSync(join(cwd, "a.txt"), "edited by the turn");
+ expect(await diffWorkingTree(bot, cwd, turn!)).toEqual({ changed: ["a.txt"], added: [], deleted: [] });
+ await release(bot, cwd, "dispatch-P");
+ });
+
+ it("reads a folder no turn has run in, and that folder's first turn is checkpointed as the turn found it", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ mkdirSync(join(cwd, "src"));
+ for (let n = 0; n < 40; n += 1) writeFileSync(join(cwd, "src", `file${n}.txt`), `file ${n}`);
+ expect(await prime(bot, cwd)).toBe(true);
+ expect(snapshotsIn(bot, cwd)).toEqual([]);
+ writeFileSync(join(cwd, "src", "file0.txt"), "edited before the first message");
+ const first = await snapshot(bot, cwd, "first turn", undefined, { pin: "dispatch-Q" });
+ expect(userGit(shadow, "show", `${first}:src/file0.txt`)).toBe("edited before the first message");
+ expect(userGit(shadow, "ls-tree", "-r", "--name-only", first!).trim().split("\n")).toHaveLength(40);
+ unlinkSync(join(cwd, "src", "file1.txt"));
+ expect(await diffWorkingTree(bot, cwd, first!)).toEqual({ changed: [], added: [], deleted: ["src/file1.txt"] });
+ await release(bot, cwd, "dispatch-Q");
+ });
+
+ it("stopped before it ends, or refused, changes nothing for the turns after it", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ for (let n = 0; n < 200; n += 1) writeFileSync(join(cwd, `file${n}.txt`), `file ${n}`);
+ const stopped = new AbortController();
+ const reading = prime(bot, cwd, stopped.signal);
+ // A message sent while the folder is still being read waits for that read, never beside it.
+ const sent = snapshot(bot, cwd, "sent while reading", undefined, { pin: "dispatch-R" });
+ stopped.abort();
+ expect(await reading).toBe(false);
+ const turn = await sent;
+ expect(turn).toMatch(/^[0-9a-f]{40}$/);
+ expect(userGit(shadow, "ls-tree", "-r", "--name-only", turn!).trim().split("\n")).toHaveLength(200);
+ expect(existsSync(join(shadow, ".git", "index.lock"))).toBe(false);
+ await release(bot, cwd, "dispatch-R");
+ expect(await prime(bot, homedir())).toBe(false);
+ expect(await prime(bot, join(cwd, "missing"))).toBe(false);
+ });
+
+ it("puts a new folder's files into a pack, so the first snapshot leaves nothing to collect", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ for (let n = 0; n < 300; n += 1) writeFileSync(join(cwd, `file${n}.txt`), `file ${n} `.repeat(40));
+ const first = await snapshot(bot, cwd, "first turn");
+ await drain(bot, cwd);
+ const counted = userGit(shadow, "count-objects", "-v");
+ expect(Number(/^in-pack: (\d+)$/m.exec(counted)?.[1])).toBeGreaterThanOrEqual(300);
+ expect(Number(/^count: (\d+)$/m.exec(counted)?.[1])).toBeLessThan(20);
+ expect(userGit(shadow, "show", `${first}:file299.txt`)).toBe("file 299 ".repeat(40));
+ // Later edits go in as single objects again.
+ writeFileSync(join(cwd, "file0.txt"), "edited");
+ const second = await snapshot(bot, cwd, "second turn");
+ expect(userGit(shadow, "show", `${second}:file0.txt`)).toBe("edited");
+ expect(Number(/^packs: (\d+)$/m.exec(userGit(shadow, "count-objects", "-v"))?.[1])).toBe(1);
+ });
+});
+
+describe("a restart in the middle of a snapshot", () => {
+ it("finds the index locked by the git it cut off, and checkpoints the next turns on a copy", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "before the restart");
+ writeFileSync(join(cwd, "b.txt"), "kept");
+ await snapshot(bot, cwd, "turn X");
+ // What a git that was killed, or is still running after its server died, leaves on the index.
+ writeFileSync(join(shadow, ".git", "index.lock"), "");
+ for (const round of ["first start", "second start"]) {
+ vi.resetModules();
+ const fresh = await import("./checkpoints.ts");
+ writeFileSync(join(cwd, "a.txt"), round);
+ const turn = await fresh.snapshot(bot, cwd, round, undefined, { pin: `dispatch-${round}` });
+ expect(turn).toMatch(/^[0-9a-f]{40}$/);
+ expect(userGit(shadow, "show", `${turn}:a.txt`)).toBe(round);
+ expect(userGit(shadow, "show", `${turn}:b.txt`)).toBe("kept");
+ writeFileSync(join(cwd, "b.txt"), `edited after ${round}`);
+ expect(await fresh.diffWorkingTree(bot, cwd, turn!)).toEqual({ changed: ["b.txt"], added: [], deleted: [] });
+ writeFileSync(join(cwd, "b.txt"), "kept");
+ await fresh.release(bot, cwd, `dispatch-${round}`);
+ }
+ // The lock was never this process's to remove; the index it guards is no longer anyone's, and git's own check passes.
+ expect(existsSync(join(shadow, ".git", "index.lock"))).toBe(true);
+ expect(existsSync(join(shadow, ".git", "index"))).toBe(false);
+ expect(() => userGit(shadow, "fsck", "--connectivity-only", "--no-dangling")).not.toThrow();
+ });
+
+ it("finds a shadow git never finished making, and makes it again", async () => {
+ const { bot, cwd } = workspace();
+ const other = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "one");
+ writeFileSync(join(other.cwd, "a.txt"), "one");
+ // What `git init` leaves when it is ended while writing its config.
+ mkdirSync(join(shadow, ".git", "refs"), { recursive: true });
+ writeFileSync(join(shadow, ".git", "config"), "[core]\n");
+ writeFileSync(join(shadow, ".git", "config.lock"), "[core]\n");
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const first = await snapshot(bot, cwd, "first turn", undefined, { pin: "dispatch-H" });
+ expect(first).toMatch(/^[0-9a-f]{40}$/);
+ expect(userGit(shadow, "show", `${first}:a.txt`)).toBe("one");
+ expect(await snapshot(bot, other.cwd, "the same bot elsewhere")).toMatch(/^[0-9a-f]{40}$/);
+ expect(warn).not.toHaveBeenCalled();
+ warn.mockRestore();
+ await release(bot, cwd, "dispatch-H");
+ });
+
+ it("checkpoints a folder's first turn whenever the read-ahead before it was stopped", async () => {
+ for (let delay = 0; delay < 24; delay += 2) {
+ const { bot, cwd } = workspace();
+ for (let n = 0; n < 30; n += 1) writeFileSync(join(cwd, `file${n}.txt`), `file ${n}`);
+ const stopped = new AbortController();
+ const reading = prime(bot, cwd, stopped.signal);
+ setTimeout(() => stopped.abort(), delay);
+ await reading;
+ const first = await snapshot(bot, cwd, "first turn");
+ expect(first, `stopped after ${delay} ms`).toMatch(/^[0-9a-f]{40}$/);
+ expect(userGit(shadowOf(bot, cwd), "ls-tree", "-r", "--name-only", first!).trim().split("\n")).toHaveLength(30);
+ }
+ }, 60_000);
+
+ it("clears the locks a git ended by force left on the shadow's refs and config, once they are too old to be held", async () => {
+ for (const lock of ["HEAD.lock", join("refs", "heads", "main.lock"), "packed-refs.lock", "config.lock"]) {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "one");
+ const leaked = await snapshot(bot, cwd, "turn X", undefined, { pin: "dispatch-X" });
+ await drain(bot, cwd);
+ userGit(shadow, "pack-refs", "--all", "--prune");
+ const path = join(shadow, ".git", lock);
+ writeFileSync(path, "");
+ const longAgo = new Date(Date.now() - 60_000);
+ utimesSync(path, longAgo, longAgo);
+ vi.resetModules();
+ const fresh = await import("./checkpoints.ts");
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ writeFileSync(join(cwd, "a.txt"), "next start");
+ const next = await fresh.snapshot(bot, cwd, "turn Y", undefined, { pin: "dispatch-Y" });
+ expect(next, lock).toMatch(/^[0-9a-f]{40}$/);
+ // The pin the last process left was swept, and this turn's pin is released.
+ expect(userGit(shadow, "for-each-ref", "--format=%(objectname)", "refs/omb-live/").trim(), lock).toBe(next);
+ expect(next).not.toBe(leaked);
+ await fresh.release(bot, cwd, "dispatch-Y");
+ expect(userGit(shadow, "for-each-ref", "refs/omb-live/").trim(), lock).toBe("");
+ expect(existsSync(path), lock).toBe(false);
+ expect(warn, lock).not.toHaveBeenCalled();
+ warn.mockRestore();
+ }
+ }, 60_000);
+
+ it("writes nothing while a collection its last server left running could still prune it", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "one");
+ await snapshot(bot, cwd, "turn X");
+ await drain(bot, cwd);
+ // A collection that prunes everything unreachable up to this second was running when the server died.
+ const pruning = Math.floor(Date.now() / 1000);
+ writeFileSync(join(shadow, ".git", "omb-collecting"), String(pruning));
+ vi.resetModules();
+ const fresh = await import("./checkpoints.ts");
+ writeFileSync(join(cwd, "a.txt"), "next start");
+ const next = await fresh.snapshot(bot, cwd, "turn Y");
+ const blob = userGit(shadow, "rev-parse", `${next}:a.txt`).trim();
+ const written = statSync(join(shadow, ".git", "objects", blob.slice(0, 2), blob.slice(2))).mtimeMs;
+ expect(Math.floor(written / 1000)).toBeGreaterThan(pruning);
+ expect(existsSync(join(shadow, ".git", "omb-collecting"))).toBe(false);
+ // That collection, ending now, takes nothing written since: not even what no snapshot names yet.
+ writeFileSync(join(cwd, "staged.txt"), "read ahead, in no snapshot yet");
+ const unnamed = userGit(shadow, "hash-object", "-w", join(cwd, "staged.txt")).trim();
+ userGit(shadow, "gc", "--quiet", `--prune=${pruning}`);
+ expect(userGit(shadow, "cat-file", "-p", unnamed)).toBe("read ahead, in no snapshot yet");
+ expect(userGit(shadow, "show", `${next}:a.txt`)).toBe("next start");
+ });
+
+ it("keeps a shadow whose snapshots sit on a branch of another name", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "one");
+ const kept = await snapshot(bot, cwd, "turn X");
+ await drain(bot, cwd);
+ userGit(shadow, "branch", "-m", "main", "trunk");
+ vi.resetModules();
+ const fresh = await import("./checkpoints.ts");
+ expect(await fresh.snapshot(bot, cwd, "turn Y")).toBe(kept);
+ expect(userGit(shadow, "show", `${kept}:a.txt`)).toBe("one");
+ });
+
+ it("reads the folder again when the index names an object the shadow has lost", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "one");
+ writeFileSync(join(cwd, "b.txt"), "kept");
+ const before = await snapshot(bot, cwd, "turn X");
+ await drain(bot, cwd);
+ writeFileSync(join(cwd, "a.txt"), "staged, then pruned");
+ // Older than the index, so git takes the staged entry as current and does not write the file's object again.
+ const earlier = new Date(Date.now() - 60_000);
+ utimesSync(join(cwd, "a.txt"), earlier, earlier);
+ expect(await diffWorkingTree(bot, cwd, before!)).toEqual({ changed: ["a.txt"], added: [], deleted: [] });
+ const lost = userGit(cwd, "hash-object", join(cwd, "a.txt")).trim();
+ rmSync(join(shadow, ".git", "objects", lost.slice(0, 2), lost.slice(2)));
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const next = await snapshot(bot, cwd, "turn Y");
+ expect(next).toMatch(/^[0-9a-f]{40}$/);
+ expect(userGit(shadow, "show", `${next}:a.txt`)).toBe("staged, then pruned");
+ expect(userGit(shadow, "show", `${next}:b.txt`)).toBe("kept");
+ expect(() => userGit(shadow, "fsck", "--connectivity-only", "--no-dangling", next!)).not.toThrow();
+ expect(warn).not.toHaveBeenCalled();
+ warn.mockRestore();
+ });
+});
+
+describe("a collection cut short", () => {
+ it("by the next turn's snapshot leaves HEAD, the running turn's commit and every object they need readable", async () => {
+ const { bot, cwd } = workspace();
+ const shadow = shadowOf(bot, cwd);
+ for (let d = 0; d < 20; d += 1) {
+ mkdirSync(join(cwd, `dir${d}`));
+ for (let f = 0; f < 50; f += 1) writeFileSync(join(cwd, `dir${d}`, `file${f}.txt`), `dir ${d} file ${f}\n`.repeat(20));
+ }
+ const running = await snapshot(bot, cwd, "a turn still running", undefined, { pin: "dispatch-S" });
+ let last: string | null = null;
+ for (let turn = 0; turn < GC_EVERY_COMMITS; turn += 1) {
+ for (let f = 0; f < 50; f += 1) writeFileSync(join(cwd, "dir0", `file${f}.txt`), `turn ${turn} file ${f}\n`.repeat(20));
+ last = await snapshot(bot, cwd, `churn ${turn}`);
+ }
+ // The settled diff lets the collection start; the next message arrives while it runs.
+ await diffWorkingTree(bot, cwd, last!);
+ writeFileSync(join(cwd, "dir1", "file0.txt"), "the next turn's folder");
+ const next = await snapshot(bot, cwd, "next turn", undefined, { pin: "dispatch-T" });
+ expect(userGit(shadow, "rev-parse", "HEAD").trim()).toBe(next);
+ expect(userGit(shadow, "show", `${next}:dir1/file0.txt`)).toBe("the next turn's folder");
+ expect(userGit(shadow, "show", `${running}:dir0/file0.txt`)).toBe("dir 0 file 0\n".repeat(20));
+ expect(() => userGit(shadow, "fsck", "--connectivity-only", "--no-dangling")).not.toThrow();
+ expect(await diffWorkingTree(bot, cwd, next!)).toEqual({ changed: [], added: [], deleted: [] });
+ await release(bot, cwd, "dispatch-T");
+ await drain(bot, cwd);
+ // The collection ran to its end behind that turn: the running turn's commit is still held by its pin.
+ expect(userGit(shadow, "show", `${running}:dir0/file0.txt`)).toBe("dir 0 file 0\n".repeat(20));
+ expect(() => userGit(shadow, "cat-file", "-e", `${last}^{commit}`)).toThrow();
+ expect(() => userGit(shadow, "fsck", "--connectivity-only", "--no-dangling")).not.toThrow();
+ await release(bot, cwd, "dispatch-S");
+ }, process.platform === "win32" ? 120_000 : 60_000);
+});
diff --git a/server/checkpoints.ts b/server/checkpoints.ts
index b2d423e71f..205dc68595 100644
--- a/server/checkpoints.ts
+++ b/server/checkpoints.ts
@@ -9,10 +9,11 @@
// snapshot-before-every-turn cadence follows Cline.
import { execFile } from "node:child_process";
import { createHash } from "node:crypto";
-import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
+import { closeSync, copyFileSync, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
import { readdir } from "node:fs/promises";
import { homedir } from "node:os";
-import { isAbsolute, join, parse, resolve } from "node:path";
+import { dirname, isAbsolute, join, parse, resolve, sep } from "node:path";
+import { setTimeout as sleep } from "node:timers/promises";
import { DATA_DIR } from "./config.ts";
import { execFileInGroup } from "./group-exec.ts";
@@ -115,13 +116,6 @@ export const GC_EVERY_COMMITS = 25;
const GC_LOOSE_OBJECTS = 6_700;
const GC_NEW_DATA_KIB = 262_144;
-const disabledBots = new Set<string>();
-
-function disable(botId: string, message: string): void {
- disabledBots.add(botId);
- console.warn(`workspace checkpoints disabled for bot ${botId} this session: ${message}`);
-}
-
class GitTimeoutError extends Error {}
const disabledFolders = new Set<string>();
@@ -132,6 +126,20 @@ function disableFolder(shadow: string, botId: string, worktree: string, message:
console.warn(`workspace checkpoints disabled for bot ${botId} in ${worktree} this session: ${message}`);
}
+/** Snapshots of a folder that failed one after another. One failure costs that turn its checkpoint and nothing else; this
+ * many in a row turn the folder off for the session, and never the bot's other folders. */
+export const FAILURES_BEFORE_OFF = 3;
+const failedInARow = new Map<string, number>();
+
+function snapshotFailed(shadow: string, botId: string, worktree: string, message: string): void {
+ const failures = (failedInARow.get(shadow) ?? 0) + 1;
+ failedInARow.set(shadow, failures);
+ // The next use looks again for a lock a stopped git left.
+ locksCleared.delete(shadow);
+ if (failures >= FAILURES_BEFORE_OFF) disableFolder(shadow, botId, worktree, message);
+ else console.warn(`workspace checkpoint not taken for bot ${botId} in ${worktree}: ${message}`);
+}
+
function folderShadow(botId: string, cwd: string): { worktree: string; shadow: string } | null {
try {
const worktree = realpathSync(resolve(cwd));
@@ -183,6 +191,24 @@ function shadowDir(botId: string, cwd: string): string {
return join(CHECKPOINTS_DIR, botId, key);
}
+// The index file a shadow's git calls use: `index`, or the one leaveLockedIndex() moved it to.
+const INDEX_POINTER = "omb-index";
+const INDEX_NAME = /^index(-[a-z0-9]{1,16})?$/;
+const indexNames = new Map<string, string>();
+function indexName(shadow: string): string {
+ let name = indexNames.get(shadow);
+ if (name === undefined) {
+ try {
+ name = readFileSync(join(shadow, ".git", INDEX_POINTER), "utf8").split("\n")[0]!;
+ } catch {
+ name = "";
+ }
+ if (!INDEX_NAME.test(name)) name = "index";
+ indexNames.set(shadow, name);
+ }
+ return name;
+}
+
function gitEnv(shadow: string, cwd: string): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = { ...process.env };
// Git honours redirection env beyond GIT_DIR (GIT_COMMON_DIR, GIT_CONFIG_KEY_*), so the whole GIT_ namespace is cleared.
@@ -191,6 +217,7 @@ function gitEnv(shadow: string, cwd: string): NodeJS.ProcessEnv {
}
env.GIT_DIR = join(shadow, ".git");
env.GIT_WORK_TREE = resolve(cwd);
+ env.GIT_INDEX_FILE = join(shadow, ".git", indexName(shadow));
env.GIT_CONFIG_GLOBAL = join(shadow, "gitconfig");
env.GIT_CONFIG_SYSTEM = join(shadow, "gitconfig_empty");
env.GIT_AUTHOR_NAME = "OpenMausBot Checkpoint";
@@ -254,15 +281,139 @@ function liveRef(pin: string): string {
return LIVE_REFS + createHash("sha256").update(pin).digest("hex").slice(0, 16);
}
+/** The pins this process took and has not released, per shadow. */
+const heldPins = new Map<string, Set<string>>();
+
+/** The shadows this process has taken over from the one before it: once each, or it would sweep its own turns' pins. */
+const takenOver = new Set<string>();
+
+/** The shadows whose leftover locks were looked for, since the start or since their last failure. */
+const locksCleared = new Set<string>();
+
+/** Git holds each of these for one ref or config write, a few milliseconds: one this old has no git behind it. The index
+ * lock is not among them, because a git reading a big folder holds that one for as long as it reads. */
+const STALE_LOCK_MS = 5_000;
+const SHORT_LOCKS = ["HEAD.lock", "packed-refs.lock", "config.lock", "gc.pid.lock", join("refs", "heads", "main.lock")];
+
+/** Windows ends a stopped git with no chance to clean up, and a crash does the same anywhere: the lock it held would fail
+ * every later snapshot. A lock younger than `staleMs` is waited for until it goes or reaches that age. Zero only where
+ * every git this process started on the shadow has ended: its own gits run one at a time there. */
+async function clearStaleLocks(shadow: string, staleMs = STALE_LOCK_MS): Promise<void> {
+ if (staleMs > 0 && locksCleared.has(shadow)) return;
+ const dir = join(shadow, ".git");
+ const pins = await readdir(join(dir, LIVE_REFS)).then((names) => names.filter((name) => name.endsWith(".lock")).map((name) => join(LIVE_REFS, name)), () => []);
+ for (const name of [...SHORT_LOCKS, ...pins]) {
+ const path = join(dir, name);
+ for (let stat = statSync(path, { throwIfNoEntry: false }); stat; stat = statSync(path, { throwIfNoEntry: false })) {
+ const age = Date.now() - stat.mtimeMs;
+ if (age < 0 || age >= staleMs) {
+ rmSync(path, { force: true });
+ break;
+ }
+ await sleep(Math.min(250, staleMs - age));
+ }
+ }
+ locksCleared.add(shadow);
+}
+
+/** While a collection runs, the second it prunes up to. A collection outlives a server that dies, and what the next
+ * server writes must be newer than that second, or the collection would prune it as it is written. */
+const COLLECTING = "omb-collecting";
+
+async function outlastCollection(shadow: string): Promise<void> {
+ const marker = join(shadow, ".git", COLLECTING);
+ let until: number;
+ try {
+ until = Number(readFileSync(marker, "utf8"));
+ } catch {
+ return;
+ }
+ const now = () => Math.floor(Date.now() / 1000);
+ // A second from a clock since set back is not waited for.
+ if (Number.isSafeInteger(until) && until - now() <= 2) while (now() <= until) await sleep(100);
+ rmSync(marker, { force: true });
+}
+
+/** A shadow is made beside its place and moved there whole, so nothing that stops this process part-way leaves a shadow
+ * git cannot open. Takes no stop signal, for the same reason. */
+async function makeShadow(shadow: string, cwd: string): Promise<void> {
+ if (existsSync(join(shadow, ".git", "HEAD"))) return;
+ const draft = `${shadow}.${process.pid}.new`;
+ for (const stale of [draft, shadow]) rmSync(stale, { recursive: true, force: true });
+ mkdirSync(draft, { recursive: true, mode: 0o700 });
+ writeFileSync(join(draft, "gitconfig"), GITCONFIG, { mode: 0o600 });
+ writeFileSync(join(draft, "gitconfig_empty"), "", { mode: 0o600 });
+ const env = gitEnv(draft, cwd);
+ // --template= keeps the user's init.templateDir hooks/config out
+ await runGit(["init", "--initial-branch=main", "--template="], cwd, env);
+ await runGit(["commit", "--no-verify", "--allow-empty", "-m", "checkpoint base"], cwd, env);
+ renameSync(draft, shadow);
+}
+
// Pins outlive a crashed process, so the first use of a shadow in this process drops every leftover pin.
-const sweptShadows = new Set<string>();
const droppedPins = new Set<string>();
-async function sweepLiveRefs(cwd: string, env: NodeJS.ProcessEnv, shadow: string, signal?: AbortSignal): Promise<void> {
- if (sweptShadows.has(shadow)) return;
- const stale = (await runGit(["for-each-ref", "--format=%(refname)", LIVE_REFS], cwd, env, signal)).split("\n").filter(Boolean);
- for (const ref of stale) await runGit(["update-ref", "-d", ref], cwd, env, signal);
+async function sweepLiveRefs(cwd: string, env: NodeJS.ProcessEnv, shadow: string): Promise<void> {
+ const stale = (await runGit(["for-each-ref", "--format=%(refname)", LIVE_REFS], cwd, env)).split("\n").filter(Boolean);
+ for (const ref of stale) await runGit(["update-ref", "-d", ref], cwd, env);
if (stale.length > 0) droppedPins.add(shadow);
- sweptShadows.add(shadow);
+}
+
+/** A shadow's first use in this process, whole or not at all: nothing here is stopped part-way by a turn's or a
+ * read-ahead's signal. */
+async function takeOver(shadow: string, cwd: string, env: NodeJS.ProcessEnv): Promise<void> {
+ if (takenOver.has(shadow)) return;
+ mkdirSync(dirname(shadow), { recursive: true, mode: 0o700 });
+ await makeShadow(shadow, cwd);
+ writeFileSync(join(shadow, "gitconfig"), GITCONFIG, { mode: 0o600 });
+ writeFileSync(join(shadow, "gitconfig_empty"), "", { mode: 0o600 });
+ await outlastCollection(shadow);
+ await clearStaleLocks(shadow);
+ leaveLockedIndex(shadow, env);
+ dropAbandonedIndex(shadow);
+ await sweepLiveRefs(cwd, env, shadow);
+ takenOver.add(shadow);
+}
+
+/** A lock on the index at a shadow's first use belongs to a git this process never started: one cut off with the last
+ * process, or one still running after it. That index is no longer this process's to write, so the shadow moves to a copy
+ * under a new name, which no other git knows. */
+function leaveLockedIndex(shadow: string, env: NodeJS.ProcessEnv): void {
+ const dir = join(shadow, ".git");
+ const current = indexName(shadow);
+ if (!existsSync(join(dir, `${current}.lock`))) return;
+ const next = `index-${Date.now().toString(36)}`;
+ let before = "";
+ try {
+ before = readFileSync(join(dir, INDEX_POINTER), "utf8").split("\n")[1] ?? "";
+ } catch {
+ }
+ if (INDEX_NAME.test(before) && before !== "index") for (const name of [before, `${before}.lock`]) rmSync(join(dir, name), { force: true });
+ try {
+ copyFileSync(join(dir, current), join(dir, next));
+ } catch {
+ }
+ writeFileSync(join(dir, INDEX_POINTER), `${next}\n${current}\n`, { mode: 0o600 });
+ indexNames.set(shadow, next);
+ env.GIT_INDEX_FILE = join(dir, next);
+}
+
+/** The index a shadow moved away from names objects nothing keeps any more, which git's own checks of the shadow would
+ * report. No git of this process reads it; a git still running from before may put it back once, for the next start. */
+function dropAbandonedIndex(shadow: string): void {
+ try {
+ const [current, before = ""] = readFileSync(join(shadow, ".git", INDEX_POINTER), "utf8").split("\n");
+ if (INDEX_NAME.test(before) && before !== current) rmSync(join(shadow, ".git", before), { force: true });
+ } catch {
+ }
+}
+
+/** After a git of this process was stopped in a way that let it clean nothing up (Windows ends the whole tree at once).
+ * Only where no git of this process is running on the shadow. */
+function dropIndexLock(env: NodeJS.ProcessEnv): void {
+ try {
+ rmSync(`${env.GIT_INDEX_FILE}.lock`, { force: true });
+ } catch {
+ }
}
/** `base`: the empty marker HEAD was made on, or null for legacy multi-commit history the next snapshot compacts. */
@@ -279,43 +430,88 @@ async function readHead(cwd: string, env: NodeJS.ProcessEnv, signal?: AbortSigna
return { hash, tree, base };
}
-/** Rewrites its config files on every use so exclude-list updates reach existing shadows. */
-async function ensureShadow(cwd: string, env: NodeJS.ProcessEnv, shadow: string, signal?: AbortSignal): Promise<Head> {
- signal?.throwIfAborted();
- mkdirSync(shadow, { recursive: true, mode: 0o700 });
- writeFileSync(join(shadow, "gitconfig"), GITCONFIG, { mode: 0o600 });
- writeFileSync(join(shadow, "gitconfig_empty"), "", { mode: 0o600 });
- if (!existsSync(join(shadow, ".git", "HEAD"))) {
- // --template= keeps the user's init.templateDir hooks/config out
- await runGit(["init", "--initial-branch=main", "--template="], cwd, env, signal);
+/** The empty commit every snapshot is made on. */
+async function baseHead(cwd: string, env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<Head> {
+ await runGit(["commit", "--no-verify", "--allow-empty", "-m", "checkpoint base"], cwd, env, signal);
+ return readHead(cwd, env, signal);
+}
+
+const CACHE_TAG = "CACHEDIR.TAG";
+const TAG_LISTING = ["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", `**/${CACHE_TAG}`];
+const STAGED_LISTING = ["ls-files", "--stage", "-z"];
+const IGNORED_LISTING = ["ls-files", "--cached", "--ignored", "--exclude-standard", "-z"];
+
+/** Cargo and other tools put caches outside target/ or build/; honour the standard CACHEDIR.TAG. */
+function cacheTagged(cwd: string, directory: string): boolean {
+ try {
+ const path = join(cwd, directory, CACHE_TAG);
+ const stat = lstatSync(path);
+ return stat.isFile() && stat.size <= 4096 && readFileSync(path, "utf8").startsWith("Signature: 8a477f597d28d172789f06886806bc55");
+ } catch {
+ return false;
}
- mkdirSync(join(shadow, ".git", "info"), { recursive: true });
- writeFileSync(join(shadow, ".git", "info", "exclude"), EXCLUDES);
- // Cargo and other tools put caches outside target/ or build/; honour the standard CACHEDIR.TAG.
- const tags = (await runGit(["ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", "**/CACHEDIR.TAG"], cwd, env, signal)).split("\0");
- const cachePatterns = new Set<string>();
- for (const tag of tags) {
+}
+
+function cacheDirsIn(cwd: string, listing: string): string[] {
+ const dirs = new Set<string>();
+ for (const tag of listing.split("\0")) {
if (!tag.includes("/") || /[\r\n]/.test(tag)) continue;
- try {
- const path = join(cwd, tag);
- const stat = lstatSync(path);
- if (!stat.isFile() || stat.size > 4096) continue;
- if (!readFileSync(path, "utf8").startsWith("Signature: 8a477f597d28d172789f06886806bc55")) continue;
- const directory = tag.slice(0, -"CACHEDIR.TAG".length);
- cachePatterns.add("/" + directory.replace(/[\\*?[\]#! ]/g, "\\$&"));
- } catch {
- }
+ const directory = tag.slice(0, -CACHE_TAG.length);
+ if (cacheTagged(cwd, directory)) dirs.add(directory);
}
- writeFileSync(join(shadow, ".git", "info", "exclude"), EXCLUDES + [...cachePatterns].join("\n") + "\n");
- let head: Head;
- try {
- head = await readHead(cwd, env, signal);
- } catch {
- await runGit(["commit", "--no-verify", "--allow-empty", "-m", "checkpoint base"], cwd, env, signal);
- head = await readHead(cwd, env, signal);
+ return [...dirs].sort();
+}
+
+function excludeFile(shadow: string): string {
+ return join(shadow, ".git", "info", "exclude");
+}
+
+/** The exclude file with only the fixed list, the scan under it, then the file with what the scan found. */
+async function scanCacheDirs(cwd: string, env: NodeJS.ProcessEnv, shadow: string, signal?: AbortSignal): Promise<string[]> {
+ writeFileSync(excludeFile(shadow), EXCLUDES);
+ const dirs = cacheDirsIn(cwd, await runGit(TAG_LISTING, cwd, env, signal));
+ writeFileSync(excludeFile(shadow), EXCLUDES + dirs.map((directory) => "/" + directory.replace(/[\\*?[\]#! ]/g, "\\$&")).join("\n") + "\n");
+ return dirs;
+}
+
+/** The cache directories the shadow's exclude file names, once this process has written it. */
+const excludedCacheDirs = new Map<string, readonly string[]>();
+
+/** What a capture reads before it stages: HEAD, and the index's paths (`staged`) and its ignored ones (`ignored`), each null
+ * when it could not be listed. */
+type Prepared = { head: Head; staged: string | null; ignored: string | null };
+
+/** The first use in a process writes the shadow's exclude file, so a new exclude list reaches existing shadows.
+ * Later uses find the exclude file naming the cache directories of the pass before, so the listings that read it run
+ * beside the scan that checks it, and run again only when the scan disagrees. */
+async function prepare(cwd: string, env: NodeJS.ProcessEnv, shadow: string, signal?: AbortSignal): Promise<Prepared> {
+ signal?.throwIfAborted();
+ await takeOver(shadow, cwd, env);
+ await clearStaleLocks(shadow);
+ signal?.throwIfAborted();
+ env.GIT_INDEX_FILE = join(shadow, ".git", indexName(shadow));
+ const list = (args: string[]) => runGit(args, cwd, env, signal).catch((e: unknown) => {
+ if (e instanceof GitTimeoutError || signal?.aborted) throw e;
+ return null;
+ });
+ const known = excludedCacheDirs.get(shadow);
+ if (known !== undefined) {
+ const [tags, read, staged, ignored] = await Promise.all([runGit(TAG_LISTING, cwd, env, signal), readHead(cwd, env, signal).catch(() => null), list(STAGED_LISTING), list(IGNORED_LISTING)]);
+ const head = read ?? (await baseHead(cwd, env, signal));
+ // The scan skips what the file already excludes, so those are checked where they stand.
+ const dirs = [...new Set([...cacheDirsIn(cwd, tags), ...known.filter((directory) => cacheTagged(cwd, directory))])].sort();
+ if (dirs.length === known.length && dirs.every((directory, at) => directory === known[at])) return { head, staged, ignored };
+ excludedCacheDirs.delete(shadow);
+ excludedCacheDirs.set(shadow, await scanCacheDirs(cwd, env, shadow, signal));
+ return { head, staged, ignored: await list(IGNORED_LISTING) };
}
- await sweepLiveRefs(cwd, env, shadow, signal);
- return head;
+ mkdirSync(join(shadow, ".git", "info"), { recursive: true });
+ const headRead = readHead(cwd, env, signal).catch(() => null);
+ const dirs = await scanCacheDirs(cwd, env, shadow, signal);
+ const head = (await headRead) ?? (await baseHead(cwd, env, signal));
+ const [staged, ignored] = await Promise.all([list(STAGED_LISTING), list(IGNORED_LISTING)]);
+ excludedCacheDirs.set(shadow, dirs);
+ return { head, staged, ignored };
}
type FolderNames = { exact: Set<string>; folded: Set<string> };
@@ -364,15 +560,8 @@ async function caseRenamed(cwd: string, paths: readonly string[]): Promise<boole
/** Would an incremental `git add -A` differ from a rebuilt index? Only when a tracked path became ignored or cache-tagged,
* a folder became or stopped being a nested repository, or a path was renamed by case only. */
-async function indexNeedsRebuild(cwd: string, env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<boolean> {
- const list = (args: string[]) => runGit(args, cwd, env, signal).catch((e: unknown) => {
- if (e instanceof GitTimeoutError || signal?.aborted) throw e;
- return null;
- });
- const ignored = await list(["ls-files", "--cached", "--ignored", "--exclude-standard", "-z"]);
- if (ignored === null || ignored.length > 0) return true;
- const staged = await list(["ls-files", "--stage", "-z"]);
- if (staged === null) return true;
+async function indexNeedsRebuild(cwd: string, { staged, ignored }: Prepared): Promise<boolean> {
+ if (ignored === null || ignored.length > 0 || staged === null) return true;
const paths: string[] = [];
const parents = new Set<string>();
for (const entry of staged.split("\0")) {
@@ -390,34 +579,95 @@ async function indexNeedsRebuild(cwd: string, env: NodeJS.ProcessEnv, signal?: A
return (process.platform === "darwin" || process.platform === "win32") && (await caseRenamed(cwd, paths));
}
-async function stageWorkTree(cwd: string, env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<void> {
- if (await indexNeedsRebuild(cwd, env, signal)) await runGit(["read-tree", "--empty"], cwd, env, signal);
- await runGit(["add", "-A", "--ignore-errors", "."], cwd, env, signal);
+/** A folder no snapshot has been made of is read whole, so its files go into one pack as they are read, not into an object
+ * file each: about twice as fast, and nothing left over to collect. Not for an index rebuilt over objects the shadow
+ * already holds: git compresses a file into the pack before it finds the object is there. */
+const WHOLE_PROJECT = { GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "core.bigFileThreshold", GIT_CONFIG_VALUE_0: "1" };
+
+async function stageWorkTree(cwd: string, env: NodeJS.ProcessEnv, prepared: Prepared, signal?: AbortSignal): Promise<void> {
+ const rebuild = await indexNeedsRebuild(cwd, prepared);
+ if (rebuild) await runGit(["read-tree", "--empty"], cwd, env, signal);
+ const unread = prepared.staged === "" && prepared.head.hash === prepared.head.base;
+ await runGit(["add", "-A", "--ignore-errors", "."], cwd, unread ? { ...env, ...WHOLE_PROJECT } : env, signal);
+}
+
+/** The checksum git ends its index file with: equal checksums are the same index, so the same tree. Null when there is none. */
+function indexChecksum(env: NodeJS.ProcessEnv): string | null {
+ let file: number | undefined;
+ try {
+ file = openSync(env.GIT_INDEX_FILE!, "r");
+ const size = fstatSync(file).size;
+ const end = Buffer.alloc(20);
+ if (size < 32 || readSync(file, end, 0, 20, size - 20) !== 20 || end.every((byte) => byte === 0)) return null;
+ return end.toString("hex");
+ } catch {
+ return null;
+ } finally {
+ if (file !== undefined) closeSync(file);
+ }
+}
+
+/** An index can name an object the shadow has lost (a collection of an earlier version, still running after its server,
+ * prunes what the next server stages). Read from nothing, the folder's files are all written again. */
+async function writeTree(cwd: string, env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<string> {
+ try {
+ return (await runGit(["write-tree"], cwd, env, signal)).trim();
+ } catch (e) {
+ if (e instanceof GitTimeoutError || signal?.aborted) throw e;
+ await runGit(["read-tree", "--empty"], cwd, env, signal);
+ await runGit(["add", "-A", "--ignore-errors", "."], cwd, env, signal);
+ return (await runGit(["write-tree"], cwd, env, signal)).trim();
+ }
}
+/** The index as the last finished snapshot left it, and that snapshot's tree. */
+const snapshotIndex = new Map<string, { checksum: string; tree: string }>();
+
type CommitResult = { hash: string; advanced: boolean; compacted: boolean };
-/** A partial capture never replaces the last usable checkpoint; with `pin`, the pin lands in the ref transaction that moves HEAD. */
-async function commitAll(cwd: string, env: NodeJS.ProcessEnv, head: Head, label: string, pin?: string, signal?: AbortSignal): Promise<CommitResult | null> {
+/** A partial capture never replaces the last usable checkpoint. With `pin`, the pin goes on the commit HEAD names while the
+ * folder is staged, and moves with HEAD in one ref transaction when the folder had changed. */
+async function commitAll(cwd: string, env: NodeJS.ProcessEnv, shadow: string, prepared: Prepared, label: string, pin?: string, signal?: AbortSignal): Promise<CommitResult | null> {
+ const { head } = prepared;
+ const early = pin !== undefined && head.base !== null;
+ const pinned = early ? runGit(["update-ref", liveRef(pin), head.hash], cwd, env).then(() => null, (e: unknown) => e) : null;
+ const unpin = async () => {
+ if (early && (await pinned) === null) await runGit(["update-ref", "-d", liveRef(pin)], cwd, env).catch(() => {});
+ };
try {
- await stageWorkTree(cwd, env, signal);
+ await stageWorkTree(cwd, env, prepared, signal);
} catch (e) {
+ await unpin();
+ dropIndexLock(env);
if (e instanceof GitTimeoutError) throw e;
return null;
}
- const tree = (await runGit(["write-tree"], cwd, env, signal)).trim();
- const changed = tree !== head.tree;
- let hash = head.hash;
- if (changed || head.base === null) {
- const base = head.base ?? (await runGit(["rev-list", "--max-parents=0", "HEAD"], cwd, env, signal)).trim();
- const message = changed ? label : (await runGit(["show", "-s", "--format=%B", "HEAD"], cwd, env, signal)).trim();
- // Parent only the empty marker: keeping the previous commit as an ancestor would retain every old tree.
- hash = (await runGit(["commit-tree", tree, "-p", base, "-m", message], cwd, env, signal)).trim();
+ try {
+ const pinFailure = await pinned;
+ if (pinFailure) throw pinFailure;
+ const staged = indexChecksum(env);
+ const last = snapshotIndex.get(shadow);
+ const tree = staged !== null && last?.checksum === staged ? last.tree : await writeTree(cwd, env, signal);
+ const changed = tree !== head.tree;
+ let hash = head.hash;
+ if (changed || head.base === null) {
+ const base = head.base ?? (await runGit(["rev-list", "--max-parents=0", "HEAD"], cwd, env, signal)).trim();
+ const message = changed ? label : (await runGit(["show", "-s", "--format=%B", "HEAD"], cwd, env, signal)).trim();
+ // Parent only the empty marker: keeping the previous commit as an ancestor would retain every old tree.
+ hash = (await runGit(["commit-tree", tree, "-p", base, "-m", message], cwd, env, signal)).trim();
+ }
+ const advanced = hash !== head.hash;
+ const updates = [advanced ? `update HEAD ${hash} ${head.hash}\n` : "", pin && (advanced || !early) ? `update ${liveRef(pin)} ${hash}\n` : ""].join("");
+ if (updates !== "") await runGit(["update-ref", "--stdin"], cwd, env, signal, updates);
+ // write-tree may have rewritten the index, so its checksum is read again.
+ const checksum = indexChecksum(env);
+ if (checksum === null) snapshotIndex.delete(shadow);
+ else snapshotIndex.set(shadow, { checksum, tree });
+ return { hash, advanced, compacted: advanced && head.base === null };
+ } catch (e) {
+ await unpin();
+ throw e;
}
- const advanced = hash !== head.hash;
- const updates = [advanced ? `update HEAD ${hash} ${head.hash}\n` : "", pin ? `update ${liveRef(pin)} ${hash}\n` : ""].join("");
- if (updates !== "") await runGit(["update-ref", "--stdin"], cwd, env, signal, updates);
- return { hash, advanced, compacted: advanced && head.base === null };
}
const commitsSinceGc = new Map<string, number>();
@@ -425,24 +675,42 @@ const commitsSinceGc = new Map<string, number>();
/** Packs grow between collections because `git add` writes files over core.bigFileThreshold straight into packs. */
const packBaselineKib = new Map<string, number>();
-/** Held until that turn's settled diff is queued, or until the next snapshot, which runs it first. */
-const pendingCollections = new Map<string, () => Promise<void>>();
+/** Held until that turn's settled diff is queued or its pin is released, whichever comes first. */
+const pendingCollections = new Map<string, (stop: AbortController) => Promise<void>>();
+
+/** A collection waiting its turn in the folder's queue or running; a snapshot or a settled diff stops it. */
+const collecting = new Map<string, AbortController>();
+/** Queued behind the folder's operations: runs what a snapshot has held by then. */
function releaseCollection(shadow: string): void {
- const collect = pendingCollections.get(shadow);
- if (collect === undefined) return;
- pendingCollections.delete(shadow);
- void serialize(shadow, collect);
+ if (collecting.get(shadow)?.signal.aborted === false) return;
+ const stop = new AbortController();
+ collecting.set(shadow, stop);
+ void serialize(shadow, async () => {
+ const collect = pendingCollections.get(shadow);
+ try {
+ if (collect === undefined || stop.signal.aborted) return;
+ pendingCollections.delete(shadow);
+ await collect(stop);
+ } finally {
+ if (collecting.get(shadow) === stop) collecting.delete(shadow);
+ }
+ }).catch(() => {});
+}
+
+/** Nobody's message or digest waits for a collection: one queued or running makes way, and is held again. */
+function yieldCollection(shadow: string): void {
+ collecting.get(shadow)?.abort();
}
-async function collectionDue(shadow: string, result: CommitResult, cwd: string, env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<boolean> {
+async function collectionDue(shadow: string, result: CommitResult, cwd: string, env: NodeJS.ProcessEnv): Promise<boolean> {
const freed = droppedPins.delete(shadow) || result.compacted;
if (!result.advanced && !freed) return false;
const commits = (commitsSinceGc.get(shadow) ?? 0) + (result.advanced ? 1 : 0);
commitsSinceGc.set(shadow, commits);
let due = freed || commits >= GC_EVERY_COMMITS;
if (!due) {
- const counted = await runGit(["count-objects", "-v"], cwd, env, signal).catch(() => "");
+ const counted = await runGit(["count-objects", "-v"], cwd, env).catch(() => "");
if (counted !== "") {
const field = (name: string) => Number(new RegExp(`^${name}: (\\d+)$`, "m").exec(counted)?.[1] ?? 0);
const pack = field("size-pack");
@@ -458,47 +726,106 @@ async function collectionDue(shadow: string, result: CommitResult, cwd: string,
return due;
}
-async function collectObsolete(cwd: string, env: NodeJS.ProcessEnv): Promise<void> {
+/** Prunes what was unreachable when it started and nothing newer: a collection this process no longer waits for (it died,
+ * or was restarted) can then never prune what a later git is writing. Windows ends a stopped git by force, with its locks
+ * left in place, so there a collection that has started runs to its end and the turn waits for it. */
+async function collectObsolete(shadow: string, cwd: string, env: NodeJS.ProcessEnv, stop: AbortController): Promise<void> {
+ const signal = process.platform === "win32" ? undefined : stop.signal;
+ const marker = join(shadow, ".git", COLLECTING);
+ const before = Math.floor(Date.now() / 1000);
try {
- await runGit(["reflog", "expire", "--expire=now", "--all"], cwd, env);
- await runGit(["gc", "--prune=now", "--quiet"], cwd, env);
+ writeFileSync(marker, String(before), { mode: 0o600 });
+ await runGit(["reflog", "expire", "--expire=now", "--all"], cwd, env, signal);
+ stop.signal.throwIfAborted();
+ await runGit(["gc", `--prune=${before}`, "--quiet"], cwd, env, signal);
} catch {
- console.warn("checkpoint cleanup deferred; the latest snapshot is preserved");
+ if (!stop.signal.aborted) console.warn("checkpoint cleanup deferred; the latest snapshot is preserved");
+ else if (!pendingCollections.has(shadow)) pendingCollections.set(shadow, (again) => collectObsolete(shadow, cwd, env, again));
+ } finally {
+ rmSync(marker, { force: true });
}
}
+function usableFolder(botId: string, cwd: string): { worktree: string; shadow: string } | null {
+ if (refusalReason(cwd) !== null) return null;
+ const folder = folderShadow(botId, cwd);
+ return folder === null || disabledFolders.has(folder.shadow) ? null : folder;
+}
+
/** Never throws. With `pin`, the commit stays reachable through later snapshots until release(pin). */
export async function snapshot(botId: string, cwd: string, label: string, signal?: AbortSignal, opts?: { pin?: string }): Promise<string | null> {
if (signal?.aborted) return null;
- if (disabledBots.has(botId)) return null;
if (!(await gitAvailable())) return null;
- if (refusalReason(cwd) !== null) return null;
- const folder = folderShadow(botId, cwd);
- if (folder === null || disabledFolders.has(folder.shadow)) return null;
+ const folder = usableFolder(botId, cwd);
+ if (folder === null) return null;
const { worktree, shadow } = folder;
try {
- // Collect ahead of this snapshot, so this turn's diff never queues behind GC.
- releaseCollection(shadow);
- return await serialize(shadow, async () => {
- const env = gitEnv(shadow, worktree);
- const head = await ensureShadow(worktree, env, shadow, signal);
- const result = await commitAll(worktree, env, head, label, opts?.pin, signal);
+ yieldCollection(shadow);
+ const env = gitEnv(shadow, worktree);
+ const hash = await serialize(shadow, async () => {
+ // A read-ahead this snapshot waited behind may have found the folder too big: the turn takes that answer.
+ if (disabledFolders.has(shadow)) return null;
+ const capture = async () => commitAll(worktree, env, shadow, await prepare(worktree, env, shadow, signal), label, opts?.pin, signal);
+ const result = await capture().catch(async (e: unknown) => {
+ if (e instanceof GitTimeoutError || signal?.aborted) throw e;
+ // Once more, without whatever lock a git stopped by force left behind.
+ await clearStaleLocks(shadow, 0);
+ return capture();
+ });
if (!result) return null;
- // Held for this turn's settled diff, so GC never eats into the digest's capture window.
- if (await collectionDue(shadow, result, worktree, env, signal)) {
- pendingCollections.set(shadow, () => collectObsolete(worktree, env));
- }
+ // Counted behind this snapshot, off the turn's path, and held for the turn's settled diff: GC never eats into the digest's capture window.
+ void serialize(shadow, async () => {
+ if (await collectionDue(shadow, result, worktree, env)) pendingCollections.set(shadow, (stop) => collectObsolete(shadow, worktree, env, stop));
+ }).catch(() => {});
return result.hash;
});
+ if (hash !== null) failedInARow.delete(shadow);
+ if (hash !== null && opts?.pin !== undefined) heldPins.set(shadow, (heldPins.get(shadow) ?? new Set()).add(opts.pin));
+ return hash;
} catch (e) {
if (signal?.aborted) return null;
const message = e instanceof Error ? e.message : String(e);
if (e instanceof GitTimeoutError) disableFolder(shadow, botId, worktree, message);
- else disable(botId, message);
+ else snapshotFailed(shadow, botId, worktree, message);
return null;
}
}
+/** Ahead of a turn: reads the folder into the shadow's index, so the turn's own snapshot finds its files already read.
+ * Moves no ref, so the last snapshot stays the newest. Never throws; only a timeout changes anything for later snapshots. */
+export async function prime(botId: string, cwd: string, signal?: AbortSignal): Promise<boolean> {
+ if (signal?.aborted || !(await gitAvailable())) return false;
+ const folder = usableFolder(botId, cwd);
+ if (folder === null) return false;
+ const { worktree, shadow } = folder;
+ const env = gitEnv(shadow, worktree);
+ return serialize(shadow, async () => {
+ try {
+ await stageWorkTree(worktree, env, await prepare(worktree, env, shadow, signal), signal);
+ await runGit(["write-tree"], worktree, env, signal);
+ return true;
+ } catch (e) {
+ dropIndexLock(env);
+ // Too big to read in the time a turn would give it: the turn must not wait that long again.
+ if (e instanceof GitTimeoutError && !signal?.aborted) disableFolder(shadow, botId, worktree, e.message);
+ return false;
+ }
+ });
+}
+
+/** Resolves once no git of this process is running or waiting on any of the bot's shadows: its folder can then be removed.
+ * A collection queued or running there is stopped first. */
+export async function quiet(botId: string): Promise<void> {
+ const mine = (shadow: string) => shadow.startsWith(join(CHECKPOINTS_DIR, botId) + sep);
+ for (const [shadow, stop] of collecting) if (mine(shadow)) stop.abort();
+ await Promise.all([...chains].filter(([shadow]) => mine(shadow)).map(([, tail]) => tail));
+}
+
+/** At shutdown: no collection is left running behind the server. */
+export function stopCollections(): void {
+ for (const stop of collecting.values()) stop.abort();
+}
+
/** Queued behind the shadow's pending operations, so a diff already queued still finds its commit. */
export async function release(botId: string, cwd: string, pin: string): Promise<void> {
if (!(await gitAvailable())) return;
@@ -507,7 +834,16 @@ export async function release(botId: string, cwd: string, pin: string): Promise<
const shadow = shadowDir(botId, worktree);
if (!existsSync(join(shadow, ".git", "HEAD"))) return;
const env = gitEnv(shadow, worktree);
- await serialize(shadow, () => runGit(["update-ref", "-d", liveRef(pin)], worktree, env));
+ const held = heldPins.get(shadow)?.delete(pin) ?? false;
+ await serialize(shadow, async () => {
+ const unpin = () => runGit(["update-ref", "-d", liveRef(pin)], worktree, env);
+ await unpin().catch(async () => {
+ await clearStaleLocks(shadow, 0);
+ await unpin();
+ });
+ });
+ // A turn that ended without a settled diff: the collection its snapshot held runs now.
+ if (held) releaseCollection(shadow);
} catch (e) {
console.warn(`checkpoint pin not released for bot ${botId}: ${e instanceof Error ? e.message : String(e)}`);
}
@@ -521,15 +857,20 @@ export interface CheckpointDiff {
export async function diffWorkingTree(botId: string, cwd: string, fromHash: string, signal?: AbortSignal): Promise<CheckpointDiff | null> {
if (signal?.aborted || !COMMIT_HASH.test(fromHash)) return null;
- if (disabledBots.has(botId) || !(await gitAvailable()) || refusalReason(cwd) !== null) return null;
- const folder = folderShadow(botId, cwd);
- if (folder === null || disabledFolders.has(folder.shadow)) return null;
+ if (!(await gitAvailable())) return null;
+ const folder = usableFolder(botId, cwd);
+ if (folder === null) return null;
const { worktree, shadow } = folder;
try {
+ yieldCollection(shadow);
const env = gitEnv(shadow, worktree);
const run = serialize(shadow, async () => {
- await ensureShadow(worktree, env, shadow, signal);
- await stageWorkTree(worktree, env, signal);
+ try {
+ await stageWorkTree(worktree, env, await prepare(worktree, env, shadow, signal), signal);
+ } catch (e) {
+ dropIndexLock(env);
+ throw e;
+ }
const out = await runGit(["diff", "--cached", "--name-status", "--no-renames", "-z", fromHash], worktree, env, signal);
const diff: CheckpointDiff = { changed: [], added: [], deleted: [] };
const fields = out.split("\0").filter((field) => field.length > 0);
diff --git a/server/cloud-credit-provider.ts b/server/cloud-credit-provider.ts
index 32f5d65f39..50f011334c 100644
--- a/server/cloud-credit-provider.ts
+++ b/server/cloud-credit-provider.ts
@@ -177,6 +177,7 @@ export class CloudCreditProvider {
},
adapter: {
...instance.adapter,
+ prestart: undefined, // every start goes through the check below
onEvent: listener => instance.adapter.onEvent(event => listener(this.plain(event))),
sendTurn: async input => {
const refused = blocked();
diff --git a/server/contracts.ts b/server/contracts.ts
index 5b40b99f6b..182a1c4608 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -334,6 +334,17 @@ export interface ProviderAdapter {
hold(threadId: ThreadId, until: number | null): boolean;
compact?(threadId: ThreadId, options: { instructions: string; session?: string; signal?: AbortSignal }): Promise<IdleCompactResult>;
};
+ /** 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`),
+ * and replaces it otherwise. `held`: one is launching or waiting. `drop` stops one that no turn took; a taken one is
+ * the turn's own. */
+ prestart?: {
+ start(input: SendTurnInput): Promise<boolean>;
+ held(threadId: ThreadId): boolean;
+ ready(threadId: ThreadId): boolean;
+ drop(threadId: ThreadId): void;
+ };
/** The engine's own count, by category, of what fills this thread's context window. null when the thread has no live
* engine process to ask or the engine gave no answer; never an estimate. */
contextBreakdown?(threadId: ThreadId, options?: { signal?: AbortSignal }): Promise<ContextBreakdown | null>;
diff --git a/server/crash-guard.ts b/server/crash-guard.ts
index 6c4f5925eb..a0caa4f399 100644
--- a/server/crash-guard.ts
+++ b/server/crash-guard.ts
@@ -36,6 +36,8 @@ export function withTurnScope<I extends Pick<ProviderInstance, "adapter">>(insta
(instance as { adapter: ProviderInstance["adapter"] }).adapter = {
...adapter,
sendTurn: (input) => runInTurn({ botId: input.botId ?? "", threadId: input.threadId }, () => adapter.sendTurn(input)),
+ // An engine started ahead of its first turn is that conversation's too: what it throws later belongs to the turn that took it.
+ ...(adapter.prestart ? { prestart: { ...adapter.prestart, start: (input) => runInTurn({ botId: input.botId ?? "", threadId: input.threadId }, () => adapter.prestart!.start(input)) } } : {}),
onEvent: (listener) => adapter.onEvent((event) => outsideTurn(() => listener(event))),
};
return instance;
diff --git a/server/delta-context.e2e.test.ts b/server/delta-context.e2e.test.ts
index 8a15eb4a98..a4c9f94dc1 100644
--- a/server/delta-context.e2e.test.ts
+++ b/server/delta-context.e2e.test.ts
@@ -60,7 +60,7 @@ async function fixture(test: (f: any) => Promise<void>, options: { env?: NodeJS.
"let botId = null;",
'try { for (const s of Object.values(JSON.parse(readFileSync(after("--mcp-config"), "utf8")).mcpServers ?? {})) botId = s?.env?.OMB_BOT_ID ?? botId; } catch {}',
`if (after("--resume") || after("--session-id")) appendFileSync(${JSON.stringify(launchesPath)}, JSON.stringify({ botId, pid: process.pid, resume: after("--resume"), sessionId: after("--session-id"), mode: process.env.FAKE_CLAUDE_MODE ?? "happy" }) + "\\n");`,
- `else if (argv[0] === "app-server") appendFileSync(${JSON.stringify(codexLaunchesPath)}, JSON.stringify({ botId: process.env.OMB_BOT_ID ?? null }) + "\\n");`,
+ `else if (argv[0] === "app-server") appendFileSync(${JSON.stringify(codexLaunchesPath)}, JSON.stringify({ botId: process.env.OMB_BOT_ID ?? null, pid: process.pid }) + "\\n");`,
`if (botId) process.env.FAKE_CLAUDE_PROMPTS = ${JSON.stringify(join(dataDir, "consumed-"))} + botId + ".jsonl";`,
// A warm Claude process ends once idle after its mode changed, like a CLI that exited, so the next turn launches under the new mode.
...(name === "claude" ? [
@@ -78,6 +78,21 @@ async function fixture(test: (f: any) => Promise<void>, options: { env?: NodeJS.
' setInterval(() => { if (idle && modeNow() !== launched) write("", () => process.exit(0)); }, 50).unref();',
"}",
] : []),
+ // A kept Codex app-server ends once idle after its mode changed, like one that exited, so the next turn launches under the new mode.
+ ...(name === "codex" ? [
+ 'if (argv[0] === "app-server") {',
+ ` const modeNow = () => existsSync(${JSON.stringify(modePath(name))}) ? readFileSync(${JSON.stringify(modePath(name))}, "utf8") : "";`,
+ " const launched = modeNow();",
+ " let idle = false;",
+ " const write = process.stdout.write.bind(process.stdout);",
+ " process.stdout.write = (chunk, ...rest) => {",
+ ` if (String(chunk).includes('"turn/completed"')) idle = true;`,
+ " return write(chunk, ...rest);",
+ " };",
+ ` process.stdin.on("data", (chunk) => { if (String(chunk).includes('"turn/start"')) idle = false; });`,
+ ' setInterval(() => { if (idle && modeNow() !== launched) write("", () => process.exit(0)); }, 50).unref();',
+ "}",
+ ] : []),
// A crashed fixture server must not leave a gated fake provider (or
// its stdio MCP child) alive after its temporary home is removed.
'process.stdin.on("end", () => process.exit(0));',
@@ -142,6 +157,7 @@ async function fixture(test: (f: any) => Promise<void>, options: { env?: NodeJS.
else rmSync(modePath(engine), { force: true });
const pid = engine === "claude" ? launches().at(-1)?.pid : undefined;
if (pid) await expect.poll(() => alive(pid), { timeout: 30_000 }).toBe(false);
+ if (engine === "codex") await expect.poll(() => jsonl(codexLaunchesPath).some((launch: any) => alive(launch.pid)), { timeout: 30_000 }).toBe(false);
};
const delegate = (key: string, to: any[], message: string, extra: Record<string, unknown> = {}) =>
({ steps: [{ arguments: { bot_ids: to.map((b) => b.id), request_key: key, message } }], reply: "Assigned", resumeReply: "Done", ...extra });
@@ -988,7 +1004,7 @@ it("does not offer a message the person stopped before any reply again on Codex"
await f.send("Warm up.");
await f.wait();
await f.send("CODEX_STOPPED_ASK please drop the staging database");
- await expect.poll(() => f.codexLaunches().length, { timeout: 15_000 }).toBe(2);
+ await expect.poll(() => f.codexCalls().filter((call: any) => call.method === "turn/start").length, { timeout: 15_000 }).toBe(2);
await f.api(`/api/bots/${f.chief.id}/interrupt`, { threadId: f.thread });
await f.idle();
f.open(f.gate("slow"));
@@ -1332,8 +1348,8 @@ it("moves a Codex chat to a new thread with its history when the person clears a
f.plan[f.chief.id] = { reply: "On high effort" };
await f.send("Think harder about this one.");
await f.wait();
- expect(f.codexCalls().filter((call: any) => call.method === "thread/resume")).toHaveLength(1);
- expect(f.codexCalls().find((call: any) => call.method === "turn/start")?.params.effort).toBe("high");
+ expect(f.codexCalls().filter((call: any) => call.method === "thread/start")).toHaveLength(1);
+ expect(f.codexCalls().filter((call: any) => call.method === "turn/start").at(-1)?.params.effort).toBe("high");
// turn/start cannot clear it: resuming would keep the thread on "high".
await f.selectModel(model);
diff --git a/server/digest.e2e.test.ts b/server/digest.e2e.test.ts
index 257cf75738..aa235c8199 100644
--- a/server/digest.e2e.test.ts
+++ b/server/digest.e2e.test.ts
@@ -1,5 +1,5 @@
-import { spawn, type ChildProcess } from "node:child_process";
-import { chmodSync, existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { execFileSync, spawn, type ChildProcess } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -161,4 +161,35 @@ posixOnly("work digest e2e (every fake engine)", () => {
expect(echoed).toContain("retry.ts");
await removeTempDir(project);
}, 60_000);
+
+ it("reads a project that holds a repository when the bot is set to it, and checkpoints the first turn on the folder as that turn finds it", async () => {
+ for (const left of [gate(), started()]) rmSync(left, { force: true });
+ const project = mkdtempSync(join(tmpdir(), "omb-digest-seeded-"));
+ writeFileSync(join(project, "README.md"), "hello");
+ mkdirSync(join(project, ".git"));
+ const created = (await api("POST", "/api/bots")).body.bot;
+ expect((await api("PATCH", `/api/bots/${created.id}`, { modelSelection: { instanceId: "gated", model: "fake-model" } })).status).toBe(200);
+ expect((await api("PATCH", `/api/bots/${created.id}`, { cwd: project })).status).toBe(200);
+
+ // no message yet: the folder is read into the bot's checkpoint, and no snapshot is taken
+ const shadows = join(home, ".openmausbot", "checkpoints", created.id);
+ const shadow = () => (existsSync(shadows) ? readdirSync(shadows) : []).map((name) => join(shadows, name, ".git")).find((dir) => existsSync(join(dir, "index")));
+ await waitFor(async () => shadow() !== undefined, "the project to be read ahead of the first message");
+ const shadowGit = (...args: string[]) => execFileSync("git", args, { encoding: "utf8", env: { ...process.env, GIT_DIR: shadow()! } }).trim();
+ expect(shadowGit("ls-files")).toBe("README.md");
+ expect(shadowGit("log", "--format=%s")).toBe("checkpoint base");
+
+ // the person edits the folder outside the app after it was read; the turn's own snapshot has that edit
+ writeFileSync(join(project, "notes.md"), "written by the person");
+ expect((await api("POST", `/api/bots/${created.id}/messages`, { text: "raise the retry limit" })).status).toBe(202);
+ await waitFor(async () => existsSync(started()), "the gated turn to reach the engine");
+ expect(shadowGit("show", "HEAD:notes.md")).toBe("written by the person");
+ writeFileSync(join(project, "retry.ts"), "export const RETRY_LIMIT = 5;");
+ writeFileSync(gate(), "go");
+ await waitFor(() => settled(created.id), "the gated turn to settle");
+ await waitFor(async () => (await getBot(created.id)).messages.some((m: Msg) => m.kind === "digest"), "digest with files");
+ const digest: Msg = (await getBot(created.id)).messages.find((m: Msg) => m.kind === "digest");
+ expect(digest.digest?.files).toMatchObject({ added: ["retry.ts"], changed: [] });
+ await removeTempDir(project);
+ }, 60_000);
});
diff --git a/server/drivers/claude-prestart.test.ts b/server/drivers/claude-prestart.test.ts
new file mode 100644
index 0000000000..058d294c3d
--- /dev/null
+++ b/server/drivers/claude-prestart.test.ts
@@ -0,0 +1,268 @@
+import { chmodSync, existsSync, mkdtempSync, readFileSync } 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 { ensureDirs } from "../config.ts";
+import type { ProviderInstance, SendTurnInput } from "../contracts.ts";
+import { recordEvents, type EventRecorder } from "../testing/events.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { ClaudeDriver } from "./claude.ts";
+import { claudePrestartTools } from "./claude-prestart.ts";
+import { PRESTART_IDLE_MS, armedIdleCount } from "./session-idle.ts";
+
+const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "testing", "fake-claude-cli.ts");
+
+const lines = (path: string): any[] => (existsSync(path) ? readFileSync(path, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : []);
+const alive = (pid: number): boolean => { try { process.kill(pid, 0); return true; } catch { return false; } };
+async function until(check: () => boolean, what: string, timeoutMs = 15_000): Promise<void> {
+ const deadline = Date.now() + timeoutMs;
+ while (!check()) {
+ if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`);
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+}
+
+describe("asking a started process to list its tools again", () => {
+ it("asks only for the servers that list through the harness, and is done when each answers", async () => {
+ const sent: any[] = [];
+ const tools = claudePrestartTools().forProcess(async (frame) => { sent.push(frame); return true; });
+ expect(sent.splice(0)).toEqual([{ type: "control_request", request_id: "prestart-ready", request: { subtype: "mcp_status" } }]);
+ expect(tools.ready).toBe(false);
+ expect(tools.frame({ type: "control_response", response: { subtype: "error", request_id: "prestart-ready", error_code: "unsupported_request" } })).toBe(true);
+ expect(tools.ready).toBe(true);
+ const done = tools.relist(["agents", "data", "ogb", "email"]);
+ expect(sent.map((frame) => frame.request)).toEqual([{ subtype: "mcp_reconnect", serverName: "data" }, { subtype: "mcp_reconnect", serverName: "email" }]);
+ expect(tools.frame({ type: "control_response", response: { subtype: "success", request_id: "someone-else" } })).toBe(false);
+ for (const frame of sent) expect(tools.frame({ type: "control_response", response: { subtype: "success", request_id: frame.request_id } })).toBe(true);
+ expect(await done).toBe(true);
+ expect(await tools.relist(["agents", "ogb"])).toBe(true);
+ });
+
+ it("is not usable after a failure, a frame that never left, a close, or a CLI that does not know the request", async () => {
+ const sent: any[] = [];
+ const engine = claudePrestartTools();
+ const tools = engine.forProcess(async (frame) => { sent.push(frame); return true; });
+ sent.splice(0);
+ const failed = tools.relist(["data"]);
+ tools.frame({ type: "control_response", response: { subtype: "error", request_id: sent[0].request_id, error: "Server not connected" } });
+ expect(await failed).toBe(false);
+ expect(engine.usable).toBe(true);
+ expect(await engine.forProcess(async () => false).relist(["data"])).toBe(false);
+ const closed = tools.relist(["device"]);
+ tools.close();
+ expect(await closed).toBe(false);
+ const unknown = tools.relist(["data"]);
+ tools.frame({ type: "control_response", response: { subtype: "error", request_id: sent.at(-1).request_id, error_code: "unsupported_request" } });
+ expect(await unknown).toBe(false);
+ expect(engine.usable).toBe(false);
+ });
+
+ it("gives up on a server that never answers", async () => {
+ vi.useFakeTimers();
+ try {
+ const waiting = claudePrestartTools().forProcess(async () => true, 3_000).relist(["data"]);
+ await vi.advanceTimersByTimeAsync(3_000);
+ expect(await waiting).toBe(false);
+ } finally { vi.useRealTimers(); }
+ });
+});
+
+describe("ClaudeDriver: a process started before the first message (fake CLI)", () => {
+ let instance: ProviderInstance;
+ let recorder: EventRecorder;
+ let scratch: string;
+ let launches: string, prompts: string, relists: string;
+ const halves = { system: "You are Testy.\n\nYour memory:\nlikes tea", systemStable: "You are Testy.", systemVolatile: "Your memory:\nlikes tea" };
+ const turn = (threadId: string, extra: Partial<SendTurnInput> = {}): SendTurnInput => ({ threadId, botId: "b1", text: "hi", model: "claude-sonnet-5", ...halves, ...extra });
+ const pids = () => lines(launches).map((launch) => launch.pid as number);
+ /** Launched, and running far enough to have said so: `count` processes in all so far. */
+ const started = async (threadId: string, count: number, extra: Partial<SendTurnInput> = {}) => {
+ const launched = await instance.adapter.prestart!.start(turn(threadId, { text: "", ...extra }));
+ if (launched) await until(() => pids().length >= count && instance.adapter.prestart!.ready(threadId), `process ${count} to start up`);
+ return launched;
+ };
+ const create = async (environment: Record<string, string> = {}) => {
+ instance = await ClaudeDriver.create({ instanceId: "claude-prestart", displayName: "Claude", environment, enabled: true, config: { cli: FAKE_CLI, permissionMode: "acceptEdits" } });
+ recorder = recordEvents(instance.adapter);
+ };
+
+ beforeEach(async () => {
+ ensureDirs();
+ chmodSync(FAKE_CLI, 0o755);
+ scratch = mkdtempSync(join(tmpdir(), "omb-prestart-test-"));
+ launches = join(scratch, "launches.jsonl"); prompts = join(scratch, "prompts.jsonl"); relists = join(scratch, "relists.jsonl");
+ process.env.FAKE_CLAUDE_LAUNCHES = launches;
+ process.env.FAKE_CLAUDE_PROMPTS = prompts;
+ process.env.FAKE_CLAUDE_MCP_RECONNECT = relists;
+ await create();
+ });
+
+ afterEach(async () => {
+ vi.useRealTimers();
+ delete process.env.FAKE_CLAUDE_LAUNCHES;
+ delete process.env.FAKE_CLAUDE_PROMPTS;
+ delete process.env.FAKE_CLAUDE_MCP_RECONNECT;
+ recorder?.stop();
+ await instance?.dispose();
+ await removeTempDir(scratch);
+ });
+
+ it("is taken by the first turn: one process in all, and the turn reads as a fresh launch's", async () => {
+ expect(await started("t-ahead", 1)).toBe(true);
+ expect(instance.adapter.prestart!.held("t-ahead")).toBe(true);
+ expect(instance.adapter.hasSession("t-ahead")).toBe(false);
+ expect(pids()).toHaveLength(1);
+ expect(recorder.events).toEqual([]);
+ expect(lines(prompts)).toEqual([]);
+
+ await instance.adapter.sendTurn(turn("t-ahead"));
+ await recorder.until((e) => e.type === "turn.completed" && e.threadId === "t-ahead");
+ expect(pids()).toHaveLength(1);
+ expect(instance.adapter.prestart!.held("t-ahead")).toBe(false);
+ expect(recorder.events.filter((e) => e.threadId === "t-ahead").map((e) => e.type).slice(0, 2)).toEqual(["turn.started", "session.started"]);
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+
+ await instance.adapter.sendTurn(turn("t-fresh"));
+ await recorder.until((e) => e.type === "turn.completed" && e.threadId === "t-fresh");
+ const [ahead, fresh] = lines(prompts);
+ expect(JSON.stringify(ahead.message.content)).toContain("likes tea");
+ expect(ahead).toEqual(fresh);
+
+ // The taken process is the conversation's own from here on: its next turn runs in it too.
+ await instance.adapter.sendTurn(turn("t-ahead", { text: "again" }));
+ await recorder.until((e) => e.type === "turn.completed" && e.threadId === "t-ahead" && recorder.events.filter((seen) => seen.type === "turn.completed" && seen.threadId === "t-ahead").length === 2);
+ expect(pids()).toHaveLength(2);
+ });
+
+ it("lists the harness-served tools again before the turn's message is written", async () => {
+ const data = { integrations: { data: { command: process.execPath, args: ["-e", ""], env: {} } } };
+ expect(await started("t-data", 1, data)).toBe(true);
+ expect(lines(relists)).toEqual([]);
+ await instance.adapter.sendTurn(turn("t-data", data));
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(lines(relists).map((frame) => frame.request)).toEqual([{ subtype: "mcp_reconnect", serverName: "data" }]);
+ expect(pids()).toHaveLength(1);
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+ });
+
+ it("is replaced, not used, when its tools cannot be listed again", async () => {
+ process.env.FAKE_CLAUDE_MCP_RECONNECT = "refuse";
+ await instance.dispose();
+ await create();
+ const data = { integrations: { data: { command: process.execPath, args: ["-e", ""], env: {} } } };
+ expect(await started("t-stale", 1, data)).toBe(true);
+ const [first] = pids();
+ await instance.adapter.sendTurn(turn("t-stale", data));
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(pids()).toHaveLength(2);
+ await until(() => !alive(first!), "the unused process to exit");
+ expect(recorder.events.filter((e) => e.type === "runtime.error" || e.type === "runtime.notice")).toEqual([]);
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+ });
+
+ it("is never started again on a CLI that does not know the request", async () => {
+ delete process.env.FAKE_CLAUDE_MCP_RECONNECT;
+ await instance.dispose();
+ await create();
+ const data = { integrations: { data: { command: process.execPath, args: ["-e", ""], env: {} } } };
+ expect(await started("t-old", 1, data)).toBe(true);
+ await instance.adapter.sendTurn(turn("t-old", data));
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(pids()).toHaveLength(2);
+ expect(await started("t-old-2", 3, data)).toBe(false);
+ expect(pids()).toHaveLength(2);
+ });
+
+ it("is closed and replaced by exactly one process when the turn's launch differs", async () => {
+ expect(await started("t-differs", 1)).toBe(true);
+ const [first] = pids();
+ await instance.adapter.sendTurn(turn("t-differs", { effort: "high" }));
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(pids()).toHaveLength(2);
+ await until(() => !alive(first!), "the unused process to exit");
+ expect(recorder.events.filter((e) => e.type === "runtime.error")).toEqual([]);
+ expect(recorder.events.filter((e) => e.type === "session.started")).toHaveLength(1);
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+ });
+
+ it("is replaced by a message that comes before it has started up: the turn never waits for it", async () => {
+ const launching = instance.adapter.prestart!.start(turn("t-race", { text: "" }));
+ const sent = instance.adapter.sendTurn(turn("t-race"));
+ await Promise.all([launching, sent]);
+ await recorder.until((e) => e.type === "turn.completed");
+ await until(() => pids().filter(alive).length === 1, "only the turn's own process to be left");
+ expect(instance.adapter.prestart!.held("t-race")).toBe(false);
+ expect(recorder.events.filter((e) => e.type === "session.started")).toHaveLength(1);
+ expect(recorder.events.filter((e) => e.type === "runtime.error")).toEqual([]);
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+ });
+
+ it("does not start beside a running turn or a second time", async () => {
+ await instance.adapter.sendTurn(turn("t-busy"));
+ expect(await started("t-busy", 1)).toBe(false);
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(await started("t-busy", 1)).toBe(false);
+ expect(await started("t-twice", 2)).toBe(true);
+ expect(await instance.adapter.prestart!.start(turn("t-twice", { text: "" }))).toBe(true);
+ expect(instance.adapter.prestart!.ready("t-twice")).toBe(true);
+ await instance.adapter.sendTurn(turn("t-twice"));
+ await recorder.until((e) => e.type === "turn.completed" && e.threadId === "t-twice");
+ expect(pids()).toHaveLength(2);
+ });
+
+ it("closes by itself when no message comes, having said nothing", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const before = armedIdleCount();
+ expect(await instance.adapter.prestart!.start(turn("t-unused", { text: "" }))).toBe(true);
+ expect(armedIdleCount()).toBe(before + 1);
+ vi.advanceTimersByTime(PRESTART_IDLE_MS - 1);
+ expect(instance.adapter.prestart!.held("t-unused")).toBe(true);
+ vi.advanceTimersByTime(1);
+ vi.useRealTimers();
+ await until(() => pids().length === 1 && !alive(pids()[0]!), "the unused process to exit");
+ await until(() => !instance.adapter.prestart!.held("t-unused"), "the driver to forget it");
+ expect(armedIdleCount()).toBe(before);
+ expect(recorder.events).toEqual([]);
+ expect(lines(prompts)).toEqual([]);
+ });
+
+ it("is stopped by a drop, while waiting and while still launching", async () => {
+ expect(await started("t-drop", 1)).toBe(true);
+ const launching = instance.adapter.prestart!.start(turn("t-drop-early", { text: "" }));
+ instance.adapter.prestart!.drop("t-drop-early");
+ instance.adapter.prestart!.drop("t-drop");
+ await launching;
+ await until(() => !instance.adapter.prestart!.held("t-drop") && !instance.adapter.prestart!.held("t-drop-early"), "the driver to forget them");
+ await until(() => pids().every((pid) => !alive(pid)), "every process to exit");
+ expect(recorder.events).toEqual([]);
+ // A drop never touches a process a turn has taken.
+ const before = pids().length;
+ expect(await started("t-taken", before + 1)).toBe(true);
+ await instance.adapter.sendTurn(turn("t-taken"));
+ instance.adapter.prestart!.drop("t-taken");
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+ });
+
+ it("is gone after the server shuts down or every engine is stopped", async () => {
+ expect(await started("t-shutdown", 1)).toBe(true);
+ await instance.adapter.stopAll();
+ await until(() => pids().every((pid) => !alive(pid)), "the process to exit after stopAll");
+ expect(await started("t-shutdown-2", 2)).toBe(true);
+ await instance.dispose();
+ expect(pids()).toHaveLength(2);
+ expect(pids().some(alive)).toBe(false);
+ expect(recorder.events).toEqual([]);
+ });
+
+ it("says nothing when it cannot start", async () => {
+ await instance.adapter.prestart!.start(turn("t-nowhere", { text: "", cwd: join(scratch, "no-such-folder") }));
+ await until(() => !instance.adapter.prestart!.held("t-nowhere"), "the driver to forget it");
+ expect(recorder.events).toEqual([]);
+ await instance.adapter.sendTurn(turn("t-nowhere"));
+ await recorder.until((e) => e.type === "turn.completed");
+ expect(recorder.events.find((e) => e.type === "turn.completed")).toMatchObject({ ok: true });
+ });
+});
diff --git a/server/drivers/claude-prestart.ts b/server/drivers/claude-prestart.ts
new file mode 100644
index 0000000000..5f30cdfb34
--- /dev/null
+++ b/server/drivers/claude-prestart.ts
@@ -0,0 +1,65 @@
+// A Claude process started before its conversation's first message connects its tool servers
+// at once. Some of OpenMausBot's own servers answer `tools/list` by asking the harness with the conversation's bearer, and
+// the harness honours a bearer only while a turn runs, so that process lists nothing from them. Before the first turn
+// takes the process it asks the CLI to connect those servers again ({type:"control_request", request:{subtype:
+// "mcp_reconnect", serverName}}, answered once the server is connected and listed; Claude Code 2.1.321), now that the turn
+// stands. A CLI that does not know the request cannot be started ahead at all.
+//
+// The CLI reads its input only once it has started up, and prints nothing until its first message. A control request
+// written at launch is therefore answered, whatever the answer, exactly when the process is ready for a message; a turn
+// that comes before that answer is quicker with a process of its own than waiting to ask this one twice.
+
+/** The tool servers whose `tools/list` the harness answers. */
+const LISTED_BY_HARNESS = new Set(["browser", "computer", "data", "email", "device"]);
+const ID_PREFIX = "prestart-tools-", READY_ID = "prestart-ready";
+const RECONNECT_WAIT_MS = 3_000;
+
+export function claudePrestartTools() {
+ let unsupported = false;
+ let sent = 0;
+ return {
+ /** False once a CLI refused the request: nothing more is started ahead on this engine until the server restarts. */
+ get usable(): boolean { return !unsupported; },
+ /** One process's requests. `write` settles true once the frame reached the CLI's stdin. */
+ forProcess(write: (frame: unknown) => Promise<boolean>, waitMs: number = RECONNECT_WAIT_MS) {
+ const pending = new Map<string, (ok: boolean) => void>();
+ const ask = (serverName: string): Promise<boolean> => new Promise((resolve) => {
+ const id = `${ID_PREFIX}${++sent}`;
+ const timer = setTimeout(() => settle(id, false), waitMs);
+ timer.unref?.();
+ pending.set(id, (ok) => { clearTimeout(timer); resolve(ok); });
+ void write({ type: "control_request", request_id: id, request: { subtype: "mcp_reconnect", serverName } }).then((delivered) => { if (!delivered) settle(id, false); });
+ });
+ const settle = (id: string, ok: boolean) => {
+ const resolve = pending.get(id);
+ pending.delete(id);
+ resolve?.(ok);
+ };
+ let ready = false;
+ void write({ type: "control_request", request_id: READY_ID, request: { subtype: "mcp_status" } });
+ return {
+ /** The CLI has started up and reads its input. */
+ get ready(): boolean { return ready; },
+ /** Consumes every answer to its own requests; false for every other frame. */
+ frame(o: any): boolean {
+ const id = o?.type === "control_response" ? o.response?.request_id : undefined;
+ if (id === READY_ID) return (ready = true);
+ if (typeof id !== "string" || !id.startsWith(ID_PREFIX)) return false;
+ if (o.response.subtype !== "success" && o.response.error_code === "unsupported_request") unsupported = true;
+ settle(id, o.response.subtype === "success");
+ return true;
+ },
+ /** True once every server of `mounted` that lists through the harness is connected again; false when one could
+ * not be, and the process must not be used. */
+ async relist(mounted: readonly string[]): Promise<boolean> {
+ const answers = await Promise.all(mounted.filter((name) => LISTED_BY_HARNESS.has(name)).map(ask));
+ return answers.every(Boolean);
+ },
+ close(): void {
+ for (const id of pending.keys()) settle(id, false);
+ },
+ };
+ },
+ };
+}
+export type ClaudePrestartTools = ReturnType<ReturnType<typeof claudePrestartTools>["forProcess"]>;
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index c84e593c9b..9c6cd89063 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -19,7 +19,7 @@ import { claudeBilling, claudeCallUsage } from "./claude-billing.ts";
import { claudeAuthFailure, claudeAuthRecovery, claudeOAuthExpired } from "./claude-auth-recovery.ts"; import { AWS_CREDENTIAL_ENV_KEYS, bedrockResultError, withBedrockCredentialError } from "./claude-bedrock-aws.ts";
import { CLAUDE_MODEL_ID, STATIC_CLAUDE_MODELS, claudeModelExtras, currentEngineCatalog, endpointModelCatalog, withCliVersionGate } from "./claude-model-extras.ts";
import { claudeOwnMcpOverHttp, withLoopbackNoProxy } from "./own-mcp-http.ts"; import { claudeAgentsMount, claudeToolSearchSetting } from "./claude-tool-search.ts"; import { claudeDisabledNativeSkillRules, unusableBuiltIns } from "./claude-unusable-tools.ts"; import { EMAIL_READ_TOOL_NAMES } from "../../shared/email.ts";
-import { claudeElicitations } from "./claude-elicitation.ts"; import { spawnContractDiff } from "./claude-spawn-contract.ts"; import { claudeContextUsage, liveContextBreakdown, writeControlFrame } from "./claude-context-usage.ts";
+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 { readCostHistory, recordCostState } from "./claude-cost-history.ts";
import { classifyResumeFailure, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";
import { ClaudeLoginController } from "./claude-login-auth.ts";
@@ -45,7 +45,7 @@ import { claudeApiError, claudeApiErrorMessage, claudeLimitError, claudeLimitFac
import { createOrgModelBlocks, modelSwapNotice, withOrgBlocks } from "./claude-model-access.ts";
import { engineHomes } from "../engine-homes/engine-homes.ts";
import { TEAM_TOOLS_FAILED, failedCustomMcp, teamToolsFailed } from "./team-tools.ts";
-import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose, stoppedForRoom } from "./session-idle.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 {
@@ -863,6 +863,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
} | null;
idleTimer: ReturnType<typeof setTimeout> | null;
closing: boolean;
+ /** Started before any message was sent (the adapter's `prestart`) and not yet taken by a turn: it says nothing in the chat.
+ * `take` makes the turn that takes it the one its launch is counted as. */
+ spare?: boolean;
+ take?: (turnId: string) => void;
+ tools?: ClaudePrestartTools;
/** The engine could not start the `agents` MCP server: retired after this turn so the next one reconnects. */
teamToolsFailed?: boolean;
stderr: string;
@@ -874,6 +879,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
const sessions = new Map<string, Session>();
const warmContracts = new Map<string, KeepWarmContract>();
const warmHolds = new Map<string, number>();
+ const spares = new Map<string, Promise<unknown>>(), spareTools = claudePrestartTools();
const sessionIdle = sessionIdlePolicy("CLAUDE");
const stopSession = (session: Session) => {
@@ -908,7 +914,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
s.broker = undefined;
broker?.close();
s.elicit.close();
- s.context.close();
+ s.context.close(); s.tools?.close();
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 insist
try {
@@ -921,7 +927,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (!s) return;
if (s.idleTimer) clearTimeout(s.idleTimer);
const held = (warmHolds.get(threadId) ?? 0) - Date.now();
- s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, "idle"), threadId, policy: sessionIdle, // per-chat
+ s.idleTimer = armIdleClose(`${instanceId}\0${threadId}`, s.spare ? PRESTART_IDLE_MS : Math.min(2_147_483_647, Math.max(engineIdleMs(threadId, sessionIdle), held)), { close: () => closeSession(threadId, s.spare ? "never used" : "idle"), threadId, policy: sessionIdle, spare: () => s.spare === true, // per-chat
idle: () => sessions.get(threadId) === s && !s.closing && !s.turn && !active.has(threadId), held: () => (warmHolds.get(threadId) ?? 0) > Date.now() });
};
// Keep-warm pings and warm summaries fork a thread's session with its live launch contract (claude-warm-summary.ts).
@@ -965,7 +971,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
});
const retryState = new Map<string, { attempt: number; cancelled: boolean; rebuilt?: boolean }>();
- const sendTurn = async (turn: SendTurnInput, logicalTurnId?: string) => {
+ /** `spare`: launch the thread's process as this turn would and stop there: nothing is written to it and no turn starts. */
+ const sendTurn = async (turn: SendTurnInput, logicalTurnId?: string, spare = false) => {
if (startupModelRefresh) await startupModelRefresh;
turn = { ...turn, toolScope: assertToolScopeSupported(DRIVER_KIND, turn.toolScope) };
if (config.managedModels && (!turn.model || !config.managedModels.includes(turn.model))) throw new Error("This model is not assigned to this workspace.");
@@ -976,6 +983,10 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
const { threadId, botId } = turn;
const relaunch = logicalTurnId !== undefined;
+ // A turn waits for a spare still launching, then takes it or replaces it below; a spare never starts beside a turn or another process.
+ const taken = () => sessions.has(threadId) || active.has(threadId) || retryState.has(threadId);
+ if (spare && taken()) return { turnId: "" };
+ if (!spare && spares.has(threadId)) await spares.get(threadId);
if (!relaunch) {
// taskkill is asynchronous on Windows: a turn sent right after Stop waits for the stopped
// process to be gone.
@@ -995,14 +1006,14 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
// Before any broker or process, so a bad attachment leaves nothing live.
const promptMsg = claudeUserMessage(turn.text, turn.images);
- const turnId = logicalTurnId ?? newId();
+ let turnId = logicalTurnId ?? newId();
const retryAbort = new AbortController();
const retry = retryState.get(threadId) ?? { attempt: 0, cancelled: false };
if (!relaunch) {
retry.cancelled = false;
retry.rebuilt = false;
}
- retryState.set(threadId, retry);
+ 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();
@@ -1150,7 +1161,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
const hookTokenPath = hooks ? hookTokenFile(threadId, botId) : null;
if (hooks && hookTokenPath) {
mkdirSync(dirname(hookTokenPath), { recursive: true, mode: 0o700 });
- writeFileAtomicIfChanged(hookTokenPath, hooks.token, { mode: 0o600, durable: false });
+ if (!spare) writeFileAtomicIfChanged(hookTokenPath, hooks.token, { mode: 0o600, durable: false });
env.OMB_HOOK_URL = hooks.url;
env.OMB_HOOK_TOKEN_FILE = hookTokenPath;
// in the packaged app process.execPath is Electron — run the helper as node
@@ -1191,9 +1202,13 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
})).digest("hex"),
});
+ // A process started ahead is taken once it has started up and has listed again the tools the harness serves only during a turn.
+ const ahead = sessions.get(threadId);
+ if (!spare && ahead?.spare && !ahead.closing && ahead.argsKey === argsKey && !(ahead.tools?.ready && await ahead.tools.relist(Object.keys(mcpServers)))) closeSession(threadId, "never used");
const live = sessions.get(threadId);
if (!turn.sessionReset && live && !live.turn && !live.closing && live.child.exitCode === null && live.argsKey === argsKey && (!sessionId || sessionId === live.sessionId)) {
stopIdleClose(`${instanceId}\0${threadId}`, live.idleTimer); // busy again: no longer idle
+ if (live.spare) { live.spare = false; live.take?.(turnId); appendNative(threadId, { dir: "out", source: "claude.session", msg: { took: "prestarted" } }); }
live.turn = { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, awaitingInit: true, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null };
active.set(threadId, { stop: () => {
if (live.turn) live.turn.stopRequested = true;
@@ -1219,7 +1234,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
return { turnId };
}
// 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" : "spawn contract changed", turn.sessionReset ? undefined : spawnContractDiff(live.argsKey, argsKey)); await stopEngineTree(live.child); }
+ if (live) { closeSession(threadId, turn.sessionReset ? "context reset" : "spawn contract changed", turn.sessionReset ? 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;
@@ -1238,7 +1253,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
removePrivateTempDir(systemPromptPath);
systemPromptPath = null;
}
- retryState.delete(threadId);
+ if (!spare) retryState.delete(threadId);
};
try {
@@ -1321,6 +1336,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
return { turnId };
}
+ if (spare && (taken() || ownHttp)) { cleanupUnownedLaunch(); return { turnId: "" }; }
let child: ReturnType<typeof spawnCli>;
try {
child = spawnCli(cliToLaunch(config.cli, launchCli), args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], box: { ...(broker ? { rw: [broker.socketPath] } : {}), ...(hookTokenPath ? { ro: [dirname(hookTokenPath)] } : {}) } }, "bot");
@@ -1346,14 +1362,14 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
mcpConfigPath,
systemPromptPath,
argsKey, cliVersion: cliHelpVersion, passedAutocompact,
- volatile: turn.systemVolatile ?? "", roster: { launched: turn.systemRoster ?? "", now: turn.systemRoster ?? "" },
+ volatile: spare ? null : turn.systemVolatile ?? "", roster: { launched: turn.systemRoster ?? "", now: turn.systemRoster ?? "" },
sessionId: sessionId ?? newSessionId,
sawInit: false,
nativePermissionMode: null,
replaysUserMessages,
- turn: { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null },
+ turn: spare ? null : { turnId, input: turn, retryAbort, settled: false, sawStreamDelta: false, pendingSteers: new Set(), deferred: null, continuationGrace: null, continuationSilence: null },
idleTimer: null,
- closing: false,
+ closing: false, spare, take: (taker) => { turnId = taker; }, ...(spare ? { tools: spareTools.forProcess((frame) => writeControlFrame(child.stdin, frame)) } : {}),
stderr: "",
costTotal: undefined,
};
@@ -1427,7 +1443,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
} catch {
return;
}
- if (session.context.frame(o)) return;
+ if (session.context.frame(o) || session.tools?.frame(o) || session.spare) return;
authRecovery.frame(threadId, o, session.costTotal);
// A replayed stdin message carries its images again: keep their bytes out of the log.
appendNative(threadId, { dir: "in", source: "claude.sdk.message", msg: o?.type === "user" && o.isReplay === true && o.message ? diagnosticClaudeUserMessage(o) : o });
@@ -1464,11 +1480,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (session.turn !== held || held.settled || !held.deferred) return;
if (held.stopRequested || session.closing) return;
held.continuationSilence = null;
- emit({
- ...base(threadId, held.turnId),
- type: "runtime.error",
- message: "Claude began a steered message but went silent; the turn was closed.",
- });
+ emit({ ...base(threadId, held.turnId), type: "runtime.error", message: "Claude began a steered message but went silent; the turn was closed." });
settleResult(held.deferred);
}, STEERED_CONTINUATION_SILENCE_MS * steerSilenceScale());
held.continuationSilence.unref?.();
@@ -1530,15 +1542,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
for (const b of Array.isArray(msg.content) ? msg.content : []) {
if (b.type === "tool_use") {
- emit({
- ...base(threadId, currentTurnId()),
- type: "item.started",
- itemType: "tool",
- itemId: b.id,
- title: b.name,
- summary: commandSummary(b.input),
- input: toolDetailPreview(b.input),
- });
+ emit({ ...base(threadId, currentTurnId()), type: "item.started", itemType: "tool", itemId: b.id, title: b.name, summary: commandSummary(b.input), input: toolDetailPreview(b.input) });
}
}
if (msg.usage) {
@@ -1678,6 +1682,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
});
child.on("error", (e) => {
+ if (session.spare) { session.broker?.close(); discardSession(threadId, session); return; }
emit({ ...base(threadId, currentTurnId()), type: "runtime.error", ...describeSpawnFailure(e, config.cli, cwd) });
settle(false, "spawn_error");
});
@@ -1689,7 +1694,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (!(await killCliTree(child, 0))) {
session.broker?.close();
session.broker = undefined;
- emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: "Claude could not be confirmed stopped; its helper processes may still be running." });
+ if (!session.spare) emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: "Claude could not be confirmed stopped; its helper processes may still be running." });
return;
}
if (closeFinalized) return;
@@ -1702,11 +1707,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (session.turn.continuationGrace) {
settleResult(held);
} else {
- emit({
- ...base(threadId, currentTurnId()),
- type: "runtime.error",
- message: `claude exited ${code} before result${session.stderr ? `: ${session.stderr.trim().slice(-300)}` : ""}`,
- });
+ emit({ ...base(threadId, currentTurnId()), type: "runtime.error", message: `claude exited ${code} before result${session.stderr ? `: ${session.stderr.trim().slice(-300)}` : ""}` });
settleResult({ ...held, ok: false, stopReason: "exit_before_result" });
}
} else if (session.turn && !session.turn.settled) {
@@ -1730,13 +1731,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (!endedBeforeTurn) {
retry.attempt++;
delayMs = computeBackoff(retry.attempt - 1);
- emit({
- ...base(threadId, turnId),
- type: "turn.retrying",
- attempt: retry.attempt,
- delayMs,
- reason: verdict.reason,
- });
+ emit({ ...base(threadId, turnId), type: "turn.retrying", attempt: retry.attempt, delayMs, reason: verdict.reason });
}
void (async () => {
const wait = interruptibleDelay(delayMs * retryScale, retryAbort.signal);
@@ -1744,13 +1739,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
if (retry.cancelled) {
active.delete(threadId);
retryState.delete(threadId);
- emit({
- ...base(threadId, turnId),
- type: "turn.completed",
- ok: false,
- stopReason: "interrupted",
- cost: null,
- });
+ emit({ ...base(threadId, turnId), type: "turn.completed", ok: false, stopReason: "interrupted", cost: null });
return;
}
retryState.set(threadId, retry);
@@ -1761,11 +1750,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
} catch (e) {
if (active.get(threadId)?.turnId === turnId) active.delete(threadId);
retryState.delete(threadId);
- emit({
- ...base(threadId, turnId),
- type: "runtime.error",
- message: e instanceof Error ? e.message : String(e),
- });
+ emit({ ...base(threadId, turnId), type: "runtime.error", message: e instanceof Error ? e.message : String(e) });
emit({
...base(threadId, turnId),
type: "turn.completed",
@@ -1840,6 +1825,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
void session.finishClose().finally(markClosed);
});
+ if (spare) { armIdle(threadId); return { turnId: "" }; }
const stop = () => {
if (session.turn) session.turn.stopRequested = true;
// taskkill is asynchronous on Windows: retire steering and approvals before the child submits more.
@@ -2041,6 +2027,20 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
hasSession: (threadId) => active.has(threadId),
enginePid: (threadId) => (active.has(threadId) ? sessions.get(threadId)?.child.pid : undefined),
cacheKeepWarm: forks.adapter,
+ prestart: {
+ start: (turn) => {
+ if (!spareTools.usable) return Promise.resolve(false);
+ const launch = sendTurn(turn, undefined, true).then(() => sessions.get(turn.threadId)?.spare === true, () => false).finally(() => { if (spares.get(turn.threadId) === launch) spares.delete(turn.threadId); });
+ spares.set(turn.threadId, launch);
+ return launch;
+ },
+ held: (threadId) => spares.has(threadId) || sessions.get(threadId)?.spare === true, ready: (threadId) => sessions.get(threadId)?.spare === true && sessions.get(threadId)?.tools?.ready === true,
+ drop: (threadId) => {
+ const close = () => { const s = sessions.get(threadId); if (s?.spare) { closeSession(threadId, "never used"); stopSession(s); } };
+ close();
+ void spares.get(threadId)?.then(close);
+ },
+ },
contextBreakdown: async (threadId, options) => liveContextBreakdown(sessions.get(threadId), options?.signal),
stopAll: async () => {
for (const { stop } of active.values()) stop();
diff --git a/server/drivers/codex-approval-config.ts b/server/drivers/codex-approval-config.ts
index fba57623cf..16f06e85f6 100644
--- a/server/drivers/codex-approval-config.ts
+++ b/server/drivers/codex-approval-config.ts
@@ -1,3 +1,6 @@
+import type { ApprovalMode } from "../../shared/approval-mode.ts";
+import { containsControlCharacter } from "./codex-app-approval.ts";
+
const plainRecord = (value: unknown): Record<string, unknown> | null =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
@@ -33,3 +36,116 @@ export function effectiveApprovalPolicy(value: unknown): unknown {
export function effectiveApprovalsReviewer(value: unknown): string {
return value === "auto_review" || value === "guardian_subagent" ? value : "user";
}
+
+export interface CodexApprovalParams {
+ thread: Record<string, unknown>;
+ turn: Record<string, unknown>;
+ /** Legacy settings for an older app-server that rejects the named-profile field. */
+ fallback?: Omit<CodexApprovalParams, "fallback">;
+}
+
+/** Codex persists these on its native thread, so they are explicit on start, resume and every turn.
+ * Codex has no narrower "edits only" sandbox, so a stray Edits value asks. */
+export function namedApprovalParams(mode: Exclude<ApprovalMode, "custom">): CodexApprovalParams {
+ if (mode === "full") {
+ return {
+ thread: {
+ approvalPolicy: "never",
+ approvalsReviewer: "user",
+ sandbox: "danger-full-access",
+ },
+ turn: {
+ approvalPolicy: "never",
+ approvalsReviewer: "user",
+ sandboxPolicy: { type: "dangerFullAccess" },
+ },
+ };
+ }
+ return {
+ thread: {
+ approvalPolicy: "on-request",
+ approvalsReviewer: mode === "auto" ? "auto_review" : "user",
+ sandbox: "workspace-write",
+ },
+ turn: {
+ approvalPolicy: "on-request",
+ approvalsReviewer: mode === "auto" ? "auto_review" : "user",
+ sandboxPolicy: { type: "workspaceWrite" },
+ },
+ };
+}
+
+export function withResolvedSandbox(params: CodexApprovalParams, session: unknown): CodexApprovalParams {
+ const requested = plainRecord(params.turn.sandboxPolicy);
+ if (!requested) return params;
+ const sandbox = plainRecord(plainRecord(session)?.sandbox);
+ if (!sandbox || typeof sandbox.type !== "string") {
+ throw new Error("Codex did not return its resolved sandbox policy. Update Codex, then retry; the turn was not started because its permissions could not be verified.");
+ }
+ if (sandbox.type !== requested.type) {
+ throw new Error("Codex did not apply the requested sandbox mode; cannot safely start the turn.");
+ }
+ return { ...params, turn: { ...params.turn, sandboxPolicy: sandbox } };
+}
+
+function legacyCustomApprovalParams(config: Record<string, unknown>): CodexApprovalParams {
+ const approvalPolicy = effectiveApprovalPolicy(config.approval_policy);
+ const approvalsReviewer = effectiveApprovalsReviewer(config.approvals_reviewer);
+ const sandbox = config.sandbox_mode === "workspace-write" ||
+ config.sandbox_mode === "danger-full-access" ||
+ config.sandbox_mode === "read-only"
+ ? config.sandbox_mode
+ : "read-only";
+ let sandboxPolicy: Record<string, unknown>;
+ if (sandbox === "danger-full-access") sandboxPolicy = { type: "dangerFullAccess" };
+ else if (sandbox === "read-only") sandboxPolicy = { type: "readOnly" };
+ else {
+ const workspace = config.sandbox_workspace_write && typeof config.sandbox_workspace_write === "object"
+ ? config.sandbox_workspace_write as Record<string, unknown>
+ : {};
+ sandboxPolicy = {
+ type: "workspaceWrite",
+ ...(Array.isArray(workspace.writable_roots) ? { writableRoots: workspace.writable_roots } : {}),
+ ...(typeof workspace.network_access === "boolean" ? { networkAccess: workspace.network_access } : {}),
+ ...(typeof workspace.exclude_slash_tmp === "boolean" ? { excludeSlashTmp: workspace.exclude_slash_tmp } : {}),
+ ...(typeof workspace.exclude_tmpdir_env_var === "boolean"
+ ? { excludeTmpdirEnvVar: workspace.exclude_tmpdir_env_var }
+ : {}),
+ };
+ }
+ return {
+ thread: { approvalPolicy, approvalsReviewer, sandbox },
+ turn: { approvalPolicy, approvalsReviewer, sandboxPolicy },
+ };
+}
+
+function configuredPermissionProfile(config: Record<string, unknown>): string | null {
+ if (typeof config.default_permissions !== "string") return null;
+ const profile = config.default_permissions.trim();
+ if (!profile || profile.length > 240 || containsControlCharacter(profile)) return null;
+ return profile;
+}
+
+export function customApprovalParams(raw: unknown): CodexApprovalParams {
+ const config = raw && typeof raw === "object" && !Array.isArray(raw)
+ ? raw as Record<string, unknown>
+ : {};
+ const fallback = legacyCustomApprovalParams(config);
+ const permissions = configuredPermissionProfile(config);
+ const approvalPolicy = effectiveApprovalPolicy(config.approval_policy);
+ const approvalsReviewer = effectiveApprovalsReviewer(config.approvals_reviewer);
+ // Codex 0.151 profiles define the sandbox but not the approval policy: reassert both approval
+ // fields so a resumed Full thread cannot keep `never`.
+ return permissions
+ ? {
+ thread: { permissions, approvalPolicy, approvalsReviewer },
+ turn: { permissions, approvalPolicy, approvalsReviewer },
+ fallback,
+ }
+ : fallback;
+}
+
+export function permissionProfileUnsupported(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : String(error);
+ return /(?:experimental api|invalid params|unknown field|unknown.*permissions|permissions.*(?:unsupported|sandbox)|cannot.*permissions)/i.test(message);
+}
diff --git a/server/drivers/codex-warm.test.ts b/server/drivers/codex-warm.test.ts
new file mode 100644
index 0000000000..8659f4335e
--- /dev/null
+++ b/server/drivers/codex-warm.test.ts
@@ -0,0 +1,141 @@
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+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 { armedIdleCount, sessionIdlePolicy } from "./session-idle.ts";
+
+const children: ChildProcessWithoutNullStreams[] = [];
+/** Stays up, and echoes each line it is sent. */
+const idleChild = () => {
+ const child = spawn(process.execPath, ["-e", "process.stdin.pipe(process.stdout); setInterval(() => {}, 1000);"], { stdio: ["pipe", "pipe", "pipe"] });
+ children.push(child);
+ 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,
+});
+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,
+});
+
+afterEach(async () => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ for (const child of children.splice(0)) {
+ if (child.exitCode !== null || child.signalCode !== null) continue;
+ const exited = once(child, "exit");
+ child.kill("SIGKILL");
+ await exited;
+ }
+});
+
+describe("a Codex app-server's launch contract", () => {
+ it("names what changed and never carries a value", () => {
+ const before = contract();
+ expect(codexContractDiff(before, contract())).toEqual([]);
+ expect(codexContractDiff(before, contract({ env: { PATH: "/nowhere", CODEX_HOME: "/nowhere", TOKEN: "second-secret", ADDED: "x" } }))).toEqual(["env:TOKEN", "env:ADDED"]);
+ expect(codexContractDiff(before, contract({ args: ["app-server"], cwd: "/other", thread: { model: "b" }, login: "someone", box: { box: { allowEnv: ["A"] } } })))
+ .toEqual(["args", "cwd", "box", "thread", "login"]);
+ expect(before).not.toContain("first-secret");
+ expect(codexConfigDigest({ mcp_servers: { a: { command: "x" }, b: { command: "y" } }, model: "m" }))
+ .toBe(codexConfigDigest({ model: "m", mcp_servers: { b: { command: "y" }, a: { command: "x" } } }));
+ expect(codexContractDiff(codexConfigDigest({ model: "m", plugins: { a: {} } }), codexConfigDigest({ model: "m", plugins: { a: { enabled: false } } }))).toEqual(["config:plugins"]);
+ expect(before).not.toContain("model=");
+ });
+
+ 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" }));
+ expect(codexLoginIdentity(login({ account_id: "account-1", access_token: "two" }))).toBe(first);
+ expect(codexLoginIdentity(login({ account_id: "account-2", access_token: "one" }))).not.toBe(first);
+ expect(codexLoginIdentity(JSON.stringify({ OPENAI_API_KEY: "key-1" }))).not.toBe(codexLoginIdentity(JSON.stringify({ OPENAI_API_KEY: "key-2" })));
+ expect(codexLoginIdentity(login({ access_token: "one" }))).not.toBe(codexLoginIdentity(login({ access_token: "two" })));
+ expect(codexLoginIdentity("{ half written")).not.toBe(first);
+ expect(codexLoginIdentity(null)).toBeNull();
+ });
+});
+
+describe("kept Codex app-servers", () => {
+ it("hand a process back only to its own conversation, contract and native thread", async () => {
+ const warm = codexWarmSessions<null>("instance-a");
+ const kept = session();
+ expect(warm.keep("thread-1", kept)).toBe(true);
+ expect(warm.take("thread-2", "{}", "native-1")).toBeNull();
+ expect(kept.connection.alive).toBe(true);
+ expect(warm.take("thread-1", "{}", "native-1")).toBe(kept);
+ expect(warm.has("thread-1")).toBe(false);
+
+ expect(warm.keep("thread-1", kept)).toBe(true);
+ expect(warm.take("thread-1", "{}", "native-2")).toBeNull();
+ await warm.retired();
+ expect(kept.connection.alive).toBe(false);
+
+ const other = session({ contract: contract() });
+ expect(warm.keep("thread-1", other)).toBe(true);
+ expect(warm.take("thread-1", contract({ cwd: "/other" }), "native-1")).toBeNull();
+ await warm.retired();
+ expect(other.connection.alive).toBe(false);
+ });
+
+ it("close an idle process after the idle time, and stop counting one that is taken or gone", async () => {
+ vi.spyOn(procs, "killCliTree").mockImplementation(async (child) => {
+ if (child.exitCode !== null || child.signalCode !== null) return true;
+ const exited = once(child, "exit");
+ child.kill("SIGKILL");
+ await exited;
+ return true;
+ });
+ const warm = codexWarmSessions<null>("instance-b");
+ const armedBefore = armedIdleCount();
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const taken = session(), idle = session(), dying = session();
+ warm.keep("taken", taken);
+ warm.keep("idle", idle);
+ warm.keep("dying", dying);
+ expect(armedIdleCount()).toBe(armedBefore + 3);
+ expect(warm.take("taken", "{}", "native-1")).toBe(taken);
+ const exited = once(dying.connection.child, "exit");
+ dying.connection.child.kill("SIGKILL");
+ await exited;
+ expect(warm.has("dying")).toBe(false);
+ expect(armedIdleCount()).toBe(armedBefore + 1);
+
+ vi.advanceTimersByTime(sessionIdlePolicy("CODEX").idleMs - 1);
+ expect(warm.has("idle")).toBe(true);
+ vi.advanceTimersByTime(1);
+ expect(warm.has("idle")).toBe(false);
+ vi.useRealTimers();
+ await warm.retired();
+ expect(idle.connection.alive).toBe(false);
+ expect(taken.connection.alive).toBe(true);
+ expect(armedIdleCount()).toBe(armedBefore);
+ });
+
+ it("refuse an app-server's request while no turn is running, and keep the thread's token total", async () => {
+ const warm = codexWarmSessions<null>("instance-c");
+ const kept = session();
+ const lines = createInterface({ input: kept.connection.child.stdout });
+ const replies: any[] = [];
+ lines.on("line", (line) => replies.push(JSON.parse(line)));
+ warm.keep("thread-1", kept);
+ // The child echoes, so what is written to it comes back as if the app-server had sent it.
+ kept.connection.write({ jsonrpc: "2.0", method: "thread/tokenUsage/updated", params: { threadId: "helper-thread", tokenUsage: { total: { inputTokens: 900, outputTokens: 900 } } } });
+ kept.connection.write({ jsonrpc: "2.0", method: "thread/tokenUsage/updated", params: { threadId: "native-1", tokenUsage: { total: { inputTokens: 14, outputTokens: 6, cachedInputTokens: 8 } } } });
+ kept.connection.write({ jsonrpc: "2.0", id: 100, method: "execCommandApproval", params: { command: "rm -rf scratch" } });
+ await expect.poll(() => replies.find((reply) => reply.id === 100 && reply.error)).toMatchObject({ error: { code: -32601 } });
+ expect(replies.some((reply) => reply.id === 100 && reply.result !== undefined)).toBe(false);
+ expect(kept.connection.usageTotal).toEqual({ input: 14, output: 6, cachedInput: 8 });
+ await warm.closeAll("test");
+ expect(kept.connection.alive).toBe(false);
+ });
+
+ it("keep nothing when switched off", () => {
+ vi.stubEnv("OMB_CODEX_SESSION_KEEP", "0");
+ const warm = codexWarmSessions<null>("instance-d");
+ expect(warm.keep("thread-1", session())).toBe(false);
+ vi.unstubAllEnvs();
+ });
+});
diff --git a/server/drivers/codex-warm.ts b/server/drivers/codex-warm.ts
new file mode 100644
index 0000000000..98c8e1e545
--- /dev/null
+++ b/server/drivers/codex-warm.ts
@@ -0,0 +1,321 @@
+import type { ChildProcessWithoutNullStreams } from "node:child_process";
+import { createHash } from "node:crypto";
+import { readFileSync, statSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+import { findCliCandidates } from "../env-path.ts";
+import { captureCliTree, killCliTree } from "../procs.ts";
+import { appendNative } from "./native.ts";
+import { armIdleClose, engineIdleMs, sessionIdlePolicy, stopIdleClose } from "./session-idle.ts";
+
+/** Codex 0.160.1 lists a table's entries (its plugins, its MCP servers) in a different order from one `config/read` to the
+ * next, so tables are compared with their keys in order. */
+const ordered = (value: unknown): unknown => Array.isArray(value) ? value.map(ordered)
+ : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => [key, ordered(entry)]))
+ : value;
+const digest = (value: unknown): string => createHash("sha256").update(JSON.stringify(ordered(value)) ?? "").digest("hex");
+
+/** A fingerprint of the effective configuration `config/read` returned, one per top-level setting. */
+export function codexConfigDigest(config: unknown): string {
+ const settings = config && typeof config === "object" && !Array.isArray(config) ? config as Record<string, unknown> : { config };
+ return JSON.stringify({ config: ordered(Object.fromEntries(Object.entries(settings).map(([name, value]) => [name, digest(value)]))) });
+}
+
+export interface CodexUsageTotal {
+ input: number;
+ output: number;
+ cachedInput: number;
+}
+
+/** What the turn that owns an app-server hears from it. */
+export interface CodexTurnLink {
+ message(message: any): void;
+ error(error: Error): void;
+ close(code: number | null, signal: NodeJS.Signals | null): void;
+}
+
+/** One `codex app-server` process and its NDJSON stream. Request ids and line framing belong to the process, so they
+ * outlive the turn that started it. */
+export class CodexConnection {
+ nextId = 1;
+ /** `config/read` replies, which carry the person's configuration. */
+ readonly sensitiveResponseIds = new Set<number>();
+ stderr = "";
+ /** Only stderr after the last protocol message can explain an exit. */
+ stderrSinceOutput = "";
+ /** The native thread's running token total (codex-cli 0.160.1 counts per app-server process). */
+ usageTotal: CodexUsageTotal | undefined;
+ /** The native thread a kept process has loaded. */
+ nativeThreadId: string | null = null;
+ /** Called once when the process exits with no turn attached. */
+ exitedIdle: (() => void) | null = null;
+ private link: CodexTurnLink | null = null;
+ private buffer = "";
+ private readonly asked = new Map<number, (result: unknown) => void>();
+ readonly child: ChildProcessWithoutNullStreams;
+
+ constructor(child: ChildProcessWithoutNullStreams) {
+ this.child = child;
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => this.read(chunk));
+ child.stderr.on("data", (chunk) => {
+ this.stderr = (this.stderr + chunk).slice(-8192);
+ this.stderrSinceOutput = (this.stderrSinceOutput + chunk).slice(-2048);
+ });
+ child.on("error", (error) => this.link?.error(error));
+ child.on("close", (code, signal) => this.link?.close(code, signal));
+ child.once("exit", () => { if (!this.link) this.exitedIdle?.(); });
+ }
+
+ get alive(): boolean {
+ return this.child.exitCode === null && this.child.signalCode === null;
+ }
+
+ attach(link: CodexTurnLink): void {
+ this.link = link;
+ this.stderr = "";
+ this.stderrSinceOutput = "";
+ }
+
+ detach(): void {
+ this.link = null;
+ }
+
+ /** A request of the connection's own, answered whether or not a turn is attached. Resolves undefined on an error
+ * reply; never resolves if the process exits first. */
+ ask(method: string, params: unknown): Promise<unknown> {
+ const id = this.nextId++;
+ if (method === "config/read") this.sensitiveResponseIds.add(id);
+ return new Promise((resolve) => {
+ this.asked.set(id, resolve);
+ this.write({ jsonrpc: "2.0", id, method, params });
+ });
+ }
+
+ write(message: unknown): void {
+ try {
+ this.child.stdin.write(JSON.stringify(message) + "\n");
+ } catch {}
+ }
+
+ private read(chunk: string): void {
+ this.buffer += chunk;
+ let newline: number;
+ while ((newline = this.buffer.indexOf("\n")) !== -1) {
+ const line = this.buffer.slice(0, newline);
+ this.buffer = this.buffer.slice(newline + 1);
+ if (!line.trim()) continue;
+ let message: any;
+ try {
+ message = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ this.stderrSinceOutput = "";
+ const answer = message?.id !== undefined && !message.method ? this.asked.get(message.id) : undefined;
+ if (answer) {
+ this.asked.delete(message.id);
+ answer(message.result);
+ } else if (this.link) this.link.message(message);
+ else this.unattended(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 {
+ 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;
+ }
+ 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 };
+ }
+}
+
+/** The Codex login a process started with, by account rather than by token: Codex rewrites auth.json when it renews
+ * a token (codex-cli 0.160.1), and that is no reason to start again. */
+export function codexLoginIdentity(stored: string | null): string | null {
+ if (stored === null) return null;
+ try {
+ const auth = JSON.parse(stored) as { auth_mode?: unknown; OPENAI_API_KEY?: unknown; tokens?: { account_id?: unknown } };
+ const account = auth.tokens?.account_id;
+ if (auth.tokens && typeof account !== "string") return digest(stored);
+ return digest({ mode: auth.auth_mode ?? null, key: auth.OPENAI_API_KEY ?? null, account: account ?? null });
+ } catch {
+ return digest(stored);
+ }
+}
+
+/** Which copy of the CLI a launch runs: an update in place replaces the file. */
+function cliIdentity(cli: string, path: string | undefined): string {
+ const at = findCliCandidates(cli, path ?? "")[0] ?? cli;
+ try {
+ const { mtimeMs, size } = statSync(at);
+ return `${at}:${mtimeMs}:${size}`;
+ } catch {
+ return at;
+ }
+}
+
+/** 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: {
+ cli: string;
+ args: readonly string[];
+ env: Record<string, string | undefined>;
+ cwd: string;
+ box: unknown;
+ 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,
+ cli: cliIdentity(parts.cli, parts.env.PATH),
+ args: digest(parts.args),
+ cwd: parts.cwd,
+ box: digest(parts.box),
+ thread: digest(parts.thread),
+ login: parts.login,
+ env: Object.fromEntries(Object.entries(parts.env).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, value]) => [name, digest(value)])),
+ });
+}
+
+/** The names of what changed between two contracts, never the values. */
+export function codexContractDiff(previous: string, next: string): string[] {
+ let before: Record<string, unknown>, after: Record<string, unknown>;
+ try {
+ before = JSON.parse(previous);
+ after = JSON.parse(next);
+ } catch {
+ return [];
+ }
+ const changed: string[] = [];
+ for (const field of new Set([...Object.keys(before), ...Object.keys(after)])) {
+ if (JSON.stringify(before[field]) === JSON.stringify(after[field])) continue;
+ const was = before[field], now = after[field];
+ if (!was || !now || typeof was !== "object" || typeof now !== "object") {
+ changed.push(field);
+ continue;
+ }
+ const old = was as Record<string, unknown>, current = now as Record<string, unknown>;
+ for (const name of new Set([...Object.keys(old), ...Object.keys(current)])) if (old[name] !== current[name]) changed.push(`${field}:${name}`);
+ }
+ return changed;
+}
+
+/** A process kept after a completed turn, with what its next turn needs to carry on. */
+export interface KeptCodex<Carried> {
+ connection: CodexConnection;
+ contract: string;
+ nativeThreadId: string;
+ /** The effective configuration the process reported when its last turn ended. Codex 0.160.1 adds its plugins and
+ * their MCP servers some time after it starts, so what it reports at start is not what it reports later. */
+ configDigest: string;
+ cwd: string;
+ carried: Carried;
+}
+
+/** `OMB_CODEX_SESSION_KEEP=0` ends every app-server with its turn. */
+const keepEnabled = (): boolean => process.env.OMB_CODEX_SESSION_KEEP !== "0";
+
+/**
+ * One provider account's kept app-servers, one per conversation (per-chat in session-idle.ts): a completed turn leaves
+ * its process up for the conversation's next turn, which then starts no process, MCP servers or native thread.
+ * Security invariant: a kept process is never handed to another conversation, and never to a turn whose contract differs.
+ */
+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>>();
+ const idleKey = (threadId: string) => `${instanceId}\0${threadId}`;
+
+ const forget = (threadId: string, why: string, contractChanged?: string[]) => {
+ const entry = kept.get(threadId);
+ if (!entry) return null;
+ kept.delete(threadId);
+ stopIdleClose(idleKey(threadId), entry.idleTimer);
+ appendNative(threadId, { dir: "out", source: "codex.session", msg: { close: why, ...(contractChanged?.length ? { contractChanged } : {}) } });
+ return entry.session;
+ };
+
+ /** Ends the whole tree: an app-server's MCP servers and shells can outlive it. */
+ const end = async (session: KeptCodex<Carried>): Promise<void> => {
+ const stopped = killCliTree(session.connection.child);
+ stopping.add(stopped);
+ try {
+ await stopped;
+ } finally {
+ stopping.delete(stopped);
+ }
+ };
+
+ const close = async (threadId: string, why: string, contractChanged?: string[]): Promise<void> => {
+ const session = forget(threadId, why, contractChanged);
+ if (session) await 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;
+ connection.detach();
+ connection.nativeThreadId = session.nativeThreadId;
+ void 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);
+ };
+ return true;
+ },
+
+ /** The conversation's kept process when it can serve this turn. Any other one is ended: `retired` resolves once
+ * it has exited. */
+ take(threadId: string, contract: string, nativeThreadId: string | null): KeptCodex<Carried> | null {
+ const entry = kept.get(threadId);
+ if (!entry) return null;
+ const { session } = entry;
+ if (session.connection.alive && session.contract === contract && session.nativeThreadId === nativeThreadId) {
+ kept.delete(threadId);
+ stopIdleClose(idleKey(threadId), entry.idleTimer);
+ return session;
+ }
+ const changed = codexContractDiff(session.contract, contract);
+ void close(threadId, changed.length ? "spawn contract changed" : "another native session", changed);
+ return null;
+ },
+
+ close,
+
+ /** Every kept process being ended has exited, so a new one may load its native thread. */
+ 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]);
+ },
+
+ has: (threadId: string): boolean => kept.has(threadId),
+ pid: (threadId: string): number | undefined => kept.get(threadId)?.session.connection.child.pid,
+ };
+}
diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.ts
index 23ada54935..3740ab18f7 100644
--- a/server/drivers/codex.test.ts
+++ b/server/drivers/codex.test.ts
@@ -800,7 +800,8 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
expect(recorder.events.at(-1)).toMatchObject({ type: "turn.completed", ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });
const seen = JSON.parse(readFileSync(dump, "utf8"));
- expect(processIsAlive(seen.pid)).toBe(false);
+ expect(processIsAlive(seen.pid)).toBe(true);
+ expect(instance.adapter.hasSession("t-codex")).toBe(false);
expect(seen.env.OPENAI_API_KEY).toBeUndefined();
expect(seen.env.BOX_TOKEN).toBeUndefined();
expect(seen.env.OMB_TTS_KEY).toBeUndefined();
@@ -2301,6 +2302,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
["company-codex-model", "company-codex-model", "openmaus_company"],
] },
])("reasserts the selected model and provider after $name app-server restarts", async ({ opts, selections }) => {
+ vi.stubEnv("OMB_CODEX_SESSION_KEEP", "0");
const token = vi.spyOn(ChatGptPlanAuthController.prototype, "accessToken").mockResolvedValue("synthetic-chatgpt-token");
const catalog = vi.spyOn(ChatGptPlanAuthController.prototype, "models").mockResolvedValue({
default: "gpt-6.1-sol", options: ["gpt-5.6-sol", "gpt-6.1-sol"].map(id => ({ id, label: id })),
@@ -2618,6 +2620,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
it("completes a turn whose process exit could not be confirmed without waiting for the stall watchdog", async () => {
await create();
vi.stubEnv("FAKE_CODEX_STOP_RETRY_MS", "50");
+ vi.stubEnv("OMB_CODEX_SESSION_KEEP", "0");
const stopping = vi.spyOn(procs, "killCliTree").mockResolvedValueOnce(false);
await instance.adapter.sendTurn({ threadId: "t-stop-unconfirmed", text: "hi" });
await expect(recorder.until((e) => e.type === "turn.completed", 10_000)).resolves.toMatchObject({ ok: true, stopReason: null });
@@ -2899,11 +2902,14 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
...(index > 0 ? { resumeCursor: "codex-thread-1" } : {}),
});
await expect(recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).resolves.toMatchObject({ ok: true });
+ // One app-server serves all three turns, so its calls add up: the rules are replaced once, when they change.
const calls = JSON.parse(readFileSync(dump, "utf8")).calls;
- const threadCall = calls.find((call: { method: string }) => call.method === (index ? "thread/resume" : "thread/start"));
- expect(threadCall.params.developerInstructions).toBe(`${system || "No OpenMausBot bot-specific instructions remain."}\n\nPrivate native rules.`);
- expect(calls.filter((call: { method: string }) => call.method === "thread/inject_items")).toHaveLength(index === 1 ? 1 : 0);
- expect(calls.find((call: { method: string }) => call.method === "turn/start").params.input).toEqual([{ type: "text", text: `message-${index}` }]);
+ expect(calls.filter((call: { method: string }) => call.method === "thread/resume")).toHaveLength(0);
+ expect(calls.find((call: { method: string }) => call.method === "thread/start").params.developerInstructions).toBe("Bot rules.\n\nPrivate native rules.");
+ const updates = calls.filter((call: { method: string }) => call.method === "thread/inject_items");
+ expect(updates).toHaveLength(index ? 1 : 0);
+ if (index) expect(JSON.stringify(updates[0].params)).toContain("No OpenMausBot bot-specific instructions remain.\\n\\nPrivate native rules.");
+ expect(calls.filter((call: { method: string }) => call.method === "turn/start").at(-1).params.input).toEqual([{ type: "text", text: `message-${index}` }]);
}
const nativeLog = readFileSync(join(NATIVE_DIR, `${threadId}.ndjson`), "utf8");
expect(nativeLog).toContain("[effective config omitted]");
@@ -3407,6 +3413,240 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
await recorder.until((e) => e.type === "turn.completed");
});
+ describe("an app-server kept between a conversation's turns", () => {
+ type Dump = { pid: number; env: Record<string, string>; calls: Array<{ method: string; params: any }> };
+ let dump: string;
+ const seen = (): Dump => JSON.parse(readFileSync(dump, "utf8"));
+ const methods = (name: string) => seen().calls.filter((call) => call.method === name);
+ const runTurn = async (input: Parameters<ProviderInstance["adapter"]["sendTurn"]>[0]) => {
+ const { turnId } = await instance.adapter.sendTurn(input);
+ const done = await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
+ return { turnId, done, events: recorder.events.filter((event) => event.turnId === turnId) };
+ };
+ const closes = (threadId: string): Array<{ close: string; contractChanged?: 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);
+ };
+
+ beforeEach(() => {
+ dump = join(scratch, "warm.json");
+ process.env.FAKE_CODEX_DUMP = dump;
+ mkdirSync(NATIVE_DIR, { recursive: true });
+ });
+
+ it("serves the next turn without a new process, handshake or native thread, and counts each turn's own tokens", async () => {
+ await create({ mode: "resume" });
+ const first = await runTurn({ threadId: "t-warm", text: "one" });
+ expect(first.done).toMatchObject({ ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });
+ const { pid } = seen();
+ expect(processIsAlive(pid)).toBe(true);
+ expect(instance.adapter.hasSession("t-warm")).toBe(false);
+ expect(instance.adapter.enginePid?.("t-warm")).toBeUndefined();
+
+ const second = await runTurn({ threadId: "t-warm", text: "two", resumeCursor: "codex-thread-1" });
+ expect(second.done).toMatchObject({ ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });
+ expect(seen().pid).toBe(pid);
+ expect(methods("initialize")).toHaveLength(1);
+ expect(methods("thread/start")).toHaveLength(1);
+ expect(methods("thread/resume")).toHaveLength(0);
+ expect(methods("turn/start").map((call) => [call.params.threadId, call.params.input])).toEqual([
+ ["codex-thread-1", [{ type: "text", text: "one" }]],
+ ["codex-thread-1", [{ type: "text", text: "two" }]],
+ ]);
+ expect(second.events.filter((event) => event.type === "turn.started")).toHaveLength(1);
+ expect(second.events.find((event) => event.type === "session.started")).toMatchObject({ sessionId: "codex-thread-1" });
+ expect(publishedMessages(second.events).map((message) => message.completed)).toEqual(["done from fake codex"]);
+
+ await instance.dispose();
+ expect(processIsAlive(pid)).toBe(false);
+ });
+
+ it.each([
+ ["model", { model: "gpt-other" }, "thread"],
+ ["approval mode", { approvalMode: "full" as const }, "thread"],
+ ["folder", { cwd: "elsewhere" }, "cwd"],
+ ["team tools credential", { integrations: { agents: { command: process.execPath, args: ["agents-proxy.js"], env: { OMB_TEST_BEARER: "second-bearer-secret" } } } }, "env:OMB_TEST_BEARER"],
+ ])("starts again when the turn's %s changed, after the kept process has exited", async (name, change, changed) => {
+ const threadId = `t-contract-${name.replaceAll(" ", "-")}`;
+ await create({ mode: "resume" });
+ const cwd = "cwd" in change ? join(scratch, change.cwd) : undefined;
+ if (cwd) mkdirSync(cwd);
+ const agents = { command: process.execPath, args: ["agents-proxy.js"], env: { OMB_TEST_BEARER: "first-bearer-secret" } };
+ await runTurn({ threadId, text: "one", integrations: { agents } });
+ const { pid } = seen();
+ const second = await runTurn({ threadId, text: "two", resumeCursor: "codex-thread-1", integrations: { agents }, ...change, ...(cwd ? { cwd } : {}) });
+ expect(second.done).toMatchObject({ ok: true });
+ expect(seen().pid).not.toBe(pid);
+ expect(processIsAlive(pid)).toBe(false);
+ expect(methods("thread/resume")).toHaveLength(1);
+ expect(second.events.some((event) => event.type === "turn.retrying" || event.type === "runtime.error")).toBe(false);
+ const [closed] = closes(threadId);
+ expect(closed.close).toBe("spawn contract changed");
+ expect(closed.contractChanged).toContain(changed);
+ expect(JSON.stringify(closed)).not.toContain("bearer-secret");
+ });
+
+ it("starts again for another native session, and never serves another conversation", async () => {
+ await create({ mode: "resume" });
+ await runTurn({ threadId: "t-own", text: "one" });
+ const { pid } = seen();
+ await runTurn({ threadId: "t-other", text: "one" });
+ const other = seen().pid;
+ expect(other).not.toBe(pid);
+ expect(processIsAlive(pid)).toBe(true);
+ await runTurn({ threadId: "t-own", text: "two", resumeCursor: "codex-thread-earlier" });
+ expect(seen().pid).not.toBe(pid);
+ expect(processIsAlive(pid)).toBe(false);
+ expect(methods("thread/resume")[0]!.params.threadId).toBe("codex-thread-earlier");
+ expect(closes("t-own")[0]!.close).toBe("another native session");
+ expect(processIsAlive(other)).toBe(true);
+ });
+
+ it("starts again, without a retry notice, when the person's Codex configuration changed between turns", async () => {
+ const rules = join(scratch, "native-rules.txt");
+ const log = join(scratch, "config-reads.log");
+ vi.stubEnv("FAKE_CODEX_INSTRUCTIONS_FILE", rules);
+ await create({ mode: "resume" });
+ vi.stubEnv("FAKE_CODEX_STARTUP_LOG", log);
+ await runTurn({ threadId: "t-config", text: "one", system: "Bot rules." });
+ const { pid } = seen();
+ // The kept process is asked for its configuration once more when its turn ends: the change comes after that.
+ await expect.poll(() => readFileSync(log, "utf8").trim().split("\n").map((line) => JSON.parse(line)).filter((entry) => entry.pid === pid && entry.event === "config/read")).toHaveLength(2);
+ writeFileSync(rules, "New native rules.");
+ const second = await runTurn({ threadId: "t-config", text: "two", system: "Bot rules.", resumeCursor: "codex-thread-1" });
+ expect(second.done).toMatchObject({ ok: true });
+ expect(seen().pid).not.toBe(pid);
+ expect(processIsAlive(pid)).toBe(false);
+ expect(methods("thread/resume")[0]!.params.developerInstructions).toBe("Bot rules.\n\nNew native rules.");
+ expect(second.events.filter((event) => event.type === "turn.started")).toHaveLength(1);
+ expect(second.events.some((event) => event.type === "turn.retrying" || event.type === "runtime.error")).toBe(false);
+ expect(closes("t-config")).toEqual([{ close: "configuration changed", contractChanged: ["config:developer_instructions"] }]);
+ });
+
+ it("starts again when config.toml changed, even while the last turn ran", async () => {
+ const home = join(scratch, "toml-home");
+ mkdirSync(home);
+ await create({ mode: "resume", environment: { HOME: scratch, CODEX_HOME: home } });
+ await runTurn({ threadId: "t-toml", text: "one" });
+ const { pid } = seen();
+ writeFileSync(join(home, "config.toml"), "model_reasoning_summary = \"auto\"\n");
+ await runTurn({ threadId: "t-toml", text: "two", resumeCursor: "codex-thread-1" });
+ expect(seen().pid).not.toBe(pid);
+ expect(closes("t-toml")).toEqual([{ close: "spawn contract changed", contractChanged: ["config"] }]);
+ });
+
+ it("resumes in a new process when the kept one died while idle", async () => {
+ await create({ mode: "resume" });
+ await runTurn({ threadId: "t-died", text: "one" });
+ const { pid } = seen();
+ process.kill(pid, "SIGKILL");
+ await expect.poll(() => closes("t-died").map((entry) => entry.close)).toEqual(["exited while idle"]);
+ const second = await runTurn({ threadId: "t-died", text: "two", resumeCursor: "codex-thread-1" });
+ expect(second.done).toMatchObject({ ok: true, usage: { input: 7, output: 3, cachedInput: 4 } });
+ expect(seen().pid).not.toBe(pid);
+ expect(methods("thread/resume")).toHaveLength(1);
+ expect(recorder.events.some((event) => event.type === "runtime.error" || event.type === "turn.retrying")).toBe(false);
+ });
+
+ it("resumes in a new process when the kept one dies as the next turn reaches it", async () => {
+ vi.stubEnv("FAKE_CODEX_DIE_ON_TURN", "2");
+ await create({ mode: "resume" });
+ await runTurn({ threadId: "t-race", text: "one" });
+ const { pid } = seen();
+ const second = await runTurn({ threadId: "t-race", text: "two", resumeCursor: "codex-thread-1" });
+ expect(second.done).toMatchObject({ ok: true });
+ expect(seen().pid).not.toBe(pid);
+ expect(methods("turn/start").map((call) => call.params.input)).toEqual([[{ type: "text", text: "two" }]]);
+ expect(second.events.filter((event) => event.type === "turn.started")).toHaveLength(1);
+ expect(second.events.some((event) => event.type === "runtime.error" || event.type === "turn.retrying")).toBe(false);
+ });
+
+ it("ends the process when a turn on it is stopped, and the next turn resumes in a new one", async () => {
+ const gate = join(scratch, "turn-gate");
+ writeFileSync(gate, "");
+ vi.stubEnv("FAKE_CODEX_COMMAND_GATE", gate);
+ await create({ mode: "resume" });
+ await runTurn({ threadId: "t-stop", text: "one" });
+ const { pid } = seen();
+ await removeTempDir(gate);
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-stop", text: "two", resumeCursor: "codex-thread-1" });
+ await expect.poll(() => methods("turn/start")).toHaveLength(2);
+ expect(instance.adapter.enginePid?.("t-stop")).toBe(pid);
+ await instance.adapter.interruptTurn("t-stop");
+ await expect(recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).resolves.toMatchObject({ ok: false, stopReason: "interrupted" });
+ expect(methods("turn/interrupt")).toHaveLength(1);
+ expect(processIsAlive(pid)).toBe(false);
+ writeFileSync(gate, "");
+ const third = await runTurn({ threadId: "t-stop", text: "three", resumeCursor: "codex-thread-1" });
+ expect(third.done).toMatchObject({ ok: true });
+ expect(seen().pid).not.toBe(pid);
+ });
+
+ it("answers a permission request on a later turn of the same process", async () => {
+ await create({ mode: "approval" });
+ for (const [index, text] of ["one", "two"].entries()) {
+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-ask", text, ...(index ? { resumeCursor: "codex-thread-1" } : {}) });
+ const opened = await recorder.until((event) => event.type === "request.opened" && event.turnId === turnId);
+ await instance.adapter.respondToRequest("t-ask", opened.requestId!, { behavior: "allow" });
+ await expect(recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).resolves.toMatchObject({ ok: true });
+ }
+ expect(methods("initialize")).toHaveLength(1);
+ expect(methods("turn/start")).toHaveLength(2);
+ });
+
+ it("does not keep a process whose turn failed", async () => {
+ vi.stubEnv("FAKE_CODEX_TRANSIENTS", "9");
+ vi.stubEnv("FAKE_CODEX_PARTIAL_FAILS", "1");
+ vi.stubEnv("FAKE_CODEX_STATE", join(scratch, "failed-launches"));
+ await create();
+ const failed = await runTurn({ threadId: "t-failed", text: "one" });
+ expect(failed.done).toMatchObject({ ok: false });
+ expect(processIsAlive(seen().pid)).toBe(false);
+ });
+
+ it("leaves no process once every engine is stopped", async () => {
+ await create();
+ await runTurn({ threadId: "t-shutdown-a", text: "one" });
+ const a = seen().pid;
+ await runTurn({ threadId: "t-shutdown-b", text: "one" });
+ const b = seen().pid;
+ expect([a, b].map(processIsAlive)).toEqual([true, true]);
+ await instance.adapter.stopAll();
+ expect([a, b].map(processIsAlive)).toEqual([false, false]);
+ });
+
+ it.skipIf(process.platform === "win32").each(["stopped", "killed while idle"])("leaves none of a kept process's children running once it is %s", async (how) => {
+ const childPid = join(scratch, "tool-server.pid");
+ const cli = join(scratch, "codex-with-tool-server.mjs");
+ writeFileSync(cli, [
+ "#!/usr/bin/env node",
+ 'import { spawn } from "node:child_process";',
+ 'import { writeFileSync } from "node:fs";',
+ 'if (process.argv[2] === "app-server" && process.env.FAKE_CODEX_TOOL_SERVER_PID) {',
+ ' const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });',
+ " writeFileSync(process.env.FAKE_CODEX_TOOL_SERVER_PID, String(child.pid));",
+ "}",
+ `await import(${JSON.stringify(new URL(`file://${FAKE_CLI}`).href)});`,
+ ].join("\n"), { mode: 0o755 });
+ await create({ cli });
+ vi.stubEnv("FAKE_CODEX_TOOL_SERVER_PID", childPid);
+ await runTurn({ threadId: "t-tree", text: "one" });
+ const root = seen().pid, child = Number(readFileSync(childPid, "utf8"));
+ expect([root, child].map(processIsAlive)).toEqual([true, true]);
+ if (how === "stopped") await instance.adapter.stopAll();
+ else process.kill(root, "SIGKILL");
+ await expect.poll(() => [root, child].map(processIsAlive), { timeout: 10_000 }).toEqual([false, false]);
+ });
+
+ it("ends every process with its turn when keeping is switched off", async () => {
+ vi.stubEnv("OMB_CODEX_SESSION_KEEP", "0");
+ await create();
+ await runTurn({ threadId: "t-off", text: "one" });
+ expect(processIsAlive(seen().pid)).toBe(false);
+ });
+ });
+
it("steers the running turn through turn/steer without killing the child", async () => {
const dump = join(scratch, "codex-steer.json");
process.env.FAKE_CODEX_DUMP = dump;
@@ -3429,7 +3669,8 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
await instance.adapter.respondToRequest("t-codex-steer", opened.requestId!, { behavior: "deny" });
await expect(recorder.until((e) => e.type === "turn.completed")).resolves.toMatchObject({ ok: true });
expect(recorder.events.some((e) => e.type === "runtime.error")).toBe(false);
- await expect.poll(() => processIsAlive(snapshot.pid), { timeout: 5_000 }).toBe(false);
+ await instance.dispose();
+ expect(processIsAlive(snapshot.pid)).toBe(false);
}, 20_000);
it("reports an explicitly refused steer as refused so the caller queues, and keeps the child alive", async () => {
@@ -3533,6 +3774,7 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)
it.each([false, true])("keeps ownership after an uncertain stop even when root close arrives (before failure: %s)", async (closeFirst) => {
await create();
+ vi.stubEnv("OMB_CODEX_SESSION_KEEP", "0");
const stopping = vi.spyOn(procs, "killCliTree").mockImplementation(async (child) => {
if (closeFirst && child.exitCode === null && child.signalCode === null) {
const closed = once(child, "close");
diff --git a/server/drivers/codex.ts b/server/drivers/codex.ts
index a4c104680e..7bc52272ea 100644
--- a/server/drivers/codex.ts
+++ b/server/drivers/codex.ts
@@ -55,7 +55,7 @@ import type { ApprovalMode } from "../../shared/approval-mode.ts";
import { CodexDeviceAuthController } from "./codex-device-auth.ts"; import { messageItem } from "../harness/text-items.ts";
import { codexAccountEmail, codexHome } from "./codex-identity.ts";
import { keepChatsOutOfCodexHistory, linkSharedCodexHome } from "./codex-shared-home.ts";
-import { containsControlCharacter, mcpAppApprovalForm, mcpAppApprovalText, mcpElicitationDeclined, plainRecord } from "./codex-app-approval.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 { keyRejected, noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";
@@ -65,7 +65,7 @@ import { parseProtocolAskQuestions, questionChoices } from "../../shared/ask-que
import { codexQuestionReply, openAsyncQuestion, type CodexAsk } from "./codex-questions.ts";
import { codexReleaseUpdate, codexUpdateCommand } from "./codex-update.ts";
export { codexUpdateCommand };
-import { effectiveApprovalPolicy, effectiveApprovalsReviewer } from "./codex-approval-config.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, 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 { 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";
@@ -111,13 +111,6 @@ function noteRenamedMcpServer(name: string, mountName: string): void {
console.error(`codex: MCP server ${JSON.stringify(name)} is mounted as ${JSON.stringify(mountName)} for this bot to keep its CLI configuration distinct`);
}
-interface CodexApprovalParams {
- thread: Record<string, unknown>;
- turn: Record<string, unknown>;
- /** Legacy settings for an older app-server that rejects the named-profile field. */
- fallback?: Omit<CodexApprovalParams, "fallback">;
-}
-
/** RequestPermissionProfile uses null for permission families that were not
* requested; GrantedPermissionProfile requires those keys to be absent. */
function grantedPermissions(raw: unknown): Record<string, unknown> {
@@ -157,112 +150,6 @@ function extendShellExclusions(policy: Record<string, unknown>, patterns: readon
]) };
}
-/** Codex persists these on its native thread, so they are explicit on start, resume and every turn.
- * Codex has no narrower "edits only" sandbox, so a stray Edits value asks. */
-function namedApprovalParams(mode: Exclude<ApprovalMode, "custom">): CodexApprovalParams {
- if (mode === "full") {
- return {
- thread: {
- approvalPolicy: "never",
- approvalsReviewer: "user",
- sandbox: "danger-full-access",
- },
- turn: {
- approvalPolicy: "never",
- approvalsReviewer: "user",
- sandboxPolicy: { type: "dangerFullAccess" },
- },
- };
- }
- return {
- thread: {
- approvalPolicy: "on-request",
- approvalsReviewer: mode === "auto" ? "auto_review" : "user",
- sandbox: "workspace-write",
- },
- turn: {
- approvalPolicy: "on-request",
- approvalsReviewer: mode === "auto" ? "auto_review" : "user",
- sandboxPolicy: { type: "workspaceWrite" },
- },
- };
-}
-
-function withResolvedSandbox(params: CodexApprovalParams, session: unknown): CodexApprovalParams {
- const requested = plainRecord(params.turn.sandboxPolicy);
- if (!requested) return params;
- const sandbox = plainRecord(plainRecord(session)?.sandbox);
- if (!sandbox || typeof sandbox.type !== "string") {
- throw new Error("Codex did not return its resolved sandbox policy. Update Codex, then retry; the turn was not started because its permissions could not be verified.");
- }
- if (sandbox.type !== requested.type) {
- throw new Error("Codex did not apply the requested sandbox mode; cannot safely start the turn.");
- }
- return { ...params, turn: { ...params.turn, sandboxPolicy: sandbox } };
-}
-
-function legacyCustomApprovalParams(config: Record<string, unknown>): CodexApprovalParams {
- const approvalPolicy = effectiveApprovalPolicy(config.approval_policy);
- const approvalsReviewer = effectiveApprovalsReviewer(config.approvals_reviewer);
- const sandbox = config.sandbox_mode === "workspace-write" ||
- config.sandbox_mode === "danger-full-access" ||
- config.sandbox_mode === "read-only"
- ? config.sandbox_mode
- : "read-only";
- let sandboxPolicy: Record<string, unknown>;
- if (sandbox === "danger-full-access") sandboxPolicy = { type: "dangerFullAccess" };
- else if (sandbox === "read-only") sandboxPolicy = { type: "readOnly" };
- else {
- const workspace = config.sandbox_workspace_write && typeof config.sandbox_workspace_write === "object"
- ? config.sandbox_workspace_write as Record<string, unknown>
- : {};
- sandboxPolicy = {
- type: "workspaceWrite",
- ...(Array.isArray(workspace.writable_roots) ? { writableRoots: workspace.writable_roots } : {}),
- ...(typeof workspace.network_access === "boolean" ? { networkAccess: workspace.network_access } : {}),
- ...(typeof workspace.exclude_slash_tmp === "boolean" ? { excludeSlashTmp: workspace.exclude_slash_tmp } : {}),
- ...(typeof workspace.exclude_tmpdir_env_var === "boolean"
- ? { excludeTmpdirEnvVar: workspace.exclude_tmpdir_env_var }
- : {}),
- };
- }
- return {
- thread: { approvalPolicy, approvalsReviewer, sandbox },
- turn: { approvalPolicy, approvalsReviewer, sandboxPolicy },
- };
-}
-
-function configuredPermissionProfile(config: Record<string, unknown>): string | null {
- if (typeof config.default_permissions !== "string") return null;
- const profile = config.default_permissions.trim();
- if (!profile || profile.length > 240 || containsControlCharacter(profile)) return null;
- return profile;
-}
-
-function customApprovalParams(raw: unknown): CodexApprovalParams {
- const config = raw && typeof raw === "object" && !Array.isArray(raw)
- ? raw as Record<string, unknown>
- : {};
- const fallback = legacyCustomApprovalParams(config);
- const permissions = configuredPermissionProfile(config);
- const approvalPolicy = effectiveApprovalPolicy(config.approval_policy);
- const approvalsReviewer = effectiveApprovalsReviewer(config.approvals_reviewer);
- // Codex 0.151 profiles define the sandbox but not the approval policy: reassert both approval
- // fields so a resumed Full thread cannot keep `never`.
- return permissions
- ? {
- thread: { permissions, approvalPolicy, approvalsReviewer },
- turn: { permissions, approvalPolicy, approvalsReviewer },
- fallback,
- }
- : fallback;
-}
-
-function permissionProfileUnsupported(error: unknown): boolean {
- const message = error instanceof Error ? error.message : String(error);
- return /(?:experimental api|invalid params|unknown field|unknown.*permissions|permissions.*(?:unsupported|sandbox)|cannot.*permissions)/i.test(message);
-}
-
/** Native instructions and image bytes stay out of diagnostics; the provider still gets the unmodified request. */
function codexNativeLogMessage(message: unknown): unknown {
if (!message || typeof message !== "object" || Array.isArray(message)) return message;
@@ -443,6 +330,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
pid?: number;
}
const active = new Map<string, Turn>();
+ const warm = codexWarmSessions<{ initialized: any; approvalParams: CodexApprovalParams; rolloutPath: unknown }>(instanceId);
const emit = (event: RuntimeEvent) => {
for (const l of Array.from(listeners)) l(event);
@@ -530,7 +418,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const waitForLaunchSlot = async (attempt: number) => {
const waiting: Turn = { stop: async () => { stopRequested = true; stopSignal.abort(); return true; }, turnId, asks: new Map() };
active.set(threadId, waiting);
- if (attempt === 0) emit({ ...base(threadId, turnId), type: "turn.started" });
+ if (attempt === 0 && !announced) emit({ ...base(threadId, turnId), type: "turn.started" });
announced = true;
emit({ ...base(threadId, turnId), type: "runtime.notice", message: `Waiting for a free Codex slot: ${codexLaunchesStarting()} Codex runs are starting on this computer. This one starts on its own.` });
const slot = await codexLaunchSlot(stopSignal.signal);
@@ -654,20 +542,26 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
) } };
const commandCwd = permissionLaunchCwd(turn.cwd ?? homedir());
- const releaseSlot = tryCodexLaunchSlot() ?? await waitForLaunchSlot(attempt);
+ // 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 } });
+ 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;
- const child = spawnHoldingSlot(releaseSlot, () => spawnCli(...codexLaunch(config.cli, appServerArgs), {
+ const connection = reused?.connection ?? new CodexConnection(spawnHoldingSlot(releaseSlot, () => spawnCli(...codexLaunch(config.cli, appServerArgs), {
cwd: turn.cwd ?? homedir(),
env,
stdio: ["pipe", "pipe", "pipe"], ...customBox,
- }, "bot"));
+ }, "bot")));
+ const child = connection.child;
let abandoned = false, resumedNativeThread = false;
let codexThreadId: string | null = null;
let codexTurnId: string | null = null;
let startingNativeTurn = false;
const earlyNotifications: any[] = [];
- const mcpStartup = mcpStartupTracker(child);
+ const mcpStartup = reused ? null : mcpStartupTracker(child);
+ let mcpFailed = false, keepable: { configDigest: string; cwd: string; carried: { initialized: any; approvalParams: CodexApprovalParams; rolloutPath: unknown } } | null = null;
const state = {
settled: false,
lastError: "",
@@ -683,17 +577,13 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
};
const asks = new Map<string, CodexAsk>();
- let nextId = 1;
- const sensitiveResponseIds = new Set<number>();
const rpcPending = new Map<number, {
resolve: (v: any) => void;
reject: (e: Error) => void;
}>();
const send = (obj: unknown) => {
- try {
- child.stdin.write(JSON.stringify(obj) + "\n");
- } catch {}
+ connection.write(obj);
appendNative(threadId, {
dir: "out",
source: "codex.app-server",
@@ -702,8 +592,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
};
const request = (method: string, params: unknown, timeoutMs = codexRpcTimeoutMs(method)) =>
new Promise<any>((resolve, reject) => {
- const id = nextId++;
- if (method === "config/read") sensitiveResponseIds.add(id);
+ const id = connection.nextId++;
+ if (method === "config/read") connection.sensitiveResponseIds.add(id);
// A wedged app-server can accept stdin and never reply.
const timer = setTimeout(() => {
if (rpcPending.delete(id)) reject(new Error(`codex ${method} timed out after ${timeoutMs}ms`));
@@ -786,6 +676,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
active.delete(threadId);
emit({ ...base(threadId, turnId), type: "turn.completed", ok, stopReason, cost: null, ...(state.usage ? { usage: state.usage } : {}) });
};
+ if (ok && contract && keepable && codexThreadId && !stopRequested && !abandoned && !disposed && !mcpFailed
+ && warm.keep(threadId, { connection, contract, nativeThreadId: codexThreadId, ...keepable })) return complete();
completeStoppedTurn = complete;
if (await stop()) return;
emit({ ...base(threadId, turnId), type: "runtime.error", message: "codex did not shut down after termination was requested" });
@@ -794,10 +686,10 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
};
// Retires this process before anything async, so a late rpc timer rejection cannot relaunch again.
- const relaunch = async (reason: string, failure: string, failedStop: string) => {
- const delayMs = computeBackoff(attempt);
- attempt++;
- emit({ ...base(threadId, turnId), type: "turn.retrying", attempt, delayMs, reason });
+ const relaunch = async (reason: string, failure: string, failedStop: string, quiet = false) => {
+ const delayMs = quiet ? 0 : computeBackoff(attempt);
+ if (quiet) announced = true;
+ else emit({ ...base(threadId, turnId), type: "turn.retrying", attempt: ++attempt, delayMs, reason });
abandoned = true;
releaseSlot();
const exited = child.exitCode !== null || child.signalCode !== null;
@@ -1015,7 +907,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const p = msg.params ?? {};
// MCP servers start with the thread, before it has an id; this process serves this turn alone.
if (msg.method === "mcpServer/startupStatus/updated") {
- mcpStartup.record(p);
+ mcpStartup?.record(p); mcpFailed ||= p.status === "failed" || p.status === "cancelled";
if (!teamToolsNoticed && teamToolsFailed(p)) {
teamToolsNoticed = true;
emit({ ...base(threadId, turnId), type: "runtime.notice", message: TEAM_TOOLS_FAILED });
@@ -1030,7 +922,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
if (!codexTurnId && msg.method === "thread/tokenUsage/updated" && p.tokenUsage?.total) {
// A total reported before this turn exists is what the process carried in: the baseline.
const t = p.tokenUsage.total;
- state.usageBaseline = { input: t.inputTokens ?? 0, output: t.outputTokens ?? 0, cachedInput: t.cachedInputTokens ?? 0 };
+ state.usageBaseline = connection.usageTotal = { input: t.inputTokens ?? 0, output: t.outputTokens ?? 0, cachedInput: t.cachedInputTokens ?? 0 };
return;
}
if (!codexTurnId) {
@@ -1162,7 +1054,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
});
if (t) {
const b = state.usageBaseline ?? { input: 0, output: 0, cachedInput: 0 };
- const now = shape(t);
+ const now = connection.usageTotal = shape(t);
state.usage = {
input: Math.max(0, now.input - b.input),
output: Math.max(0, now.output - b.output),
@@ -1222,55 +1114,29 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
}
};
- let buf = "";
- child.stdout.setEncoding("utf8");
- child.stdout.on("data", (chunk) => {
+ const message = (msg: any) => {
if (abandoned || state.settled) return;
- buf += chunk;
- let nl;
- while (!state.settled && !abandoned && (nl = buf.indexOf("\n")) !== -1) {
- const line = buf.slice(0, nl);
- buf = buf.slice(nl + 1);
- if (!line.trim()) continue;
- let msg: any;
- try {
- msg = JSON.parse(line);
- } catch {
- continue;
- }
- stderrSinceOutput = "";
- const loggedMessage = codexNativeIncomingLogMessage(msg, sensitiveResponseIds);
- appendNative(threadId, { dir: "in", source: "codex.app-server", msg: loggedMessage });
- if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
- const pend = rpcPending.get(msg.id);
- if (pend) {
- rpcPending.delete(msg.id);
- if (msg.error) pend.reject(new CodexRpcError(msg.error));
- else pend.resolve(msg.result);
- }
- } else if (msg.id !== undefined && msg.method) {
- handleServerRequest(msg);
- } else if (msg.method) {
- handleNotification(msg);
+ const loggedMessage = codexNativeIncomingLogMessage(msg, connection.sensitiveResponseIds);
+ appendNative(threadId, { dir: "in", source: "codex.app-server", msg: loggedMessage });
+ if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
+ const pend = rpcPending.get(msg.id);
+ if (pend) {
+ rpcPending.delete(msg.id);
+ if (msg.error) pend.reject(new CodexRpcError(msg.error));
+ else pend.resolve(msg.result);
}
+ } else if (msg.id !== undefined && msg.method) {
+ handleServerRequest(msg);
+ } else if (msg.method) {
+ handleNotification(msg);
}
- });
-
- let stderr = "";
- // Only stderr after the last protocol message can explain an exit; older bytes are context.
- let stderrSinceOutput = "";
- child.stderr.on("data", (c) => {
- stderr += c;
- stderrSinceOutput += c;
- if (stderr.length > 8192) stderr = stderr.slice(-8192);
- if (stderrSinceOutput.length > 2048) stderrSinceOutput = stderrSinceOutput.slice(-2048);
- });
- child.on("error", (e) => {
+ };
+ const error = (e: Error) => {
if (abandoned) return;
emit({ ...base(threadId, turnId), type: "runtime.error", ...describeSpawnFailure(e, config.cli, turn.cwd ?? homedir()) });
void settle(false, "spawn_error");
- });
- child.on("close", (code, signal) => {
+ };
+ const close = (code: number | null, signal: NodeJS.Signals | null) => {
if (abandoned) return;
if (state.settled) {
void stop();
@@ -1280,7 +1146,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
void settle(false, "interrupted");
return;
}
- const recentStderr = stderrSinceOutput.trim();
+ const recentStderr = connection.stderrSinceOutput.trim();
const hadStreamedOutput = codexTurnId !== null || state.sawStreamDelta;
// A signal exit (OOM, kill -9) is terminal whatever the stderr says; classifyError cannot see it.
const verdict =
@@ -1288,27 +1154,28 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
? { transient: false, reason: "interrupted" }
: classifyError({ exitCode: code, stderr: recentStderr });
const exitMessage = `codex exited ${code}${signal ? ` (signal ${signal})` : ""} before turn/completed${
- recentStderr ? `: ${recentStderr.slice(-300)}` : hadStreamedOutput && stderr.trim() ? "; no stderr after the last app-server output" : ""
+ recentStderr ? `: ${recentStderr.slice(-300)}` : hadStreamedOutput && connection.stderr.trim() ? "; no stderr after the last app-server output" : ""
}`;
// Relaunch only when turn/start was never acknowledged: a replay could re-run tools the user saw.
- if (!stopRequested && codexTurnId === null && earlyNotifications.length === 0 && verdict.transient && attempt < RETRY_MAX_ATTEMPTS - 1) {
- void relaunch(verdict.reason, exitMessage, "exit_before_result").catch(() => {});
+ if (!stopRequested && codexTurnId === null && earlyNotifications.length === 0 && (reused || (verdict.transient && attempt < RETRY_MAX_ATTEMPTS - 1))) {
+ void relaunch(verdict.reason, exitMessage, "exit_before_result", Boolean(reused)).catch(() => {});
return;
}
emit({ ...base(threadId, turnId), type: "runtime.error", message: exitMessage });
void settle(false, "exit_before_result");
- });
+ };
+ connection.attach({ message, error, close });
active.set(threadId, { stop, turnId, asks, steer: steerActiveTurn, pid: child.pid });
if (attempt === 0 && !announced) emit({ ...base(threadId, turnId), type: "turn.started" });
try {
- const initialized = await request("initialize", {
+ const initialized = reused ? reused.carried.initialized : await request("initialize", {
clientInfo: { name: "openmausbot", title: "OpenMausBot", version: serverVersion() },
// Named permission profiles are an experimental app-server field in Codex 0.151.
capabilities: { experimentalApi: true },
});
- send({ jsonrpc: "2.0", method: "initialized", params: {} });
+ if (!reused) send({ jsonrpc: "2.0", method: "initialized", params: {} });
// developerInstructions replaces, rather than appends to, native config.
let effectiveConfig: unknown;
try {
@@ -1326,6 +1193,10 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
: "Could not read Codex configuration; cannot safely update bot instructions. Retry after checking Codex.",
);
}
+ // config/read reads the files again (codex-cli 0.160.1); the loaded thread keeps what it started with.
+ const configDigest = codexConfigDigest(effectiveConfig);
+ if (reused && reused.configDigest !== configDigest) { appendNative(threadId, { dir: "out", source: "codex.session", msg: { close: "configuration changed", contractChanged: codexContractDiff(reused.configDigest, configDigest) } }); return relaunch("", "Codex configuration changed", "rpc_error", true); }
+ if (!reused) await warm.retired();
if (privateEnv.length || authBridge) {
const snapshot = (effectiveConfig as { features?: { shell_snapshot?: unknown } } | null)?.features?.shell_snapshot;
if (provenPrivateEnv || authBridge ? snapshot !== false : snapshot === true) {
@@ -1388,7 +1259,10 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
let startedModel: string | null = null;
// The plan refused the dropped session before anything ran, so replaying the chat repeats no side effects.
let { text: promptText, replayed: rebuiltFromReplay } = droppedUnsupportedSession ? recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure: "before-accept" }) : { text: turn.text, replayed: false };
- if (cursor) {
+ if (reused) {
+ codexThreadId = reused.nativeThreadId; approvalParams = reused.carried.approvalParams; resumedNativeThread = true;
+ rolloutAt = rolloutMark(reused.carried.rolloutPath); state.usageBaseline = connection.usageTotal;
+ } else if (cursor) {
const resumeThread = () => request("thread/resume", {
...selectionConfig,
threadId: cursor,
@@ -1477,7 +1351,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
];
const startTurn = () => {
promptSubmitted = true;
- startingNativeTurn = true;
+ startingNativeTurn = true; keepable = { configDigest, cwd: turn.cwd ?? homedir(), carried: { initialized, approvalParams, rolloutPath: rolloutAt?.path } };
return request("turn/start", {
threadId: codexThreadId,
input: turnInput,
@@ -1491,7 +1365,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
});
};
const waitNames = supportsMcpStartup(initialized?.userAgent) ? enabledMcpMounts([...selectedMcp.keys(), ...directMounts], effectiveConfig, turn.toolScope !== undefined) : [];
- const mcpReady = await mcpStartup.settled(waitNames, stopSignal.signal);
+ const mcpReady = !mcpStartup || await mcpStartup.settled(waitNames, stopSignal.signal);
if (!mcpReady || stopRequested || state.settled) return releaseSlot();
try {
await startTurn();
@@ -1511,6 +1385,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
const reported: ReturnType<typeof codexUserFailure> = refused ? { message: codexSignInExpired(raw) } : codexUserFailure(raw, route);
const needsAuth = refused || /(?:\b401\b|unauthorized|missing bearer|authentication required)/i.test(raw);
const verdict = classifyError(failure);
+ if (reused && !state.settled && !abandoned && !stopRequested && codexTurnId === null && earlyNotifications.length === 0) return relaunch("", reported.message, "rpc_error", true);
if (!state.settled && !abandoned && !recoveredMissingSession && !stopRequested && !needsAuth && codexTurnId === null && earlyNotifications.length === 0 && verdict.transient && attempt < RETRY_MAX_ATTEMPTS - 1 && state.sawStreamDelta === false) {
return relaunch(verdict.reason, reported.message, "rpc_error");
}
@@ -1642,7 +1517,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
signOut: async () => {
if (!planAuth) {
const mark = loginMark();
- await authentication.signOut();
+ await warm.closeAll("signed out"); await authentication.signOut();
loginAccepted(mark);
return;
}
@@ -1698,7 +1573,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
hasSession: (threadId) => active.has(threadId),
enginePid: (threadId) => active.get(threadId)?.pid,
stopAll: async () => {
- await Promise.all([...active.values()].map(({ stop }) => stop()));
+ await Promise.all([...active.values()].map(({ stop }) => stop())); await warm.closeAll("stopAll");
},
onEvent: (listener) => {
listeners.add(listener);
@@ -1710,7 +1585,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {
planGeneration++;
await authentication.dispose();
await planAuth?.dispose();
- await Promise.all([...active.values()].map(({ stop }) => stop()));
+ await Promise.all([...active.values()].map(({ stop }) => stop())); await warm.closeAll("dispose");
listeners.clear();
},
};
diff --git a/server/drivers/session-idle.test.ts b/server/drivers/session-idle.test.ts
index 3c0f0a6d92..958177c563 100644
--- a/server/drivers/session-idle.test.ts
+++ b/server/drivers/session-idle.test.ts
@@ -2,7 +2,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { forgetPresence, personAsks, sawThread, seenWithin } from "../thread-presence.ts";
import {
- armIdleClose, engineIdleMs, idleEnginesAllowed, keepWarm, sessionIdlePolicy, SMALL_BOX_IDLE_MS, stopIdleClose, UNWATCHED_IDLE_MS, warmEngineKeys,
+ armIdleClose, engineIdleMs, idleEnginesAllowed, keepWarm, PRESTART_IDLE_MS, PRESTART_MOST, prestartAllowed, sessionIdlePolicy, SMALL_BOX_BYTES, SMALL_BOX_IDLE_MS, stopIdleClose, sweepIdleEngines,
+ UNWATCHED_IDLE_MS, warmEngineKeys,
} from "./session-idle.ts";
const GB = 1024 ** 3;
@@ -161,3 +162,52 @@ describe("idle engines on a small box", () => {
}
});
});
+
+describe("engines started before a first message", () => {
+ const engine = (spare: boolean) => {
+ const state = { closed: 0 };
+ return { state, warm: { idle: () => true, close: () => { state.closed += 1; }, spare: () => spare, threadId: "t", policy: sessionIdlePolicy("CLAUDE", {}, DESKTOP) } };
+ };
+ afterEach(() => { for (const key of warmEngineKeys()) stopIdleClose(key, null); });
+
+ it("are for hosts where memory is not rationed: none on a small box, none where turns wait for room", () => {
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: false })).toBe(true);
+ expect(prestartAllowed({ bytes: SMALL_BOX_BYTES }, { enabled: false })).toBe(false);
+ expect(prestartAllowed({ bytes: GB }, { enabled: false })).toBe(false);
+ expect(prestartAllowed({ bytes: DESKTOP }, { enabled: true })).toBe(false);
+ });
+
+ it("wait no longer than an engine nobody is looking at is kept, and only a couple at once", () => {
+ expect(PRESTART_IDLE_MS).toBe(UNWATCHED_IDLE_MS);
+ expect(PRESTART_MOST).toBe(2);
+ });
+
+ it("close before any engine a turn has used when the box allows fewer idle engines", () => {
+ const [used, spare, later] = [engine(false), engine(true), engine(false)];
+ const fits = () => 2;
+ keepWarm("used", used.warm, { bytes: DESKTOP }, () => 8 * GB, fits);
+ keepWarm("spare", spare.warm, { bytes: DESKTOP }, () => 8 * GB, fits);
+ keepWarm("later", later.warm, { bytes: DESKTOP }, () => 8 * GB, fits);
+ expect([used.state.closed, spare.state.closed, later.state.closed]).toEqual([0, 1, 0]);
+ expect(warmEngineKeys()).toEqual(["used", "later"]);
+ });
+
+ it("close at once when room runs short, while a used engine keeps the time the room still allows", () => {
+ vi.useFakeTimers();
+ try {
+ const [used, spare] = [engine(false), engine(true)];
+ const timers = [armIdleClose("used", 600_000, used.warm, 1_000), armIdleClose("spare", PRESTART_IDLE_MS, spare.warm, 1_000)];
+ const roomy = { enabled: true, headroom: () => 1, roomFactor: () => 1, shortOfRoom: () => false };
+ expect(sweepIdleEngines(roomy, 2_000)).toBe(0);
+ const tight = { enabled: true, headroom: () => 0.9, roomFactor: () => 0.9, shortOfRoom: () => false };
+ sawThread("t", 2_000);
+ expect(sweepIdleEngines(tight, 2_000)).toBe(1);
+ expect([used.state.closed, spare.state.closed]).toEqual([0, 1]);
+ stopIdleClose("used", timers[0]!);
+ stopIdleClose("spare", timers[1]!);
+ } finally {
+ vi.useRealTimers();
+ forgetPresence();
+ }
+ });
+});
diff --git a/server/drivers/session-idle.ts b/server/drivers/session-idle.ts
index f4014be703..8e1008d8c7 100644
--- a/server/drivers/session-idle.ts
+++ b/server/drivers/session-idle.ts
@@ -79,6 +79,8 @@ export interface WarmEngine {
policy?: SessionIdlePolicy;
/** Kept on purpose until a time (a prompt-cache keep-warm): only a shortage of room closes it before then. */
held?: () => boolean;
+ /** Started before any message and not yet used by a turn: the first to close when room is short. */
+ spare?: () => boolean;
}
/** Idle engines of every driver, the longest idle first. */
@@ -94,12 +96,15 @@ export function keepWarm(key: string, engine: WarmEngine, box: Pick<BoxMemory, "
for (const [other, warm] of warmEngines) if (other !== key && (!warm.idle() || warm.held?.())) warmEngines.delete(other);
const extra = warmEngines.size - idleEnginesAllowed(box, available(), most);
if (extra <= 0) return;
- for (const [other, warm] of [...warmEngines].slice(0, extra)) {
+ for (const [other, warm] of sparesFirst([...warmEngines]).slice(0, extra)) {
warmEngines.delete(other);
warm.close();
}
}
+const sparesFirst = (engines: Array<[string, WarmEngine]>): Array<[string, WarmEngine]> =>
+ [...engines.filter(([, warm]) => warm.spare?.()), ...engines.filter(([, warm]) => !warm.spare?.())];
+
/** Every per-chat engine idle now, with when it went idle: what the sweep looks at again. */
const armed = new Map<string, { engine: WarmEngine; since: number; timer: ReturnType<typeof setTimeout> }>();
@@ -134,7 +139,7 @@ export function sweepIdleEngines(memory: Pick<EngineMemory, "enabled" | "headroo
// No longer idle (a turn took it again, or it ended): its driver arms it again when it next goes idle.
if (!engine.idle()) { armed.delete(key); continue; }
if (!engine.threadId || !engine.policy || (engine.held?.() && !short)) continue;
- if (now - since < engineIdleMs(engine.threadId, engine.policy, { enabled: true, headroom: () => factor, roomFactor: () => factor }, now)) continue;
+ if (!engine.spare?.() && now - since < engineIdleMs(engine.threadId, engine.policy, { enabled: true, headroom: () => factor, roomFactor: () => factor }, now)) continue;
armed.delete(key);
warmEngines.delete(key);
engine.close();
@@ -156,6 +161,18 @@ const WATCHED_MS = 30 * 60_000;
/** A thread nobody has in front of them (a teammate's delegated work, a routine) keeps its engine this long. */
export const UNWATCHED_IDLE_MS = 30_000;
+/** An engine started before any message (a person just made a conversation) waits this long for the first one: the time
+ * an engine nobody is looking at is already kept, and longer than writing a first line usually takes. */
+export const PRESTART_IDLE_MS = UNWATCHED_IDLE_MS;
+/** Each waiting engine holds 250 to 450 MB, so only this many wait at once. */
+export const PRESTART_MOST = 2;
+
+/** Engines start ahead of a message only where memory is not rationed: never on a small box, and never where turns wait
+ * for room (a Cloud home, a self-hosted server), whose admission counts the engines a turn starts. */
+export function prestartAllowed(box: Pick<BoxMemory, "bytes"> = boxMemory(), memory: Pick<EngineMemory, "enabled"> = engineMemory): boolean {
+ return !memory.enabled && box.bytes > SMALL_BOX_BYTES;
+}
+
/**
* How long one conversation's idle engine (per-chat) stays up after a turn. Where turns wait for room (a Cloud home, a
* self-hosted Linux server): briefly for a thread no person has had in front of them lately, and for the one they have,
diff --git a/server/engine-homes/engine-homes.ts b/server/engine-homes/engine-homes.ts
index 954793f7fd..7a8ff52452 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.prestart ? { prestart: { ...adapter.prestart, start: (input) => homes.within(input.threadId, () => adapter.prestart!.start(input), input.botId) } } : {}),
...(warm ? { cacheKeepWarm: {
...warm,
ping: (threadId, options) => homes.within(threadId, () => warm.ping(threadId, options)),
diff --git a/server/engine-memory.ts b/server/engine-memory.ts
index 48c8207d25..49b5b2c2df 100644
--- a/server/engine-memory.ts
+++ b/server/engine-memory.ts
@@ -802,6 +802,8 @@ export function withEngineMemory(instance: ProviderInstance, memory: EngineMemor
};
(instance as { adapter: ProviderAdapter }).adapter = {
...adapter,
+ // Admission counts the engines turns start: none starts ahead of one here.
+ prestart: undefined,
onEvent: (listener) => {
listeners.add(listener);
const off = adapter.onEvent((item) => { for (const shown of present(item)) listener(shown); });
diff --git a/server/engine-prestart.test.ts b/server/engine-prestart.test.ts
new file mode 100644
index 0000000000..b7d72e8664
--- /dev/null
+++ b/server/engine-prestart.test.ts
@@ -0,0 +1,191 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { SendTurnInput } from "./contracts.ts";
+import { PRESTART_IDLE_MS, PRESTART_MOST } from "./drivers/session-idle.ts";
+import { createEnginePrestart, type EnginePrestartDeps, type SessionCredentials } from "./engine-prestart.ts";
+
+const FIRST = "11111111-aaaa-4aaa-8aaa-111111111111";
+const NEXT = "22222222-bbbb-4bbb-8bbb-222222222222";
+
+/** What index.ts keeps for a conversation's bearer, as its sessionBearer writes it. */
+const grantsOf = (threadId: string, kind: string, approval: unknown) => JSON.stringify({ botId: "bot", threadId, kind, createdBots: 0, openedThreads: 0, approval });
+
+function host(overrides: Partial<EnginePrestartDeps> = {}) {
+ const credentials: SessionCredentials = new Map([[FIRST, new Map([
+ ["bot agents", { grants: grantsOf(FIRST, "agents", "full"), token: "a".repeat(48) }],
+ ["bot data", { grants: grantsOf(FIRST, "data", "full"), token: "d".repeat(48) }],
+ ])]]);
+ const started: SendTurnInput[] = [], dropped: string[] = [];
+ const held = new Set<string>();
+ const state = { allowed: true, blank: true, busy: false, refused: false, shape: "sonnet/full" as string | null, up: true, folder: `/work/bot/${NEXT}` as string | null };
+ const prestart = createEnginePrestart({
+ adapter: (id) => (id === "claude" ? { prestart: {
+ start: async (input) => { started.push(input); if (state.up) held.add(input.threadId); return state.up; },
+ held: (threadId) => held.has(threadId), ready: (threadId) => held.has(threadId),
+ drop: (threadId) => { dropped.push(threadId); held.delete(threadId); },
+ } } : undefined),
+ credentials,
+ allowed: () => state.allowed, blank: () => state.blank, busy: () => state.busy, refused: () => state.refused,
+ shape: () => state.shape, approval: () => "full", folder: () => state.folder,
+ ...overrides,
+ });
+ return { prestart, credentials, started, dropped, held, state };
+}
+
+const firstTurn = (extra: Partial<SendTurnInput> = {}): SendTurnInput => ({
+ threadId: FIRST, botId: "bot", text: "the first message", model: "claude-sonnet-5", approvalMode: "full", cwd: `/work/bot/${FIRST}`,
+ resumeCursor: "session-1", systemStable: "You are Testy.", systemVolatile: "Busy: no", system: "You are Testy.\n\nBusy: no",
+ integrations: {
+ agents: { command: "node", args: ["agents.js"], env: { OMB_THREAD_ID: FIRST, OMB_COMMS_TOKEN: "a".repeat(48) } },
+ data: { command: "node", args: ["proxy.js", "data"], env: { OMB_MCP_TOKEN_DATA: "d".repeat(48) } },
+ },
+ ...extra,
+});
+
+describe("starting a new conversation's engine from the bot's last launch", () => {
+ beforeEach(() => { vi.useFakeTimers(); });
+ afterEach(() => { vi.useRealTimers(); });
+
+ it("starts it as the last launch, for the new conversation's id, folder and bearers, with no message and no session to resume", () => {
+ const { prestart, credentials, started } = host();
+ const input = firstTurn();
+ expect(prestart.note("claude", input, true)).toBe(input);
+ prestart.threadMade("bot", NEXT);
+ expect(started).toHaveLength(1);
+ const launch = started[0]!;
+ expect(launch).toMatchObject({ threadId: NEXT, botId: "bot", text: "", model: "claude-sonnet-5", approvalMode: "full", cwd: `/work/bot/${NEXT}`, systemStable: "You are Testy." });
+ expect(launch.resumeCursor).toBeUndefined();
+ const bearers = credentials.get(NEXT)!;
+ expect(bearers.get("bot agents")!.grants).toBe(grantsOf(NEXT, "agents", "full"));
+ expect(launch.integrations!.agents!.env).toEqual({ OMB_THREAD_ID: NEXT, OMB_COMMS_TOKEN: bearers.get("bot agents")!.token });
+ expect(launch.integrations!.data!.env).toEqual({ OMB_MCP_TOKEN_DATA: bearers.get("bot data")!.token });
+ expect(new Set([bearers.get("bot agents")!.token, bearers.get("bot data")!.token, "a".repeat(48), "d".repeat(48)]).size).toBe(4);
+ expect(JSON.stringify(launch)).not.toContain(FIRST);
+ expect(credentials.get(FIRST)!.get("bot agents")!.token).toBe("a".repeat(48));
+ });
+
+ it("keeps a bearer the conversation already holds for the same grants", () => {
+ const { prestart, credentials, started } = host();
+ credentials.set(NEXT, new Map([["bot agents", { grants: grantsOf(NEXT, "agents", "full"), token: "n".repeat(48) }]]));
+ prestart.note("claude", firstTurn(), true);
+ prestart.threadMade("bot", NEXT);
+ expect(started[0]!.integrations!.agents!.env.OMB_COMMS_TOKEN).toBe("n".repeat(48));
+ });
+
+ it.each([
+ ["the host does not start engines ahead (a small box, a Cloud home)", { allowed: false }],
+ ["the conversation already has a message", { blank: false }],
+ ["a turn is already being set up there", { busy: true }],
+ ["a first message would be refused (paused, over a limit, signed out)", { refused: true }],
+ ["its model, approval level or folder differs from the last launch's", { shape: "opus/ask" }],
+ ["its folder is not where the last launch's would be", { folder: "/elsewhere" }],
+ ["it has no folder of its own", { folder: null }],
+ ])("starts nothing when %s", (_why, change) => {
+ const { prestart, credentials, started, state } = host();
+ prestart.note("claude", firstTurn(), true);
+ Object.assign(state, change);
+ prestart.threadMade("bot", NEXT);
+ expect(started).toEqual([]);
+ expect(prestart.waiting()).toEqual([]);
+ expect(credentials.has(NEXT)).toBe(false);
+ });
+
+ it("starts nothing for a bot with no launch to go by, for the conversation the launch came from, or on another engine's adapter", () => {
+ const { prestart, started } = host();
+ prestart.threadMade("bot", NEXT);
+ prestart.note("claude", firstTurn(), true);
+ prestart.threadMade("other-bot", NEXT);
+ prestart.threadMade("bot", FIRST);
+ prestart.note("codex", firstTurn(), true);
+ prestart.threadMade("bot", NEXT);
+ expect(started).toEqual([]);
+ });
+
+ it.each([
+ ["a turn no person sent", {}, false],
+ ["a person's own MCP server", { integrations: { custom: { mine: { command: "x", args: [] } } } }, true],
+ ["a browser", { integrations: { browser: { command: "node", args: [], env: {} } } }, true],
+ ["a computer", { integrations: { localComputer: { command: "node", args: [], env: {} } } }, true],
+ ["connected apps", { integrations: { composio: { command: "node", args: [], env: {} } } }, true],
+ ["a guest's confinement", { guestConfined: true }, true],
+ ["a tool selection", { toolScope: { servers: [] } }, true],
+ ["the person's own Claude MCP configuration", { mcpFromUserConfig: true }, true],
+ ])("does not go by a launch with %s, and forgets the one before it when a person sent it", (_what, extra, person) => {
+ const { prestart, started } = host();
+ prestart.note("claude", firstTurn(), true);
+ prestart.note("claude", firstTurn(extra as Partial<SendTurnInput>), person);
+ prestart.threadMade("bot", NEXT);
+ expect(started).toHaveLength(person ? 0 : 1);
+ });
+
+ it("keeps only a couple waiting at once, and counts one again once it was taken or is gone", () => {
+ const { prestart, started, held } = host({ folder: (_bot, threadId) => `/work/bot/${threadId}` });
+ prestart.note("claude", firstTurn(), true);
+ const made = ["t-1", "t-2", "t-3"];
+ for (const threadId of made) prestart.threadMade("bot", threadId);
+ expect(started.map((launch) => launch.threadId)).toEqual(made.slice(0, PRESTART_MOST));
+ held.delete("t-1");
+ prestart.threadMade("bot", "t-3");
+ expect(started.map((launch) => launch.threadId)).toEqual(["t-1", "t-2", "t-3"]);
+ prestart.threadMade("bot", "t-3");
+ expect(started).toHaveLength(3);
+ });
+
+ it("leaves the bearers with the turn that takes the engine", () => {
+ const { prestart, credentials, dropped } = host();
+ prestart.note("claude", firstTurn(), true);
+ prestart.threadMade("bot", NEXT);
+ const token = credentials.get(NEXT)!.get("bot agents")!.token;
+ prestart.note("claude", firstTurn({ threadId: NEXT }), true);
+ vi.advanceTimersByTime(PRESTART_IDLE_MS + 60_000);
+ expect(credentials.get(NEXT)!.get("bot agents")!.token).toBe(token);
+ expect(dropped).toEqual([]);
+ expect(prestart.waiting()).toEqual([]);
+ });
+
+ it("retires the bearers of an engine no message came for, a little after it closed", () => {
+ const { prestart, credentials, dropped } = host();
+ prestart.note("claude", firstTurn(), true);
+ prestart.threadMade("bot", NEXT);
+ vi.advanceTimersByTime(PRESTART_IDLE_MS);
+ expect(credentials.has(NEXT)).toBe(true);
+ vi.advanceTimersByTime(5_000);
+ expect(credentials.has(NEXT)).toBe(false);
+ expect(dropped).toEqual([NEXT]);
+ expect(credentials.has(FIRST)).toBe(true);
+ });
+
+ it("leaves them alone when the timer comes due while a turn is being set up there", () => {
+ const { prestart, credentials, dropped, state } = host();
+ prestart.note("claude", firstTurn(), true);
+ prestart.threadMade("bot", NEXT);
+ state.busy = true;
+ vi.advanceTimersByTime(PRESTART_IDLE_MS + 5_000);
+ expect(credentials.has(NEXT)).toBe(true);
+ expect(dropped).toEqual([]);
+ });
+
+ it("stops the engine and retires its bearers on a drop (a Stop, a deleted conversation or bot), and only then", () => {
+ const { prestart, credentials, dropped } = host();
+ prestart.note("claude", firstTurn(), true);
+ prestart.drop(FIRST);
+ expect(dropped).toEqual([]);
+ expect(credentials.has(FIRST)).toBe(true);
+ prestart.threadMade("bot", NEXT);
+ prestart.drop(NEXT);
+ expect(dropped).toEqual([NEXT]);
+ expect(credentials.has(NEXT)).toBe(false);
+ vi.advanceTimersByTime(PRESTART_IDLE_MS + 60_000);
+ expect(dropped).toEqual([NEXT]);
+ });
+
+ it("retires the bearers at once when the engine could not start", async () => {
+ const { prestart, credentials, state } = host();
+ state.up = false;
+ prestart.note("claude", firstTurn(), true);
+ prestart.threadMade("bot", NEXT);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(credentials.has(NEXT)).toBe(false);
+ expect(prestart.waiting()).toEqual([]);
+ });
+});
diff --git a/server/engine-prestart.ts b/server/engine-prestart.ts
new file mode 100644
index 0000000000..ced18c566c
--- /dev/null
+++ b/server/engine-prestart.ts
@@ -0,0 +1,145 @@
+// Starting a new conversation's engine before its first message. An engine process is launched for one conversation
+// (its folder, its session and its bearers are in the launch), so nothing can be kept spare for whichever comes next.
+// What can be known ahead is the launch the bot's last conversation used: a new conversation on the same bot, with the
+// same model, approval level and folder rule, launches the same way but for its own id and its own bearers. This file
+// keeps that last launch per bot, rewrites it for the new conversation and asks the driver to start it. The driver takes
+// the process for the first turn only when that turn's own launch comes out identical, and replaces it otherwise
+// so a wrong guess costs a process that was never used, never a wrong one that was.
+//
+// Not started ahead: a bot's very first conversation (no launch to go by), a launch that mounts anything beyond
+// OpenMausBot's own tool servers (a person's MCP servers, connected apps, a browser or a computer would be started
+// early), a guest's or tool-scoped turn, and any host where engines wait for memory.
+import { randomBytes } from "node:crypto";
+
+import type { ProviderAdapter, SendTurnInput } from "./contracts.ts";
+import { PRESTART_IDLE_MS, PRESTART_MOST } from "./drivers/session-idle.ts";
+
+/** Each conversation's bearers: per slot, what the bearer grants and the bearer. */
+export type SessionCredentials = Map<string, Map<string, { grants: string; token: string }>>;
+
+/** The conversation's bearer for a slot: the one it holds while its grants stand, a new one otherwise. */
+export function bearerForGrants(credentials: SessionCredentials, threadId: string, slot: string, grants: string): string {
+ const slots = credentials.get(threadId) ?? new Map<string, { grants: string; token: string }>();
+ credentials.set(threadId, slots);
+ const held = slots.get(slot);
+ if (held?.grants === grants) return held.token;
+ const token = randomBytes(24).toString("hex");
+ slots.set(slot, { grants, token });
+ return token;
+}
+
+export interface EnginePrestartDeps {
+ adapter(instanceId: string): Pick<ProviderAdapter, "prestart"> | undefined;
+ credentials: SessionCredentials;
+ /** The host starts engines ahead at all. */
+ allowed(): boolean;
+ /** Everything about a conversation that decides its launch besides its id: null when it is gone. Two conversations of
+ * one bot with the same answer launch alike. */
+ shape(botId: string, threadId: string): string | null;
+ /** The approval level a bearer of this conversation is bound to, as its grants record it. */
+ approval(botId: string, threadId: string): unknown;
+ /** Makes the conversation's working folder as its first turn would (its skills in place), and says where it is: the
+ * engine reads the folder as it starts. Null when the conversation has none of its own. */
+ folder(botId: string, threadId: string): string | null;
+ /** No message yet. */
+ blank(threadId: string): boolean;
+ /** A turn is being set up or running there. */
+ busy(botId: string, threadId: string): boolean;
+ /** A first message would be refused now (the bot is paused or held, at its limit, over budget, its AI signed out). */
+ refused(botId: string, threadId: string): boolean;
+ /** How long a started engine waits; the bearers made for it are retired a little after. */
+ idleMs?: number;
+}
+
+interface Launch {
+ instanceId: string;
+ threadId: string;
+ shape: string;
+ /** The turn's input as JSON, without the message and without anything that resumes a session. */
+ input: string;
+ bearers: Array<{ slot: string; grants: string; token: string }>;
+}
+
+/** The tool servers OpenMausBot runs itself: starting them early starts nothing of the person's. */
+const OWN_SERVERS = new Set(["agents", "phone", "data", "device", "email", "hooks", "custom", "customResultBudgets", "mcpApps"]);
+
+function startsOnlyOwnServers(input: SendTurnInput): boolean {
+ const mounted = input.integrations ?? {};
+ return Object.keys(mounted).every((name) => OWN_SERVERS.has(name)) && Object.keys(mounted.custom ?? {}).length === 0
+ && !input.guestConfined && !input.mcpFromUserConfig && input.toolScope === undefined;
+}
+
+const RELEASE_AFTER_MS = 5_000;
+/** One launch per bot, for the bots a person wrote to most recently. */
+const LAUNCHES_KEPT = 32;
+
+export function createEnginePrestart(deps: EnginePrestartDeps) {
+ const launches = new Map<string, Launch>();
+ /** Conversations given bearers ahead of any turn, until a turn uses them or they are retired. */
+ const reserved = new Map<string, { botId: string; instanceId: string; timer: ReturnType<typeof setTimeout> }>();
+
+ const release = (threadId: string, retire: boolean) => {
+ const held = reserved.get(threadId);
+ if (!held) return;
+ clearTimeout(held.timer);
+ reserved.delete(threadId);
+ if (!retire) return;
+ deps.adapter(held.instanceId)?.prestart?.drop(threadId);
+ deps.credentials.delete(threadId);
+ };
+
+ const bearerFor = (botId: string, threadId: string, slot: string, grantedElsewhere: string): string =>
+ bearerForGrants(deps.credentials, threadId, slot, JSON.stringify({ ...JSON.parse(grantedElsewhere), threadId, approval: deps.approval(botId, threadId) }));
+
+ return {
+ /** Called with every turn's input as it goes to its engine; returns it unchanged. A person's own turn becomes what
+ * the bot's next new conversation is started from. */
+ note(instanceId: string, input: SendTurnInput, person: boolean): SendTurnInput {
+ release(input.threadId, false);
+ const botId = input.botId;
+ if (!botId) return input;
+ const shape = person && startsOnlyOwnServers(input) ? deps.shape(botId, input.threadId) : null;
+ if (shape === null) {
+ if (person) launches.delete(botId);
+ return input;
+ }
+ const { text: _text, images: _images, transcript: _transcript, recalled: _recalled, recoveryText: _recovery, resumeCursor: _cursor, sessionReset: _reset,
+ startupRecovery: _startup, mentionTurn: _mention, ...launch } = input;
+ launches.delete(botId);
+ if (launches.size >= LAUNCHES_KEPT) launches.delete(launches.keys().next().value!);
+ launches.set(botId, {
+ instanceId, threadId: input.threadId, shape, input: JSON.stringify(launch),
+ bearers: [...(deps.credentials.get(input.threadId) ?? [])].map(([slot, held]) => ({ slot, ...held })),
+ });
+ return input;
+ },
+
+ /** A person made a conversation: its engine starts now when the bot's last launch says how. */
+ threadMade(botId: string, threadId: string): void {
+ const from = launches.get(botId);
+ const adapter = from && deps.adapter(from.instanceId)?.prestart;
+ if (!from || !adapter || from.threadId === threadId || !deps.allowed() || !deps.blank(threadId) || deps.busy(botId, threadId)
+ || deps.shape(botId, threadId) !== from.shape || deps.refused(botId, threadId)) return;
+ for (const [other, held] of reserved) if (!deps.adapter(held.instanceId)?.prestart?.held(other)) release(other, !deps.busy(held.botId, other));
+ if (reserved.size >= PRESTART_MOST || reserved.has(threadId)) return;
+ let input = from.input.replaceAll(from.threadId, threadId);
+ const cwd = (JSON.parse(input) as SendTurnInput).cwd;
+ if (!cwd || deps.folder(botId, threadId) !== cwd) return;
+ for (const bearer of from.bearers) input = input.replaceAll(bearer.token, bearerFor(botId, threadId, bearer.slot, bearer.grants));
+ const launch = { ...(JSON.parse(input) as SendTurnInput), text: "" };
+ const timer = setTimeout(() => release(threadId, !deps.busy(botId, threadId)), (deps.idleMs ?? PRESTART_IDLE_MS) + RELEASE_AFTER_MS);
+ timer.unref?.();
+ reserved.set(threadId, { botId, instanceId: from.instanceId, timer });
+ void adapter.start(launch).then((up) => { if (!up && !deps.busy(botId, threadId)) release(threadId, true); },
+ () => release(threadId, !deps.busy(botId, threadId)));
+ },
+
+ /** The conversation's bearers were retired (a Stop, a delete): an engine started ahead with them goes too. */
+ drop(threadId: string): void {
+ release(threadId, true);
+ },
+
+ waiting: (): string[] => [...reserved.keys()],
+ };
+}
+export type EnginePrestart = ReturnType<typeof createEnginePrestart>;
diff --git a/server/harness/registry.ts b/server/harness/registry.ts
index d599235856..3ffc373130 100644
--- a/server/harness/registry.ts
+++ b/server/harness/registry.ts
@@ -447,13 +447,14 @@ export class ProviderRegistry {
}
/** `reuse`: answer from a status read since the last forgetSnapshots(); one older than `ms` is read again in the background
- * and `changed` runs when that read differs. */
- describe(options: { known?: boolean; reuse?: { ms: number; changed(): void } } = {}) {
+ * and `changed` runs when that read differs. One older than `maxAgeMs` is not reused: its engine is read first. */
+ describe(options: { known?: boolean; reuse?: { ms: number; maxAgeMs?: number; changed(): void } } = {}) {
return this.describeWith((instance) => {
const seed = options.known && this.unread?.has(instance.instanceId) ? this.seeds.get(instance.instanceId) : undefined;
if (seed) return Promise.resolve(seed);
const last = options.reuse && this.readsOf.get(instance);
if (!options.reuse || !last || last.generation !== this.snapshotGeneration) return this.read(instance);
+ if (options.reuse.maxAgeMs !== undefined && Date.now() - last.at >= options.reuse.maxAgeMs) return this.read(instance);
if (Date.now() - last.at >= options.reuse.ms) {
const { changed } = options.reuse;
void this.read(instance).then((snapshot) => { if (JSON.stringify(snapshot) !== JSON.stringify(last.snapshot)) changed(); });
diff --git a/server/host/checkpoint-seeds.test.ts b/server/host/checkpoint-seeds.test.ts
new file mode 100644
index 0000000000..d3774ce063
--- /dev/null
+++ b/server/host/checkpoint-seeds.test.ts
@@ -0,0 +1,214 @@
+import { mkdirSync, mkdtempSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { createCheckpointSeeds, STARTUP_FOLDERS, type SeedBot, type SeedChange } from "./checkpoint-seeds.ts";
+import { refusalReason } from "../checkpoints.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+
+const scratch: string[] = [];
+afterAll(async () => {
+ for (const dir of scratch) await removeTempDir(dir);
+});
+
+function folder(kind: "project" | "plain"): string {
+ const dir = mkdtempSync(join(tmpdir(), "omb-seed-"));
+ scratch.push(dir);
+ if (kind === "project") mkdirSync(join(dir, ".git"));
+ return dir;
+}
+
+type Read = { botId: string; cwd: string; signal: AbortSignal; end: () => void };
+
+function setup(options: { bots?: SeedBot[]; chatOnly?: string[]; ownRoots?: string[] } = {}) {
+ const bots = new Map((options.bots ?? []).map((bot) => [bot.id, bot]));
+ const reads: Read[] = [];
+ const clock = 1_000_000_000_000;
+ let listener: (change: SeedChange) => void = () => {};
+ let startUp: (() => void) | null = null;
+ const seeds = createCheckpointSeeds({
+ bots: () => [...bots.values()],
+ bot: (id) => bots.get(id),
+ worksInFolders: (bot) => !(options.chatOnly ?? []).includes(bot.id),
+ refusal: refusalReason,
+ prime: (botId, cwd, signal) => new Promise<void>((end) => {
+ const read = { botId, cwd, signal, end };
+ reads.push(read);
+ signal.addEventListener("abort", () => end(), { once: true });
+ }),
+ onChange: (given) => { listener = given; },
+ ownRoots: options.ownRoots ?? [],
+ now: () => clock,
+ later: (run) => { startUp = run; },
+ });
+ return {
+ seeds,
+ reads,
+ bots,
+ set(bot: SeedBot, threadId?: string) {
+ bots.set(bot.id, bot);
+ listener({ type: "bot", botId: bot.id, ...(threadId ? { threadId } : {}) });
+ },
+ remove(botId: string) {
+ bots.delete(botId);
+ listener({ type: "bot.deleted", botId });
+ },
+ now: () => clock,
+ runStartUp() { startUp?.(); },
+ started: () => startUp !== null,
+ };
+}
+
+const read = (reads: Read[]) => reads.map((one) => `${one.botId}:${one.cwd}`);
+
+describe("checkpoint seeds", () => {
+ it("reads a project folder once when a bot is set to it, however often the bot changes afterwards", async () => {
+ const project = folder("project");
+ const host = setup();
+ host.set({ id: "bob", cwd: project });
+ host.set({ id: "bob", cwd: project });
+ host.set({ id: "bob", cwd: project }, "thread-1");
+ expect(read(host.reads)).toEqual([`bob:${project}`]);
+ host.reads[0]!.end();
+ await host.seeds.settled();
+ host.set({ id: "bob", cwd: project });
+ expect(host.reads).toHaveLength(1);
+ });
+
+ it("reads the folder one conversation was moved to", () => {
+ const project = folder("project");
+ const host = setup();
+ host.set({ id: "bob", tasks: [{ threadId: "thread-1", cwd: project }, { threadId: "thread-2", cwd: null }] }, "thread-1");
+ expect(read(host.reads)).toEqual([`bob:${project}`]);
+ });
+
+ it("never reads a folder without a repository, a refused folder, one of the app's own, or for a bot whose engine has no folder", () => {
+ const plain = folder("plain");
+ const project = folder("project");
+ const own = folder("project");
+ const host = setup({ chatOnly: ["chatty"], ownRoots: [own] });
+ host.set({ id: "bob", cwd: plain });
+ host.set({ id: "home", cwd: homedir() });
+ host.set({ id: "docs", cwd: join(homedir(), "Documents") });
+ host.set({ id: "relative", cwd: "some/project" });
+ host.set({ id: "missing", cwd: join(plain, "gone") });
+ host.set({ id: "chatty", cwd: project });
+ host.set({ id: "private", cwd: own });
+ host.set({ id: "nested", cwd: join(own, ".git") });
+ host.set({ id: "none" });
+ expect(host.reads).toEqual([]);
+ });
+
+ it("reads nothing because something else about a bot changed: not for bots already on their folders at start-up, not for a conversation pinned to its bot's folder", async () => {
+ const project = folder("project");
+ const other = folder("project");
+ const onProject: SeedBot = { id: "bob", cwd: project, tasks: [{ threadId: "thread-1", cwd: other }, { threadId: "thread-2" }] };
+ const host = setup({ bots: [onProject, { id: "amy", cwd: other }] });
+ host.set(onProject);
+ host.set(onProject, "thread-1");
+ host.set({ id: "amy", cwd: other }, "main");
+ host.set({ ...onProject, tasks: [{ threadId: "thread-1", cwd: other }, { threadId: "thread-2", cwd: project }] }, "thread-2");
+ expect(host.reads).toEqual([]);
+ // A folder being set is what reads one: on a conversation, then on a bot.
+ host.set({ ...onProject, tasks: [{ threadId: "thread-1", cwd: other }, { threadId: "thread-2", cwd: other }] }, "thread-2");
+ host.set({ id: "amy", cwd: project });
+ expect(read(host.reads)).toEqual([`bob:${other}`]);
+ host.reads[0]!.end();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(read(host.reads)).toEqual([`bob:${other}`, `amy:${project}`]);
+ host.reads[1]!.end();
+ await host.seeds.settled();
+ });
+
+ it("reads one folder at a time, in the order they were set", async () => {
+ const first = folder("project");
+ const second = folder("project");
+ const third = folder("project");
+ const host = setup();
+ host.set({ id: "a", cwd: first });
+ host.set({ id: "b", cwd: second });
+ host.set({ id: "c", cwd: third });
+ expect(read(host.reads)).toEqual([`a:${first}`]);
+ host.reads[0]!.end();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(read(host.reads)).toEqual([`a:${first}`, `b:${second}`]);
+ host.reads[1]!.end();
+ await Promise.resolve();
+ await Promise.resolve();
+ host.reads[2]!.end();
+ await host.seeds.settled();
+ expect(read(host.reads)).toEqual([`a:${first}`, `b:${second}`, `c:${third}`]);
+ });
+
+ it("stops reading a folder its bot was moved off, and reads it again when the bot comes back", async () => {
+ const old = folder("project");
+ const next = folder("project");
+ const host = setup();
+ host.set({ id: "bob", cwd: old });
+ host.set({ id: "bob", cwd: next });
+ expect(host.reads[0]!.signal.aborted).toBe(true);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(read(host.reads)).toEqual([`bob:${old}`, `bob:${next}`]);
+ expect(host.reads[1]!.signal.aborted).toBe(false);
+ host.reads[1]!.end();
+ await host.seeds.settled();
+ host.set({ id: "bob", cwd: old });
+ expect(read(host.reads)).toEqual([`bob:${old}`, `bob:${next}`, `bob:${old}`]);
+ });
+
+ it("stops and forgets a deleted bot's folders, running or waiting", async () => {
+ const first = folder("project");
+ const second = folder("project");
+ const host = setup();
+ host.set({ id: "a", cwd: first });
+ host.set({ id: "b", cwd: second });
+ host.remove("b");
+ host.remove("a");
+ expect(host.reads[0]!.signal.aborted).toBe(true);
+ await host.seeds.settled();
+ expect(host.reads).toHaveLength(1);
+ });
+
+ it("reads nothing at start-up until it is told the start-up is over, then the folders used in the last week, newest first", async () => {
+ const day = 24 * 60 * 60 * 1000;
+ const projects = Array.from({ length: STARTUP_FOLDERS + 2 }, () => folder("project"));
+ const stale = folder("project");
+ const plain = folder("plain");
+ const host = setup();
+ const at = host.now();
+ for (const [index, project] of projects.entries()) host.bots.set(`bot-${index}`, { id: `bot-${index}`, cwd: project, tasks: [{ threadId: `t-${index}`, updatedAt: at - index * 1000 }] });
+ host.bots.set("stale", { id: "stale", cwd: stale, tasks: [{ threadId: "t-stale", updatedAt: at - 8 * day, askedAt: at - 9 * day }] });
+ host.bots.set("plain", { id: "plain", cwd: plain, tasks: [{ threadId: "t-plain", askedAt: at }] });
+ host.bots.set("moved", { id: "moved", cwd: stale, tasks: [{ threadId: "t-private", cwd: null, updatedAt: at }] });
+ host.bots.set("unused", { id: "unused", cwd: stale });
+ host.seeds.start();
+ expect(host.started()).toBe(true);
+ expect(host.reads).toEqual([]);
+ host.runStartUp();
+ for (let n = 0; n < STARTUP_FOLDERS + 4; n += 1) {
+ host.reads[n]?.end();
+ await Promise.resolve();
+ await Promise.resolve();
+ }
+ await host.seeds.settled();
+ // "plain" took one of the places and was turned away for having no repository.
+ expect(read(host.reads)).toEqual(projects.slice(0, STARTUP_FOLDERS - 1).map((project, index) => `bot-${index}:${project}`));
+ });
+
+ it("reads nothing more once the server is shutting down, and stops the read under way", () => {
+ const first = folder("project");
+ const second = folder("project");
+ const host = setup();
+ host.set({ id: "a", cwd: first });
+ host.seeds.stop();
+ expect(host.reads[0]!.signal.aborted).toBe(true);
+ host.set({ id: "b", cwd: second });
+ host.seeds.start();
+ host.runStartUp();
+ expect(host.reads).toHaveLength(1);
+ });
+});
diff --git a/server/host/checkpoint-seeds.ts b/server/host/checkpoint-seeds.ts
new file mode 100644
index 0000000000..0d673f17fb
--- /dev/null
+++ b/server/host/checkpoint-seeds.ts
@@ -0,0 +1,162 @@
+// Reads a bot's project folder into its checkpoint shadow before the first turn there, so that turn's own snapshot finds the
+// files already read: when the folder is set, and once after start-up for the folders in recent use. Only a folder a bot is
+// set to work in, only one that holds a repository, and one folder at a time.
+import { existsSync, realpathSync } from "node:fs";
+import { isAbsolute, join, relative, resolve } from "node:path";
+
+export interface SeedTask {
+ threadId: string;
+ cwd?: string | null;
+ updatedAt?: number;
+ askedAt?: number;
+}
+
+export interface SeedBot {
+ id: string;
+ cwd?: string;
+ tasks?: readonly SeedTask[];
+}
+
+export type SeedChange = { type: "bot"; botId: string; threadId?: string } | { type: "bot.deleted"; botId: string } | { type: string };
+
+export interface CheckpointSeedsDeps<Bot extends SeedBot = SeedBot> {
+ bots(): readonly Bot[];
+ bot(id: string): Bot | null | undefined;
+ /** Does the bot's engine work in a folder at all? */
+ worksInFolders(bot: Bot): boolean;
+ /** Why a folder is never snapshotted, or null. */
+ refusal(cwd: string): string | null;
+ /** Reads the folder into the bot's shadow without taking a snapshot. */
+ prime(botId: string, cwd: string, signal: AbortSignal): Promise<unknown>;
+ onChange(listener: (change: SeedChange) => void): unknown;
+ /** The app's own folders: a bot's private task folders and the shadows themselves live under these. */
+ ownRoots: readonly string[];
+ now?(): number;
+ /** Runs the start-up pass once the start-up itself is over. */
+ later?(run: () => void): void;
+}
+
+/** Start-up reads at most this many folders, the most recently used first. */
+export const STARTUP_FOLDERS = 6;
+const RECENT_MS = 7 * 24 * 60 * 60 * 1000;
+const STARTUP_DELAY_MS = 20_000;
+
+function inside(root: string, path: string): boolean {
+ const rel = relative(root, path);
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
+}
+
+export function createCheckpointSeeds<Bot extends SeedBot>(deps: CheckpointSeedsDeps<Bot>) {
+ const now = deps.now ?? Date.now;
+ const later = deps.later ?? ((run) => { setTimeout(run, STARTUP_DELAY_MS).unref?.(); });
+ /** Bot and folder, once queued. */
+ const queued = new Set<string>();
+ /** The folder each bot, and each conversation with one of its own, was last seen set to: a change to anything else about a
+ * bot reads nothing. */
+ const folders = new Map<string, string | null | undefined>();
+ for (const bot of deps.bots()) {
+ folders.set(bot.id, bot.cwd);
+ for (const task of bot.tasks ?? []) folders.set(`${bot.id}\0${task.threadId}`, task.cwd);
+ }
+ const moved = (id: string, folder: string | null | undefined): boolean => {
+ const before = folders.get(id);
+ folders.set(id, folder);
+ return Boolean(folder) && before !== folder;
+ };
+ const queue: Array<{ botId: string; folder: string }> = [];
+ let running: { botId: string; folder: string; stop: AbortController } | null = null;
+ let stopped = false;
+ const idle: Array<() => void> = [];
+ const key = (botId: string, folder: string) => `${botId}\0${folder}`;
+
+ const qualifies = (folder: string): boolean => {
+ if (!isAbsolute(folder) || deps.refusal(folder) !== null) return false;
+ try {
+ const real = realpathSync(resolve(folder));
+ if (deps.ownRoots.some((root) => inside(resolve(root), resolve(folder)) || inside(realpathSync(resolve(root)), real))) return false;
+ return existsSync(join(real, ".git"));
+ } catch {
+ return false;
+ }
+ };
+
+ const pump = (): void => {
+ if (running || stopped) return;
+ const next = queue.shift();
+ if (!next) {
+ for (const done of idle.splice(0)) done();
+ return;
+ }
+ const mine = { ...next, stop: new AbortController() };
+ running = mine;
+ void deps.prime(next.botId, next.folder, mine.stop.signal).catch(() => {}).then(() => {
+ // Cut short: the folder may be read again when the bot is next set to it.
+ if (mine.stop.signal.aborted) queued.delete(key(next.botId, next.folder));
+ if (running === mine) running = null;
+ pump();
+ });
+ };
+
+ const consider = (bot: Bot, folder: string | null | undefined): void => {
+ if (stopped || !folder || queued.has(key(bot.id, folder)) || !deps.worksInFolders(bot) || !qualifies(folder)) return;
+ queued.add(key(bot.id, folder));
+ queue.push({ botId: bot.id, folder });
+ pump();
+ };
+
+ /** Is the bot, or one of its conversations, still set to this folder? */
+ const worksIn = (bot: Bot, folder: string): boolean => bot.cwd === folder || (bot.tasks ?? []).some((task) => task.cwd === folder);
+
+ const forget = (botId: string, keep: (folder: string) => boolean = () => false): void => {
+ for (let at = queue.length - 1; at >= 0; at -= 1) {
+ const one = queue[at]!;
+ if (one.botId !== botId || keep(one.folder)) continue;
+ queue.splice(at, 1);
+ queued.delete(key(botId, one.folder));
+ }
+ if (running?.botId === botId && !keep(running.folder)) running.stop.abort();
+ };
+
+ deps.onChange((change) => {
+ if (change.type !== "bot" && change.type !== "bot.deleted") return;
+ if (!("botId" in change)) return;
+ const bot = change.type === "bot" ? deps.bot(change.botId) : undefined;
+ if (!bot) {
+ for (const id of folders.keys()) if (id === change.botId || id.startsWith(`${change.botId}\0`)) folders.delete(id);
+ return forget(change.botId);
+ }
+ forget(bot.id, (folder) => worksIn(bot, folder));
+ if (moved(bot.id, bot.cwd)) consider(bot, bot.cwd);
+ const task = "threadId" in change && change.threadId ? bot.tasks?.find((one) => one.threadId === change.threadId) : undefined;
+ // A conversation pinned to its bot's own folder is pinned as its turn starts: that turn reads the folder itself.
+ if (task && moved(`${bot.id}\0${task.threadId}`, task.cwd) && task.cwd !== bot.cwd) consider(bot, task.cwd);
+ });
+
+ return {
+ /** The folders of the conversations used in the last week, most recent first. */
+ start(): void {
+ later(() => {
+ const used = new Map<string, { bot: Bot; folder: string; at: number }>();
+ for (const bot of deps.bots()) {
+ for (const task of bot.tasks ?? []) {
+ const folder = task.cwd === undefined ? bot.cwd : task.cwd;
+ const at = Math.max(task.askedAt ?? 0, task.updatedAt ?? 0);
+ if (!folder || now() - at > RECENT_MS) continue;
+ const known = used.get(key(bot.id, folder));
+ if (!known || known.at < at) used.set(key(bot.id, folder), { bot, folder, at });
+ }
+ }
+ for (const { bot, folder } of [...used.values()].sort((left, right) => right.at - left.at).slice(0, STARTUP_FOLDERS)) consider(bot, folder);
+ });
+ },
+ stop(): void {
+ stopped = true;
+ queue.length = 0;
+ running?.stop.abort();
+ },
+ /** Resolves once nothing is being read or waiting to be. */
+ settled(): Promise<void> {
+ return running || queue.length > 0 ? new Promise((done) => { idle.push(done); }) : Promise.resolve();
+ },
+ };
+}
diff --git a/server/host/delete-leftovers.test.ts b/server/host/delete-leftovers.test.ts
index 98f60fa8a2..60b2de341d 100644
--- a/server/host/delete-leftovers.test.ts
+++ b/server/host/delete-leftovers.test.ts
@@ -1,7 +1,7 @@
import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment, plainlyUnder, removeMemoryLayer, removeUnder, type DeleteLeftoversDeps } from "./delete-leftovers.ts";
@@ -263,6 +263,21 @@ describe("a deleted bot", () => {
expect(forgotten.sort()).toEqual([...layers].sort());
});
+ it("leaves its checkpoints in place until no git is running on them, then takes them", async () => {
+ let quiet = () => {};
+ const asked: string[] = [];
+ const { dataDir, bots, deleteBot } = fixture({ checkpointsQuiet: (botId) => { asked.push(botId); return new Promise<void>((done) => { quiet = done; }); } });
+ bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });
+ const checkpoint = put(join(dataDir, "checkpoints", "scout", "0123456789abcdef", ".git", "HEAD"));
+ const uploaded = put(join(dataDir, "box-uploads", "scout", "t1", upload(1)));
+ deleteBot("scout");
+ await Promise.resolve();
+ expect(asked).toEqual(["scout"]);
+ expect([existsSync(checkpoint), existsSync(uploaded)]).toEqual([true, false]);
+ quiet();
+ await vi.waitFor(() => expect(existsSync(checkpoint)).toBe(false));
+ });
+
it("never follows a link out of the data folder", () => {
const { dataDir, outside, bots, deleteBot } = fixture();
bots.push({ id: "scout", tasks: [{ threadId: "t1" }] });
diff --git a/server/host/delete-leftovers.ts b/server/host/delete-leftovers.ts
index 6fd6064f32..81d59861e5 100644
--- a/server/host/delete-leftovers.ts
+++ b/server/host/delete-leftovers.ts
@@ -54,6 +54,8 @@ export interface DeleteLeftoversDeps {
deleteAttachment(name: string): void;
engineFolders(): EngineSessionFolders;
layers: MemoryLayerRecords;
+ /** Resolves once no git is running on the bot's checkpoints: Windows cannot remove a folder a process still has open. */
+ checkpointsQuiet?(botId: string): Promise<void>;
/** Runs `flush` once the delete under way has finished, so one pass covers every conversation it removed. */
defer?(flush: () => void): void;
warn?(line: string): void;
@@ -281,7 +283,9 @@ export function createDeleteLeftovers(deps: DeleteLeftoversDeps) {
function removeBot(botId: string): void {
if (!ID.test(botId) || isLayerId(botId)) return;
- attempt(`checkpoints of ${botId}`, () => void removeUnder(dataDir, join(dataDir, "checkpoints", botId)));
+ const removeCheckpoints = () => attempt(`checkpoints of ${botId}`, () => void removeUnder(dataDir, join(dataDir, "checkpoints", botId)));
+ if (deps.checkpointsQuiet) void deps.checkpointsQuiet(botId).then(removeCheckpoints, removeCheckpoints);
+ else removeCheckpoints();
attempt(`box uploads of ${botId}`, () => void removeUnder(dataDir, join(dataDir, "box-uploads", botId)));
const live = new Set(deps.store.bots.map((bot) => bot.id));
for (const layer of entries(join(dataDir, "workspaces"))) {
diff --git a/server/host/message-pages.ts b/server/host/message-pages.ts
index 8f1a90257f..91ee7b9d9e 100644
--- a/server/host/message-pages.ts
+++ b/server/host/message-pages.ts
@@ -1,9 +1,10 @@
import type { Message, Store } from "../store.ts";
+import { messagesAround } from "../thread-history.ts";
import { toolResultPrefix } from "../tool-results.ts";
const MESSAGE_PAGE_MAX = 200;
-/** How much of a tool step's output a conversation page carries: the rest is fetched when the step is opened, so
- * switching to a conversation full of tool steps stays light. */
+/** How much of a tool step's output a conversation page or a live frame carries: the rest is fetched when the step is
+ * opened, so switching to a conversation full of tool steps stays light. */
export const TOOL_OUTPUT_PREVIEW = 1_000;
/** undefined = absent, null = present but unusable (the caller answers 400). */
@@ -20,8 +21,8 @@ export function slimMessage(message: Message): Message | Record<string, unknown>
return { ...rest, hasImage: true };
}
-/** A message as a conversation page carries it: slimmed, and a plain tool step's long output cut to a preview marked
- * `clipped`. Input stays whole (labels parse it), and so do rows whose tool output is the reply itself (a teammate's
+/** A message as a conversation page and a live `message` or `message.patch` frame carry it: slimmed, and a plain tool
+ * step's long output cut to a preview marked `clipped`. Input stays whole (labels parse it), and so do rows whose tool output is the reply itself (a teammate's
* result, a relayed message, a handoff). */
export function pageMessage(message: Message): Message | Record<string, unknown> {
const slim = slimMessage(message);
@@ -48,13 +49,8 @@ export function messagePages(store: Pick<Store, "messagesFor" | "messagesTail" |
}
function messageWindow(threadId: string, messageId: string, limit: number) {
- const all = store.messagesFor(threadId);
- const index = all.findIndex((message) => message.id === messageId);
- if (index < 0) return null;
- const before = Math.floor((limit - 1) / 2);
- const start = Math.max(0, Math.min(index - before, all.length - limit));
- const stop = Math.min(all.length, start + limit);
- return { messages: all.slice(start, stop).map(pageMessage), hasMore: start > 0 };
+ const page = messagesAround(threadId, messageId, limit, () => ({ messages: store.messagesFor(threadId), activeLeafId: store.activeLeaf(threadId) }));
+ return page ? { ...page, messages: page.messages.map(pageMessage) } : null;
}
return { messagePage, messagePageBefore, messageWindow };
diff --git a/server/host/suggested-selection.test.ts b/server/host/suggested-selection.test.ts
new file mode 100644
index 0000000000..703c6c9294
--- /dev/null
+++ b/server/host/suggested-selection.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { ModelSelection } from "../contracts.ts";
+import { selectDefaultModelSelection, type SelectableInstance } from "../default-model-selection.ts";
+import { ENGINE_LIST_REUSE_MS, ProviderRegistry } from "../harness/registry.ts";
+import { makeFakeDriver } from "../testing/fake-driver.ts";
+import { SUGGESTION_MAX_AGE_MS, suggestedSelection } from "./suggested-selection.ts";
+
+afterEach(() => vi.useRealTimers());
+
+async function engines(saved?: ModelSelection) {
+ const fake = makeFakeDriver();
+ const registry = new ProviderRegistry([fake.driver]);
+ await registry.load({ a: { driver: "fake" } });
+ let changed = 0;
+ const suggest = () => suggestedSelection<SelectableInstance>({
+ reused: (age) => registry.describe({ reuse: { ...age, changed: () => { changed += 1; } } }),
+ fresh: () => registry.describe(),
+ select: async (instances) => selectDefaultModelSelection(instances, saved),
+ });
+ return { fake, registry, suggest, changed: () => changed };
+}
+
+describe("suggestedSelection", () => {
+ it("reads every engine when none was read yet, and answers as a fresh read does", async () => {
+ const { fake, registry, suggest } = await engines();
+ const answer = await suggest();
+ expect(fake.probes).toHaveLength(1);
+ expect(answer.instanceId).toBe("a");
+ expect(answer).toEqual(selectDefaultModelSelection(await registry.describe()));
+ });
+
+ it("probes no CLI once the engine list holds a status that names an engine", async () => {
+ const { fake, registry, suggest } = await engines();
+ await registry.describe({ reuse: { ms: ENGINE_LIST_REUSE_MS, changed: () => {} } });
+ const before = fake.probes.length;
+ const first = await suggest();
+ expect(await suggest()).toEqual(first);
+ expect(first.instanceId).toBe("a");
+ expect(fake.probes).toHaveLength(before);
+ });
+
+ it("reads again after anything in the app changed an engine's status", async () => {
+ const { fake, registry, suggest } = await engines();
+ await suggest();
+ const before = fake.probes.length;
+ registry.forgetSnapshots();
+ await suggest();
+ expect(fake.probes.length).toBeGreaterThan(before);
+ });
+
+ it("answers from a status under ten minutes old and reads the engine first once it is older", async () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ const { fake, suggest } = await engines();
+ await suggest();
+ const before = fake.probes.length;
+ vi.setSystemTime(Date.now() + ENGINE_LIST_REUSE_MS - 1_000);
+ await suggest();
+ expect(fake.probes).toHaveLength(before);
+ vi.setSystemTime(Date.now() + SUGGESTION_MAX_AGE_MS + 1_000);
+ await suggest();
+ expect(fake.probes).toHaveLength(before + 1);
+ });
+
+ it("reads every engine again when the held statuses name none", async () => {
+ const calls: string[] = [];
+ const answer = await suggestedSelection<string>({
+ reused: async () => { calls.push("reused"); return ["signed out"]; },
+ fresh: async () => { calls.push("fresh"); return ["signed in"]; },
+ select: async (instances) => instances[0] === "signed in" ? { instanceId: "a", model: "m" } : { instanceId: "", model: "" },
+ });
+ expect(calls).toEqual(["reused", "fresh"]);
+ expect(answer).toEqual({ instanceId: "a", model: "m" });
+ });
+
+ it("keeps a saved choice whose engine is not ready as no choice, after a fresh read", async () => {
+ const { fake, suggest } = await engines({ instanceId: "gone", model: "m" });
+ expect(await suggest()).toEqual({ instanceId: "", model: "" });
+ expect(fake.probes.length).toBeGreaterThan(0);
+ });
+});
diff --git a/server/host/suggested-selection.ts b/server/host/suggested-selection.ts
new file mode 100644
index 0000000000..dff7751324
--- /dev/null
+++ b/server/host/suggested-selection.ts
@@ -0,0 +1,24 @@
+import type { ModelSelection } from "../contracts.ts";
+import { ENGINE_LIST_REUSE_MS } from "../harness/registry.ts";
+
+/** The oldest engine status New bot's offer may rest on; past it the engine is read again before the answer. */
+export const SUGGESTION_MAX_AGE_MS = 10 * 60_000;
+
+/**
+ * The engine and model New bot offers. Answered from the status reads the engine list already holds, so opening New bot
+ * spawns no CLI; when those reads name no engine (nothing was ready, or nothing was read yet) every engine is read
+ * again first, so one installed or signed in from a terminal a moment ago is found.
+ *
+ * Known open risk: nothing checks the offer's engine status again before the bot is made. An engine removed or signed
+ * out outside the app within SUGGESTION_MAX_AGE_MS of its last read can be offered once; the bot is then made on it and
+ * its first turn reports the engine's own sign-in or missing-CLI problem.
+ */
+export async function suggestedSelection<Instance>(engines: {
+ reused(age: { ms: number; maxAgeMs: number }): Promise<readonly Instance[]>;
+ fresh(): Promise<readonly Instance[]>;
+ select(instances: readonly Instance[]): Promise<ModelSelection>;
+}): Promise<ModelSelection> {
+ const quick = await engines.select(await engines.reused({ ms: ENGINE_LIST_REUSE_MS, maxAgeMs: SUGGESTION_MAX_AGE_MS }));
+ if (quick.instanceId && quick.model) return quick;
+ return engines.select(await engines.fresh());
+}
diff --git a/server/hosted-models.ts b/server/hosted-models.ts
index fd31c10e1c..1bb7068337 100644
--- a/server/hosted-models.ts
+++ b/server/hosted-models.ts
@@ -106,7 +106,7 @@ export function hostedModelPolicy(dataDirectory: string, env: NodeJS.ProcessEnv
installRuntime: undefined, startAuthentication: undefined, getAuthentication: undefined,
completeAuthentication: undefined, cancelAuthentication: undefined, signOut: undefined,
snapshot: async () => ({ ...await instance.snapshot(), authenticated: true, billing: "metered" }),
- adapter: { ...instance.adapter, sendTurn: async input => {
+ adapter: { ...instance.adapter, prestart: undefined, sendTurn: async input => {
if (!input.model || !models.includes(input.model)) throw new Error(HOSTED_MODEL_SELECTION_ERROR);
return instance.adapter.sendTurn(input);
} },
diff --git a/server/index.ts b/server/index.ts
index 9152332cc5..e2e2e8308e 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -60,7 +60,7 @@ import {
requireBrowserCleanupAcknowledged,
type BrowserCleanupWireRequest,
} from "./browser-lifecycle-cleanup.ts";
-import * as checkpoints from "./checkpoints.ts";
+import * as checkpoints from "./checkpoints.ts"; import { createCheckpointSeeds } from "./host/checkpoint-seeds.ts";
import { commandReceipt } from "./commands.ts"; import { moveSavedGrants } from "./mcp-grant-spec.ts";
import { buildTurnDigest, coverageForDriver, digestCompletedLate, digestPromptLine, renderDigest, toolEvidence } from "./digest.ts";
import { appendDecision, bindDecisionRetention, decisionRetentionDays, flushDecisionLog, pruneDecisions, withDecisionActor, type DecisionActor, type DecisionVia } from "./decision-log.ts";
@@ -299,7 +299,7 @@ import { createDelegatedLevel } from "./host/delegated-level.ts";
import { createLiveApprovalMode } from "./host/live-approval.ts";
import { CONSENT_RULE, continuedOrigin, escapeNotes, labelledLine, OUTSIDE, peerLineText, peerProvenanceNote, quoteInNote, reportNote, requestWorkOrigin, type WorkOrigin } from "./peer-provenance.ts"; import { lineNote, PROVENANCE_PROMPT } from "./provenance-label.ts"; import { openRoomThread } from "./host/room-new-thread.ts"; import { createLineLabels } from "./host/line-labels.ts";
import { decideRoomPost, emptyRoomPostBudget, type RoomPostAttempt, type RoomPostBudget } from "./room-post-budget.ts";
-import { messagePages, pageSize, slimMessage } from "./host/message-pages.ts";
+import { messagePages, pageMessage, pageSize, slimMessage } from "./host/message-pages.ts"; import { suggestedSelection } from "./host/suggested-selection.ts";
import { coordinateResultMessage, createAsksActingPerson, createTeammatePrompts } from "./host/teammate-prompts.ts"; import { createPersonalReach } from "./host/personal-reach.ts"; import { createMausBotOwnChat } from "./host/mausbot-own-chat.ts"; import { moveMemoryLayer } from "./memory-move.ts";
import { createQueuedReason } from "./host/queued-reason.ts";
import { ReplayBuffer } from "./host/sse-replay.ts";
@@ -650,7 +650,7 @@ import { withScopeHint } from "./connector-scope-hint.ts"; import { accountsByAp
import { connectorFileDeps, connectorFileScope, prepareConnectorFiles, withMissingFileHint } from "./connector-files.ts";
import { createConnectorCards } from "./host/connector-cards.ts";
import { createLoginMailCodes } from "./host/login-mail-codes.ts"; import { createLateToolResults } from "./host/late-tool-results.ts"; import { internalBodyRefusal } from "./host/internal-body-ids.ts";
-import { onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";
+import { onThreadMade, onThreadSeen, personAsks as personAskAt, sawThread } from "./thread-presence.ts"; import { bearerForGrants, createEnginePrestart } from "./engine-prestart.ts"; import { prestartAllowed } from "./drivers/session-idle.ts"; import { createWarmSummaryHost, HARNESS_IDLE_FRACTION } from "./host/warm-summary-host.ts";
const PORT = Number(process.env.OMB_PORT || process.env.OGB_PORT || 8799);
const WEBHOOK_PORT = Number(process.env.OMB_WEBHOOK_PORT || PORT + 1);
@@ -1011,7 +1011,6 @@ function cloudGuestOpened(threadId: string): boolean {
const guestDrivenTurns = new Map<string, string>();
-
/** Never the owner when a guest drives the source, so the new conversation is confined like it. On a Team Cloud it is the
* source's audience: one person's only from their own private chat (else a shared chat's work reads their notes). */
function openerFrom(fromThreadId: string): string | undefined {
@@ -1021,9 +1020,6 @@ function openerFrom(fromThreadId: string): string | undefined {
return person && !cloudOwnerPerson(person) ? person : CLOUD_NOBODY_KEY;
}
-
-
-
/** Loopback is not the owner on a Cloud home: only processes on the machine (a bot's shell) arrive that way. */
function cloudOwnerSession(auth: RequestAuth): boolean {
return auth.kind === "session" && auth.scopes.includes("admin");
@@ -1346,7 +1342,6 @@ function adminAuditRows(
return rows;
}
-
function operatorPrices(): PriceList | null {
return entitled("billing") && cfg.billing?.prices && Object.keys(cfg.billing.prices).length ? cfg.billing.prices : null;
}
@@ -1671,6 +1666,10 @@ function beginInternalCapabilityGeneration(threadId: string, generation = random
// Security invariant: a turn's depth, the hand-off it runs for and whether it may author skills are read from that record on every call, never
// from the engine, so a person's message and a teammate's report keep one bearer.
const sessionCredentials = new Map<string, Map<string, { grants: string; token: string }>>();
+const enginePrestart = createEnginePrestart({ adapter: (id) => registry.get(id)?.adapter, credentials: sessionCredentials, allowed: prestartAllowed, blank: (threadId) => store.messagesFor(threadId).length === 0, busy: (botId, threadId) => threadBusy(botId, threadId), approval: (botId, threadId) => { const thread = botForThread(botId, threadId); return thread ? approvalModeFor(thread) : null; },
+ shape: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), task = store.taskByThread(botId, threadId); return bot && task ? JSON.stringify([bot.modelSelection, approvalModeForTurn(bot, false, threadId), task.projectId ?? null, task.cwd?.includes(threadId) ? null : task.cwd ?? null]) : null; },
+ folder: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId), instance = bot && registry.get(bot.modelSelection.instanceId); if (!bot || !instance || !supportsWorkspaceFiles(instance.driverKind)) return null; ensureWorkspace(botId, appLanguage()); return ensureTaskWorkspaceWithSkills(botId, threadId, skillsHost.turnImports(bot, threadId, instance)) ?? null; },
+ refused: (botId, threadId) => { const bot = store.projectBotForTask(botId, threadId); try { assertWithinBudget(cfg, DATA_DIR); } catch { return true; } return !bot || Boolean(bot.approvalGrant) || providerInstancesChanging.has(bot.modelSelection.instanceId) || limitTakeover.stillSignedOut(bot.modelSelection.instanceId) || botAtThreadCapacity(botId, threadId) || Boolean(botHolds.text(botId, threadLanguage(threadId)) ?? starterCaps.pausedText(botId, threadLanguage(threadId))); } }); onThreadMade(enginePrestart.threadMade);
function sessionGrants({ generation: _turn, depth: _depth, roomHandoffId: _handoff, skillAuthoring: _skills, ...grants }: Omit<InternalCapability, "orphanExpiresAt">): string {
const thread = botForThread(grants.botId, grants.threadId);
@@ -1678,15 +1677,7 @@ function sessionGrants({ generation: _turn, depth: _depth, roomHandoffId: _hando
}
function sessionBearer(capability: Omit<InternalCapability, "orphanExpiresAt">): string {
- const credentials = sessionCredentials.get(capability.threadId) ?? new Map<string, { grants: string; token: string }>();
- sessionCredentials.set(capability.threadId, credentials);
- const slot = `${capability.botId} ${capability.kind}${capability.connectorsFor ? ` ${capability.connectorsFor}` : ""}`;
- const grants = sessionGrants(capability);
- const held = credentials.get(slot);
- if (held?.grants === grants) return held.token;
- const token = randomBytes(24).toString("hex");
- credentials.set(slot, { grants, token });
- return token;
+ return bearerForGrants(sessionCredentials, capability.threadId, `${capability.botId} ${capability.kind}${capability.connectorsFor ? ` ${capability.connectorsFor}` : ""}`, sessionGrants(capability));
}
function mintInternalCapability(capability: Omit<InternalCapability, "orphanExpiresAt" | "turnStartedAt">, { perTurn = false } = {}): string {
@@ -1741,7 +1732,7 @@ function revokeEarlierTurnCapabilities(threadId: string): void {
/** Also retires the thread's bearers, so nothing that still holds one is honoured again. */
function revokeInternalCapabilitiesForThread(threadId: string): void {
revokeEarlierTurnCapabilities(threadId); lateToolResults.forgetThread(threadId);
- sessionCredentials.delete(threadId);
+ sessionCredentials.delete(threadId); enginePrestart.drop(threadId);
}
function revokeAllInternalCapabilities(): void {
@@ -4481,10 +4472,10 @@ store.onChange((change) => {
broadcast({ kind: "sections", sections: store.sections });
break;
case "message":
- broadcast({ kind: "message", threadId: change.threadId, message: slimMessage(change.message) });
+ broadcast({ kind: "message", threadId: change.threadId, message: pageMessage(change.message) });
break;
case "message.patch":
- broadcast({ kind: "message.patch", threadId: change.threadId, message: slimMessage(change.message) });
+ broadcast({ kind: "message.patch", threadId: change.threadId, message: pageMessage(change.message) });
break;
case "thread":
broadcast({ kind: "thread", threadId: change.threadId, activeLeafId: change.activeLeafId });
@@ -5393,7 +5384,7 @@ bus.subscribe((event: RuntimeEvent) => {
});
// `pin` keeps a sibling thread's snapshot in the same folder from reclaiming the commit mid-turn.
const turnStartedAt = new Map<string, number>();
-const turnCheckpoints = new Map<string, { botId: string; cwd: string; hash: string; pin: string }>();
+const turnCheckpoints = new Map<string, { botId: string; cwd: string; hash: string; pin: string }>(); const checkpointSeeds = createCheckpointSeeds({ bots: () => store.bots, bot: (id) => store.bot(id), worksInFolders: (bot) => { const engine = registry.get(bot.modelSelection.instanceId); return engine ? supportsWorkspaceFiles(engine.driverKind) : false; }, refusal: checkpoints.refusalReason, prime: checkpoints.prime, onChange: (listener) => store.onChange(listener), ownRoots: [DATA_DIR] });
// Not every driver stamps every item with a turnId (some ACP agents), so unstamped rows go to the thread's live turn.
const liveTurnByThread = new Map<string, string>();
@@ -7737,23 +7728,23 @@ async function beginTurn(
turnContext.delete(threadId);
void (async () => {
- try {
+ try { const setup = perf.setupClock();
const engineRead = registry.engineRead(instance.instanceId);
if (engineRead) {
- await engineRead;
+ await engineRead; setup.lap("engineRead");
if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) throw new DirectTurnSetupCancelled("turn stopped while the engine was read");
}
if (opts?.runOn === "cloud") {
- const readiness = await cloudRoutineReadiness(botId, threadId);
+ const readiness = await cloudRoutineReadiness(botId, threadId); setup.lap("cloudReady");
if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) {
throw new DirectTurnSetupCancelled("turn stopped during cloud readiness");
}
if (!readiness.ready) throw new Error(readiness.reason ?? "The cloud computer is not ready");
}
- await warmSummaries.beforeTurn(threadId, () => directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId));
- if (usesNativeImageInput && !opts?.compactOnly) turnImages.push(...await videoFramesWithin(turnImages.length, resolvedImages.videos));
+ await warmSummaries.beforeTurn(threadId, () => directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)); setup.lap("summaries");
+ if (usesNativeImageInput && !opts?.compactOnly) turnImages.push(...await videoFramesWithin(turnImages.length, resolvedImages.videos)); setup.lap("videoFrames");
await compactConversation({ bot, threadId, generation: dispatchClaimId, instance, model,
- excludedIds: new Set([userMessage.id, ...(opts?.excludeMessageIds ?? [])]), manual: opts?.compactOnly === true });
+ excludedIds: new Set([userMessage.id, ...(opts?.excludeMessageIds ?? [])]), manual: opts?.compactOnly === true }); setup.lap("compact");
if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) throw new DirectTurnSetupCancelled("turn stopped during context setup");
if (opts?.compactOnly) {
clearDirectTurnDispatch(threadId, dispatchClaimId);
@@ -7877,13 +7868,13 @@ async function beginTurn(
],
skills,
);
- if (phoneOffered) integrations.phone = phoneIntegration(bot.id, threadId, dispatchClaimId);
+ setup.lap("context"); if (phoneOffered) integrations.phone = phoneIntegration(bot.id, threadId, dispatchClaimId);
if (bot.composio !== false && composio.configured(cfg) && instance.adapter.capabilities.composioMcp === true) {
- Object.assign(integrations, await teamConnections.appsIntegrations(bot, threadId, dispatchClaimId, instance.adapter.capabilities.mcpToolsFoundByName ? "dotted" : "plain"));
+ Object.assign(integrations, await teamConnections.appsIntegrations(bot, threadId, dispatchClaimId, instance.adapter.capabilities.mcpToolsFoundByName ? "dotted" : "plain")); setup.lap("apps");
}
// User MCP servers' tools are never pre-allowed: every call rides the normal permission flow.
if (instance.adapter.capabilities.customMcp === true && !proactive.fence.confines(threadId) && !botApiThread(threadId)) {
- const custom = await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, dispatchClaimId));
+ const custom = await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, dispatchClaimId)); setup.lap("mcp");
attachCustomMcp(integrations, { ...custom, ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: dispatchClaimId }) }, cfg, { botId: bot.id, threadId }, teamConnections.mcpServerApps(bot, { servers: custom, bridged: Boolean(integrations.composio), blocked: (slug) => managedPolicy.appsConnectRefusal([slug]) }));
if (Object.keys(custom).length) Object.assign(integrations, chatAppsMcp.turnMounts(custom, bot.toolScope));
}
@@ -7912,8 +7903,8 @@ async function beginTurn(
const mountsLocalComputer = instance.adapter.capabilities.localComputerMcp === true;
const dispatchTask = store.taskByThread(bot.id, threadId);
const handoffMayUseCloud = !computerSkipped && plan.computer === undefined && isHandedWork(opts?.coordination ? coordinator.node(opts.coordination.id) : undefined) && !teamComputer && cloudBackend === "box" && boat.boatConfigured(cfg)
- && canWorkOnCloud(cloudEngine(instance)) && !computerPlaceRefusal("box") && !cloudPlaceRefusal(cloudEngine(instance, bot.modelSelection.model), "works-on", bot.name) && !computerToolsRefusal(toolScope, "works-on", bot.name);
- const ownCloud = handoffMayUseCloud ? await ownCloudStateWithin(boat.boatStatus(cfg, bot.id)) : undefined, handoffOwnCloud = handoffUsesOwnCloud({ plan, handoffWork: Boolean(ownCloud), ownCloudState: ownCloud?.state });
+ && canWorkOnCloud(cloudEngine(instance)) && !computerPlaceRefusal("box") && !cloudPlaceRefusal(cloudEngine(instance, bot.modelSelection.model), "works-on", bot.name) && !computerToolsRefusal(toolScope, "works-on", bot.name); setup.lap("workspace");
+ const ownCloud = handoffMayUseCloud ? await ownCloudStateWithin(boat.boatStatus(cfg, bot.id)) : undefined, handoffOwnCloud = handoffUsesOwnCloud({ plan, handoffWork: Boolean(ownCloud), ownCloudState: ownCloud?.state }); if (handoffMayUseCloud) setup.lap("ownCloud");
let wants: ComputerWant = computerSkipped ? "off" : handoffOwnCloud ? "cloud" : plan.computer;
const skipComputer = (error: unknown) => {
if (!answer.incident || error instanceof DirectTurnSetupCancelled || error instanceof ComputerWaitParked) throw error;
@@ -8183,10 +8174,10 @@ async function beginTurn(
}
} catch (error) {
skipComputer(!namedPlace || !placeSource ? error : await asPlaceFailure(error, namedPlace, placeSource, bot, cloudBackend));
- }
+ } setup.lap("computer");
// Electron owns cua-driver and its TCC attribution; the harness only reads its running connection descriptor.
- if (wants === undefined && !integrations.localComputer && !computerPlaceRefusal("localVm") && await attachLocalVm(false)) computerKind = "vm";
+ if (wants === undefined && !integrations.localComputer && !computerPlaceRefusal("localVm") && await attachLocalVm(false)) computerKind = "vm"; setup.lap("localVm");
// An unattended run with a VPS configured never lands on the host's own desktop, nor does a bot whose own desktop awaits an update.
const hostBarred = (cloudBackend === "vps" && Boolean(opts?.automationSource)) || autoVpsOutdated || Boolean(vmUpdateNote);
if (
@@ -8253,8 +8244,8 @@ async function beginTurn(
const learnPrompt = skillAuthoring ? profilePrompt ? LEARN_RULES_PROMPT : LEARN_PROMPT : "";
// Wait for the snapshot right before dispatch: the engine must not edit the project until it settles.
- if (checkpointCwd) {
- const before = await checkpoints.snapshot(bot.id, checkpointCwd, `turn ${threadId.slice(0, 8)}`, undefined, { pin: dispatchClaimId });
+ if (checkpointCwd) { setup.lap("sync");
+ const before = await checkpoints.snapshot(bot.id, checkpointCwd, `turn ${threadId.slice(0, 8)}`, undefined, { pin: dispatchClaimId }); setup.lap("checkpoint");
if (!directTurnClaimIsCurrent(bot.id, dispatchClaimId, threadId)) {
if (before) void checkpoints.release(bot.id, checkpointCwd, dispatchClaimId);
throw new DirectTurnSetupCancelled("turn stopped during checkpoint");
@@ -8287,8 +8278,8 @@ async function beginTurn(
instance.adapter.capabilities.browserMcp === true
) {
const selectedProfile = liveBot.browserProfile;
- browser = await openBrowserBeside(() => browserIntegration(bot.id, selectedProfile, { threadId, generation: dispatchClaimId }),
- mountedComputer, (error) => console.warn(`[browser] thread ${threadId}: left out beside ${mountedComputer} (${redactSecretsInText(String(error))})`));
+ setup.lap("sync"); browser = await openBrowserBeside(() => browserIntegration(bot.id, selectedProfile, { threadId, generation: dispatchClaimId }),
+ mountedComputer, (error) => console.warn(`[browser] thread ${threadId}: left out beside ${mountedComputer} (${redactSecretsInText(String(error))})`)); setup.lap("browser");
if (browser) integrations.browser = browser.integration;
if (browser) {
const spec = browser.spec;
@@ -8311,7 +8302,7 @@ async function beginTurn(
if (computerSelection) computerSelection.mounted = mountedComputer ?? (integrations.browser ? "browser" : undefined);
recordTurnPlace(bot.id, threadId, plan.computer === undefined && mountedComputer === "local" && integrations.browser ? "browser" : mountedComputer ?? (integrations.browser ? "browser" : null));
// Never overlap a replacement with a cancelled adapter's pre-id window: wait for it, then revalidate this exact claim.
- await pendingCancelledProviderHandshakes.waitForClear(threadId);
+ setup.lap("sync"); await pendingCancelledProviderHandshakes.waitForClear(threadId); setup.lap("handshakeClear");
if (!markDirectTurnDispatching(bot.id, dispatchClaimId, threadId)) {
throw new DirectTurnSetupCancelled("turn stopped before dispatch");
}
@@ -8328,7 +8319,7 @@ async function beginTurn(
applyAgentsBridge(threadId, integrations, cfg, bot, turnEngine(instance, providerConfigs(), registry.lastSnapshot(instance.instanceId), cwd));
const confined = proactive.fence.confines(threadId), apiFenced = botApiThread(threadId); if (confined || apiFenced) for (const key of Object.keys(integrations) as Array<keyof typeof integrations>) if (!(apiFenced ? BOT_API_TOOLS : READ_AND_DRAFT_TOOLS).has(key)) delete integrations[key];
const selectionRulesStable = Boolean(integrations.agents) && bot.computer !== "off" && !inheritedTeamComputer(bot), memoryOpts = { managedWrites: Boolean(integrations.agents), fileTools: worksInWorkspace && !apiFenced, enabled: bot.memoryEnabled !== false, writesRefused: notesRefused };
- const prompt = buildSystemPrompt(persona, liveBot?.soul ?? bot.soul ?? "", [
+ setup.lap("sync"); const prompt = buildSystemPrompt(persona, liveBot?.soul ?? bot.soul ?? "", [
{ id: "user-profile", label: "About the user", text: userProfileSystemPrompt(teamHost.profileFor(threadId, cfg.profile)) }, { id: "people", label: "People", text: teamMessages.prompt(bot.id, threadId, Boolean(integrations.agents)) }, { id: "long-waits", label: "Waiting on the person", text: teammatePrompts.personBehind(bot.id, threadId) ? teamMessages.longWaits(threadId) : "" },
{ id: "setup", label: "Setup", text: setupSystemPrompt(setupMode, {
skills: skillAuthoring, chief: Boolean((liveBot ?? bot).chiefOfStaff),
@@ -8378,7 +8369,7 @@ async function beginTurn(
{ id: "webhook", label: "Webhook provenance", text: opts?.automationSource === "webhook" ? WEBHOOK_PROMPT : opts?.automationSource === "api" ? (botApiThread(threadId) ? BOT_API_PROMPT : BOT_API_OWNER_PROMPT) : "" },
{ id: "automation-reply", label: "Automation reply", text: opts?.automationSource && automationReports.reportsElsewhere(threadId) ? AUTOMATION_REPLY_PROMPT : "" },
{ id: "mentions", label: "Mentions", text: (tagged.length ? `The user named these existing teammates: ${tagged.map(b => `${peerName(b.name)} (${b.id})`).join(", ")}. Use coordinate_bots when their contribution is needed; do not substitute native helper agents for these bots.` : "") + placesElsewhere.mentioned(providerText, store.bots) },
- ].filter((part) => (apiFenced ? BOT_API_PARTS.has(part.id) : !confined || READ_AND_DRAFT_PARTS.has(part.id))), integrations.agents, { replyStyle: liveBot?.replyStyle ?? bot.replyStyle, rules: cfg.everyBotRules });
+ ].filter((part) => (apiFenced ? BOT_API_PARTS.has(part.id) : !confined || READ_AND_DRAFT_PARTS.has(part.id))), integrations.agents, { replyStyle: liveBot?.replyStyle ?? bot.replyStyle, rules: cfg.everyBotRules }); setup.lap("prompt");
turnPromptBytes.set(threadId, { stable: Buffer.byteLength(prompt.stable), volatile: Buffer.byteLength(prompt.volatile) });
// Recall rides in front of this turn's message, never the system prompt, whose volatile half is re-sent whole on any change.
const recalled = autoRecallPrompt(bot, threadId, resolvedImages.text, {
@@ -8399,7 +8390,7 @@ async function beginTurn(
const shareNote = skillsHost.shareNote(bot, threadId, Boolean(privateWorkspace));
const startupRecovery = (opts?.automaticRecoveryIndex ?? 0) < startupBackups(liveBot ?? bot, cfg.automaticRecovery).length; const posted = unreadThreadPosts(store.activePath(threadId)); // post_to_thread messages left here since its last run
const held = limitTakeover.heldAtStart(bot, { instanceId, model }, startupRecovery); // a limit or a sign-out already known: straight to an AI that can carry on, with the reset only when one was named
- if (held) throw held.scope === "signed-out" ? Object.assign(new TurnAuthenticationRefusedError(`signed-out-${randomUUID()}`, `${engineName(instanceId)} is signed out.`, true), userErrorFields(userError("serverError.engine.signedOut", { name: engineName(instanceId) }))) : new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, held.resetsAt, held.scope, true);
+ if (held) throw held.scope === "signed-out" ? Object.assign(new TurnAuthenticationRefusedError(`signed-out-${randomUUID()}`, `${engineName(instanceId)} is signed out.`, true), userErrorFields(userError("serverError.engine.signedOut", { name: engineName(instanceId) }))) : new TurnUsageLimitRefusedError(`limit-${randomUUID()}`, `${engineName(instanceId)} is at its usage limit.`, held.resetsAt, held.scope, true); perf.noteSetup(threadId, setup.done());
const dispatch = await guardTurnDispatch(shareNote.after(savedSteps.dispatch.sendTurn(instance, personLine && !opts?.unattended && !opts?.app?.context && !guestConfined ? { botId: bot.id, message: userMessage, turnText: text, placePicked: wants === "local" && placeSource !== "auto-pin" } : null, {
threadId,
botId: bot.id,
@@ -8427,7 +8418,7 @@ async function beginTurn(
...skillsHost.turnSettings(bot, threadId, instance, managedPolicy.restrictsMcp()),
cwd, ...(worksInWorkspace || guestConfined || cloudGuestOpened(threadId) ? {} : { toolResultFolder: messageFileRootsForThread(bot.id, threadId).find((root) => root !== ATTACHMENTS_DIR) }),
botSettingsFile: botSettingsFile(bot),
- }, (input) => quickFallback.sendTurn(instance, input, route.quickModel ? { model, own: bot.modelSelection, onFallback: () => store.patchMessage(threadId, userMessage.id, { quickModel: undefined }) } : undefined))), () => companyShutdown || !directTurnClaimExists(bot.id, dispatchClaimId, threadId), async () => {
+ }, (input) => quickFallback.sendTurn(instance, enginePrestart.note(instance.instanceId, input, personLine && !automated), route.quickModel ? { model, own: bot.modelSelection, onFallback: () => store.patchMessage(threadId, userMessage.id, { quickModel: undefined }) } : undefined))), () => companyShutdown || !directTurnClaimExists(bot.id, dispatchClaimId, threadId), async () => {
await (runningTurnEngines.get(threadId) ?? instance).adapter.interruptTurn(threadId).catch(() => {});
});
if (dispatch.cancelled) {
@@ -12062,7 +12053,7 @@ const { react } = createReactions({
});
const publishedPages = createPublishedPages({ dataDir: DATA_DIR, cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, patch: (threadId, messageId, text, publishedPage) => void store.patchMessage(threadId, messageId, { text, publishedPage }), liveRoots: (botId, threadId) => liveRoots(threadId, botId), paused: () => workspaceMaintenance.active || moveFreeze.frozen(), apps: { chat: chatApps, store } }); ROUTES.push(createReactionRoutes({ react, reactorFor, cloudGuestSendRefusal }), publishedPages.routes, savedSteps.routes, createPlacesElsewhereRoutes({ elsewhere: placesElsewhere, owner: (auth) => !sharedMembership() && !HOSTED_WORKSPACE && (auth.kind === "loopback" || ownHome.owner(auth) || (CLOUD_PERSONAL && cloudOwnerSession(auth))) }));
// `let` slots are read per request.
-const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, threadsReferencing, keptAttachments, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), engineFolders: () => engineSessionFolders(DATA_DIR, [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env))), layers: memoryLayerRecords });
+const keptAttachments = () => { const routineFiles = routines?.attachmentPaths(); return routineFiles && calendarCalls ? keptAttachmentNames([...store.bots.map((bot) => bot.avatarUrl), cfg.profile?.avatarUrl], [workspaceBannerStore.current()?.name, ...routineFiles, ...calendarCalls.list().flatMap((call) => call.attachments?.map((file) => file.path) ?? []), ...[...turnAttachmentsByTurn.values()].flat().map((file) => file.path)]) : null; }; createDeleteLeftovers({ dataDir: DATA_DIR, store, checkpointsQuiet: checkpoints.quiet, threadsReferencing, keptAttachments, deleteAttachment: (name) => deleteAttachment(join(ATTACHMENTS_DIR, name)), engineFolders: () => engineSessionFolders(DATA_DIR, [process.env, ...Object.values(providerConfigs()).map((instance) => instanceEnvironment(process.env, instance))].flatMap((env) => engineHomes.everyHome(env))), layers: memoryLayerRecords });
ROUTES.push(createThreadRoutes({
groupFor: personRooms.groupForAuth, ...(botOrders ? { botOrderFor: (auth: RequestAuth, bots: readonly BotRecord[]) => { const person = botOrders.personOf(auth); return person ? botOrders.ordered(person, bots) : bots; } } : {}),
store, userName: userNameFor, sessions, groupUsageReader, lendingEnabled,
@@ -14641,7 +14632,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (method === "GET" && path === "/api/bot-defaults") {
return json(res, 200, {
defaults: structuredClone(cfg.newBotDefaults ?? newBotDefaultsSchema.parse({})),
- modelSelection: await defaultSelection(),
+ modelSelection: await suggestedSelection({ reused: (age) => registry.describe({ reuse: { ...age, changed: () => broadcast({ kind: "config", ...configStatus() }) } }), fresh: () => registry.describe(), select: (instances) => defaultSelection(undefined, instances) }),
suggestedName: pickBotName(store.bots.map(bot => bot.name)),
});
}
@@ -15261,7 +15252,7 @@ server.listen(PORT, listenHost(server), async () => {
companyRuntimeReady(); cloudHealth?.speed.ready(); void tailnetShare.start(process.env);
console.log(`openmausbot server on http://127.0.0.1:${PORT}`);
personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); startCloudTeamRoster({ cloudHome: CLOUD_HOME, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, ownKey: () => composio.connectionMode(cfg) === "self-hosted", apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });
- void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });
+ void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); checkpointSeeds.start(); });
followupsReady = true; engineUpdates.start();
drainQueuedSends();
drainQueuedChannelSends();
@@ -15322,7 +15313,7 @@ const gracefulShutdown = createGracefulShutdown({
followupsReady = false;
companyShutdown = true;
// Before any provider is torn down, so what the teardown fails stays cut for the next start.
- coordinator.close(); botLink.close();
+ coordinator.close(); botLink.close(); checkpointSeeds.stop(); checkpoints.stopCollections();
noteTurnsCutByShutdown();
if (workspaceAccessTimer) clearInterval(workspaceAccessTimer);
// Invalidate turn bearers before any cleanup reaches an await: child MCP processes and the listener may outlive it.
diff --git a/server/managed-desktop.ts b/server/managed-desktop.ts
index 4d01ad852b..7725777077 100644
--- a/server/managed-desktop.ts
+++ b/server/managed-desktop.ts
@@ -149,6 +149,7 @@ export class ManagedDesktopProviders {
},
adapter: {
...instance.adapter,
+ prestart: undefined, // every start goes through the check below
sendTurn: async input => {
if (!active()) throw new Error(unavailable());
if (!input.model || !provider.models.includes(input.model)) throw new Error("This model is not enabled by your Company administrator.");
diff --git a/server/perf/day-ledger.ts b/server/perf/day-ledger.ts
index 820bb88aeb..7c2d47f152 100644
--- a/server/perf/day-ledger.ts
+++ b/server/perf/day-ledger.ts
@@ -1,6 +1,7 @@
// The last day of turn timings by hour: one histogram per phase and per tool kind, and counts. Bounded at 25 hours of
// fixed-size slots whatever the traffic.
import { addTo, countOf, emptyHistogram, histogramQuantile, mergeInto, parseHistogram, PHASES, type Histogram, type Phase, type PhaseStats } from "./phases.ts";
+import { SETUP_STEPS, type SetupStats, type SetupStep } from "./setup-steps.ts";
import { activeMs, counter, isLimitScope, isRetryCode, isToolKind, KIND, type LimitScope, type ToolKind, type TurnTiming } from "./turn-record.ts";
const HOUR = 3_600_000;
@@ -16,6 +17,7 @@ interface Slot {
failed: number;
slow: number[];
phases: Partial<Record<Phase, Histogram>>;
+ setup: Partial<Record<SetupStep, Histogram>>;
tools: Partial<Record<ToolKind, ToolSlot>>;
retries: { turns: number; n: number; backoffMs: number; why: Record<string, number> };
/** Turns a usage limit refused, by `<engine kind>:<scope>`. */
@@ -23,7 +25,7 @@ interface Slot {
failovers: number;
}
-const emptySlot = (hour: number): Slot => ({ hour, turns: 0, failed: 0, slow: SLOW_TURN_MS.map(() => 0), phases: {}, tools: {},
+const emptySlot = (hour: number): Slot => ({ hour, turns: 0, failed: 0, slow: SLOW_TURN_MS.map(() => 0), phases: {}, setup: {}, tools: {},
retries: { turns: 0, n: 0, backoffMs: 0, why: counter() }, limits: counter(), failovers: 0 });
const bump = (map: Record<string, number>, key: string, cap: number, by = 1) => {
@@ -36,6 +38,8 @@ export interface DayAggregate {
turns: number;
failed: number;
phases: Partial<Record<Phase, PhaseStats>>;
+ /** Bucketed like the phases: a step under the first bucket's edge reads as that edge at most. */
+ setup: SetupStats;
slow: number[];
tools: ToolAggregate[];
retries: { turns: number; n: number; backoffMs: number; why: Record<string, number> };
@@ -75,6 +79,10 @@ export function createDayLedger(now: () => number) {
const ms = turn.ms[phase];
if (ms !== undefined) addTo(into.phases[phase] ??= emptyHistogram(), ms);
}
+ for (const step of SETUP_STEPS) {
+ const ms = turn.setup?.[step];
+ if (ms !== undefined) addTo(into.setup[step] ??= emptyHistogram(), ms);
+ }
const active = activeMs(turn);
SLOW_TURN_MS.forEach((edge, index) => { if (active > edge) into.slow[index]! += 1; });
if (turn.retries) {
@@ -92,13 +100,15 @@ export function createDayLedger(now: () => number) {
const from = Math.floor((now() - windowMs) / HOUR);
const phases: Partial<Record<Phase, Histogram>> = {};
const tools: Partial<Record<ToolKind, ToolSlot>> = {};
- const out: DayAggregate = { turns: 0, failed: 0, phases: {}, slow: SLOW_TURN_MS.map(() => 0), tools: [],
+ const setup: Partial<Record<SetupStep, Histogram>> = {};
+ const out: DayAggregate = { turns: 0, failed: 0, phases: {}, setup: {}, slow: SLOW_TURN_MS.map(() => 0), tools: [],
retries: { turns: 0, n: 0, backoffMs: 0, why: counter() }, limits: counter(), failovers: 0 };
for (const entry of slots.values()) {
if (entry.hour <= from) continue;
out.turns += entry.turns; out.failed += entry.failed; out.failovers += entry.failovers;
entry.slow.forEach((count, index) => { out.slow[index]! += count; });
for (const [phase, histogram] of Object.entries(entry.phases) as Array<[Phase, Histogram]>) mergeInto(phases[phase] ??= emptyHistogram(), histogram);
+ for (const [step, histogram] of Object.entries(entry.setup) as Array<[SetupStep, Histogram]>) mergeInto(setup[step] ??= emptyHistogram(), histogram);
for (const [kind, tool] of Object.entries(entry.tools) as Array<[ToolKind, ToolSlot]>) {
const into = tools[kind] ??= { hist: emptyHistogram(), errors: 0, open: 0 };
mergeInto(into.hist, tool.hist); into.errors += tool.errors; into.open += tool.open;
@@ -108,6 +118,7 @@ export function createDayLedger(now: () => number) {
for (const [key, count] of Object.entries(entry.limits)) bump(out.limits, key, LIMIT_KEYS_KEPT, count);
}
for (const phase of PHASES) if (phases[phase]) out.phases[phase] = statsOf(phases[phase]);
+ for (const step of SETUP_STEPS) if (setup[step]) out.setup[step] = statsOf(setup[step]);
out.tools = (Object.entries(tools) as Array<[ToolKind, ToolSlot]>)
.map(([kind, tool]) => ({ kind, n: countOf(tool.hist), errors: tool.errors, open: tool.open, ms: tool.hist.sum, p95: histogramQuantile(tool.hist, 0.95), max: tool.hist.max }))
.sort((left, right) => right.ms - left.ms);
@@ -146,6 +157,10 @@ function parseSlot(raw: Record<string, unknown> | null): Slot | null {
const value = (raw.phases as Record<string, unknown> | undefined)?.[phase];
if (value) slot.phases[phase] = parseHistogram(value);
}
+ for (const step of SETUP_STEPS) {
+ const value = (raw.setup as Record<string, unknown> | undefined)?.[step];
+ if (value) slot.setup[step] = parseHistogram(value);
+ }
for (const [kind, value] of Object.entries((raw.tools ?? {}) as Record<string, Record<string, unknown>>)) {
if (isToolKind(kind) && value) slot.tools[kind] = { hist: parseHistogram(value.hist), errors: whole(value.errors), open: whole(value.open) };
}
diff --git a/server/perf/loop-stalls.test.ts b/server/perf/loop-stalls.test.ts
index 9e43486532..8a6a757647 100644
--- a/server/perf/loop-stalls.test.ts
+++ b/server/perf/loop-stalls.test.ts
@@ -70,7 +70,7 @@ describe("the loop stall recorder", () => {
it("fits the health report's budget with the rest of the timings, and holds numbers only", () => {
const stalls = createLoopStalls();
const report = stalls.report();
- const body = perfHealth({ hour: { turns: 0, failed: 0, phases: {}, slow: [], partial: false }, day: { turns: 0, failed: 0, slow: [], phases: {}, tools: [], retries: { n: 0, turns: 0, backoffMs: 0, why: {} }, limits: {}, failovers: 0 } as never,
+ const body = perfHealth({ hour: { turns: 0, failed: 0, phases: {}, setup: {}, slow: [], partial: false }, day: { turns: 0, failed: 0, slow: [], phases: {}, setup: {}, tools: [], retries: { n: 0, turns: 0, backoffMs: 0, why: {} }, limits: {}, failovers: 0 } as never,
live: [], limits: null, process: null, stalls: report });
expect(JSON.stringify(body).length).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);
expect(body.stalls).toEqual(report);
diff --git a/server/perf/perf-host.ts b/server/perf/perf-host.ts
index eb5cd4cfcd..f12bad7e24 100644
--- a/server/perf/perf-host.ts
+++ b/server/perf/perf-host.ts
@@ -11,6 +11,7 @@ import { duration, limitHolds, perfHealth, perfLines, turnLine, type PerfHealth
import { createProcessHealth, type ProcessHealthRecorder } from "./process-health.ts";
import type { ProcessRow } from "./process-buckets.ts";
import { createProcessSampler, linuxProcessList, LINUX_SAMPLE_MS, nodeUtilization, OTHER_SAMPLE_MS, psProcessList, type ProcessSampler } from "./process-sampler.ts";
+import { createSetupClock, type SetupClock, type SetupMs } from "./setup-steps.ts";
import type { FailoverWhy } from "./turn-record.ts";
import { createTurnTimings, type Refusal, type SlowNote, type TurnTimings } from "./turn-timings.ts";
@@ -120,6 +121,9 @@ export function createPerfHost(deps: PerfHostDeps) {
noteHeld: (threadId: string, why: "plan-limit" | "memory") => guarded("held", () => timings.noteHeld(threadId, why), undefined),
noteFailover: (threadId: string, why: FailoverWhy) => guarded("failover", () => timings.noteFailover(threadId, why), undefined),
noteNotStarted: (threadId: string, turnId: string | null, refusal?: Refusal) => guarded("refused", () => timings.noteNotStarted(threadId, turnId, refusal), undefined),
+ /** Times one direct turn's setup; its laps go to `noteSetup` just before the engine is asked. */
+ setupClock: (): SetupClock => createSetupClock(),
+ noteSetup: (threadId: string, ms: SetupMs) => guarded("setup", () => timings.noteSetup(threadId, ms), undefined),
/** Logs a usage-limit hold that started or ended since the last check; the sampler runs it after each sample. */
checkHolds: watchHolds,
health: (): PerfHealth | null => guarded("health", () => perfHealth(sources()), null),
diff --git a/server/perf/perf-privacy.test.ts b/server/perf/perf-privacy.test.ts
index 193622c3b2..6117ff13e5 100644
--- a/server/perf/perf-privacy.test.ts
+++ b/server/perf/perf-privacy.test.ts
@@ -9,6 +9,7 @@ import { buildDevsReport } from "../devs-report.ts";
import type { StoreChange } from "../store.ts";
import { createPerfHost, PERF_FILE } from "./perf-host.ts";
import { PERF_HEALTH_MAX_BYTES, perfHealth } from "./perf-report.ts";
+import { SETUP_STEPS } from "./setup-steps.ts";
import { createProcessSampler, type ProcessList } from "./process-sampler.ts";
import { createTurnTimings, RING_CAP } from "./turn-timings.ts";
@@ -168,6 +169,7 @@ describe("the perf field's size", () => {
for (let retry = 0; retry < 4; retry++) big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.retrying", attempt: retry, delayMs: 1000, reason: `reason_${(turn * 4 + retry) % 20}` });
big.noteEvent({ eventId: "e", provider: `engine${turn % 20}`, threadId, createdAt: "", turnId: `t${turn}`, type: "runtime.error", message: "m", limit: (["engine", "model", "credits"] as const)[turn % 3] });
clock += 1_234_567;
+ big.noteSetup(`thread_${turn + 1}`, Object.fromEntries(SETUP_STEPS.map((step, index) => [step, 1_234_567 + index])));
if (turn < 250) big.noteEvent({ eventId: "e", provider: "p", threadId, createdAt: "", turnId: `t${turn}`, type: "turn.completed", ok: turn % 2 === 0 });
}
clock = START + 250 * 1_234_567;
@@ -181,6 +183,8 @@ describe("the perf field's size", () => {
console.log(`perf health, every part full: ${bytes} bytes (budget ${PERF_HEALTH_MAX_BYTES})`);
expect(bytes).toBeLessThanOrEqual(PERF_HEALTH_MAX_BYTES);
expect(body.h24.tools.length).toBeGreaterThan(0);
+ expect(Object.keys(body.h24.setup)).toHaveLength(7);
+ expect(Object.keys(body.h1.setup)).toHaveLength(7);
});
});
diff --git a/server/perf/perf-report.ts b/server/perf/perf-report.ts
index a011b900d3..d2406eb9e6 100644
--- a/server/perf/perf-report.ts
+++ b/server/perf/perf-report.ts
@@ -9,13 +9,14 @@ import { PHASES, type Phase, type PhaseStats } from "./phases.ts";
import type { StallsReport, StallStats, Tally } from "./loop-stalls.ts";
import { processHealthLines, trimmedProcessHealth, type ProcessHealth } from "./process-health.ts";
import type { ProcessReport } from "./process-sampler.ts";
+import { SETUP_STEPS, slowestSetupSteps, type SetupStats } from "./setup-steps.ts";
import { RING_CAP, type LiveTurnView, type WindowStats } from "./turn-timings.ts";
import type { TurnTiming } from "./turn-record.ts";
/** The health report's `perf` field is at most this many bytes of JSON; parts are dropped, least useful first, to fit. */
export const PERF_HEALTH_MAX_BYTES = 8 * 1024;
export const PERF_HEALTH_VERSION = 1;
-const LIVE_SHOWN = 5, TOOLS_SHOWN = 8, HOLDS_SHOWN = 8;
+const LIVE_SHOWN = 5, TOOLS_SHOWN = 8, HOLDS_SHOWN = 8, SETUP_STEPS_SHOWN = 6, TURN_SETUP_STEPS_SHOWN = 3;
const LIMIT_DRIVERS = new Set(["claude", "codex", "grok", "opencode"]);
const WINDOWS = new Set(["5-hour", "weekly", "other"]);
@@ -46,13 +47,15 @@ export function limitHolds(report: EngineLimitsReport | null | undefined): Limit
const phasesOf = (phases: Partial<Record<Phase, PhaseStats>>) => Object.fromEntries(PHASES.flatMap((phase) => (phases[phase] ? [[phase, phases[phase]]] : [])));
+const setupOf = (stats: SetupStats, kept = SETUP_STEPS_SHOWN): SetupStats => Object.fromEntries(slowestSetupSteps(stats, kept));
+
export function perfHealth(sources: PerfSources) {
const { hour, day } = sources;
const body = {
v: PERF_HEALTH_VERSION,
slowEdgesMs: [...SLOW_TURN_MS],
- h1: { turns: hour.turns, failed: hour.failed, partial: hour.partial, slow: hour.slow, phases: phasesOf(hour.phases) },
- h24: { turns: day.turns, failed: day.failed, slow: day.slow, phases: phasesOf(day.phases), tools: day.tools.slice(0, TOOLS_SHOWN), retries: day.retries, limits: day.limits, failovers: day.failovers },
+ h1: { turns: hour.turns, failed: hour.failed, partial: hour.partial, slow: hour.slow, phases: phasesOf(hour.phases), setup: setupOf(hour.setup) },
+ h24: { turns: day.turns, failed: day.failed, slow: day.slow, phases: phasesOf(day.phases), setup: setupOf(day.setup), tools: day.tools.slice(0, TOOLS_SHOWN), retries: day.retries, limits: day.limits, failovers: day.failovers },
live: sources.live.slice(0, LIVE_SHOWN),
holds: limitHolds(sources.limits),
process: sources.process,
@@ -61,6 +64,7 @@ export function perfHealth(sources: PerfSources) {
bots: sources.bots ?? null,
};
const size = () => JSON.stringify(body).length;
+ if (size() > PERF_HEALTH_MAX_BYTES) { body.h1.setup = setupOf(hour.setup, 2); body.h24.setup = setupOf(day.setup, 2); }
if (size() > PERF_HEALTH_MAX_BYTES && body.bots) body.bots = { ...body.bots, shown: body.bots.shown.slice(0, 3), ...(body.bots.cap ? { cap: { ...body.bots.cap, events: body.bots.cap.events.slice(-1) } } : {}) };
if (size() > PERF_HEALTH_MAX_BYTES && body.process) body.process = { ...body.process, buckets: body.process.buckets.slice(0, 6) };
if (size() > PERF_HEALTH_MAX_BYTES) body.h24.tools = body.h24.tools.slice(0, 4);
@@ -95,6 +99,8 @@ export function duration(ms: number): string {
const iso = (at: number) => new Date(at).toISOString().replace(/\.\d{3}Z$/, "Z");
const phaseLine = (phases: Partial<Record<Phase, PhaseStats>>) =>
PHASES.flatMap((phase) => { const stats = phases[phase]; return stats ? [`${phase} p50 ${duration(stats.p50)} p95 ${duration(stats.p95)} max ${duration(stats.max)}`] : []; }).join("; ");
+const setupLine = (stats: SetupStats) =>
+ slowestSetupSteps(stats, SETUP_STEPS.length).map(([step, one]) => `${step} p50 ${duration(one.p50)} p95 ${duration(one.p95)} max ${duration(one.max)}${step === "total" ? "" : ` (${one.n})`}`).join("; ");
const slowLine = (slow: number[]) => SLOW_TURN_MS.map((edge, index) => `${slow[index] ?? 0} over ${duration(edge)}`).join(", ");
const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? "" : "s"}`;
const counts = (map: Record<string, number>) => Object.entries(map).sort((a, b) => b[1] - a[1]).map(([key, count]) => `${key} ${count}`).join(", ");
@@ -102,6 +108,9 @@ const counts = (map: Record<string, number>) => Object.entries(map).sort((a, b)
export function turnLine(turn: TurnTiming): string {
const parts = PHASES.filter((phase) => phase !== "total" && turn.ms[phase] !== undefined)
.map((phase) => `${phase} ${duration(turn.ms[phase]!)}${phase === "queue" && turn.queueWhy ? ` (${turn.queueWhy})` : ""}`);
+ const steps = SETUP_STEPS.flatMap((step) => (step !== "total" && turn.setup?.[step] ? [[step, turn.setup[step]] as const] : []))
+ .sort((left, right) => right[1] - left[1]).slice(0, TURN_SETUP_STEPS_SHOWN).map(([step, ms]) => `${step} ${duration(ms)}`);
+ if (turn.setup?.total !== undefined) parts.push(`setup ${duration(turn.setup.total)}${steps.length ? ` (${steps.join(", ")})` : ""}`);
const tools = turn.tools.map((tool) => `${tool.kind} ${tool.n}x ${duration(tool.ms)}${tool.errors ? ` ${tool.errors} failed` : ""}${tool.open ? ` ${tool.open} left open` : ""}`);
const extra = [
turn.retries ? `retries ${turn.retries} (${(turn.retryWhy ?? []).join(", ")}), backoff ${duration(turn.backoffMs)}` : "",
@@ -118,8 +127,10 @@ export function perfLines(sources: PerfSources, recent: readonly TurnTiming[], r
const lines = ["## Performance (timings only: no messages, names, files or addresses)"];
lines.push(`Last hour: ${plural(hour.turns, "turn")}, ${hour.failed} failed${hour.partial ? ` (only the latest ${RING_CAP} kept)` : ""}; slow: ${slowLine(hour.slow)}`);
if (hour.turns) lines.push(` ${phaseLine(hour.phases)}`);
+ if (hour.setup.total) lines.push(` Turn setup, inside queue (turns it took 1ms or more): ${setupLine(hour.setup)}`);
lines.push(`Last 24 h: ${plural(day.turns, "turn")}, ${day.failed} failed; slow: ${slowLine(day.slow)}`);
if (day.turns) lines.push(` ${phaseLine(day.phases)}`);
+ if (day.setup.total) lines.push(` Turn setup, inside queue (turns it took 1ms or more): ${setupLine(day.setup)}`);
if (day.tools.length) lines.push(` Tool kinds by time: ${day.tools.slice(0, TOOLS_SHOWN).map((tool) =>
`${tool.kind} ${duration(tool.ms)} (${plural(tool.n, "call")}, p95 ${duration(tool.p95)}, max ${duration(tool.max)}${tool.errors ? `, ${tool.errors} failed` : ""}${tool.open ? `, ${tool.open} left open` : ""})`).join("; ")}`);
if (day.retries.n) lines.push(` Retries: ${day.retries.n} in ${plural(day.retries.turns, "turn")}, ${duration(day.retries.backoffMs)} of backoff (${counts(day.retries.why)})`);
diff --git a/server/perf/setup-steps.e2e.test.ts b/server/perf/setup-steps.e2e.test.ts
new file mode 100644
index 0000000000..b562017a43
--- /dev/null
+++ b/server/perf/setup-steps.e2e.test.ts
@@ -0,0 +1,23 @@
+import { expect, it } from "vitest";
+import { launchVerificationServer } from "../../scripts/control-omb.ts";
+
+it("a direct turn's setup shows in the diagnostics: its total over the hour and on the turn's own line", async () => {
+ const fixture = await launchVerificationServer();
+ const api = async (method: string, path: string, body?: unknown) => {
+ const response = await fetch(`${fixture.info.url}${path}`, { method, headers: { "content-type": "application/json", origin: fixture.info.url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });
+ expect(response.ok).toBe(true);
+ return response.json() as Promise<Record<string, never>>;
+ };
+ try {
+ const { bots } = await api("GET", "/api/bots") as unknown as { bots: Array<{ id: string; threadId: string }> };
+ const bot = bots[0]!;
+ await api("POST", `/api/bots/${bot.id}/messages`, { text: "Say hi", threadId: bot.threadId });
+ const lines = async () => String((await api("GET", "/api/diagnostics/performance") as unknown as { text: string }).text).split("\n");
+ const finished = (line: string) => line.includes(`thread ${bot.threadId}`) && line.includes("queue ");
+ await expect.poll(async () => (await lines()).some(finished), { timeout: 30_000 }).toBe(true);
+ const text = await lines();
+ expect(text.filter((line) => line.includes("Turn setup, inside queue")).every((line) => /: total p50 \d/.test(line))).toBe(true);
+ expect(text.filter((line) => line.includes("Turn setup, inside queue"))).toHaveLength(2);
+ expect(text.find(finished)).toMatch(/queue \S+ \(dispatch\).*, setup \d/);
+ } finally { await fixture.close(); }
+}, 90_000);
diff --git a/server/perf/setup-steps.test.ts b/server/perf/setup-steps.test.ts
new file mode 100644
index 0000000000..6fa93b5c29
--- /dev/null
+++ b/server/perf/setup-steps.test.ts
@@ -0,0 +1,144 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import type { RuntimeEvent } from "../contracts.ts";
+import { perfHealth, perfLines, turnLine } from "./perf-report.ts";
+import { createSetupClock, parseSetupMs, SETUP_STEPS } from "./setup-steps.ts";
+import { createTurnTimings } from "./turn-timings.ts";
+
+const START = 1_800_000_000_000;
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+function world(file?: string) {
+ let clock = START;
+ const timings = createTurnTimings({ now: () => clock, botOf: () => "bot_1", ...(file ? { file } : {}) });
+ const emit = (type: string, threadId = "thread_1", turnId = "turn_1", extra: Record<string, unknown> = {}) =>
+ timings.noteEvent({ eventId: "e", provider: "claudeAgent", threadId, createdAt: "", turnId, type, ...extra } as RuntimeEvent);
+ return { timings, emit, advance: (ms: number) => { clock += ms; }, now: () => clock };
+}
+const sources = (timings: ReturnType<typeof createTurnTimings>) => ({ hour: timings.window(), day: timings.day(), live: timings.live(), limits: null, process: null });
+
+describe("the setup clock", () => {
+ it("gives each lap the time since the one before, adds a name lapped twice, and files the rest as sync", () => {
+ let at = 100;
+ const queued: Array<() => void> = [];
+ const clock = createSetupClock(() => at, (run) => queued.push(run));
+ at += 7; queued.shift()!();
+ at += 40; clock.lap("compact");
+ at += 3; clock.lap("sync");
+ at += 250; clock.lap("checkpoint");
+ at += 2; clock.lap("sync");
+ at += 0.4; clock.lap("browser");
+ at += 5;
+ expect(clock.done()).toEqual({ total: 307, handoff: 7, compact: 40, checkpoint: 250, sync: 10 });
+ at += 90; clock.lap("browser");
+ expect(clock.done()).toEqual({ total: 307, handoff: 7, compact: 40, checkpoint: 250, sync: 10 });
+ });
+
+ it("takes its first lap by itself once its maker's own work is over, before any awaited step resumes", async () => {
+ let at = 0;
+ const clock = createSetupClock(() => at);
+ at += 12;
+ await Promise.resolve();
+ at += 30; clock.lap("summaries");
+ expect(clock.done()).toEqual({ total: 42, handoff: 12, summaries: 30 });
+ });
+
+ it("never goes negative when the clock steps back", () => {
+ let at = 100;
+ const clock = createSetupClock(() => at, () => {});
+ at -= 50; clock.lap("mcp");
+ expect(clock.done()).toEqual({ total: 0 });
+ });
+
+ it("reads back known steps and numbers only", () => {
+ expect(parseSetupMs({ total: 12.4, mcp: 7, "rm -rf /": 3, browser: "4", checkpoint: -1, compact: Number.NaN, __proto__: { apps: 1 } })).toEqual({ total: 12, mcp: 7 });
+ expect(parseSetupMs({ mcp: 7 })).toBeUndefined();
+ expect(parseSetupMs("total")).toBeUndefined();
+ });
+});
+
+describe("a turn's setup, recorded with the turn", () => {
+ it("rides on the thread's next turn to start, in its record, the hour, the day, the health read and the lines", () => {
+ const w = world();
+ w.timings.noteSetup("thread_1", { total: 420, checkpoint: 300, mcp: 90, prompt: 20, sync: 10 });
+ w.timings.noteSetup("thread_2", { total: 20, prompt: 20 });
+ w.emit("turn.started");
+ w.emit("turn.started", "thread_2", "turn_2");
+ w.advance(1_000);
+ w.emit("turn.completed", "thread_1", "turn_1", { ok: true });
+ w.emit("turn.completed", "thread_2", "turn_2", { ok: true });
+ w.emit("turn.started", "thread_1", "turn_3");
+ w.emit("turn.completed", "thread_1", "turn_3", { ok: true });
+
+ const [first, second, third] = w.timings.recent();
+ expect(first!.setup).toEqual({ total: 420, checkpoint: 300, mcp: 90, prompt: 20, sync: 10 });
+ expect(second!.setup).toEqual({ total: 20, prompt: 20 });
+ expect(third!.setup).toBeUndefined();
+ expect(turnLine(first!)).toContain("setup 420ms (checkpoint 300ms, mcp 90ms, prompt 20ms)");
+ expect(turnLine(third!)).not.toContain("setup");
+
+ const hour = w.timings.window();
+ expect(hour.setup.total).toEqual({ p50: 20, p95: 420, max: 420, n: 2 });
+ expect(hour.setup.checkpoint).toEqual({ p50: 300, p95: 300, max: 300, n: 1 });
+ expect(w.timings.day().setup.total).toMatchObject({ max: 420, n: 2 });
+
+ const health = perfHealth(sources(w.timings));
+ expect(Object.keys(health.h1.setup)).toEqual(["total", "checkpoint", "mcp", "prompt", "sync"]);
+ expect(health.h24.setup.checkpoint).toMatchObject({ max: 300, n: 1 });
+ const lines = perfLines(sources(w.timings), w.timings.recent(), "Latest:");
+ expect(lines.filter((line) => line.includes("Turn setup, inside queue"))).toHaveLength(2);
+ expect(lines.find((line) => line.includes("Turn setup"))).toContain("total p50 20ms p95 420ms max 420ms; checkpoint p50 300ms p95 300ms max 300ms (1)");
+ });
+
+ it("a turn that never started takes no setup into the thread's next turn", () => {
+ const w = world();
+ w.timings.noteSetup("thread_1", { total: 500, browser: 500 });
+ w.timings.noteNotStarted("thread_1", null);
+ w.emit("turn.started");
+ w.emit("turn.completed", "thread_1", "turn_1", { ok: true });
+ expect(w.timings.recent()[0]!.setup).toBeUndefined();
+ });
+
+ it("a setup noted hours before a turn starts is not that turn's", () => {
+ const w = world();
+ w.timings.noteSetup("thread_1", { total: 500 });
+ w.advance(3 * 3_600_000);
+ w.emit("turn.started");
+ w.emit("turn.completed", "thread_1", "turn_1", { ok: true });
+ expect(w.timings.recent()[0]!.setup).toBeUndefined();
+ });
+
+ it("survives a restart, loads a file written before setups were timed, and drops what is not a known step", () => {
+ const dir = mkdtempSync(join(tmpdir(), "perf-setup-"));
+ dirs.push(dir);
+ const file = join(dir, "perf-timings.json");
+ const w = world(file);
+ w.emit("turn.started");
+ w.emit("turn.completed", "thread_1", "turn_1", { ok: true });
+ w.timings.noteSetup("thread_1", { total: 80, mcp: 80 });
+ w.emit("turn.started", "thread_1", "turn_2");
+ w.emit("turn.completed", "thread_1", "turn_2", { ok: true });
+ w.timings.flush();
+ const saved = JSON.parse(readFileSync(file, "utf8"));
+ saved.ring[1].setup["cat /Users/ada/plan.md"] = 5;
+ saved.ring[1].setup.browser = "OMB_SECRET";
+ delete saved.day[0].setup;
+ writeFileSync(file, JSON.stringify(saved));
+ const again = createTurnTimings({ file, now: w.now });
+ expect(again.recent().map((turn) => turn.setup)).toEqual([undefined, { total: 80, mcp: 80 }]);
+ expect(again.day().turns).toBe(2);
+ expect(again.day().setup).toEqual({});
+ });
+
+ it("takes anything but a setup's numbers as no setup", () => {
+ const w = world();
+ w.timings.noteSetup("thread_1", { browser: "x" } as never);
+ w.emit("turn.started");
+ w.emit("turn.completed", "thread_1", "turn_1", { ok: true });
+ expect(w.timings.recent()[0]!.setup).toBeUndefined();
+ expect(SETUP_STEPS.at(-1)).toBe("total");
+ });
+});
diff --git a/server/perf/setup-steps.ts b/server/perf/setup-steps.ts
new file mode 100644
index 0000000000..5a4bfbfaf6
--- /dev/null
+++ b/server/perf/setup-steps.ts
@@ -0,0 +1,76 @@
+// Where a direct turn's setup time goes, between its message being stored and its engine being asked: one fixed name per
+// awaited step and per long synchronous stretch. Numbers only; a step's name never comes from outside this list.
+import { exactQuantile, type PhaseStats } from "./phases.ts";
+
+/**
+ * `handoff`: what the request that sent the message still had to do before the first step could run. `engineRead`: the
+ * engine's first status read. `cloudReady`: a cloud routine's computer. `summaries`: a summary of the conversation still
+ * being written that this turn needs. `videoFrames`: frames cut from attached videos. `compact`: conversation compaction.
+ * `context`: choosing what the engine is shown of the conversation. `apps`: connected apps. `mcp`: the bot's own MCP
+ * servers. `workspace`: the bot's folders and skills. `ownCloud`: a hand-off's own cloud computer. `computer`: mounting
+ * the place the bot works. `localVm`: the private desktop when no place was named. `checkpoint`: the project snapshot.
+ * `browser`: the bot's browser. `handshakeClear`: a stopped turn's engine start still unwinding. `prompt`: the system
+ * prompt. `sync`: every other synchronous stretch. `total`: all of it.
+ */
+export const SETUP_STEPS = ["handoff", "engineRead", "cloudReady", "summaries", "videoFrames", "compact", "context", "apps", "mcp", "workspace", "ownCloud",
+ "computer", "localVm", "checkpoint", "browser", "handshakeClear", "prompt", "sync", "total"] as const;
+export type SetupStep = (typeof SETUP_STEPS)[number];
+export type SetupMs = Partial<Record<SetupStep, number>>;
+export type SetupStats = Partial<Record<SetupStep, PhaseStats>>;
+
+/** Each lap takes the time since the one before it; a name lapped twice adds up. The first lap, `handoff`, is taken by
+ * itself as soon as the code that made the clock has run to its end. */
+export function createSetupClock(now: () => number = () => performance.now(), soon: (run: () => void) => void = queueMicrotask) {
+ const startedAt = now();
+ let last = startedAt, done = false;
+ const spent: SetupMs = {};
+ const lap = (step: Exclude<SetupStep, "total">) => {
+ if (done) return;
+ const at = now();
+ spent[step] = (spent[step] ?? 0) + Math.max(0, at - last);
+ last = at;
+ };
+ soon(() => lap("handoff"));
+ return {
+ lap,
+ /** Whole milliseconds; a step under one is left out. */
+ done(): SetupMs {
+ lap("sync");
+ done = true;
+ const out: SetupMs = { total: Math.round(Math.max(0, last - startedAt)) };
+ for (const step of SETUP_STEPS) {
+ const ms = Math.round(spent[step] ?? 0);
+ if (step !== "total" && ms >= 1) out[step] = ms;
+ }
+ return out;
+ },
+ };
+}
+export type SetupClock = ReturnType<typeof createSetupClock>;
+
+/** Setup timings from outside (the saved file, a caller): known steps with whole, finite, non-negative numbers only. */
+export function parseSetupMs(value: unknown): SetupMs | undefined {
+ if (!value || typeof value !== "object") return undefined;
+ const raw = value as Record<string, unknown>, out: SetupMs = {};
+ for (const step of SETUP_STEPS) {
+ const ms = Object.hasOwn(raw, step) ? raw[step] : undefined;
+ if (typeof ms === "number" && Number.isFinite(ms) && ms >= 0) out[step] = Math.min(Math.round(ms), 1e10);
+ }
+ return out.total === undefined ? undefined : out;
+}
+
+export function setupStatsOf(turns: ReadonlyArray<{ setup?: SetupMs }>): SetupStats {
+ const stats: SetupStats = {};
+ for (const step of SETUP_STEPS) {
+ const values = turns.flatMap((turn) => (turn.setup?.[step] === undefined ? [] : [turn.setup[step]])).sort((left, right) => left - right);
+ if (values.length) stats[step] = { p50: exactQuantile(values, 0.5), p95: exactQuantile(values, 0.95), max: values.at(-1)!, n: values.length };
+ }
+ return stats;
+}
+
+/** The whole setup, then its steps with the highest 95th percentile first, at most `kept` of them. */
+export function slowestSetupSteps(stats: SetupStats, kept: number): Array<[SetupStep, PhaseStats]> {
+ const steps = SETUP_STEPS.flatMap((step) => (step !== "total" && stats[step] ? [[step, stats[step]] as [SetupStep, PhaseStats]] : []))
+ .sort((left, right) => right[1].p95 - left[1].p95 || right[1].max - left[1].max).slice(0, kept);
+ return [...(stats.total ? [["total", stats.total] as [SetupStep, PhaseStats]] : []), ...steps];
+}
diff --git a/server/perf/turn-record.ts b/server/perf/turn-record.ts
index 0fa4bc22c0..5a1421ccca 100644
--- a/server/perf/turn-record.ts
+++ b/server/perf/turn-record.ts
@@ -3,6 +3,7 @@
// or Codex tool title can be the command itself), a stop reason's words, a prompt or a path.
import { traceToolLook, type TraceToolIcon } from "../../shared/usage-trace.ts";
import { PHASES, type PhaseMs } from "./phases.ts";
+import { parseSetupMs, type SetupMs } from "./setup-steps.ts";
export type ToolKind = TraceToolIcon;
const TOOL_KINDS: ReadonlySet<string> = new Set<ToolKind>(["search", "web", "browser", "computer", "phone", "files", "terminal", "memory",
@@ -42,6 +43,8 @@ export interface TurnTiming {
ok: boolean;
stop: string;
ms: PhaseMs;
+ /** A direct turn's setup, by step: part of its `queue`. */
+ setup?: SetupMs;
queueWhy?: QueueWhy;
retries: number;
/** What the engine said its retry delays would be, summed. */
@@ -83,10 +86,11 @@ export function parseTurnTiming(value: unknown): TurnTiming | null {
? [{ kind: tool.kind as ToolKind, n: count(tool.n), ms: count(tool.ms), max: count(tool.max), errors: count(tool.errors), open: count(tool.open) }]
: []).slice(0, TOOL_KINDS_KEPT);
const retryWhy = Array.isArray(raw.retryWhy) ? raw.retryWhy.map(retryCode).slice(0, RETRY_WHY_KEPT) : [];
+ const setup = parseSetupMs(raw.setup);
return {
turnId: matchOr(ID, raw.turnId, null), threadId: matchOr(ID, raw.threadId, null), botId: matchOr(ID, raw.botId, null),
engine: matchOr(KIND, raw.engine, null), startedAt: count(raw.startedAt, 1e14), endedAt: count(raw.endedAt, 1e14), ok: raw.ok === true,
- stop: stopCode(raw.ok === true, raw.stop), ms,
+ stop: stopCode(raw.ok === true, raw.stop), ms, ...(setup ? { setup } : {}),
...(QUEUE_WHY.has(raw.queueWhy as string) ? { queueWhy: raw.queueWhy as QueueWhy } : {}),
retries: count(raw.retries, 1e6), backoffMs: count(raw.backoffMs), ...(retryWhy.length ? { retryWhy } : {}),
...(LIMIT_SCOPES.has(raw.limit as string) ? { limit: raw.limit as LimitScope } : {}),
diff --git a/server/perf/turn-timings.ts b/server/perf/turn-timings.ts
index e1d4302dfe..da3cc6360d 100644
--- a/server/perf/turn-timings.ts
+++ b/server/perf/turn-timings.ts
@@ -8,6 +8,7 @@ import type { RuntimeEvent } from "../contracts.ts";
import type { Message } from "../store.ts";
import { createDayLedger, DAY_HOURS, SLOW_TURN_MS } from "./day-ledger.ts";
import { exactQuantile, PHASES, type Phase, type PhaseMs, type PhaseStats } from "./phases.ts";
+import { parseSetupMs, setupStatsOf, type SetupMs, type SetupStats } from "./setup-steps.ts";
import {
activeMs, ID, isLimitScope, KIND, matchOr, parseTurnTiming, retryCode, RETRY_WHY_KEPT, stopCode, TOOL_KINDS_KEPT, toolKindOf,
type FailoverWhy, type LimitScope, type QueueWhy, type ToolKind, type ToolStat, type TurnTiming,
@@ -39,6 +40,7 @@ interface Live {
startedAt: number;
queueMs?: number;
queueWhy?: QueueWhy;
+ setup?: SetupMs;
sessionAt: number | null;
firstOutputAt: number | null;
state: LiveState;
@@ -59,7 +61,7 @@ interface Live {
export interface LiveTurnView { botId: string | null; threadId: string | null; engine: string | null; ageMs: number; state: LiveState; stateMs: number; tool?: ToolKind; queueMs?: number }
-export interface WindowStats { turns: number; failed: number; phases: Partial<Record<Phase, PhaseStats>>; slow: number[]; partial: boolean }
+export interface WindowStats { turns: number; failed: number; phases: Partial<Record<Phase, PhaseStats>>; setup: SetupStats; slow: number[]; partial: boolean }
/** What refused a turn before it ran: a usage limit (and on which engine), or a sign-in that expired. */
export interface Refusal { limit?: LimitScope; engine?: string | null; resetsAt?: number; signedOut?: boolean }
@@ -97,6 +99,7 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
const pending = new Map<string, { at: number; behind: boolean }>();
const held = new Map<string, QueueWhy>();
const failovers = new Map<string, { why: FailoverWhy; at: number }>();
+ const setups = new Map<string, { ms: SetupMs; at: number }>();
let savedAt = -Infinity, saveTimer: ReturnType<typeof setTimeout> | null = null;
const remember = <V>(map: Map<string, V>, key: string, value: V, cap: number) => {
@@ -155,10 +158,14 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
failovers.delete(threadId);
const failover = moved && at - moved.at <= FAILOVER_TTL_MS ? moved.why : undefined;
const queueMs = waiting && at - waiting.at <= PENDING_TTL_MS ? Math.max(0, at - waiting.at) : undefined;
+ const prepared = setups.get(threadId);
+ setups.delete(threadId);
+ const setup = prepared && at - prepared.at <= PENDING_TTL_MS ? prepared.ms : undefined;
const turn: Live = {
key: threadId, turnId: matchOr(ID, event.turnId, null), threadId: matchOr(ID, threadId, null),
botId: matchOr(ID, options.botOf?.(threadId), null), engine: matchOr(KIND, event.provider, null), startedAt: at,
...(queueMs !== undefined ? { queueMs, queueWhy: why ?? (waiting!.behind ? "behind-turn" : "dispatch") } : {}),
+ ...(setup ? { setup } : {}),
sessionAt: null, firstOutputAt: null, state: "model", stateSince: at, spent: { model: 0, tool: 0, resource: 0, person: 0, retry: 0 },
openTools: new Map(), requests: 0, waits: 0, retrying: false, retries: 0, backoffMs: 0, retryWhy: [], tools: new Map(),
...(failover ? { failover } : {}),
@@ -187,7 +194,7 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
for (const [state, spent] of Object.entries(turn.spent) as Array<[LiveState, number]>) if (spent > 0 || state === "model") ms[STATE_PHASE[state]] = spent;
const record: TurnTiming = {
turnId: turn.turnId, threadId: turn.threadId, botId: turn.botId, engine: turn.engine, startedAt: turn.startedAt, endedAt: at,
- ok, stop: stopCode(ok, stopReason), ms, ...(turn.queueWhy ? { queueWhy: turn.queueWhy } : {}),
+ ok, stop: stopCode(ok, stopReason), ms, ...(turn.setup ? { setup: turn.setup } : {}), ...(turn.queueWhy ? { queueWhy: turn.queueWhy } : {}),
retries: turn.retries, backoffMs: turn.backoffMs, ...(turn.retryWhy.length ? { retryWhy: turn.retryWhy } : {}),
...(turn.limit ? { limit: turn.limit } : {}), ...(turn.limitResetsAt ? { limitResetsAt: turn.limitResetsAt } : {}),
...(turn.failover ? { failover: turn.failover } : {}),
@@ -265,6 +272,7 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
noteNotStarted(threadId: string, turnId: string | null, refusal: Refusal = {}) {
const at = now();
clearWaiting(threadId);
+ setups.delete(threadId);
const turn = live.get(threadId);
const engine = refusal.engine === undefined ? turn?.engine ?? null : matchOr(KIND, refusal.engine, null);
const limit = isLimitScope(refusal.limit) ? refusal.limit : undefined;
@@ -277,6 +285,11 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
}
if (limit) { day.noteRefusal(engine, limit, at); saveSoon(); }
},
+ /** This thread's turn is set up and its engine is about to be asked: its next turn to start carries these timings. */
+ noteSetup(threadId: string, ms: unknown) {
+ const setup = parseSetupMs(ms);
+ if (setup) remember(setups, threadId, { ms: setup, at: now() }, PENDING_CAP);
+ },
/** This thread's next turn waits for a place: under the plan's limit on turns at once, or for memory. */
noteHeld(threadId: string, why: "plan-limit" | "memory") { remember(held, threadId, why, PENDING_CAP); },
/** This thread moved to another AI: a usage limit, or its AI signed out. */
@@ -289,7 +302,7 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
const threads = new Set(filter.threadIds ?? []), bots = new Set(filter.botIds ?? []);
const all = !threads.size && !bots.size;
const picked = ring.filter((turn) => all || (turn.threadId !== null && threads.has(turn.threadId)) || (turn.botId !== null && bots.has(turn.botId)));
- return picked.slice(-(filter.limit ?? RING_CAP)).map((turn) => ({ ...turn, ms: { ...turn.ms }, tools: turn.tools.map((tool) => ({ ...tool })) }));
+ return picked.slice(-(filter.limit ?? RING_CAP)).map((turn) => ({ ...turn, ms: { ...turn.ms }, ...(turn.setup ? { setup: { ...turn.setup } } : {}), tools: turn.tools.map((tool) => ({ ...tool })) }));
},
/** Exact percentiles over the turns that ended in the last `windowMs`, from the ring; `partial` when the ring is full
* and its oldest turn ended inside the window, so turns before it are missing. */
@@ -302,7 +315,7 @@ export function createTurnTimings(options: TurnTimingsOptions = {}) {
if (values.length) phases[phase] = { p50: exactQuantile(values, 0.5), p95: exactQuantile(values, 0.95), max: values.at(-1)!, n: values.length };
}
const slow = SLOW_TURN_MS.map((edge) => turns.filter((turn) => activeMs(turn) > edge).length);
- return { turns: turns.length, failed: turns.filter((turn) => !turn.ok).length, phases, slow, partial: ring.length >= RING_CAP && ring[0]!.endedAt > from };
+ return { turns: turns.length, failed: turns.filter((turn) => !turn.ok).length, phases, setup: setupStatsOf(turns), slow, partial: ring.length >= RING_CAP && ring[0]!.endedAt > from };
},
day: (windowMs = DAY_HOURS * HOUR) => day.read(windowMs),
live(): LiveTurnView[] {
diff --git a/server/routes/bots-create.test.ts b/server/routes/bots-create.test.ts
index ecbf052b78..89c28644a4 100644
--- a/server/routes/bots-create.test.ts
+++ b/server/routes/bots-create.test.ts
@@ -2,11 +2,13 @@
// desktop app), while a request, the New bot defaults, Approve for me, or a server without it keep their own.
import { rmSync } from "node:fs";
import type { IncomingMessage, ServerResponse } from "node:http";
-import { beforeEach, describe, expect, it } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import type { WireBot } from "../../shared/wire.ts";
+import { OwnedFile } from "../atomic.ts";
import { DATA_DIR, type AppConfig } from "../config.ts";
import type { ModelSelection } from "../contracts.ts";
+import { BOTS_FILE } from "../registry-store.ts";
import type { RequestAuth } from "../request-auth.ts";
import { Store, type BotRecord } from "../store.ts";
import { createBotCreateRoutes, type BotCreateRouteDeps } from "./bots-create.ts";
@@ -60,7 +62,7 @@ function fixture(options: { newBotComputer?: BotCreateRouteDeps["newBotComputer"
expect(sent[0]!.status, JSON.stringify(sent[0]!.body)).toBe(201);
return store.bot(sent[0]!.body.bot.id)!;
};
- return { create, asked };
+ return { create, asked, store };
}
describe("where a new bot works", () => {
@@ -87,3 +89,39 @@ describe("where a new bot works", () => {
expect((await fixture().create({ name: "Cy" })).computer).toBeUndefined();
});
});
+
+describe("saving a new bot", () => {
+ const botsFileWrites = async (run: () => unknown) => {
+ const write = vi.spyOn(OwnedFile.prototype, "write");
+ try {
+ await run();
+ return write.mock.results.filter((result, call) => result.value === true && (write.mock.contexts[call] as OwnedFile).path === BOTS_FILE).length;
+ } finally {
+ write.mockRestore();
+ }
+ };
+
+ it("writes bots.json once for the POST and not again for a PATCH that changes nothing", async () => {
+ const fx = fixture({ newBotComputer: () => "local" });
+ await fx.create({ name: "Warm" });
+ let bot = await fx.create({ name: "Other" });
+ expect(await botsFileWrites(async () => { bot = await fx.create({ name: "Ada", modelSelection: sonnet, requireAvailableModel: true, useDefaults: false }); })).toBe(1);
+ expect(await botsFileWrites(() => fx.store.patchBot(bot.id, { name: bot.name, notifications: bot.notifications }))).toBe(0);
+ expect(new Store(() => sonnet).bot(bot.id)!.tasks).toEqual(fx.store.bot(bot.id)!.tasks!.map(({ busy: _busy, activity: _activity, ...task }) => expect.objectContaining(task)));
+ });
+
+
+ it("writes bots.json once, with the request's settings already in it", async () => {
+ const fx = fixture({ newBotComputer: () => "local" });
+ await fx.create({ name: "Warm" });
+ const write = vi.spyOn(OwnedFile.prototype, "write");
+ try {
+ const bot = await fx.create({ name: "Ada", useDefaults: false, settings: { soul: "Be brief.", approvalMode: "auto", browser: false } });
+ const written = write.mock.results.flatMap((result, call) => result.value === true && (write.mock.contexts[call] as OwnedFile).path === BOTS_FILE ? [write.mock.calls[call]![0]] : []);
+ expect(written).toHaveLength(1);
+ expect(JSON.parse(written[0]!)[0]).toMatchObject({ id: bot.id, name: "Ada", soul: "Be brief.", autoApprove: true, browser: false });
+ } finally {
+ write.mockRestore();
+ }
+ });
+});
diff --git a/server/routes/bots-create.ts b/server/routes/bots-create.ts
index 7429c8b61e..39c817a2cc 100644
--- a/server/routes/bots-create.ts
+++ b/server/routes/bots-create.ts
@@ -212,13 +212,11 @@ export function createBotCreateRoutes(deps: BotCreateRouteDeps): RouteHandler {
const bot = store.createBot({ ...profile.patch, soul: settings.soul, section, modelSelection: selection,
toolScope: settings.toolScope ?? undefined, color: settings.color ?? look?.color, mascotBody: settings.mascotBody ?? look?.mascotBody,
...(deps.team && creator ? { createdBy: creator } : {}), ...(reportsTo ? { reportsTo } : {}),
- ...(created?.ok ? { visibility: created.visibility } : {}) }, kept.id ? { ...kept, seedMessages: false } : {});
- const createdRoutines: Array<{ id: string; enabled: boolean }> = [];
- try {
+ ...(created?.ok ? { visibility: created.visibility } : {}) }, { ...(kept.id ? { ...kept, seedMessages: false } : {}), settle: (made) => {
const { chiefOfStaff: _chief, managedSections: _managed, toolScope: _toolScope, ...ordinary } = settings;
- store.patchBot(bot.id, {
+ store.patchBot(made.id, {
// Store creation completed the workspace defaults (effort included): the rest of the template must not undo them.
- ...ordinary, name: bot.name, section, modelSelection: bot.modelSelection,
+ ...ordinary, name: made.name, section, modelSelection: made.modelSelection,
mascotExpression: ordinary.mascotExpression ?? undefined,
avatarUrl: ordinary.avatarUrl || undefined,
// Auto with Approve for me stays Auto: This computer with it needs the warning only the bot's Settings shows.
@@ -228,6 +226,9 @@ export function createBotCreateRoutes(deps: BotCreateRouteDeps): RouteHandler {
voiceNoteEveryReply: ordinary.voiceNoteEveryReply ?? undefined,
autoApprove: ordinary.approvalMode === "auto",
});
+ } });
+ const createdRoutines: Array<{ id: string; enabled: boolean }> = [];
+ try {
const presetSkills = new Set(preset?.preset.skills ?? []);
const presetNotes = new Set(Object.keys(preset?.preset.seed?.memory ?? {}));
for (const [file, text] of Object.entries(template.memory)) {
diff --git a/server/routes/tasks.ts b/server/routes/tasks.ts
index 56ed5d6e8b..c8a686e82a 100644
--- a/server/routes/tasks.ts
+++ b/server/routes/tasks.ts
@@ -18,7 +18,7 @@ import type { MessagePage } from "./channels.ts";
import { bulkDeleteThreadIds, type BulkDeleteRefusal } from "./bulk-delete.ts";
import { forkMessageId } from "./fork-request.ts";
import { PASS, type RouteHandler } from "./table.ts";
-import { sawThread } from "../thread-presence.ts";
+import { madeThread, sawThread } from "../thread-presence.ts";
import { refusalBody, userError } from "../user-errors.ts";
import type { ServerErrorBody } from "../../shared/server-text.ts";
import { readThreadNotifications, type NotificationListed } from "./notifications.ts";
@@ -216,6 +216,7 @@ export function createTaskRoutes(deps: TaskRouteDeps): RouteHandler & { deleteTa
const task = store.createTask(bot.id, typeof body.title === "string" ? body.title : undefined, body.select !== false, body.projectId, undefined, body.approvalMode, undefined, cwd,
auth.kind === "session" ? (created) => threadStarters.set(created.threadId, actorKey(auth)) : undefined);
if (!task) return json(res, 500, { error: "couldn't create that task" });
+ madeThread(bot.id, task.threadId);
return json(res, 201, { bot: publicBot(store.bot(bot.id)!), task: wireTask(task, store.bot(bot.id)!.modelSelection) } satisfies TaskResponse);
}
m = path.match(/^\/api\/bots\/([\w-]+)\/tasks\/delete$/);
diff --git a/server/routes/threads-page-leaf.test.ts b/server/routes/threads-page-leaf.test.ts
new file mode 100644
index 0000000000..4643084130
--- /dev/null
+++ b/server/routes/threads-page-leaf.test.ts
@@ -0,0 +1,168 @@
+import { rmSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { DATA_DIR } from "../config.ts";
+import type { ModelSelection } from "../contracts.ts";
+import { json, readBody } from "../harness/http.ts";
+import { messagePages, pageSize } from "../host/message-pages.ts";
+import * as mdb from "../message-db.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { Store, type Message } from "../store.ts";
+import { dispatchRoutes } from "./table.ts";
+import { createThreadRoutes, type ThreadRouteDeps } from "./threads.ts";
+
+const sonnet: ModelSelection = { instanceId: "claude", model: "claude-sonnet-5" };
+const servers: Server[] = [];
+
+beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+afterEach(async () => {
+ await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
+});
+
+async function serve(store: Store) {
+ const deps = { store, defaultPage: 50, pageSize, ...messagePages(store), viewerFor: () => ({}), visibleTo: () => ({ bot: () => true, group: () => true }), workspaceAccess: () => null,
+ desktopMutationToken: () => undefined, companionMutationToken: () => undefined, cliOwnerToken: () => undefined } as unknown as ThreadRouteDeps;
+ const routes = [createThreadRoutes(deps)];
+ const server = createServer(async (req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const auth = { kind: "loopback", scopes: ["admin"] } as RequestAuth;
+ const handled = await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody });
+ if (!handled) json(res, 404, { from: "inline routes" });
+ });
+ servers.push(server);
+ await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
+ const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ return async (path: string) => {
+ const res = await fetch(`${base}${path}`);
+ return { status: res.status, body: await res.json() as { messages: Message[]; hasMore: boolean; activeLeafId: string | null } };
+ };
+}
+
+const say = (store: Store, threadId: string, text: string) => store.appendMessage(threadId, { role: "user", kind: "text", text });
+const row = (id: string, extra: Partial<Message> = {}): Message => ({ id, at: 1_700_000_000_000 + Number(id.slice(1)), role: "user", kind: "text", text: id, ...extra } as Message);
+
+/** Each builds one conversation and names it; `warm` keeps the building Store, whose cache then holds the conversation. */
+const conversations: Record<string, (store: Store) => string> = {
+ "a straight conversation": (store) => {
+ const bot = store.createBot({}, { seedMessages: false });
+ for (let i = 0; i < 12; i++) say(store, bot.threadId, `message ${i}`);
+ return bot.threadId;
+ },
+ "an edited message whose older branch is the one shown": (store) => {
+ const bot = store.createBot({}, { seedMessages: false });
+ const first = say(store, bot.threadId, "first");
+ const kept = say(store, bot.threadId, "kept branch");
+ for (let i = 0; i < 6; i++) say(store, bot.threadId, `kept ${i}`);
+ store.branchMessage(bot.threadId, kept.id, "edited branch");
+ for (let i = 0; i < 6; i++) say(store, bot.threadId, `edited ${i}`);
+ store.setActiveLeaf(bot.threadId, kept.id);
+ expect(store.activeLeaf(bot.threadId)).not.toBe(store.messagesFor(bot.threadId).at(-1)!.id);
+ expect(first.parentId).toBeNull();
+ return bot.threadId;
+ },
+ "a message inserted behind the newest one": (store) => {
+ const bot = store.createBot({}, { seedMessages: false });
+ const anchor = say(store, bot.threadId, "anchor");
+ for (let i = 0; i < 6; i++) say(store, bot.threadId, `after ${i}`);
+ store.insertMessageAfter(bot.threadId, anchor.id, { role: "bot", kind: "text", text: "inserted" });
+ return bot.threadId;
+ },
+ "rows stored without parents and no stored leaf": (store) => {
+ const bot = store.createBot({}, { seedMessages: false });
+ mdb.importThread(bot.threadId, Array.from({ length: 12 }, (_, i) => row(`m${i}`)), null);
+ return bot.threadId;
+ },
+ "old rows without parents under newer rows that have them": (store) => {
+ const bot = store.createBot({}, { seedMessages: false });
+ mdb.importThread(bot.threadId, [
+ ...Array.from({ length: 6 }, (_, i) => row(`m${i}`)),
+ ...Array.from({ length: 6 }, (_, i) => row(`m${i + 6}`, { parentId: `m${i + 5}` })),
+ ], "m9");
+ return bot.threadId;
+ },
+ "a stored leaf that is an empty string": (store) => {
+ const bot = store.createBot({}, { seedMessages: false });
+ mdb.importThread(bot.threadId, Array.from({ length: 12 }, (_, i) => row(`m${i}`, { parentId: i ? `m${i - 1}` : null })), "");
+ return bot.threadId;
+ },
+ "a conversation with nothing in it": (store) => store.createBot({}, { seedMessages: false }).threadId,
+};
+
+describe("GET /api/threads/:threadId/messages", () => {
+ for (const [name, build] of Object.entries(conversations)) {
+ for (const warm of [false, true]) {
+ it(`names the same leaf as the whole conversation does: ${name}${warm ? ", already in memory" : ""}`, async () => {
+ const builder = new Store(() => sonnet);
+ const threadId = build(builder);
+ if (warm) builder.messagesFor(threadId);
+ const whole = new Store(() => sonnet);
+ const all = whole.messagesFor(threadId);
+ const leaf = whole.activeLeaf(threadId);
+ for (const limit of [0, 1, 3, 50]) {
+ const get = await serve(warm ? builder : new Store(() => sonnet));
+ const page = await get(`/api/threads/${threadId}/messages?limit=${limit}`);
+ expect(page.status).toBe(200);
+ expect(page.body.activeLeafId, `limit ${limit}`).toBe(leaf);
+ expect(page.body.messages.map((message) => message.id), `limit ${limit}`).toEqual(all.slice(Math.max(0, all.length - limit)).map((message) => message.id));
+ expect(page.body.hasMore, `limit ${limit}`).toBe(all.length > limit);
+ }
+ });
+ }
+ }
+
+ for (const [name, build] of Object.entries(conversations)) {
+ for (const warm of [false, true]) {
+ it(`gives the page around a message as the whole conversation would: ${name}${warm ? ", already in memory" : ""}`, async () => {
+ const builder = new Store(() => sonnet);
+ const threadId = build(builder);
+ if (warm) builder.messagesFor(threadId);
+ const whole = new Store(() => sonnet);
+ const all = whole.messagesFor(threadId);
+ const leaf = whole.activeLeaf(threadId);
+ const get = await serve(warm ? builder : new Store(() => sonnet));
+ expect((await get(`/api/threads/${threadId}/messages?around=no-such-message&limit=3`)).status).toBe(404);
+ for (const limit of [0, 1, 2, 3, 4, 5, 11, 12, 13, 50]) {
+ for (const [index, target] of all.entries()) {
+ const before = Math.floor((limit - 1) / 2);
+ const start = Math.max(0, Math.min(index - before, all.length - limit));
+ const page = await get(`/api/threads/${threadId}/messages?around=${target.id}&limit=${limit}`);
+ expect(page.status).toBe(200);
+ expect(page.body, `limit ${limit}, message ${index}`).toEqual({ messages: all.slice(start, Math.min(all.length, start + limit)), hasMore: start > 0, activeLeafId: leaf });
+ }
+ }
+ });
+ }
+ }
+
+ it("answers the page around a message without reading the rest of the conversation", async () => {
+ const builder = new Store(() => sonnet);
+ const threadId = conversations["an edited message whose older branch is the one shown"]!(builder);
+ const target = builder.messagesFor(threadId)[7]!;
+ const read = vi.spyOn(mdb, "readThread");
+ try {
+ const get = await serve(new Store(() => sonnet));
+ const page = await get(`/api/threads/${threadId}/messages?around=${target.id}&limit=3`);
+ expect(page.body.messages.map((message) => message.id)).toEqual(builder.messagesFor(threadId).slice(6, 9).map((message) => message.id));
+ expect(read).not.toHaveBeenCalled();
+ } finally {
+ read.mockRestore();
+ }
+ });
+
+ it("answers the newest page of a long conversation without reading the rest of it", async () => {
+ const builder = new Store(() => sonnet);
+ const threadId = conversations["an edited message whose older branch is the one shown"]!(builder);
+ const read = vi.spyOn(mdb, "readThread");
+ try {
+ const get = await serve(new Store(() => sonnet));
+ const page = await get(`/api/threads/${threadId}/messages?limit=3`);
+ expect(page.body.messages).toHaveLength(3);
+ expect(page.body.activeLeafId).toBe(builder.activeLeaf(threadId));
+ expect(read).not.toHaveBeenCalled();
+ } finally {
+ read.mockRestore();
+ }
+ });
+});
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 00da8225a3..977ec8dd35 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -54,7 +54,7 @@ export interface ThreadRouteDeps {
pageSize(raw: string | null): number | null | undefined;
messagePage(threadId: string, limit: number | undefined): MessagePage;
messagePageBefore(threadId: string, before: string, limit: number): MessagePage | null;
- messageWindow(threadId: string, messageId: string, limit: number): { messages: Array<Message | Record<string, unknown>>; hasMore: boolean } | null;
+ messageWindow(threadId: string, messageId: string, limit: number): { messages: Array<Message | Record<string, unknown>>; hasMore: boolean; activeLeafId: string | null } | null;
publicBotQueuedMessages(): ReturnType<typeof queuedSteerSnapshot>;
publicGroupState(record: GroupRecord): WireGroup;
wireBot(bot: BotRecord): WireBot;
@@ -151,14 +151,14 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
if (around) {
const window = messageWindow(threadId, around, limit ?? DEFAULT_PAGE);
if (!window) return json(res, 404, { error: "no such message" });
- return json(res, 200, { ...window, activeLeafId: store.activeLeaf(threadId) });
+ return json(res, 200, window);
}
// An unknown cursor must not answer with the newest page: the client would paginate in a circle.
if (before) {
const page = messagePageBefore(threadId, before, limit ?? DEFAULT_PAGE);
return page ? json(res, 200, page) : json(res, 404, { error: "no such message" });
}
- return json(res, 200, { ...messagePage(threadId, limit ?? DEFAULT_PAGE), activeLeafId: store.activeLeaf(threadId) });
+ return json(res, 200, messagePage(threadId, limit ?? DEFAULT_PAGE));
}
m = path.match(/^\/api\/threads\/([\w-]+)\/messages\/([\w-]+)\/image$/);
diff --git a/server/store-create-settle.test.ts b/server/store-create-settle.test.ts
new file mode 100644
index 0000000000..db446e2db5
--- /dev/null
+++ b/server/store-create-settle.test.ts
@@ -0,0 +1,98 @@
+import { existsSync, readFileSync, rmSync } from "node:fs";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { OwnedFile } from "./atomic.ts";
+import { soulFile } from "./bot-folder.ts";
+import { DATA_DIR } from "./config.ts";
+import type { ModelSelection } from "./contracts.ts";
+import { BOTS_FILE } from "./registry-store.ts";
+import { Store, type StoreChange } from "./store.ts";
+
+const selection = (): ModelSelection => ({ instanceId: "claude", model: "claude-sonnet-5" });
+const savedBots = () => (JSON.parse(readFileSync(BOTS_FILE, "utf8")) as Array<{ id: string; name: string; cwd?: string }>);
+
+/** How many times bots.json was really written while `run` ran: a save of unchanged text writes nothing. */
+function botsFileWrites(run: () => void): number {
+ const write = vi.spyOn(OwnedFile.prototype, "write");
+ try {
+ run();
+ return write.mock.results.filter((result, call) => result.value === true && (write.mock.contexts[call] as OwnedFile).path === BOTS_FILE).length;
+ } finally {
+ write.mockRestore();
+ }
+}
+
+describe("Store.createBot with settle", () => {
+ beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));
+
+ it("saves the bot once, finished, before anyone hears of it", () => {
+ const store = new Store(selection);
+ store.createBot({ name: "Already here" });
+ const heard: Array<{ change: StoreChange; saved: boolean }> = [];
+ let made = "";
+ store.onChange((change) => { if (change.type === "bot") heard.push({ change, saved: savedBots().some((bot) => bot.id === made && bot.cwd === "/work") }); });
+
+ const writes = botsFileWrites(() => {
+ const bot = store.createBot({ name: "Scout", soul: "Be brief." }, { seedMessages: false, settle: (fresh) => { made = fresh.id; store.patchBot(fresh.id, { cwd: "/work" }); } });
+ expect(bot.cwd).toBe("/work");
+ });
+
+ expect(writes).toBe(1);
+ expect(heard.length).toBeGreaterThan(0);
+ expect(heard.every((entry) => entry.saved)).toBe(true);
+ expect(savedBots().map((bot) => bot.name)).toEqual(["Scout", "Already here"]);
+ expect(readFileSync(soulFile(made), "utf8")).toBe("Be brief.");
+ });
+
+ it("leaves nothing of a greeted bot for a later save: its one write holds what memory holds", () => {
+ const store = new Store(selection);
+ for (const settle of [undefined, (fresh: { id: string }) => { store.patchBot(fresh.id, { cwd: "/work" }); }]) {
+ let bot = store.bots[0]!;
+ expect(botsFileWrites(() => { bot = store.createBot({ name: "Greeted" }, { settle }); })).toBe(1);
+ const greeting = store.messagesFor(bot.threadId);
+ expect(greeting).toHaveLength(1);
+ expect(greeting[0]!.at).toBe(bot.createdAt);
+ const { busy: _busy, activity: _activity, ...task } = bot.tasks![0]!;
+ expect((savedBots().find((saved) => saved.id === bot.id) as unknown as typeof bot).tasks![0]).toEqual(task);
+ expect(botsFileWrites(() => { store.patchBot(bot.id, { name: bot.name }); })).toBe(0);
+ }
+ });
+
+ it("writes bots.json once without settle too", () => {
+ const store = new Store(selection);
+ expect(botsFileWrites(() => { store.createBot({ name: "Scout" }, { seedMessages: false }); })).toBe(1);
+ });
+
+ it("leaves no bot in memory or on disk when settle throws, before or after its own save", () => {
+ const store = new Store(selection);
+ const kept = store.createBot({ name: "Already here" });
+ const heard: StoreChange[] = [];
+ store.onChange((change) => heard.push(change));
+
+ expect(() => store.createBot({ name: "Early" }, { settle: () => { throw new Error("refused early"); } })).toThrow("refused early");
+ expect(heard.map((change) => change.type)).toEqual(["bot.deleted"]);
+ let late = "";
+ expect(() => store.createBot({ name: "Late" }, { settle: (fresh) => { late = fresh.id; store.patchBot(fresh.id, { cwd: "/work" }); throw new Error("refused late"); } })).toThrow("refused late");
+
+ expect(heard.filter((change) => "botId" in change && change.botId === late).map((change) => change.type)).toEqual(["bot", "bot.deleted"]);
+ expect(store.bots.map((bot) => bot.id)).toEqual([kept.id]);
+ expect(savedBots().map((bot) => bot.id)).toEqual([kept.id]);
+ expect(new Store(selection).bots.map((bot) => bot.id)).toEqual([kept.id]);
+ expect(existsSync(soulFile(late))).toBe(false);
+ expect(store.messagesFor(kept.threadId).length).toBeGreaterThan(0);
+ });
+
+ it("leaves no bot in memory when the save fails", () => {
+ const store = new Store(selection);
+ const kept = store.createBot({ name: "Already here" });
+ const write = vi.spyOn(OwnedFile.prototype, "write").mockImplementation(() => { throw new Error("disk full"); });
+ try {
+ expect(() => store.createBot({ name: "Plain" })).toThrow("disk full");
+ expect(() => store.createBot({ name: "Settled" }, { settle: (fresh) => { store.patchBot(fresh.id, { cwd: "/work" }); } })).toThrow("disk full");
+ } finally {
+ write.mockRestore();
+ }
+ expect(store.bots.map((bot) => bot.id)).toEqual([kept.id]);
+ expect(savedBots().map((bot) => bot.id)).toEqual([kept.id]);
+ });
+});
diff --git a/server/store.ts b/server/store.ts
index eb5bcc17fe..e3120d9215 100644
--- a/server/store.ts
+++ b/server/store.ts
@@ -40,7 +40,7 @@ import { sameModelSelection } from "../shared/thread-model.ts";
import { initialGreetingMessage } from "./initial-greeting.ts"; import { createDefaultBot, defaultBotRefusal, type DefaultBotIntro } from "./default-bot.ts";
import { appsFromCreator } from "./inherited-apps.ts"; import { newBotOwner, sharedAsMaker, sharedUnlessRestricted, type NewBotSharingRule } from "./new-bot-sharing.ts";
import { ThreadCache, type ThreadState } from "./thread-cache.ts";
-import { messagesBefore } from "./thread-history.ts";
+import { lastMessageId, messagesBefore } from "./thread-history.ts";
import { titleFromMessage, UNTITLED_TASK } from "./thread-title.ts";
import { buildTask, threadTitleFrom, UNTITLED_THREAD } from "./task-record.ts";
import { createBotFork, createGroupFork } from "./store-forks.ts";
@@ -320,7 +320,7 @@ export class Store {
botsMigrated = true;
}
if (!existsSync(soulFile(b.id))) {
- try { writeSoulMirror(b.id, b.soul); } catch (e) {
+ try { writeSoulMirror(b.id, b.soul, false); } catch (e) {
console.warn(`[bot-folder] could not create SOUL.md for ${b.id}: ${(e as Error).message}`);
}
}
@@ -1087,7 +1087,7 @@ export class Store {
const tail = mdb.readThreadTail(threadId, messagesFile(threadId), limit);
const legacyRows = tail.hasMore !== undefined && tail.messages.some((m) => m.parentId === undefined);
if (tail.hasMore === true && !legacyRows) {
- return { messages: tail.messages, hasMore: true, activeLeafId: tail.activeLeafId ?? tail.messages.at(-1)?.id ?? null };
+ return { messages: tail.messages, hasMore: true, activeLeafId: tail.activeLeafId || (tail.messages.at(-1)?.id ?? lastMessageId(threadId)) };
}
state = this.threads.load(threadId, legacyRows ? mdb.readThread(threadId, messagesFile(threadId)) : tail);
}
@@ -1276,7 +1276,8 @@ export class Store {
>
> = {},
opts: {
- seedMessages?: boolean; id?: string; threadId?: string; beforeShown?: (bot: BotRecord) => void;
+ /** `settle` finishes the new bot's record (patchBot and the like) before its one save; a throw leaves no bot behind. */
+ seedMessages?: boolean; id?: string; threadId?: string; beforeShown?: (bot: BotRecord) => void; settle?: (bot: BotRecord) => void;
} = {},
): BotRecord {
const toolScope = parseToolScope(profile.toolScope);
@@ -1311,24 +1312,23 @@ export class Store {
threadId: bot.threadId,
title: UNTITLED_THREAD,
createdAt: bot.createdAt,
- updatedAt: bot.createdAt,
+ updatedAt: bot.createdAt, ...(opts.seedMessages !== false ? { lastThreadOrderAt: bot.createdAt } : {}),
resumeCursors: {},
unread: false,
activity: "idle",
busy: false,
}];
// Persist before publishing or greeting, so an interrupted creation cannot inherit tools.
- this.saveBots([bot, ...this.bots]);
- this.bots.unshift(bot);
- try {
- writeSoulMirror(bot.id, bot.soul ?? "");
- } catch (e) {
- console.warn(`[bot-folder] could not write SOUL.md mirror for ${bot.id}: ${(e as Error).message}`);
+ try { this.bots.unshift(bot); opts.settle?.(bot); this.saveBots(); } catch (error) {
+ const at = this.bots.findIndex((made) => made.id === bot.id); if (at >= 0) this.bots.splice(at, 1);
+ if (opts.settle) try { this.saveBots(); } catch { console.warn(`store: bot ${bot.id} was not finished and may reappear on restart`); } finally { this.emit({ type: "bot.deleted", botId: bot.id }); }
+ throw error;
}
+ try { writeSoulMirror(bot.id, bot.soul ?? "", false); } catch (e) { console.warn(`[bot-folder] could not write SOUL.md mirror for ${bot.id}: ${(e as Error).message}`); }
// Before its transcript: clients need the bot/thread mapping to place either message.
opts.beforeShown?.(bot); this.emit({ type: "bot", botId: bot.id });
if (opts.seedMessages !== false) {
- this.appendMessage(bot.threadId, initialGreetingMessage(name, this.initialLanguage, !bot.soul?.trim() && !bot.description.trim(), this.personName()));
+ this.appendMessage(bot.threadId, { ...initialGreetingMessage(name, this.initialLanguage, !bot.soul?.trim() && !bot.description.trim(), this.personName()), at: bot.createdAt });
}
return bot;
}
diff --git a/server/testing/fake-claude-cli.ts b/server/testing/fake-claude-cli.ts
index a400ff9dca..afbc7cef0d 100755
--- a/server/testing/fake-claude-cli.ts
+++ b/server/testing/fake-claude-cli.ts
@@ -19,6 +19,9 @@
// unsupported, like any other control_request
// FAKE_CLAUDE_CONTEXT_USAGE_LATE 1: the first get_context_usage is answered only when the next control_request arrives
// FAKE_CLAUDE_CONTROL_LOG JSON-lines file every control_response the host writes is appended to
+// FAKE_CLAUDE_MCP_RECONNECT JSON-lines file: an mcp_reconnect control_request is appended to it and answered with
+// success, as Claude Code 2.1.321 answers once the server is connected again; "refuse" answers it as a failure
+// FAKE_CLAUDE_LAUNCHES JSON-lines file every stream-json process appends its {pid, argv} to as it starts
// FAKE_CLAUDE_EXIT_AFTER_TURN 1: exit once the turn is answered, so later turns relaunch with --resume
// FAKE_CLAUDE_AUTH_AFTER_TURN 1: from the second turn, answer as not-logged-in; FAKE_CLAUDE_AUTH_AFTER_WORK 1: not-logged-in
// calls a tool first
@@ -1355,6 +1358,7 @@ const playTurn = (prompt: JsonValue, late = false) => {
}
};
+if (process.env.FAKE_CLAUDE_LAUNCHES) appendFileSync(process.env.FAKE_CLAUDE_LAUNCHES, `${JSON.stringify({ pid: process.pid, argv: process.argv.slice(2) })}\n`);
let buf = "";
process.stdin.on("data", (c) => {
buf += c;
@@ -1374,6 +1378,12 @@ process.stdin.on("data", (c) => {
continue;
}
const control = prompt as { type?: unknown; request_id?: unknown; request?: { subtype?: unknown } } | null;
+ if (control?.type === "control_request" && control.request?.subtype === "mcp_reconnect" && process.env.FAKE_CLAUDE_MCP_RECONNECT) {
+ const refused = process.env.FAKE_CLAUDE_MCP_RECONNECT === "refuse";
+ if (!refused) appendFileSync(process.env.FAKE_CLAUDE_MCP_RECONNECT, `${line}\n`);
+ out({ type: "control_response", response: refused ? { subtype: "error", request_id: control.request_id, error: "Server not connected" } : { subtype: "success", request_id: control.request_id } });
+ continue;
+ }
if (control?.type === "control_request") {
const usage = control.request?.subtype === "get_context_usage" ? process.env.FAKE_CLAUDE_CONTEXT_USAGE : undefined;
const answer = { type: "control_response", response: usage
diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.ts
index 392c032519..65d3b024a2 100755
--- a/server/testing/fake-codex-app-server.ts
+++ b/server/testing/fake-codex-app-server.ts
@@ -34,6 +34,9 @@
// FAKE_CODEX_ACCOUNT_MODE chatgpt (default) | api-key | none | unsupported | error | hang
// FAKE_CODEX_RESUME_ERROR JSON-RPC error rejecting thread/resume
// FAKE_CODEX_ARCHIVED "1": thread/resume says the session is archived until thread/unarchive; "unarchive-fails": unarchive is refused too
+// FAKE_CODEX_INSTRUCTIONS_FILE while this file exists, config/read reports its text as developer_instructions: the
+// person's configuration changed while the process ran (codex-cli 0.160.1 reads the files on every config/read)
+// FAKE_CODEX_DIE_ON_TURN this process is killed as its Nth turn/start arrives, before any reply
// FAKE_CODEX_STARTUP_DELAY_MS hold the initialize reply this long, like a loaded host
// FAKE_CODEX_STARTUP_LOG append {pid, at, event: "initialize" | "turn/start"} per launch
// FAKE_CODEX_START_ERROR JSON-RPC error rejecting thread/start
@@ -219,7 +222,9 @@ let experimentalApi = false;
const out = (obj: unknown) => process.stdout.write(JSON.stringify(obj) + "\n");
let nativeThreadId = "codex-thread-1";
-const nativeTurnId = "turn-1";
+let nativeTurnId = "turn-1";
+let turnsStarted = 0;
+let turnsFinished = 0;
const notify = (method: string, params: any) => out({
jsonrpc: "2.0", method,
params: {
@@ -410,7 +415,7 @@ 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, cachedInputTokens: carried.cachedInputTokens + 4, outputTokens: carried.outputTokens + 3 },
+ total: { inputTokens: carried.inputTokens + 7 * ++turnsFinished, cachedInputTokens: carried.cachedInputTokens + 4 * turnsFinished, outputTokens: carried.outputTokens + 3 * turnsFinished },
last: { inputTokens: 7, cachedInputTokens: 4, outputTokens: 3 },
modelContextWindow: 272000,
} });
@@ -493,7 +498,8 @@ const playRoomPlanTurn = (msg: any, planPath: string) => {
if (!early) ack();
// Loaded only in this mode: other tests run a copy of this file on its own.
void import("./room-handoff-agent.ts").then(({ runRoomHandoffAgent }) => runRoomHandoffAgent(process.argv.slice(2), planPath, { message: { content: text } },
- { integration, system: developerInstructions, evidence: { resumedThread } }))
+ // A later turn of one process carries on the thread it has loaded, with no thread/resume.
+ { integration, system: developerInstructions, evidence: { resumedThread: resumedThread ?? (turnsStarted > 1 ? nativeThreadId : null) } }))
.then((reply) => {
notify("item/completed", { item: { id: "m1", type: "agentMessage", text: reply } });
notify("turn/completed", { turn: { status: "completed" } });
@@ -602,6 +608,7 @@ process.stdin.on("data", (chunk) => {
}
break;
case "config/read":
+ logStartup("config/read");
if (mode === "config-read-error") {
dump();
out({ jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "config unavailable" } });
@@ -631,7 +638,8 @@ process.stdin.on("data", (chunk) => {
harmless_name: { env: { DISPLAY_LABEL: "innocuous-config-secret-7a9c" } },
},
}),
- developer_instructions: process.env.FAKE_CODEX_INSTRUCTIONS ?? null,
+ developer_instructions: process.env.FAKE_CODEX_INSTRUCTIONS_FILE && existsSync(process.env.FAKE_CODEX_INSTRUCTIONS_FILE)
+ ? readFileSync(process.env.FAKE_CODEX_INSTRUCTIONS_FILE, "utf8") : process.env.FAKE_CODEX_INSTRUCTIONS ?? null,
shell_environment_policy: shellEnvironmentPolicy(),
features: Object.fromEntries(process.argv.flatMap((arg, index) => {
const match = process.argv[index - 1] === "-c" ? /^features\.(\w+)=(true|false)$/.exec(arg) : null;
@@ -718,7 +726,9 @@ process.stdin.on("data", (chunk) => {
break;
case "turn/start": {
if (process.env.FAKE_CODEX_MCP_READY_MS) mcpReadyAtTurnStart = mcpPending.length === 0;
+ nativeTurnId = `turn-${++turnsStarted}`;
dump();
+ if (Number(process.env.FAKE_CODEX_DIE_ON_TURN) === turnsStarted) process.kill(process.pid, "SIGKILL");
logStartup("turn/start");
nativeThreadId = msg.params?.threadId ?? nativeThreadId;
if (mode === "early-tool-timeout" || mode === "early-tool-error") {
@@ -1135,5 +1145,6 @@ process.stdin.on("data", (chunk) => {
}
});
-// match the real app-server: stay alive until killed
+// codex-cli 0.160.1 stays up between turns and exits once its stdin closes.
+process.stdin.on("end", () => setTimeout(() => process.exit(0), 200));
setInterval(() => {}, 1_000);
diff --git a/server/testing/fixtures/registry-format1/bots.json b/server/testing/fixtures/registry-format1/bots.json
index 01624ac0d5..88e3e90529 100644
--- a/server/testing/fixtures/registry-format1/bots.json
+++ b/server/testing/fixtures/registry-format1/bots.json
@@ -23,9 +23,9 @@
"title": "New thread",
"createdAt": 1794819601000,
"updatedAt": 1794819601000,
+ "lastThreadOrderAt": 1794819601000,
"resumeCursors": {},
- "unread": false,
- "lastThreadOrderAt": 1794819601000
+ "unread": false
}
]
},
@@ -83,9 +83,9 @@
"title": "New thread",
"createdAt": 1794819600000,
"updatedAt": 1794819600000,
+ "lastThreadOrderAt": 1794819600000,
"resumeCursors": {},
- "unread": false,
- "lastThreadOrderAt": 1794819600000
+ "unread": false
}
]
}
diff --git a/server/thread-history.ts b/server/thread-history.ts
index c8c36d3c8b..e1f450c75e 100644
--- a/server/thread-history.ts
+++ b/server/thread-history.ts
@@ -15,10 +15,21 @@ function sliceBefore({ messages, activeLeafId }: ThreadState, before: string, li
return { messages: messages.slice(start, end), hasMore: start > 0, activeLeafId };
}
+function sliceAround({ messages, activeLeafId }: ThreadState, messageId: string, limit: number): HistoryPage | null {
+ const index = messages.findIndex((message) => message.id === messageId);
+ if (index < 0) return null;
+ const before = Math.floor((limit - 1) / 2);
+ const start = Math.max(0, Math.min(index - before, messages.length - limit));
+ const stop = Math.min(messages.length, start + limit);
+ return { messages: messages.slice(start, stop), hasMore: start > 0, activeLeafId };
+}
+
const LAST_MESSAGE = "SELECT id FROM messages WHERE thread_id = ? ORDER BY rowid DESC LIMIT 1";
+const MESSAGE_ROW = "SELECT rowid FROM messages WHERE thread_id = ? AND id = ?";
+const LATER_MESSAGES = "SELECT json FROM messages WHERE thread_id = ? AND rowid >= ? ORDER BY rowid LIMIT ?";
const EARLIER_MESSAGES = "SELECT json FROM messages WHERE thread_id = ? AND rowid < ? ORDER BY rowid DESC LIMIT ?";
-function lastMessageId(threadId: string): string | null {
+export function lastMessageId(threadId: string): string | null {
return (prepared(LAST_MESSAGE).get(threadId) as { id: string } | undefined)?.id ?? null;
}
@@ -31,7 +42,7 @@ export function messagesBefore(
): HistoryPage | null {
if (cached) return sliceBefore(cached, before, limit);
- const cursor = prepared("SELECT rowid FROM messages WHERE thread_id = ? AND id = ?").get(threadId, before) as { rowid: number } | undefined;
+ const cursor = prepared(MESSAGE_ROW).get(threadId, before) as { rowid: number } | undefined;
if (!cursor) {
if (lastMessageId(threadId) !== null) return null;
return sliceBefore(loadThread(), before, limit);
@@ -43,3 +54,19 @@ export function messagesBefore(
return { ...page, activeLeafId: readStoredActiveLeaf(threadId) || lastMessageId(threadId) };
}
+
+/** The page of `limit` messages with `messageId` in its middle, pushed back from either end of the conversation. */
+export function messagesAround(threadId: string, messageId: string, limit: number, loadThread: () => ThreadState): HistoryPage | null {
+ if (limit < 1) return sliceAround(loadThread(), messageId, limit);
+
+ const cursor = prepared(MESSAGE_ROW).get(threadId, messageId) as { rowid: number } | undefined;
+ if (!cursor) return lastMessageId(threadId) === null ? sliceAround(loadThread(), messageId, limit) : null;
+
+ const earlier = decodeMessagePage(prepared(EARLIER_MESSAGES).all(threadId, cursor.rowid, limit + 1) as Array<{ json: string }>, limit);
+ const later = (prepared(LATER_MESSAGES).all(threadId, cursor.rowid, limit) as Array<{ json: string }>).map((row) => JSON.parse(row.json) as Message);
+ const near = [...earlier.messages, ...later];
+ if (near.some((message) => message.parentId === undefined)) return sliceAround(loadThread(), messageId, limit);
+
+ const page = sliceAround({ messages: near, activeLeafId: readStoredActiveLeaf(threadId) || lastMessageId(threadId) }, messageId, limit)!;
+ return { ...page, hasMore: page.hasMore || earlier.hasMore };
+}
diff --git a/server/thread-presence.ts b/server/thread-presence.ts
index dca46e7974..7e96ebd7a3 100644
--- a/server/thread-presence.ts
+++ b/server/thread-presence.ts
@@ -40,6 +40,21 @@ export function seenWithin(threadId: string, ms: number, now: number = Date.now(
return now - (sightings.get(threadId) ?? -Infinity) <= ms;
}
+const madeListeners = new Set<(botId: string, threadId: string) => void>();
+
+/** A person made this conversation themselves, just now: its first message is probably on its way. */
+export function madeThread(botId: string, threadId: string): void {
+ for (const listener of madeListeners) {
+ try { listener(botId, threadId); } catch (error) { console.warn(`thread presence: ${(error as Error).message}`); }
+ }
+}
+
+/** Hears every conversation a person makes; returns the unsubscribe. */
+export function onThreadMade(listener: (botId: string, threadId: string) => void): () => void {
+ madeListeners.add(listener);
+ return () => madeListeners.delete(listener);
+}
+
export function forgetPresence(): void {
sightings.clear();
personAsks.clear();
diff --git a/src/lib/create-configured-bot.test.ts b/src/lib/create-configured-bot.test.ts
index 25b4e4b025..a7c781e4c3 100644
--- a/src/lib/create-configured-bot.test.ts
+++ b/src/lib/create-configured-bot.test.ts
@@ -118,4 +118,65 @@ describe("configured bot creation", () => {
expect(f.approvals.setMode).toHaveBeenCalledTimes(1);
expect(f.events.at(-1)).toBe("DELETE /api/bots/created");
});
+
+ describe("a template with memory, skills and a routine", () => {
+ const skill = (name: string) => ({ name, description: "", warnings: [], source: `local:${name}`, text: `---\nname: ${name}\n---\n`, enabled: true });
+ const routine = { name: "Morning check", prompt: "Check the inbox", schedule: { type: "daily" as const, time: "09:00", weekdays: [1, 2, 3, 4, 5] } };
+ function templated(failing?: string) {
+ const draft = new BotCreationDraft({
+ profile: { name: "Fixture" },
+ memory: { "MEMORY.md": "index", "memory/notes.md": "notes" },
+ skills: [skill("first-skill"), skill("second-skill")],
+ routines: [routine],
+ }, vi.fn());
+ const events: string[] = [];
+ const open = new Set<string>();
+ let widest = 0;
+ const request = vi.fn(async (path: string, init?: RequestInit) => {
+ const body = JSON.parse(String(init?.body ?? "{}"));
+ const event = `${init?.method} ${path}${body.path ? ` ${body.path}` : path.endsWith("/skill-template") ? ` ${body.name}` : ""}`;
+ events.push(event);
+ open.add(event);
+ widest = Math.max(widest, open.size);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ open.delete(event);
+ if (event === failing) throw new Error("Refused");
+ if (path === "/api/routines") return { routine: { id: "routine-1" } };
+ return { bot: { ...draft.bot, id: "created", threadId: "initial", approvalMode: "ask" } };
+ }) as unknown as typeof api;
+ return { draft, events, request, widest: () => widest };
+ }
+ const setup = ["PUT /api/bots/created/memory/file MEMORY.md", "PUT /api/bots/created/memory/file memory/notes.md",
+ "POST /api/bots/created/skill-template first-skill", "POST /api/bots/created/skill-template second-skill", "POST /api/routines"];
+
+ it("sends each file once, each kind in its own order, the kinds side by side", async () => {
+ const f = templated();
+ const result = await createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined);
+ expect(result.warnings).toEqual([]);
+ expect(f.events.slice(0, 2)).toEqual(["POST /api/bots", "PATCH /api/bots/created"]);
+ expect(f.events.at(-1)).toBe("PATCH /api/routines/routine-1");
+ expect(f.events.slice(2, -1).sort()).toEqual([...setup].sort());
+ const at = (event: string) => f.events.indexOf(event);
+ expect(at(setup[0]!)).toBeLessThan(at(setup[1]!));
+ expect(at(setup[2]!)).toBeLessThan(at(setup[3]!));
+ expect(f.events.slice(2, 5).sort()).toEqual([setup[0]!, setup[2]!, setup[4]!].sort());
+ expect(f.widest()).toBe(3);
+ });
+
+ it("removes the routine and the bot when a skill is refused, after every other request has answered", async () => {
+ const f = templated(setup[2]);
+ await expect(createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined)).rejects.toThrow("Refused");
+ expect(f.events.slice(-2)).toEqual(["DELETE /api/routines/routine-1", "DELETE /api/bots/created"]);
+ expect(f.events).not.toContain(setup[3]);
+ expect(f.events).toContain(setup[1]);
+ expect(f.events).not.toContain("PATCH /api/routines/routine-1");
+ });
+
+ it("removes the bot when a memory file is refused", async () => {
+ const f = templated(setup[0]);
+ await expect(createConfiguredBot(f.draft, f.request, persistBotUpdate, undefined)).rejects.toThrow("Refused");
+ expect(f.events.slice(-2)).toEqual(["DELETE /api/routines/routine-1", "DELETE /api/bots/created"]);
+ expect(f.events).not.toContain(setup[1]);
+ });
+ });
});
diff --git a/src/lib/create-configured-bot.ts b/src/lib/create-configured-bot.ts
index 04f9d1366d..70f175ef98 100644
--- a/src/lib/create-configured-bot.ts
+++ b/src/lib/create-configured-bot.ts
@@ -58,22 +58,35 @@ export async function createConfiguredBot(
throw new Error(t("newBot.threadApprovalNotGranted"));
}
}
- for (const [path, text] of Object.entries(template.memory)) {
- if (preset?.notes.includes(path)) continue;
- await request(`/api/bots/${bot.id}/memory/file`, {
- method: "PUT", body: JSON.stringify({ path, text }),
- });
- }
- for (const skill of template.skills) {
- if (preset?.skills.includes(skill.name)) continue;
- await request(`/api/bots/${bot.id}/skill-template`, { method: "POST", body: JSON.stringify(skill) });
- }
- for (const routine of template.routines) {
- const result = await request<{ routine: Routine }>("/api/routines", {
- method: "POST", body: JSON.stringify({ ...routine, botId: bot.id, enabled: false }),
- });
- routines.push({ id: result.routine.id, enabled: routine.enabled !== false });
- }
+ const botId = bot.id;
+ // Memory, skills and routines are separate stores on the server: each kind is written in its own order, the three
+ // side by side. Every request has answered before a failure is reported, so cleanup sees each routine that was made.
+ const setup = await Promise.allSettled([
+ (async () => {
+ for (const [path, text] of Object.entries(template.memory)) {
+ if (preset?.notes.includes(path)) continue;
+ await request(`/api/bots/${botId}/memory/file`, {
+ method: "PUT", body: JSON.stringify({ path, text }),
+ });
+ }
+ })(),
+ (async () => {
+ for (const skill of template.skills) {
+ if (preset?.skills.includes(skill.name)) continue;
+ await request(`/api/bots/${botId}/skill-template`, { method: "POST", body: JSON.stringify(skill) });
+ }
+ })(),
+ (async () => {
+ for (const routine of template.routines) {
+ const result = await request<{ routine: Routine }>("/api/routines", {
+ method: "POST", body: JSON.stringify({ ...routine, botId, enabled: false }),
+ });
+ routines.push({ id: result.routine.id, enabled: routine.enabled !== false });
+ }
+ })(),
+ ]);
+ const failed = setup.find((step) => step.status === "rejected");
+ if (failed) throw failed.reason;
} catch (error) {
const cleanup: string[] = [];
for (const routine of routines) {
@@ -96,9 +109,10 @@ export async function createConfiguredBot(
warnings.push(t("newBot.warning.chiefOfStaff", { error: error instanceof Error ? error.message : String(error) }));
}
}
- for (const routine of routines.filter(routine => routine.enabled)) {
- try { await request(`/api/routines/${routine.id}`, { method: "PATCH", body: JSON.stringify({ enabled: true }) }); }
- catch (error) { warnings.push(t("newBot.warning.routine", { error: error instanceof Error ? error.message : String(error) })); }
+ const switchedOn = await Promise.allSettled(routines.filter(routine => routine.enabled).map(routine =>
+ request(`/api/routines/${routine.id}`, { method: "PATCH", body: JSON.stringify({ enabled: true }) })));
+ for (const outcome of switchedOn) {
+ if (outcome.status === "rejected") warnings.push(t("newBot.warning.routine", { error: outcome.reason instanceof Error ? outcome.reason.message : String(outcome.reason) }));
}
return { bot, warnings, ...(response.paused ? { paused: true as const } : {}) };
}