@@ -109,6 +109,78 @@ const ZERO_USAGE: Usage = {
109109 cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
110110 };
111111
112+function withUsage(
113+ message: AssistantMessage,
114+ api: string,
115+ totalTokens: number,
116+): AssistantMessage {
117+ return {
118+ ...message,
119+ api,
120+ provider: "test",
121+ model: api,
122+ usage: {
123+ ...ZERO_USAGE,
124+ input: totalTokens,
125+ totalTokens,
126+ cost: { ...ZERO_USAGE.cost },
127+ },
128+ };
129+}
130+
131+function advanceCompleteToolHistorySpan(
132+ messages: readonly Message[],
133+ startIndex: number,
134+): number | null {
135+ const message = messages[startIndex];
136+ if (!message) {
137+ return null;
138+ }
139+ if (message.role === "toolResult") {
140+ return null;
141+ }
142+ if (message.role !== "assistant") {
143+ return startIndex + 1;
144+ }
145+
146+ const pendingToolCallIds = message.content.flatMap((block) => {
147+ return block.type === "toolCall" ? [block.id] : [];
148+ });
149+ if (pendingToolCallIds.length === 0) {
150+ return startIndex + 1;
151+ }
152+
153+ let cursor = startIndex + 1;
154+ while (pendingToolCallIds.length > 0) {
155+ const nextMessage = messages[cursor];
156+ if (!nextMessage || nextMessage.role !== "toolResult") {
157+ return null;
158+ }
159+
160+ const matchIndex = pendingToolCallIds.indexOf(nextMessage.toolCallId);
161+ if (matchIndex === -1) {
162+ return null;
163+ }
164+
165+ pendingToolCallIds.splice(matchIndex, 1);
166+ cursor += 1;
167+ }
168+
169+ return cursor;
170+}
171+
172+function isCompleteToolHistory(messages: readonly Message[]): boolean {
173+ let index = 0;
174+ while (index < messages.length) {
175+ const nextIndex = advanceCompleteToolHistorySpan(messages, index);
176+ if (nextIndex === null) {
177+ return false;
178+ }
179+ index = nextIndex;
180+ }
181+ return true;
182+}
183+
112184 function getTextContent(
113185 content: ReadonlyArray<{ type: string; text?: string }>,
114186 ): string {
@@ -2316,6 +2388,120 @@ describe("agent loop", () => {
23162388 }
23172389 });
23182390
2391+ test("context compaction keeps tool call history valid across compaction boundaries", async () => {
2392+ const api = "test/context-compaction-tool-history";
2393+ const sourceId = "test-context-compaction-tool-history";
2394+ const model: Model<string> = {
2395+ id: api,
2396+ name: "Context Compaction Tool History Model",
2397+ api,
2398+ provider: "test",
2399+ baseUrl: "http://localhost:0",
2400+ reasoning: false,
2401+ input: ["text"],
2402+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
2403+ contextWindow: 250,
2404+ maxTokens: 4096,
2405+ };
2406+ const compactionRequests: Message[][] = [];
2407+ const mainRequests: Message[][] = [];
2408+
2409+ const buildProviderStream = (context: Context) => {
2410+ const isCompaction = (context.systemPrompt ?? "").includes(
2411+ "You summarize earlier conversation context for a coding agent.",
2412+ );
2413+ if (isCompaction) {
2414+ compactionRequests.push(structuredClone(context.messages));
2415+ } else {
2416+ mainRequests.push(structuredClone(context.messages));
2417+ }
2418+
2419+ const stream = createAssistantMessageEventStream();
2420+ const finalMessage = isCompaction
2421+ ? fauxAssistantMessage("summary")
2422+ : fauxAssistantMessage("done");
2423+
2424+ queueMicrotask(() => {
2425+ stream.push({ type: "done", reason: "stop", message: finalMessage });
2426+ stream.end(finalMessage);
2427+ });
2428+
2429+ return stream;
2430+ };
2431+
2432+ registerApiProvider(
2433+ {
2434+ api,
2435+ stream: (_model, context) => buildProviderStream(context),
2436+ streamSimple: (_model, context) => buildProviderStream(context),
2437+ },
2438+ sourceId,
2439+ );
2440+
2441+ try {
2442+ const session = createSession(db, { cwd: tmp });
2443+ const currentUser = makeUser(`current request ${"x".repeat(380)}`);
2444+ const turn = appendMessage(db, session.id, currentUser);
2445+ const toolCall = fauxToolCall("shell", { command: "echo tool" });
2446+ const toolCallMessage = withUsage(
2447+ fauxAssistantMessage([toolCall], { stopReason: "toolUse" }),
2448+ api,
2449+ 250,
2450+ );
2451+ const toolResultMessage: Message = {
2452+ role: "toolResult",
2453+ toolCallId: toolCall.id,
2454+ toolName: "shell",
2455+ content: [{ type: "text", text: `tool output ${"t".repeat(380)}` }],
2456+ isError: false,
2457+ timestamp: Date.now() + 1,
2458+ };
2459+ const followUpOne = withUsage(
2460+ fauxAssistantMessage(`assistant 1 ${"a".repeat(380)}`),
2461+ api,
2462+ 250,
2463+ );
2464+ const followUpTwo = withUsage(
2465+ fauxAssistantMessage(`assistant 2 ${"b".repeat(380)}`),
2466+ api,
2467+ 250,
2468+ );
2469+ const messages: Message[] = [
2470+ currentUser,
2471+ toolCallMessage,
2472+ toolResultMessage,
2473+ followUpOne,
2474+ followUpTwo,
2475+ ];
2476+
2477+ appendMessage(db, session.id, toolCallMessage, turn);
2478+ appendMessage(db, session.id, toolResultMessage, turn);
2479+ appendMessage(db, session.id, followUpOne, turn);
2480+ appendMessage(db, session.id, followUpTwo, turn);
2481+
2482+ const result = await runAgentLoop({
2483+ db,
2484+ sessionId: session.id,
2485+ turn,
2486+ model,
2487+ systemPrompt: "Test",
2488+ tools: [],
2489+ toolHandlers: new Map(),
2490+ messages,
2491+ cwd: tmp,
2492+ });
2493+
2494+ expect(result.stopReason).toBe("stop");
2495+ expect(compactionRequests.length).toBeGreaterThan(0);
2496+ expect(mainRequests).toHaveLength(1);
2497+ for (const request of [...compactionRequests, ...mainRequests]) {
2498+ expect(isCompleteToolHistory(request)).toBe(true);
2499+ }
2500+ } finally {
2501+ unregisterApiProviders(sourceId);
2502+ }
2503+ });
2504+
23192505 test("context compaction summarizes older messages without re-compacting earlier summaries", async () => {
23202506 const api = "test/context-compaction";
23212507 const sourceId = "test-context-compaction";
@@ -2521,21 +2707,17 @@ describe("agent loop", () => {
25212707 const messages: Message[] = [userMsg];
25222708
25232709 for (let index = 0; index < 6; index += 1) {
2524- const assistantMessage: AssistantMessage = {
2525- ...fauxAssistantMessage(`assistant ${index} ${"a".repeat(380)}`),
2710+ const toolCall = fauxToolCall("shell", {
2711+ command: `echo tool ${index}`,
2712+ });
2713+ const assistantMessage = withUsage(
2714+ fauxAssistantMessage([toolCall], { stopReason: "toolUse" }),
25262715 api,
2527- provider: "test",
2528- model: api,
2529- usage: {
2530- ...ZERO_USAGE,
2531- input: 250,
2532- totalTokens: 250,
2533- cost: { ...ZERO_USAGE.cost },
2534- },
2535- };
2716+ 250,
2717+ );
25362718 const toolResultMessage: Message = {
25372719 role: "toolResult",
2538- toolCallId: `call-${index}`,
2720+ toolCallId: toolCall.id,
25392721 toolName: "shell",
25402722 content: [{ type: "text", text: `tool ${index} ${"t".repeat(380)}` }],
25412723 isError: false,