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(runtime): guard context and delegation recovery (#970 #971)
vastsab4614d246cd6
diff --git a/docs/adr/0064-codex-parity-context-compaction.md b/docs/adr/0064-codex-parity-context-compaction.mdindex e6e9545fa..e7dee1deb 100644--- a/docs/adr/0064-codex-parity-context-compaction.md+++ b/docs/adr/0064-codex-parity-context-compaction.md@@ -1,6 +1,6 @@# ADR 0064: Codex-parity context compaction-- Status: Accepted+- Status: Accepted (automatic trigger amended by D623 / issue #970)- Date: 2026-08-06- Deciders: PI-Desktop core- Amends: ADR 0061 / ADR 0030 / D158 / D200; amended by ADR 0136@@ -61,9 +61,11 @@ retained-tail recovery, ADR 0061's model-window-derived budgets, and ADR 0061's`pendingBackgroundCheckpoint`, `backgroundCompaction`, `backgroundAbort`,`checkpointBaselineTokens`, `backgroundLimit`, and the three call sites in`tool_execution_start`, `prompt()`, and the run `finally`.- `prepareNextTurn()` re-estimates the budget and compacts synchronously when- the total crosses `hardLimit`. The increment-scoped trigger goes with it —- there is no longer a second threshold for it to guard.+ `prompt()` and `prepareNextTurn()` re-estimate at their pre-request+ boundaries and compact synchronously when the estimate reaches+ `floor(hardLimit * 0.9)`. There is no background checkpoint. `hardLimit`+ remains the non-negotiable request safety guard; failed compaction below it+ may continue, but no request is issued at or above it.2. **Codex's retained shape.** `codexShapedPreparation()` keeps`prepareCompaction()`'s cut point (and therefore its turn-boundary andsplit-turn handling), then folds `turnPrefixMessages` and `retainedTail` back@@ -92,8 +94,10 @@ retained-tail recovery, ADR 0061's model-window-derived budgets, and ADR 0061's4. **`new_context` is back.** The tool is parameterless and carries Codex'sdescription verbatim; executing it only sets `pendingModelCompaction` andreturns the family's rollover message. `prepareNextTurn()` compacts when- `pendingModelCompaction || tokens >= hardLimit`, matching Codex's- `should_roll_over`. The name is synchronized across `activeTools()`,+ the model requested `new_context` or the estimate reaches+ `floor(hardLimit * 0.9)`, matching the `should_roll_over` turn boundary.+ `hardLimit` remains the final request guard (D623). The name is synchronized+ across `activeTools()`,`isCoreTool()`, the contract-mode allowlists, and the host-coreno-confirmation allowlist (`crates/host-core/src/permissions.rs`), where itreplaces `"CompactContext"`.@@ -163,9 +167,11 @@ compaction controls and still ignores persisted `contextCompaction` values- Model context after a compaction is much smaller and much lossier: noassistant reasoning and no tool output survives except through the summary.The visible transcript is untouched, so nothing is lost to the user.-- The summary input is now the entire compacted range rather than the range- minus the tail, so each summary request is larger than under ADR 0061 — but- there are fewer of them, because the trigger is one hard edge again.+- The summary input covers the entire compacted range rather than the range+ minus the tail, so each summary request remains larger than under ADR 0061.+- The 90% safety trigger intentionally pays for some additional summaries to+ reduce provider-side context overflows; `hardLimit` remains the fail-closed+ backstop.- Compaction is auditable from the transcript again, restoring ADR 0030'svisibility property that ADR 0061 reversed.- Every compaction interrupts the user with a warning. This is intended: only@@ -213,3 +219,12 @@ against "one summary request" from a settings row.- `codex-rs/core/src/compact.rs`, `compact_token_budget.rs`,`session/token_budget.rs`, `tools/handlers/new_context_window_spec.rs`(behavioral reference)+## Amendment (2026-09-23, D623 / issue #970): Earlier inline compaction trigger++The inline-only lifecycle is unchanged. Automatic compaction now starts at 90%+of the derived safe budget from both new-prompt preflight and in-run turn-boundary+checks. This leaves a deterministic margin for estimator drift and growth during+the preceding model/tool turn. A failed soft-trigger compaction may proceed only+while the context remains below `hardLimit`; at or above the hard boundary the+runtime still blocks the provider request. No settings, background work, host+protocol, or storage semantics are added.diff --git a/docs/adr/0299-subagent-context-budget.md b/docs/adr/0299-subagent-context-budget.mdindex b096a03fb..821d0423f 100644--- a/docs/adr/0299-subagent-context-budget.md+++ b/docs/adr/0299-subagent-context-budget.md@@ -76,13 +76,16 @@ protection at all.3. **Turn-boundary compaction for delegates.** `SubagentRun` wires`prepareNextTurnWithContext`. At a delegate turn boundary the run- re-estimates its own context; at or above `hardLimit` it compacts- synchronously before the next provider request, using the `prepareCompaction`- and `generateSummary` primitives `@earendil-works/pi-agent-core` 0.85.1- already exports. Retention follows the parent's rule (ADR 0136): a boundary- with pending tool results retains as an active turn, a completed turn- retains as a completed turn. There is no pre-computation and no second- threshold, matching ADR 0064 clause 1.+ re-estimates its own context; automatic compaction starts at+ `floor(hardLimit * 0.9)` (the shared threshold in ADR 0064) before the next+ provider request. The hard limit remains a final guard: if compaction is+ disabled or cannot reduce the context below budget, the next request is+ rejected rather than sent over budget. Compaction uses the+ `prepareCompaction` and `generateSummary` primitives+ `@earendil-works/pi-agent-core` 0.85.1 already exports. Retention follows the+ parent's rule (ADR 0136): a boundary with pending tool results retains as an+ active turn, a completed turn retains as a completed turn. There is no+ pre-computation.4. **Degradation before failure.** When a summary cannot be generated, or thecompacted context still exceeds `hardLimit`, the run keeps the original taskdiff --git a/docs/adr/README.md b/docs/adr/README.mdindex a04a8822d..3309e19d0 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -87,7 +87,7 @@ Each ADR includes:| 0061 | Imperceptible background context compaction | Accepted (amends 0030 / 0049; clauses 2/4/6/7/8 amended by 0064) || 0062 | Bounded Subagents Behind a Task Tool | Accepted for implementation (`maxTurns` clause withdrawn by 0253) || 0063 | A Managed Surface for Global Subagent Definitions | Accepted for implementation (`maxTurns` field withdrawn by 0253) |-| 0064 | Codex-parity context compaction | Accepted (amends 0061 / 0030) |+| 0064 | Codex-parity context compaction | Accepted (amended by D623 / issue #970: 90% inline trigger) || 0065 | Smooth shell layout and stream feedback | Accepted for implementation || 0066 | Empty home direct bottom composer | Accepted for implementation (amends D111) || 0067 | ChatGPT-inspired empty-home starter guidance | Superseded by D206 |diff --git a/docs/spec/00-baseline.md b/docs/spec/00-baseline.mdindex f720905a8..b8fecb293 100644--- a/docs/spec/00-baseline.md+++ b/docs/spec/00-baseline.md@@ -223,3 +223,6 @@ details:The frozen protocol remains v9 and storage schema remains v10. Future changesmust preserve the automated M6 scenarios E2E-104 through E2E-117 or update therelevant decision record before changing the contract.+> D623 / ADR 0064 amends the inline automatic compaction trigger to 90% of+> the derived hard budget. The hard limit remains the final provider-request+> guard; no background compaction or storage/protocol change is introduced.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 544ed9a9a..829b7efe2 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -383,15 +383,16 @@ entries. The desktop runtime owns when they run and how the result crosses theRust storage boundary; OpenCode DCP is an AGPL-3.0 behavioral reference only,not a linked or copied dependency.-Compaction follows Codex's mechanism (ADR 0064): it always happens inline at a-turn boundary, the model can request it through `new_context`, every compaction-adds a transcript row and raises one warning toast, and there is no-pre-computation anywhere.+Compaction follows Codex's mechanism (ADR 0064, amended by D623): it remains+inline at turn boundaries, and the model can request it through `new_context`.+Automatic compaction starts at 90% of the derived `hardLimit`; there is no+background pre-computation.pi 0.84.4+ invokes `prepareNextTurn` only when the loop will start anotherassistant turn in the same run — including between a completed tool batch and-the follow-up model request. A new user prompt still compacts before its first-provider request through `automaticCompactionNeeded` in `prompt()`.+the follow-up model request. A new user prompt is checked before its first+provider request through `automaticCompactionNeeded` in `prompt()`, including+the pending user message.For every pi loop turn:@@ -399,22 +400,22 @@ For every pi loop turn:results for that turn are complete2. PI-Desktop rebuilds the context from the full transcript plus the newestvalid checkpoint and estimates the next request budget-3. below the hard boundary, and with no pending model request, the next turn- proceeds unchanged-4. at or above the hard boundary, or when the model called `new_context`,+3. below 90% of `hardLimit`, and with no pending model request, the next turn+ proceeds unchanged (a budget reminder may be added to that request)+4. at or above the 90% trigger, or when the model called `new_context`,compaction runs synchronously before the next provider request. In thesummary family, generation is mandatory; the runtime preflights the summaryinput against the model window, reduces it once, and then splits a range thatstill does not fit into chunks that each do, so a prompt too large for onerequest is summarized by several (ADR 0302). An automatic summary failure- first attempts a deterministic retained-tail checkpoint, while manual- compaction still reports `CONTEXT_COMPACTION_FAILED`+ first attempts a deterministic retained-tail checkpoint. If a soft-trigger+ compaction fails but the request remains below `hardLimit`, the unchanged+ context may proceed; once the hard boundary is reached, failure is terminal.5. successful generation or deterministic recovery first appends thecheckpoint through host-core, then installs its summary plus the applicable- retained tail as the runtime context for the next provider request; a- hard-boundary checkpoint is re-estimated before it is persisted and again- before continuation, and cannot authorize the next request unless it is- below the hard budget+ retained tail as the runtime context for the next provider request; every+ checkpoint is re-estimated before persistence and continuation, and cannot+ authorize a request at or above the hard budgetCheckpoint generation and installation are separate operations.`buildCheckpoint` runs the preparation, budget preflight, and summary request@@ -498,29 +499,37 @@ installed: one when the remaining budget falls toone at 2,000 tokens remaining, telling it to write down whatever must survive.Neither reminder is persisted or shown in the transcript.-The hard boundary is the model context window minus request headroom.-Headroom is the maximum of a 16,384-token reserve floor, model maximum output-capped at 25% of the context window, and a 5% safety margin. The reserve floor-is itself capped at half the window. The cut-point target passed to pi is-derived from the model window as 20% of the hard budget clamped to+The hard boundary is the model context window minus request headroom. Automatic+compaction starts at 90% of `hardLimit`; this deterministic margin is not+configurable. Headroom is the maximum of a 16,384-token reserve floor, model+maximum output capped at 25% of the context window, and a 5% safety margin. The+reserve floor is itself capped at half the window. The cut-point target passed+to pi is derived from the model window as 20% of the hard budget clamped to8,000–64,000 tokens, then capped at half the hard budget; it decides where the-boundary falls, not what survives it. The active-user retention limit is 20,000-tokens, capped at half the hard budget so retention alone cannot fill a small-window and leave the summary no room. A fallback's window is capped by 25% of-the hard budget and by the room the carried-forward summary and the recovery-notice leave, so recovery cannot install a checkpoint the guard rejects. None of-these values are configurable.+boundary falls, not what survives it. The active-user retention limit is+20,000 tokens, capped at half the hard budget so retention alone cannot fill a+small window and leave the summary no room. A fallback's window is capped by+25% of the hard budget and by the room the carried-forward summary and the+recovery notice leave, so recovery cannot install a checkpoint the guard+rejects. None of these values are configurable.**Estimate calibration (D606).** Every threshold above is compared against one-number, and that number is corrected against what requests actually cost. pi's-`estimateContextTokens` anchors on the last assistant usage and estimates-everything after it as `chars / 4`: that constant under-counts CJK text, and-with no anchor left it omits the system prompt and the tool schemas, which the-next request still pays for. The two errors are measured and applied-separately — the per-character bias as a scale-free ratio over the guessed-tail, and an unanchored residual as a ratio only for observations taken at a-comparable scale (0.5×–2× of the estimate), otherwise as the observed overhead-capped at 32,000 tokens.+number, corrected against observed request usage. pi's `estimateContextTokens`+anchors on the last assistant usage and estimates everything after it as+`chars / 4`: that constant under-counts CJK text, and with no anchor left it+omits system/tool overhead. The budget also computes the output-cap estimator+over non-system conversation messages plus the current system prompt and active+tool schemas. System-transcript rows are metadata snapshots of that same prompt+and are excluded from this component, so the request estimate counts the prompt+and schemas exactly once. The budget uses the larger of this full-request+estimate and the calibrated message estimate. This is a hard floor before the+first calibration sample and prevents counting overhead twice after an+unanchored residual has learned it.++The calibration still measures the two errors separately — per-character bias+as a scale-free ratio over the guessed tail, and an unanchored residual as a+ratio only for observations taken at a comparable scale (0.5×–2× of the+message estimate), otherwise as the observed overhead capped at 32,000 tokens.The correction is asymmetric because this number gates compaction: upwardapplies once three observations exist, downward needs three agreeing samples,@@ -925,20 +934,23 @@ duration only covers starting the background work.duration-timeout a delegate. `idle-timeout` / `max-duration` frontmatter stillparses so old documents load, but those values are not armed. A delegate runsuntil it finishes, fails, is `TaskStop`'d, or the user Stops / the runtime is-disposed. The parent agent judges whether to-cancel via `TaskStop`; a one-line heartbeat (who, status, elapsed, turns, last-tool) is what it has to go on while the delegate is running.+disposed. The parent agent judges whether to cancel via `TaskStop`; a one-line+heartbeat (who, status, elapsed, turns, last tool) is what it has to go on while+the delegate is running.When the parent stops calling tools while delegates are still running, theruntime swallows that `agent_end`, keeps the durable turn open, waits for the-delegates, and prompts the parent with their reports. Ending the parent loop-does not abort them.+delegates, and prompts the parent with their reports. Every terminal result+resolves the parent wait before best-effort transcript publication; a failed+`SubagentRun` initialization returns a tool error and never leaves a running+record. User Stop and runtime disposal also abort the parent wait signal, so+they can end the parent turn even if a delegate ignores its abort. Ending the+parent loop does not otherwise abort delegates.Fatal provider/stream errors (including exhausted HTTP 429) and parent abortsretain their existing `failed` and `aborted` outcomes. A terminal parent error-also aborts leftover delegates,-skips the resume prompt, and returns the session to idle so Continue is not-`AGENT_BUSY` (D352).+also aborts leftover delegates, skips the resume prompt, and returns the+session to idle so Continue is not `AGENT_BUSY` (D352).**Resumable delegations (ADR 0279).** `Task` accepts an optional `resume`parameter carrying the `delegationId` of a settled delegation in the same@@ -1046,28 +1058,26 @@ track the effective alternative, including after settlement and reload. If allalternatives fail, the result remains `failed` with the final provider error.See [ADR subagent-model-fallback](../../adr/subagent-model-fallback.md).-**Context budget and compaction (ADR 0299).** A delegate has the same+**Context budget and compaction (ADR 0299, D623).** A delegate has the samewindow protection the session has, derived the same way. The budget comesfrom the model the run actually resolved — a `Task.model` override, adefinition pin, or the inherited session model — through the sharedderivation of §5.1, so `hardLimit` is that window minus the same requestheadroom and a per-definition `maxTokens` cap participates as the output-budget. At a delegate turn boundary the run re-estimates its own context and,-at or above `hardLimit`, compacts synchronously before the next provider-request, with the retention mode chosen from the same lifecycle rule as the-session: a boundary that still has pending tool results retains as an active-turn, a completed one as a completed turn. There is no pre-computation and no-second threshold.--When a summary cannot be generated, or the compacted context still exceeds-the budget, the run degrades: it keeps the original task brief plus the most-recent message(s), discards the rest of its history, continues, and records-that it was degraded, so the report and the lifecycle details say the-delegate lost history rather than presenting a complete answer. When even-that does not fit, the run fails with `SUBAGENT_CONTEXT_OVERFLOW`-(not retriable) naming what the parent can change — narrow the task,-delegate to a model with a larger window, read less at once — instead of-forwarding the provider's overflow text.+budget. At a delegate turn boundary the run re-estimates its own context and+starts compaction at `floor(hardLimit * 0.9)`, before the next provider+request. A compaction result must still fit below `hardLimit`; that remains+the non-negotiable provider-request guard. The retention mode follows the+same lifecycle rule as the session, and there is no pre-computation.++When a summary cannot be generated or installed below the hard limit, the run+degrades: it keeps the original task brief plus the most recent message(s),+discards the rest of its history, continues, and records that it was degraded,+so the report and lifecycle details say the delegate lost history rather than+presenting a complete answer. When even that does not fit, the run fails with+`SUBAGENT_CONTEXT_OVERFLOW` (not retriable) naming what the parent can change —+narrow the task, delegate to a model with a larger window, read less at once —+instead of forwarding the provider's overflow text.An ordered alternative (**Ordered model fallback**, above) is re-evaluatedagainst its own window before it is attempted: an alternative whose budgetdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 44249df78..2bdca4dc0 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -9098,6 +9098,10 @@ This test plan spec is accepted when:- Click **Continue** and expect the app to append the localized continuationprompt (`Continue the user's unfinished task.` / `继续用户未完成的任务`) to thesame session and start the next turn without truncating the failed turn.+- Activate the localized **Dismiss** action. Expect the error card to disappear+ from the current transcript view while its underlying error message and raw+ diagnostic data remain unchanged; navigating away and back in the same app+ runtime keeps the dismissal.### US-UI-61 Assistant context summary + retry (D103, D184, D244, D347)@@ -10041,25 +10045,35 @@ This test plan spec is accepted when:node and the `TaskStop` row both read `stopped` (not `running`). End theturn and reload the session; confirm the card is not labelled workingand does not keep ticking elapsed.+ 11. Inject synchronous `SubagentRun` initialization failure; confirm the+ `Task` result is an error and `TaskList` has no permanently running row.+ 12. In a runtime fixture, make settled-row publication throw and confirm the+ parent's idle auto-resume still returns the report. Stop a parent blocked+ in auto-resume while a child ignores abort; confirm the parent ends and+ reports idle without a timeout loop.- **Expected**: `Task` returns immediately with a `delegationId` and the parentkeeps working; `TaskWait` converges with per-delegation reports and statuses;- `TaskList`/`TaskStop` drive the lifecycle; a `TaskStop` result and a finished- turn never leave a live “Subagent working” card; builtin `fixer` inherits the- selected session permission mode, so `auto` also covers explicit external- paths without a duplicate authorization prompt while `ask` and- `accept-edits` retain their approval boundaries; a global definition's- declared scope is dropped; the per-session running cap of 10 is enforced; no- delegate outlives its turn; reloaded transcripts keep their delegation- topology.+ every terminal child state wakes the parent even if transcript publication+ fails. A synchronous child initialization failure returns a tool error and+ leaves no `running` delegation. User Stop/Dispose abort the parent wait as+ well as delegates, and cancelled sessions do not remain `AGENT_BUSY` solely+ because a child is still settling. `TaskList`/`TaskStop` drive the lifecycle;+ a `TaskStop` result and a finished turn never leave a live “Subagent working”+ card; builtin `fixer` inherits the selected session permission mode, so+ `auto` also covers explicit external paths without a duplicate authorization+ prompt while `ask` and `accept-edits` retain their approval boundaries; a+ global definition's declared scope is dropped; the per-session running cap+ of 10 is enforced; no delegate outlives its turn; reloaded transcripts keep+ their delegation topology.- **Specs linked**: `03-runtime/02-agent-runtime.md` §5f/§5f.1/§7.1,- `03-runtime/03-tools-and-permissions.md` §10.2, `08-meta/decisions-log.md`- (D242 amends D231), ADR 0089 and ADR 0100+ `03-runtime/03-tools-and-permissions.md` §10.2,+ `08-meta/decisions-log.md` (D242 amends D231), ADR 0089 and ADR 0100- **Acceptance**: C (conversation), E (tools & permissions), F (persistence),Security, Quality- **Milestone**: M6+-- **Status**: Draft (unit coverage in `packages/agent-runtime`- `runtime.test.ts` subagent suite and host-core `rpc/mod.rs` delegate-scope- tests; desktop journey pending)+- **Status**: Unit coverage includes synchronous initialization failure,+ completion-publication failure, and Stop during parent auto-resume in+ `packages/agent-runtime/src/runtime.test.ts`; desktop journey pending#### E2E-162 / E2E-173: Delegate workflow scrolling@@ -10852,32 +10866,46 @@ This test plan spec is accepted when:#### E2E-164: Context compaction preserves the active task boundary- **Preconditions**: A provider fixture can complete multiple sequential tasks,- trigger an automatic checkpoint at a terminal boundary, trigger an active-turn- checkpoint during a tool loop, and restart a session.+ trigger inline automatic compaction at 90% of `hardLimit` (before the hard+ boundary), exercise an active-turn checkpoint during a tool loop, and restart+ a session.- **Steps**:1. Complete task A and task B in one session with distinct instructions andvisible completion replies.- 2. Trigger a checkpoint after a completed turn, then send task C and capture- the next provider request context.- 3. Trigger compaction while task D still has tool results or `toolUse`- pending, and capture the next provider request.- 4. Restart and reopen the session, then send another prompt.-- **Expected**: A completed-turn checkpoint has an empty retained tail; the next- request contains its summary plus task C and no bare A/B prompts. An active- checkpoint retains exactly the latest active user prompt, with no older user- prompts or pre-boundary assistant/tool messages. Restart honors- `retainedTailMode`, and legacy multi-user tails normalize to the latest user- message. If automatic summary generation fails, the fallback retains a- bounded recent user tail even after a completed turn, and a later retry- removes only the synthetic recovery notice while preserving any carried- summary. The visible transcript remains complete and checkpoint rows remain.+ 2. Advance the context estimate to 91% of `hardLimit`, send task C, and capture+ the first provider request; assert that compaction is installed first.+ 3. Trigger compaction during task D after tool results cross the 90% trigger+ while remaining below the hard limit; capture the follow-up provider+ request and confirm it uses the checkpoint.+ 4. Force summary plus retained-tail recovery to fail once below `hardLimit`+ and once at/above it; the soft failure may proceed unchanged, while the+ hard-boundary failure must not send the provider request.+ 5. Start an approved plan execution with the estimate at 91% of `hardLimit`;+ capture the first request and confirm preflight compaction runs before+ `continue()` while retaining the internal approved-plan instruction.+ 6. Restart and reopen the session, then send another prompt.+- **Expected**: Automatic session compaction starts at+ `floor(hardLimit * 0.9)` for prompt, approved-plan, and in-run turn+ preflights; the estimate includes serialized messages, the active system+ prompt, and tool schemas. A request is never issued at or above `hardLimit`.+ A failed soft-trigger summary may proceed only while below the hard budget,+ and hard-limit failure remains fail-closed. A completed-turn checkpoint has+ an empty retained tail; the next request contains its summary plus task C+ and no bare A/B prompts. An approved-plan checkpoint uses active-turn+ retention so the instruction survives before `continue()`. An active+ checkpoint retains exactly the latest active user prompt, with no older+ user prompts or pre-boundary assistant/tool messages. Restart honors+ `retainedTailMode`, and legacy multi-user tails normalize to the latest user+ message. If automatic summary generation fails at the hard boundary, the+ fallback retains a bounded recent user tail. The visible transcript remains+ complete and checkpoint rows remain.- **Specs linked**: `03-runtime/02-agent-runtime.md`,`03-runtime/04-data-storage.md`, `03-runtime/16-tool-result-limits.md`,- `08-meta/decisions-log.md` (D275), ADR 0136+ `08-meta/decisions-log.md` (D623), ADR 0064, ADR 0136- **Acceptance**: C (chat/stream), F (persistence), Quality- **Milestone**: M5-- **Status**: Unit-covered (`packages/agent-runtime/src/runtime.test.ts`,- `context-compaction.test.mjs`); provider/UI journey Draft+- **Status**: Unit-covered (`packages/agent-runtime/src/context-budget.test.ts`,+ `runtime.test.ts`, `subagent-context.test.ts`); provider/UI journey Draft#### E2E-165: A2A and Peer tools are withdrawndiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex cfbcc32ca..e58e293ff 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -7006,3 +7006,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.unmatched free-form IDs stay generic unknown, while published capabilitiesand explicit binding overrides retain their existing precedence. See`03-runtime/13-model-catalog-and-selection.md` §11.3.++## 2026-09-23 — Compact before the hard request budget (D623, issue #970)++- Automatic session and subagent compaction now starts at 90% of the derived+ `hardLimit`, inline at the next request boundary. New user prompts are+ included in the preflight estimate; tool results are measured before the+ follow-up provider request.+- `hardLimit` remains the final safety boundary. A failed summary below it may+ proceed without a checkpoint; a context at or above it never reaches the+ provider. This trades some additional summaries for fewer provider overflows.+- The runtime remains inline-only: no background summary, user setting,+ protocol change, or transcript/storage rewrite. See ADR 0064,+ `03-runtime/02-agent-runtime.md`, and E2E-164.diff --git a/packages/agent-runtime/src/context-budget.test.ts b/packages/agent-runtime/src/context-budget.test.tsindex 7d6c4828c..9fea7f9a0 100644--- a/packages/agent-runtime/src/context-budget.test.ts+++ b/packages/agent-runtime/src/context-budget.test.ts@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";import type { AssistantMessage, Model } from "@earendil-works/pi-ai";import type { AgentMessage } from "@earendil-works/pi-agent-core";import {+ AUTO_COMPACTION_TRIGGER_RATIO,+ automaticCompactionThresholdFor,COMPACTION_MAX_KEEP_RECENT_TOKENS,COMPACTION_MIN_KEEP_RECENT_TOKENS,COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS,@@ -25,6 +27,18 @@ describe("contextBudgetFor", () => {keepRecentTokens: 44_800,});});+ it("derives an early automatic trigger while preserving the hard guard", () => {+ const limits = contextBudgetLimitsFor({+ contextWindow: 256_000,+ maxTokens: 32_000,+ });+ const trigger = automaticCompactionThresholdFor(limits);++ expect(AUTO_COMPACTION_TRIGGER_RATIO).toBe(0.9);+ expect(trigger).toBe(201_600);+ expect(trigger).toBeLessThan(limits.hardLimit);+ expect(automaticCompactionThresholdFor({ hardLimit: 1 })).toBe(1);+ });it("clamps the retained tail for a small model context window", () => {// A 32K window cannot spare 20% for the tail: the half-budget clamp wins,diff --git a/packages/agent-runtime/src/context-budget.ts b/packages/agent-runtime/src/context-budget.tsindex 57f6291c9..5ecf73b24 100644--- a/packages/agent-runtime/src/context-budget.ts+++ b/packages/agent-runtime/src/context-budget.ts@@ -44,12 +44,12 @@ export const COMPACTION_MAX_KEEP_RECENT_TOKENS = 64_000;*/export const COMPACTION_RETAINED_USER_MESSAGE_MAX_TOKENS = 20_000;-/**- * Context thresholds derived from the active model's window.+/** Context limits derived from the active model's window.** `hardLimit` is the safety boundary: the next provider request must not be- * issued while the context is at or above it. Compaction happens inline at that- * boundary, the way Codex does it — there is no off-critical-path variant.+ * issued while the context is at or above it. Automatic compaction starts at+ * 90% of that budget, inline at the next turn boundary; there is no+ * off-critical-path variant.*/export type ContextBudget = {/** Estimated tokens in the reconstructed model context. */@@ -62,6 +62,19 @@ export type ContextBudget = {keepRecentTokens: number;};+/** Fraction of the safe request budget that starts automatic compaction. */+export const AUTO_COMPACTION_TRIGGER_RATIO = 0.9;++/**+ * Start compaction before the hard boundary so estimator drift and one-turn+ * growth do not leave the provider request as the first overflow detector.+ */+export function automaticCompactionThresholdFor(+ budget: Pick<ContextBudget, "hardLimit">,+): number {+ return Math.max(1, Math.floor(budget.hardLimit * AUTO_COMPACTION_TRIGGER_RATIO));+}+/*** The only model facts the budget depends on. Kept structural and optional so a* pi-ai `Model` passes directly, while a catalog entry that never reported adiff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 8600cfc45..8e4268e15 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -20,6 +20,8 @@ import {type RuntimeMatchConfig,type RuntimeProviderConfig,} from "./runtime.js";+import { estimateOutputCapInputTokens } from "./output-cap.js";+import { COMPACTION_SUMMARY_MAX_RETRIES } from "./compaction-summary-input.js";import type { ProjectInstructions } from "./project-instructions.js";import { classifyAgentError } from "./agent-errors.js";@@ -38,6 +40,8 @@ const subagentRuns = vi.hoisted(() => ({calls: [] as any[],result: undefined as any,/** When true, run() waits for resolveRun() so tests control settlement. */+ constructorError: undefined as unknown,+ ignoreAbort: false,deferred: false,instances: [] as Array<{ resolve: (r: unknown) => void; settled: boolean }>,/** Settles the oldest unresolved deferred run (tests control order). */@@ -50,6 +54,9 @@ vi.mock("./subagent.js", async (importOriginal) => {SubagentRun: class {private signal?: AbortSignal;constructor(options: unknown) {+ if (subagentRuns.constructorError !== undefined) {+ throw subagentRuns.constructorError;+ }subagentRuns.calls.push(options);// Per-instance: concurrent delegates must abort on their own signal.this.signal = (options as { signal?: AbortSignal }).signal;@@ -66,21 +73,23 @@ vi.mock("./subagent.js", async (importOriginal) => {next.resolve(result);}};- this.signal?.addEventListener(- "abort",- () => {- if (instance.settled) return;- instance.settled = true;- resolve({- agentName: "explorer",- status: "aborted",- report: "The delegated task was aborted.",- turns: 0,- toolCalls: 0,- });- },- { once: true },- );+ if (!subagentRuns.ignoreAbort) {+ this.signal?.addEventListener(+ "abort",+ () => {+ if (instance.settled) return;+ instance.settled = true;+ resolve({+ agentName: "explorer",+ status: "aborted",+ report: "The delegated task was aborted.",+ turns: 0,+ toolCalls: 0,+ });+ },+ { once: true },+ );+ }});}return Promise.resolve(@@ -2572,6 +2581,88 @@ describe("DesktopAgentRuntime plan transitions", () => {await runtime.dispose();});+ it("counts request system prompt and tools once despite system transcript rows", async () => {+ const runtime = createRuntime();+ const internal = runtime as any;+ const agent = internal.agent;+ const messages: any[] = agent.state.messages;+ const requestMessages = messages.filter(+ (message) => message.role !== "system" && "content" in message,+ );+ const budget = internal.contextBudget(messages);+ const requestEstimate = estimateOutputCapInputTokens(+ {+ messages: requestMessages,+ systemPrompt: agent.state.systemPrompt,+ tools: internal.activeTools(),+ },+ internal.model,+ );+ const duplicatedEstimate = estimateOutputCapInputTokens(+ {+ messages: messages.filter((message) => "content" in message),+ systemPrompt: agent.state.systemPrompt,+ tools: internal.activeTools(),+ },+ internal.model,+ );++ expect(messages.some((message) => message.role === "system")).toBe(true);+ expect(agent.state.systemPrompt.length).toBeGreaterThan(0);+ expect(internal.activeTools().length).toBeGreaterThan(0);+ expect(duplicatedEstimate).toBeGreaterThan(requestEstimate);+ expect(budget.tokens).toBeGreaterThanOrEqual(requestEstimate);+ expect(budget.tokens).toBeLessThan(duplicatedEstimate);++ await runtime.dispose();+ });+++ it("does not continue an approved plan when preflight cannot clear hardLimit", async () => {+ const onEvent = vi.fn();+ const runtime = createRuntime({ onEvent });+ const internal = runtime as any;+ const agent = internal.agent;+ agent.continue = vi.fn(async () => undefined);+ vi.spyOn(internal, "automaticCompactionNeeded").mockReturnValue(true);+ vi.spyOn(internal, "automaticCompactionWouldExceedHardLimit").mockReturnValue(true);+ const runCompaction = vi.spyOn(internal, "runCompaction").mockResolvedValue(false);+ const execution: PlanExecution = {+ id: "oversized-plan",+ proposalId: "proposal-oversized",+ sessionId: "session-1",+ kind: "plan",+ plan: "# Very large approved snapshot",+ title: "Oversized plan",+ question: "Proceed?",+ artifact: {+ relativePath: ".pi/plan/proposal-oversized.md",+ sha256: "abc123",+ sizeBytes: 31,+ },+ targetPermissionMode: "auto",+ state: "running",+ };++ await runtime.executeApprovedPlan(execution, "execution-turn-oversized");++ expect(runCompaction).toHaveBeenCalledWith(+ "threshold",+ false,+ "active_turn",+ );+ expect((runtime as any).fullEntries.at(-1).message.content).toContain(+ execution.plan,+ );+ expect(onEvent.mock.calls.map(([envelope]) => (envelope as any).event)).toContainEqual(+ expect.objectContaining({+ type: "error",+ error: expect.objectContaining({ code: "CONTEXT_COMPACTION_FAILED" }),+ }),+ );+ await runtime.dispose();+ });+it("re-runs a silent turn during approved plan execution", async () => {const onEvent = vi.fn();const runtime = createRuntime({ onEvent });@@ -4981,7 +5072,7 @@ describe("DesktopAgentRuntime compaction restore", () => {const estimate = estimateAgentContextTokens((runtime as any).agent.state.messages);expect(estimate.usageTokens).toBe(0);expect(estimate.lastUsageIndex).toBeNull();- expect(budget.tokens).toBe(estimate.tokens);+ expect(budget.tokens).toBeGreaterThan(estimate.tokens);expect(budget.tokens).toBeGreaterThan(0);expect(budget.tokens).toBeLessThan(250_000);await runtime.dispose();@@ -5025,7 +5116,7 @@ describe("DesktopAgentRuntime per-turn context protection", () => {const runtime = createRuntime();expect((runtime as any).contextBudget([])).toMatchObject({- tokens: 0,+ tokens: expect.any(Number),hardLimit: 224_000,requestHeadroom: 32_000,keepRecentTokens: 44_800,@@ -5055,19 +5146,19 @@ describe("DesktopAgentRuntime per-turn context protection", () => {await runtime.dispose();});- it("compacts a long tool loop at the hard boundary, reminding once on the way", async () => {+ it("compacts a long tool loop at the soft threshold after a reminder", async () => {const onEvent = vi.fn();const runtime = createRuntime({ onEvent });const prepareNextTurn = (runtime as any).prepareNextTurn.bind(runtime);const handleAgentEvent = (runtime as any).handleAgentEvent.bind(runtime);vi.spyOn(runtime as any, "contextBudget").mockReturnValueOnce({- tokens: 205_000,+ tokens: 195_000,hardLimit: 224_000,requestHeadroom: 32_000,}).mockReturnValueOnce({- tokens: 210_000,+ tokens: 198_000,hardLimit: 224_000,requestHeadroom: 32_000,})@@ -5086,8 +5177,8 @@ describe("DesktopAgentRuntime per-turn context protection", () => {const stillBelow = await prepareNextTurn(nextTurn);await handleAgentEvent({ type: "turn_end", message: assistant, toolResults: [toolResult] });- // 19k left of a 224k limit is inside the first reminder tier, so the model- // is told once. The claim then holds for the rest of this window.+ // 29k left is inside the first reminder tier but still below the 90%+ // compaction trigger, so the model can close out before host compaction.expect(below.context.systemPrompt).toContain("<context_budget>");expect(below.context.systemPrompt).toContain("new_context");expect(stillBelow.context.systemPrompt).not.toContain("<context_budget>");@@ -5264,28 +5355,34 @@ describe("DesktopAgentRuntime per-turn context protection", () => {await runtime.dispose();});- it("warns once more right before the boundary, then not again", async () => {+ it("automatically compacts at the early threshold before the final reminder", async () => {const runtime = createRuntime();- vi.spyOn(runtime as any, "contextBudget").mockReturnValue({- tokens: 223_000,- hardLimit: 224_000,- requestHeadroom: 32_000,- keepRecentTokens: 44_800,- });+ vi.spyOn(runtime as any, "contextBudget")+ .mockReturnValueOnce({+ tokens: 223_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ keepRecentTokens: 44_800,+ })+ .mockReturnValueOnce({+ tokens: 40_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ keepRecentTokens: 44_800,+ })+ .mockReturnValue({+ tokens: 40_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ keepRecentTokens: 44_800,+ });+ const compact = vi.spyOn(runtime as any, "runCompaction").mockResolvedValue(true);const first = await (runtime as any).prepareNextTurn(nextTurn);- const second = await (runtime as any).prepareNextTurn(nextTurn);-- expect(first.context.systemPrompt).toContain(- "the next request compacts this conversation",- );- expect(second.context.systemPrompt).not.toContain("<context_budget>");- // Installing a checkpoint opens a new window, so both tiers come back.- (runtime as any).contextReminderClaimed = false;- (runtime as any).contextFallbackReminderClaimed = false;- const afterCheckpoint = await (runtime as any).prepareNextTurn(nextTurn);- expect(afterCheckpoint.context.systemPrompt).toContain("<context_budget>");+ await (runtime as any).prepareNextTurn(nextTurn);+ expect(compact).toHaveBeenCalledOnce();+ expect(first.context.systemPrompt).not.toContain("<context_budget>");await runtime.dispose();});@@ -5894,6 +5991,28 @@ describe("DesktopAgentRuntime per-turn context protection", () => {await runtime.dispose();});+ it("blocks an over-budget continuation when automatic compaction is disabled", async () => {+ const runtime = createRuntime({+ compactionSettings: {+ enabled: false,+ reserveTokens: 16_384,+ keepRecentTokens: 20_000,+ },+ });+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue({+ tokens: 225_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ });+ const runCompaction = vi.spyOn(runtime as any, "runCompaction");++ await expect((runtime as any).prepareNextTurn(nextTurn)).rejects.toThrow(+ "CONTEXT_TOO_LARGE",+ );+ expect(runCompaction).not.toHaveBeenCalled();+ await runtime.dispose();+ });+it("withdraws the compaction tool when automatic protection is disabled", async () => {const runtime = createRuntime();const before = (runtime as any).agent.state.tools.map(@@ -5916,12 +6035,43 @@ describe("DesktopAgentRuntime per-turn context protection", () => {await runtime.dispose();});+ it("rejects an over-budget first prompt when automatic compaction is disabled", async () => {+ const onEvent = vi.fn();+ const runtime = createRuntime({+ onEvent,+ compactionSettings: {+ enabled: false,+ reserveTokens: 16_384,+ keepRecentTokens: 20_000,+ },+ });+ const agent = (runtime as any).agent;+ agent.prompt = vi.fn();+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue({+ tokens: 225_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ });++ await runtime.prompt("oversized request", "user-disabled-compaction");++ expect(agent.prompt).not.toHaveBeenCalled();+ expect(onEvent.mock.calls.map(([envelope]) => (envelope as any).event)).toContainEqual(+ expect.objectContaining({+ type: "error",+ error: expect.objectContaining({ code: "CONTEXT_TOO_LARGE" }),+ }),+ );+ await runtime.dispose();+ });+it("keeps a preflight-rejected user message in reusable runtime context", async () => {const onEvent = vi.fn();const runtime = createRuntime({ onEvent });const agent = (runtime as any).agent;agent.prompt = vi.fn();vi.spyOn(runtime as any, "automaticCompactionNeeded").mockReturnValue(true);+ vi.spyOn(runtime as any, "automaticCompactionWouldExceedHardLimit").mockReturnValue(true);vi.spyOn(runtime as any, "runCompaction").mockResolvedValue(false);await runtime.prompt("oversized request", "user-preflight");@@ -6258,7 +6408,7 @@ describe("DesktopAgentRuntime inline context compaction", () => {await runtime.dispose();});- it("does not compact when automatic protection is disabled", async () => {+ it("does not compact an in-budget turn when automatic protection is disabled", async () => {const runtime = createRuntime({host: { call: vi.fn().mockResolvedValue(undefined), onNotification: vi.fn(() => () => {}) },history,@@ -6268,7 +6418,12 @@ describe("DesktopAgentRuntime inline context compaction", () => {keepRecentTokens: 20_000,},});- budgetSpy(runtime);+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue({+ tokens: 100_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ keepRecentTokens: 20_000,+ });const generateCompaction = vi.spyOn(runtime as any, "generateCompaction");await (runtime as any).prepareNextTurn(nextTurn);@@ -7176,6 +7331,12 @@ describe("DesktopAgentRuntime subagents", () => {expect(converged.details.status).toBe("completed");expect(converged.content[0].text).toContain("src/app.ts:12");+ const noOpStop = await stop.execute("stop-completed", {+ delegationIds: [firstId],+ });+ expect(noOpStop.content[0].text).toContain("No matching running");+ expect((runtime as any).delegations.get(firstId).status).toBe("completed");+// TaskStop stops the still-running second delegate and reports "stopped".const stopped = await stop.execute("stop-1", { delegationIds: [secondId] });expect(stopped.details.stopped).toHaveLength(1);@@ -7193,6 +7354,56 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});+ it("returns a pending cancellation instead of hanging when a delegate ignores abort", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.deferred = true;+ subagentRuns.ignoreAbort = true;+ subagentRuns.resolveRun = undefined;+ const task = taskTool(runtime);+ const stop = (runtime as any).agent.state.tools.find(+ (tool: any) => tool.name === "TaskStop",+ );+ const started = await task.execute("task-unresponsive", {+ agent: "explorer",+ task: "Keep working unless cancellation reaches you.",+ });+ const delegationId = (started.details as any).delegationId as string;++ vi.useFakeTimers();+ try {+ const stopping = stop.execute("stop-unresponsive", {+ delegationIds: [delegationId],+ });+ await vi.advanceTimersByTimeAsync(5_000);+ const result = await stopping;+ expect(result.content[0].text).toContain("remain running");+ expect(result.details.stopped).toEqual([]);+ expect(result.details.stopPending).toMatchObject([+ { delegationId, status: "running" },+ ]);+ expect((runtime as any).delegations.get(delegationId).status).toBe(+ "running",+ );+ } finally {+ vi.useRealTimers();+ subagentRuns.ignoreAbort = false;+ subagentRuns.deferred = false;+ }++ (subagentRuns as any).resolveRun?.({+ agentName: "explorer",+ status: "aborted",+ report: "The delegated task was aborted.",+ turns: 0,+ toolCalls: 0,+ });+ await Promise.resolve();+ await Promise.resolve();+ await runtime.dispose();+ });+it("caps running delegates per session at MAX_SUBAGENT_CONCURRENCY", async () => {const runtime = createRuntime({ subagents: [explorer] });subagentRuns.calls.length = 0;@@ -9109,13 +9320,14 @@ describe("context estimate calibration", () => {});const messages = [- { role: "user" as const, content: "x".repeat(4_000), timestamp: 1 },+ { role: "user" as const, content: "x".repeat(40_000), timestamp: 1 },];it("moves the gate by what past requests actually cost", async () => {const runtime = createRuntime();- const raw = (runtime as any).contextBudget(messages).tokens;- expect(raw).toBeGreaterThan(0);+ const raw = estimateAgentContextTokens(messages).tokens;+ const initialBudget = (runtime as any).contextBudget(messages).tokens;+ expect(initialBudget).toBeGreaterThan(raw);// Two unanchored reports, each costing three times the estimate: CJK text// against the estimator's `chars / 4` constant. Below the sample threshold@@ -9129,7 +9341,7 @@ describe("context estimate calibration", () => {};(runtime as any).recordContextCalibration(report(raw * 3), false);}- expect((runtime as any).contextBudget(messages).tokens).toBe(raw);+ expect((runtime as any).contextBudget(messages).tokens).toBe(initialBudget);(runtime as any).inFlightContextEstimate = {tokens: raw,@@ -9138,7 +9350,9 @@ describe("context estimate calibration", () => {lastUsageIndex: null,};(runtime as any).recordContextCalibration(report(raw * 3), false);- expect((runtime as any).contextBudget(messages).tokens).toBe(raw * 3);+ expect((runtime as any).contextBudget(messages).tokens).toBe(+ Math.max(raw * 3, initialBudget),+ );await runtime.dispose();});@@ -9690,3 +9904,192 @@ describe("DesktopAgentRuntime loop context ownership (D620)", () => {}});});++describe("DesktopAgentRuntime early context compaction", () => {+ const history: UiMessage[] = [+ {+ id: "old-user",+ role: "user",+ content: "older task context",+ createdAt: "2026-07-28T00:00:00Z",+ status: "complete",+ },+ {+ id: "recent-user",+ role: "user",+ content: "continue the task",+ createdAt: "2026-07-28T00:00:01Z",+ status: "complete",+ },+ ];+ const softBudget = {+ tokens: 205_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ keepRecentTokens: 44_800,+ };++ it("compacts a follow-up turn before the hard limit", async () => {+ const runtime = createRuntime({ history });+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue(softBudget);+ const compact = vi.spyOn(runtime as any, "runCompaction").mockResolvedValue(true);++ await (runtime as any).prepareNextTurn({+ context: { systemPrompt: "base", messages: [], tools: [] },+ newMessages: [],+ });++ expect(softBudget.tokens).toBeLessThan(softBudget.hardLimit);+ expect(compact).toHaveBeenCalledOnce();+ await runtime.dispose();+ });++ it("preflights a new prompt at the same early trigger", async () => {+ const runtime = createRuntime({ history });+ const events: string[] = [];+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue(softBudget);+ const compact = vi.spyOn(runtime as any, "runCompaction").mockImplementation(async () => {+ events.push("compact");+ return true;+ });+ const prompt = vi.spyOn((runtime as any).agent, "prompt").mockImplementation(async () => {+ events.push("prompt");+ });++ await runtime.prompt("next user request");++ expect(compact).toHaveBeenCalledOnce();+ expect(prompt).toHaveBeenCalledOnce();+ expect(events).toEqual(["compact", "prompt"]);+ await runtime.dispose();+ });+});++ it("continues a soft-trigger preflight when compaction fails below the hard limit", async () => {+ const history: UiMessage[] = [+ {+ id: "old-user",+ role: "user",+ content: "older task context",+ createdAt: "2026-07-28T00:00:00Z",+ status: "complete",+ },+ {+ id: "recent-user",+ role: "user",+ content: "continue the task",+ createdAt: "2026-07-28T00:00:01Z",+ status: "complete",+ },+ ];+ const softBudget = {+ tokens: 205_000,+ hardLimit: 224_000,+ requestHeadroom: 32_000,+ keepRecentTokens: 44_800,+ };+ const runtime = createRuntime({ history });+ vi.spyOn(runtime as any, "contextBudget").mockReturnValue(softBudget);+ vi.spyOn(runtime as any, "runCompaction").mockResolvedValue(false);+ const prompt = vi.spyOn((runtime as any).agent, "prompt").mockResolvedValue(undefined);++ await runtime.prompt("next user request");++ expect(prompt).toHaveBeenCalledOnce();+ await runtime.dispose();+ });++describe("DesktopAgentRuntime delegation wait settlement safety", () => {+ const explorer: SubagentDefinition = {+ name: "explorer",+ description: "Search the workspace and report findings.",+ tools: ["Read", "Glob", "Grep"],+ prompt: "Report file paths and line numbers.",+ source: "builtin",+ };++ function taskTool(runtime: DesktopAgentRuntime) {+ return (runtime as any).agent.state.tools.find(+ (tool: any) => tool.name === "Task",+ );+ }+ it("does not register a running delegation when SubagentRun initialization throws", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ subagentRuns.calls.length = 0;+ subagentRuns.constructorError = new Error("agent initialization failed");+ try {+ const started = await taskTool(runtime).execute("task-init-failed", {+ agent: "explorer",+ task: "Find it.",+ });++ expect(String((started.details as any)?.error)).toMatch(/initialize/i);+ expect((runtime as any).runningDelegations()).toHaveLength(0);+ await expect((runtime as any).resumeAfterDelegations()).resolves.toBeUndefined();+ } finally {+ subagentRuns.constructorError = undefined;+ await runtime.dispose();+ }+ });++ it("wakes the parent even when settlement publication throws", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.deferred = true;+ subagentRuns.resolveRun = undefined;+ const prompt = vi.fn(async () => undefined);+ (runtime as any).agent.prompt = prompt;+ (runtime as any).agent.waitForIdle = vi.fn(async () => undefined);+ try {+ const started = await taskTool(runtime).execute("task-publish-failed", {+ agent: "explorer",+ task: "Find it.",+ });+ const delegationId = (started.details as any).delegationId as string;+ vi.spyOn(runtime as any, "publishDelegationSettlement").mockImplementation(() => {+ throw new Error("event publication failed");+ });++ const resume = (runtime as any).resumeAfterDelegations();+ subagentRuns.resolveRun!({+ agentName: "explorer",+ status: "completed",+ report: "Found it in src/app.ts:12.",+ turns: 1,+ toolCalls: 1,+ });+ await resume;++ expect((runtime as any).delegations.get(delegationId).status).toBe("completed");+ expect(prompt).toHaveBeenCalledOnce();+ } finally {+ subagentRuns.deferred = false;+ await runtime.dispose();+ }+ });++ it("lets user Stop interrupt auto-resume even if a delegate ignores abort", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.deferred = true;+ subagentRuns.ignoreAbort = true;+ subagentRuns.resolveRun = undefined;+ try {+ await taskTool(runtime).execute("task-stop-wait", {+ agent: "explorer",+ task: "Find it.",+ });+ const resume = (runtime as any).resumeAfterDelegations();+ await Promise.resolve();++ await runtime.abort();+ await resume;+ } finally {+ subagentRuns.ignoreAbort = false;+ subagentRuns.deferred = false;+ await runtime.dispose();+ }+ }, 1_000);+});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex b49f68cde..29813cf9e 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -152,6 +152,7 @@ import {} from "./provider-binding.js";import {contextBudgetFor,+ automaticCompactionThresholdFor,contextBudgetLimitsFor,retainedUserMessageBudget,type ContextBudget,@@ -170,6 +171,7 @@ import {import {clampOutputToContext,effectiveModelContextWindow,+ estimateOutputCapInputTokens,} from "./output-cap.js";import {composeSubagentSystemPrompt,@@ -4371,70 +4373,97 @@ Delegation rules:...(modelChangedFrom ? { modelChangedFrom } : {}),};this.delegations.set(delegationId, record);- const scopedTools = this.scopeDelegateTools(tools, definition);- new SubagentRun({- definition,- sessionId: this.sessionId,- turnId: this.turnId,- parentToolCallId: toolCallId,- task,- provider,- infiniteProviderRetry: this.infiniteProviderRetry,- thinkingLevel,- fallbackModels: (definition.fallbackModels ?? []).map((pin) => ({- key: subagentModelKey(pin),- provider: this.subagentProviders[subagentModelKey(pin)],- })),- inheritedThinkingLevel: this.thinkingLevel,- onModelChange: (next, level) => {- record.modelId = next.modelId;- record.thinkingLevel = level;- this.delegationChains.retarget(record.delegateSessionId, {- modelKey: this.delegationModelKeyFor(next),- modelId: next.modelId,- });- this.publishDelegationSettlement(record);- },- systemPrompt: composeSubagentSystemPrompt({+ let subagentRun: SubagentRun;+ try {+ const scopedTools = this.scopeDelegateTools(tools, definition);+ subagentRun = new SubagentRun({definition,- guidance: this.subagentGuidance(definition),- toolNames: declaredToolNames,- }),- tools: scopedTools,- onEvent: (envelope) => {- this.noteDelegationActivity(record, envelope);- this.onEvent(envelope);- },- // A host failure inside a delegate reaches its tool-error channel- // through the same bookkeeping the parent uses.- resolveToolOutcome: (context) => this.resolveOwnToolOutcome(context),- signal: abortSignal,- // A resumed run replays its chain before this turn's `task` (ADR 0276).- ...(initialMessages ? { initialMessages } : {}),- })- .run()- .then(- (result) => this.settleDelegation(record, result),- // SubagentRun.run() settles its own errors into results; this- // guard only keeps an unexpected rejection from leaving the- // delegation stuck in "running" forever.- (error: unknown) => {- this.settleDelegation(record, {- agentName: definition.name,- modelId: provider.modelId,- thinkingLevel,- status: "failed",- report: "",- turns: 0,- toolCalls: 0,- error: {- code: "UNEXPECTED_DELEGATION_REJECTION",- message:- error instanceof Error ? error.message : "unknown error",- },+ sessionId: this.sessionId,+ turnId: this.turnId,+ parentToolCallId: toolCallId,+ task,+ provider,+ infiniteProviderRetry: this.infiniteProviderRetry,+ thinkingLevel,+ fallbackModels: (definition.fallbackModels ?? []).map((pin) => ({+ key: subagentModelKey(pin),+ provider: this.subagentProviders[subagentModelKey(pin)],+ })),+ inheritedThinkingLevel: this.thinkingLevel,+ onModelChange: (next, level) => {+ record.modelId = next.modelId;+ record.thinkingLevel = level;+ this.delegationChains.retarget(record.delegateSessionId, {+ modelKey: this.delegationModelKeyFor(next),+ modelId: next.modelId,});+ this.publishDelegationSettlement(record);},+ systemPrompt: composeSubagentSystemPrompt({+ definition,+ guidance: this.subagentGuidance(definition),+ toolNames: declaredToolNames,+ }),+ tools: scopedTools,+ onEvent: (envelope) => {+ this.noteDelegationActivity(record, envelope);+ this.onEvent(envelope);+ },+ // A host failure inside a delegate reaches its tool-error channel+ // through the same bookkeeping the parent uses.+ resolveToolOutcome: (context) => this.resolveOwnToolOutcome(context),+ signal: abortSignal,+ // A resumed run replays its chain before this turn's `task` (ADR 0276).+ ...(initialMessages ? { initialMessages } : {}),+ });+ } catch {+ // A constructor/scope failure happens after registry allocation. Make+ // it terminal before returning or idle auto-resume will await a+ // completion promise for a worker that never existed.+ record.reportDelivered = true;+ this.settleDelegation(record, {+ agentName: definition.name,+ modelId: provider.modelId,+ thinkingLevel,+ status: "failed",+ report: "",+ turns: 0,+ toolCalls: 0,+ error: {+ code: "SUBAGENT_INITIALIZATION_FAILED",+ message: "The subagent runtime could not be initialized.",+ },+ });+ return this.subagentToolError(+ toolCallId,+ `Could not initialize the ${definition.name} subagent. No work was started.`,);+ }++ let runPromise: Promise<SubagentRunResult>;+ try {+ runPromise = subagentRun.run();+ } catch (error) {+ runPromise = Promise.reject(error);+ }+ void runPromise+ .then((result) => this.settleDelegation(record, result))+ .catch((error: unknown) => {+ this.settleDelegation(record, {+ agentName: definition.name,+ modelId: provider.modelId,+ thinkingLevel,+ status: "failed",+ report: "",+ turns: 0,+ toolCalls: 0,+ error: {+ code: "UNEXPECTED_DELEGATION_REJECTION",+ message:+ error instanceof Error ? error.message : "unknown error",+ },+ });+ });const label =isRecord(params) && typeof params.description === "string"@@ -4495,21 +4524,30 @@ Delegation rules:: result.status;record.result = result;record.completedAt = Date.now();- if (result.usage) {- this.turnSubagentUsage = addUsage(this.turnSubagentUsage, result.usage);- }- this.delegationChains.settle(record.delegateSessionId, record.status);- // An aborted call never sends `tool_end`, so a settled run drops whatever- // its calls left behind rather than pinning those arguments for the session.- for (const toolCallId of record.pendingToolCallIds ?? []) {- this.delegateToolCalls.delete(toolCallId);- }- record.pendingToolCallIds = undefined;- this.publishDelegationSettlement(record);+ // Resolve before event publication or bookkeeping: none of those side+ // effects may strand TaskWait or the parent's idle auto-resume.record.resolveCompletion();- this.refreshDelegationWait();- this.refreshResumablePrompt();- this.pruneFinishedDelegations();+ try {+ if (result.usage) {+ this.turnSubagentUsage = addUsage(this.turnSubagentUsage, result.usage);+ }+ this.delegationChains.settle(record.delegateSessionId, record.status);+ // An aborted call never sends `tool_end`, so a settled run drops whatever+ // its calls left behind rather than pinning those arguments for the session.+ for (const toolCallId of record.pendingToolCallIds ?? []) {+ this.delegateToolCalls.delete(toolCallId);+ }+ record.pendingToolCallIds = undefined;+ this.publishDelegationSettlement(record);+ } catch {+ process.stderr.write(+ `[agent-runtime] delegation settlement side effect failed (session=${this.sessionId} delegation=${record.delegationId})\n`,+ );+ } finally {+ this.refreshDelegationWait();+ this.refreshResumablePrompt();+ this.pruneFinishedDelegations();+ }}private publishDelegationSettlement(record: DelegationRecord): void {@@ -4588,6 +4626,7 @@ Delegation rules:private terminateParentTurn(): void {this.turnHadError = true;this.acceptingSteering = false;+ this.steeringWaitAbort?.abort();this.retainPendingSteering();this.abortRunningDelegations();this.delegationWaitTargets = undefined;@@ -5055,7 +5094,7 @@ Delegation rules:name: SUBAGENT_STOP_TOOL_NAME,label: "Task Stop",description:- "Stop one or more running subagents. `delegationIds` defaults to every running subagent. Stopped subagents report as stopped; their partial work is lost.",+ "Request cancellation for one or more running subagents. `delegationIds` defaults to every running subagent. A subagent is reported as stopped only after it confirms termination; an unresponsive subagent remains running.",parameters: Type.Object({delegationIds: Type.Optional(Type.Array(@@ -5073,22 +5112,50 @@ Delegation rules:const targets = ids.length? ids.map((id) => this.delegations.get(id))- .filter((record): record is DelegationRecord => record !== undefined)+ .filter(+ (record): record is DelegationRecord =>+ record !== undefined && record.status === "running",+ ): this.runningDelegations();for (const record of targets) {record.stopRequested = true;record.abort();}- // Persist the settled snapshot: aborting is async, and a `running`- // `details.stopped[]` made finished sessions keep a live topology card.- await Promise.all(targets.map((record) => record.completion));+ // Cancellation is cooperative: bound the wait so a worker that ignores+ // abort cannot wedge the parent tool call. Still-running workers are+ // explicitly returned as pending, never mislabeled as stopped.+ let stopTimeout: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([+ Promise.all(targets.map((record) => record.completion)),+ new Promise<void>((resolve) => {+ stopTimeout = setTimeout(resolve, 5_000);+ }),+ ]);+ if (stopTimeout !== undefined) clearTimeout(stopTimeout);+ const pending = targets.filter((record) => record.status === "running");+ const stopped = targets.filter((record) => record.status === "stopped");+ const settled = targets.filter(+ (record) => record.status !== "running" && record.status !== "stopped",+ );const text =targets.length === 0? "No matching running subagents to stop."- : `Stopped ${targets.length} subagent${targets.length === 1 ? "" : "s"}.`;+ : pending.length > 0+ ? `Cancellation requested for ${targets.length} subagent${targets.length === 1 ? "" : "s"}; ${pending.length} have not confirmed termination and remain running.`+ : settled.length > 0+ ? `Cancellation settled for ${targets.length} subagent${targets.length === 1 ? "" : "s"}: ${stopped.length} stopped and ${settled.length} had already finished.`+ : `Stopped ${stopped.length} subagent${stopped.length === 1 ? "" : "s"}.`;return {content: [{ type: "text", text }],- details: { stopped: targets.map(delegationSummary) },+ details: {+ stopped: stopped.map(delegationSummary),+ ...(pending.length > 0+ ? { stopPending: pending.map(delegationSummary) }+ : {}),+ ...(settled.length > 0+ ? { settled: settled.map(delegationSummary) }+ : {}),+ },};},};@@ -5895,18 +5962,30 @@ Delegation rules:private contextBudget(messages: AgentMessage[]): ContextBudget {const budget = contextBudgetFor(this.model, messages);- // Correct the raw estimate with what past requests actually cost. The- // `chars / 4` tail is biased on CJK text, and a projection with no usage- // anchor is missing the system/tool overhead; below the sample threshold- // `correct()` returns the raw value unchanged, and the downward direction- // is bounded by `CONTEXT_CALIBRATION_FACTOR_MIN`.+ // Calibration learns from message usage; the output-cap estimator adds the+ // active system prompt and tool schemas that the provider also receives.+ // Taking the larger full-request estimate avoids double-counting overhead+ // once unanchored calibration has learned it, while keeping that overhead as+ // a hard floor before the first usable sample.+ const calibratedMessageTokens = this.contextCalibration.correct(+ estimateContextTokens(messages, this.model),+ );+ const requestTokens = estimateOutputCapInputTokens(+ {+ messages: messages.filter(+ (message): message is Extract<AgentMessage, { content: unknown }> =>+ message.role !== "system" && "content" in message,+ ),+ ...(typeof this.agent.state.systemPrompt === "string"+ ? { systemPrompt: this.agent.state.systemPrompt }+ : {}),+ tools: this.activeTools(),+ },+ this.model,+ );return {...budget,- // Same target model as `contextBudgetFor` above: the calibration input- // must describe the request this runtime will actually send.- tokens: this.contextCalibration.correct(- estimateContextTokens(messages, this.model),- ),+ tokens: Math.max(calibratedMessageTokens, requestTokens),};}@@ -5956,7 +6035,19 @@ Delegation rules:const context = this.liveSessionContext();const messages = [...context.messages, ...additionalMessages];const budget = this.contextBudget(messages);- return this.compactionEnabled && budget.tokens >= budget.hardLimit;+ return (+ this.compactionEnabled &&+ budget.tokens >= automaticCompactionThresholdFor(budget)+ );+ }++ private automaticCompactionWouldExceedHardLimit(+ additionalMessages: AgentMessage[] = [],+ ): boolean {+ const context = this.liveSessionContext();+ const messages = [...context.messages, ...additionalMessages];+ const budget = this.contextBudget(messages);+ return budget.tokens >= budget.hardLimit;}private retainedUserMessageBudget(budget: ContextBudget): number {@@ -6103,19 +6194,25 @@ Delegation rules:_signal?: AbortSignal,): Promise<AgentLoopTurnUpdate> {let context = this.rebuiltAgentContext();+ const budget = this.contextBudget(context.messages);+ const hardLimitReached = budget.tokens >= budget.hardLimit;if (!this.compactionEnabled) {this.pendingModelCompaction = false;+ if (hardLimitReached) {+ throw new Error(+ "CONTEXT_TOO_LARGE: context exceeds the safe model budget while automatic compaction is disabled",+ );+ }return { context };}- const budget = this.contextBudget(context.messages);- const hardLimitReached = budget.tokens >= budget.hardLimit;- // Codex's `should_roll_over`: either the model asked for a new window or- // the limit forces one. A model request that fails to compact is not fatal- // — nothing is over the boundary yet — so only the limit throws.+ const automaticThresholdReached =+ budget.tokens >= automaticCompactionThresholdFor(budget);+ // Compact deterministically before the request approaches the hard limit.+ // `new_context` remains an optional earlier model request.const modelRequested = this.pendingModelCompaction;this.pendingModelCompaction = false;- if (!hardLimitReached && !modelRequested) {+ if (!automaticThresholdReached && !modelRequested) {return { context: this.withContextBudgetReminder(context, budget) };}@@ -7699,16 +7796,22 @@ Delegation rules:this.appendLiveEntry(userMessageId, incomingUserMessage);this.setAgentMessages(this.liveSessionContext().messages);}- private failBeforeProviderRequest(- incomingUserMessage: AgentMessage,+ private failCurrentPreflight(error: ReturnType<typeof classifyAgentError>,): void {- this.keepPreflightUserMessage(incomingUserMessage);this.terminateParentTurn();this.finalizeCurrentAssistant("error", error);this.emit({ type: "error", error });}+ private failBeforeProviderRequest(+ incomingUserMessage: AgentMessage,+ error: ReturnType<typeof classifyAgentError>,+ ): void {+ this.keepPreflightUserMessage(incomingUserMessage);+ this.failCurrentPreflight(error);+ }+/*** Start execution for a host-approved plan without creating a visible user* turn. pi-agent-core needs a user message before `continue()`, so the@@ -7792,6 +7895,38 @@ Delegation rules:this.appendLiveEntry(internalId, internalMessage);this.setAgentActivity({ phase: "starting", since: Date.now() });this.setAgentMessages(this.liveSessionContext().messages);+ if (this.automaticCompactionNeeded()) {+ const compacted = await this.runCompaction(+ "threshold",+ false,+ "active_turn",+ );+ if (!compacted) {+ if (this.compactionAborted) {+ this.terminateParentTurn();+ this.finalizeCurrentAssistant("aborted");+ return { turnId: this.turnId };+ }+ if (this.automaticCompactionWouldExceedHardLimit()) {+ this.failCurrentPreflight({+ code: "CONTEXT_COMPACTION_FAILED",+ message:+ "Automatic context compaction failed before approved plan execution",+ retriable: false,+ });+ return { turnId: this.turnId };+ }+ }+ }+ if (this.automaticCompactionWouldExceedHardLimit()) {+ this.failCurrentPreflight({+ code: "CONTEXT_TOO_LARGE",+ message:+ "The approved plan still exceeds the safe model context budget after compaction",+ retriable: false,+ });+ return { turnId: this.turnId };+ }await this.agent.continue();await this.waitForIdleAndSteering();// Same recovery contract as a user prompt: a plan execution that overflows,@@ -7859,14 +7994,17 @@ Delegation rules:this.keepPreflightUserMessage(incomingUserMessage);throw turnAbortedError("Turn aborted while compacting context");}- this.failBeforeProviderRequest(incomingUserMessage, {- code: "CONTEXT_COMPACTION_FAILED",- message: "Automatic context compaction failed before the model request",- retriable: false,- });- return { turnId: this.turnId };- }- if (this.automaticCompactionNeeded([incomingUserMessage])) {+ // A soft-trigger summary failure is recoverable while the hard+ // provider budget still has room; retain the hard guard below.+ if (this.automaticCompactionWouldExceedHardLimit([incomingUserMessage])) {+ this.failBeforeProviderRequest(incomingUserMessage, {+ code: "CONTEXT_COMPACTION_FAILED",+ message: "Automatic context compaction failed before the model request",+ retriable: false,+ });+ return { turnId: this.turnId };+ }+ } else if (this.automaticCompactionWouldExceedHardLimit([incomingUserMessage])) {this.failBeforeProviderRequest(incomingUserMessage, {code: "CONTEXT_TOO_LARGE",message:@@ -7876,6 +8014,18 @@ Delegation rules:return { turnId: this.turnId };}}+ if (+ !this.compactionEnabled &&+ this.automaticCompactionWouldExceedHardLimit([incomingUserMessage])+ ) {+ this.failBeforeProviderRequest(incomingUserMessage, {+ code: "CONTEXT_TOO_LARGE",+ message:+ "The pending prompt exceeds the safe model context budget while automatic compaction is disabled",+ retriable: false,+ });+ return { turnId: this.turnId };+ }await this.extensionBeforeAgentStart(modelInput);if (this.runCancelled || this.disposed) {this.keepPreflightUserMessage(incomingUserMessage);@@ -8073,6 +8223,7 @@ Delegation rules:this.acceptingSteering = false;this.gracefulStopRequested = false;this.runCancelled = true;+ this.steeringWaitAbort?.abort();this.extensionRunner?.cancelPending();this.resolvePendingAskTools();this.abortRunningDelegations();@@ -8100,7 +8251,7 @@ Delegation rules:this.agent.state.isStreaming ||this.compactionInProgress ||this.agentActivity !== undefined ||- (!this.turnHadError && this.runningDelegations().length > 0),+ (!this.turnHadError && !this.runCancelled && this.runningDelegations().length > 0),currentTurnId: this.turnId,modelId: this.provider.modelId,pendingToolConfirmations: 0,@@ -8119,6 +8270,7 @@ Delegation rules:this.disposed = true;this.acceptingSteering = false;this.runCancelled = true;+ this.steeringWaitAbort?.abort();this.resolvePendingAskTools();this.abortRunningDelegations();this.delegationWaitTargets = undefined;diff --git a/packages/agent-runtime/src/subagent-context.test.ts b/packages/agent-runtime/src/subagent-context.test.tsindex fa3b04dc1..b83e48672 100644--- a/packages/agent-runtime/src/subagent-context.test.ts+++ b/packages/agent-runtime/src/subagent-context.test.ts@@ -17,7 +17,7 @@ import {buildProviderModel,type RuntimeProviderConfig,} from "./provider-binding.js";-import { contextBudgetFor } from "./context-budget.js";+import { automaticCompactionThresholdFor, contextBudgetFor } from "./context-budget.js";import {degradedDelegateMessages,delegateRetentionMode,@@ -210,6 +210,63 @@ describe("prepareDelegateTurnContext", () => {});});+ it("compacts at the shared early trigger before the hard limit", async () => {+ const taskBrief = "Read the permission flow.";+ const messages: AgentMessage[] = [+ userMessage(taskBrief),+ assistantToolCall("soft-trigger"),+ toolResult("x".repeat(7_500), "soft-trigger"),+ ];+ const budget = contextBudgetFor(smallModel(), messages);+ const { factory, prompts } = summaryModels(() => summarySuccess("SUMMARY TEXT"));++ expect(budget.tokens).toBeLessThan(budget.hardLimit);+ expect(budget.tokens).toBeGreaterThanOrEqual(+ automaticCompactionThresholdFor(budget),+ );+ const outcome = await prepareDelegateTurnContext({+ messages,+ model: smallModel(),+ taskBrief,+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("compacted");+ expect(prompts).toHaveLength(1);+ });+ it("charges pending task, system prompt, and tool schemas against the budget", async () => {+ const taskBrief = "Read the permission flow.";+ const messages: AgentMessage[] = [+ userMessage(taskBrief),+ assistantToolCall("call-1"),+ toolResult("a".repeat(2_300), "call-1"),+ assistantToolCall("call-2"),+ toolResult("b".repeat(2_300), "call-2"),+ ];+ const baseBudget = contextBudgetFor(smallModel(), messages);+ expect(baseBudget.tokens).toBeLessThan(+ automaticCompactionThresholdFor(baseBudget),+ );+ const { factory, prompts } = summaryModels(() => summarySuccess("SUMMARY TEXT"));++ const outcome = await prepareDelegateTurnContext({+ messages,+ additionalMessages: [userMessage("Continue scanning.")],+ model: smallModel(),+ taskBrief,+ systemPrompt: "s".repeat(2_600),+ tools: [{ name: "Read", description: "t".repeat(800) }],+ retentionMode: "active_turn",+ summaryModels: factory,+ signal: new AbortController().signal,+ });++ expect(outcome.kind).toBe("compacted");+ expect(prompts).toHaveLength(1);+ });+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({diff --git a/packages/agent-runtime/src/subagent-context.ts b/packages/agent-runtime/src/subagent-context.tsindex e4df24c06..a87ba7b3e 100644--- a/packages/agent-runtime/src/subagent-context.ts+++ b/packages/agent-runtime/src/subagent-context.ts@@ -17,7 +17,6 @@import {BACKGROUND_CONTEXT,createCompactionSummaryMessage,- estimateTokens,generateSummaryWithUsage,prepareCompaction,withAbortSignal,@@ -37,6 +36,7 @@ import type {UserMessage,} from "@earendil-works/pi-ai";import {+ automaticCompactionThresholdFor,contextBudgetFor,contextBudgetLimitsFor,retainedUserMessageBudget,@@ -44,6 +44,11 @@ import {type ContextBudgetModel,type ContextBudgetModelInput,} from "./context-budget.js";+import {+ estimateOutputCapInputTokens,+ type OutputCapContext,+ type OutputCapReplayTarget,+} from "./output-cap.js";import {COMPACTION_SUMMARY_RETRY_POLICY,estimateSummaryPromptTokens,@@ -132,16 +137,21 @@ export function delegateSummaryModels(}/**- * 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`.+ * Decide the context for a delegate's next provider request. Below the shared+ * 90% automatic trigger nothing changes; at or above it the run compacts+ * synchronously, then degrades, and only then reports the hard-limit 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. */+ /** The model whose resolved output cap defines this request's hard limit. */model: Model<Api>;+ /** New text the next provider request will append after any checkpoint. */+ additionalMessages?: AgentMessage[];+ /** Provider-visible prompt/tool overhead, separate from transcript rows. */+ systemPrompt?: string;+ tools?: unknown[];/** The delegated instruction, kept verbatim through degradation. */taskBrief: string;retentionMode: DelegateRetentionMode;@@ -149,13 +159,35 @@ export async function prepareDelegateTurnContext(input: {summaryModels: () => Models;thinkingLevel?: ThinkingLevel;signal: AbortSignal;+ /** False when `Agent.prompt(taskBrief)` will append the task after preflight. */+ retainTaskBriefOnDegradation?: boolean;}): Promise<DelegateTurnUpdate> {- const budget = contextBudgetFor(input.model, input.messages);- if (budget.tokens < budget.hardLimit) return { kind: "unchanged" };+ const additionalMessages = input.additionalMessages ?? [];+ const budget = delegateContextBudgetFor(+ input.model,+ input.messages,+ additionalMessages,+ input.systemPrompt,+ input.tools,+ );+ if (budget.tokens < automaticCompactionThresholdFor(budget)) {+ return { kind: "unchanged" };+ }+ // With no history there is nothing to compact; if the complete next request+ // still fits the hard budget, do not manufacture a lossy checkpoint.+ if (input.messages.length === 0 && budget.tokens < budget.hardLimit) {+ return { kind: "unchanged" };+ }const compacted = await compactDelegateContext(input, budget);if (compacted) {- const fit = contextBudgetFor(input.model, compacted.messages);+ const fit = delegateContextBudgetFor(+ input.model,+ compacted.messages,+ additionalMessages,+ input.systemPrompt,+ input.tools,+ );if (fit.tokens < fit.hardLimit) {return { kind: "compacted", ...compacted };}@@ -165,13 +197,64 @@ export async function prepareDelegateTurnContext(input: {input.messages,input.taskBrief,input.model,+ {+ systemPrompt: input.systemPrompt,+ tools: input.tools,+ additionalMessages,+ includeTaskBrief: input.retainTaskBriefOnDegradation !== false,+ },);if (degraded) {- return { kind: "degraded", messages: degraded, tokensBefore: budget.tokens };+ const fit = delegateContextBudgetFor(+ input.model,+ degraded,+ additionalMessages,+ input.systemPrompt,+ input.tools,+ );+ if (fit.tokens < fit.hardLimit) {+ return { kind: "degraded", messages: degraded, tokensBefore: budget.tokens };+ }}return { kind: "overflow", tokens: budget.tokens, hardLimit: budget.hardLimit };}+function outputCapContextMessages(+ messages: AgentMessage[],+): OutputCapContext["messages"] {+ return messages.filter(+ (message): message is Extract<AgentMessage, { content: unknown }> =>+ "content" in message,+ );+}++function outputCapReplayTarget(+ model: ContextBudgetModelInput,+): OutputCapReplayTarget | undefined {+ if (!("api" in model)) return undefined;+ return { api: model.api, provider: model.provider, id: model.id };+}++function delegateContextBudgetFor(+ model: Model<Api>,+ messages: AgentMessage[],+ additionalMessages: AgentMessage[] = [],+ systemPrompt?: string,+ tools?: unknown[],+): ContextBudget {+ const requestMessages = [...messages, ...additionalMessages];+ const estimate = contextBudgetFor(model, requestMessages);+ const requestTokens = estimateOutputCapInputTokens(+ {+ messages: outputCapContextMessages(requestMessages),+ ...(systemPrompt !== undefined ? { systemPrompt } : {}),+ ...(tools !== undefined ? { tools } : {}),+ },+ outputCapReplayTarget(model),+ );+ return { ...estimate, tokens: Math.max(estimate.tokens, requestTokens) };+}+/*** 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,@@ -279,29 +362,58 @@ async function compactDelegateContext(* the request that produced it, which describes the pre-degradation context* and would condemn every rebuilt context to still look oversized.*/+export type DelegateDegradationOptions = {+ systemPrompt?: string;+ tools?: unknown[];+ additionalMessages?: AgentMessage[];+ /** Omit a task brief that will be appended through `Agent.prompt()` next. */+ includeTaskBrief?: boolean;+};+export function degradedDelegateMessages(messages: AgentMessage[],taskBrief: string,model: ContextBudgetModelInput,+ options: DelegateDegradationOptions = {},): AgentMessage[] | undefined {const limits = contextBudgetLimitsFor(model);const briefIndex = messages.findIndex((message) => message.role === "user");- const brief: UserMessage =+ const brief: UserMessage | undefined =briefIndex >= 0? (messages[briefIndex] as UserMessage)- : { role: "user", content: taskBrief, timestamp: Date.now() };- const target = "api" in model ? model : undefined;- const briefTokens = estimateTokens(brief, target);- if (briefTokens >= limits.hardLimit) return undefined;+ : options.includeTaskBrief === false+ ? undefined+ : { role: "user", content: taskBrief, timestamp: Date.now() };+ const requestOverhead = estimateOutputCapInputTokens(+ {+ messages: outputCapContextMessages(options.additionalMessages ?? []),+ ...(options.systemPrompt !== undefined+ ? { systemPrompt: options.systemPrompt }+ : {}),+ ...(options.tools !== undefined ? { tools: options.tools } : {}),+ },+ outputCapReplayTarget(model),+ );+ const briefTokens = brief+ ? estimateOutputCapInputTokens(+ { messages: outputCapContextMessages([brief]) },+ outputCapReplayTarget(model),+ )+ : 0;+ const hardLimit = limits.hardLimit;+ let tokens = briefTokens + requestOverhead;+ if (tokens >= hardLimit) return undefined;- const pool = messages.slice(briefIndex + 1);+ const pool = messages.slice(briefIndex >= 0 ? briefIndex + 1 : 0);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, target);- if (tokens + cost >= limits.hardLimit) break;+ const cost = estimateOutputCapInputTokens(+ { messages: [message] },+ outputCapReplayTarget(model),+ );+ if (tokens + cost >= hardLimit) break;suffix.unshift(message);tokens += cost;}@@ -310,7 +422,7 @@ export function degradedDelegateMessages(// 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];+ return [...(brief ? [brief] : []), ...suffix];}/**@@ -422,12 +534,16 @@ function isCompactionSummary(}/** Failed, aborted, and empty assistants are transcript rows, not context. */-function isDelegateContextMessage(message: AgentMessage): boolean {+/** Failed, aborted, and empty assistants are transcript rows, not context. */+function isDelegateContextMessage(+ message: AgentMessage,+): message is Extract<AgentMessage, { content: unknown }> {return (- message.role !== "assistant" ||- (message.stopReason !== "error" &&- message.stopReason !== "aborted" &&- message.stopReason !== "deferred" &&- message.content.length > 0)+ "content" in message &&+ (message.role !== "assistant" ||+ (message.stopReason !== "error" &&+ message.stopReason !== "aborted" &&+ message.stopReason !== "deferred" &&+ message.content.length > 0)));}diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.tsindex 589963161..1b48777aa 100644--- a/packages/agent-runtime/src/subagent.test.ts+++ b/packages/agent-runtime/src/subagent.test.ts@@ -1,4 +1,5 @@import { describe, expect, it, vi } from "vitest";+import { Type } from "typebox";import type { AgentEventEnvelope, SubagentDefinition } from "@pi-desktop/shared";import type { Message } from "@earendil-works/pi-ai";import {@@ -722,6 +723,46 @@ describe("SubagentRun context budget (ADR 0299)", () => {expect(typeof run.agent.prepareNextTurnWithContext).toBe("function");});+ it("preflights the first request with system and tool-schema overhead", async () => {+ const smallProvider: 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 tools = [{+ name: "Read",+ label: "Read",+ description: "t".repeat(2_200),+ parameters: Type.Object({}),+ execute: async () => ({+ content: [{ type: "text" as const, text: "unused" }],+ details: {},+ }),+ }];+ const { run } = createRun({+ provider: smallProvider,+ systemPrompt: "s".repeat(6_200),+ tools,+ });+ const prompt = vi.spyOn(run.agent, "prompt").mockResolvedValue(undefined);+ vi.spyOn(run.agent, "waitForIdle").mockResolvedValue(undefined);++ const result = await (run as unknown as SubagentRun).run();++ expect(result.status).toBe("failed");+ expect(result.error?.code).toBe("SUBAGENT_CONTEXT_OVERFLOW");+ expect(prompt).not.toHaveBeenCalled();+ });+it("remaps a provider context overflow no fallback could absorb", async () => {const { run } = createRun();const failure = {diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.tsindex a1ba6f357..66c8c664f 100644--- a/packages/agent-runtime/src/subagent.ts+++ b/packages/agent-runtime/src/subagent.ts@@ -62,6 +62,7 @@ import {delegateSummaryModels,prepareDelegateTurnContext,subagentContextOverflowError,+ type DelegateTurnUpdate,} from "./subagent-context.js";import {dedupeToolCallMessages,@@ -284,6 +285,50 @@ export class SubagentRun {signal?.addEventListener("abort", onAbort, { once: true });let caughtError: ReturnType<typeof classifyAgentError> | undefined;try {+ const initialTaskMessage: AgentMessage = {+ role: "user",+ content: this.opts.task,+ timestamp: Date.now(),+ };+ const agentState = this.agent.state;+ const preflightModel = agentState?.model ?? this.modelBinding().model;+ const preflightMessages = (agentState?.messages ?? []).filter(+ (message) => message.role !== "system",+ );+ const preflightSystemPrompt =+ agentState?.systemPrompt ?? this.opts.systemPrompt;+ const preflightTools = agentState?.tools ?? this.opts.tools;+ const initialContext = await prepareDelegateTurnContext({+ messages: preflightMessages,+ additionalMessages: [initialTaskMessage],+ model: preflightModel,+ taskBrief: this.opts.task,+ retentionMode: "active_turn",+ summaryModels: () =>+ delegateSummaryModels(+ this.provider,+ preflightModel,+ this.opts.sessionId,+ ),+ systemPrompt: preflightSystemPrompt,+ tools: preflightTools,+ retainTaskBriefOnDegradation: false,+ thinkingLevel: agentState?.thinkingLevel ?? this.thinkingLevel,+ signal: this.runSignal(),+ });+ if (this.runSignal().aborted) {+ return this.result("aborted", "The delegated task was aborted.");+ }+ if (initialContext.kind === "overflow") {+ return this.result(+ "failed",+ "",+ subagentContextOverflowError(this.provider.modelId),+ );+ }+ if (initialContext.kind !== "unchanged") {+ this.installContextOutcome(initialContext);+ }await this.agent.prompt(this.opts.task);await this.agent.waitForIdle();while (!signal?.aborted) {@@ -353,6 +398,25 @@ export class SubagentRun {}, this.retryState);}+ private installContextOutcome(+ outcome: Extract<DelegateTurnUpdate, { kind: "compacted" | "degraded" }>,+ ): void {+ const systemMessage = this.agent.state.messages.find(+ (message) => message.role === "system",+ );+ this.agent.state.messages = [+ ...(systemMessage ? [systemMessage] : []),+ ...outcome.messages.filter((message) => message.role !== "system"),+ ];+ if (outcome.kind === "compacted") {+ this.contextCompactions += 1;+ const summaryUsage = usageFromPi(outcome.summaryUsage);+ this.usage = addUsage(this.usage, summaryUsage);+ } else {+ this.contextDegraded = true;+ }+ }+/*** Shape the delegate's next in-run turn, mirroring the session's* `prepareNextTurn` (ADR 0299, decisions 2-4). A compaction rewrites only@@ -364,6 +428,8 @@ export class SubagentRun {): Promise<AgentLoopTurnUpdate | undefined> {const outcome = await prepareDelegateTurnContext({messages: this.agent.state.messages,+ systemPrompt: this.agent.state.systemPrompt,+ tools: this.agent.state.tools,model: this.agent.state.model,taskBrief: this.opts.task,retentionMode: delegateRetentionMode(turn),@@ -387,20 +453,7 @@ export class SubagentRun {);throw new Error(this.pendingContextOverflow.message);}- const systemMessage = this.agent.state.messages.find(- (message) => message.role === "system",- );- this.agent.state.messages = [- ...(systemMessage ? [systemMessage] : []),- ...outcome.messages.filter((message) => message.role !== "system"),- ];- if (outcome.kind === "compacted") {- this.contextCompactions += 1;- const summaryUsage = usageFromPi(outcome.summaryUsage);- this.usage = addUsage(this.usage, summaryUsage);- } else {- this.contextDegraded = true;- }+ this.installContextOutcome(outcome);return {context: {// The loop owns its context array: pi appends every streamed assistant