Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Long threads: Claude and Codex compact their own sessions; the summary is written ahead of the limit (#6670)
Milind Soni198b84350b69
diff --git a/docs/verification/context-compaction.md b/docs/verification/context-compaction.mdindex 62adf9c14b..db42c87cda 100644--- a/docs/verification/context-compaction.md+++ b/docs/verification/context-compaction.md@@ -1,5 +1,38 @@# Conversation context compaction+## Who compacts++An engine that keeps its own session and compacts it (Claude Code, Codex:+`nativeCompaction` in the driver's capabilities) is left to do so. OpenMausBot+does not summarize such a conversation before a turn, does not replace its+session, and shows the engine's compaction as a note in the chat when the+engine reports it (Claude Code's `compact_boundary`, Codex's+`contextCompaction` item). **Compact now** asks the engine first: for Claude+Code that is its own `/compact` on a fork of the session, as for a warm+summary below, and the conversation moves to that fork.++OpenMausBot's own fold (below) is what compacts in every other case:++- an engine with no compaction of its own that OpenMausBot is told of (the API+ models, Pi, Muse Code, ACP agents);+- a session its engine left uncompacted: the last measured prompt is within+ 10,000 tokens or 5% (whichever is closer) of the model's window, or of+ `OMB_CLAUDE_AUTOCOMPACT` when that is lower (190,000 by default). Claude Code+ compacts about 33,000 tokens below that point and Codex at 90% of its+ window, so a healthy session never reads this high;+- Claude Code with `DISABLE_AUTO_COMPACT` or `DISABLE_COMPACT` in the+ account's environment: the fold runs at the thresholds under Bounds;+- `context.compactAt` set in config.json: the fold runs there for every+ engine, as it did before engines were left to compact themselves;+- Compact now when the engine cannot run its own (no session open or parked,+ a Claude Code too old to fork, Codex).++```sh+pnpm exec vitest run server/host/conversation-compaction.test.ts server/context-compaction.e2e.test.ts+```++## OpenMausBot's fold+Long direct conversations can summarize older exchanges before the next turn.The full transcript, its branches and attachments are retained. The new sessiongets a bounded summary plus recent exchanges; later turns resume that session.@@ -35,12 +68,20 @@ the idle gap after the turn before, while the prompt cache is still warm, sothe next turn starts small.- **When:** a direct conversation (not a room or a routine's run) whose turn- ended with 100k tokens or more of context gets one about 3 minutes later. A- conversation at 80% or more of where Claude Code summarizes by itself- (`OMB_CLAUDE_AUTOCOMPACT`, 200,000 by default) gets one about 10 seconds- later, because its next turn would summarize anyway. For other engines,- OpenMausBot's own fold runs while idle once the conversation is at 85% of- the threshold its next turn would fold at.+ ended with 100k tokens or more of context gets one about 3 minutes later.+ Claude Code summarizes by itself about 33,000 tokens below+ `OMB_CLAUDE_AUTOCOMPACT` (200,000 by default, so near 167k). A conversation+ within 27,000 tokens of that point (140k) gets its summary about 10 seconds+ after the turn, since one more turn of tool work can reach that point; a+ message sent meanwhile is not held up and the summary is dropped, and+ after one dropped that way the conversation goes back to the 3 minutes+ until a summary is written. Within+ 7,000 tokens of it (160k) it starts one second after the turn, because the next turn+ would summarize anyway; a message sent meanwhile shows "context compaction+ started (auto)" and its turn starts when the summary is written (at most 3+ minutes, then the turn goes on without it). For an engine+ OpenMausBot folds for, the fold runs while idle once the conversation is at+ 85% of the threshold its next turn would fold at.- **Claude Code:** `/compact` with instructions to keep the person's latestrequests and every open question (open question cards are named), on afork of the session (`--resume <session> --fork-session`) launched with@@ -373,11 +414,13 @@ those at the top level. A URL inside a command is left as the command ran.`context` settings in config.json are optional. `autoCompact: false` disablesautomatic folding, `compactAt` is a fraction below 1 or a token count, and`rebuildBytes` controls replay size (default 24,000 bytes). Context-only settings-do not reload provider processes. The default threshold is 80% of the known+do not reload provider processes. For an engine that does not compact itself+the default threshold is 80% of the knownmodel window; a real latest-prompt measurement wins over a transcript estimate,except an ACP agent's own reading, which is shown and does not time compaction.Summed input tokens across tool rounds are never treated as context size.-For Claude, the threshold and post-compaction regrowth floor also leave 10%+For Claude with a `compactAt` set or its own compaction switched off, the+threshold and post-compaction regrowth floor also leave 10%headroom below the selected account's numeric native-compaction setting.That account's setting takes precedence over the inherited launch environment.Native `auto`/`off` settings supply no known numeric bound; other engines keepdiff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.tsindex 170b9ba890..50e360ff4a 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": 15385,+ "server/index.ts": 15337,"src/state/store.tsx": 3288,"electron/main.mjs": 3124,"server/store.ts": 2265,diff --git a/server/context-compaction.e2e.test.ts b/server/context-compaction.e2e.test.tsindex 9af16773b9..aa28698587 100644--- a/server/context-compaction.e2e.test.ts+++ b/server/context-compaction.e2e.test.ts@@ -71,7 +71,49 @@ async function setup(hang: boolean, fakeEnv: NodeJS.ProcessEnv) {} finally { if (!ready) await session.close(); }}+/** Account environment is a persisted config setting, not writable through the public config patch: this changes only+ * the stopped fixture's own config. With DISABLE_COMPACT, Claude Code has no compaction and a summary is OpenMausBot's fold. */+const claudeEnvironment = (f: Awaited<ReturnType<typeof setup>>, values: Record<string, string>) => f.restart(() => {+ const path = join(f.session.info.dataDir, "config.json");+ const config = JSON.parse(readFileSync(path, "utf8"));+ Object.assign(config.instances.claude.environment, values);+ writeFileSync(path, JSON.stringify(config));+});++it("Compact now runs Claude Code's own compaction and keeps the conversation on a session of that engine", () => fixture(async f => {+ await f.send("OLDER_REQUEST use port 9000");+ await f.send("CORRECTION use port 9001 instead");+ await f.send("LATEST and name the service ledger");+ const before = await f.messages();+ const oldSession = f.task().resumeCursors.claude;+ const turnsBefore = f.turns().length;+ await f.compact();+ await f.idle();+ const after = await f.messages();+ expect(after.at(-1)).toMatchObject({ kind: "compaction", engineCompaction: true });+ expect(after.at(-1).compaction).toBeUndefined();+ expect(after.filter(m => m.kind === "compaction")).toHaveLength(1);+ expect(after.slice(0, before.length).map(m => m.id)).toEqual(before.map(m => m.id));+ expect(f.turns()).toHaveLength(turnsBefore);+ const summarized = f.task().resumeCursors.claude;+ expect(summarized).not.toBe(oldSession);+ expect(summarized).toMatch(/^fork-/);+ await f.compact();+ await f.idle();+ expect((await f.messages()).filter(m => m.kind === "compaction")).toHaveLength(1);+ expect(f.task().resumeCursors.claude).toBe(summarized);+ expect(f.task().appliedCompactionId).toBeUndefined();+ await f.send("What port did we settle on?");+ const prompt = String(f.turns().at(-1).prompt.message.content);+ expect(prompt).not.toContain("Earlier conversation summary");+ expect(prompt).toContain("CORRECTION use port 9001 instead");+ expect(prompt).toContain("LATEST and name the service ledger");+ expect(prompt).not.toContain("OLDER_REQUEST");+ expect(f.task().resumeCursors.claude).toBe(summarized);+}), 90_000);+it("compacts durably, keeps corrections and starts a fresh native session without deleting any chats", () => fixture(async f => {+ await claudeEnvironment(f, { DISABLE_COMPACT: "1" });await f.send("OLDER_REQUEST use port 9000");await f.send("CORRECTION use port 9001 instead; cancel the earlier request");const before = await f.messages();@@ -133,6 +175,7 @@ it("automatically folds old exchanges while keeping the two latest and the incom}), 70_000);it("Stop cancels a stalled summary without writing a late record or starting an agent", () => fixture(async f => {+ await claudeEnvironment(f, { DISABLE_COMPACT: "1" });await f.send("Keep this original chat intact");const before = await f.messages();const previousRequest = before.findLast(message => message.role === "user");@@ -160,16 +203,7 @@ it.each([{ native: "off", tokens: 190_000, compactions: 0 },{ native: "auto", tokens: 190_000, compactions: 0 },])("respects the selected account's native compaction setting ($native)", ({ native, tokens, compactions }) => fixture(async f => {- if (native !== undefined) {- // Account environment is a persisted config setting, not writable through- // the public config patch. Change only this stopped fixture's own config.- await f.restart(() => {- const path = join(f.session.info.dataDir, "config.json");- const config = JSON.parse(readFileSync(path, "utf8"));- config.instances.claude.environment.OMB_CLAUDE_AUTOCOMPACT = native;- writeFileSync(path, JSON.stringify(config));- });- }+ if (native !== undefined) await claudeEnvironment(f, { OMB_CLAUDE_AUTOCOMPACT: native });await f.api(`/api/bots/${f.bot.id}/tasks/${f.thread}`, {modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6[1m]" },}, "PATCH");@@ -185,3 +219,22 @@ it.each([expect(f.turns().at(-1).resumed).toBe(false);}}, false, { FAKE_CLAUDE_CONTEXT_TOKENS: String(tokens) }), 90_000);++it.each([+ { name: "leaves a session Claude Code will compact itself", tokens: 165_000, engineOff: false, compactions: 0 },+ { name: "folds a session that Claude Code left uncompacted near its limit", tokens: 191_000, engineOff: false, compactions: 1 },+ { name: "folds at 80% when Claude Code's own compaction is switched off", tokens: 165_000, engineOff: true, compactions: 1 },+])("on a 200k model, $name", ({ tokens, engineOff, compactions }) => fixture(async f => {+ if (engineOff) await claudeEnvironment(f, { DISABLE_AUTO_COMPACT: "1" });+ await f.api(`/api/bots/${f.bot.id}/tasks/${f.thread}`, {+ modelSelection: { instanceId: "claude", model: "claude-sonnet-4-6" },+ }, "PATCH");+ for (const text of ["FIRST historical request", "SECOND keep recent", "THIRD correction"]) await f.send(text);+ const session = f.task().resumeCursors.claude;+ expect(typeof session).toBe("string");+ await f.send("INCOMING follow-up");+ expect(f.task().usage.context).toMatchObject({ tokens, window: 200_000 });+ expect((await f.messages()).filter(m => m.kind === "compaction")).toHaveLength(compactions);+ expect(f.task().resumeCursors.claude === session).toBe(compactions === 0);+ expect(String(f.turns().at(-1).prompt.message.content).includes("Earlier conversation summary")).toBe(compactions === 1);+}, false, { FAKE_CLAUDE_CONTEXT_TOKENS: String(tokens) }), 90_000);diff --git a/server/contracts.ts b/server/contracts.tsindex 182a1c4608..029e98c5f3 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -290,6 +290,9 @@ export interface ProviderAdapter {/** A resumeCursor turn runs in that exact native session, or fails, or starts a new one from recoveryText (session.started says* `rebuilt`), never a blank one. */strictResume?: boolean;+ /** The engine compacts its own session as it nears its window and reports it (`context.compacted`), so OpenMausBot+ * leaves that session alone and folds only one its engine left uncompacted. */+ nativeCompaction?: boolean;/** sendTurn can register the harness's hook helper with the engine (integrations.hooks). */hooks?: boolean;/** "confined": sendTurn honours `guestConfined`; absent, a guest turn is refused. */diff --git a/server/drivers/claude.ts b/server/drivers/claude.tsindex 9c6cd89063..ac04b825fd 100644--- a/server/drivers/claude.ts+++ b/server/drivers/claude.ts@@ -2008,7 +2008,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {get strictResume() {return cliVersionChecked && cliVersion !== null && claudeCliSupports(cliVersion, "--system-prompt-snapshot");},- localComputerMcp: true,+ localComputerMcp: true, nativeCompaction: true,hooks: true, askTool: { kind: "mcp", server: "ogb", name: "ask_user" },},sendTurn: (turn) => authRecovery.send(turn, sendTurn),diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 3740ab18f7..e40eea46bc 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -2226,6 +2226,20 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)expect(types.indexOf("turn.progress")).toBeGreaterThan(types.indexOf("item.started"));});+ it("reports Codex's own compaction of the session once, and as no tool", async () => {+ process.env.FAKE_CODEX_COMPACTION = "1";+ try {+ await create();+ await instance.adapter.sendTurn({ threadId: "t-compaction", text: "carry on" });+ await recorder.until((e) => e.type === "turn.completed");+ } finally {+ delete process.env.FAKE_CODEX_COMPACTION;+ }+ expect(recorder.events.filter((e) => e.type === "context.compacted")).toHaveLength(1);+ expect(recorder.events.some((e) => "itemId" in e && e.itemId === "c1")).toBe(false);+ expect(instance.adapter.capabilities.nativeCompaction).toBe(true);+ });+it("streams a running command's output to the bus, and names its app-server while the turn runs", async () => {const gate = join(scratch, "command-done");Object.assign(process.env, { FAKE_CODEX_COMMAND: "/bin/zsh -lc 'pnpm test'", FAKE_CODEX_COMMAND_OUTPUT: JSON.stringify(["RUN v3\n", " ✓ a.test.ts\n"]), FAKE_CODEX_COMMAND_GATE: gate });diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 7bc52272ea..9913c6e6b0 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -1039,8 +1039,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {emit({ ...base(threadId, turnId), type: "item.completed", itemType: "assistant_image", data: img.data, fromTool: true });}}- } else if (item.type === "reasoning") {- emit({ ...base(threadId, turnId), type: "item.updated", itemType: "reasoning", tokens: null });+ } else if (item.type === "reasoning" || item.type === "contextCompaction") {+ emit(item.type === "reasoning" ? { ...base(threadId, turnId), type: "item.updated", itemType: "reasoning", tokens: null } : { ...base(threadId, turnId), type: "context.compacted" });}break;}@@ -1553,7 +1553,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {images: true,nativeImageInput: true,effortLevels: ["low", "medium", "high", "xhigh", "max"],- strictResume: true,+ strictResume: true, nativeCompaction: true,},sendTurn,interruptTurn: async (threadId) => {diff --git a/server/fresh-start.e2e.test.ts b/server/fresh-start.e2e.test.tsindex a3953942d9..27b2aac327 100644--- a/server/fresh-start.e2e.test.ts+++ b/server/fresh-start.e2e.test.ts@@ -53,7 +53,7 @@ it("sends the provider nothing from before the divider, while a warm session and// A summary written before the divider must not cross it either.await f.api(`/api/bots/${f.bot.id}/compact`, { method: "POST", body: JSON.stringify({ threadId: f.thread }) });await f.settled();- expect((await f.messages()).some((m) => m.kind === "compaction" && m.compaction && !m.compaction.fresh)).toBe(true);+ expect((await f.messages()).some((m) => m.kind === "compaction" && m.engineCompaction && !m.compaction)).toBe(true);f.guard();const reset = await f.startFresh() as { message: WireMessage | null };diff --git a/server/host/conversation-compaction.test.ts b/server/host/conversation-compaction.test.tsnew file mode 100644index 0000000000..bc06c5516f--- /dev/null+++ b/server/host/conversation-compaction.test.ts@@ -0,0 +1,146 @@+import { describe, expect, it } from "vitest";+import { compactBudget } from "../context-budget.ts";+import type { BotRecord, Message } from "../store.ts";+import { claudeCompactionDisabled, createConversationCompaction, foldBackstop, foldDue, type ConversationCompactionDeps } from "./conversation-compaction.ts";++describe("foldBackstop", () => {+ it("sits above where each engine compacts by itself and below its limit", () => {+ // Claude Code with --autocompact 200000 compacts near 167k; with its own window on a 1M model, near 967k.+ expect(foldBackstop(200_000, 200_000)).toBe(190_000);+ expect(foldBackstop(1_000_000, 200_000)).toBe(190_000);+ expect(foldBackstop(1_000_000)).toBe(990_000);+ expect(foldBackstop(200_000, 100_000)).toBe(95_000);+ // Codex compacts at 90% of the window it reports.+ expect(foldBackstop(272_000)).toBeGreaterThan(272_000 * 0.9);+ expect(foldBackstop(272_000)).toBeLessThan(272_000);+ expect(foldBackstop(8_000)).toBe(7_600);+ });+});++describe("foldDue", () => {+ const claude = { engineCompacts: true, estimatedBytes: 0, window: 200_000, nativeCompactAt: 200_000 };++ it("leaves a self-compacting engine's session alone below the backstop, where the fold used to run first", () => {+ expect(compactBudget(200_000, undefined, 200_000)).toBe(160_000);+ for (const contextTokens of [160_000, 164_274, 170_000, 189_999]) expect(foldDue({ ...claude, contextTokens })).toBe(false);+ });++ it("folds a session its engine left uncompacted", () => {+ expect(foldDue({ ...claude, contextTokens: 190_000 })).toBe(true);+ expect(foldDue({ engineCompacts: true, estimatedBytes: 0, window: 1_000_000, contextTokens: 989_999 })).toBe(false);+ expect(foldDue({ engineCompacts: true, estimatedBytes: 0, window: 1_000_000, contextTokens: 990_000 })).toBe(true);+ });++ it("never folds a self-compacting engine's session on a transcript estimate, which is not what its session holds", () => {+ expect(foldDue({ ...claude, estimatedBytes: 4_000_000 })).toBe(false);+ expect(foldDue({ ...claude, estimatedBytes: 4_000_000, idleFraction: 0.85 })).toBe(false);+ });++ it("keeps the fold where it was for an engine that does not compact itself", () => {+ const fed = { engineCompacts: false, estimatedBytes: 0, window: 200_000 };+ expect(foldDue({ ...fed, contextTokens: 159_999 })).toBe(false);+ expect(foldDue({ ...fed, contextTokens: 160_000 })).toBe(true);+ expect(foldDue({ ...fed, estimatedBytes: 640_000 })).toBe(true);+ expect(foldDue({ ...fed, contextTokens: 136_000, idleFraction: 0.85 })).toBe(true);+ expect(foldDue({ ...fed, contextTokens: 135_999, idleFraction: 0.85 })).toBe(false);+ });++ it("keeps the fold where it was for Claude Code with its own compaction switched off", () => {+ expect(foldDue({ engineCompacts: false, estimatedBytes: 0, window: 200_000, nativeCompactAt: 200_000, contextTokens: 160_000 })).toBe(true);+ });++ it("honours a compactAt the person set, for every engine", () => {+ expect(foldDue({ ...claude, configuredCompactAt: 0.5, contextTokens: 99_999 })).toBe(false);+ expect(foldDue({ ...claude, configuredCompactAt: 0.5, contextTokens: 100_000 })).toBe(true);+ expect(foldDue({ ...claude, configuredCompactAt: 120_000, contextTokens: 120_000 })).toBe(true);+ // Still never past the engine's own point.+ expect(foldDue({ ...claude, configuredCompactAt: 0.99, contextTokens: 180_000 })).toBe(true);+ });+});++describe("claudeCompactionDisabled", () => {+ it("reads Claude Code's own switches", () => {+ expect(claudeCompactionDisabled({})).toBe(false);+ expect(claudeCompactionDisabled({ DISABLE_AUTO_COMPACT: "1" })).toBe(true);+ expect(claudeCompactionDisabled({ DISABLE_COMPACT: "true" })).toBe(true);+ expect(claudeCompactionDisabled({ DISABLE_AUTO_COMPACT: "0", DISABLE_COMPACT: "" })).toBe(false);+ });+});++describe("compactConversation", () => {+ const bot = { id: "bot" } as BotRecord;+ const thread = "thread";+ function setup(options: { tokens: number; nativeCompaction?: boolean; engineCompactionOn?: boolean; engineCompact?: boolean; compactAt?: number }) {+ const messages: Message[] = ["one", "two", "three", "four"].flatMap((word, index) => [+ { id: `u${index}`, role: "user", kind: "text", text: `ask ${word}`, at: index * 2 } as Message,+ { id: `b${index}`, role: "bot", kind: "text", text: `answer ${word}`, at: index * 2 + 1 } as Message,+ ]);+ const asked: string[] = [];+ const deps: ConversationCompactionDeps = {+ store: {+ taskByThread: () => ({ lastContextModel: "engine:model", usage: { context: { tokens: options.tokens, window: 200_000 } }, resumeCursors: {} }) as never,+ activePath: () => messages,+ patchTask: () => undefined as never,+ appendMessage: (_threadId: string, message: Partial<Message>) => { const made = { id: `m${messages.length}`, ...message } as Message; messages.push(made); return made; },+ } as never,+ context: () => (options.compactAt === undefined ? undefined : { compactAt: options.compactAt }),+ directContext: (_bot, _thread, all) => all.filter((m) => m.kind === "text").map((m) => ({ id: m.id, role: m.role === "user" ? "user" as const : "assistant" as const, text: m.text ?? "" })),+ latestCompaction: () => undefined,+ nativeCompactTokens: () => 200_000,+ engineCompactionOn: () => options.engineCompactionOn ?? true,+ engineCompact: async (target) => { asked.push(target.instanceId); return options.engineCompact ?? false; },+ generateText: () => undefined,+ claimIsCurrent: () => true,+ controllers: new Map(),+ cancelled: (reason) => new Error(reason),+ idleFraction: 0.85,+ };+ const instance = { instanceId: "engine", driverKind: "claudeAgent", adapter: { capabilities: { nativeCompaction: options.nativeCompaction ?? true } } };+ const run = (manual: boolean) => createConversationCompaction(deps)({ bot, threadId: thread, generation: "g", instance, model: "model", excludedIds: new Set(), manual });+ const folds = () => messages.filter((m) => m.kind === "compaction");+ return { run, folds, asked, deps };+ }++ it("writes no fold before a turn at 164k on an engine that compacts itself, and one on an engine that does not", async () => {+ const own = setup({ tokens: 164_274 });+ await own.run(false);+ expect(own.folds()).toHaveLength(0);+ const fed = setup({ tokens: 164_274, nativeCompaction: false });+ await fed.run(false);+ expect(fed.folds()).toHaveLength(1);+ expect(fed.folds()[0]!.compaction).toMatchObject({ by: "harness", tokensBefore: 164_274 });+ });++ it("folds a session that reached the backstop: its engine did not compact", async () => {+ const stuck = setup({ tokens: 191_000 });+ await stuck.run(false);+ expect(stuck.folds()).toHaveLength(1);+ expect(stuck.asked).toEqual([]);+ });++ it("folds at the usual point when the engine's own compaction is switched off", async () => {+ const off = setup({ tokens: 164_274, engineCompactionOn: false });+ await off.run(false);+ expect(off.folds()).toHaveLength(1);+ });++ it("Compact now asks the engine first and writes no fold of its own when the engine did it", async () => {+ const done = setup({ tokens: 50_000, engineCompact: true });+ await done.run(true);+ expect(done.asked).toEqual(["engine"]);+ expect(done.folds()).toHaveLength(0);+ expect(done.deps.controllers.size).toBe(0);+ });++ it("Compact now falls back to the fold when the engine has no compaction to offer, and never asks an engine without one", async () => {+ const refused = setup({ tokens: 50_000, engineCompact: false });+ await refused.run(true);+ expect(refused.asked).toEqual(["engine"]);+ expect(refused.folds()).toHaveLength(1);+ expect(refused.folds()[0]!.compaction).toMatchObject({ by: "person" });+ const fed = setup({ tokens: 50_000, nativeCompaction: false, engineCompact: true });+ await fed.run(true);+ expect(fed.asked).toEqual([]);+ expect(fed.folds()).toHaveLength(1);+ });+});diff --git a/server/host/conversation-compaction.ts b/server/host/conversation-compaction.tsnew file mode 100644index 0000000000..6d8858703a--- /dev/null+++ b/server/host/conversation-compaction.ts@@ -0,0 +1,129 @@+import { draftSummary, foldPoint } from "../compaction-summary.ts";+import { compactBudget, compactionReading, contextWindowFor, shouldCompact } from "../context-budget.ts";+import { MAX_SUMMARY_BYTES, selectReplay } from "../context-rebuild.ts";+import type { ModelCatalog } from "../contracts.ts";+import type { ContextMessage } from "../delta-context.ts";+import { sinceFreshStart } from "../fresh-start.ts";+import type { BotRecord, Message, Store } from "../store.ts";++const positive = (n: number | null | undefined): n is number => typeof n === "number" && Number.isFinite(n) && n > 0;+const set = (value: string | undefined) => Boolean(value && !/^(0|false|no|off)$/i.test(value.trim()));++/** Claude Code 2.1 turns its own compaction off with DISABLE_AUTO_COMPACT or DISABLE_COMPACT in its environment. */+export function claudeCompactionDisabled(env: Record<string, string | undefined>): boolean {+ return set(env.DISABLE_AUTO_COMPACT) || set(env.DISABLE_COMPACT);+}++/** An engine that compacts itself does so below its limit (Claude Code about 33k tokens under its compaction window, Codex+ * at 90% of the model's window), so a session measured this close to the limit was not compacted by its engine. */+export function foldBackstop(window: number, nativeCompactAt?: number): number {+ const limit = positive(nativeCompactAt) ? Math.min(window, nativeCompactAt) : window;+ return Math.floor(Math.max(limit - 10_000, limit * 0.95));+}++/** When OpenMausBot's own fold runs before a turn. An engine that compacts its own session keeps that session: the fold+ * is only the guard for a session its engine left uncompacted. `context.compactAt` set by the person applies to every engine. */+export function foldDue(input: {+ engineCompacts: boolean; configuredCompactAt?: number; contextTokens?: number; estimatedBytes: number;+ window: number; nativeCompactAt?: number; floor?: number; idleFraction?: number;+}): boolean {+ const { window, nativeCompactAt } = input;+ if (input.engineCompacts && !positive(input.configuredCompactAt)) {+ return positive(input.contextTokens) && input.contextTokens >= foldBackstop(window, nativeCompactAt);+ }+ return shouldCompact({ contextTokens: input.contextTokens, estimatedBytes: input.estimatedBytes,+ budget: compactBudget(window, input.configuredCompactAt, nativeCompactAt) * (input.idleFraction ?? 1), floor: input.floor, window, nativeCompactAt });+}++interface CompactionInstance {+ instanceId: string;+ driverKind: string;+ models?: ModelCatalog;+ adapter: { capabilities: { contextReading?: "meter"; nativeCompaction?: boolean } };+}++export interface CompactConversationInput {+ bot: BotRecord; threadId: string; generation: string; instance: CompactionInstance; model: string;+ excludedIds: ReadonlySet<string>; manual: boolean; idle?: AbortSignal;+}++export interface ConversationCompactionDeps {+ store: Pick<Store, "taskByThread" | "activePath" | "patchTask" | "appendMessage">;+ context(): { autoCompact?: boolean; compactAt?: number } | undefined;+ directContext(bot: BotRecord, threadId: string, messages: Message[]): ContextMessage[];+ latestCompaction(messages: readonly Message[]): ({ id: string; firstKeptId?: string } & Record<string, unknown>) | undefined;+ /** Where the engine compacts by itself, in tokens, when OpenMausBot set that point. */+ nativeCompactTokens(instance: CompactionInstance): number | undefined;+ /** False for an engine whose own compaction is switched off in its environment. */+ engineCompactionOn(instance: CompactionInstance): boolean;+ /** The engine's own compaction of this conversation's session, asked for by the person; false when it has none to offer now. */+ engineCompact(target: { botId: string; threadId: string; instanceId: string }, signal: AbortSignal): Promise<boolean>;+ generateText(botId: string, instance: CompactionInstance): ((prompt: string, options?: { signal?: AbortSignal }) => Promise<string>) | undefined;+ claimIsCurrent(botId: string, generation: string, threadId: string): boolean;+ controllers: Map<string, { generation: string; controller: AbortController }>;+ cancelled(reason: string): Error;+ idleFraction: number;+}++export function createConversationCompaction(deps: ConversationCompactionDeps) {+ const { store } = deps;+ return async function compactConversation(input: CompactConversationInput): Promise<void> {+ const { bot, threadId, generation, instance, model, excludedIds, manual, idle } = input;+ const task = store.taskByThread(bot.id, threadId);+ const settings = deps.context();+ if (!task || (!manual && settings?.autoCompact === false)) return;+ const messages = sinceFreshStart(store.activePath(threadId));+ const context = deps.directContext(bot, threadId, messages);+ const record = deps.latestCompaction(messages) as ({ id: string; firstKeptId?: string; summary: string; foldedThroughId?: string } | undefined);+ // A retry must apply the existing record before considering another fold.+ if (!manual && record && record.id !== task.appliedCompactionId) return;+ if (manual && record?.id === messages.at(-1)?.id && !record?.firstKeptId) return;+ if (manual && messages.at(-1)?.kind === "compaction" && messages.at(-1)?.engineCompaction) return;+ const selected = selectReplay(context, {+ budgetBytes: Math.max(1_024, context.reduce((n, entry) => n + Buffer.byteLength(entry.text) + 16, 0) + 4 * MAX_SUMMARY_BYTES + 1_024),+ maxMessages: Number.MAX_SAFE_INTEGER, excludedIds, compaction: record as never,+ });+ const history = selected.transcript.filter(entry => entry.id);+ if (!history.length) return;+ const measurement = compactionReading(instance.adapter.capabilities, task.lastContextModel === `${instance.instanceId}:${model}` && !task.rewound ? task.usage?.context : undefined);+ const window = contextWindowFor(model, instance.models, measurement?.window);+ const bytes = history.reduce((n, entry) => n + Buffer.byteLength(entry.text), 0);+ let floor = task.contextFloor;+ if (record && record.id === task.appliedCompactionId && floor === undefined && measurement?.tokens) {+ floor = measurement.tokens;+ store.patchTask(bot.id, threadId, { contextFloor: floor });+ }+ const engineCompacts = instance.adapter.capabilities.nativeCompaction === true && deps.engineCompactionOn(instance);+ if (!manual && !foldDue({ engineCompacts, configuredCompactAt: settings?.compactAt, contextTokens: measurement?.tokens, estimatedBytes: bytes,+ window, nativeCompactAt: deps.nativeCompactTokens(instance), floor, idleFraction: idle ? deps.idleFraction : 1 })) return;+ const fold = manual ? { folded: history, firstKeptId: "" } : foldPoint(history);+ if (!fold) return;+ const foldedThroughId = manual+ ? context.findLast(entry => !excludedIds.has(entry.id))?.id+ : fold.folded.at(-1)?.id;+ if (!foldedThroughId) return;+ const prefix = JSON.stringify(messages);+ const controller = new AbortController();+ idle?.addEventListener("abort", () => controller.abort(), { once: true });+ if (idle?.aborted) controller.abort();+ deps.controllers.set(threadId, { generation, controller });+ try {+ if (manual && engineCompacts && await deps.engineCompact({ botId: bot.id, threadId, instanceId: instance.instanceId }, controller.signal)) return;+ controller.signal.throwIfAborted();+ const summary = await draftSummary(fold.folded, { signal: controller.signal, generateText: deps.generateText(bot.id, instance) });+ if (!idle && !deps.claimIsCurrent(bot.id, generation, threadId)) throw deps.cancelled("context summarization stopped");+ controller.signal.throwIfAborted();+ if (prefix !== JSON.stringify(sinceFreshStart(store.activePath(threadId)).slice(0, messages.length))) {+ if (manual) throw new Error("the conversation changed during summarization — please retry");+ return;+ }+ store.appendMessage(threadId, {+ role: "bot", kind: "compaction",+ compaction: { summary, firstKeptId: fold.firstKeptId, foldedThroughId,+ tokensBefore: measurement?.tokens ?? Math.ceil(bytes / 4), by: manual ? "person" : "harness" },+ }, { kind: "compaction.append", key: `${threadId}:${messages.at(-1)?.id}:${fold.firstKeptId}` });+ } finally {+ if (deps.controllers.get(threadId)?.generation === generation) deps.controllers.delete(threadId);+ }+ };+}diff --git a/server/host/warm-summary-host.test.ts b/server/host/warm-summary-host.test.tsindex c4ab7d1ec8..007d717f4c 100644--- a/server/host/warm-summary-host.test.ts+++ b/server/host/warm-summary-host.test.ts@@ -4,9 +4,9 @@ import type { IdleCompactResult } from "../contracts.ts";import type { HandedState } from "../delta-context.ts";import type { Message } from "../store.ts";import { createJobSlots } from "../job-slots.ts";-import { WARM_SUMMARY_GIVE_UP_MS, WARM_SUMMARY_IDLE_MS, WARM_SUMMARY_RETRY_MS, WARM_SUMMARY_SOON_MS } from "../warm-summary.ts";+import { WARM_SUMMARY_GIVE_UP_MS, WARM_SUMMARY_IDLE_MS, WARM_SUMMARY_NOW_MS, WARM_SUMMARY_RETRY_MS, WARM_SUMMARY_SOON_MS } from "../warm-summary.ts";import { addServerLinePacks } from "../server-lines.ts";-import { createWarmSummaryHost, keptAfterSummary, PRESENCE_HOLD_MS, summaryInstructions, type WarmSummaryHostDeps } from "./warm-summary-host.ts";+import { COMPACTION_STARTED_LINE, createWarmSummaryHost, keptAfterSummary, PRESENCE_HOLD_MS, summaryInstructions, type WarmSummaryHostDeps } from "./warm-summary-host.ts";let at = 0;const line = (role: "user" | "bot", text: string, extra: Partial<Message> = {}): Message =>@@ -225,17 +225,77 @@ describe("warm summaries for a Claude conversation", () => {expect(f.appended).toEqual([]);});- it("does nothing below 100k tokens, and starts at once from 80% of the engine's own compaction point", async () => {+ it("does nothing below 100k tokens, and starts at once close to the engine's own compaction point", async () => {const small = setup({}, { tokens: 60_000 });small.finishTurn();await small.advance(WARM_SUMMARY_IDLE_MS * 3);expect(small.compactCalls).toEqual([]);const near = setup({}, { tokens: 165_000 });near.finishTurn();- await near.advance(WARM_SUMMARY_SOON_MS);+ await near.advance(WARM_SUMMARY_NOW_MS);expect(near.compactCalls).toHaveLength(1);});+ it("places both points below where the engine compacts at a lower setting too", async () => {+ const low = setup({ nativeCompactAt: () => 100_000 }, { tokens: 60_500 });+ low.finishTurn();+ await low.advance(WARM_SUMMARY_NOW_MS);+ expect(low.compactCalls).toHaveLength(1);+ const lower = setup({ nativeCompactAt: () => 100_000 }, { tokens: 52_000 });+ lower.finishTurn();+ await lower.advance(WARM_SUMMARY_NOW_MS);+ expect(lower.compactCalls).toEqual([]);+ await lower.advance(WARM_SUMMARY_SOON_MS);+ expect(lower.compactCalls).toHaveLength(1);+ });++ it("writes the summary ahead from 27k below the engine's own point, after the pause of a quick reply, and minutes later below that", async () => {+ const below = setup({}, { tokens: 139_000 });+ below.finishTurn();+ await below.advance(WARM_SUMMARY_IDLE_MS - 1);+ expect(below.compactCalls).toEqual([]);+ await below.advance(1);+ expect(below.compactCalls).toHaveLength(1);+ const ahead = setup({}, { tokens: 141_465 });+ ahead.finishTurn();+ await ahead.advance(WARM_SUMMARY_SOON_MS - 1);+ expect(ahead.compactCalls).toEqual([]);+ await ahead.advance(1);+ expect(ahead.compactCalls).toHaveLength(1);+ });++ it("shows the engine's own compaction line to a person whose turn waits for the summary, then the summary's line", async () => {+ let finish = (_result: IdleCompactResult): void => undefined;+ const compact = vi.fn(() => new Promise<IdleCompactResult>((resolve) => { finish = resolve; }));+ const s = setup({ instance: () => ({ adapter: { cacheKeepWarm: { compact, hold: () => true } } }) }, { tokens: 165_000 });+ s.finishTurn();+ await s.advance(WARM_SUMMARY_NOW_MS);+ expect(compact).toHaveBeenCalledTimes(1);+ expect(s.appended).toEqual([]);+ const waiting = s.host.beforeTurn("t1");+ await s.advance(0);+ expect(s.appended.map((m) => m.tool?.name)).toEqual([COMPACTION_STARTED_LINE]);+ finish({ ok: true, session: "fork-session", sessionBefore: "live-session", input: 4, cacheRead: 160_000, cacheWrite: 40, output: 2_400, costUsd: 0.2, model: "claude-opus-5-5" });+ expect(await waiting).toBe("waited");+ expect(s.appended.map((m) => m.kind)).toEqual(["activity", "activity"]);+ expect(s.appended[1]!.tool?.name).toMatch(/summarized this conversation while it was idle/);+ expect(s.task.resumeCursors.claude).toBe("fork-session");+ });++ it("lets a waiting turn go on, on its own session, when the summary fails", async () => {+ let finish = (_result: IdleCompactResult): void => undefined;+ const compact = vi.fn(() => new Promise<IdleCompactResult>((resolve) => { finish = resolve; }));+ const s = setup({ instance: () => ({ adapter: { cacheKeepWarm: { compact, hold: () => true } } }) }, { tokens: 165_000 });+ s.finishTurn();+ await s.advance(WARM_SUMMARY_NOW_MS);+ const waiting = s.host.beforeTurn("t1");+ await s.advance(0);+ finish({ ok: false, reason: "the summary failed: API error" });+ expect(await waiting).toBe("waited");+ expect(s.task.resumeCursors.claude).toBe("live-session");+ expect(s.appended.map((m) => m.tool?.name)).toEqual([COMPACTION_STARTED_LINE]);+ });+it("never summarizes a room, or with automatic compaction off", async () => {const room = setup({}, { room: true });room.finishTurn();diff --git a/server/host/warm-summary-host.ts b/server/host/warm-summary-host.tsindex c3f7c07fc5..90103a85cd 100644--- a/server/host/warm-summary-host.ts+++ b/server/host/warm-summary-host.ts@@ -21,9 +21,16 @@ import type { Message, Store } from "../store.ts";import type { WaitRecord } from "../waits.ts";import { createWarmSummary, WARM_SUMMARY_MIN_TOKENS, WARM_SUMMARY_RETRY_MS, type WarmSummaryOutcome, type WarmSummaryPlan, type WarmSummaryTarget } from "../warm-summary.ts";-/** Claude Code summarizes at the start of a turn once its context passes about 0.81 of its window (162k of 200k measured- * on a Team trial): from 0.8 the next turn would summarize anyway, so the warm summary starts almost at once. */-export const NATIVE_SOON_FRACTION = 0.8;+/** Claude Code 2.1.321 summarizes about this far below its compaction window: near 167k with `--autocompact 200000`+ * (162k was measured on a Team trial), and before 74k with 100000. */+export const NATIVE_COMPACT_HEADROOM = 33_000;+/** Within this of that point the next turn would summarize anyway: 160k at the default. */+export const NATIVE_SOON_MARGIN = 7_000;+/** Within this of that point an ordinary turn of tool work can end past it (one whole-file read adds about 22k): 140k at+ * the default. */+export const NATIVE_AHEAD_MARGIN = 27_000;+/** The line Claude Code's own PreCompact hook puts in the chat; a turn waiting for a summary shows the same one. */+export const COMPACTION_STARTED_LINE = "context compaction started (auto)";/** Kept word for word after a summary: the person's last two messages and everything since. */export const KEPT_EXCHANGES = 2;/** OpenMausBot's fold runs while idle once a conversation is this close to where the next turn would fold it. */@@ -98,7 +105,7 @@ export function createWarmSummaryHost(deps: WarmSummaryHostDeps) {const { store } = deps;const now = deps.now ?? Date.now;- const native = async (target: WarmSummaryTarget, control: { signal: AbortSignal; awaited(): boolean }): Promise<WarmSummaryOutcome> => {+ const native = async (target: WarmSummaryTarget, control: { signal: AbortSignal; awaited(): boolean }, askedByPerson = false): Promise<WarmSummaryOutcome> => {const { threadId, botId, instanceId } = target;const compact = deps.instance(instanceId)?.adapter.cacheKeepWarm?.compact;const session = store.taskByThread(botId, threadId)?.resumeCursors[instanceId];@@ -113,8 +120,9 @@ export function createWarmSummaryHost(deps: WarmSummaryHostDeps) {const { state, exchanges } = keptAfterSummary(sinceFreshStart(store.activePath(threadId)), result.session, task.handedMessages?.[instanceId]);store.setResumeCursor(botId, instanceId, result.session, threadId);store.setHandedMessages(botId, threadId, instanceId, state);- store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: serverLine(deps.language?.(threadId), "server.warmSummary.summarized"), ok: true } });- deps.log?.(`warm summary ${threadId}: moved to its summarized session, keeping ${exchanges} exchange(s) word for word`);+ store.appendMessage(threadId, askedByPerson ? { role: "bot", kind: "compaction", engineCompaction: true }+ : { role: "bot", kind: "activity", tool: { name: serverLine(deps.language?.(threadId), "server.warmSummary.summarized"), ok: true } });+ deps.log?.(`${askedByPerson ? "compact now" : "warm summary"} ${threadId}: moved to its summarized session, keeping ${exchanges} exchange(s) word for word`);return { ok: true };};@@ -129,7 +137,8 @@ export function createWarmSummaryHost(deps: WarmSummaryHostDeps) {if (!instance.adapter.cacheKeepWarm?.compact) return { way: "harness", soon: false };const at = deps.nativeCompactAt(target.instanceId);if (at === undefined || contextTokens === undefined || contextTokens < Math.min(WARM_SUMMARY_MIN_TOKENS, at / 2)) return null;- return { way: "native", soon: contextTokens >= at * NATIVE_SOON_FRACTION };+ const point = at - NATIVE_COMPACT_HEADROOM;+ return { way: "native", soon: contextTokens >= point - NATIVE_SOON_MARGIN, ahead: contextTokens >= point - NATIVE_AHEAD_MARGIN };},hold: ({ botId, threadId }) => {if (deps.busy(botId, threadId)) return { reason: "the bot is busy", retry: true };@@ -158,11 +167,20 @@ export function createWarmSummaryHost(deps: WarmSummaryHostDeps) {return await deps.fold(target, control.signal) ? { ok: true } : { ok: false, reason: "the conversation does not need a summary yet" };}, { signal: control.signal, urgent: control.awaited, onWait: () => { waited = true; } });},+ waiting: ({ threadId }) => { store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: COMPACTION_STARTED_LINE, ok: true } }); },log: deps.log,});return {...warm,+ /** The person asked for a summary now: the engine's own compaction of the conversation's session, where the engine has+ * one to run outside a turn. False leaves the conversation as it was. */+ async compactNow(target: WarmSummaryTarget, signal: AbortSignal): Promise<boolean> {+ warm.forget(target.threadId);+ const outcome = await native(target, { signal, awaited: () => true }, true);+ if (!outcome.ok) deps.log?.(`compact now ${target.threadId}: not by the engine (${outcome.reason})`);+ return outcome.ok;+ },/** The person has the conversation in front of them (opened it, or is active in the app with it open). */sawThread(threadId: string): void {warm.seen(threadId);diff --git a/server/index.ts b/server/index.tsindex 15319c1048..5e24dada1d 100644--- a/server/index.ts+++ b/server/index.ts@@ -13,9 +13,9 @@ import { ToolResults, TOOL_RESULT_MAX_CHARS } from "./tool-results.ts";import { basename, join } from "node:path";import { authorizeExternalRuntime, externalRuntimeIsActive, type ExternalRuntimeGrant } from "./external-runtime.ts";import { z } from "zod";-import { selectReplay, replayToolCalls, DEFAULT_REBUILD_BYTES, MAX_SUMMARY_BYTES } from "./context-rebuild.ts";-import { draftSummary, foldPoint } from "./compaction-summary.ts";-import { compactBudget, compactionReading, contextWindowFor, shouldCompact } from "./context-budget.ts";+import { selectReplay, replayToolCalls, DEFAULT_REBUILD_BYTES } from "./context-rebuild.ts";+import { claudeCompactionDisabled, createConversationCompaction } from "./host/conversation-compaction.ts";+import { compactionReading } from "./context-budget.ts";import { autoCompactWindow } from "./drivers/claude.ts";import { RoomContextTracker, roomResetNote } from "./room-context.ts";import { createRoomTranscript, GROUP_CONTEXT_MESSAGES } from "./host/room-transcript.ts";@@ -6978,63 +6978,15 @@ function peerReplayText(m: Message, name: string, text: string): string {}const { lineLabels, personPrompt, routineRunNote } = createLineLabels({ sharedChat: (threadId) => sharedMembership() && !store.groupByThread(threadId) && audienceMember(teamHost.audienceOf(threadId)) === null, userName: userNameFor, teamRole: (key) => (teamOwners.people?.list() ?? []).find((one) => personKey({ id: "", email: one.email }) === key)?.role, routineName: (threadId) => { const run = routines?.runForThread(threadId); return routines?.listRoutines().find((one) => one.id === run?.routineId)?.name; } });-async function compactConversation(input: {- bot: BotRecord; threadId: string; generation: string;- instance: NonNullable<ReturnType<typeof registry.get>>; model: string;- excludedIds: ReadonlySet<string>; manual: boolean; idle?: AbortSignal;-}): Promise<void> {- const { bot, threadId, generation, instance, model, excludedIds, manual, idle } = input;- const task = store.taskByThread(bot.id, threadId);- if (!task || (!manual && cfg.context?.autoCompact === false)) return;- const messages = sinceFreshStart(store.activePath(threadId));- const context = directContext(bot, threadId, messages);- const record = latestCompaction(messages);- // A retry must apply the existing record before considering another fold.- if (!manual && record && record.id !== task.appliedCompactionId) return;- if (manual && record?.id === messages.at(-1)?.id && !record?.firstKeptId) return;- const selected = selectReplay(context, {- budgetBytes: Math.max(1_024, context.reduce((n, entry) => n + Buffer.byteLength(entry.text) + 16, 0) + 4 * MAX_SUMMARY_BYTES + 1_024),- maxMessages: Number.MAX_SAFE_INTEGER, excludedIds, compaction: record,- });- const history = selected.transcript.filter(entry => entry.id);- if (!history.length) return;- const measurement = compactionReading(instance.adapter.capabilities, task.lastContextModel === `${instance.instanceId}:${model}` && !task.rewound ? task.usage?.context : undefined);- const window = contextWindowFor(model, instance.models, measurement?.window);- const bytes = history.reduce((n, entry) => n + Buffer.byteLength(entry.text), 0);- let floor = task.contextFloor;- if (record && record.id === task.appliedCompactionId && floor === undefined && measurement?.tokens) {- floor = measurement.tokens;- store.patchTask(bot.id, threadId, { contextFloor: floor });- }- const nativeCompactAt = nativeCompactTokens(instance);- if (!manual && !shouldCompact({ contextTokens: measurement?.tokens, estimatedBytes: bytes,- budget: compactBudget(window, cfg.context?.compactAt, nativeCompactAt) * (idle ? HARNESS_IDLE_FRACTION : 1), floor, window, nativeCompactAt })) return;- const fold = manual ? { folded: history, firstKeptId: "" } : foldPoint(history);- if (!fold) return;- const foldedThroughId = manual- ? context.findLast(entry => !excludedIds.has(entry.id))?.id- : fold.folded.at(-1)?.id;- if (!foldedThroughId) return;- const prefix = JSON.stringify(messages);- const controller = new AbortController(); idle?.addEventListener("abort", () => controller.abort(), { once: true }); if (idle?.aborted) controller.abort();- compactionControllers.set(threadId, { generation, controller });- try {- const summary = await draftSummary(fold.folded, { signal: controller.signal, generateText: sideJobs.text("compaction", bot.id, { instance })?.generateText });- if (!idle && !directTurnClaimIsCurrent(bot.id, generation, threadId)) throw new DirectTurnSetupCancelled("context summarization stopped");- controller.signal.throwIfAborted();- if (prefix !== JSON.stringify(sinceFreshStart(store.activePath(threadId)).slice(0, messages.length))) {- if (manual) throw new Error("the conversation changed during summarization — please retry");- return;- }- store.appendMessage(threadId, {- role: "bot", kind: "compaction",- compaction: { summary, firstKeptId: fold.firstKeptId, foldedThroughId,- tokensBefore: measurement?.tokens ?? Math.ceil(bytes / 4), by: manual ? "person" : "harness" },- }, { kind: "compaction.append", key: `${threadId}:${messages.at(-1)?.id}:${fold.firstKeptId}` });- } finally {- if (compactionControllers.get(threadId)?.generation === generation) compactionControllers.delete(threadId);- }-}+const compactConversation = createConversationCompaction({+ store, context: () => cfg.context, directContext, latestCompaction,+ nativeCompactTokens: (instance) => nativeCompactTokens(instance),+ engineCompactionOn: (instance) => instance.driverKind !== "claudeAgent" || !claudeCompactionDisabled({ ...process.env, ...cfg.instances?.[instance.instanceId]?.environment }),+ engineCompact: (target, signal) => warmSummaries.compactNow(target, signal),+ generateText: (botId, instance) => sideJobs.text("compaction", botId, { instance: instance as NonNullable<ReturnType<typeof registry.get>> })?.generateText,+ claimIsCurrent: (botId, generation, threadId) => directTurnClaimIsCurrent(botId, generation, threadId),+ controllers: compactionControllers, cancelled: (reason) => new DirectTurnSetupCancelled(reason), idleFraction: HARNESS_IDLE_FRACTION,+});const handoffs = new Handoffs({order: (threadId) => sinceFreshStart(store.activePath(threadId)).filter(isContextMessage).map((m) => m.id),diff --git a/server/testing/fake-codex-app-server.ts b/server/testing/fake-codex-app-server.tsindex 65d3b024a2..9220815ffe 100755--- a/server/testing/fake-codex-app-server.ts+++ b/server/testing/fake-codex-app-server.ts@@ -27,6 +27,7 @@// FAKE_STREAM_SCRIPT, FAKE_STREAM_CADENCE a scripted reply chosen by a marker in the prompt (as stream-script.ts)// FAKE_CODEX_PATCH_BYTES each turn first writes web/index.html by apply_patch, streamed as two// item/fileChange/patchUpdated notifications (codex-cli 0.160.1's schema) of half and all this many bytes+// FAKE_CODEX_COMPACTION "1": each turn first compacts its context, as codex-cli 0.160.1 reports it (a contextCompaction item)// FAKE_CODEX_IGNORE_FEATURES "1": config/read reports no `-c features.*` override// FAKE_CODEX_SHELL_ENVIRONMENT_POLICY JSON config/read reports, every field present and null unless set (codex-cli 0.160)// FAKE_CODEX_APPROVAL_REQUEST JSON {method, params} override in approval mode@@ -386,6 +387,10 @@ const dump = () => {};const finishTurn = () => {+ if (process.env.FAKE_CODEX_COMPACTION === "1") {+ notify("item/started", { item: { id: "c1", type: "contextCompaction" } });+ notify("item/completed", { item: { id: "c1", type: "contextCompaction" } });+ }const patchBytes = Number(process.env.FAKE_CODEX_PATCH_BYTES);if (patchBytes > 0) {const change = (bytes: number) => [{ path: `${process.cwd()}/web/index.html`, kind: { type: "add" }, diff: "+".repeat(bytes) }];diff --git a/server/warm-summary.e2e.test.ts b/server/warm-summary.e2e.test.tsindex b75338458c..38b7032202 100644--- a/server/warm-summary.e2e.test.ts+++ b/server/warm-summary.e2e.test.ts@@ -49,7 +49,7 @@ async function setup(extra: NodeJS.ProcessEnv) {const lastPrompt = () => readFileSync(prompts, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)).at(-1);const lastLaunch = () => JSON.parse(readFileSync(session.fixtureDumpPath, "utf8")).argv as string[];const compactDump = () => existsSync(env.FAKE_CLAUDE_COMPACT_DUMP) ? JSON.parse(readFileSync(env.FAKE_CLAUDE_COMPACT_DUMP, "utf8")) : null;- return { session, bot, thread, task, send, messages, lastPrompt, lastLaunch, compactDump,+ return { session, bot, thread, task, send, messages, lastPrompt, lastLaunch, compactDump, cli,close: async () => { try { await session.close(); } finally { await removeTempDir(scratch); } } };} catch (error) {await session.close();@@ -113,6 +113,45 @@ it("a message sent while the summary it needs is being written waits for it rathexpect(launch[launch.indexOf("--resume") + 1]).toBe(f.task().resumeCursors.claude);expect(f.compactDump()).not.toBeNull();expect(words(f.lastPrompt())).toContain("MSG-3 and the subtitle");+ // The person saw why: Claude Code's own compaction line, once, then the summary's.+ const lines = (await f.messages()).filter((m) => m.kind === "activity").map((m) => String(m.tool?.name));+ expect(lines.filter((name) => name === "context compaction started (auto)")).toHaveLength(1);+ expect(lines.findIndex((name) => /while it was idle/.test(name))).toBeGreaterThan(lines.indexOf("context compaction started (auto)"));+}), 120_000);++// Claude Code's own compaction is out of reach in the next two (FAKE_CLAUDE_AUTOCOMPACT_AT), so the only compaction line is the wait's.+it("a summary that fails while a turn waits for it lets the turn run on its own session", () => fixture({+ FAKE_CLAUDE_AUTOCOMPACT_AT: "900000",+ FAKE_CLAUDE_COMPACT_RESULT: JSON.stringify({ type: "result", subtype: "error_during_execution", is_error: true, result: "API Error: 529 overloaded" }),+}, async (f) => {+ for (const text of ["MSG-1 build the landing page", "MSG-2 make the title bold", "MSG-3 and the subtitle"]) await f.send(text);+ const session = f.task().resumeCursors.claude;+ await sleep(1_000);+ const waited = await f.send("MSG-4 what changed?");+ record({ case: "sent during a summary that failed", nextReplyMs: waited });+ expect(waited).toBeLessThan(COMPACT_MS + 3_000);+ expect(f.task().resumeCursors.claude).toBe(session);+ expect(words(f.lastPrompt())).toContain("MSG-4 what changed?");+ const all = await f.messages();+ expect(all.filter((m) => m.kind === "activity" && m.tool?.name === "context compaction started (auto)")).toHaveLength(1);+ expect(all.some((m) => m.kind === "activity" && /while it was idle/.test(m.tool?.name ?? ""))).toBe(false);+ expect(all.findLast((m) => m.role === "bot" && m.kind === "text")?.at).toBeGreaterThan(all.findLast((m) => m.role === "user")!.at);+}), 120_000);++it("Stop ends a turn that waits for a summary, and the next message is answered", () => fixture({ FAKE_CLAUDE_AUTOCOMPACT_AT: "900000" }, async (f) => {+ for (const text of ["MSG-1 build the landing page", "MSG-2 make the title bold", "MSG-3 and the subtitle"]) await f.send(text);+ await sleep(1_000);+ await f.cli("send", "--bot", f.bot.id, "--task", f.thread, "--text", "MSG-4 what changed?");+ await sleep(1_000);+ const stopped = performance.now();+ await f.cli("interrupt", "--bot", f.bot.id, "--task", f.thread);+ expect((await f.cli("wait", "--bot", f.bot.id, "--task", f.thread, "--timeout", "30")).status).toBe("settled");+ // Well before the summary (about 6 s) would have finished.+ expect(performance.now() - stopped).toBeLessThan(COMPACT_MS - 2_500);+ expect(words(f.lastPrompt())).not.toContain("MSG-4 what changed?");+ const next = await f.send("MSG-5 carry on");+ expect(next).toBeLessThan(COMPACT_MS + 3_000);+ expect(words(f.lastPrompt())).toContain("MSG-5 carry on");}), 120_000);it("a message sent during a summary the turn did not need is never held up by it", () => fixture({ FAKE_CLAUDE_CONTEXT_GROWTH: "100000:10000" }, async (f) => {diff --git a/server/warm-summary.test.ts b/server/warm-summary.test.tsindex 3c72915bb8..ca42a0d006 100644--- a/server/warm-summary.test.ts+++ b/server/warm-summary.test.ts@@ -4,6 +4,7 @@ import {createWarmSummary,WARM_SUMMARY_GIVE_UP_MS,WARM_SUMMARY_IDLE_MS,+ WARM_SUMMARY_NOW_MS,WARM_SUMMARY_RETRY_MS,WARM_SUMMARY_SOON_MS,type WarmSummaryDeps,@@ -69,11 +70,68 @@ describe("warm summary scheduling", () => {expect(warm.state("t1")).toMatchObject({ running: false, last: { outcome: "summarized" } });});- it("starts almost at once when the next turn would summarize anyway", async () => {- const { time, warm, runs } = setup({}, { way: "native", soon: true });+ it("starts as soon as the turn has settled when the next turn would summarize anyway", async () => {+ const { time, warm, runs } = setup({}, { way: "native", soon: true, ahead: true });warm.turnCompleted(target, { ok: true, contextTokens: 170_000 });+ await time.advance(WARM_SUMMARY_NOW_MS - 1);+ expect(runs).toHaveLength(0);+ await time.advance(1);+ expect(runs).toHaveLength(1);+ });++ it("starts after the pause of a quick reply when an ordinary turn could reach the engine's own point", async () => {+ const { time, warm, runs } = setup({}, { way: "native", soon: false, ahead: true });+ warm.turnCompleted(target, { ok: true, contextTokens: 145_000 });+ await time.advance(WARM_SUMMARY_SOON_MS - 1);+ expect(runs).toHaveLength(0);+ await time.advance(1);+ expect(runs).toHaveLength(1);+ });++ it("never holds a turn up for a summary written ahead, and says nothing in the chat about it", async () => {+ const waited: string[] = [];+ const { time, warm, runs } = setup({ waiting: (t) => { waited.push(t.threadId); } }, { way: "native", soon: false, ahead: true });+ warm.turnCompleted(target, { ok: true, contextTokens: 145_000 });+ await time.advance(WARM_SUMMARY_SOON_MS);+ expect(await warm.beforeTurn("t1")).toBe("abandoned");+ expect(runs[0]!.signal.aborted).toBe(true);+ expect(waited).toEqual([]);+ });++ it("writes ahead only once for a person who answers faster than the summary takes, then waits for the idle time", async () => {+ const { time, warm, runs } = setup({}, { way: "native", soon: false, ahead: true });+ warm.turnCompleted(target, { ok: true, contextTokens: 145_000 });await time.advance(WARM_SUMMARY_SOON_MS);expect(runs).toHaveLength(1);+ expect(await warm.beforeTurn("t1")).toBe("abandoned");+ runs[0]!.finish({ ok: false, reason: "a turn started while summarizing" });+ warm.turnStarted("t1");+ await time.advance(0);+ warm.turnCompleted(target, { ok: true, contextTokens: 150_000 });+ await time.advance(WARM_SUMMARY_IDLE_MS - 1);+ expect(runs).toHaveLength(1);+ await time.advance(1);+ expect(runs).toHaveLength(2);+ runs[1]!.finish({ ok: true });+ await time.advance(0);+ // Summarized once: the next approach is written ahead again.+ warm.turnCompleted(target, { ok: true, contextTokens: 145_000 });+ await time.advance(WARM_SUMMARY_SOON_MS);+ expect(runs).toHaveLength(3);+ });++ it("tells the host once when a turn begins waiting, and lets the turn go on when the summary fails", async () => {+ const waited: string[] = [];+ const { time, warm, runs } = setup({ waiting: (t) => { waited.push(t.threadId); } }, { way: "native", soon: true, ahead: true });+ warm.turnCompleted(target, { ok: true, contextTokens: 170_000 });+ await time.advance(WARM_SUMMARY_NOW_MS);+ const waiting = warm.beforeTurn("t1");+ await time.advance(0);+ expect(waited).toEqual(["t1"]);+ runs[0]!.finish({ ok: false, reason: "the summary failed: API error" });+ expect(await waiting).toBe("waited");+ expect(warm.state("t1")).toMatchObject({ running: false, last: { outcome: "failed: the summary failed: API error" } });+ expect(await warm.beforeTurn("t1")).toBe("none");});it("arms nothing for a conversation that does not qualify, or a turn that failed", async () => {diff --git a/server/warm-summary.ts b/server/warm-summary.tsindex 356939a688..b7bad618f2 100644--- a/server/warm-summary.ts+++ b/server/warm-summary.ts@@ -16,8 +16,10 @@export const WARM_SUMMARY_MIN_TOKENS = 100_000;/** Idle this long after a turn: long enough that a quick reply is not raced, well inside a 5-minute API-key cache. */export const WARM_SUMMARY_IDLE_MS = 3 * 60_000;-/** When the next turn would summarize at its start anyway: start almost at once. */+/** When the next turn may summarize part-way through: start almost at once, after the pause of a quick reply. */export const WARM_SUMMARY_SOON_MS = 10_000;+/** When the next turn would summarize at its start anyway: start as soon as the turn before has settled. */+export const WARM_SUMMARY_NOW_MS = 1_000;/** A busy bot, or a routine about to run: look again this much later. */export const WARM_SUMMARY_RETRY_MS = 2 * 60_000;/** A subscription's prompt cache lives an hour from the last request: after this the summary would write it all again. */@@ -32,10 +34,13 @@ export interface WarmSummaryTarget {}/** `native`: the engine's own compaction (Claude Code's /compact on a fork); `harness`: OpenMausBot's fold, for engines- * whose context it rebuilds. `soon`: the next turn would summarize at its start anyway. */+ * whose context it rebuilds. `soon`: the next turn would summarize at its start anyway, so the summary starts at once and a+ * turn that begins meanwhile waits for it. `ahead`: an ordinary turn could reach that point, so the summary starts after+ * the pause of a quick reply, and a turn that begins meanwhile is not held up by it. */export interface WarmSummaryPlan {way: "native" | "harness";soon: boolean;+ ahead?: boolean;}export type WarmSummaryOutcome = { ok: true } | { ok: false; reason: string; retry?: boolean };@@ -53,6 +58,8 @@ export interface WarmSummaryDeps {/** Writes and applies the summary. `awaited()`: a turn is waiting for it, so the turn's own setup is no reason to drop it.* `stale()`: why it is no longer worth writing now (the cache went cold, or a hold), for a run that had to wait. */run(target: WarmSummaryTarget, plan: WarmSummaryPlan, control: { signal: AbortSignal; awaited(): boolean; stale(): { reason: string; retry: boolean } | null }): Promise<WarmSummaryOutcome>;+ /** A turn began waiting for the summary being written. */+ waiting?(target: WarmSummaryTarget): void;log?(line: string): void;}@@ -80,10 +87,18 @@ export interface WarmSummaryState {export function createWarmSummary(deps: WarmSummaryDeps) {const scale = deps.timeScale && deps.timeScale > 0 && deps.timeScale <= 1 ? deps.timeScale : 1;- const [idleMs, soonMs, retryMs, giveUpMs] = [WARM_SUMMARY_IDLE_MS, WARM_SUMMARY_SOON_MS, WARM_SUMMARY_RETRY_MS, WARM_SUMMARY_GIVE_UP_MS]+ const [idleMs, soonMs, nowMs, retryMs, giveUpMs] = [WARM_SUMMARY_IDLE_MS, WARM_SUMMARY_SOON_MS, WARM_SUMMARY_NOW_MS, WARM_SUMMARY_RETRY_MS, WARM_SUMMARY_GIVE_UP_MS].map((ms) => Math.max(1, Math.round(ms * scale)));const pending = new Map<string, Pending>();const last = new Map<string, { at: number; outcome: string }>();+ /** Conversations whose summary written ahead was dropped for a turn: their person answers within the minute it takes,+ * so the next one waits for the idle time rather than spend a second summary call the same way. */+ const overtaken = new Set<string>();+ const overtake = (p: Pending) => {+ if (!p.plan.ahead || p.plan.soon) return;+ overtaken.add(p.target.threadId);+ if (overtaken.size > 500) overtaken.delete(overtaken.values().next().value!);+ };let disposed = false;const note = (threadId: string, outcome: string) => {@@ -132,7 +147,7 @@ export function createWarmSummary(deps: WarmSummaryDeps) {}if (p.run === run) p.run = null;if (pending.get(p.target.threadId) !== p) return;- if (outcome.ok) return drop(p, "summarized");+ if (outcome.ok) { overtaken.delete(p.target.threadId); return drop(p, "summarized"); }if (outcome.retry && !controller.signal.aborted && deps.now() + retryMs - p.turnEndedAt < giveUpMs) {note(p.target.threadId, `waiting: ${outcome.reason}`);return schedule(p, retryMs);@@ -151,10 +166,11 @@ export function createWarmSummary(deps: WarmSummaryDeps) {if (existing) drop(existing);if (!turn.ok) return;const plan = deps.plan(target, turn.contextTokens);+ if (!plan?.ahead) overtaken.delete(target.threadId);if (!plan) return;const p: Pending = { target, plan, turnEndedAt: deps.now(), dueAt: null, timer: null, run: null };pending.set(target.threadId, p);- schedule(p, plan.soon ? soonMs : idleMs);+ schedule(p, plan.soon ? nowMs : plan.ahead && !overtaken.has(target.threadId) ? soonMs : idleMs);},/** A turn began on this conversation: what the summary would cover is no longer the whole of it. */@@ -163,6 +179,7 @@ export function createWarmSummary(deps: WarmSummaryDeps) {if (!p) return;if (p.run && !p.run.awaited) {deps.log?.(`warm summary ${threadId}: a turn started while it was being written`);+ overtake(p);p.run.controller.abort();}if (!p.run) drop(p);@@ -180,11 +197,13 @@ export function createWarmSummary(deps: WarmSummaryDeps) {const run = p.run;if (!p.plan.soon) {deps.log?.(`warm summary ${threadId}: a turn that does not need it starts now`);+ overtake(p);run.controller.abort();return "abandoned";}deps.log?.(`warm summary ${threadId}: a turn waits for it`);run.awaited = true;+ deps.waiting?.(p.target);const deadline = deps.now() + WARM_SUMMARY_TURN_WAIT_MS;let settled = false;void run.done.then(() => { settled = true; });@@ -205,6 +224,7 @@ export function createWarmSummary(deps: WarmSummaryDeps) {},forget(threadId: string): void {+ overtaken.delete(threadId);const p = pending.get(threadId);if (!p) return;p.run?.controller.abort();diff --git a/src/locales/server-lines.test.ts b/src/locales/server-lines.test.tsindex 11797f351a..30e45aadb4 100644--- a/src/locales/server-lines.test.ts+++ b/src/locales/server-lines.test.ts@@ -503,6 +503,7 @@ const PENDING: Readonly<Record<string, ReadonlyArray<readonly [file: string, sni],"restarts, stops and context": [["server/index.ts", "context compaction started ( … )"],+ ["server/host/warm-summary-host.ts", "context compaction started (auto)"],["server/index.ts", "context compacted — re-sent the last … digest …"],["server/index.ts", "generated image could not be attached — …"],["server/index.ts", "invalid image"],