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(delegation): keep the prompt prefix stable across settlements (#1903)
Lan3e4bbe123823
diff --git a/docs/adr/0279-resumable-subagent-delegations.md b/docs/adr/0279-resumable-subagent-delegations.mdindex 442acb652..4496a1ea1 100644--- a/docs/adr/0279-resumable-subagent-delegations.md+++ b/docs/adr/0279-resumable-subagent-delegations.md@@ -161,12 +161,19 @@ Reads are counted from the delegate's read-only tool rows (`Read`, `Glob`,`Grep`, `BrowserPreview`), accumulated per chain; write-tool targets are notcounted and not listed.-### 9. The parent sees a resumable list in its system prompt--Each prompt composes the current resumable chains into the parent's system-prompt: agent name, delegation id, the one-line objective, and the files the-chain has read (capped at 8, truncated). Only settled, in-budget chains appear —-a running chain is never listed, so the parent is not lured into resuming one.+### 9. The parent discovers a resumable list through `TaskList`++`TaskList` reports the current resumable chains: agent name, delegation id, the+one-line objective, and the files the chain has read (capped at 8, truncated).+Only settled, in-budget chains appear — a running chain is never listed, so the+parent is not lured into resuming one.++The list deliberately stays out of the system prompt. It changes on every+settlement, and rewriting instructions mid-session invalidates the request+prefix providers cache on; ADR 0337 records that trade-off and supersedes the+earlier "compose the list into the prompt" decision. A failed resume still names+the reusable ids in its own tool error, so discovery never depends on the parent+having listed first.The `resume` parameter's own schema description carries the rule that reuserequires the id; prose alone does not resume anything.diff --git a/docs/adr/0337-stable-prompt-prefix-across-delegation.md b/docs/adr/0337-stable-prompt-prefix-across-delegation.mdnew file mode 100644index 000000000..534d0cd37--- /dev/null+++ b/docs/adr/0337-stable-prompt-prefix-across-delegation.md@@ -0,0 +1,104 @@+# ADR 0337: Keep the request prefix stable across delegation settlements++- Status: Accepted+- Date: 2026-10-25+- Deciders: PI-Desktop maintainers+- Related: ADR 0279 (resumable subagent delegations), ADR 0089 (delegation+ tools), `docs/spec/03-runtime/02-agent-runtime.md`+- Amends: ADR 0279 §9++## Context++ADR 0279 §9 put the resumable-chain list into the parent's **system prompt**,+and recomposed that prompt every time a delegation settled. The intent was that+the parent sees what it can continue without calling a tool.++That recomposition breaks provider prompt caching. Anthropic, OpenAI, and the+gateways in front of them cache a conversation by the exact byte prefix of the+request: instructions, then tools, then messages. PI-Desktop does not rewrite+the leading system message in place — `syncSystemSections` appends a new+system message carrying only the changed sections+(`packages/agent-runtime/src/system-transcript.ts`). Which one of two request+shapes goes out depends on the transport:++- A model with `supportsMidConvoSystemMessages` keeps the appended system+ message in place, so only the tail is new.+- Every other model goes through `collapseSystemMessages`+ (`@earendil-works/pi-ai`, `utils/transcript.js`), which replays all system+ messages into **the first** one. The changed section therefore changes the+ first system block of the request.++The verified catalog sets `supportsMidConvoSystemMessages` only for a narrow+DeepSeek route (`packages/agent-runtime/src/fixed-tool-declarations.ts`,+`transcript-compat.ts`); for everything else the collapsed shape applies. So+each settlement — up to `MAX_SUBAGENT_CONCURRENCY` per turn, plus resumptions —+could invalidate the whole cached prefix, not just its tail. The cost scales+with session length, which is exactly the case delegation exists to keep cheap.++The organization of the system prompt also matters more than one prompt block:+a section that changes on its own schedule turns a stable conversation into a+sequence of unrelated caches.++## Decision++1. **The system prompt never carries delegation state.** `composeSystemPrompt`+ no longer composes a resumable block, and the runtime no longer recomposes+ the prompt on settlement. Instructions change only for reasons the user+ controls: mode, project instructions, memory, skills, custom prompt.+2. **`TaskList` is the discovery path.** Its result now carries the resumable+ chains — agent name, `delegationId`, objective, and up to+ `MAX_RESUMABLE_LISTED_FILES` files read — as both text (the existing+ `formatResumableList` rendering) and a structured `details.resumable` array.+ Its description names `Task(resume: ...)` as the reason to call it.+3. **Tool errors stay authoritative.** Unknown, mismatched, over-budget, and+ history-less resume ids still return a tool error that names the reusable+ ids inline (`DelegationChainRegistry.unknownResumeError` /+ `noHistoryResumeError`), so a failed resume never depends on the parent+ having called `TaskList` first.+4. **The registry keeps its own gate.** `resumableList` still excludes running,+ non-resumable, and over-budget chains, so a listing never advertises an id+ the resume path would reject.++The `resumablePromptStale` deferral, the `refreshResumablePrompt` hook, and the+two `applyPendingResumablePrompt` calls in the silent-turn and progress-turn+recovery paths are removed with their reason: there is no prompt-level+resumable state left to defer.++## Consequences++- Delegation settlements are invisible to the request prefix. A long session+ that spawns many delegates keeps one cache lineage until something the user+ actually changed (instructions, mode, skills, conversation content) does.+- The parent must call `TaskList` to learn ids proactively. That is a tool call+ the model already owns and only pays for when it needs the ids; a resume it+ attempts blind still gets the ids back in the error.+- `TaskList` grows with the reusable chain count (bounded by+ `MAX_RESUMABLE_CHAINS_PER_AGENT`), not with the conversation.+- This ADR fixes one source of prefix churn, not all of them.+ `TOOL_ACTIVATION_SECTION` (on-demand tool activation) and the context-budget+ reminder still append system messages mid-turn for their own documented+ reasons; changing those is separate work with its own trade-offs.+- ADR 0279 §9 is superseded by decision 2 here; its other decisions stand.++## Alternatives Considered++- **Refresh the list only at turn start.** Cheap and would cut the churn to one+ rewrite per turn, but it still rewrites the collapsed first system block+ whenever the settled set grew, so a turn after every delegation misses the+ whole prefix. It also keeps a per-turn-variable section in instructions whose+ job is to be stable.+- **Move the list into the last user message.** Keeps the head stable and needs+ no new tool surface, but it rewrites conversation history the transcript owns+ and would make the persisted rows disagree with the request.+- **Keep the list in the prompt and mark it cache-friendly.** Providers cache+ bytes, not sections; no marker changes the invalidation.++## Verification++- `packages/agent-runtime/src/runtime.test.ts`: a settled delegation leaves both+ `composedSystemPrompt` and the live system prompt byte-identical, and the+ resumable entry appears in `TaskList`'s text and `details.resumable`.+- `packages/agent-runtime/src/delegation-chain.test.ts`: listing gates+ (running, non-resumable, over-budget, ordering) and the block rendering.+- `apps/desktop` transcript and delegation suites are unaffected; the change is+ confined to prompt composition and the `TaskList` result shape.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 4452e1b44..f535b94e9 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -387,5 +387,6 @@ Each ADR includes:| local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation || 0332 | [macOS keeps its translucent window surface with an opaque opt-out](0332-macos-opaque-window-surface.md) | Accepted (D665, amended by D666 and D667; supersedes the macOS vibrancy window backing from D348; issue #1064) || gen-ui-inline-visualization | [Inline generative UI visualizations](gen-ui-inline-visualization.md) | Accepted (D671) |+| 0337 | [Keep the request prefix stable across delegation settlements](0337-stable-prompt-prefix-across-delegation.md) | Accepted (supersedes ADR 0279 §9) || model-reasoning-effort-override | [Model reasoning effort override](model-reasoning-effort-override.md) | Proposed |diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 428577b23..1d035d08a 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -964,7 +964,9 @@ core set rather than the on-demand catalog of §7.1:reports when they finish, even if the parent already stopped calling tools.Only `TaskStop` or user Stop aborts a delegate.- `TaskList()` — reports every delegation of the session with status and a- running heartbeat.+ running heartbeat, plus the resumable chains (`details.resumable`) the parent+ can continue with `Task(resume: ...)`; this is the only read path for that+ list (ADR 0337).- `TaskStop(delegationIds?)` — stops running delegations (defaults to all);waits for each abort to settle, then persists `status: "stopped"` with`completedAt` on `details.stopped[]`. Stopped delegations read as `stopped`.@@ -1106,11 +1108,12 @@ a non-resumable status, an over-budget chain, and a chain whose rows are goneeach return a tool error naming the reason and, for an unknown id, the reusableids when there are any.-The parent discovers reusable chains through the system prompt, which lists+The parent discovers reusable chains through `TaskList`, whose result listseach chain's latest `delegationId`, its objective, and up to`MAX_RESUMABLE_LISTED_FILES` (8) of the files it read (with a `(+N more)`-suffix past that). The list is recomposed when a delegation settles, around the-existing prompt sections. A resumed run is an ordinary delegation for+suffix past that). The list never enters the system prompt: it changes on every+settlement, and rewriting instructions mid-session invalidates the request+prefix providers cache on (ADR 0337). A resumed run is an ordinary delegation for`MAX_SUBAGENT_CONCURRENCY`, `TaskWait`, `TaskList`, `TaskStop`, and lifecyclesnapshots. The immediate `Task` result and the lifecycle details add`resumedFrom` for audit; the transcript renders a chain as one continuousdiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 4811a85ba..ae7f12df8 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -703,7 +703,8 @@ Frontmatter 新增 `permission: inherit | ask | accept-edits | auto`(默认(D328)—— 等待返回心跳(谁、状态、已用时、轮数、最后工具)以及已完成的报告。运行时会保持父级回合打开,并在它们完成时把剩余报告交回,即使父级已经停止调用工具。只有 `TaskStop` 或用户 Stop 才会中止委托。-- `TaskList()` — 报告会话的每个委托及其状态和运行中心跳。+- `TaskList()` — 报告会话的每个委托及其状态和运行中心跳,并给出父级可用+ `Task(resume: ...)` 继续的可复用链(`details.resumable`);这是该清单唯一的读取路径(ADR 0337)。- `TaskStop(delegationIds?)` — 停止正在运行的委托(默认全部);等待每次中止结算后,在 `details.stopped[]` 上持久化 `status: "stopped"` 与`completedAt`。被停止的委托读作 `stopped`。@@ -787,10 +788,11 @@ fallbacks, session inheritance, and current override grants; other definitions'private pins are excluded. A denied known key never selects another account bymodel id (#841).-父级通过系统提示发现可复用的链:那里列出每条链最新的 `delegationId`、它的目标,以及它-读过的文件最多 `MAX_RESUMABLE_LISTED_FILES`(8)个(超出部分带 `(+N more)` 后缀)。-清单会在委托结算时围绕既有的提示段落重新组装。对 `MAX_SUBAGENT_CONCURRENCY`、-`TaskWait`、`TaskList`、`TaskStop` 以及生命周期快照而言,恢复来的运行就是一个普通+父级通过 `TaskList` 发现可复用的链:它的结果列出每条链最新的 `delegationId`、它的目标,+以及它读过的文件最多 `MAX_RESUMABLE_LISTED_FILES`(8)个(超出部分带 `(+N more)` 后缀)。+这份清单**不进系统提示**:它每次结算都会变,而中途改写指令会使 provider 缓存的请求前缀失效+(ADR 0337)。对 `MAX_SUBAGENT_CONCURRENCY`、`TaskWait`、`TaskList`、`TaskStop`+以及生命周期快照而言,恢复来的运行就是一个普通委托。委托。`Task` 的立即返回结果与生命周期 details 会增加 `resumedFrom` 以便追溯;transcript 把一条链渲染成它最新 `Task` 卡片下的一段连续多轮对话,不带单独的“已恢复”标记。diff --git a/packages/agent-runtime/src/delegation-chain.test.ts b/packages/agent-runtime/src/delegation-chain.test.tsindex 66634e54d..70b69ed8c 100644--- a/packages/agent-runtime/src/delegation-chain.test.ts+++ b/packages/agent-runtime/src/delegation-chain.test.ts@@ -166,7 +166,7 @@ describe("resolveResume", () => {});});-describe("resumableList / promptBlock", () => {+describe("resumableList / resumableBlock", () => {it("excludes running, non-resumable and over-budget chains, newest first", () => {vi.useFakeTimers({ now: 1_700_000_000_000 });const registry = new DelegationChainRegistry();@@ -238,7 +238,7 @@ describe("resumableList / promptBlock", () => {});registry.settle("res-2", "failed");- const block = registry.promptBlock({ runningDelegationIds: NONE });+ const block = registry.resumableBlock({ runningDelegationIds: NONE });expect(block).toContain("explorer / del-1: explore the parser");expect(block).toContain("Files read: a1.ts, a2.ts");expect(block).toContain("(+1 more)");@@ -250,7 +250,7 @@ describe("resumableList / promptBlock", () => {const registry = new DelegationChainRegistry();start(registry, { delegateSessionId: "res-1", delegationId: "del-1" });registry.settle("res-1", "completed");- expect(registry.promptBlock({ runningDelegationIds: NONE })).toContain(+ expect(registry.resumableBlock({ runningDelegationIds: NONE })).toContain("Files read: none recorded",);});diff --git a/packages/agent-runtime/src/delegation-chain.ts b/packages/agent-runtime/src/delegation-chain.tsindex 3c21f47ea..150fee00c 100644--- a/packages/agent-runtime/src/delegation-chain.ts+++ b/packages/agent-runtime/src/delegation-chain.ts@@ -200,7 +200,13 @@ export class DelegationChainRegistry {return listed.sort((left, right) => right.lastActivityAt - left.lastActivityAt);}- promptBlock(options: {+ /**+ * The resumable chains as one text block. This rides in a `TaskList` result,+ * never in the system prompt: the list changes every time a delegation+ * settles, and a system-prompt change rewrites the request prefix that+ * provider prompt caches key on (ADR 0337).+ */+ resumableBlock(options: {runningDelegationIds: ReadonlySet<string>;}): string {return formatResumableList(this.resumableList(options));diff --git a/packages/agent-runtime/src/delegation-history.ts b/packages/agent-runtime/src/delegation-history.tsindex dca85fbf3..dbfe4e484 100644--- a/packages/agent-runtime/src/delegation-history.ts+++ b/packages/agent-runtime/src/delegation-history.ts@@ -675,6 +675,13 @@ export function listedReadFiles(return { files: files.slice(0, limit), omitted: files.length - limit };}+/**+ * Render the resumable chains for a tool result.+ *+ * This text used to ride in the parent's system prompt, which made every+ * settlement rewrite the request prefix providers cache on (ADR 0337). It is+ * now carried by `TaskList`, so the parent reads it when it needs the ids.+ */export function formatResumableList(chains: readonly ResumableChain[]): string {if (chains.length === 0) return "";const lines = [diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 55bafca1e..e2df8ce7c 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -9252,6 +9252,33 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});+ it("keeps a running delegation out of the resumable list TaskList reports", async () => {+ const runtime = createRuntime({ subagents: [explorer] });+ const internals = runtime as any;+ subagentRuns.calls.length = 0;+ subagentRuns.instances.length = 0;+ subagentRuns.deferred = true;+ subagentRuns.resolveRun = undefined;+ const started = await internals.agent.state.tools+ .find((candidate: { name: string }) => candidate.name === "Task")+ .execute("task-1", { agent: "explorer", task: "Find it." });+ const delegationId = (started.details as { delegationId: string }).delegationId;++ const listed = await internals.agent.state.tools+ .find((candidate: { name: string }) => candidate.name === "TaskList")+ .execute("list-1", {});+ // The running delegation is reported as progress, never as a resume target:+ // resuming it is a tool error the parent must not be lured into.+ expect(listed.details.delegations).toContainEqual(+ expect.objectContaining({ delegationId, status: "running" }),+ );+ expect(listed.details.resumable).toEqual([]);+ expect(listed.content[0].text).not.toContain("Reusable subagent sessions");++ subagentRuns.deferred = false;+ await runtime.dispose();+ });+it("scopes a mutating delegate's tool calls with its permission", async () => {const mutator: SubagentDefinition = {name: "fixer",@@ -9554,8 +9581,9 @@ describe("DesktopAgentRuntime subagents", () => {await runtime.dispose();});- it("lists a settled delegation in the parent's system prompt", async () => {+ it("lists a settled delegation through TaskList, not in the system prompt", async () => {const runtime = createRuntime({ subagents: [explorer] });+ const internals = runtime as any;subagentRuns.calls.length = 0;subagentRuns.deferred = true;const started = await startTask(runtime, "task-1", {@@ -9564,6 +9592,7 @@ describe("DesktopAgentRuntime subagents", () => {description: "find the bug",});const delegationId = (started.details as any).delegationId as string;+ const promptWhileRunning = internals.composedSystemPrompt;subagentRuns.resolveRun?.({agentName: "explorer",status: "completed",@@ -9571,11 +9600,29 @@ describe("DesktopAgentRuntime subagents", () => {turns: 1,toolCalls: 0,});+ // ADR 0337: a settlement must not rewrite the request prefix providers+ // cache on, so the instructions stay byte-identical and the list is read+ // on demand instead.await vi.waitFor(() => {- expect((runtime as any).agent.state.systemPrompt).toContain(- `explorer / ${delegationId}: find the bug`,- );+ expect(internals.delegations.get(delegationId)?.status).toBe("completed");});+ expect(internals.composedSystemPrompt).toBe(promptWhileRunning);+ expect(internals.agent.state.systemPrompt).toBe(promptWhileRunning);+ expect(internals.agent.state.systemPrompt).not.toContain(delegationId);++ const listed = await internals.agent.state.tools+ .find((tool: any) => tool.name === "TaskList")+ .execute("list-1", {});+ expect(listed.content[0].text).toContain(+ `explorer / ${delegationId}: find the bug`,+ );+ expect(listed.details.resumable).toContainEqual(+ expect.objectContaining({+ agent: "explorer",+ delegationId,+ objective: "find the bug",+ }),+ );subagentRuns.deferred = false;await runtime.dispose();});@@ -9746,13 +9793,26 @@ describe("DesktopAgentRuntime subagents", () => {turns: 1,toolCalls: 1,});+ // The resumable list moved out of the system prompt into `TaskList`+ // (ADR 0337): the instructions must not change when a delegation settles,+ // or every settlement would invalidate the cached request prefix.+ const promptBeforeSettlement = internals.composedSystemPrompt;await vi.waitFor(() => {- expect(internals.agent.state.systemPrompt).toContain(- "Files read: src/deep.ts",- );+ expect(internals.agent.state.systemPrompt).toBe(promptBeforeSettlement);});expect(internals.agent.state.systemPrompt).not.toContain(- "Files read: none recorded",+ "Files read: src/deep.ts",+ );+ const listed = await internals.agent.state.tools+ .find((tool: any) => tool.name === "TaskList")+ .execute("list-1", {});+ expect(listed.content[0].text).toContain("Files read: src/deep.ts");+ expect(listed.details.resumable).toContainEqual(+ expect.objectContaining({+ agent: "explorer",+ delegationId,+ files: ["src/deep.ts"],+ }),);expect(internals.delegationChainsdiff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex ac4c71bb0..7415acd1d 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -194,6 +194,7 @@ import { DelegationChainRegistry } from "./delegation-chain.js";import {extractReadFiles,isReadOnlyToolName,+ listedReadFiles,originalTaskFromTranscript,rebuildChainsFromTranscript,selectChainRows,@@ -1854,9 +1855,6 @@ export class DesktopAgentRuntime {/** The prompt this runtime composed last, so a mid-turn refresh can tell its* own prompt from a transient variant it must not clobber. */private composedSystemPrompt?: string;- /** Set when a refresh was skipped because a transient prompt variant owned the- * live prompt; that variant's cleanup applies it once the prompt is restored. */- private resumablePromptStale = false;/** Set by `abort` / `dispose` so a finishing delegate cannot restart the parent. */private runCancelled = false;/**@@ -2482,59 +2480,27 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst projectPrompt = projectInstructionsPrompt(this.projectInstructions);const memoryPrompt = projectMemoryPrompt(this.projectMemory);const optionalToolsPrompt = this.optionalToolsPrompt();- const resumablePrompt =- this.subagents.length > 0- ? this.delegationChains.promptBlock({- runningDelegationIds: this.runningDelegationIds(),- })- : "";this.composedSections = {runtime: this.baseSystemPrompt,...(this.trackToolActivation && this.declarationPolicy ? {[TOOL_ACTIVATION_SECTION]: toolActivationSection(this.declarationPolicy.key, this.activeDeferredToolNames),} : {}),...pluginSkillsPromptSections(this.pluginSkills),+ // The resumable-delegation list deliberately stays out: it changes on+ // every settlement, and a system-prompt change rewrites the request+ // prefix provider prompt caches key on (ADR 0337). `TaskList` carries it+ // instead, so the parent pays for it only when it reads it.context: composeModeSystemPrompt(this.mode, [...(this.customSystemPrompt?.append ? [this.customSystemPrompt.append] : []),...(optionalToolsPrompt ? [optionalToolsPrompt] : []),...(projectPrompt ? [projectPrompt] : []),...(memoryPrompt ? [memoryPrompt] : []),- ...(resumablePrompt ? [resumablePrompt] : []),].join("\n\n")),};const composed = Object.values(this.composedSections).filter(Boolean).join("\n\n");this.composedSystemPrompt = composed;return composed;}-- /**- * The resumable list changes when a delegation settles, so the prompt the- * parent reads on its next turn reflects it. Recomposing is only worth it- * when subagents exist at all, and only while the live prompt is still the- * one this runtime composed: a transient variant (the delegation nudge) owns- * it otherwise, and the next turn recomposes anyway.- */- private refreshResumablePrompt(): void {- if (this.subagents.length === 0) return;- if (!this.agent) return;- if (this.composedSystemPrompt === undefined) return;- if (this.agentSystemPromptContent() !== this.composedSystemPrompt) {- // A transient variant (the delegation nudge) owns the live prompt. Its- // own cleanup restores the composed text, and applies this refresh then,- // so a chain that settled mid-nudge is still listed on the next turn.- this.resumablePromptStale = true;- return;- }- this.setAgentSystemPrompt(this.composeSystemPrompt());- }-- /** Apply a resumable-list refresh that a transient prompt variant deferred. */- private applyPendingResumablePrompt(): void {- if (!this.resumablePromptStale) return;- this.resumablePromptStale = false;- this.refreshResumablePrompt();- }-/*** Host failures and mutation-failure termination are recorded per tool-call* id while the call runs; this is where they reach pi's tool-error channel.@@ -4885,13 +4851,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the? this.seedResumedDelegate(resumedChain, provider): undefined;if (resume && !initialMessages) {- // The chain resolved but has nothing left to replay. Drop it so the- // prompt stops advertising an id that can never be continued, and- // report the drop without listing that same id as reusable.- if (resumedChain) {- this.delegationChains.drop(resumedChain.delegateSessionId);- this.refreshResumablePrompt();- }+ // The chain resolved but has nothing left to replay. Drop it so it+ // stops being advertised as reusable, and report the drop without+ // listing that same id as reusable.+ if (resumedChain) this.delegationChains.drop(resumedChain.delegateSessionId);return this.subagentToolError(toolCallId,this.noHistoryResumeMessage(resume),@@ -5222,7 +5185,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the} finally {this.clearMutationRecovery(record.delegationId);this.refreshDelegationWait();- this.refreshResumablePrompt();+ // The settlement reaches `TaskList` on its next read; nothing here may+ // touch the system prompt, which would invalidate the provider's prompt+ // cache mid-session (ADR 0337).this.pruneFinishedDelegations();}}@@ -5760,22 +5725,42 @@ Do not invent objections or turn speculative risks into blockers. Stop when thename: SUBAGENT_LIST_TOOL_NAME,label: "Task List",description:- "List the subagents started by Task in this session with their status. Use it to check progress without waiting, or before TaskStop to choose what to stop.",+ "List the subagents started by Task in this session with their status, plus the subagent sessions that `Task(resume: ...)` can continue. Use it to check progress without waiting, to find a resumable delegation id, or before TaskStop to choose what to stop.",parameters: Type.Object({}),executionMode: "sequential",execute: async () => {const delegations = [...this.delegations.values()].sort((left, right) => left.startedAt - right.startedAt,);- const text =+ // Resumability is reported here rather than in the system prompt+ // (ADR 0337): the list changes on every settlement, and rewriting the+ // instructions mid-session invalidates the provider's cached request+ // prefix. A result the model reads on demand costs nothing otherwise.+ const runningDelegationIds = this.runningDelegationIds();+ const resumable = this.delegationChains.resumableList({+ runningDelegationIds,+ });+ const text = [delegations.length === 0? "No subagents have been started in this session.": delegations.map((record) => `- ${formatDelegationHeartbeat(record)}`)- .join("\n");+ .join("\n"),+ this.delegationChains.resumableBlock({ runningDelegationIds }),+ ]+ .filter((part) => part.trim())+ .join("\n\n");return {content: [{ type: "text", text }],- details: { delegations: delegations.map(delegationSummary) },+ details: {+ delegations: delegations.map(delegationSummary),+ resumable: resumable.map((chain) => ({+ agent: chain.agentName,+ delegationId: chain.latestDelegationId,+ objective: chain.latestObjective,+ ...listedReadFiles(chain.readFiles),+ })),+ },};},};@@ -6586,7 +6571,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (this.agentSystemPromptContent() === promptWithNudge) {this.setAgentSystemPrompt(promptBefore);}- this.applyPendingResumablePrompt();this.silentTurnRerunInProgress = false;this.suppressSilentTurnRunEnd = false;}@@ -6697,7 +6681,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (this.agentSystemPromptContent() === promptWithNudge) {this.setAgentSystemPrompt(promptBefore);}- this.applyPendingResumablePrompt();this.progressTurnRerunInProgress = false;this.suppressProgressTurnRunEnd = false;}@@ -8782,7 +8765,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// turn can be searched again when the new task actually needs it.this.subagentOverrideProviders = {};this.resetDeferredToolsForPrompt();- this.refreshResumablePrompt();// Claims are message-scoped: a later prompt must observe edited or newly// created instruction files instead of reusing a previous chain.this.pathInstructionClaims.clear();@@ -8917,7 +8899,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.activateDeferredTools(selectedTools);this.setAgentTools(this.activeTools());}- this.refreshResumablePrompt();this.pathInstructionClaims.clear();this.pendingUserMessageId = userMessageId;this.resetRunRecoveryState();