Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
docs(adr): adopt ADR 0299 subagent context budget
Zihao Peng8a478e54d430
diff --git a/docs/adr/0299-subagent-context-budget.md b/docs/adr/0299-subagent-context-budget.mdnew file mode 100644index 000000000..b096a03fb--- /dev/null+++ b/docs/adr/0299-subagent-context-budget.md@@ -0,0 +1,173 @@+# ADR 0299: Subagent context budget and delegate compaction++- Status: Accepted for implementation+- Date: 2026-09-20+- Deciders: PI-Desktop core+- Amends: ADR 0064 (extends its compaction contract to delegates); extends+ ADR 0062 / ADR 0279+- Related: ADR 0030 (hard boundary), ADR 0049 (retained-tail recovery),+ ADR 0136 (active task boundary), ADR 0246, ADR 0253,+ ADR subagent-model-fallback++## Context++Every context protection the session Agent has is wired for the session Agent+only. A delegate (`Task`, ADR 0062) runs the same pi `Agent` class with none of+it:++- `SubagentRun`'s constructor (`packages/agent-runtime/src/subagent.ts:214`)+ passes `streamFn`, `getApiKey`, `convertToLlm`, `afterToolCall` and+ `initialState`. It does not pass `prepareNextTurnWithContext`. That hook has+ exactly one wiring in the source tree,+ `packages/agent-runtime/src/runtime.ts:1894`, and it belongs to the parent+ session.+- `subagent.ts` has no notion of `contextWindow`, holds no token budget, and+ calls no compaction primitive. A delegate's context grows until the provider+ rejects the request.+- The parent has three layers the delegate lacks: `contextBudget()`+ (`runtime.ts:5652`, `hardLimit = contextWindow − requestHeadroom`), a+ pre-flight compaction in `prompt()` (`runtime.ts:7434`), and turn-boundary+ compaction in `prepareNextTurn()` (`runtime.ts:5839`, ADR 0064).+- A delegate cannot compact on its own initiative either: `new_context` is on+ `SUBAGENT_INHERIT_DENY_TOOLS`+ (`packages/shared/src/subagent-definition.ts:117`), because executing it sets+ the *parent* runtime's `pendingModelCompaction` flag. That denial is correct+ and stays.+- A resumed chain (ADR 0279) is seeded whole: `seedDelegateMessages()`+ (`packages/agent-runtime/src/delegation-history.ts:311`) puts the original+ task first and appends every converted chain row, de-duplicating the task+ brief and truncating nothing. The chain-level `MAX_RESUMABLE_READ_LINES`+ guard removes an over-read chain from the reusable list; it does not bound+ what a still-reusable chain seeds.+- On overflow the provider error classifies as `CONTEXT_TOO_LARGE` with+ `retriable = false` (`packages/agent-runtime/src/agent-errors.ts:407`, `:412`,+ `:426`) and `SubagentRun.run()` returns `result("failed", ...)`+ (`subagent.ts:275`). What reaches the parent model is the provider's raw+ English sentence, which names no recovery it can act on.+- `fallbackModels` is the only escape today, and it does not work for this+ failure: `useNextModel()` (`subagent.ts:302`) carries the accumulated context+ across unchanged, so an alternative whose window is not larger fails+ identically and burns a model slot doing it.++ADR 0064 does not mention subagents or delegates anywhere. This is an omission+from that design, not a deliberate exclusion: the delegate loop is a second+`Agent` in the same sidecar, running the same provider requests against the+same kind of window, and nothing in ADR 0064's reasoning distinguishes it. The+practical consequence is that the feature whose purpose is to keep large reads+out of the session's window (ADR 0062) is the one path with no window+protection at all.++## Decision++1. **One budget formula, shared.** The parent's budget derivation moves+ verbatim into a pure module, `packages/agent-runtime/src/context-budget.ts`,+ and both `PiRuntime` and `SubagentRun` call it.+ `hardLimit = contextWindow − requestHeadroom` with the existing headroom,+ reserve-floor, and `keepRecentTokens` clamps is unchanged, so the session's+ observable behavior is identical before and after the extraction. The module+ takes a model window and maximum output and returns a budget; it reads no+ runtime state, so the two callers cannot drift.++2. **A delegate budget derives from the delegate's own model.** The window and+ output cap come from the model the run actually resolved — a `Task.model`+ override, a definition pin, or the inherited session model (§5f) — not from+ the session model and not from the definition. A per-definition `maxTokens`+ cap (ADR 0210) participates as the output budget it already is.++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.++4. **Degradation before failure.** When a summary cannot be generated, or the+ compacted context still exceeds `hardLimit`, the run keeps the original task+ brief plus the most recent message(s) and discards the rest of its history.+ The run continues and records that it was degraded, so the parent's report+ and the lifecycle details say the delegate lost history rather than+ presenting a complete answer.++5. **A terminal code the parent can act on.** When even the degraded context+ does not fit, the run fails with `SUBAGENT_CONTEXT_OVERFLOW`+ (`retriable: no`) carrying guidance the parent model can execute: narrow the+ task, delegate to a model with a larger context window, or read less at+ once. The provider's raw overflow text is no longer what the parent receives+ for this failure.++6. **Fallback models are re-evaluated against their own window.** Before+ advancing to an alternative, the controller checks the carried context+ against that alternative's budget. An alternative that cannot fit is skipped+ and recorded in `modelFailures` with that reason instead of being attempted+ into the same failure. Ordering, duplicate skipping, retry budgets, and the+ rest of ADR subagent-model-fallback are unchanged.++7. **Resume seeds within the budget.** `seedDelegateMessages()` truncates the+ seeded chain against the delegate's budget. The original task brief and the+ most recent turns are preserved; the oldest tool results are dropped first.+ A resume therefore starts below `hardLimit` instead of overflowing on its+ first request.++8. **`new_context` stays denied to delegates.** Delegate compaction is entirely+ automatic. The tool mutates parent runtime state, so inheriting it would+ let a delegate compact its parent; `SUBAGENT_INHERIT_DENY_TOOLS` keeps it+ out.++## Consequences++- A long delegate no longer ends in a provider overflow error. It compacts,+ and if it cannot compact it degrades, and only then fails — with a code that+ tells the parent what to change.+- A compacted delegate is lossier in exactly the way a compacted session is:+ assistant reasoning and tool output survive only through the summary. A+ delegate's report is the only thing the parent ever sees, so this is less+ visible than for the session — and for the same reason, a degraded run must+ say so, or the parent would read a partial answer as a complete one.+- Compaction costs the delegate a summary request at the moment it is already+ working, so a delegate that crosses the boundary is slower and more+ expensive than one that does not. The alternative it replaces is a failed+ run.+- Sharing one budget module makes the parent's formula load-bearing for two+ callers. A change to it now changes both, which is the point; it also means+ the parent's existing budget tests are the regression surface for delegates.+- Fallback re-evaluation can leave a configured alternative unused. The+ `modelFailures` entry names the reason, so the skip is auditable rather than+ silent.+- Resume truncation means a resumed delegate can start without history it had+ in an earlier round. It keeps the task brief and the recent turns, so the+ resume is still warmer than a cold start, but it is no longer a promise that+ the whole chain is in context.++## Not decided here / out of scope++- **Transcript rows.** Delegate compaction affects the delegate's model context+ only. It rewrites no persisted transcript row. The delegate's rows stay+ complete and visible, and the session runtime already keeps rows carrying+ `parentToolCallId` out of the parent's model context (§5f, Events and+ context), so nothing about the parent's context changes.+- **Durable checkpoints.** No host-core compaction record is written for a+ delegate. The checkpoint chain of ADR 0064 clause 6 remains the session's.+ A delegate's compaction is in-memory for the duration of its run.+- **Transcript presentation.** No compaction divider row, no warning toast, and+ no context-inspector line for a delegate. The user's visible surface for a+ delegate stays the delegation card and its report.+- **`new_context` for delegates.** Denied, per clause 8.+- **Parent behavior.** Clause 1 is an extraction, not a change. Nothing in+ this record alters when or how the session Agent compacts.+- **Cross-run budget accounting.** Concurrent delegates are budgeted+ independently, each against its own model. There is no session-wide ceiling+ across delegates and none is proposed here.++## References++- `docs/adr/0064-codex-parity-context-compaction.md`+- `docs/adr/0062-bounded-subagents-behind-a-task-tool.md`+- `docs/adr/0279-resumable-subagent-delegations.md`+- `docs/adr/0136-active-task-boundary-across-compaction.md`+- `docs/adr/subagent-model-fallback.md`+- `docs/spec/03-runtime/02-agent-runtime.md` §5.1, §5f+- `docs/spec/03-runtime/08-error-codes.md` §3.2+- `docs/spec/06-delivery/04-e2e-test-plan.md`diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 33bb16ed9..917bd6cb0 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -327,6 +327,7 @@ Each ADR includes:| 0296 | [Signed macOS DMG is a two-icon install](0296-macos-signed-dmg-two-icon-install.md) | Accepted (D457; amends ADR 0232 / ADR 0204) || 0297 | [Provider-hosted web search as an adapter capability](0297-provider-hosted-web-search-adapter-capability.md) | Accepted || 0298 | [The app ships no fonts](0298-remove-bundled-fonts.md) | Accepted (D598; amends ADR 0083 / D232) |+| 0299 | [Subagent context budget and delegate compaction](0299-subagent-context-budget.md) | Accepted for implementation (amends ADR 0064; extends ADR 0062 / ADR 0279) || turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted || provider-display-order | [Provider display order](provider-display-order.md) | Accepted || provider-system-certificates | [Desktop sidecar uses OS-trusted certificates](provider-system-certificates.md) | Accepted |diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex b885e5257..a28b7485b 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -492,6 +492,10 @@ be left with the guard off and no way to restore it. Manual `/compact` remainsavailable while the session is idle. Checkpoint generation is abortable andcounts as running state until durable persistence completes.+A delegate (§5f) runs the same derivation against its own resolved model and+compacts at its own turn boundaries, without a durable checkpoint chain of+its own (ADR 0299).+## 5b. Operating mode and planning state- Default product mode: **Agent**@@ -912,6 +916,45 @@ 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+window protection the session has, derived the same way. The budget comes+from the model the run actually resolved — a `Task.model` override, a+definition pin, or the inherited session model — through the shared+derivation of §5.1, so `hardLimit` is that window minus the same request+headroom 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.++An ordered alternative (**Ordered model fallback**, above) is re-evaluated+against its own window before it is attempted: an alternative whose budget+cannot hold the carried context is skipped and recorded in `modelFailures`+with that reason rather than retried into the same failure. A resumed chain+is seeded within the budget — `seedDelegateMessages` preserves the original+task brief and the recent turns and drops the oldest tool results first — so+a resume starts below `hardLimit` instead of overflowing on its first+request.++Delegate compaction affects the delegate's model context only. It rewrites no+persisted transcript row, writes no host-core checkpoint, and adds no+compaction row, warning toast, or context-inspector line; the delegate keeps+its complete visible rows and the parent still sees only reports. Compaction+is entirely automatic: `new_context` remains denied to delegates, because+executing it would set the parent runtime's pending-compaction flag.+**Events and context.** Every event a delegate emits carries`parentToolCallId` and `agentName` on its envelope, and Electron main copies bothonto the persisted row. When the runtime rebuilds model context it skips everydiff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.mdindex a668211c6..cd9f72213 100644--- a/docs/spec/03-runtime/08-error-codes.md+++ b/docs/spec/03-runtime/08-error-codes.md@@ -102,6 +102,7 @@ does not turn temporary thread pressure into a host process exit.| `SPEECH_INPUT_TOO_LARGE` | no | speech input exceeds 25 MB || `SUBAGENT_IDLE_TIMEOUT` | no | withdrawn (D328): idle watchdogs are not armed; the code remains for stored results || `SUBAGENT_DURATION_TIMEOUT` | no | withdrawn (D328): duration watchdogs are not armed; the code remains for stored results |+| `SUBAGENT_CONTEXT_OVERFLOW` | no | a delegate's own model context exceeded its safe budget and neither automatic turn-boundary compaction nor the degraded retry that keeps only the task brief and the most recent messages brought it back below the limit; the failure names the actionable recovery instead of the provider's overflow text |### 3.3 Workspace / tools / permissions| code | retriable | meaning |diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex bb5ad75e3..1b105d06c 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7887,6 +7887,9 @@ identify the platform validation still needed.| F — Persistence (catalog window provenance) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings || Quality (catalog window provenance) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings || M6+ (catalog window provenance) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| C — Conversation & stream (delegate context budget) | E2E-SUBAGENT-context-overflow-compacts-before-failing, E2E-SUBAGENT-context-overflow-reports-actionable-failure, E2E-SUBAGENT-resume-seeds-within-context-budget |+| Quality (delegate context budget) | E2E-SUBAGENT-context-overflow-compacts-before-failing, E2E-SUBAGENT-context-overflow-reports-actionable-failure, E2E-SUBAGENT-resume-seeds-within-context-budget |+| M6+ (delegate context budget) | E2E-SUBAGENT-context-overflow-compacts-before-failing, E2E-SUBAGENT-context-overflow-reports-actionable-failure, E2E-SUBAGENT-resume-seeds-within-context-budget |The `US-UI-*` visual scenarios (§UI shell visual scenarios) trace to theCodex parity decisions in [decisions-log §D](../08-meta/decisions-log.md)@@ -9874,6 +9877,108 @@ This test plan spec is accepted when:capable environment. Required suites: `test:e2e`, `test:e2e:subagents`,`test:e2e:transcript`.+#### E2E-SUBAGENT-context-overflow-compacts-before-failing++- **Preconditions**: An Agent session on a deterministic local transport whose+ model metadata declares a small context window (for example 16,000 tokens)+ and whose replies are scripted. The small window is injected through that+ fake provider, never a real one: real providers and paid APIs are not+ default test environments in this repository. A user definition+ `~/.agents/subagents/reader.md` declares `Read`, `Glob`, and `Grep`, and the+ workspace holds files large enough that two or three reads cross the+ delegate's hard limit.+- **Steps**:+ 1. Delegate a brief that requires reading those files in sequence and record+ every request the transport receives, with its estimated size.+ 2. Read the request that follows the boundary at which the delegate crosses+ its hard limit.+ 3. Repeat with the crossing landing while a tool result is still pending,+ then with it landing on a completed turn.+ 4. Repeat with the summary request scripted to fail.+ 5. Run the same brief as the session Agent on the same fixture and compare+ its requests and transcript rows with a run recorded before this change.+ 6. Inspect the delegation card, the transcript, the context inspector, and+ the parent's own model context after the delegate settles.+- **Expected**: The delegate keeps working instead of failing. The request+ after the crossing is below the hard limit and carries a summary plus the+ applicable retained tail; no request is sent above the window. A pending+ tool result retains as an active turn (latest user message only), a+ completed turn retains none. A failed summary degrades to the original task+ brief plus the most recent message(s), the run still completes, and the+ report and lifecycle details say it was degraded rather than presenting a+ partial answer as complete. Delegate compaction adds no transcript row, no+ host-core checkpoint, no warning toast, and no context-inspector line; the+ delegate's own rows stay complete and the parent's model context still holds+ only the report. The session Agent behaves exactly as it did before.+- **Specs linked**: `03-runtime/02-agent-runtime.md` §5.1, §5f,+ `03-runtime/08-error-codes.md` §3.2, ADR 0299, ADR 0064, ADR 0136+- **Acceptance criterion**: C — Conversation & stream; Quality+- **Milestone**: M6++- **Status**: Draft. Required suites: `test:e2e`, `test:e2e:subagents`.++#### E2E-SUBAGENT-context-overflow-reports-actionable-failure++- **Preconditions**: The same injected small-window fake provider, sized so+ even the degraded context cannot fit. One definition declares two ordered+ `fallbackModels`: one whose window is no larger than the primary's and one+ that is larger. A second definition declares none.+- **Steps**:+ 1. Delegate a brief that overflows past both compaction and degradation, and+ read the tool result the parent receives plus the lifecycle details.+ 2. Repeat for the definition that declares the two alternatives, recording+ which alternatives the transport is actually asked for.+ 3. Repeat with every alternative at the same small window.+ 4. Read the delegation card and the report in English and in Chinese.+ 5. Continue the parent turn, then send a new prompt.+- **Expected**: The run fails with `SUBAGENT_CONTEXT_OVERFLOW`, not retriable,+ and what the parent reads names what it can change — narrow the task,+ delegate to a model with a larger context window, read less at once. The+ provider's raw overflow sentence is not what the parent receives. An+ alternative whose own budget cannot hold the carried context is never+ requested and appears in `modelFailures` with that reason; the larger+ alternative is attempted and can succeed. With no alternative that fits, the+ outcome stays `SUBAGENT_CONTEXT_OVERFLOW` rather than the final provider+ error. The delegate's rows stay durable and visible, the session returns to+ idle, and the next prompt is not `AGENT_BUSY`.+- **Specs linked**: `03-runtime/02-agent-runtime.md` §5f,+ `03-runtime/08-error-codes.md` §3.2, ADR 0299,+ ADR subagent-model-fallback+- **Acceptance criterion**: C — Conversation & stream; Quality+- **Milestone**: M6++- **Status**: Draft. Required suites: `test:e2e`, `test:e2e:subagents`,+ `test:e2e:subagent-models`.++#### E2E-SUBAGENT-resume-seeds-within-context-budget++- **Preconditions**: The same injected small-window fake provider. One settled+ `reader` chain read enough to exceed the delegate hard limit while staying+ under `MAX_RESUMABLE_READ_LINES`; a second settled chain fits well inside+ the budget.+- **Steps**:+ 1. `Task.resume` the over-budget chain and capture its first provider+ request in full.+ 2. `Task.resume` the chain that fits and capture the same request.+ 3. Ask the resumed run for a conclusion the chain reached in its most recent+ round, and for one it reached in its first round.+ 4. Relaunch the app, rebuild the chain index from the transcript, and resume+ the over-budget chain again.+ 5. Accumulate more than `MAX_RESUMABLE_READ_LINES` of read-only output in a+ chain and read the reusable list the next prompt offers.+- **Expected**: The first request of a resumed run is below the hard limit. It+ opens with the original task brief and holds the most recent turns; the+ oldest tool results are dropped first, and dropping an assistant message+ drops its tool calls with it, so no orphaned tool call reaches the provider.+ A chain that fits is seeded whole, exactly as before. The most recent+ conclusion is answered from the seeded context; the first round's may be+ gone, and the run says so rather than inventing it. A resume never fails+ with `CONTEXT_TOO_LARGE` or `SUBAGENT_CONTEXT_OVERFLOW` on its first+ request. `MAX_RESUMABLE_READ_LINES` still removes an over-read chain from+ the reusable list; truncation does not make it resumable again.+- **Specs linked**: `03-runtime/02-agent-runtime.md` §5f, ADR 0299, ADR 0279+- **Acceptance criterion**: C — Conversation & stream; Quality+- **Milestone**: M6++- **Status**: Draft. Required suites: `test:e2e`, `test:e2e:subagents`.+#### E2E-161: A delegation lifecycle row reads as a subagent row- **Preconditions**: A project-bound Agent session with a mocked provider streamdiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 12b23502f..d009d7fd9 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -391,6 +391,9 @@ Headroom 是 16,384 个代币储备底线的最大值,模型最大输出会话空闲时可用。检查点生成是可中止的并且计为运行状态,直到持久持久性完成。+委托(第 5f 节)对照它自己解析出的模型走同一条推导,并在它自己的回合边界上压缩,+但没有属于它自己的持久检查点链(ADR 0299)。+## 5b.运营模式及规划状态- 默认产品模式:**Agent**@@ -680,6 +683,31 @@ Electron main 里解析一次——凭据与 models.dev 快照都在那里——因此包含空格的显示名是合法的。+**上下文预算与压缩(ADR 0299)。** 委托拥有与会话相同的窗口保护,并且以相同方式+推导。预算取自该次运行实际解析出的模型 —— `Task.model` 覆盖、定义引脚,或继承+的会话模型 —— 走第 5.1 节那条共享推导,因此 `hardLimit` 就是该窗口减去同样的+请求余量,而按定义声明的 `maxTokens` 上限作为输出预算参与其中。在委托的回合边界+上,该次运行会重新估计它自己的上下文;达到或超过 `hardLimit` 时,就在下一次提供商+请求之前同步压缩,保留模式按与会话相同的生命周期规则选择:仍有待处理工具结果的+边界按活动回合保留,已完成的边界按完成回合保留。没有任何预计算,也没有第二道阈值。++当摘要无法生成,或压缩后的上下文仍然超出预算时,该次运行降级:只保留原始任务简报+加最近的若干条消息,丢弃其余历史,继续运行,并记录它已被降级,因此报告与生命周期+details 会说明该委托丢失了历史,而不是把一个不完整的答案当作完整答案呈现。若连这样+也放不下,该次运行以 `SUBAGENT_CONTEXT_OVERFLOW`(不可重试)失败,点名父级可以改变+什么 —— 缩小任务范围、改用窗口更大的模型、一次读取更少内容 —— 而不是把提供商的+溢出文本转发出去。++有序备选模型在被尝试之前会对照它自己窗口重新评估:预算装不下已携带上下文的备选+会被跳过,并以该理由记入 `modelFailures`,而不是被重试进同一个失败。恢复来的链在+预算之内播种 —— `seedDelegateMessages` 保留原始任务简报与最近的轮次,并优先丢弃最旧+的工具结果 —— 因此一次恢复从 `hardLimit` 之下开始,而不是在它的第一次请求上就溢出。++委托压缩只影响委托的模型上下文。它不改写任何持久化的转录行,不写入 host-core 检查点,+也不添加压缩行、警告 toast 或上下文检查器条目;委托保留它完整的可见行,父级依旧只看到+报告。压缩完全自动:`new_context` 对委托仍然被拒绝,因为执行它会设置父级运行时的待压缩+标记。+**事件与上下文。** 委托发出的每个事件都在信封上携带 `parentToolCallId` 和`agentName`,Electron main 会把这两者一并复制到持久化的行上。运行时重建模型上下文时会跳过每一条带 `parentToolCallId` 的行:父级从始至终只通过 `TaskWait`diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.mdindex 19020f18c..c4f229e14 100644--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md@@ -103,6 +103,7 @@ stdio 与 Tokio 的动态阻塞池隔离,因此后一种情况| `SPEECH_INPUT_TOO_LARGE` | 不 | 语音输入超过 25 MB || `SUBAGENT_IDLE_TIMEOUT` | 不 | 已撤回(D328):空闲看门狗不再武装;代码仅为已存储结果保留 || `SUBAGENT_DURATION_TIMEOUT` | 不 | 已撤回(D328):时长看门狗不再武装;代码仅为已存储结果保留 |+| `SUBAGENT_CONTEXT_OVERFLOW` | 不 | 委派自身的模型上下文超出其安全预算,自动的回合边界压缩与仅保留任务简报和最近消息的降级重试都没能把它带回限制以内;该失败给出可执行的恢复方式,而不是提供商的溢出文本 |### 3. 3 工作空间/工具/权限diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex f2260c45e..d4dee1173 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -4280,6 +4280,86 @@ IPC 请求无法关闭。`apps/desktop/test/assistant-turns.test.mjs`);桌面旅程需要具备条件的环境。必需套件:`test:e2e`、`test:e2e:subagents`、`test:e2e:transcript`。+#### E2E-SUBAGENT-context-overflow-compacts-before-failing++- **先决条件**:一个使用确定性本地传输的 Agent 会话,其模型元数据声明了一个很小的+ 上下文窗口(例如 16,000 个 token),回复也是脚本化的。这个小窗口由注入的伪提供商+ 给出,绝不来自真实提供商:在本仓库里,真实提供商与付费 API 不是默认测试环境。+ 一份用户定义 `~/.agents/subagents/reader.md` 声明 `Read`、`Glob` 与 `Grep`,+ 工作区里的文件大到只需两三次读取就会越过委托的硬边界。+- **步骤**:+ 1. 委派一个必须按顺序读完这些文件的任务简报,记录传输收到的每一次请求及其+ 估算大小。+ 2. 读取委托越过硬边界之后的那一次请求。+ 3. 让越界发生在仍有待处理工具结果的时刻,再让它发生在一个已完成的回合上,+ 各重复一次。+ 4. 把摘要请求脚本化为失败,再重复一次。+ 5. 用同一套夹具让会话 Agent 跑同样的任务简报,把它的请求与转录行同本次改动+ 之前记录的一次运行作对比。+ 6. 在委托结算后检查委派卡片、转录、上下文检查器,以及父级自己的模型上下文。+- **预期**:委托继续工作,而不是失败。越界之后的那一次请求低于硬边界,携带摘要+ 加上适用的保留尾部;没有任何请求超出窗口被发出。仍有待处理工具结果时按活动+ 回合保留(只留最新的用户消息),已完成的回合不保留。摘要失败会降级为原始任务+ 简报加最近的若干条消息,该次运行依然完成,报告与生命周期 details 会说明它已被+ 降级,而不是把一个不完整的答案当作完整答案呈现。委托压缩不添加转录行、不写+ host-core 检查点、不弹警告 toast、也不添加上下文检查器条目;委托自己的行保持+ 完整,父级的模型上下文里依旧只有那份报告。会话 Agent 的行为与改动之前完全一致。+- **链接规格**:`03-runtime/02-agent-runtime.md` §5.1、§5f、+ `03-runtime/08-error-codes.md` §3.2、ADR 0299、ADR 0064、ADR 0136+- **验收**:C — 对话和直播;品质+- **里程碑**:M6++- **状态**:草稿。必需套件:`test:e2e`、`test:e2e:subagents`。++#### E2E-SUBAGENT-context-overflow-reports-actionable-failure++- **先决条件**:同一个注入的小窗口伪提供商,窗口小到连降级后的上下文也放不下。+ 一份定义声明两个有序 `fallbackModels`:一个窗口不比主模型更大,另一个更大。+ 第二份定义不声明任何备选。+- **步骤**:+ 1. 委派一个会一路越过压缩与降级的任务简报,读取父级收到的工具结果以及生命周期+ details。+ 2. 对声明了那两个备选定义重复一次,记录传输实际被请求了哪些备选。+ 3. 让每个备选都处在同样的小窗口上,再重复一次。+ 4. 分别在英文与中文下读取委派卡片与报告。+ 5. 继续父级回合,然后发送一条新的提示。+- **预期**:该次运行以 `SUBAGENT_CONTEXT_OVERFLOW`(不可重试)失败,父级读到的内容+ 点名它可以改变什么 —— 缩小任务范围、改用上下文窗口更大的模型、一次读取更少内容。+ 提供商原始的溢出语句不是父级收到的东西。自身预算装不下已携带上下文的备选永远不会+ 被请求,并以该理由出现在 `modelFailures` 里;窗口更大的那个备选会被尝试,并且可以+ 成功。当没有任何备选装得下时,结果仍是 `SUBAGENT_CONTEXT_OVERFLOW`,而不是最后那个+ 提供商错误。委托的行保持持久且可见,会话回到空闲,下一条提示不会是 `AGENT_BUSY`。+- **链接规格**:`03-runtime/02-agent-runtime.md` §5f、+ `03-runtime/08-error-codes.md` §3.2、ADR 0299、+ ADR subagent-model-fallback+- **验收**:C — 对话和直播;品质+- **里程碑**:M6++- **状态**:草稿。必需套件:`test:e2e`、`test:e2e:subagents`、+ `test:e2e:subagent-models`。++#### E2E-SUBAGENT-resume-seeds-within-context-budget++- **先决条件**:同一个注入的小窗口伪提供商。一条已结算的 `reader` 链读取的内容+ 足以超出委托的硬边界,但仍在 `MAX_RESUMABLE_READ_LINES` 以内;第二条已结算的+ 链远远落在预算之内。+- **步骤**:+ 1. 对超出预算的那条链执行 `Task.resume`,完整捕获它的第一次提供商请求。+ 2. 对落在预算之内的那条链执行 `Task.resume`,捕获同样的请求。+ 3. 向恢复后的运行询问该链在最近一轮得出的结论,再询问它在第一轮得出的结论。+ 4. 重启应用,从转录重建链索引,再次恢复那条超出预算的链。+ 5. 在一条链里累积超过 `MAX_RESUMABLE_READ_LINES` 的只读输出,读取下一条提示给出+ 的可复用清单。+- **预期**:恢复后运行的第一次请求低于硬边界。它以原始任务简报开头,并保有最近的+ 若干轮;最旧的工具结果优先被丢弃,而丢弃一条助手消息会连同它的工具调用一起丢弃,+ 因此没有孤立的工具调用会到达提供商。落在预算之内的链仍按原样整条播种。最近一轮的+ 结论能从播种的上下文里答出;第一轮的结论可能已经不在,此时该次运行会照实说明,而+ 不是凭空编造。一次恢复绝不会在它的第一次请求上以 `CONTEXT_TOO_LARGE` 或+ `SUBAGENT_CONTEXT_OVERFLOW` 失败。`MAX_RESUMABLE_READ_LINES` 仍然会把读取过多的链+ 移出可复用清单;裁剪不会让它重新变得可恢复。+- **链接规格**:`03-runtime/02-agent-runtime.md` §5f、ADR 0299、ADR 0279+- **验收**:C — 对话和直播;品质+- **里程碑**:M6++- **状态**:草稿。必需套件:`test:e2e`、`test:e2e:subagents`。+#### E2E-145:工具结果读取为结构化块,从不 JSON- **先决条件**:项目绑定的 Agent 会话,具有允许的权限@@ -5162,6 +5242,9 @@ IPC 请求无法关闭。| F — 持久化(目录窗口来源) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings || 品质(目录窗口来源) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings || M6+(目录窗口来源) | E2E-MODEL-catalog-window-correction-reaches-saved-bindings |+| C — 对话和直播(委托上下文预算) | E2E-SUBAGENT-context-overflow-compacts-before-failing、E2E-SUBAGENT-context-overflow-reports-actionable-failure、E2E-SUBAGENT-resume-seeds-within-context-budget |+| 品质(委托上下文预算) | E2E-SUBAGENT-context-overflow-compacts-before-failing、E2E-SUBAGENT-context-overflow-reports-actionable-failure、E2E-SUBAGENT-resume-seeds-within-context-budget |+| M6+(委托上下文预算) | E2E-SUBAGENT-context-overflow-compacts-before-failing、E2E-SUBAGENT-context-overflow-reports-actionable-failure、E2E-SUBAGENT-resume-seeds-within-context-budget |`US-UI-*` 视觉场景(§UI shell 视觉场景)追踪到[决策日志 §D](/zh-CN/spec/08-meta/decisions-log) 中的法典平价决策diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 485ebd199..3348ab34c 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -2118,6 +2118,7 @@ sklm: {"MUTATION_RETRY_BUDGET_EXHAUSTED": "Die gleiche Bearbeitung schlug dreimal fehl, daher wurde dieser Zug abgebrochen, anstatt es erneut zu versuchen. Bitten Sie erneut, fortzufahren.","CONTEXT_TOO_LARGE": "Dieser Chat ist nach der Kontextwiederherstellung immer noch zu lang. Kürzen Sie Ihre Nachricht oder starten Sie einen neuen Chat.","CONTEXT_COMPACTION_FAILED": "Der Modellkontext dieser Konversation konnte nicht komprimiert werden.",+ "SUBAGENT_CONTEXT_OVERFLOW": "Die Aufgabe eines Subagenten hat das Kontextlimit seines Modells überschritten. Grenzen Sie die Aufgabe ein, geben Sie dem Subagenten ein Modell mit größerem Kontextfenster oder lassen Sie ihn weniger auf einmal lesen.","AGENT_BUSY": "Dieser Chat funktioniert bereits. Warten Sie, bis der Vorgang abgeschlossen ist, oder stoppen Sie ihn zuerst.","TURN_ABORTED": "Gestoppt.","workspaceActivationFailed": "Projekt-Arbeitsbereich konnte nicht aktiviert werden",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex f3590bb7a..228f2b33c 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -2159,6 +2159,8 @@ importConfirm: "Imported extensions run inside the agent process with the same a"The same edit failed three times, so this turn stopped instead of retrying blind. Ask again to continue.",CONTEXT_TOO_LARGE: "This chat is still too long after context recovery. Shorten your message or start a new chat.",CONTEXT_COMPACTION_FAILED: "Couldn't compact this conversation's model context.",+ SUBAGENT_CONTEXT_OVERFLOW:+ "A subagent's task grew past its model's context limit. Narrow the task, give the subagent a model with a larger context window, or have it read less at once.",AGENT_BUSY: "This chat is already working. Wait for it to finish, or stop it first.",TURN_ABORTED: "Stopped.",workspaceActivationFailed: "Unable to activate project workspace",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 088ef61cb..82fa1993b 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -2118,6 +2118,7 @@ sklm: {"MUTATION_RETRY_BUDGET_EXHAUSTED": "La misma edición falló tres veces, por lo que este turno se detuvo en lugar de volver a intentarlo a ciegas. Pregunta nuevamente para continuar.","CONTEXT_TOO_LARGE": "Este chat aún dura demasiado después de la recuperación del contexto. Acorta tu mensaje o inicia un nuevo chat.","CONTEXT_COMPACTION_FAILED": "No se pudo compactar el contexto del modelo de esta conversación.",+ "SUBAGENT_CONTEXT_OVERFLOW": "La tarea de un subagente superó el límite de contexto de su modelo. Reduce el alcance de la tarea, dale al subagente un modelo con una ventana de contexto más grande o haz que lea menos a la vez.","AGENT_BUSY": "Este chat ya está funcionando. Espere a que termine o deténgalo primero.","TURN_ABORTED": "Detenido.","workspaceActivationFailed": "No se pudo activar el espacio de trabajo del proyecto",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 1150c579e..4626411e0 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -2118,6 +2118,7 @@ sklm: {"MUTATION_RETRY_BUDGET_EXHAUSTED": "La même modification a échoué trois fois, donc ce tour s'est arrêté au lieu de réessayer en aveugle. Demandez à nouveau pour continuer.","CONTEXT_TOO_LARGE": "Ce chat est encore trop long après la récupération du contexte. Raccourcissez votre message ou démarrez une nouvelle discussion.","CONTEXT_COMPACTION_FAILED": "Impossible de compacter le contexte du modèle de cette conversation.",+ "SUBAGENT_CONTEXT_OVERFLOW": "La tâche d'un sous-agent a dépassé la limite de contexte de son modèle. Réduisez la tâche, confiez au sous-agent un modèle doté d'une fenêtre de contexte plus grande, ou faites-lui lire moins de choses à la fois.","AGENT_BUSY": "Ce chat fonctionne déjà. Attendez qu'il se termine ou arrêtez-le d'abord.","TURN_ABORTED": "Arrêté.","workspaceActivationFailed": "Impossible d'activer l'espace de travail du projet",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 25c6873db..5803640f6 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -2157,6 +2157,8 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이"같은 편집이 세 번 실패하여 무작정 재시도하지 않고 이 턴을 중지했습니다. 계속하려면 다시 요청하세요.",CONTEXT_TOO_LARGE: "컨텍스트를 복구한 후에도 이 채팅이 너무 깁니다. 메시지를 줄이거나 새 채팅을 시작하세요.",CONTEXT_COMPACTION_FAILED: "이 대화의 모델 컨텍스트를 압축할 수 없습니다.",+ SUBAGENT_CONTEXT_OVERFLOW:+ "서브에이전트의 작업이 모델의 컨텍스트 한도를 넘었습니다. 작업 범위를 좁히거나, 컨텍스트 창이 더 큰 모델을 지정하거나, 한 번에 읽는 양을 줄이세요.",AGENT_BUSY: "이 채팅은 이미 작업 중입니다. 완료될 때까지 기다리거나 먼저 중지하세요.",TURN_ABORTED: "중지됨",workspaceActivationFailed: "프로젝트 작업 공간을 활성화할 수 없습니다",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex eeb41d0e8..c20fec938 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -2157,6 +2157,8 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç"Aynı düzenleme üç kez başarısız oldu, bu yüzden körü körüne yeniden denemek yerine tur durdu. Devam etmek için yeniden sorun.",CONTEXT_TOO_LARGE: "Bağlam kurtarmadan sonra bu sohbet hâlâ çok uzun. İletinizi kısaltın veya yeni sohbet açın.",CONTEXT_COMPACTION_FAILED: "Bu sohbetin model bağlamı sıkıştırılamadı.",+ SUBAGENT_CONTEXT_OVERFLOW:+ "Bir alt ajanın görevi, modelinin bağlam sınırını aştı. Görevi daraltın, alt ajana daha büyük bağlam penceresi olan bir model verin veya bir defada daha az okumasını sağlayın.",AGENT_BUSY: "Bu sohbet zaten çalışıyor. Bitmesini bekleyin veya önce durdurun.",TURN_ABORTED: "Durduruldu.",workspaceActivationFailed: "Proje çalışma alanı etkinleştirilemedi",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex d1d1cfe8d..aecacba61 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -2121,6 +2121,8 @@ sklm: {"同一处修改连续失败三次,本轮已停止,不再盲目重试。再说一次即可继续。",CONTEXT_TOO_LARGE: "上下文恢复后对话仍然过长。请缩短消息内容或新开对话。",CONTEXT_COMPACTION_FAILED: "无法压缩当前对话的模型上下文。",+ SUBAGENT_CONTEXT_OVERFLOW:+ "子智能体的任务超出了其模型的上下文上限。请缩小任务范围、为它选择上下文窗口更大的模型,或让它一次读取更少的内容。",AGENT_BUSY: "此对话正在处理中。请等待完成,或先停止当前任务。",TURN_ABORTED: "已停止。",workspaceActivationFailed: "无法激活项目工作区",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 17e227859..a3f8755d3 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -2119,6 +2119,8 @@ sklm: {"同一處修改連續失敗三次,本輪已停止,不再盲目重試。再說一次即可繼續。",CONTEXT_TOO_LARGE: "上下文恢復後對話仍然過長。請縮短訊息內容或新開對話。",CONTEXT_COMPACTION_FAILED: "無法壓縮當前對話的模型上下文。",+ SUBAGENT_CONTEXT_OVERFLOW:+ "子智慧體的任務超出了其模型的上下文上限。請縮小任務範圍、為它選擇上下文視窗更大的模型,或讓它一次讀取更少的內容。",AGENT_BUSY: "此對話正在處理中。請等待完成,或先停止當前任務。",TURN_ABORTED: "已停止。",workspaceActivationFailed: "無法啟用專案工作區",diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.tsindex adf4c6b0a..02a097b3f 100644--- a/packages/shared/src/errors.ts+++ b/packages/shared/src/errors.ts@@ -85,6 +85,13 @@ export const ErrorCodes = {SPEECH_INPUT_TOO_LARGE: "SPEECH_INPUT_TOO_LARGE",SUBAGENT_IDLE_TIMEOUT: "SUBAGENT_IDLE_TIMEOUT",SUBAGENT_DURATION_TIMEOUT: "SUBAGENT_DURATION_TIMEOUT",+ /**+ * A delegate's own model context exceeded the safe budget: automatic+ * compaction and the degraded retry both failed to bring the subagent's+ * input back under its model's limit. Not retriable — the task itself, the+ * delegate's model, or how much it reads at once has to change.+ */+ SUBAGENT_CONTEXT_OVERFLOW: "SUBAGENT_CONTEXT_OVERFLOW",WORKSPACE_REQUIRED: "WORKSPACE_REQUIRED",PATH_OUTSIDE_WORKSPACE: "PATH_OUTSIDE_WORKSPACE",TOOL_NOT_FOUND: "TOOL_NOT_FOUND",