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): give delegates the session's context budget
Zihao Peng56fd864cc59e
diff --git a/apps/desktop/test/context-compaction.test.mjs b/apps/desktop/test/context-compaction.test.mjsindex 2ce20be39..52f827126 100644--- a/apps/desktop/test/context-compaction.test.mjs+++ b/apps/desktop/test/context-compaction.test.mjs@@ -30,6 +30,10 @@ const [turns,styles,enLocale,+ subagent,+ subagentContext,+ contextBudget,+ delegationHistory,] = await Promise.all([read("../../../packages/shared/src/protocol.ts"),readSharedTypesSource(),@@ -48,6 +52,10 @@ const [read("../src/lib/assistant-turns.ts"),loadStyles(),read("../../../packages/i18n/src/locales/en/index.ts"),+ read("../../../packages/agent-runtime/src/subagent.ts"),+ read("../../../packages/agent-runtime/src/subagent-context.ts"),+ read("../../../packages/agent-runtime/src/context-budget.ts"),+ read("../../../packages/agent-runtime/src/delegation-history.ts"),]);test("context compaction is wired through protocol v11 and the manual IPC path", () => {@@ -108,6 +116,48 @@ test("the hard boundary is enforced by the host, with a model-side escape hatch"assert.match(hostPermissions, /"new_context"/);});+test("a delegate gets the session's turn-boundary budget protection (ADR 0299)", () => {+ // The delegate Agent wires the same hook the session does, and the budget+ // comes from the shared module evaluated against the run's resolved model.+ assert.match(subagent, /prepareNextTurnWithContext:\s*\(context, signal\)\s*=>/);+ assert.match(subagent, /from "\.\/context-budget\.js"/);+ assert.match(subagent, /contextBudgetFor\(/);+ // Terminal failure is the actionable delegate code, never the provider's+ // raw overflow text; the remap happens only after fallback had its chance.+ assert.match(subagent, /"SUBAGENT_CONTEXT_OVERFLOW"/);+ assert.match(subagent, /subagentContextOverflowError\(this\.provider\.modelId\)/);+ assert.match(subagent, /error\.code === "CONTEXT_TOO_LARGE"/);+ // Fallback alternatives are re-evaluated against their own window before+ // switching; one that cannot fit is skipped with the reason recorded.+ assert.match(subagent, /contextBudgetFor\(binding\.model, carried\)/);+ assert.match(+ subagent,+ /budget\.tokens >= budget\.hardLimit[\s\S]*?recordModelFailure\(identity/,+ );+ // The run result reports compaction and degradation additively, and the+ // lifecycle details the parent sees carry both flags (ADR 0299 decision 4).+ assert.match(subagent, /contextCompactions\?: number/);+ assert.match(subagent, /contextDegraded\?: boolean/);+ assert.match(runtime, /contextCompactions: record\.result\.contextCompactions/);+ assert.match(runtime, /contextDegraded: record\.result\.contextDegraded/);+ // A resumed chain is seeded within the delegate's own budget (decision 7):+ // the oldest tool call/result pairs leave first, and a stripped carrier+ // stops claiming "toolUse".+ assert.match(runtime, /budget: contextBudgetLimitsFor\(model\)/);+ assert.match(delegationHistory, /truncateSeededMessages/);+ assert.match(delegationHistory, /\.\.\.message, content, stopReason: "stop"/);+ // The compaction itself uses pi-agent-core's primitives, the session's+ // retention rule, and the degradation ladder of decision 4.+ assert.match(subagentContext, /prepareCompaction\(/);+ assert.match(subagentContext, /generateSummaryWithUsage\(/);+ assert.match(subagentContext, /contextBudgetFor\(input\.model/);+ assert.match(subagentContext, /delegateRetentionMode/);+ assert.match(subagentContext, /\? "active_turn"\s*: "completed_turn"/);+ assert.match(subagentContext, /degradedDelegateMessages/);+ // Delegate compaction is in-memory only: no host persistence, no transcript.+ assert.doesNotMatch(subagentContext, /appendCompaction|host\.call/);+});+test("every checkpoint is durable, not just the newest one", () => {// One transcript row per compaction needs the whole chain to survive a// restart, a rewrite, and a fork.@@ -131,7 +181,7 @@ test("a checkpoint carries only the active user message past the boundary", () =// The summary covers the whole boundary range. An in-progress turn carries// only its latest user message, while a completed turn carries no naked// historical user messages into the next task.- assert.match(runtime, /COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS = 20_000/);+ assert.match(contextBudget, /COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS = 20_000/);assert.match(runtime, /type CompactionRetentionMode = "active_turn" \| "completed_turn"/);assert.match(runtime, /retainedTailMode: retentionMode/);assert.match(runtime, /private codexShapedPreparation\(/);diff --git a/packages/agent-runtime/src/delegation-history.test.ts b/packages/agent-runtime/src/delegation-history.test.tsindex 998ee79c1..feaf544c9 100644--- a/packages/agent-runtime/src/delegation-history.test.ts+++ b/packages/agent-runtime/src/delegation-history.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from "vitest";+import { estimateTokens } from "@earendil-works/pi-agent-core";+import type { Message } from "@earendil-works/pi-ai";import { MAX_RESUMABLE_READ_LINES, type UiMessage } from "@pi-desktop/shared";+import {+ contextBudgetLimitsFor,+ type ContextBudgetLimits,+} from "./context-budget.js";import {chainRowsToMessages,extractReadFiles,@@ -27,6 +33,43 @@ function provider(): RuntimeProviderConfig {} as RuntimeProviderConfig;}+/** Limits whose hard limit the small fixture rows in this file never reach. */+function generousBudget(): ContextBudgetLimits {+ return contextBudgetLimitsFor({ contextWindow: 1_000_000, maxTokens: 32_000 });+}++/** Limits with an exact hard limit, for truncation tests. */+function budgetAt(hardLimit: number): ContextBudgetLimits {+ return { hardLimit, requestHeadroom: 0, keepRecentTokens: 0 };+}++/** Estimated size of a seeded list, the same heuristic the truncation applies. */+function seededTokens(messages: readonly Message[]): number {+ return messages.reduce((sum, message) => sum + estimateTokens(message), 0);+}++/**+ * Assert the provider-side pairing invariant: every tool result follows an+ * assistant carrying its call, every call has its result, and no assistant+ * carries nothing.+ */+function expectWellFormedPairs(messages: readonly Message[]): void {+ const callIds: string[] = [];+ const resultIds: string[] = [];+ for (const message of messages) {+ if (message.role === "assistant") {+ expect(message.content.length).toBeGreaterThan(0);+ for (const block of message.content) {+ if (block.type === "toolCall") callIds.push(block.id);+ }+ } else if (message.role === "toolResult") {+ expect(callIds).toContain(message.toolCallId);+ resultIds.push(message.toolCallId);+ }+ }+ expect([...resultIds].sort()).toEqual([...callIds].sort());+}+function delegateAssistant(id: string,content: string,@@ -211,6 +254,7 @@ describe("seedDelegateMessages", () => {rows,provider: provider(),model: buildProviderModel(provider()),+ budget: generousBudget(),});expect(messages[0]).toMatchObject({role: "user",@@ -251,6 +295,7 @@ describe("seedDelegateMessages", () => {rows,provider: provider(),model: buildProviderModel(provider()),+ budget: generousBudget(),});expect(messages.filter((message) => message.role === "user")).toHaveLength(1);});@@ -264,6 +309,7 @@ describe("seedDelegateMessages", () => {rows,provider: provider(),model: buildProviderModel(provider()),+ budget: generousBudget(),});expect(messages).toHaveLength(3);expect(messages[1]).toMatchObject({ role: "assistant", stopReason: "toolUse" });@@ -289,6 +335,7 @@ describe("seedDelegateMessages", () => {rows,provider: provider(),model: buildProviderModel(provider()),+ budget: generousBudget(),});const assistants = messages.filter((message) => message.role === "assistant");expect(assistants).toHaveLength(1);@@ -299,6 +346,235 @@ describe("seedDelegateMessages", () => {});});+describe("seedDelegateMessages budget truncation (ADR 0299 §7)", () => {+ /** ~1000 estimated tokens of tool output. */+ const BIG = "x".repeat(4000);+ /** ~500 estimated tokens of tool output. */+ const MEDIUM = "y".repeat(2000);++ function bigRead(toolCallId: string, text: string): UiMessage {+ return delegateTool(+ toolCallId,+ "Read",+ { path: `${toolCallId}.ts` },+ { content: [{ type: "text", text }] },+ "call-1",+ );+ }++ function seed(+ rows: UiMessage[],+ hardLimit: number,+ originalTask = "explore the parser",+ ): Message[] {+ return seedDelegateMessages({+ originalTask,+ rows,+ provider: provider(),+ model: buildProviderModel(provider()),+ budget: budgetAt(hardLimit),+ });+ }++ it("leaves a seed that fits entirely alone", () => {+ const rows: UiMessage[] = [+ delegateAssistant("a1", "looking", "call-1"),+ delegateTool("t1", "Read", { path: "a.ts" }, { content: "body" }, "call-1"),+ delegateAssistant("a2", "done", "call-1"),+ ];+ const messages = seed(rows, 1_000_000);+ expect(messages.map((message) => message.role)).toEqual([+ "user",+ "assistant",+ "toolResult",+ "assistant",+ ]);+ expectWellFormedPairs(messages);+ });++ it("drops the oldest tool result with its call before newer history", () => {+ const rows: UiMessage[] = [+ delegateAssistant("a1", "first look", "call-1"),+ bigRead("t1", BIG),+ delegateAssistant("a2", "second look", "call-1"),+ bigRead("t2", BIG),+ delegateAssistant("a3", "summary", "call-1"),+ ];+ const messages = seed(rows, 1050);++ expect(messages[0]).toMatchObject({+ role: "user",+ content: [{ type: "text", text: "explore the parser" }],+ });+ // The oldest pair is gone, call and result together; the carrier keeps its+ // text, and the newer pair survives untouched.+ expect(+ messages.some(+ (message) => message.role === "toolResult" && message.toolCallId === "t1",+ ),+ ).toBe(false);+ expect(+ messages.some(+ (message) =>+ message.role === "assistant" &&+ message.content.some(+ (block) => block.type === "toolCall" && block.id === "t1",+ ),+ ),+ ).toBe(false);+ expect(+ messages.some(+ (message) =>+ message.role === "assistant" &&+ message.content.some(+ (block) => block.type === "text" && block.text === "first look",+ ),+ ),+ ).toBe(true);+ // The stripped carrier keeps its text but no longer claims "toolUse" —+ // no call survives for that stopReason to refer to.+ const strippedCarrier = messages.find(+ (message) =>+ message.role === "assistant" &&+ message.content.some(+ (block) => block.type === "text" && block.text === "first look",+ ),+ );+ expect(strippedCarrier).toMatchObject({ stopReason: "stop" });+ expect(+ messages.some(+ (message) => message.role === "toolResult" && message.toolCallId === "t2",+ ),+ ).toBe(true);+ expectWellFormedPairs(messages);+ expect(seededTokens(messages)).toBeLessThan(1050);+ });++ it("drops parallel calls on one carrier as one unit", () => {+ const rows: UiMessage[] = [+ delegateAssistant("a1", "checking two files", "call-1"),+ bigRead("t1", MEDIUM),+ bigRead("t2", MEDIUM),+ delegateAssistant("a2", "both read", "call-1"),+ ];+ const messages = seed(rows, 100);++ const toolCallIds: string[] = [];+ for (const message of messages) {+ if (message.role !== "assistant") continue;+ for (const block of message.content) {+ if (block.type === "toolCall") toolCallIds.push(block.id);+ }+ }+ expect(toolCallIds).toEqual([]);+ expect(messages.some((message) => message.role === "toolResult")).toBe(false);+ // The carrier's text and the recent turn survive the drop.+ expect(+ messages.some(+ (message) =>+ message.role === "assistant" &&+ message.content.some(+ (block) =>+ block.type === "text" && block.text === "checking two files",+ ),+ ),+ ).toBe(true);+ expectWellFormedPairs(messages);+ expect(seededTokens(messages)).toBeLessThan(100);+ });++ it("removes a carrier left with nothing once its pair is dropped", () => {+ const rows: UiMessage[] = [+ // An orphan tool row gets a synthesized, text-free carrier.+ bigRead("t1", BIG),+ delegateAssistant("a2", "recent summary", "call-1"),+ ];+ const messages = seed(rows, 50);++ expect(messages.map((message) => message.role)).toEqual(["user", "assistant"]);+ expect(messages[1]).toMatchObject({ role: "assistant" });+ expectWellFormedPairs(messages);+ expect(seededTokens(messages)).toBeLessThan(50);+ });++ it("drops tool results before older plain history", () => {+ const rows: UiMessage[] = [+ delegateAssistant("a1", `old:${"a".repeat(2000)}`, "call-1"),+ delegateAssistant("a2", "reading", "call-1"),+ bigRead("t1", MEDIUM),+ delegateAssistant("a3", "done", "call-1"),+ ];+ const messages = seed(rows, 520);++ // The older plain text survives while the newer tool pair goes first.+ expect(+ messages.some(+ (message) =>+ message.role === "assistant" &&+ message.content.some(+ (block) => block.type === "text" && block.text.startsWith("old:"),+ ),+ ),+ ).toBe(true);+ expect(messages.some((message) => message.role === "toolResult")).toBe(false);+ expectWellFormedPairs(messages);+ expect(seededTokens(messages)).toBeLessThan(520);+ });++ it("drops whole older messages once no tool pairs remain", () => {+ const rows: UiMessage[] = [+ delegateAssistant("a1", `old:${"a".repeat(2000)}`, "call-1"),+ delegateAssistant("a2", `mid:${"b".repeat(2000)}`, "call-1"),+ delegateAssistant("a3", `new:${"c".repeat(2000)}`, "call-1"),+ ];+ const messages = seed(rows, 1010);++ expect(messages).toHaveLength(3);+ expect(messages[0]).toMatchObject({ role: "user" });+ const texts: string[] = [];+ for (const message of messages) {+ if (message.role !== "assistant") continue;+ for (const block of message.content) {+ if (block.type === "text") texts.push(block.text);+ }+ }+ // Oldest-first: the recent turns are the ones kept.+ expect(texts).toEqual([+ `mid:${"b".repeat(2000)}`,+ `new:${"c".repeat(2000)}`,+ ]);+ expect(seededTokens(messages)).toBeLessThan(1010);+ });++ it("seeds the brief alone when nothing else fits", () => {+ const rows: UiMessage[] = [+ delegateAssistant("a1", BIG, "call-1"),+ bigRead("t1", BIG),+ ];+ const messages = seed(rows, 20);++ expect(messages).toHaveLength(1);+ expect(messages[0]).toMatchObject({+ role: "user",+ content: [{ type: "text", text: "explore the parser" }],+ });+ expect(seededTokens(messages)).toBeLessThan(20);+ });++ it("keeps the brief even when it alone crosses the hard limit", () => {+ const brief = `task:${"x".repeat(200)}`;+ const rows: UiMessage[] = [delegateAssistant("a1", "small", "call-1")];+ const messages = seed(rows, 10, brief);++ // Truncation cannot go below the brief; a resume never loses its task.+ expect(messages).toHaveLength(1);+ expect(messages[0]).toMatchObject({+ role: "user",+ content: [{ type: "text", text: brief }],+ });+ });+});+describe("rebuildChainsFromTranscript", () => {it("groups resume links into one chain with the latest objective", () => {const transcript: UiMessage[] = [diff --git a/packages/agent-runtime/src/delegation-history.ts b/packages/agent-runtime/src/delegation-history.tsindex 29faa37fe..75c159a5f 100644--- a/packages/agent-runtime/src/delegation-history.ts+++ b/packages/agent-runtime/src/delegation-history.ts@@ -21,11 +21,13 @@* and api/replay details depend on the binding.*/+import { estimateTokens } from "@earendil-works/pi-agent-core";import type {AssistantMessage,Message,Model,Api,+ ToolCall,ToolResultMessage,UserMessage,} from "@earendil-works/pi-ai";@@ -36,6 +38,7 @@ import {type UiMessage,} from "@pi-desktop/shared";import { isRecord, timestampMs, usageToPi } from "./agent-messages.js";+import type { ContextBudgetLimits } from "./context-budget.js";import {apiBindingForProviderModel,type RuntimeProviderConfig,@@ -307,12 +310,20 @@ export function chainRowsToMessages();}-/** Seed a resumed run: original task as the first user turn, then history. */+/**+ * Seed a resumed run: original task as the first user turn, then history.+ *+ * The seed is truncated against the delegate's budget (ADR 0299 §7) so a+ * resumed run's first request fits its own window instead of overflowing on+ * arrival. Truncation drops the oldest tool results first and never splits a+ * call from its result; the task brief itself is always kept.+ */export function seedDelegateMessages(options: {originalTask: string;rows: readonly UiMessage[];provider: RuntimeProviderConfig;model: Model<Api>;+ budget: ContextBudgetLimits;}): Message[] {const history = chainRowsToMessages(options.rows, options.provider, options.model);const first: UserMessage = {@@ -330,7 +341,83 @@ export function seedDelegateMessages(options: {message.content[0].text === options.originalTask),);- return [first, ...rest];+ return truncateSeededMessages(+ [first, ...rest],+ options.budget.hardLimit,+ );+}++/**+ * Bring a seeded chain under the delegate's hard limit (ADR 0299 §7).+ *+ * `messages[0]` is the original task brief and is never dropped. The oldest+ * tool results go first: they are the bulkiest entries, and the delegate can+ * re-read a file but cannot reconstruct its most recent turns. A result always+ * leaves together with its call, and a carrier left with neither text nor+ * calls is removed too, so the replay never holds an orphaned `toolUse` /+ * `toolResult` pair (providers reject those). If stripping every pair is not+ * enough, whole messages go oldest-first until only the brief is left; a brief+ * that alone crosses the limit is kept as is, because a resume cannot start+ * with less than its task.+ *+ * Sizes are measured with the per-message heuristic rather than+ * `estimateContextTokens`: that estimator anchors on the last assistant's+ * recorded usage, which still counts the history this truncation drops, so the+ * anchor could never fall below the limit no matter how much is removed.+ */+function truncateSeededMessages(+ messages: Message[],+ hardLimit: number,+): Message[] {+ const kept = [...messages];+ const tokenCounts = kept.map((message) => estimateTokens(message));+ let total = tokenCounts.reduce((sum, count) => sum + count, 0);+ if (total < hardLimit) return kept;++ // Phase 1: strip tool call/result pairs, oldest first.+ for (let i = 1; i < kept.length && total >= hardLimit; ) {+ const message = kept[i];+ if (message.role !== "assistant") {+ i += 1;+ continue;+ }+ const callIds = new Set(+ message.content+ .filter((block): block is ToolCall => block.type === "toolCall")+ .map((block) => block.id),+ );+ if (callIds.size === 0) {+ i += 1;+ continue;+ }+ const content = message.content.filter((block) => block.type !== "toolCall");+ // A carrier whose calls are gone must not keep claiming "toolUse" — the+ // replay would hand the model a stopReason no provider produced (the same+ // rule chainRowsToMessages applies to failed rows above).+ const carrier: AssistantMessage | undefined =+ content.length > 0 ? { ...message, content, stopReason: "stop" } : undefined;+ const carrierTokens = carrier ? estimateTokens(carrier) : 0;+ // A carrier's results sit directly behind it, one per call, in order.+ let end = i + 1;+ while (end < kept.length) {+ const next = kept[end];+ if (next.role !== "toolResult" || !callIds.has(next.toolCallId)) break;+ total -= tokenCounts[end];+ end += 1;+ }+ total -= tokenCounts[i] - carrierTokens;+ kept.splice(i, end - i, ...(carrier ? [carrier] : []));+ tokenCounts.splice(i, end - i, ...(carrier ? [carrierTokens] : []));+ }++ // Phase 2: no pairs remain; drop whole messages oldest-first down to the+ // brief.+ for (let i = 1; i < kept.length && total >= hardLimit; ) {+ total -= tokenCounts[i];+ kept.splice(i, 1);+ tokenCounts.splice(i, 1);+ }+ return kept;}function toolResultFromUi(m: UiMessage, timestamp: number): ToolResultMessage {diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 5190d8143..e61e5daf7 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -134,6 +134,7 @@ import {} from "./provider-binding.js";import {contextBudgetFor,+ contextBudgetLimitsFor,retainedUserMessageBudget,type ContextBudget,} from "./context-budget.js";@@ -441,6 +442,14 @@ function delegationSummary(record: DelegationRecord): Record<string, unknown> {...(record.completedAt ? { completedAt: record.completedAt } : {}),...(record.result?.modelFailures ? { modelFailures: record.result.modelFailures } : {}),...(record.result?.error ? { error: record.result.error } : {}),+ // A delegate that compacted or lost history says so in its lifecycle+ // details, not only in the report text (ADR 0299, decision 4).+ ...(record.result?.contextCompactions+ ? { contextCompactions: record.result.contextCompactions }+ : {}),+ ...(record.result?.contextDegraded+ ? { contextDegraded: record.result.contextDegraded }+ : {}),...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),...(record.modelChangedFrom? { modelChangedFrom: record.modelChangedFrom }@@ -3845,11 +3854,16 @@ Delegation rules:if (!originalTask) return undefined;const rows = selectChainRows(this.transcriptHistory, chain);if (rows.length === 0) return undefined;+ // The seed is truncated against the delegate's own budget (ADR 0299 §7),+ // derived from the same model the resumed run will use, so the first+ // request fits the window instead of overflowing on arrival.+ const model = buildProviderModel(provider);return seedDelegateMessages({originalTask,rows,provider,- model: buildProviderModel(provider),+ model,+ budget: contextBudgetLimitsFor(model),});}diff --git a/packages/agent-runtime/src/subagent-context.test.ts b/packages/agent-runtime/src/subagent-context.test.tsnew file mode 100644index 000000000..f45303d19--- /dev/null+++ b/packages/agent-runtime/src/subagent-context.test.ts@@ -0,0 +1,440 @@+import { describe, expect, it } from "vitest";+import {+ createCompactionSummaryMessage,+ type AgentMessage,+ type PrepareNextTurnContext,+} from "@earendil-works/pi-agent-core";+import type {+ Api,+ AssistantMessage,+ Model,+ Models,+ ToolResultMessage,+ Usage,+ UserMessage,+} from "@earendil-works/pi-ai";+import {+ buildProviderModel,+ type RuntimeProviderConfig,+} from "./provider-binding.js";+import { contextBudgetFor } from "./context-budget.js";+import {+ degradedDelegateMessages,+ delegateRetentionMode,+ prepareDelegateTurnContext,+ subagentContextOverflowError,+} from "./subagent-context.js";++const provider: RuntimeProviderConfig = {+ id: "local",+ name: "Local",+ baseUrl: "http://127.0.0.1:11434/v1",+ modelId: "local-model",+ apiKey: "",+ authKind: "none",+ supportsReasoning: false,+ supportedThinkingLevels: ["off"],+};++/** A 4 096-token window whose safe budget lands at 2 048 tokens. */+function smallModel(): Model<Api> {+ return {+ ...buildProviderModel(provider),+ contextWindow: 4_096,+ maxTokens: 1_024,+ };+}++const ZERO_USAGE: Usage = {+ input: 0,+ output: 0,+ cacheRead: 0,+ cacheWrite: 0,+ totalTokens: 0,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+};++function userMessage(text: string): UserMessage {+ return { role: "user", content: text, timestamp: 1 };+}++function assistantText(text: string): AssistantMessage {+ return {+ role: "assistant",+ api: "openai-completions",+ provider: "local",+ model: "local-model",+ stopReason: "stop",+ timestamp: 1,+ usage: ZERO_USAGE,+ content: [{ type: "text", text }],+ };+}++function assistantToolCall(id: string, preamble = ""): AssistantMessage {+ return {+ ...assistantText(preamble),+ content: [+ ...(preamble ? [{ type: "text" as const, text: preamble }] : []),+ { type: "toolCall" as const, id, name: "Read", arguments: { path: "a.ts" } },+ ],+ };+}++function toolResult(text: string, toolCallId = "call-1"): ToolResultMessage {+ return {+ role: "toolResult",+ toolCallId,+ toolName: "Read",+ content: [{ type: "text", text }],+ isError: false,+ timestamp: 1,+ };+}++/** Fake `Models` registry whose summary completion is caller-controlled. */+function summaryModels(+ respond: () => AssistantMessage,+): { factory: () => Models; prompts: string[] } {+ const prompts: string[] = [];+ const factory = () =>+ ({+ completeSimple: async (+ _model: unknown,+ context: { messages: Array<{ content: unknown }> },+ ) => {+ const content = context.messages[0]?.content;+ prompts.push(+ typeof content === "string"+ ? content+ : Array.isArray(content)+ ? content+ .map((block) =>+ typeof block === "object" && block !== null && "text" in block+ ? String((block as { text: unknown }).text)+ : "",+ )+ .join("")+ : "",+ );+ return respond();+ },+ }) as unknown as Models;+ return { factory, prompts };+}++function summarySuccess(text: string): AssistantMessage {+ return {+ ...assistantText(text),+ usage: {+ ...ZERO_USAGE,+ input: 5,+ output: 2,+ totalTokens: 7,+ },+ };+}++function summaryFailure(errorMessage: string): AssistantMessage {+ return {+ ...assistantText(""),+ stopReason: "error",+ errorMessage,+ } as AssistantMessage;+}++function turnContext(+ overrides: Partial<PrepareNextTurnContext> = {},+): PrepareNextTurnContext {+ return {+ message: assistantText("done"),+ toolResults: [],+ context: { systemPrompt: "system", messages: [], tools: [] },+ newMessages: [],+ ...overrides,+ };+}++/** Messages that overflow the small model: brief plus ~750-token results. */+function overflowingMessages(brief: string): AgentMessage[] {+ return [+ userMessage(brief),+ assistantToolCall("call-1"),+ toolResult("a".repeat(3_000), "call-1"),+ assistantToolCall("call-2"),+ toolResult("b".repeat(3_000), "call-2"),+ assistantToolCall("call-3"),+ toolResult("c".repeat(3_000), "call-3"),+ ];+}++describe("delegateRetentionMode", () => {+ it("retains the active turn when tool results are pending", () => {+ expect(+ delegateRetentionMode(+ turnContext({ toolResults: [toolResult("ok")] }),+ ),+ ).toBe("active_turn");+ expect(+ delegateRetentionMode(+ turnContext({+ message: { ...assistantText(""), stopReason: "toolUse" },+ }),+ ),+ ).toBe("active_turn");+ });++ it("treats a settled turn as completed", () => {+ expect(delegateRetentionMode(turnContext())).toBe("completed_turn");+ });+});++describe("prepareDelegateTurnContext", () => {+ it("leaves a context below the hard limit untouched and never builds the summary registry", () => {+ const { factory, prompts } = summaryModels(() => summarySuccess("S"));+ let built = 0;+ return prepareDelegateTurnContext({+ messages: [userMessage("Find the permission dialog.")],+ model: smallModel(),+ taskBrief: "Find the permission dialog.",+ retentionMode: "active_turn",+ summaryModels: () => {+ built += 1;+ return factory();+ },+ signal: new AbortController().signal,+ }).then((outcome) => {+ expect(outcome).toEqual({ kind: "unchanged" });+ expect(built).toBe(0);+ expect(prompts).toHaveLength(0);+ });+ });++ it("compacts synchronously at the hard limit and retains the task brief of an active turn", async () => {+ const { factory, prompts } = summaryModels(() => summarySuccess("SUMMARY TEXT"));+ const outcome = await prepareDelegateTurnContext({+ messages: overflowingMessages("Read the three files."),+ model: smallModel(),+ taskBrief: "Read the three files.",+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("compacted");+ if (outcome.kind !== "compacted") return;+ expect(outcome.tokensBefore).toBeGreaterThan(0);+ expect(outcome.summaryUsage?.totalTokens).toBe(7);+ expect(outcome.messages[0]?.role).toBe("compactionSummary");+ expect(+ (outcome.messages[0] as { summary?: string }).summary,+ ).toContain("SUMMARY TEXT");+ // The active turn retains the latest user message — the task brief.+ expect(outcome.messages.at(-1)).toEqual(userMessage("Read the three files."));+ // The summary request covered the folded history, tool output included.+ expect(prompts).toHaveLength(1);+ expect(prompts[0]).toContain("Read the three files.");+ // Everything past the boundary fits under the hard limit again.+ const fit = contextBudgetFor(smallModel(), outcome.messages);+ expect(fit.tokens).toBeLessThan(fit.hardLimit);+ });++ it("retains no bare user message across a completed turn", async () => {+ const { factory } = summaryModels(() => summarySuccess("SUMMARY TEXT"));+ const outcome = await prepareDelegateTurnContext({+ messages: overflowingMessages("Read the three files."),+ model: smallModel(),+ taskBrief: "Read the three files.",+ retentionMode: "completed_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("compacted");+ if (outcome.kind !== "compacted") return;+ expect(outcome.messages).toHaveLength(1);+ expect(outcome.messages[0]?.role).toBe("compactionSummary");+ });++ it("threads a prior in-memory summary into the next compaction instead of re-summarizing it", async () => {+ const { factory, prompts } = summaryModels(() => summarySuccess("SUMMARY TWO"));+ const messages: AgentMessage[] = [+ createCompactionSummaryMessage("SUMMARY ONE", 3_000, 1),+ assistantToolCall("call-9"),+ toolResult("d".repeat(3_000), "call-9"),+ assistantToolCall("call-10"),+ toolResult("e".repeat(3_000), "call-10"),+ assistantToolCall("call-11"),+ toolResult("f".repeat(3_000), "call-11"),+ ];+ const outcome = await prepareDelegateTurnContext({+ messages,+ model: smallModel(),+ taskBrief: "Read the three files.",+ retentionMode: "completed_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("compacted");+ expect(prompts[0]).toContain("<previous-summary>");+ expect(prompts[0]).toContain("SUMMARY ONE");+ expect(prompts[0]).not.toContain("<summary>");+ });++ it("degrades to the task brief plus the recent tail when the summary cannot be generated", async () => {+ const { factory } = summaryModels(() => summaryFailure("invalid api key"));+ const outcome = await prepareDelegateTurnContext({+ messages: overflowingMessages("Read the three files."),+ model: smallModel(),+ taskBrief: "Read the three files.",+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("degraded");+ if (outcome.kind !== "degraded") return;+ expect(outcome.messages[0]).toEqual(userMessage("Read the three files."));+ expect(outcome.messages.length).toBeGreaterThan(1);+ expect(outcome.messages[1]?.role).not.toBe("toolResult");+ });++ it("degrades when the compacted context still exceeds the hard limit", async () => {+ // A summary that is itself larger than the safe budget.+ const { factory } = summaryModels(() => summarySuccess("s".repeat(12_000)));+ const outcome = await prepareDelegateTurnContext({+ messages: overflowingMessages("Read the three files."),+ model: smallModel(),+ taskBrief: "Read the three files.",+ retentionMode: "completed_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("degraded");+ });++ it("reports the terminal overflow when even the task brief does not fit", async () => {+ const { factory } = summaryModels(() => summaryFailure("invalid api key"));+ const brief = "x".repeat(12_000);+ const outcome = await prepareDelegateTurnContext({+ messages: overflowingMessages(brief),+ model: smallModel(),+ taskBrief: brief,+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("overflow");+ if (outcome.kind !== "overflow") return;+ expect(outcome.hardLimit).toBe(2_048);+ expect(outcome.tokens).toBeGreaterThanOrEqual(outcome.hardLimit);+ });++ it("rethrows an abort that lands mid-summary instead of degrading", async () => {+ const controller = new AbortController();+ const { factory } = summaryModels(() => {+ controller.abort();+ return { ...summaryFailure("aborted"), stopReason: "aborted" } as AssistantMessage;+ });+ await expect(+ prepareDelegateTurnContext({+ messages: overflowingMessages("Read the three files."),+ model: smallModel(),+ taskBrief: "Read the three files.",+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: controller.signal,+ }),+ ).rejects.toThrow("aborted while compacting");+ });+});++describe("degradedDelegateMessages", () => {+ it("keeps the brief plus the most recent complete exchanges that still fit", () => {+ const brief = userMessage("Survey the module.");+ const exchange = (id: string, text: string): AgentMessage[] => [+ assistantToolCall(id),+ toolResult(text, id),+ ];+ const messages: AgentMessage[] = [+ brief,+ ...exchange("call-1", "a".repeat(3_000)),+ ...exchange("call-2", "b".repeat(3_000)),+ ...exchange("call-3", "c".repeat(3_000)),+ ];++ const degraded = degradedDelegateMessages(messages, "Survey the module.", smallModel());++ // ~750 tokens per result against a 2 048-token budget: the oldest+ // exchange drops, and the kept suffix starts on an assistant, so every+ // retained result still has its call.+ expect(degraded).toEqual([brief, ...messages.slice(3)]);+ });++ it("drops an orphaned leading tool result when its call no longer fits", () => {+ const brief = userMessage("Survey the module.");+ // The assistant's own bulk is what pushes the budget over, so the cut+ // lands between the call and its result.+ const call = assistantToolCall("call-1", "p".repeat(5_200));+ const result = toolResult("r".repeat(3_000), "call-1");++ const degraded = degradedDelegateMessages(+ [brief, call, result],+ "Survey the module.",+ smallModel(),+ );++ expect(degraded).toEqual([brief]);+ });++ it("skips failed and empty assistant rows when keeping the recent tail", () => {+ const brief = userMessage("Survey the module.");+ const failed = {+ ...assistantText("partial"),+ stopReason: "error",+ } as AssistantMessage;++ const degraded = degradedDelegateMessages(+ [brief, failed, assistantText("final answer")],+ "Survey the module.",+ smallModel(),+ );++ expect(degraded?.map((message) => message.role)).toEqual(["user", "assistant"]);+ expect(degraded?.[1]).toEqual(assistantText("final answer"));+ });++ it("returns undefined when the brief alone crosses the hard limit", () => {+ const brief = "x".repeat(12_000);+ expect(+ degradedDelegateMessages([userMessage(brief)], brief, smallModel()),+ ).toBeUndefined();+ });+});++describe("carried-context budget check", () => {+ it("measures a carried context against a candidate model's own window", () => {+ const fits = contextBudgetFor(smallModel(), [userMessage("small")]);+ expect(fits).toEqual(+ expect.objectContaining({ tokens: 2, hardLimit: 2_048 }),+ );+ const tooBig = contextBudgetFor(smallModel(), [+ userMessage("y".repeat(12_000)),+ ]);+ expect(tooBig.tokens).toBeGreaterThanOrEqual(tooBig.hardLimit);+ });+});++describe("subagentContextOverflowError", () => {+ it("names the code the parent can act on and the ways out", () => {+ const error = subagentContextOverflowError("local-model");+ expect(error.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");+ expect(error.message).toContain("local-model");+ expect(error.message).toContain("Narrow the task");+ expect(error.message).toContain("larger context window");+ expect(error.message).toContain("read less at once");+ });+});diff --git a/packages/agent-runtime/src/subagent-context.ts b/packages/agent-runtime/src/subagent-context.tsnew file mode 100644index 000000000..42d1fd2fe--- /dev/null+++ b/packages/agent-runtime/src/subagent-context.ts@@ -0,0 +1,431 @@+/**+ * A delegate's own context budget: turn-boundary compaction, degradation, and+ * the terminal overflow a parent can act on (ADR 0299, decisions 2-6).+ *+ * The session compacts through durable checkpoints owned by host-core; a+ * delegate compacts only its in-memory model context for the duration of its+ * run (ADR 0299, Consequences). Nothing in this module writes to host-core,+ * the transcript, or the parent's context: the input is the delegate agent's+ * message list, and the output is the replacement list the run installs.+ *+ * The budget formula is the shared one from `context-budget.ts`, evaluated+ * against the model the run actually resolved — a definition's `maxTokens`+ * pin included — so a delegate never gets a looser boundary than its parent+ * would compute for the same model.+ */++import {+ BACKGROUND_CONTEXT,+ createCompactionSummaryMessage,+ estimateTokens,+ generateSummaryWithUsage,+ prepareCompaction,+ withAbortSignal,+ type AgentMessage,+ type CompactionSettings,+ type CompactionSummaryMessage,+ type Entry,+ type MessageEntry,+ type PrepareNextTurnContext,+ type ThinkingLevel,+} from "@earendil-works/pi-agent-core";+import type {+ Api,+ Model,+ Models,+ Usage,+ UserMessage,+} from "@earendil-works/pi-ai";+import {+ contextBudgetFor,+ contextBudgetLimitsFor,+ retainedUserMessageBudget,+ type ContextBudget,+ type ContextBudgetModel,+} from "./context-budget.js";+import {+ COMPACTION_SUMMARY_RETRY_POLICY,+ estimateSummaryPromptTokens,+ reduceSummaryInput,+ type CompactionSummaryInput,+} from "./compaction-summary-input.js";+import { withCompactionRequestHeaders } from "./compaction-request.js";+import {+ DEFAULT_MAX_TOKENS,+ createProviderModels,+ type RuntimeProviderConfig,+} from "./provider-binding.js";++/**+ * Safety margin between the summary prompt and the model window. The session+ * applies the same 2 048-token reserve; the constant is local because+ * `runtime.ts` owns its private copy and importing the runtime would cycle.+ */+const DELEGATE_SUMMARY_PROMPT_SAFETY_TOKENS = 2_048;++/** Marker replacing the elided middle of a retained delegate task brief. */+const DELEGATE_RETENTION_TRUNCATION_MARKER =+ "\n\n[delegate context truncated: this message crossed the retained context budget]\n\n";++/** Which side of a turn boundary the delegate sits on (ADR 0136's rule). */+export type DelegateRetentionMode = "active_turn" | "completed_turn";++/**+ * A boundary with pending tool results retains the active turn's instruction;+ * a completed turn carries no naked historical user message into what follows.+ */+export function delegateRetentionMode(+ turn: PrepareNextTurnContext,+): DelegateRetentionMode {+ return (turn.toolResults?.length ?? 0) > 0 ||+ turn.message?.stopReason === "toolUse"+ ? "active_turn"+ : "completed_turn";+}++/** What a delegate turn boundary decided about the next request's context. */+export type DelegateTurnUpdate =+ | { kind: "unchanged" }+ | {+ kind: "compacted";+ messages: AgentMessage[];+ tokensBefore: number;+ summaryUsage?: Usage;+ }+ | { kind: "degraded"; messages: AgentMessage[]; tokensBefore: number }+ | { kind: "overflow"; tokens: number; hardLimit: number };++/**+ * The terminal failure the parent model can act on (ADR 0299, decision 5):+ * not the provider's raw overflow sentence, but the three changes that would+ * actually let a retry succeed.+ */+export function subagentContextOverflowError(modelId: string): {+ code: "SUBAGENT_CONTEXT_OVERFLOW";+ message: string;+} {+ return {+ code: "SUBAGENT_CONTEXT_OVERFLOW",+ message:+ `The delegated task does not fit in the context window of model "${modelId}", even after compaction and history reduction. ` ++ "Narrow the task, delegate to a model with a larger context window, or make the delegate read less at once.",+ };+}++/**+ * Build the provider registry a delegate summary request goes through, with+ * the same header seam the session's compaction uses: pi-agent-core hands the+ * collection to its own request path, so provider and session headers have to+ * ride on it.+ */+export function delegateSummaryModels(+ provider: RuntimeProviderConfig,+ model: Model<Api>,+ sessionId: string,+): Models {+ return withCompactionRequestHeaders(+ createProviderModels(provider, model),+ provider,+ sessionId,+ );+}++/**+ * Decide the context for a delegate's next provider request. Below the hard+ * limit nothing changes; at or above it the run compacts synchronously, then+ * degrades, and only then reports the overflow its caller turns into+ * `SUBAGENT_CONTEXT_OVERFLOW`.+ */+export async function prepareDelegateTurnContext(input: {+ /** The delegate agent's current in-memory messages. */+ messages: AgentMessage[];+ /** The model this run resolved, per-definition `maxTokens` included. */+ model: Model<Api>;+ /** The delegated instruction, kept verbatim through degradation. */+ taskBrief: string;+ retentionMode: DelegateRetentionMode;+ /** Built lazily: a boundary below the limit never pays for a registry. */+ summaryModels: () => Models;+ thinkingLevel?: ThinkingLevel;+ signal: AbortSignal;+}): Promise<DelegateTurnUpdate> {+ const budget = contextBudgetFor(input.model, input.messages);+ if (budget.tokens < budget.hardLimit) return { kind: "unchanged" };++ const compacted = await compactDelegateContext(input, budget);+ if (compacted) {+ const fit = contextBudgetFor(input.model, compacted.messages);+ if (fit.tokens < fit.hardLimit) {+ return { kind: "compacted", ...compacted };+ }+ }++ const degraded = degradedDelegateMessages(+ input.messages,+ input.taskBrief,+ input.model,+ );+ if (degraded) {+ return { kind: "degraded", messages: degraded, tokensBefore: budget.tokens };+ }+ return { kind: "overflow", tokens: budget.tokens, hardLimit: budget.hardLimit };+}++/**+ * Compact through pi-agent-core's primitives, shaped the way the session's+ * checkpoint is shaped: pi's three contiguous ranges are summarized as one,+ * and the retained tail is rebuilt from the retention mode rather than pi's+ * token cut, so no tool call can be orphaned from its result. Returns+ * undefined when no summary could be produced — the caller degrades instead.+ */+async function compactDelegateContext(+ input: {+ messages: AgentMessage[];+ model: Model<Api>;+ retentionMode: DelegateRetentionMode;+ summaryModels: () => Models;+ thinkingLevel?: ThinkingLevel;+ signal: AbortSignal;+ },+ budget: ContextBudget,+): Promise<+ { messages: AgentMessage[]; tokensBefore: number; summaryUsage?: Usage } | undefined+> {+ // A prior in-memory compaction left its summary message at the head; it+ // threads into the next summary as `previousSummary` instead of being+ // summarized a second time.+ const head = input.messages[0];+ const previousSummary = isCompactionSummary(head) ? head.summary : undefined;+ const compactable =+ previousSummary === undefined ? input.messages : input.messages.slice(1);+ const prepared = prepareCompaction(delegateMessageEntries(compactable), {+ enabled: true,+ reserveTokens: budget.requestHeadroom,+ keepRecentTokens: budget.keepRecentTokens,+ } satisfies CompactionSettings);+ if (!prepared.ok || !prepared.value) return undefined;+ const messagesToSummarize = [+ ...prepared.value.messagesToSummarize,+ ...prepared.value.turnPrefixMessages,+ ...prepared.value.retainedTail,+ ];+ if (messagesToSummarize.length === 0) return undefined;++ let summaryInput: CompactionSummaryInput = {+ messagesToSummarize,+ turnPrefixMessages: [],+ isSplitTurn: false,+ previousSummary,+ };+ // The summary request itself must fit the window; shrink it one bounded+ // step the way the session does, then give up to the degradation path.+ if (delegateSummaryInputExceedsBudget(summaryInput, input.model, budget)) {+ const reduced = reduceSummaryInput(summaryInput);+ if (+ !reduced ||+ delegateSummaryInputExceedsBudget(reduced, input.model, budget)+ ) {+ return undefined;+ }+ summaryInput = reduced;+ }++ const result = await generateSummaryWithUsage(+ summaryInput.messagesToSummarize,+ input.summaryModels(),+ input.model,+ budget.requestHeadroom,+ undefined,+ summaryInput.previousSummary,+ input.thinkingLevel,+ COMPACTION_SUMMARY_RETRY_POLICY,+ undefined,+ withAbortSignal(input.signal, BACKGROUND_CONTEXT),+ );+ if (!result.ok) {+ if (result.error.code === "aborted" || input.signal.aborted) {+ // A stop that landed mid-summary is an abort, not a compaction failure.+ throw new Error("Turn aborted while compacting context");+ }+ return undefined;+ }+ return {+ messages: [+ createCompactionSummaryMessage(+ result.value.text,+ prepared.value.tokensBefore,+ Date.now(),+ ),+ ...retainedDelegateTail(+ messagesToSummarize,+ input.retentionMode,+ budget,+ ),+ ],+ tokensBefore: prepared.value.tokensBefore,+ summaryUsage: result.value.usage,+ };+}++/**+ * The degraded context (ADR 0299, decision 4): the original task brief plus+ * the most recent message(s) that still fit, everything older discarded.+ * Returns undefined when even the brief alone crosses the hard limit — the+ * terminal case its caller reports as `SUBAGENT_CONTEXT_OVERFLOW`.+ *+ * Sizing uses the per-message character estimate rather than+ * `estimateContextTokens`: a kept assistant message carries the usage block of+ * the request that produced it, which describes the pre-degradation context+ * and would condemn every rebuilt context to still look oversized.+ */+export function degradedDelegateMessages(+ messages: AgentMessage[],+ taskBrief: string,+ model: ContextBudgetModel,+): AgentMessage[] | undefined {+ const limits = contextBudgetLimitsFor(model);+ const briefIndex = messages.findIndex((message) => message.role === "user");+ const brief: UserMessage =+ briefIndex >= 0+ ? (messages[briefIndex] as UserMessage)+ : { role: "user", content: taskBrief, timestamp: Date.now() };+ const briefTokens = estimateTokens(brief);+ if (briefTokens >= limits.hardLimit) return undefined;++ const pool = messages.slice(briefIndex + 1);+ const suffix: AgentMessage[] = [];+ let tokens = briefTokens;+ for (let index = pool.length - 1; index >= 0; index -= 1) {+ const message = pool[index];+ if (!isDelegateContextMessage(message)) continue;+ const cost = estimateTokens(message);+ if (tokens + cost >= limits.hardLimit) break;+ suffix.unshift(message);+ tokens += cost;+ }+ // Tool results are contiguous with the assistant that requested them, so a+ // suffix cut can only start inside that pair on the result side. Dropping+ // leading results keeps the pair rule intact: no result reaches a provider+ // without its call, and no call without its results.+ while (suffix[0]?.role === "toolResult") suffix.shift();+ return [brief, ...suffix];+}++/**+ * The retained tail of a delegate compaction. An active turn keeps only the+ * latest user message — for a delegate, the task brief — truncated rather+ * than dropped when it alone crosses the retention budget (the session's+ * newest-first selection degenerates to exactly this for one candidate).+ */+function retainedDelegateTail(+ messages: AgentMessage[],+ mode: DelegateRetentionMode,+ budget: ContextBudget,+): AgentMessage[] {+ if (mode !== "active_turn") return [];+ const latestUser = messages+ .filter((message): message is UserMessage => message.role === "user")+ .at(-1);+ if (!latestUser) return [];+ return [+ truncateDelegateUserMessage(latestUser, retainedUserMessageBudget(budget)),+ ];+}++function truncateDelegateUserMessage(+ message: UserMessage,+ tokenBudget: number,+): UserMessage {+ const text = delegateUserMessageText(message);+ const maxChars = Math.max(1, tokenBudget) * 4;+ if (text.length <= maxChars) return message;+ if (maxChars <= DELEGATE_RETENTION_TRUNCATION_MARKER.length) {+ return {+ ...message,+ content: DELEGATE_RETENTION_TRUNCATION_MARKER.trim().slice(0, maxChars),+ };+ }+ const retainedChars = maxChars - DELEGATE_RETENTION_TRUNCATION_MARKER.length;+ const headChars = Math.ceil(retainedChars * 0.75);+ const tailChars = retainedChars - headChars;+ return {+ ...message,+ content: `${text.slice(0, headChars)}${DELEGATE_RETENTION_TRUNCATION_MARKER}${+ tailChars > 0 ? text.slice(-tailChars) : ""+ }`,+ };+}++/** Flatten a user message the way the session's checkpoint truncation does. */+function delegateUserMessageText(message: UserMessage): string {+ if (typeof message.content === "string") return message.content;+ return message.content+ .map((block) =>+ block.type === "text"+ ? block.text+ : `[${block.type} content omitted from checkpoint]`,+ )+ .join("\n");+}++/** The summary prompt must fit beside the model's own output budget. */+function delegateSummaryInputExceedsBudget(+ input: CompactionSummaryInput,+ model: Model<Api>,+ budget: ContextBudget,+): boolean {+ const contextWindow = budget.hardLimit + budget.requestHeadroom;+ const modelOutputBudget = Math.min(+ Math.floor(budget.requestHeadroom * 0.8),+ Math.max(1, Math.round(model.maxTokens || DEFAULT_MAX_TOKENS)),+ );+ const limit = Math.max(+ 1,+ contextWindow - modelOutputBudget - DELEGATE_SUMMARY_PROMPT_SAFETY_TOKENS,+ );+ return estimateSummaryPromptTokens(input) > limit;+}++/**+ * Synthetic message-entry chain for `prepareCompaction`. A delegate has no+ * durable entry log, so the cut point is computed over its in-memory messages+ * wrapped in the entry shape pi's compaction expects.+ */+function delegateMessageEntries(messages: AgentMessage[]): Entry[] {+ let parentId: string | null = null;+ return messages.map((message, index) => {+ const id = `delegate-context-${index}`;+ const entry: MessageEntry = {+ type: "message",+ id,+ parentId,+ seq: index,+ timestamp: messageTimestamp(message),+ message,+ };+ parentId = id;+ return entry;+ });+}++function messageTimestamp(message: AgentMessage): number {+ const timestamp = (message as { timestamp?: unknown }).timestamp;+ return typeof timestamp === "number" ? timestamp : Date.now();+}++function isCompactionSummary(+ message: AgentMessage | undefined,+): message is CompactionSummaryMessage {+ return message?.role === "compactionSummary";+}++/** Failed, aborted, and empty assistants are transcript rows, not context. */+function isDelegateContextMessage(message: AgentMessage): boolean {+ return (+ message.role !== "assistant" ||+ (message.stopReason !== "error" &&+ message.stopReason !== "aborted" &&+ message.stopReason !== "deferred" &&+ message.content.length > 0)+ );+}diff --git a/packages/agent-runtime/src/subagent-fallback.test.ts b/packages/agent-runtime/src/subagent-fallback.test.tsindex 6e00d5743..3009fb256 100644--- a/packages/agent-runtime/src/subagent-fallback.test.ts+++ b/packages/agent-runtime/src/subagent-fallback.test.ts@@ -241,4 +241,32 @@ describe("subagent model fallback over real transport", () => {expect(g.requests.every((request) => request.reasoning_effort === undefined)).toBe(true);});+ it("skips a fallback whose window cannot hold the carried context (ADR 0299)", async () => {+ const f = await fixture({ failureStatus: { primary: 413 } });+ const base = f.provider("secondary");+ const small: RuntimeProviderConfig = {+ ...base,+ modelConfig: {+ ...genericModelConfig("secondary", base.baseUrl!),+ contextWindow: 4_096,+ maxTokens: 1_024,+ },+ };+ const result = await f.run({+ initialMessages: [{ role: "user", content: "z".repeat(12_000), timestamp: 1 }],+ fallbackModels: [{ key: "secondary/secondary", provider: small }],+ });+ // The carried context (~3 000 tokens) never reaches the 2 048-token safe+ // budget of the fallback, so the fallback is skipped without a request and+ // the run reports the actionable overflow instead of the raw provider text.+ expect(result.status).toBe("failed");+ expect(f.requests.map((request) => request.model)).toEqual(["primary"]);+ expect(result.error?.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");+ expect(result.error?.message).toContain("larger context window");+ expect(result.modelFailures).toEqual([+ expect.objectContaining({ model: "primary/primary", code: "CONTEXT_TOO_LARGE" }),+ expect.objectContaining({ model: "secondary/secondary", code: "SUBAGENT_CONTEXT_OVERFLOW" }),+ ]);+ });+});diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.tsindex c07a3a81e..4cc0e96d2 100644--- a/packages/agent-runtime/src/subagent.test.ts+++ b/packages/agent-runtime/src/subagent.test.ts@@ -536,6 +536,149 @@ describe("SubagentRun watchdogs", () => {});});+describe("SubagentRun context budget (ADR 0299)", () => {+ it("wires the delegate's turn boundary through prepareNextTurnWithContext", () => {+ const { run } = createRun();++ expect(typeof run.agent.prepareNextTurnWithContext).toBe("function");+ });++ it("remaps a provider context overflow no fallback could absorb", async () => {+ const { run } = createRun();+ const failure = {+ ...assistantMessage({ content: [], stopReason: "error" }),+ errorMessage: "prompt is too long: 300000 tokens",+ };+ const state = { messages: [] as Array<Record<string, unknown>> };+ run.agent = {+ state,+ prompt: vi.fn(async () => {+ state.messages = [{ role: "user", content: "task" }, failure];+ run.handleEvent({ type: "message_start", message: failure });+ run.handleEvent({ type: "message_end", message: failure });+ }),+ waitForIdle: vi.fn(async () => undefined),+ abort: vi.fn(),+ };++ const result = await (run as unknown as SubagentRun).run();++ expect(result.status).toBe("failed");+ expect(result.error?.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");+ expect(result.error?.message).toContain("larger context window");+ expect(result.error?.message).not.toContain("prompt is too long");+ expect(result.report).toContain("Narrow the task");+ });++ it("keeps the boundary guard's overflow code instead of classifying its thrown text", () => {+ const { run } = createRun();+ run.pendingContextOverflow = {+ code: "SUBAGENT_CONTEXT_OVERFLOW",+ message: "degraded context still does not fit",+ };++ run.handleEvent({+ type: "message_end",+ message: {+ ...assistantMessage({ content: [], stopReason: "error" }),+ errorMessage: "degraded context still does not fit",+ },+ });++ expect(run.streamError).toEqual({+ code: "SUBAGENT_CONTEXT_OVERFLOW",+ message: "degraded context still does not fit",+ });+ expect(run.pendingContextOverflow).toBeUndefined();+ });++ it("skips a fallback whose window cannot hold the carried context", () => {+ const small: RuntimeProviderConfig = {+ ...provider,+ id: "small",+ modelId: "small-model",+ modelConfig: {+ source: "generic",+ name: "small-model",+ baseUrl: provider.baseUrl ?? "",+ reasoning: false,+ input: ["text"],+ contextWindow: 4_096,+ maxTokens: 1_024,+ },+ };+ const { run } = createRun({+ fallbackModels: [{ key: "small/small-model", provider: small }],+ });+ const brief = { role: "user", content: "y".repeat(12_000), timestamp: 1 };+ const failure = {+ ...assistantMessage({ content: [], stopReason: "error" }),+ errorMessage: "prompt is too long",+ };+ run.agent.state.messages = [brief, failure];+ run.streamError = { code: "CONTEXT_TOO_LARGE", message: "prompt is too long" };++ const switched = run.useNextModel();++ expect(switched).toBe(false);+ expect(run.agent.state.model.id).toBe("local-model");+ expect(run.modelFailures).toEqual([+ expect.objectContaining({+ model: "local/local-model",+ code: "CONTEXT_TOO_LARGE",+ }),+ expect.objectContaining({+ model: "small/small-model",+ code: "SUBAGENT_CONTEXT_OVERFLOW",+ }),+ ]);+ });++ it("carries the uncompacted context onto a fallback whose window fits", () => {+ const big: RuntimeProviderConfig = {+ ...provider,+ id: "big",+ modelId: "big-model",+ };+ const { run, events } = createRun({+ fallbackModels: [{ key: "big/big-model", provider: big }],+ });+ const brief = { role: "user", content: "y".repeat(12_000), timestamp: 1 };+ const failure = {+ ...assistantMessage({ content: [], stopReason: "error" }),+ errorMessage: "prompt is too long",+ };+ run.agent.state.messages = [brief, failure];+ run.streamError = { code: "CONTEXT_TOO_LARGE", message: "prompt is too long" };++ const switched = run.useNextModel();++ expect(switched).toBe(true);+ expect(run.agent.state.model.id).toBe("big-model");+ // Only the failed assistant row is dropped; nothing is compacted away.+ expect(run.agent.state.messages).toEqual([brief]);+ expect(run.streamError).toBeUndefined();+ expect(events.some((event) => event.event.type === "message_end")).toBe(true);+ });++ it("reports compactions and degradation on the run result", () => {+ const { run } = createRun();+ run.contextCompactions = 2;+ run.contextDegraded = true;++ const result = run.result("completed", "Done.");++ expect(result.contextCompactions).toBe(2);+ expect(result.contextDegraded).toBe(true);+ expect(result.report).toContain("older working history was discarded");++ const clean = createRun();+ const cleanResult = clean.run.result("completed", "Done.");+ expect(cleanResult.contextCompactions).toBeUndefined();+ expect(cleanResult.contextDegraded).toBeUndefined();+ expect(cleanResult.report).toBe("Done.");+ });+});describe("SubagentRun retries before fallback", () => {it.each([429, 503])("exhausts the shared retry budget before switching after HTTP %s", async (status) => {diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.tsindex 09db5f093..c4687f247 100644--- a/packages/agent-runtime/src/subagent.ts+++ b/packages/agent-runtime/src/subagent.ts@@ -26,8 +26,10 @@ import {type AfterToolCallContext,type AfterToolCallResult,type AgentEvent,+ type AgentLoopTurnUpdate,type AgentMessage,type AgentTool,+ type PrepareNextTurnContext,} from "@earendil-works/pi-agent-core";import type { AssistantMessage } from "@earendil-works/pi-ai";import {@@ -53,6 +55,13 @@ import {import type { RuntimeProviderConfig } from "./provider-binding.js";import { clampThinkingLevel } from "./thinking-level.js";import { subagentModelBinding, type SubagentProviderRetryState } from "./subagent-model-binding.js";+import { contextBudgetFor } from "./context-budget.js";+import {+ delegateRetentionMode,+ delegateSummaryModels,+ prepareDelegateTurnContext,+ subagentContextOverflowError,+} from "./subagent-context.js";import {classifyProviderError,delayWithAbort,@@ -91,6 +100,10 @@ export type SubagentRunResult = {toolCalls: number;usage?: MessageUsage;modelFailures?: Array<{ model: string; code: string; message: string }>;+ /** In-memory context compactions the run needed (ADR 0299). */+ contextCompactions?: number;+ /** True when the run had to discard working history without a summary. */+ contextDegraded?: boolean;error?: { code: string; message: string };};@@ -199,6 +212,11 @@ export class SubagentRun {private toolCalls = 0;private usage?: MessageUsage;private streamError?: { code: string; message: string };+ private contextCompactions = 0;+ private contextDegraded = false;+ /** Set when the turn-boundary guard throws because even the degraded+ * context does not fit; the synthetic stream error keeps this code. */+ private pendingContextOverflow?: { code: "SUBAGENT_CONTEXT_OVERFLOW"; message: string };private pendingProviderRetry?: ReturnType<typeof classifyAgentError>;private providerRetryInProgress = false;private providerTransientRetryAttempt = 0;@@ -223,6 +241,11 @@ export class SubagentRun {streamFn: binding.streamFn,getApiKey: binding.getApiKey,convertToLlm,+ // The same turn-boundary context protection the session has (ADR 0299):+ // re-estimate at each boundary, compact before the next request, degrade+ // before failing. The budget derives from this run's resolved model.+ prepareNextTurnWithContext: (context, signal) =>+ this.prepareNextTurn(context, signal),afterToolCall: async (context) => this.afterToolCall(context),initialState: {systemPrompt: opts.systemPrompt,@@ -274,13 +297,10 @@ export class SubagentRun {if (caughtError.code === "TURN_ABORTED") {return this.result("aborted", "The delegated task was aborted.");}- return this.result("failed", "", {- code: caughtError.code,- message: caughtError.message,- });+ return this.result("failed", "", this.terminalError(caughtError));}if (this.streamError) {- return this.result("failed", "", this.streamError);+ return this.result("failed", "", this.terminalError(this.streamError));}if (!this.lastReportText.trim()) {return this.result("failed", "", {@@ -292,14 +312,72 @@ export class SubagentRun {}private modelBinding() {+ return this.bindingFor(this.provider, this.thinkingLevel);+ }++ private bindingFor(+ provider: RuntimeProviderConfig,+ thinkingLevel: SubagentThinkingLevel,+ ) {return subagentModelBinding({- provider: this.provider,- thinkingLevel: this.thinkingLevel,+ provider,+ thinkingLevel,sessionId: this.opts.sessionId,maxTokens: this.opts.definition.maxTokens,}, this.retryState);}+ /**+ * Shape the delegate's next in-run turn, mirroring the session's+ * `prepareNextTurn` (ADR 0299, decisions 2-4). A compaction rewrites only+ * this agent's in-memory messages; nothing is persisted anywhere.+ */+ private async prepareNextTurn(+ turn: PrepareNextTurnContext,+ signal?: AbortSignal,+ ): Promise<AgentLoopTurnUpdate | undefined> {+ const outcome = await prepareDelegateTurnContext({+ messages: this.agent.state.messages,+ model: this.agent.state.model,+ taskBrief: this.opts.task,+ retentionMode: delegateRetentionMode(turn),+ summaryModels: () =>+ delegateSummaryModels(+ this.provider,+ this.agent.state.model,+ this.opts.sessionId,+ ),+ thinkingLevel: this.agent.state.thinkingLevel,+ signal: signal ?? this.runSignal(),+ });+ if (outcome.kind === "unchanged") return undefined;+ if (outcome.kind === "overflow") {+ // The Agent wrapper converts this throw into the normal error/agent_end+ // sequence; `message_end` picks the pending overflow up so the run+ // surfaces SUBAGENT_CONTEXT_OVERFLOW instead of a classified provider+ // error, and `useNextModel` still gets its fallback pass first.+ this.pendingContextOverflow = subagentContextOverflowError(+ this.provider.modelId,+ );+ throw new Error(this.pendingContextOverflow.message);+ }+ this.agent.state.messages = outcome.messages;+ if (outcome.kind === "compacted") {+ this.contextCompactions += 1;+ const summaryUsage = usageFromPi(outcome.summaryUsage);+ this.usage = addUsage(this.usage, summaryUsage);+ } else {+ this.contextDegraded = true;+ }+ return {+ context: {+ systemPrompt: this.agent.state.systemPrompt,+ messages: this.agent.state.messages,+ tools: this.agent.state.tools,+ },+ };+ }+/** Continue the same agent at the failed request; never replay completed tools. */private useNextModel(): boolean {if (this.runSignal().aborted || !this.streamError || this.streamError.code === "TURN_ABORTED") return false;@@ -309,6 +387,10 @@ export class SubagentRun {// failures, cancellation, and unexpected internal exceptions do not.if (failed?.role !== "assistant" || failed.stopReason !== "error") return false;this.recordModelFailure(`${this.provider.id}/${this.provider.modelId}`, this.streamError);+ // What an alternative would actually carry: the current context minus the+ // failed assistant row (ADR 0299 decision 6 re-evaluates it against each+ // alternative's own window before switching).+ const carried = this.agent.state.messages.slice(0, -1);while (this.fallbackIndex < this.opts.fallbackModels.length) {const next = this.opts.fallbackModels[this.fallbackIndex++];if (!next.provider) {@@ -321,15 +403,27 @@ export class SubagentRun {const identity = `${next.provider.id}/${next.provider.modelId}`;if (this.attemptedModels.has(identity)) continue;this.attemptedModels.add(identity);- this.provider = next.provider;const requested = this.opts.definition.thinkingLevel ?? this.opts.inheritedThinkingLevel ?? this.opts.thinkingLevel;- this.thinkingLevel = requested === "omit" ? "omit" : clampThinkingLevel(this.provider, requested);- const binding = this.modelBinding();+ const thinking = requested === "omit" ? "omit" : clampThinkingLevel(next.provider, requested);+ const binding = this.bindingFor(next.provider, thinking);+ // An alternative whose window cannot hold the carried context would fail+ // identically to the model it replaces; skip it with the reason recorded+ // instead of burning the slot on the same overflow.+ const budget = contextBudgetFor(binding.model, carried);+ if (budget.tokens >= budget.hardLimit) {+ this.recordModelFailure(identity, {+ code: "SUBAGENT_CONTEXT_OVERFLOW",+ message: `The carried context (~${budget.tokens} tokens) does not fit this model's safe budget (${budget.hardLimit} tokens).`,+ });+ continue;+ }+ this.provider = next.provider;+ this.thinkingLevel = thinking;this.agent.state.model = binding.model;this.agent.state.thinkingLevel = binding.agentThinkingLevel;this.agent.streamFunction = binding.streamFn;this.agent.getApiKey = binding.getApiKey;- this.agent.state.messages = this.agent.state.messages.slice(0, -1);+ this.agent.state.messages = carried;this.streamError = undefined;this.providerTransientRetryAttempt = 0;this.providerRateLimitRetryAttempt = 0;@@ -406,6 +500,19 @@ export class SubagentRun {}}+ /**+ * The failure the parent receives once no fallback can proceed. A provider+ * overflow is remapped to the actionable delegate code (ADR 0299, decision+ * 5) — but only here, after `useNextModel` had its chance, so a larger+ * fallback window still rescues the run.+ */+ private terminalError(error: { code: string; message: string }): { code: string; message: string } {+ if (error.code === "CONTEXT_TOO_LARGE" || error.code === "SUBAGENT_CONTEXT_OVERFLOW") {+ return subagentContextOverflowError(this.provider.modelId);+ }+ return error;+ }+private result(status: SubagentRunStatus,report: string,@@ -422,6 +529,11 @@ export class SubagentRun {`The ${name} subagent failed after ${this.turns} turn(s): ${error?.message ?? "unknown error"}.`,...(body ? ["Its last output was:", body] : []),].join("\n\n");+ // A degraded run must say so, or the parent would read a partial answer+ // as a complete one (ADR 0299, decision 4).+ const degradationNote = this.contextDegraded+ ? "Note: this subagent's context exceeded its model's window and older working history was discarded without a summary, so this report may be incomplete."+ : undefined;return {agentName: name,modelId: this.provider.modelId,@@ -429,12 +541,15 @@ export class SubagentRun {status,report: boundedReport([...this.modelFailures.map((failure) => `Model ${failure.model} failed (${failure.code}): ${failure.message}`),+ ...(degradationNote ? [degradationNote] : []),text,].join("\n\n")),turns: this.turns,toolCalls: this.toolCalls,...(this.usage ? { usage: this.usage } : {}),...(this.modelFailures.length ? { modelFailures: [...this.modelFailures] } : {}),+ ...(this.contextCompactions > 0 ? { contextCompactions: this.contextCompactions } : {}),+ ...(this.contextDegraded ? { contextDegraded: true } : {}),...(error ? { error } : {}),};}@@ -571,22 +686,31 @@ export class SubagentRun {let classifiedError: ReturnType<typeof classifyAgentError> | undefined;let retryAttempt: number | undefined;if (failed) {- const raw =- typeof (message as { errorMessage?: unknown }).errorMessage === "string"- ? ((message as { errorMessage?: string }).errorMessage as string)- : "provider stream failed";- classifiedError = withProviderFetchFailure(- classifyProviderError(raw, this.retryState.status),- this.retryState.failure,- );- retryAttempt = this.claimProviderRetry(classifiedError, "stream");- if (retryAttempt !== undefined) {- this.pendingProviderRetry = classifiedError;+ const overflow = this.pendingContextOverflow;+ this.pendingContextOverflow = undefined;+ if (overflow) {+ // The boundary guard threw after degradation still did not fit.+ // The synthetic failure message carries the thrown text; keep the+ // actionable code instead of classifying it as a provider error.+ this.streamError = overflow;} else {- this.streamError = {- code: classifiedError.code,- message: classifiedError.message,- };+ const raw =+ typeof (message as { errorMessage?: unknown }).errorMessage === "string"+ ? ((message as { errorMessage?: string }).errorMessage as string)+ : "provider stream failed";+ classifiedError = withProviderFetchFailure(+ classifyProviderError(raw, this.retryState.status),+ this.retryState.failure,+ );+ retryAttempt = this.claimProviderRetry(classifiedError, "stream");+ if (retryAttempt !== undefined) {+ this.pendingProviderRetry = classifiedError;+ } else {+ this.streamError = {+ code: classifiedError.code,+ message: classifiedError.message,+ };+ }}}const messageUsage = usageFromPi(message.usage);