Skip to content

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

Chat engine: a conversation's requests only grow at the end, so local models reuse their prompt cache

aivsomkar05f3a389a77c
diff --git a/docs/verification/openai-tools.md b/docs/verification/openai-tools.md
index 2c40883054..2fdbd014a1 100644
--- a/docs/verification/openai-tools.md
+++ b/docs/verification/openai-tools.md
@@ -196,6 +196,48 @@ Each refusal's full error object, `failed_generation` included, is written to
the thread's redacted native log (`native/THREAD.ndjson` in the data
directory), next to the tool names every request offered.
+## A conversation's requests only grow at the end
+
+A provider reuses only the unchanged start of a request: OpenAI, OpenRouter
+and DeepSeek bill it as cached input, and llama.cpp skips reading it again. A
+hybrid model (Qwen3.5 and 3.6, Granite 4) reuses nothing once anything before
+the end has changed, so a change near the start costs a full re-read, minutes
+for a 40k-token prompt on a local GPU. So within a conversation each request
+is the previous one with new messages added at the end:
+
+- Earlier turns go again exactly as sent: the user message with its context
+ note and automatic recall, every tool call and result, the final reply.
+ Screenshots of earlier turns become a one-line note.
+- The history is not trimmed to a fixed size each turn. Compaction folds it
+ when it nears the model's window; past the replay bound, old messages go
+ in batches of half the bound, so the start holds still between batches.
+- A local server's refusal of an oversized request reports its real window
+ (llama.cpp's `n_ctx`), which compaction then times its folds by.
+- The tool list holds still. Most templates (Qwen3.6 among them) render it
+ first, so a change there costs the whole prompt. A model on this computer or
+ network waits for every MCP server before a turn's first request. On a
+ hosted model a server still starting joins that turn once, and the bot's
+ later turns wait for it.
+- A model on this computer or network is asked to keep earlier turns'
+ thinking in the prompt (`chat_template_kwargs.preserve_thinking`), which
+ Qwen3.6's template otherwise drops at every new message.
+
+The start changes only when the conversation itself changes: an edit or
+rewind, a compaction, another model, new bot instructions, an app restart.
+
+Every request's native log line says how much of the previous request it
+repeats, as `repeats: { messages, of, tools }`. Start the app with
+`OPENMAUS_LOG_CHAT_REQUESTS=1` to log each request's full messages and tools
+too (secrets redacted, images left out), to see where two requests differ.
+
+```sh
+pnpm exec vitest run server/openai-prefix.e2e.test.ts server/drivers/openai-chat-prefix.test.ts
+```
+
+The end-to-end test sends eight tool-using turns to a fake provider through
+the isolated harness, past the old 24 KB history bound, and checks that each
+request starts with all of the one before.
+
Cloud routine readiness uses the executing bot’s selected runner (including a
thread’s model override at dispatch), rather than any available cloud engine.
The probe checks the bot-owned or inherited team Boat without provisioning or
diff --git a/server/context-budget.ts b/server/context-budget.ts
index 9dd63bd3f3..28425a43d9 100644
--- a/server/context-budget.ts
+++ b/server/context-budget.ts
@@ -1,4 +1,5 @@
import type { ModelCatalog } from "./contracts.ts";
+import type { TaskRecord } from "./store.ts";
import { modelContextWindow } from "./model-context-window.ts";
export const DEFAULT_CONTEXT_WINDOW = 128_000;
@@ -17,6 +18,11 @@ export function compactionReading<T>(capabilities: { contextReading?: "meter" }
return capabilities?.contextReading === "meter" ? undefined : reading;
}
+/** The context a thread's last turn on this engine and model reported, the reading compaction times its folds by. */
+export function lastContextReading(instance: { instanceId: string; adapter: { capabilities: { contextReading?: "meter" } } }, model: string | undefined, task: Pick<TaskRecord, "lastContextModel" | "rewound" | "usage">) {
+ return compactionReading(instance.adapter.capabilities, task.lastContextModel === `${instance.instanceId}:${model}` && !task.rewound ? task.usage?.context : undefined);
+}
+
/** Leave headroom even for a small local model: an 8k floor would make compaction unreachable on an 8k window. */
export function compactBudget(window: number, compactAt?: number, nativeCompactAt?: number): number {
if (!positive(window)) throw new Error("invalid model context window");
diff --git a/server/context-rebuild.test.ts b/server/context-rebuild.test.ts
index 8351fa8477..1546ab831f 100644
--- a/server/context-rebuild.test.ts
+++ b/server/context-rebuild.test.ts
@@ -94,6 +94,26 @@ describe("context replay", () => {
}
});
+ it.each([
+ { budgetBytes: 4_096, maxMessages: 1_000, stable: true },
+ { budgetBytes: 1_000_000, maxMessages: 40, stable: true },
+ ])("drops old messages in batches, so a growing conversation replays the same start between drops (%j)", (bounds) => {
+ const history: ReplayEntry[] = [];
+ const replays: string[][] = [];
+ for (let turn = 0; turn < 120; turn++) {
+ history.push({ id: `q${turn}`, role: "user", text: `question ${turn} ${"words ".repeat(turn % 7 * 9)}` });
+ history.push({ id: `a${turn}`, role: "assistant", text: `answer ${turn} ${"words ".repeat(turn % 5 * 11)}` });
+ const result = selectReplay(history, bounds);
+ expect(size(result)).toBeLessThanOrEqual(bounds.budgetBytes);
+ expect(result.transcript.filter((entry) => entry.id).length).toBeLessThanOrEqual(bounds.maxMessages);
+ expect(result.representedIds.at(-1)).toBe(`a${turn}`);
+ replays.push(result.transcript.map((entry) => entry.text));
+ }
+ const restarts = replays.slice(1).filter((next, index) => replays[index]!.some((text, at) => next[at] !== text)).length;
+ expect(restarts).toBeGreaterThan(0);
+ expect(restarts).toBeLessThanOrEqual(replays.length / 4);
+ });
+
it.each([NaN, Infinity, -1, 0, 512, 1_024.5])("rejects an invalid budget %s", (budgetBytes) => {
expect(() => selectReplay([], { budgetBytes })).toThrow("invalid context");
});
diff --git a/server/context-rebuild.ts b/server/context-rebuild.ts
index 81e304031f..6f44c464d9 100644
--- a/server/context-rebuild.ts
+++ b/server/context-rebuild.ts
@@ -177,12 +177,35 @@ export function boundedContextText(text: string, limit: number): string {
return head + notice + bytes.subarray(start).toString("utf8");
}
+/** Where the replay starts: the earliest of a fixed set of cut points, counted from the conversation's start, that leaves
+ * the rest within `bytes` and `messages`. Cut points sit half the bounds apart, so a growing conversation replays the same
+ * start until half its replay has to go at once, and a provider's prompt cache keeps matching in between. Undefined when
+ * the newest messages alone are too big for any cut point. */
+function stableCut(entries: readonly ReplayEntry[], bytes: number, messages: number): number | undefined {
+ if (bytes <= 16) return undefined;
+ const sizes = entries.map((entry) => Buffer.byteLength(entry.text) + 16);
+ const total = sizes.reduce((n, size) => n + size, 0);
+ const byteStep = bytes / 2;
+ let byteCut: number | undefined;
+ for (let index = 0, before = 0; index < entries.length; before += sizes[index]!, index++) {
+ const onGrid = index === 0 || Math.floor(before / byteStep) > Math.floor((before - sizes[index - 1]!) / byteStep);
+ if (onGrid && total - before <= bytes) { byteCut = index; break; }
+ }
+ if (byteCut === undefined) return undefined;
+ const messageStep = Math.max(1, Math.floor(messages / 2));
+ const messageCut = Math.ceil(Math.max(0, entries.length - messages) / messageStep) * messageStep;
+ return Math.max(byteCut, messageCut);
+}
+
export function selectReplay(
history: readonly ReplayEntry[],
options: {
budgetBytes?: number; maxMessages?: number; excludedIds?: ReadonlySet<string>; compaction?: CompactionRecord & { id: string };
/** Reach `inline` only. */
tools?: readonly ReplayToolCall[];
+ /** For an engine that sends the history with every request: drop old messages in batches (see stableCut), so the
+ * provider's prompt cache keeps matching, rather than filling the bounds anew each turn. */
+ stable?: boolean;
} = {},
): {
transcript: ReplayEntry[];
@@ -216,7 +239,13 @@ export function selectReplay(
}
const kept: ReplayEntry[] = [];
const shortened: string[] = [];
- for (let i = entries.length - 1; i >= 0 && kept.length < maxMessages; i--) {
+ const start = options.stable ? stableCut(entries, available, maxMessages) : undefined;
+ if (start !== undefined) {
+ kept.push(...entries.slice(start));
+ representedIds.push(...kept.map((entry) => entry.id));
+ available -= kept.reduce((n, entry) => n + Buffer.byteLength(entry.text) + 16, 0);
+ }
+ for (let i = entries.length - 1; start === undefined && i >= 0 && kept.length < maxMessages; i--) {
const entry = entries[i]!;
if (available <= 16) break;
const size = Buffer.byteLength(entry.text) + 16;
diff --git a/server/contracts.ts b/server/contracts.ts
index f9bf9d260c..866eec614c 100644
--- a/server/contracts.ts
+++ b/server/contracts.ts
@@ -128,7 +128,8 @@ export interface SendTurnInput {
/** Drivers namespace process-level resources (broker socket, CLI session) by botId too: threadIds may coincide across bots. */
botId?: string;
text: string;
- /** The recall block the harness put in front of `text`; it informs this turn only, so a replay can leave it out. */
+ /** The recall block the harness put in front of `text`, for this turn. A transcript engine replays it as sent, so each
+ * later request starts with this one and the provider's prompt cache keeps matching. */
recalled?: string;
/** Reasserted every turn so a resumed native session cannot keep a stale, more permissive mode. */
approvalMode?: ApprovalMode;
diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.ts
index 90d5390219..5e6716a37e 100644
--- a/server/drivers/chat-mcp-tools.test.ts
+++ b/server/drivers/chat-mcp-tools.test.ts
@@ -1591,6 +1591,17 @@ describe("Chat MCP servers starting in the background", () => {
expect(await session.join()).toBeUndefined();
});
+ it("waits for a slow server the conversation listed before, so the tool list holds still from the first request", async () => {
+ const agents = fixture();
+ const slow = fixture(slowStart(800));
+ const session = await mountChatTools({ agents: agents.server, custom: { slow: slow.server } }, agents.controller.signal, false, undefined, undefined, undefined, undefined,
+ undefined, undefined, { background: true, waitFor: new Set(["slow"]) });
+ sessions.push(session);
+ expect(names(session)).toEqual(["agents_write", "slow_write"]);
+ expect(session.listedServers().sort()).toEqual(["agents", "slow"]);
+ expect(await session.join()).toBeUndefined();
+ });
+
it("says when a server that was still starting is skipped", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const agents = fixture();
diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.ts
index a752018fbd..907381481b 100644
--- a/server/drivers/chat-mcp-tools.ts
+++ b/server/drivers/chat-mcp-tools.ts
@@ -60,6 +60,8 @@ export interface ChatToolSession {
/** With `background`: lists the tools of servers that finished starting since the last call. The lines say which were
* skipped and what the tool limit did; undefined when none finished. */
join(): Promise<string[] | undefined>;
+ /** The servers with a tool listed now. */
+ listedServers(): string[];
validate(name: string, args: unknown): void;
/** Directory reads and OpenMausBot's own agents server need no card; call_tool shows the tool it runs. */
view(name: string, args: Record<string, unknown>): ChatToolCallView;
@@ -109,6 +111,9 @@ export interface ChatToolMountOptions {
conversation?: string;
notice?: (line: { message: string; text: ServerText }) => void;
background?: boolean;
+ /** Started before the first request even with `background`: servers the conversation listed before, since a tool list
+ * that changes mid-conversation makes the model read the whole prompt again. */
+ waitFor?: ReadonlySet<string>;
onSettled?: (server: string) => void;
}
const DEFAULT_CALL_MS = 10 * 60_000;
@@ -798,7 +803,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
const waited = (index: number) => {
const [name, descriptor] = servers[index]!;
return (index < builtIns && (mustHave(descriptor) || !OPTIONAL_BUILT_INS.has(name) || descriptor === integrations?.localComputer || descriptor === integrations?.browser))
- || servers.filter(([other]) => other === name).length > 1;
+ || servers.filter(([other]) => other === name).length > 1 || options.waitFor?.has(name) === true;
};
const waitAll = !options.background || !servers.some(([, descriptor]) => descriptor === agentsServer);
await Promise.all(settled.filter((_, index) => waitAll || waited(index)));
@@ -921,6 +926,7 @@ export async function mountChatTools(integrations: SendTurnInput["integrations"]
};
return {
definitions, skipped, trimmed, merged, budget, validate, view, close,
+ listedServers: () => [...new Set([...registered.values()].map((tool) => tool.server))],
async refit(limit) {
if (closed || signal.aborted) throw new ChatToolSessionError("MCP session closed");
await layout(limit);
diff --git a/server/drivers/chat-size-limit.test.ts b/server/drivers/chat-size-limit.test.ts
index 6671ff9f72..c485eb77ac 100644
--- a/server/drivers/chat-size-limit.test.ts
+++ b/server/drivers/chat-size-limit.test.ts
@@ -100,6 +100,24 @@ describe("smallerResend", () => {
{ role: "user", content: [{ type: "text", text: `Screenshot result from tool call ${id}:` }, image(screenshot)] },
];
+ it("drops an earlier turn's tool call together with its results, never one without the other", () => {
+ const call = (id: string): OpenAIChatMessage[] => [
+ { role: "assistant", content: null, tool_calls: [{ id, type: "function", function: { name: "look_up", arguments: "{}" } }, { id: `${id}-b`, type: "function", function: { name: "look_up", arguments: "{}" } }] },
+ { role: "tool", tool_call_id: id, content: `result ${id} ${"r".repeat(3_000)}` },
+ { role: "tool", tool_call_id: `${id}-b`, content: `result ${id}-b ${"r".repeat(3_000)}` },
+ { role: "assistant", content: `answer ${id}` },
+ ];
+ const earlier: OpenAIChatMessage[] = ["one", "two", "three"].flatMap((id) => [{ role: "user", content: `question ${id}` }, ...call(id)]);
+ for (let share = 0.2; share < 1; share += 0.05) {
+ const { request, messages, refused } = turn(earlier);
+ const resend = smallerResend(messages, request, refused, share)!;
+ const calls = new Set(resend.messages.flatMap((message) => message.tool_calls?.map((entry) => entry.id) ?? []));
+ const results = resend.messages.filter((message) => message.role === "tool").map((message) => message.tool_call_id);
+ expect(results.filter((id) => !calls.has(id!)), `share ${share.toFixed(2)}`).toEqual([]);
+ expect([...calls].filter((id) => !results.includes(id)), `share ${share.toFixed(2)}`).toEqual([]);
+ }
+ });
+
it("strips this turn's older screenshots first and never touches the system prompt or the request's attachment", () => {
const { system, request, messages, refused } = turn(history(4, 500), [...toolRound("first", 100, 100_000), ...toolRound("second", 100, 20_000)]);
const resend = smallerResend(messages, request, refused)!;
diff --git a/server/drivers/chat-size-limit.ts b/server/drivers/chat-size-limit.ts
index 0087e32c8b..5db90ed0fc 100644
--- a/server/drivers/chat-size-limit.ts
+++ b/server/drivers/chat-size-limit.ts
@@ -27,21 +27,28 @@ export function refusesRequestSize(status: number, body: string): boolean {
return error?.code === "context_length_exceeded" || CONTEXT_REFUSALS.has(error?.type);
}
+/** The window a refused request was counted against: llama.cpp's n_ctx, its context per slot. */
+export function refusedWindow(body: string): number | undefined {
+ const window = bodyError(body)?.n_ctx;
+ return typeof window === "number" && Number.isSafeInteger(window) && window > 0 ? window : undefined;
+}
+
/** The share of a refused request that fits the window its provider counted (llama.cpp's n_ctx of n_prompt_tokens). */
export function shareThatFits(body: string): number | undefined {
- const error = bodyError(body);
- const window = error?.n_ctx, prompt = error?.n_prompt_tokens;
- if (typeof window !== "number" || typeof prompt !== "number" || window <= 0 || prompt < window) return undefined;
+ const window = refusedWindow(body), prompt = bodyError(body)?.n_prompt_tokens;
+ if (window === undefined || typeof prompt !== "number" || prompt < window) return undefined;
return window / prompt * WINDOW_FILLED_BY_RESEND;
}
export class RequestTooLargeError extends Error {
readonly bytes: number;
readonly fits: number | undefined;
- constructor(message: string, bytes: number, fits?: number) {
+ readonly window: number | undefined;
+ constructor(message: string, bytes: number, fits?: number, window?: number) {
super(message);
this.bytes = bytes;
this.fits = fits;
+ this.window = window;
}
}
@@ -118,13 +125,19 @@ export function smallerResend(
sizes[index] = size;
out[index] = next;
};
+ // A tool result goes with the call it answers: OpenAI and Groq refuse a request that has one without the other.
+ const dropWithResults = (index: number) => {
+ replace(index, null);
+ for (let next = index + 1; next < requestAt && messages[next]!.role === "tool"; next++) replace(next, null);
+ };
const shrinkable = messages.flatMap((message, index) => index === requestAt || message.role === "system" ? [] : [index]);
const latestCalls = messages.findLastIndex((message) => message.role === "assistant" && Boolean(message.tool_calls?.length));
const steps = [
...shrinkable.filter((index) => imagesIn(messages[index]!)).map((index) => () => replace(index, withoutImages(out[index]!))),
...shrinkable.filter((index) => index > requestAt && messages[index]!.role === "tool" && sizes[index]! > LONG_TOOL_OUTPUT_BYTES)
.map((index) => () => replace(index, shortenedToolOutput(out[index]!))),
- ...shrinkable.filter((index) => index < requestAt && omittedBefore(messages[index]!) === undefined).map((index) => () => replace(index, null)),
+ ...shrinkable.filter((index) => index < requestAt && messages[index]!.role !== "tool" && omittedBefore(messages[index]!) === undefined)
+ .map((index) => () => dropWithResults(index)),
...shrinkable.filter((index) => index > requestAt && index < latestCalls && messages[index]!.role === "tool"
&& sizes[index]! > bytesOf(omittedToolOutput(messages[index]!))).map((index) => () => replace(index, omittedToolOutput(out[index]!))),
];
diff --git a/server/drivers/openai-chat-prefix.test.ts b/server/drivers/openai-chat-prefix.test.ts
new file mode 100644
index 0000000000..016f0612d7
--- /dev/null
+++ b/server/drivers/openai-chat-prefix.test.ts
@@ -0,0 +1,204 @@
+// A conversation's requests must only ever grow at the end: llama.cpp and every provider's prompt cache reuse the longest
+// unchanged start, and a hybrid model (Qwen3.6, Granite 4) reuses nothing once anything before the end changes.
+import { randomUUID } from "node:crypto";
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { createServer, type ServerResponse } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import type { ProviderInstance, SendTurnInput } from "../contracts.ts";
+import { removeTempDir } from "../testing/cleanup.ts";
+import { recordEvents } from "../testing/events.ts";
+import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";
+import { OpenAICompatDriver } from "./openai-compat.ts";
+
+interface ChatRequest { messages: Array<{ role?: string }>; tools?: unknown[]; chat_template_kwargs?: unknown }
+type Transcript = NonNullable<SendTurnInput["transcript"]>;
+
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });
+
+function sse(response: ServerResponse, delta: unknown, finish: string) {
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`);
+ response.end("data: [DONE]\n\n");
+}
+
+const EMPTY = { type: "object", properties: {}, additionalProperties: false };
+
+async function mcp(name: string, toolsDelayMs = 0): Promise<FakeHttpMcp> {
+ const server = await startFakeHttpMcp({ tools: [{ name: "get", description: `Reads ${name}`, inputSchema: EMPTY }], toolsDelayMs });
+ cleanups.push(() => server.close());
+ return server;
+}
+
+const STDIO_MCP = `
+import { createInterface } from "node:readline";
+const reply = (id, result) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\\n");
+createInterface({ input: process.stdin }).on("line", (line) => {
+ const request = JSON.parse(line);
+ if (request.method === "initialize") reply(request.id, { protocolVersion: "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "agents", version: "1" } });
+ else if (request.method === "tools/list") reply(request.id, { tools: [{ name: "get", description: "Reads agents", inputSchema: ${JSON.stringify(EMPTY)} }] });
+ else if (request.method === "tools/call") reply(request.id, { content: [{ type: "text", text: "agents ok" }] });
+ else if (request.id !== undefined) reply(request.id, {});
+});
+`;
+
+/** OpenMausBot's own agents server runs as a local process. */
+function agentsServer() {
+ const directory = mkdtempSync(join(tmpdir(), "omb-prefix-"));
+ cleanups.push(() => removeTempDir(directory));
+ const script = join(directory, "agents.mjs");
+ writeFileSync(script, STDIO_MCP);
+ return { command: process.execPath, args: [script], env: {} };
+}
+
+/** Each turn calls `call` once, then answers; the reply is delayed so a server still starting has listed by round two. */
+async function conversation(call: string, roundDelayMs = 0) {
+ const requests: ChatRequest[] = [];
+ let answers = 0;
+ const server = createServer(async (request, response) => {
+ if (request.method !== "POST") {
+ response.setHeader("content-type", "application/json");
+ response.end('{"data":[]}');
+ return;
+ }
+ let data = "";
+ for await (const part of request) data += part.toString();
+ const body = JSON.parse(data) as ChatRequest;
+ requests.push({ messages: body.messages, tools: body.tools, chat_template_kwargs: body.chat_template_kwargs });
+ const reply = () => body.messages.at(-1)?.role === "tool"
+ ? sse(response, { content: `Answer ${++answers}` }, "stop")
+ : sse(response, { reasoning_content: "Looking it up first.", tool_calls: [{ index: 0, id: `call-${randomUUID()}`, type: "function", function: { name: call, arguments: "{}" } }] }, "tool_calls");
+ setTimeout(reply, body.messages.at(-1)?.role === "tool" ? 0 : roundDelayMs);
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("fixture did not bind TCP");
+ const instance: ProviderInstance = await OpenAICompatDriver.create({
+ instanceId: randomUUID(), displayName: "Prefix fixture", enabled: true,
+ config: { url: `http://127.0.0.1:${address.port}/v1`, apiKeyEnv: "FIXTURE_CHAT_KEY" },
+ environment: { FIXTURE_CHAT_KEY: "fixture-credential-5b0f3c" },
+ });
+ const recorder = recordEvents(instance.adapter);
+ cleanups.push(async () => {
+ recorder.stop();
+ await instance.dispose();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+ const threadId = randomUUID();
+ const transcript: Transcript = [];
+ return {
+ requests,
+ /** One turn as the app sends it: the stored conversation so far, the stable instructions and this turn's changing ones. */
+ async turn(text: string, integrations: SendTurnInput["integrations"], model = "fixture-model") {
+ const replies: string[] = [];
+ const done = recorder.events.length;
+ await instance.adapter.sendTurn({
+ threadId, botId: "prefix-bot", text, model, approvalMode: "full", integrations,
+ transcript: [...transcript], system: "Stable instructions\n\nNow: " + text, systemStable: "Stable instructions", systemVolatile: "Now: " + text,
+ });
+ const completed = await recorder.until((event) => event.type === "turn.completed" && recorder.events.indexOf(event) >= done);
+ expect(completed).toMatchObject({ ok: true });
+ for (const event of recorder.events.slice(done)) {
+ if (event.type === "item.completed" && event.itemType === "assistant_text") replies.push(event.text!);
+ }
+ // The app stores a summary of the turn's work after its replies.
+ transcript.push({ role: "user", text }, ...replies.map((reply) => ({ role: "assistant" as const, text: `${reply} ` })),
+ { role: "assistant", text: `[What the bot did in an earlier turn: tools ×1 · reply: ${replies.at(-1)}]` });
+ },
+ };
+}
+
+/** Where `next` stops repeating `previous`, or null when it starts with all of it. */
+function divergence(previous: ChatRequest, next: ChatRequest): string | null {
+ if (JSON.stringify(previous.tools ?? []) !== JSON.stringify(next.tools ?? [])) return "tool list changed";
+ for (const [index, message] of previous.messages.entries()) {
+ if (JSON.stringify(message) !== JSON.stringify(next.messages[index])) return `message ${index} of ${previous.messages.length} changed`;
+ }
+ return null;
+}
+
+const changes = (requests: readonly ChatRequest[]) =>
+ requests.slice(1).flatMap((next, index) => {
+ const where = divergence(requests[index]!, next);
+ return where ? [`request ${index + 2}: ${where}`] : [];
+ });
+
+/** llama.cpp b12532's refusal of a prompt past its context per slot. */
+const LLAMA_CPP_TOO_LONG = '{"error":{"code":400,"message":"request (5000 tokens) exceeds the available context size (4096 tokens), try increasing it","type":"exceed_context_size_error","n_prompt_tokens":5000,"n_ctx":4096}}';
+
+describe("a conversation's requests to an OpenAI-compatible model", () => {
+ it("reports the window a local server refused a request with, so compaction folds before the next refusal", async () => {
+ let requests = 0;
+ const server = createServer(async (request, response) => {
+ if (request.method !== "POST") { response.setHeader("content-type", "application/json"); response.end('{"data":[]}'); return; }
+ for await (const _ of request) { /* drain */ }
+ if (++requests === 1) { response.writeHead(400, { "content-type": "application/json" }); response.end(LLAMA_CPP_TOO_LONG); return; }
+ response.writeHead(200, { "content-type": "text/event-stream" });
+ response.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "Done." }, finish_reason: "stop" }] })}\n\n`);
+ response.write(`data: ${JSON.stringify({ choices: [], usage: { prompt_tokens: 3000, completion_tokens: 2 } })}\n\n`);
+ response.end("data: [DONE]\n\n");
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("fixture did not bind TCP");
+ const instance = await OpenAICompatDriver.create({
+ instanceId: randomUUID(), displayName: "Window fixture", enabled: true,
+ config: { url: `http://127.0.0.1:${address.port}/v1`, apiKeyEnv: "FIXTURE_CHAT_KEY" }, environment: { FIXTURE_CHAT_KEY: "fixture-credential-5b0f3c" },
+ });
+ const recorder = recordEvents(instance.adapter);
+ cleanups.push(async () => {
+ recorder.stop();
+ await instance.dispose();
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ });
+ await instance.adapter.sendTurn({ threadId: randomUUID(), text: "Next", model: "fixture-model", system: "Rules",
+ transcript: Array.from({ length: 8 }, (_, index) => ({ role: index % 2 ? "assistant" as const : "user" as const, text: `earlier ${index} ${"words ".repeat(400)}` })) });
+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });
+ expect(requests).toBe(2);
+ expect(recorder.events).toContainEqual(expect.objectContaining({ type: "thread.token-usage.updated", contextTokens: 3002, contextWindow: 4096 }));
+ });
+
+ it("only grow at the end across turns that call tools, while the changing instructions move on", async () => {
+ const lookup = await mcp("lookup");
+ const chat = await conversation("lookup_get");
+ const integrations = { custom: { lookup: { type: "http" as const, url: lookup.url, headers: {} } } };
+ for (const text of ["First question", "Second question", "Third question"]) await chat.turn(text, integrations);
+ expect(chat.requests).toHaveLength(6);
+ expect(changes(chat.requests)).toEqual([]);
+ // A local server is asked to keep earlier thinking in the prompt (Qwen3.6's template drops it otherwise).
+ expect(chat.requests.map((request) => request.chat_template_kwargs)).toEqual(Array(6).fill({ preserve_thinking: true }));
+ });
+
+ it("give another model the earlier turns' replies as text, never the first model's reasoning", async () => {
+ const lookup = await mcp("lookup");
+ const chat = await conversation("lookup_get");
+ const integrations = { custom: { lookup: { type: "http" as const, url: lookup.url, headers: {} } } };
+ await chat.turn("First question", integrations);
+ await chat.turn("Second question", integrations);
+ expect(JSON.stringify(chat.requests[2]!.messages)).toContain("Looking it up first.");
+ await chat.turn("Third question", integrations, "other-model");
+ const switched = chat.requests[4]!.messages;
+ expect(JSON.stringify(switched)).not.toContain("Looking it up first.");
+ expect(switched.filter((message) => message.role === "tool")).toHaveLength(0);
+ expect(switched.at(-1)).toMatchObject({ role: "user", content: expect.stringContaining("Third question") });
+ });
+
+ it("keep one tool list from the first request on a local server, waiting for a slow server to start", async () => {
+ const slow = await mcp("slow", 300);
+ const chat = await conversation("agents_get", 600);
+ const integrations = {
+ agents: agentsServer(),
+ custom: { slow: { type: "http" as const, url: slow.url, headers: {} } },
+ } as SendTurnInput["integrations"];
+ for (const text of ["First question", "Second question", "Third question"]) await chat.turn(text, integrations);
+ expect(chat.requests).toHaveLength(6);
+ expect(chat.requests.map((request) => JSON.stringify(request.tools).includes("slow_get"))).toEqual(Array(6).fill(true));
+ expect(changes(chat.requests)).toEqual([]);
+ });
+});
diff --git a/server/drivers/openai-chat-replay.ts b/server/drivers/openai-chat-replay.ts
new file mode 100644
index 0000000000..d132120bd2
--- /dev/null
+++ b/server/drivers/openai-chat-replay.ts
@@ -0,0 +1,113 @@
+import { createHash } from "node:crypto";
+import type { ChatToolDefinition } from "./chat-mcp-tools.ts";
+import type { OpenAIChatMessage } from "./openai-chat.ts";
+
+type TranscriptEntry = { role: "user" | "assistant"; text: string };
+
+export interface DeliveredUserMessage {
+ text: string;
+ sent: string;
+ volatile?: string;
+ after: string;
+ /** What its turn sent after it, through the final reply, and the replies the app stored: the turn is replayed as sent
+ * to the same model while the transcript still carries those replies right after this message. Another model gets the
+ * replies' text, never this model's reasoning. */
+ turn?: { model: string; messages: OpenAIChatMessage[]; replies: string[]; bytes: number };
+}
+
+const MAX_DELIVERED_THREADS = 256;
+/** Past this, the turns of the conversations used longest ago go back to replaying as their replies' text. */
+const MAX_KEPT_TURN_BYTES = 64 * 1024 * 1024;
+const EARLIER_SCREENSHOT = "[A screenshot from an earlier turn, not kept.]";
+
+export function keepRecent<K, V>(map: Map<K, V>, key: K, value: V) {
+ map.delete(key);
+ map.set(key, value);
+ if (map.size > MAX_DELIVERED_THREADS) map.delete(map.keys().next().value!);
+}
+
+const sameReplies = (stored: readonly string[], kept: readonly string[]) =>
+ stored.length === kept.length && stored.every((text, index) => text.trim() === kept[index]!.trim());
+
+const withoutImages = (message: OpenAIChatMessage): OpenAIChatMessage => Array.isArray(message.content) && message.content.some((part) => part.type === "image_url")
+ ? { ...message, content: message.content.map((part) => part.type === "image_url" ? { type: "text" as const, text: EARLIER_SCREENSHOT } : part) }
+ : message;
+
+const fingerprint = (text: string) => createHash("sha256").update(text).digest("base64url");
+
+function replayDelivered(
+ transcript: readonly TranscriptEntry[],
+ records: readonly DeliveredUserMessage[],
+ model: string,
+): { content: Map<number, string>; turns: Map<number, { messages: OpenAIChatMessage[]; through: number }>; matched: DeliveredUserMessage[]; volatile: string | undefined } {
+ const found: Array<{ index: number; record: DeliveredUserMessage }> = [];
+ let next = records.length - 1;
+ for (let index = transcript.length - 1; index >= 0 && next >= 0; index--) {
+ const message = transcript[index]!;
+ if (message.role !== "user" || !message.text) continue;
+ const after = index > 0 ? fingerprint(transcript[index - 1]!.text) : undefined;
+ for (let at = next; at >= 0; at--) {
+ const record = records[at]!;
+ if (record.text !== message.text && !record.text.endsWith("\n\n" + message.text)) continue;
+ if (after !== undefined && record.after !== after) continue;
+ found.unshift({ index, record });
+ next = at - 1;
+ break;
+ }
+ }
+ const content = new Map<number, string>();
+ const turns = new Map<number, { messages: OpenAIChatMessage[]; through: number }>();
+ let volatile: string | undefined;
+ for (const { index, record } of found) {
+ content.set(index, record.sent);
+ if (record.volatile !== undefined) volatile = record.volatile;
+ // The app may store more after a turn's replies (a summary of the work it did); that follows the replayed turn.
+ const stored = record.turn ? transcript.slice(index + 1, index + 1 + record.turn.replies.length) : [];
+ if (record.turn?.model === model && stored.every((entry) => entry.role === "assistant") && sameReplies(stored.map((entry) => entry.text), record.turn.replies)) {
+ turns.set(index, { messages: record.turn.messages, through: index + stored.length });
+ }
+ }
+ return { content, turns, matched: found.map(({ record }) => record), volatile };
+}
+
+/** What each conversation sent its model, so the next request starts with all of it and a prompt cache can reuse it. */
+export function createChatReplay() {
+ const delivered = new Map<string, DeliveredUserMessage[]>();
+ const lastSent = new Map<string, { tools: string; messages: string[] }>();
+ return {
+ replay(threadId: string, transcript: readonly TranscriptEntry[], model: string) {
+ const found = replayDelivered(transcript, delivered.get(threadId) ?? [], model);
+ const history: OpenAIChatMessage[] = [];
+ for (let index = 0; index < transcript.length; index++) {
+ history.push({ role: transcript[index]!.role, content: found.content.get(index) ?? transcript[index]!.text });
+ const sent = found.turns.get(index);
+ if (sent) { history.push(...sent.messages); index = sent.through; }
+ }
+ const record = (request: Pick<DeliveredUserMessage, "text" | "sent" | "volatile">): DeliveredUserMessage => {
+ const kept = { ...request, after: transcript.length ? fingerprint(transcript.at(-1)!.text) : "" };
+ keepRecent(delivered, threadId, [...found.matched, kept]);
+ return kept;
+ };
+ return { history, volatile: found.volatile, record };
+ },
+ keepTurn(record: DeliveredUserMessage, model: string, sent: OpenAIChatMessage[], replies: string[]) {
+ const messages = sent.map(withoutImages);
+ record.turn = { model, messages, replies, bytes: Buffer.byteLength(JSON.stringify(messages)) };
+ let total = 0;
+ for (const records of delivered.values()) for (const kept of records) total += kept.turn?.bytes ?? 0;
+ for (const records of delivered.values()) {
+ if (total <= MAX_KEPT_TURN_BYTES) break;
+ for (const kept of records) { total -= kept.turn?.bytes ?? 0; delete kept.turn; }
+ }
+ },
+ /** How much of the conversation's previous request this one starts with: all a provider's prompt cache can reuse. */
+ repeated(threadId: string, messages: readonly OpenAIChatMessage[], tools: readonly ChatToolDefinition[]) {
+ const sent = { tools: fingerprint(JSON.stringify(tools)), messages: messages.map((message) => fingerprint(JSON.stringify(message))) };
+ const before = lastSent.get(threadId);
+ keepRecent(lastSent, threadId, sent);
+ if (!before) return {};
+ const changed = before.messages.findIndex((hash, index) => sent.messages[index] !== hash);
+ return { repeats: { messages: changed < 0 ? before.messages.length : changed, of: before.messages.length, tools: before.tools === sent.tools } };
+ },
+ };
+}
diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.ts
index 961c63b1b4..e37edb650b 100644
--- a/server/drivers/openai-chat-tools.test.ts
+++ b/server/drivers/openai-chat-tools.test.ts
@@ -1464,7 +1464,10 @@ describe("structured tool execution boundaries", () => {
expect(log.length).toBeLessThan(large.length);
const outgoing = log.trim().split("\n").map((line) => JSON.parse(line) as { dir: string; msg: unknown })
.filter((entry) => entry.dir === "out").map((entry) => entry.msg);
- expect(outgoing).toEqual(f.requests.map((request) => ({ model: "fixture-model", messageCount: request.messages.length })));
+ expect(outgoing).toEqual(f.requests.map((request, index) => {
+ const before = f.requests[index - 1]?.messages.length;
+ return { model: "fixture-model", messageCount: request.messages.length, ...(before ? { repeats: { messages: before, of: before, tools: true } } : {}) };
+ }));
});
it.each(["stream", "approval", "rpc", "continuation"] as const)("cancels during %s, closes execution authority, and settles exactly once", async (stage) => {
@@ -1537,7 +1540,7 @@ describe("a turn with the person's Windows computer, the built-in browser and th
return { ...others, agents: catalog(syntheticToolNames("agent", agents), { after: names.map((name) => join(gates, name)) }) };
};
- it("sends the first request without waiting for a slow server, and lists its tools from the next round", async () => {
+ it("sends a hosted model's first request without waiting for a slow server, and lists its tools from the next round", async () => {
// The slow server cannot start until the first request has arrived: a turn that waited for it would give up on it
// first, so its tools could never be listed in the next round, however slow the runner.
const gate = mkdtempSync(join(tmpdir(), "omb-chat-tools-slow-"));
@@ -1552,7 +1555,7 @@ describe("a turn with the person's Windows computer, the built-in browser and th
// The turn has the slow server's tools in hand before the next round.
await settledServer("notes");
sse(response, [chunk({ tool_calls: [toolCall("agents_agent_1", "{}")] }, "tool_calls")]);
- });
+ }, "groq");
await f.start({ integrations: { agents: catalog(syntheticToolNames("agent", 1)), custom: { notes } } });
expect(await f.completed()).toMatchObject({ ok: true });
expect(settledBeforeFirst).toBe(false);
@@ -1575,7 +1578,7 @@ describe("a turn with the person's Windows computer, the built-in browser and th
if ((body.tools?.length ?? 0) <= 6) return answer(response);
response.writeHead(400, { "content-type": "application/json" });
response.end(JSON.stringify({ error: { message: `Invalid 'tools': array too long. Expected an array with maximum length 6, but got an array with length ${body.tools!.length} instead.`, type: "invalid_request_error" } }));
- });
+ }, "groq");
const warn = console.warn;
console.warn = () => {};
try {
diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.ts
index dc723fdc71..275289a318 100644
--- a/server/drivers/openai-chat.ts
+++ b/server/drivers/openai-chat.ts
@@ -1,5 +1,5 @@
import { RuntimeNoticeError, runtimeErrorText } from "./runtime-notice-error.ts";
-import { createHash } from "node:crypto";
+import { createChatReplay, keepRecent, type DeliveredUserMessage } from "./openai-chat-replay.ts";
import type {
DriverCreateInput,
ModelCatalog,
@@ -30,7 +30,7 @@ import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS }
import { plainFailure } from "./engine-errors.ts";
import { noticeFailure } from "../chat-notices.ts";
import { toolFailureMessage } from "./tool-failure.ts";
-import { refusesRequestSize, RequestTooLargeError, resendsAllowed, shareThatFits, sizeChange, smallerResend } from "./chat-size-limit.ts";
+import { refusedWindow, refusesRequestSize, RequestTooLargeError, resendsAllowed, shareThatFits, sizeChange, smallerResend } from "./chat-size-limit.ts";
import { requestTooLargeMessage } from "../../shared/request-too-large.ts";
import { toolSchemaProfileFor } from "../tool-schema-profile.ts";
import { classifyContinuable, writeTurnHandoff } from "../turn-continuation.ts";
@@ -143,50 +143,6 @@ const asError = (value: unknown): Error =>
const MAX_TURN_TOOL_CALLS = 200;
const MAX_ANNOUNCEMENT_NUDGES = 3;
-interface DeliveredUserMessage {
- text: string;
- sent: string;
- volatile?: string;
- after: string;
-}
-
-const MAX_REPLAY_EXTRA_BYTES = 24_000;
-const MAX_DELIVERED_THREADS = 256;
-
-const fingerprint = (text: string) => createHash("sha256").update(text).digest("base64url");
-
-function replayDelivered(
- transcript: ReadonlyArray<{ role: "user" | "assistant"; text: string }>,
- records: readonly DeliveredUserMessage[],
-): { content: Map<number, string>; matched: DeliveredUserMessage[]; volatile: string | undefined } {
- const found: Array<{ index: number; record: DeliveredUserMessage }> = [];
- let next = records.length - 1;
- for (let index = transcript.length - 1; index >= 0 && next >= 0; index--) {
- const message = transcript[index]!;
- if (message.role !== "user" || !message.text) continue;
- const after = index > 0 ? fingerprint(transcript[index - 1]!.text) : undefined;
- for (let at = next; at >= 0; at--) {
- const record = records[at]!;
- if (record.text !== message.text && !record.text.endsWith("\n\n" + message.text)) continue;
- if (after !== undefined && record.after !== after) continue;
- found.unshift({ index, record });
- next = at - 1;
- break;
- }
- }
- const content = new Map<number, string>();
- let volatile: string | undefined;
- let budget = MAX_REPLAY_EXTRA_BYTES;
- for (const { index, record } of found) {
- const extra = Buffer.byteLength(record.sent) - Buffer.byteLength(transcript[index]!.text);
- if (extra > budget) break;
- budget -= extra;
- content.set(index, record.sent);
- if (record.volatile !== undefined) volatile = record.volatile;
- }
- return { content, matched: found.map(({ record }) => record), volatile };
-}
-
const CORRECTIVE_ROUND = "[OpenMausBot: a tool call in this turn failed (its result is marked ok:false). Re-run the failed operations with corrected inputs where possible, check the results, then give your final answer. Do not report results you did not get.]";
const NUDGE_ANNOUNCED_ACTION = "You said what you would do next but called no tool. Use your tools for only the remaining work, or reply with verified results if nothing is left to do. Never repeat an operation that succeeded, was denied, or may already have taken effect; inspect its state instead. Do not retry a destructive operation.";
@@ -221,7 +177,11 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (completion.responseOutput) responseOutputs.set(reply, completion.responseOutput);
return reply;
};
- const delivered = new Map<string, DeliveredUserMessage[]>();
+ const conversations = createChatReplay();
+ /** Per bot (or conversation): the MCP servers its last turn listed tools from, started before the next turn's first request. */
+ const listedServers = new Map<string, Set<string>>();
+ /** The window a local server refused an oversized request with (llama.cpp's n_ctx), for compaction to time folds by. */
+ const refusedWindows = new Map<string, number>();
/** Not cleared on `sessionReset`: with no cursor the harness sends it on nearly every turn. */
const sessionGrants = new Map<string, Set<string>>();
@@ -300,7 +260,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const refused = tools.length ? routeRefusal(route, status, body) : null;
if (refused) return new ModelRouteRefused(refused, message);
if (rejectsKey(status, body)) noteKeyRejected(options.apiUrl, options.apiKey);
- if (refusesRequestSize(status, body)) return new RequestTooLargeError(message, Buffer.byteLength(payload), shareThatFits(body));
+ if (refusesRequestSize(status, body)) return new RequestTooLargeError(message, Buffer.byteLength(payload), shareThatFits(body), refusedWindow(body));
if (rejectsToolsParameter(status, body)) return new UnsupportedChatToolsError(message);
const refusal = refusedToolCall(status, body);
if (refusal) return new RejectedToolCallError(message, refusal);
@@ -481,10 +441,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const seesImages = (turn: SendTurnInput) =>
options.imageInput?.(turn.model || options.models().default) ?? true;
- const messagesFor = (turn: SendTurnInput): OpenAIChatMessage[] => {
+ const messagesFor = (turn: SendTurnInput, model: string): { messages: OpenAIChatMessage[]; record: DeliveredUserMessage } => {
const halves = promptHalves(turn);
const transcript = turn.transcript ?? [];
- const replay = replayDelivered(transcript, delivered.get(turn.threadId) ?? []);
+ const replay = conversations.replay(turn.threadId, transcript, model);
const volatile = halves.volatile.trim();
const note = halves.stable === null || (!turn.mentionTurn && replay.volatile === volatile) ? ""
: volatileContextNote(volatile, Boolean(replay.volatile));
@@ -493,24 +453,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const userTurn = note ? { ...turn, text: withContextNote(note, turn.text) } : turn;
const content = options.computerUse && seesImages(turn) ? chatUserContent(userTurn) : textOnly(userTurn.text);
const kept = turn.recalled ? turn.text.replace(`${turn.recalled}\n\n`, "") : turn.text;
- const record = {
- text: kept,
- sent: textOnly(withContextNote(note, kept)),
- ...(note ? { volatile } : {}),
- after: transcript.length ? fingerprint(transcript.at(-1)!.text) : "",
- };
- delivered.delete(turn.threadId);
- delivered.set(turn.threadId, [...replay.matched, record]);
- if (delivered.size > MAX_DELIVERED_THREADS) delivered.delete(delivered.keys().next().value!);
+ const record = replay.record({ text: kept, sent: textOnly(userTurn.text), ...(note ? { volatile } : {}) });
const system = halves.stable ?? turn.system;
- return [
- ...(system ? [{ role: "system" as const, content: system }] : []),
- ...transcript.map((message, index) => ({
- role: message.role,
- content: replay.content.get(index) ?? message.text,
- })),
- { role: "user", content },
- ];
+ return { messages: [...(system ? [{ role: "system" as const, content: system }] : []), ...replay.history, { role: "user", content }], record };
};
const sendTurn = async (turn: SendTurnInput) => {
@@ -521,6 +466,9 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
const abort = new AbortController();
let messages: OpenAIChatMessage[] = [];
let request: OpenAIChatMessage | undefined;
+ let record: DeliveredUserMessage | undefined;
+ const replies: string[] = [];
+ const serversKey = turn.botId ?? turn.threadId;
const retainImages = chatImageBudget();
let model = turn.model || options.models().default;
const maskable = (value: unknown): value is string => typeof value === "string" && value.length >= 8; // a short placeholder key ("1") would redact every match
@@ -547,9 +495,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
});
const grantsKey = JSON.stringify([turn.threadId, turn.botId ?? null]);
const granted = sessionGrants.get(grantsKey) ?? new Set<string>();
- sessionGrants.delete(grantsKey);
- sessionGrants.set(grantsKey, granted);
- if (sessionGrants.size > MAX_DELIVERED_THREADS) sessionGrants.delete(sessionGrants.keys().next().value!);
+ keepRecent(sessionGrants, grantsKey, granted);
const approval = createChatToolApproval({
signal: abort.signal,
granted: shellOff(turn) ? undefined : granted,
@@ -603,7 +549,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (preparation) { await preparation; model = turn.model || options.models().default; }
abort.signal.throwIfAborted();
if (options.computerUse && turn.images?.length && seesImages(turn)) assertImageTransport(options.apiUrl);
- messages = messagesFor(turn);
+ ({ messages, record } = messagesFor(turn, model));
request = messages.at(-1)!;
for (const message of messages) retainImages(message.content);
emit({ ...base(turn.threadId, turnId), type: "session.started", sessionId: null, model });
@@ -611,8 +557,10 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
if (!parsed.ok) throw new Error(parsed.error);
const scope = parsed.scope;
const toolsOff = options.tools === false || options.toolUse?.(model) === false;
+ // The tool list leads the prompt: a server joining mid-turn makes a local hybrid model (Qwen3.6) read all of it again,
+ // minutes per step, so a local model waits for every server and others wait for the ones this bot used last turn.
tools = await mountChatTools(toolsOff ? undefined : withHostFileTools(turn.integrations), abort.signal, options.computerUse, scope, turn.mcpCallTimeoutMs,
- toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), { background: true, conversation: turn.threadId, notice: ({ message, text }) => emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), text }) });
+ toolSchemaProfileFor({ url: options.apiUrl, model }), turn.cwd ?? turn.toolResultFolder, safeText, chatToolLimitFor(options.apiUrl, model), { background: !options.localModel, waitFor: listedServers.get(serversKey), conversation: turn.threadId, notice: ({ message, text }) => emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message), text }) });
noteToolBudget(turn.botId, tools.budget);
for (const message of chatToolNotices(tools)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
const questionAllowed = !toolsOff && allowsTool(scope, { kind: "native", name: ASK_USER_TOOL });
@@ -631,7 +579,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
// Servers still starting join between rounds, never once the tools were dropped (none left while ask_user is allowed).
const joined = !questionAllowed || tools.definitions.length ? await joinLateChatTools(tools, [ASK_USER_TOOL_DEFINITION]) : undefined;
for (const message of joined ?? []) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", message: safeText(message) });
- native("out", options.nativeLog.outgoing(turn, messages, model, tools.definitions));
+ native("out", { ...object(options.nativeLog.outgoing(turn, messages, model, tools.definitions)), ...conversations.repeated(turn.threadId, messages, tools.definitions),
+ ...(process.env.OPENMAUS_LOG_CHAT_REQUESTS === "1" ? { messages, tools: tools.definitions } : {}) });
let attempt = 0;
let resends = 0;
let completion: Completion;
@@ -697,6 +646,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
}
// A provider refuses an oversized request before running anything, so a smaller copy may go again.
if (error instanceof RequestTooLargeError && !abort.signal.aborted) {
+ if (error.window) refusedWindows.set(model, error.window);
const resend = resends < resendsAllowed(error) ? smallerResend(messages, request, error.bytes, error.fits) : null;
native("out", { refused: "request_too_large", bytes: error.bytes, ...(resend ? { before: resend.before, after: resend.after } : {}) });
console.warn(`${options.driverKind}: ${model} refused a ${error.bytes}-byte request as too large; ${resend ? `resending smaller (${sizeChange(resend.before, resend.after)})` : "not resending"}`);
@@ -737,14 +687,16 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
usage.output += completion.usage.output;
if (completion.usage.cachedInput !== undefined) usage.cachedInput = (usage.cachedInput ?? 0) + completion.usage.cachedInput;
hasUsage = true;
- const contextWindow = options.models().options.find((entry) => entry.id === model)?.contextWindow;
+ // A request bigger than the refused window went through: the server was given more context since.
+ if ((refusedWindows.get(model) ?? Infinity) < completion.usage.input + completion.usage.output) refusedWindows.delete(model);
+ const contextWindow = refusedWindows.get(model) ?? options.models().options.find((entry) => entry.id === model)?.contextWindow;
// Accounting sums the turn; context occupancy is the latest round only.
emit({ ...base(turn.threadId, turnId), type: "thread.token-usage.updated", ...usage,
contextTokens: completion.usage.input + completion.usage.output, ...(contextWindow ? { contextWindow } : {}) });
}
// Reasoning on a tool-call round belongs to the protocol, not a final reply.
const reply = completion.text.trim() ? completion.text : completion.toolCalls.length || unreadable ? "" : completion.reasoning;
- if (reply.trim()) { spoke = true; emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: safeText(reply) }); }
+ if (reply.trim()) { spoke = true; replies.push(safeText(reply)); emit({ ...base(turn.threadId, turnId), type: "item.completed", itemType: "assistant_text", text: safeText(reply) }); }
abort.signal.throwIfAborted();
if (unreadable) {
askedAgain = true;
@@ -784,6 +736,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
messages.push(assistantReply(model, completion, reply));
continue;
}
+ messages.push(assistantReply(model, completion, reply));
ok = true;
break;
}
@@ -891,6 +844,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
} finally {
turnEntry.ending = true;
approval.close();
+ if (tools) keepRecent(listedServers, serversKey, new Set(tools.listedServers()));
let cleanupFailed = false;
try { await tools?.close(); }
catch {
@@ -900,6 +854,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)
failure = "Tool processes could not be stopped; their execution state is uncertain.";
}
if (abort.signal.aborted) { ok = false; stopReason = "interrupted"; }
+ const asked = request ? messages.indexOf(request) : -1;
+ if (ok && record && asked >= 0) conversations.keepTurn(record, model, messages.slice(asked + 1), replies);
if (!ok && (unread.length || turnEntry.asides.length)) emit({ ...base(turn.threadId, turnId), type: "runtime.notice", ...noticeFailure("chat.notice.unreadMessage") });
if (failure && (!abort.signal.aborted || cleanupFailed)) {
// "upstream" (an OpenAI-compatible URL) names no provider, and the Cloud trial credit reads its raw line.
diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.ts
index 1a6c215f64..4fbad6c132 100644
--- a/server/drivers/openai-compat.test.ts
+++ b/server/drivers/openai-compat.test.ts
@@ -995,10 +995,9 @@ describe("OpenAICompatDriver", () => {
await done();
});
- it("leaves automatic recall out of the replay and keeps the added bytes bounded", async () => {
+ it("replays each turn's automatic recall and changing context as sent, so every request starts with the last", async () => {
const { send, done } = await fixture();
const transcript: Array<{ role: "user" | "assistant"; text: string }> = [];
- const bytes = (messages: any[]) => Buffer.byteLength(JSON.stringify(messages));
let previous: any[] = [];
for (let turn = 0; turn < 20; turn++) {
const minute = String(turn).padStart(2, "0");
@@ -1011,10 +1010,7 @@ describe("OpenAICompatDriver", () => {
transcript: [...transcript],
});
expect(messages.at(-1).content).toContain(recalled);
- if (turn > 0) expect(messages.slice(0, previous.length - 1)).toEqual(previous.slice(0, -1));
- for (const message of messages.slice(1, -1)) expect(message.content).not.toContain("<recalled");
- const stored = [{ role: "system", content: "Standing rules." }, ...transcript.map((m) => ({ role: m.role, content: m.text }))];
- expect(bytes(messages.slice(0, -1)) - bytes(stored)).toBeLessThanOrEqual(24_000 + 2_000);
+ if (turn > 0) expect(messages.slice(0, previous.length)).toEqual(previous);
previous = messages;
transcript.push({ role: "user", text: typed }, { role: "assistant", text: "hi" });
}
diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.ts
index 8e93e89df0..c2f3688e8a 100644
--- a/server/drivers/openai-compat.ts
+++ b/server/drivers/openai-compat.ts
@@ -44,6 +44,11 @@ const NO_MODELS: ModelCatalog = { default: "", options: [] };
const OLLAMA_STATUS_MS = 5_000;
const OLLAMA_FIRST_LIST_MS = 2_000;
+/** Qwen3.6's chat template drops earlier turns' thinking unless asked to keep it, which changes the prompt's start at every
+ * new message; a hybrid model then reads it all again. llama.cpp, vLLM and SGLang pass these to the template, and a
+ * template without the option ignores it. https://huggingface.co/Qwen/Qwen3.6-35B-A3B#preserve-thinking */
+const KEEP_EARLIER_THINKING = { preserve_thinking: true };
+
const withEffort = (effort: string | undefined) => effort ? { reasoning_effort: effort } : {};
const EFFORT_CHOICES = ["low", "medium", "high"].map((id) => ({ id, label: titleCaseModelId(id, /[-_ ]+/) }));
/** OpenAI's reasoning models, gpt-5 onward. o1-mini, o1-preview and the chat aliases refuse `reasoning_effort`. */
@@ -427,6 +432,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {
? { provider: { order: [config.provider], allow_fallbacks: false } }
: {}),
...(isOpenRouterUrl(config.url) && isClaudeModel(model) ? openRouterPromptCache(threadId) : {}),
+ ...(onThisNetwork(config.url) ? { chat_template_kwargs: KEEP_EARLIER_THINKING } : {}),
}),
httpErrorLabel: "upstream",
missingKeyError: missingKey,
diff --git a/server/host/conversation-compaction.ts b/server/host/conversation-compaction.ts
index 92e24e8b2a..ab8be6b48d 100644
--- a/server/host/conversation-compaction.ts
+++ b/server/host/conversation-compaction.ts
@@ -1,5 +1,5 @@
import { draftSummary, foldPoint } from "../compaction-summary.ts";
-import { compactBudget, compactionReading, contextWindowFor, shouldCompact } from "../context-budget.ts";
+import { compactBudget, contextWindowFor, lastContextReading, shouldCompact } from "../context-budget.ts";
import { MAX_SUMMARY_BYTES, selectReplay } from "../context-rebuild.ts";
import type { ModelCatalog } from "../contracts.ts";
import type { EngineCompactCheck, EngineCompactOutcome } from "./warm-summary-host.ts";
@@ -92,7 +92,7 @@ export function createConversationCompaction(deps: ConversationCompactionDeps) {
});
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 measurement = lastContextReading(instance, model, task);
const window = contextWindowFor(model, instance.models, measurement?.window);
const bytes = history.reduce((n, entry) => n + Buffer.byteLength(entry.text), 0);
let floor = task.contextFloor, seededFloor = false;
diff --git a/server/host/resume-check.ts b/server/host/resume-check.ts
index 9172de06ad..2428a3a5be 100644
--- a/server/host/resume-check.ts
+++ b/server/host/resume-check.ts
@@ -1,12 +1,22 @@
import { createHash } from "node:crypto";
+import { contextWindowFor, lastContextReading } from "../context-budget.ts";
import { DEFAULT_REBUILD_BYTES, replayToolCalls, selectReplay } from "../context-rebuild.ts";
import type { ContextMessage } from "../delta-context.ts";
import { sinceFreshStart } from "../fresh-start.ts";
import { resumePlan } from "../resume-plan.ts";
import type { BotRecord, Message, Store, TaskRecord } from "../store.ts";
+import { replaysNatively } from "../turn-context.ts";
import type { CompactConversationInput } from "./conversation-compaction.ts";
+/** About half the window at four bytes a token, leaving the rest to the instructions, tools and the turn's own work. */
+const EVERY_TURN_BYTES_PER_WINDOW_TOKEN = 2;
+
type Compaction = NonNullable<Parameters<typeof selectReplay>[1]>["compaction"];
+type TurnEngine = {
+ instance: Parameters<typeof lastContextReading>[0] & { driverKind: Parameters<typeof replaysNatively>[0]; models?: Parameters<typeof contextWindowFor>[1] };
+ model: string | undefined;
+ task: Parameters<typeof lastContextReading>[2];
+};
export interface ResumeCheckDeps {
store: Pick<Store, "taskByThread" | "activePath">;
@@ -22,11 +32,16 @@ export interface ResumeCheckDeps {
}
export function createResumeCheck(deps: ResumeCheckDeps) {
- const replayInputs = (bot: BotRecord, threadId: string, activeMessages: Message[], skip: ReadonlySet<string>) => {
+ const replayInputs = (bot: BotRecord, threadId: string, activeMessages: Message[], skip: ReadonlySet<string>, engine?: TurnEngine) => {
const context = deps.directContext(bot, threadId, activeMessages);
const record = deps.latestCompaction(activeMessages);
const settings = deps.context();
- const selection = selectReplay(context, { budgetBytes: settings?.rebuildBytes ?? DEFAULT_REBUILD_BYTES, excludedIds: skip, compaction: record, tools: replayToolCalls(activeMessages, settings) });
+ // Bounds the conversation's text; the engine's replayed tool calls and results come on top, and compaction, timed by
+ // the whole request's size, folds both. Only an engine sent the history with every request gets it this way.
+ const window = engine && replaysNatively(engine.instance.driverKind)
+ ? contextWindowFor(engine.model, engine.instance.models, lastContextReading(engine.instance, engine.model, engine.task)?.window) : undefined;
+ const bounds = window ? { budgetBytes: Math.max(DEFAULT_REBUILD_BYTES, Math.floor(window * EVERY_TURN_BYTES_PER_WINDOW_TOKEN)), maxMessages: Number.MAX_SAFE_INTEGER, stable: true } : {};
+ const selection = selectReplay(context, { ...bounds, ...(settings?.rebuildBytes ? { budgetBytes: settings.rebuildBytes } : {}), excludedIds: skip, compaction: record, tools: replayToolCalls(activeMessages, settings) });
return { context, replayable: context.filter((m) => !skip.has(m.id)), record, selection };
};
diff --git a/server/index.ts b/server/index.ts
index 62b4a44592..1641746a71 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -7691,7 +7691,7 @@ async function beginTurn(
if ((m.roomRequest.phase === "request" && m.roomRequest.id === opts.coordination.id) ||
(m.roomRequest.phase === "result" && coordinationChildren?.has(m.roomRequest.id))) skipTranscript.add(m.id);
}
- const { context, replayable, record, selection } = replayInputs(bot, threadId, activeMessages, skipTranscript);
+ const { context, replayable, record, selection } = replayInputs(bot, threadId, activeMessages, skipTranscript, { instance, model, task });
const contextOrder = context.map(m => m.id);
const transcript = selection.transcript.map(({ role, text }) => ({ role, text }));
// Engines keep a session in the folder it started in, so a thread that follows its bot to the bot's working folder starts a new one there.
diff --git a/server/openai-boat.e2e.test.ts b/server/openai-boat.e2e.test.ts
index f8f426f55b..8110bc5317 100644
--- a/server/openai-boat.e2e.test.ts
+++ b/server/openai-boat.e2e.test.ts
@@ -31,7 +31,9 @@ it("keeps the selected API model for direct, group and scheduled Boat turns and
if (path === "/v1/chat/completions") {
if (isTitleCall(body)) { res.statusCode = 500; return res.end("{}"); }
requests.push(body);
- const completed = body.messages.some((message: any) => message.role === "tool");
+ // Earlier turns come back with their tool calls, so only a result since this turn's request means the call ran.
+ const asked = body.messages.findLastIndex((message: any) => message.role === "user" && JSON.stringify(message.content).includes("Inspect the assigned cloud desktop."));
+ const completed = body.messages.slice(asked + 1).some((message: any) => message.role === "tool");
const tool = body.tools?.find((entry: any) => entry.function.name === "computer_screenshot");
return res.end(JSON.stringify({ choices: [{ message: completed
? { role: "assistant", content: "Fixture completed." }
diff --git a/server/openai-prefix.e2e.test.ts b/server/openai-prefix.e2e.test.ts
new file mode 100644
index 0000000000..351f80fd08
--- /dev/null
+++ b/server/openai-prefix.e2e.test.ts
@@ -0,0 +1,95 @@
+import { createServer } from "node:http";
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+import { isTitleCall } from "./testing/title-call.ts";
+
+const MCP_FIXTURE = `
+import { createInterface } from 'node:readline';
+createInterface({ input: process.stdin }).on('line', (line) => {
+ const request = JSON.parse(line);
+ if (request.id === undefined) return;
+ const result = request.method === 'initialize' ? { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1' } }
+ : request.method === 'tools/list' ? { tools: [{ name: 'look_up', description: 'Look a fact up', inputSchema: { type: 'object', properties: { topic: { type: 'string' } }, required: ['topic'], additionalProperties: false } }] }
+ : { content: [{ type: 'text', text: 'Fact about ' + request.params.arguments.topic + ': ' + 'detail '.repeat(300) }] };
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\\n');
+});
+`;
+
+type ChatRequest = { messages: Array<{ role: string }>; tools?: Array<{ function: { name: string; description?: string } }> };
+
+/** Where `next` stops repeating `previous`, or null when it starts with all of it. */
+function divergence(previous: ChatRequest, next: ChatRequest): string | null {
+ if (JSON.stringify(previous.tools ?? []) !== JSON.stringify(next.tools ?? [])) return "tool list changed";
+ const changed = previous.messages.findIndex((message, index) => JSON.stringify(message) !== JSON.stringify(next.messages[index]));
+ return changed < 0 ? null : `message ${changed} of ${previous.messages.length} changed`;
+}
+
+it("sends a bot's conversation to an OpenAI-compatible model as requests that only grow at the end, past the old 24 KB history window", async () => {
+ const requests: ChatRequest[] = [];
+ let answers = 0;
+ const upstream = createServer(async (req, res) => {
+ if (req.url === "/v1/models") {
+ res.setHeader("content-type", "application/json");
+ res.end(JSON.stringify({ data: [{ id: "fixture-model" }] }));
+ return;
+ }
+ if (req.method !== "POST") { res.writeHead(404).end(); return; }
+ let body = "";
+ for await (const chunk of req) body += chunk;
+ const request = JSON.parse(body) as ChatRequest;
+ if (isTitleCall(request)) { res.writeHead(500).end(); return; }
+ const frame = (delta: unknown, finish: string) => `data: ${JSON.stringify({ choices: [{ index: 0, delta, finish_reason: finish }] })}\n\ndata: [DONE]\n\n`;
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ // Requests without tools are the harness's own side calls (summaries, suggestions), not the conversation.
+ if (!request.tools?.length) { res.end(frame({ content: "ok" }, "stop")); return; }
+ requests.push(request);
+ const tool = request.tools.find((entry) => entry.function.description === "Look a fact up")!.function.name;
+ if (request.messages.at(-1)?.role === "tool") res.end(frame({ content: `Answer ${++answers}: ${"Here is what I found. ".repeat(200)}` }, "stop"));
+ else res.end(frame({ tool_calls: [{ index: 0, id: `call-${requests.length}`, type: "function", function: { name: tool, arguments: '{"topic":"cache"}' } }] }, "tool_calls"));
+ });
+ await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));
+ const address = upstream.address();
+ if (!address || typeof address === "string") throw new Error("fixture provider address missing");
+ const fixture = await launchVerificationServer();
+ const control = (args: string[]) => runControlOmb([...args, "--url", fixture.info.url]) as Promise<any>;
+ 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) }),
+ });
+ const result = await response.json() as any;
+ expect(response.ok, JSON.stringify(result)).toBe(true);
+ return result;
+ };
+ try {
+ await api("PATCH", "/api/config", { openaiCompat: { key: "synthetic-fixture-key", url: `http://127.0.0.1:${address.port}/v1`, model: "fixture-model" } });
+ await api("POST", "/api/instances/openaiCompat/refresh-models", {});
+ const script = join(fixture.info.dataDir, "fixture-mcp.mjs");
+ writeFileSync(script, MCP_FIXTURE);
+ await api("POST", "/api/mcp/servers", { name: "facts", command: process.execPath, args: [script], env: {}, enabled: true });
+ await api("PATCH", "/api/mcp/servers/facts", { enabled: true });
+ const { bot } = await control(["new-bot", "--name", "Prefix check"]);
+ await control(["set-model", "--bot", bot.id, "--instance", "openaiCompat", "--model", "fixture-model"]);
+ await api("PATCH", `/api/bots/${bot.id}`, { mcpServers: ["facts"], approvalMode: "full", soul: "Look facts up before answering." });
+ const turns: number[] = [];
+ for (let turn = 1; turn <= 8; turn++) {
+ turns.push(requests.length);
+ expect((await control(["send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", `Question ${turn}: what changed?`])).success).toBe(true);
+ const settled = await control(["wait", "--bot", bot.id, "--task", bot.activeTaskId, "--timeout", "30"]);
+ expect(settled.status, JSON.stringify(settled.messages?.slice(-3))).toBe("settled");
+ }
+ expect(requests).toHaveLength(16);
+ const history = requests.at(-1)!.messages.reduce((bytes, message) => bytes + Buffer.byteLength(JSON.stringify(message)), 0);
+ expect(history).toBeGreaterThan(48_000);
+ const changes = requests.slice(1).flatMap((next, index) => {
+ const where = divergence(requests[index]!, next);
+ return where ? [`request ${index + 2} (turn ${turns.findLastIndex((start) => start <= index + 1) + 1}): ${where}`] : [];
+ });
+ expect(changes).toEqual([]);
+ } finally {
+ await fixture.close();
+ upstream.closeAllConnections();
+ await new Promise<void>((resolve) => upstream.close(() => resolve()));
+ }
+}, 180_000);