Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): shrink the retained-tail fallback until it fits
vastsad7dbeac04173
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex bb1e5e812..16ae03353 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -735,9 +735,16 @@ The complete transcript remains durable and visible, while the next modelrequest receives only that recovery checkpoint and applicable tail. Thelifecycle event marks this as `fallback: "retained_tail"`, and the checkpoint'smark carries the same `fallback`, so the renderer shows a warning and labels-the transcript row as a failed summary rather than a false success. If the-fallback cannot be prepared, persisted, or kept below the safe budget, the user-row and an assistant error remain durable and no provider request starts.+the transcript row as a failed summary rather than a false success. The window+is sized from the local estimate while installation re-estimates with the+calibrated one, so a window the calibrated estimate still puts at or above the+safe budget is halved and retried, down to 1/128 of its first size, before the+recovery gives up (issue #2494). If the fallback cannot be prepared, persisted,+or kept below the safe budget, the user row and an assistant error remain+durable and no provider request starts. That `CONTEXT_COMPACTION_FAILED` error+is classified as local (`details.origin: "local"`), so it carries no stream+timings or HTTP status from an earlier request, and its message names the+checkpoint failure that caused it.Provider-reported context overflow is the last recovery layer: omit the failedassistant from model context, compact once, and retry once. A second overflowremains terminal and is reported as `CONTEXT_TOO_LARGE`: the error classifierdiff --git a/packages/agent-runtime/src/agent-errors.test.ts b/packages/agent-runtime/src/agent-errors.test.tsindex 46d9f124e..3b880e785 100644--- a/packages/agent-runtime/src/agent-errors.test.ts+++ b/packages/agent-runtime/src/agent-errors.test.ts@@ -1076,6 +1076,7 @@ describe("classifyAgentError", () => {).toMatchObject({code: "CONTEXT_COMPACTION_FAILED",retriable: false,+ details: { origin: "local" },});});diff --git a/packages/agent-runtime/src/agent-errors.ts b/packages/agent-runtime/src/agent-errors.tsindex 7b2e3c6ed..86d53ae08 100644--- a/packages/agent-runtime/src/agent-errors.ts+++ b/packages/agent-runtime/src/agent-errors.ts@@ -623,7 +623,10 @@ export function classifyAgentError(err: unknown): ClassifiedAgentError {return result("TURN_ABORTED", false);}if (/CONTEXT_COMPACTION_FAILED/i.test(rawMessage)) {- return result("CONTEXT_COMPACTION_FAILED", false);+ // The checkpoint guard fails before any provider request is sent, so the+ // stream timings and last HTTP status of the previous request say nothing+ // about it (#2494).+ return result("CONTEXT_COMPACTION_FAILED", false, { origin: "local" });}// Network failures never carry an HTTP status; probe before status logic so// "fetch failed" causes don't fall through to the generic bucket. The causediff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex d83c3caac..60597e840 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -9179,6 +9179,102 @@ describe("DesktopAgentRuntime per-turn context protection", () => {await runtime.dispose();});+ it("shrinks the retained-tail fallback until it fits a calibrated budget (#2494)", async () => {+ // A provider tokenizer that counts more tokens than the local estimate+ // (CJK text, for one) teaches the calibration a ratio above 1. The+ // fallback tail used to be sized by the raw estimate while the install+ // check used the calibrated one, so every summary failure past the hard+ // limit ended the turn with CONTEXT_COMPACTION_FAILED, on every retry.+ const onEvent = vi.fn();+ const host = {+ call: vi.fn(async (method: string) => {+ if (method === "project.instructions.resolve") return { entries: [] };+ if (method === "tools.execute") return { ok: true, content: "x ".repeat(6_000) };+ return undefined;+ }),+ onNotification: vi.fn(() => () => {}),+ };+ const runtime = createRuntime({+ host,+ onEvent,+ provider: {+ ...provider,+ modelConfig: { ...provider.modelConfig!, contextWindow: 128_000, maxTokens: 128_000 },+ },+ });+ const internal = runtime as any;+ let requests = 0;+ const usage = (input: number) => ({+ input,+ output: 50,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: input + 50,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ });+ internal.models = {+ streamSimple: (_model: unknown, context: any) => {+ requests += 1;+ const done = requests > 12;+ const chars =+ JSON.stringify(context.messages).length ++ String(context.systemPrompt ?? "").length ++ JSON.stringify(context.tools ?? []).length;+ const message = {+ ...assistantMessage({+ content: done+ ? [{ type: "text", text: "done" }]+ : [{ type: "toolCall", id: `read-${requests}`, name: "Read", arguments: { path: `f${requests}.ts` } }],+ stopReason: done ? "stop" : "toolUse",+ }),+ usage: usage(Math.round((chars / 4) * 1.8)),+ timestamp: Date.now(),+ } as AssistantMessage;+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "start", partial: message });+ stream.push({ type: "done", reason: done ? "stop" : "toolUse", message } as never);+ stream.end(message);+ });+ return stream;+ },+ completeSimple: async () => {+ throw new Error("summary relay unavailable");+ },+ };++ try {+ await runtime.prompt("Read every file.", "user-2494");++ const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);+ expect(events).toContainEqual(+ expect.objectContaining({ type: "compaction_end", ok: true, fallback: "retained_tail" }),+ );+ expect(events.filter((event) => event.type === "error")).toEqual([]);+ expect(requests).toBe(13);+ } finally {+ await runtime.dispose();+ }+ });++ it("names the checkpoint failure cause in the turn error (#2494)", async () => {+ const runtime = createRuntime();+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue({+ tokens: 225_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ });+ vi.spyOn(runtime as any, "performCompaction").mockImplementation(async () => {+ (runtime as any).emitCompactionFailure("threshold", 225_000, "summary relay unavailable");+ return false;+ });++ await expect((runtime as any).prepareNextTurn(nextTurn)).rejects.toThrow(+ "CONTEXT_COMPACTION_FAILED: unable to create a checkpoint before the next model request: summary relay unavailable",+ );+ await runtime.dispose();+ });+it("keeps manual compaction failures terminal instead of silently dropping context", async () => {const host = { call: vi.fn().mockResolvedValue(undefined) };const onEvent = vi.fn();diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex fead92e91..ff48fed14 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -752,6 +752,12 @@ const COMPACTION_FALLBACK_NOTICE_TOKENS = 512;* history than a successful checkpoint would (`fallbackRetainedTail`).*/const COMPACTION_FALLBACK_KEEP_RECENT_RATIO = 0.25;+/**+ * Smallest fraction of that window the recovery path shrinks to before it+ * gives up: seven halvings, enough for a calibrated estimate many times the+ * local one (`recoverCompactionFailure`, issue #2494).+ */+const COMPACTION_FALLBACK_MIN_TAIL_SCALE = 1 / 128;export const COMPACTION_FALLBACK_MARKER ="[automatic context recovery: older context was omitted after summary generation failed]";/** Stored in place of a carried-forward summary when a fallback had none. */@@ -2080,6 +2086,8 @@ export class DesktopAgentRuntime {private readonly activeTurnSettlements = new Map<string, Promise<void>>();/** The in-flight checkpoint was cut short by Stop/dispose, not by a failure. */private compactionAborted = false;+ /** Why the latest checkpoint attempt failed, for the turn error it causes. */+ private lastCompactionFailure?: string;/** Set by the `new_context` tool, consumed at the next turn boundary. */private pendingModelCompaction = false;/** One-shot request to finish the current turn at the next boundary. */@@ -7510,9 +7518,11 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}// Continuing would immediately issue the provider request that this// guard exists to prevent. The Agent wrapper converts this failure to- // the normal error/agent_end event sequence.+ // the normal error/agent_end event sequence. The checkpoint's own cause+ // rides along so the turn error says why (#2494).+ const cause = this.lastCompactionFailure;throw new Error(- "CONTEXT_COMPACTION_FAILED: unable to create a checkpoint before the next model request",+ `CONTEXT_COMPACTION_FAILED: unable to create a checkpoint before the next model request${cause ? `: ${cause}` : ""}`,);}context = this.rebuiltAgentContext();@@ -7578,6 +7588,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (this.compactionInProgress) return false;this.compactionInProgress = true;this.compactionAborted = false;+ this.lastCompactionFailure = undefined;const previous = this.agentActivity;this.setAgentActivity({phase: "compacting",@@ -7629,6 +7640,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// A checkpoint cut short by the user's Stop is not a failed compaction;// it reports under the abort code so the turn reads as stopped.const aborted = this.compactionAborted;+ if (!aborted) this.lastCompactionFailure = message;this.emit({type: "compaction_end",reason,@@ -7805,6 +7817,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theretentionMode: CompactionRetentionMode,budget: ContextBudget,failureReason: CompactionFailureReason,+ tailScale = 1,): ContextCompactionRecord {const previousSummary = preparation.previousSummary? boundedText(@@ -7827,6 +7840,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thebudget,maxSummaryChars,retentionMode,+ tailScale,);return this.createCheckpoint({@@ -7864,6 +7878,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thebudget: ContextBudget,maxSummaryChars: number,retentionMode: CompactionRetentionMode,+ tailScale: number,): AgentMessage[] {const summaryTokens = Math.ceil(maxSummaryChars / 4);const available = Math.max(@@ -7879,7 +7894,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the);return selectRecentTail(preparation.messagesToSummarize,- Math.min(target, available),+ Math.max(1, Math.floor(Math.min(target, available) * tailScale)),{ latestUserGoal: retentionMode === "active_turn" },);}@@ -8124,36 +8139,45 @@ Do not invent objections or turn speculative risks into blockers. Stop when thereturn false;}- const checkpoint = this.createFallbackCheckpoint(- fallbackPreparation,- throughMessageId,- Math.max(- 256,- Math.min(- COMPACTION_FALLBACK_MAX_SUMMARY_CHARS,- Math.floor(budget.hardLimit * 0.75),+ // The tail is sized from the local estimate, but the install check below+ // measures the calibrated one. A provider whose tokenizer counts more than+ // the estimate (CJK text, for one) makes the first window too large, and+ // failing here leaves every later turn at the same hard limit (#2494).+ // Halve the window until it fits; the newest message is always kept.+ for (let tailScale = 1; ; tailScale /= 2) {+ const checkpoint = this.createFallbackCheckpoint(+ fallbackPreparation,+ throughMessageId,+ Math.max(+ 256,+ Math.min(+ COMPACTION_FALLBACK_MAX_SUMMARY_CHARS,+ Math.floor(budget.hardLimit * 0.75),+ ),),- ),- retentionMode,- budget,- failureReason,- );- const persisted = await this.persistCheckpoint(- checkpoint,- reason,- willRetry,- true,- "retained_tail",- );- if (persisted === "persisted") return true;- if (persisted === "oversized") {- this.emitCompactionFailure(+ retentionMode,+ budget,+ failureReason,+ tailScale,+ );+ const persisted = await this.persistCheckpoint(+ checkpoint,reason,- checkpoint.tokensBefore,- "Automatic context recovery could not reduce the retained context below the safe model budget",+ willRetry,+ true,+ "retained_tail",);+ if (persisted === "persisted") return true;+ if (persisted === "failed") return false;+ if (tailScale <= COMPACTION_FALLBACK_MIN_TAIL_SCALE) {+ this.emitCompactionFailure(+ reason,+ checkpoint.tokensBefore,+ "Automatic context recovery could not reduce the retained context below the safe model budget",+ );+ return false;+ }}- return false;}private async generateCompaction(