Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(agent-runtime): resume a settled subagent delegation in place

v_wyxgwang9ee0ce476f87
diff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.ts
index c3fb4b1b1..2ec9d9b0e 100644
--- a/apps/desktop/src/lib/assistant-turns.ts
+++ b/apps/desktop/src/lib/assistant-turns.ts
@@ -74,18 +74,20 @@ function isDelegationStartActivity(item: AssistantActivityItem): boolean {
return item.kind === "tool" && isDelegationStartTool(item.message.toolName);
}
-/** Delegate rows grouped by the `Task` call that produced them. */
+/** Delegate rows grouped by the `Task` call that produced them, chains merged. */
function collectSubagentRuns(
messages: readonly UiMessage[],
): Map<string, SubagentRun> {
+ const latestCall = chainLatestCalls(messages);
const runs = new Map<string, SubagentRun>();
for (const message of messages) {
const parent = message.parentToolCallId;
if (!parent) continue;
- let run = runs.get(parent);
+ const key = latestCall(parent);
+ let run = runs.get(key);
if (!run) {
run = { items: [] };
- runs.set(parent, run);
+ runs.set(key, run);
}
if (message.agentName && !run.agentName) run.agentName = message.agentName;
if (message.role === "tool") {
@@ -103,6 +105,61 @@ function collectSubagentRuns(
return runs;
}
+// Map each Task call to the last call of its chain (ADR 0276): a resumed
+// delegation is one delegate session continued by a later Task call, so the
+// chain's rows all belong on the latest card, where they read as one
+// continuing conversation rather than a card per call.
+function chainLatestCalls(
+ messages: readonly UiMessage[],
+): (toolCallId: string) => string {
+ const callByDelegationId = new Map<string, string>();
+ const childOf = new Map<string, string>();
+ for (const message of messages) {
+ if (message.role !== "tool" || !isDelegationStartTool(message.toolName)) {
+ continue;
+ }
+ const toolCallId = message.toolCallId;
+ if (!toolCallId) continue;
+ const result = message.toolResult;
+ const details =
+ result && typeof result === "object" && !Array.isArray(result)
+ ? (result as { details?: unknown }).details
+ : undefined;
+ const delegationId =
+ details && typeof details === "object" && !Array.isArray(details)
+ ? (details as { delegationId?: unknown }).delegationId
+ : undefined;
+ if (typeof delegationId === "string" && delegationId) {
+ callByDelegationId.set(delegationId, toolCallId);
+ }
+ const args = message.toolArgs;
+ const resume =
+ args && typeof args === "object" && !Array.isArray(args)
+ ? (args as { resume?: unknown }).resume
+ : undefined;
+ const prior =
+ typeof resume === "string" && resume.trim()
+ ? callByDelegationId.get(resume.trim())
+ : undefined;
+ if (prior) childOf.set(prior, toolCallId);
+ }
+ const latest = new Map<string, string>();
+ return (toolCallId: string): string => {
+ const cached = latest.get(toolCallId);
+ if (cached) return cached;
+ let current = toolCallId;
+ const seen = new Set<string>([current]);
+ for (;;) {
+ const next = childOf.get(current);
+ if (!next || seen.has(next)) break;
+ seen.add(next);
+ current = next;
+ }
+ latest.set(toolCallId, current);
+ return current;
+ };
+}
+
/**
* Group provider-level assistant fragments and tool rows into user-level turns.
* Providers end an assistant message before each tool call, but that transport
diff --git a/apps/desktop/test/assistant-turns.test.mjs b/apps/desktop/test/assistant-turns.test.mjs
index fbe3a35c0..de4013e5a 100644
--- a/apps/desktop/test/assistant-turns.test.mjs
+++ b/apps/desktop/test/assistant-turns.test.mjs
@@ -259,6 +259,74 @@ test("a delegate turn with both reasoning and text keeps both rows", () => {
);
});
+test("a resumed delegation continues in the latest Task card (ADR 0276)", () => {
+ const { entries, visible } = buildTranscriptEntries([
+ message("user", "user", "Audit the store"),
+ message("task-1", "tool", "report", {
+ toolName: "Task",
+ toolCallId: "task-1",
+ toolArgs: { agent: "explorer", task: "Explore the parser." },
+ toolResult: { details: { delegationId: "del-1" } },
+ }),
+ message("delegate-1", "assistant", "Found the parser.", {
+ parentToolCallId: "task-1",
+ agentName: "explorer",
+ }),
+ message("task-2", "tool", "report", {
+ toolName: "Task",
+ toolCallId: "task-2",
+ toolArgs: { agent: "explorer", task: "Now cover the lexer.", resume: "del-1" },
+ toolResult: { details: { delegationId: "del-2" } },
+ }),
+ message("delegate-2", "assistant", "Covered the lexer.", {
+ parentToolCallId: "task-2",
+ agentName: "explorer",
+ }),
+ message("final", "assistant", "Both halves are covered."),
+ ]);
+
+ // Each `Task` call still owns its own row in the parent's turn stream…
+ assert.deepEqual(
+ visible.map((entry) => entry.id),
+ ["user", "task-1", "task-2", "final"],
+ );
+ const turn = entries[1];
+ const activity = turn.parts[0];
+ assert.equal(activity.kind, "activity");
+ assert.equal(activity.items.length, 2);
+ // …but the chain's rows all live on the latest card, in production order, so
+ // a resumed run reads as one continuing conversation instead of a card that
+ // starts from nothing.
+ assert.equal(activity.items[0].delegate, undefined);
+ assert.equal(activity.items[1].delegate.agentName, "explorer");
+ assert.deepEqual(
+ activity.items[1].delegate.items.map((item) => item.message.id),
+ ["delegate-1", "delegate-2"],
+ );
+});
+
+test("a resume link whose parent Task row is gone leaves the card intact", () => {
+ const { entries } = buildTranscriptEntries([
+ message("user", "user", "Audit the store"),
+ message("task-2", "tool", "report", {
+ toolName: "Task",
+ toolCallId: "task-2",
+ toolArgs: { agent: "explorer", task: "More.", resume: "del-1" },
+ toolResult: { details: { delegationId: "del-2" } },
+ }),
+ message("delegate-2", "assistant", "More.", {
+ parentToolCallId: "task-2",
+ agentName: "explorer",
+ }),
+ ]);
+
+ const delegate = entries[1].parts[0].items[0].delegate;
+ assert.deepEqual(
+ delegate.items.map((item) => item.message.id),
+ ["delegate-2"],
+ );
+});
+
function mark(id, throughMessageId, overrides = {}) {
return {
id,
diff --git a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
index e4c5c3b31..5e987718a 100644
--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
@@ -3,7 +3,8 @@
- Status: Accepted for implementation (definition roots amended by ADR 0112;
timeout policy amended by ADR 0119; delegation presentation amended by D265;
- opt-in parent-tool inherit amended by ADR 0246)
+ opt-in parent-tool inherit amended by ADR 0246; resumable delegations amended
+ by ADR 0276)
- Date: 2026-08-06
- Deciders: PI-Desktop core
- Related: D201, ADR 0041 (persistence outbox), ADR 0048 (lazy per-turn tool
@@ -11,7 +12,7 @@
template documents), D138 (session-scoped inline permission requests),
D198 (contract modes), ADR 0112 (capability roots and Settings IA), ADR 0119
(event-driven subagent timeouts), D265 (one delegation reads as a card too),
- ADR 0246 (opt-in `tools: inherit`)
+ ADR 0246 (opt-in `tools: inherit`), ADR 0276 (resumable delegations)
## Context
diff --git a/docs/adr/0089-proactive-background-subagent-delegation.md b/docs/adr/0089-proactive-background-subagent-delegation.md
index d01123cfb..5272b936a 100644
--- a/docs/adr/0089-proactive-background-subagent-delegation.md
+++ b/docs/adr/0089-proactive-background-subagent-delegation.md
@@ -1,9 +1,10 @@
# ADR 0089: Proactive Background Subagent Delegation
-- Status: Accepted for implementation
+- Status: Accepted for implementation (resumable delegations amended by
+ ADR 0276)
- Date: 2026-08-16
- Deciders: PI-Desktop core
-- Related: D201, D202, ADR 0062, ADR 0063, ADR 0048, ADR 0100, E2E-142
+- Related: D201, D202, ADR 0062, ADR 0063, ADR 0048, ADR 0100, ADR 0276, E2E-142
## Context
diff --git a/docs/adr/0276-resumable-subagent-delegations.md b/docs/adr/0276-resumable-subagent-delegations.md
new file mode 100644
index 000000000..6cbe9b8d4
--- /dev/null
+++ b/docs/adr/0276-resumable-subagent-delegations.md
@@ -0,0 +1,196 @@
+# ADR 0276: Resumable subagent delegations
+
+- Status: Accepted for implementation
+- Date: 2026-09-17
+- Deciders: PI-Desktop core
+- Related: [ADR 0062](0062-bounded-subagents-behind-a-task-tool.md) ·
+ [ADR 0089](0089-proactive-background-subagent-delegation.md) ·
+ [ADR 0119](0119-event-driven-subagent-timeouts.md) ·
+ [ADR 0165](0165-withdraw-a2a-peer-stack.md) ·
+ [03-runtime/02-agent-runtime.md](../spec/03-runtime/02-agent-runtime.md) §5f
+- Amends: ADR 0062 (the `Task` tool contract) and ADR 0089 (the delegation
+ lifecycle). Both are preserved — every existing boundary still holds; this
+ adds one opt-in parameter and one piece of bookkeeping.
+- Tracking: #513
+
+## Context
+
+Delegation as built by ADR 0062 and ADR 0089 spawns one `SubagentRun` per `Task`
+call. Each run starts with `messages: []` (`packages/agent-runtime/src/subagent.ts`)
+and is single-use. A delegate's transcript rows are persisted — they carry
+`parentToolCallId` and `agentName` and land in the session transcript — but
+nothing ever reads them back into a delegate, and the session runtime skips them
+when it rebuilds model context (`runtime.ts`, `if (m.parentToolCallId) continue;`).
+
+That makes every `Task` call a cold start even when the parent delegates the
+same subagent for the same files twice. The context the first run bought —
+which files it read, what it found, what it already changed — is discarded, and
+the second run pays for it again, or worse, works from a stale file version it
+never re-reads.
+
+The pieces to do better are already in place: the rows are persisted with
+enough fidelity for a full rebuild (tool call/result pairs, thinking blocks, and
+the original `Task` arguments on the tool row), and the session runtime already
+contains a `UiMessage[] → AgentMessage[]` converter that produces well-formed
+provider messages including synthesized carriers for orphan tool rows.
+
+## Decision
+
+Add an opt-in `resume` parameter to the `Task` tool. When present, the new
+delegation is seeded with the prior delegation's reconstructed context instead
+of starting empty.
+
+### 1. `Task` gains `resume?: delegationId`
+
+Resolution is by `delegationId` only — the id the `Task` result already returns
+and `TaskWait` already accepts. A second, stable internal key
+(`delegateSessionId`) exists solely to chain the runs; it never appears in a
+tool parameter, tool result, or prompt. The runtime keeps a reverse map from
+every `delegationId` issued on a live chain to that chain, so an id from the
+middle of a chain resolves too.
+
+### 2. Chains, not records, are the unit of resumability
+
+A **chain** is one `delegateSessionId` plus the ordered `Task` toolCallIds that
+belong to it. Each `resume` appends the new toolCallId. Child transcript rows
+are keyed by `parentToolCallId`, so reconstructing a chain's context means
+selecting every row whose `parentToolCallId` is in the chain and whose
+`agentName` matches.
+
+`DelegationRecord` gains `delegateSessionId`, `toolCallIdChain`, `resumable`,
+`readFiles`, and `readLineCount`. The registry keeps a secondary index from
+`delegateSessionId` to the chain's live record.
+
+### 3. Context reconstruction is a pure function
+
+A new module (`packages/agent-runtime/src/delegation-history.ts`) owns:
+
+- selecting the chain's rows from the session transcript,
+- synthesizing the original `task` as the first user message from the first
+ `Task` tool row's persisted arguments,
+- converting to `AgentMessage[]` with the delegate's own provider/model binding
+ (a pinned delegation model is not the session model),
+- a read-file / line-count budget gate.
+
+`SubagentRun` gains `initialMessages?: AgentMessage[]`; when present it seeds
+`initialState.messages` instead of `[]`. The run is otherwise a completely
+normal run: it occupies a `MAX_SUBAGENT_CONCURRENCY` slot, inherits the
+definition's permission scope, and settles through the existing
+`settleDelegation` path with its own `delegationId`, report, and counters.
+
+### 4. Validation is visible, never thrown
+
+`resume` is validated before the run starts; every failure is a tool error the
+model can act on:
+
+| Condition | Error |
+|---|---|
+| unknown or evicted id | `Unknown delegation "<id>"` plus the current resumable list |
+| still running | `Delegation <id> is still running; call TaskWait to converge first` |
+| `stopped` / `aborted` | not resumable; a future revive path (out of scope here) |
+| `Task.agent` differs from the chain's agent | name mismatch, lists available |
+| `Task.model` present on a resume | not allowed on a resumed run — start a new delegation to change models |
+| chain exceeds the read budget | the chain is excluded from the resumable list, so this surfaces as unknown id |
+
+No new error codes for "evicted" versus "never existed": both resolve to the
+same unknown-id error, because the model's only correct action is identical.
+
+### 5. Only `completed` and `failed` are resumable
+
+A `failed` run's reads and findings still have value; its failed assistant row
+is dropped by the converter like any other error row. `stopped` and `aborted`
+encode the user's or the parent's decision to abandon that line of work, and
+resuming it would contradict the stop. (`timed_out` is a vestigial status —
+ADR 0119's timeouts were withdrawn by D328 — and is treated as `failed` for this
+purpose.)
+
+### 6. One live record per chain, ever
+
+There is no queuing and no message-append. A chain has at most one running
+record at a time; a `resume` while the chain is running is rejected with the
+TaskWait error above. This keeps the chain a strict straight line with no
+forking successors.
+
+### 7. Resumable chains are bounded, LRU, per agent name
+
+`MAX_RESUMABLE_CHAINS_PER_AGENT = 2`. Chains are exempt from the existing
+`pruneFinishedDelegations` oldest-first sweep while under this bound; exceeding
+it evicts the least-recently-used whole chain (record, chain index, and reverse
+map entries together). Tombstones are unnecessary: `delegationId` is a random
+UUID, so an evicted id cannot collide with a future one.
+
+### 8. Read budget gates chain growth
+
+A delegate has no compaction of its own, so an unbounded chain would eventually
+overflow its own context window. Rather than trimming inside the chain, a chain
+whose cumulative read volume exceeds `MAX_RESUMABLE_READ_LINES` (50,000) silently
+leaves the resumable list — the next delegation for that work is a cold start,
+which still works. The gate is checked when the resumable list is built, so it
+costs nothing at delegation time.
+
+Reads are counted from the delegate's read-only tool rows (`Read`, `Glob`,
+`Grep`, `BrowserPreview`), accumulated per chain; write-tool targets are not
+counted 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.
+
+The `resume` parameter's own schema description carries the rule that reuse
+requires the id; prose alone does not resume anything.
+
+### 10. Same session only
+
+`resume` resolves only against the current session's transcript. There is no
+cross-session addressing; sharing facts between conversations stays in the
+prompt, as ADR 0165 concluded when it withdrew the peer stack.
+
+### 11. Definition edits take effect on resume, with a diagnostic
+
+A definition edited between two delegations is applied as-is on resume — the
+same "editing takes effect on the next prompt" semantics the catalog already
+has — and the change is recorded in the delegation's lifecycle details. No
+definition snapshot is stored; snapshots would need new persistent state and
+would contradict the existing semantics.
+
+### 12. Chain index is rebuilt from the transcript on startup
+
+The chain registry is in memory, but the chain relationship is recoverable:
+`Task` tool rows are persisted with their arguments, including `resume`. At
+session launch the runtime scans the transcript's `Task` rows, groups them by
+their `resume` links into chains, and rehydrates the secondary index. Restart
+does not lose resumability.
+
+### 13. The transcript renders a chain as one continuous conversation
+
+A resumed delegation's card shows the whole chain's rows as consecutive turns
+(task → reply → task → reply) with no special "resumed" badge. The new run's
+counters start at zero; `details.resumedFrom` keeps the link auditable.
+
+## Consequences
+
+- `Task`'s parameter schema widens by one optional field. Every existing call is
+ unchanged: `resume` omitted is exactly today's behavior.
+- The delegate→parent context boundary is untouched. Reconstructed rows seed the
+ delegate's own context only; the parent still receives nothing but reports
+ through `TaskWait`, and `parentToolCallId` rows are still skipped when the
+ parent's context is rebuilt.
+- No new storage schema, tables, or event types. The required fields
+ (`delegateSessionId`, `toolCallIdChain`, `resumable`, read tracking) live on
+ the in-memory `DelegationRecord`; `resumedFrom` rides the existing lifecycle
+ details projection.
+- A resumed run is billed and bounded exactly like a fresh one — same concurrency
+ slot, same permission scope, same fallback models, same abort sources.
+- Failure mode of the read budget is graceful degradation to a cold start, never
+ a broken or oversized request.
+
+## Out of scope (二期)
+
+- Reviving a `stopped` / `aborted` delegation.
+- In-chain compaction or placeholder substitution for old tool results.
+- Task queuing / work append on a running delegation.
+- Cross-session resumption.
+- User-visible settings for the bounds; they stay code constants.
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index 50e1a7267..c112c31c1 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -647,7 +647,7 @@ intentional override.
mode and only when the catalog is non-empty, and all four belong to the Agent
core set rather than the on-demand catalog of §7.1:
-- `Task(agent, task, description?, model?)` — validates its arguments (an
+- `Task(agent, task, description?, model?, resume?)` — validates its arguments (an
unknown `agent`, an empty `task`, an unresolvable model pin and a definition
whose tools are all unavailable each return a tool error explaining the
failure rather than throwing), starts the delegate **in the background**, and
@@ -770,6 +770,53 @@ also aborts leftover delegates,
skips the resume prompt, and returns the session to idle so Continue is not
`AGENT_BUSY` (D352).
+**Resumable delegations (ADR 0276).** `Task` accepts an optional `resume`
+parameter carrying the `delegationId` of a settled delegation in the same
+conversation. The resumed delegate is a new `SubagentRun` seeded with the
+chain's prior messages — the original `task` brief plus every row the chain
+produced — and then prompted with the new `task`, so a delegate that already
+read or changed a file continues from that context instead of starting cold.
+Seeding is transcript-backed: the chain's rows are exactly those carrying
+`parentToolCallId` for one of the chain's `Task` calls, and they are converted
+into provider messages with the delegate's own binding (a pinned delegation
+model is not the session model). Nothing is kept warm in memory and no new
+event type, storage schema, or tool parameter is introduced.
+
+A chain is the sequence of `Task` calls that share one delegate session: the
+first call, plus every later call that passed the earlier `delegationId` as
+`resume`. The runtime rebuilds the chain index from the persisted transcript at
+launch — each `Task` row carries its own `delegationId` in `toolResult.details`
+and the resumed id in `toolArgs.resume` — so resumability survives a sidecar
+restart. Chain identity (`delegateSessionId`) stays internal; the parent only
+ever passes a `delegationId`, and the reverse map resolves it.
+
+Only `completed` and `failed` chains are resumable; `stopped` and `aborted`
+runs are terminal and revive only by starting a new delegation. A chain whose
+read-only tool output exceeds `MAX_RESUMABLE_READ_LINES` (50000) leaves the
+reusable list without an in-chain trim, so a resume never silently drops
+history. The registry keeps at most `MAX_RESUMABLE_CHAINS_PER_AGENT` (2) chains
+per definition name, evicting least-recently-active ones.
+
+Resume is strictly same-session and never queues: resuming a running
+delegation is a tool error telling the parent to converge with `TaskWait`
+first, and a chain has at most one live record at a time. `model` and `resume`
+together are rejected — a resumed run keeps the chain's model, and changing
+models means starting a new delegation. An unknown id, an id belonging to
+another definition, a non-resumable status, and an over-budget chain each
+return a tool error naming the reason and, for an unknown id, the reusable ids
+when there are any.
+
+The parent discovers reusable chains through the system prompt, which lists
+each 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
+`MAX_SUBAGENT_CONCURRENCY`, `TaskWait`, `TaskList`, `TaskStop`, and lifecycle
+snapshots. The immediate `Task` result and the lifecycle details add
+`resumedFrom` for audit; the transcript renders a chain as one continuous
+multi-turn conversation under its latest `Task` card, with no separate
+"resumed" marker.
+
**Model pins.** `model: <provider>/<model>` in the frontmatter is resolved once
per launch in Electron main, where credentials and the models.dev snapshot live, against
provider id, vendor key or display name, and capped at
diff --git a/packages/agent-runtime/src/delegation-chain.ts b/packages/agent-runtime/src/delegation-chain.ts
new file mode 100644
index 000000000..a5dd0409d
--- /dev/null
+++ b/packages/agent-runtime/src/delegation-chain.ts
@@ -0,0 +1,222 @@
+/**
+ * In-memory chain registry for resumable delegations (ADR 0276).
+ *
+ * The registry is rebuilt from the session transcript at launch, then updated
+ * as `Task` calls settle. It never appears in a tool parameter: the parent
+ * only ever passes a `delegationId`, and the reverse map finds the chain.
+ */
+
+import {
+ MAX_RESUMABLE_CHAINS_PER_AGENT,
+ MAX_RESUMABLE_READ_LINES,
+} from "@pi-desktop/shared";
+import {
+ formatResumableList,
+ isChainWithinReadBudget,
+ type DelegationChain,
+ type ResumableChain,
+} from "./delegation-history.js";
+
+const RESUMABLE_STATUSES = new Set(["completed", "failed", "timed_out"]);
+
+export type ChainLookupError =
+ | { kind: "unknown" }
+ | { kind: "running"; delegationId: string }
+ | { kind: "not-resumable"; status: string }
+ | { kind: "agent-mismatch"; expected: string; actual: string }
+ | { kind: "over-budget" };
+
+export class DelegationChainRegistry {
+ private readonly chains = new Map<string, DelegationChain>();
+ /** Every live `delegationId` on a chain, pointing at that chain's session id. */
+ private readonly byDelegationId = new Map<string, string>();
+
+ hydrate(chains: DelegationChain[]): void {
+ this.chains.clear();
+ this.byDelegationId.clear();
+ for (const chain of chains) this.install(chain);
+ this.evictOverflow();
+ }
+
+ lookup(delegationId: string): DelegationChain | undefined {
+ const sessionId = this.byDelegationId.get(delegationId);
+ if (!sessionId) return undefined;
+ return this.chains.get(sessionId);
+ }
+
+ resolveResume(options: {
+ resume: string;
+ agentName: string;
+ runningDelegationIds: ReadonlySet<string>;
+ }): { ok: true; chain: DelegationChain } | { ok: false; error: ChainLookupError } {
+ const chain = this.lookup(options.resume);
+ if (!chain) return { ok: false, error: { kind: "unknown" } };
+ if (chain.agentName !== options.agentName) {
+ return {
+ ok: false,
+ error: {
+ kind: "agent-mismatch",
+ expected: chain.agentName,
+ actual: options.agentName,
+ },
+ };
+ }
+ const latest = chain.latestDelegationId;
+ if (latest && options.runningDelegationIds.has(latest)) {
+ return { ok: false, error: { kind: "running", delegationId: latest } };
+ }
+ // An unknown status only happens for a chain rebuilt from the transcript
+ // at launch, where live records are gone: its last run is settled by
+ // definition. A settled chain carries its own status, which survives
+ // `pruneFinishedDelegations` deleting the runtime's records.
+ if (chain.latestStatus && !RESUMABLE_STATUSES.has(chain.latestStatus)) {
+ return {
+ ok: false,
+ error: { kind: "not-resumable", status: chain.latestStatus },
+ };
+ }
+ if (!isChainWithinReadBudget(chain)) {
+ return { ok: false, error: { kind: "over-budget" } };
+ }
+ return { ok: true, chain };
+ }
+
+ start(options: {
+ delegateSessionId: string;
+ delegationId: string;
+ toolCallId: string;
+ agentName: string;
+ originalTask: string;
+ objective: string;
+ latestModelId?: string;
+ resumedFrom?: DelegationChain;
+ }): DelegationChain {
+ const existing = options.resumedFrom
+ ? this.chains.get(options.resumedFrom.delegateSessionId)
+ : undefined;
+ const chain: DelegationChain = existing
+ ? {
+ ...existing,
+ toolCallIds: [...existing.toolCallIds, options.toolCallId],
+ delegationIds: [...existing.delegationIds, options.delegationId],
+ latestDelegationId: options.delegationId,
+ latestObjective: options.objective || existing.latestObjective,
+ latestModelId: options.latestModelId ?? existing.latestModelId,
+ latestStatus: "running",
+ lastActivityAt: Date.now(),
+ }
+ : {
+ delegateSessionId: options.delegateSessionId,
+ toolCallIds: [options.toolCallId],
+ delegationIds: [options.delegationId],
+ agentName: options.agentName,
+ readFiles: [],
+ readLineCount: 0,
+ originalTask: options.originalTask,
+ latestDelegationId: options.delegationId,
+ latestObjective: options.objective,
+ latestModelId: options.latestModelId,
+ latestStatus: "running",
+ lastActivityAt: Date.now(),
+ };
+ this.install(chain);
+ return chain;
+ }
+
+ noteReads(
+ delegateSessionId: string,
+ files: readonly string[],
+ lineCount: number,
+ ): void {
+ const chain = this.chains.get(delegateSessionId);
+ if (!chain) return;
+ const merged = [...chain.readFiles];
+ for (const file of files) {
+ if (!merged.includes(file)) merged.push(file);
+ }
+ this.chains.set(delegateSessionId, {
+ ...chain,
+ readFiles: merged,
+ readLineCount: chain.readLineCount + lineCount,
+ lastActivityAt: Date.now(),
+ });
+ }
+
+ settle(delegateSessionId: string, status: string): void {
+ const chain = this.chains.get(delegateSessionId);
+ if (!chain) return;
+ this.chains.set(delegateSessionId, {
+ ...chain,
+ latestStatus: status,
+ lastActivityAt: Date.now(),
+ });
+ this.evictOverflow();
+ }
+
+ drop(delegateSessionId: string): void {
+ const chain = this.chains.get(delegateSessionId);
+ if (!chain) return;
+ this.chains.delete(delegateSessionId);
+ for (const id of chain.delegationIds) this.byDelegationId.delete(id);
+ }
+
+ resumableList(options: {
+ runningDelegationIds: ReadonlySet<string>;
+ }): ResumableChain[] {
+ const listed: ResumableChain[] = [];
+ for (const chain of this.chains.values()) {
+ const latest = chain.latestDelegationId;
+ if (!latest) continue;
+ if (options.runningDelegationIds.has(latest)) continue;
+ if (chain.latestStatus && !RESUMABLE_STATUSES.has(chain.latestStatus)) {
+ continue;
+ }
+ if (!isChainWithinReadBudget(chain, MAX_RESUMABLE_READ_LINES)) continue;
+ listed.push({
+ ...chain,
+ latestDelegationId: latest,
+ latestObjective: chain.latestObjective ?? "",
+ });
+ }
+ return listed.sort((left, right) => right.lastActivityAt - left.lastActivityAt);
+ }
+
+ promptBlock(options: {
+ runningDelegationIds: ReadonlySet<string>;
+ }): string {
+ return formatResumableList(this.resumableList(options));
+ }
+
+ unknownResumeError(resume: string, list: readonly ResumableChain[]): string {
+ const available = list
+ .map((chain) => `${chain.agentName} / ${chain.latestDelegationId}`)
+ .join(", ");
+ return available
+ ? `Unknown delegation "${resume}". Reusable: ${available}.`
+ : `Unknown delegation "${resume}". No reusable subagent sessions in this conversation.`;
+ }
+
+ private install(chain: DelegationChain): void {
+ this.chains.set(chain.delegateSessionId, chain);
+ for (const id of chain.delegationIds) {
+ this.byDelegationId.set(id, chain.delegateSessionId);
+ }
+ }
+
+ private evictOverflow(): void {
+ const byAgent = new Map<string, DelegationChain[]>();
+ for (const chain of this.chains.values()) {
+ const group = byAgent.get(chain.agentName) ?? [];
+ group.push(chain);
+ byAgent.set(chain.agentName, group);
+ }
+ for (const group of byAgent.values()) {
+ const sorted = [...group].sort(
+ (left, right) => right.lastActivityAt - left.lastActivityAt,
+ );
+ for (const stale of sorted.slice(MAX_RESUMABLE_CHAINS_PER_AGENT)) {
+ this.drop(stale.delegateSessionId);
+ }
+ }
+ }
+}
diff --git a/packages/agent-runtime/src/delegation-history.test.ts b/packages/agent-runtime/src/delegation-history.test.ts
new file mode 100644
index 000000000..49ce9431f
--- /dev/null
+++ b/packages/agent-runtime/src/delegation-history.test.ts
@@ -0,0 +1,432 @@
+import { describe, expect, it } from "vitest";
+import { MAX_RESUMABLE_READ_LINES, type UiMessage } from "@pi-desktop/shared";
+import {
+ extractReadFiles,
+ formatResumableList,
+ isChainWithinReadBudget,
+ listedReadFiles,
+ originalTaskFromTranscript,
+ rebuildChainsFromTranscript,
+ selectChainRows,
+ seedDelegateMessages,
+ taskObjectiveFromArgs,
+ type DelegationChain,
+ type ResumableChain,
+} from "./delegation-history.js";
+import type { RuntimeProviderConfig } from "./provider-binding.js";
+import { buildProviderModel } from "./provider-binding.js";
+
+function provider(): RuntimeProviderConfig {
+ return {
+ id: "test-provider",
+ modelId: "test-model",
+ apiStyle: "openai-completions",
+ apiKey: "test-key",
+ } as RuntimeProviderConfig;
+}
+
+function delegateAssistant(
+ id: string,
+ content: string,
+ parentToolCallId: string,
+): UiMessage {
+ return {
+ id,
+ role: "assistant",
+ content,
+ status: "complete",
+ createdAt: new Date(1_700_000_000_000).toISOString(),
+ parentToolCallId,
+ agentName: "explorer",
+ };
+}
+
+function delegateTool(
+ toolCallId: string,
+ toolName: string,
+ args: unknown,
+ result: unknown,
+ parentToolCallId: string,
+): UiMessage {
+ return {
+ id: `row-${toolCallId}`,
+ role: "tool",
+ content: "",
+ toolCallId,
+ toolName,
+ toolArgs: args,
+ toolResult: result,
+ toolStatus: "success",
+ createdAt: new Date(1_700_000_001_000).toISOString(),
+ parentToolCallId,
+ agentName: "explorer",
+ };
+}
+
+function taskRow(
+ taskCallId: string,
+ delegationId: string,
+ task: string,
+ options: { resume?: string; description?: string } = {},
+): UiMessage {
+ return {
+ id: `row-${taskCallId}`,
+ role: "tool",
+ content: "",
+ toolCallId: taskCallId,
+ toolName: "Task",
+ toolArgs: {
+ agent: "explorer",
+ task,
+ ...(options.description ? { description: options.description } : {}),
+ ...(options.resume ? { resume: options.resume } : {}),
+ },
+ toolResult: { details: { delegationId, agent: "explorer" } },
+ toolStatus: "success",
+ createdAt: new Date(1_700_000_000_000).toISOString(),
+ };
+}
+
+describe("selectChainRows", () => {
+ it("keeps only the chain's own calls and agent", () => {
+ const rows: UiMessage[] = [
+ delegateAssistant("a1", "first", "call-1"),
+ delegateAssistant("a2", "sibling", "call-other"),
+ delegateAssistant("a3", "second", "call-2"),
+ {
+ id: "p1",
+ role: "assistant",
+ content: "parent",
+ status: "complete",
+ createdAt: new Date(1_700_000_000_000).toISOString(),
+ },
+ ];
+ const selected = selectChainRows(rows, {
+ toolCallIds: ["call-1", "call-2"],
+ agentName: "explorer",
+ });
+ expect(selected.map((row) => row.id)).toEqual(["a1", "a3"]);
+ });
+
+ it("drops rows whose agent name differs on a shared call id", () => {
+ const rows: UiMessage[] = [
+ delegateAssistant("a1", "explorer", "call-1"),
+ { ...delegateAssistant("a2", "reviewer", "call-1"), agentName: "reviewer" },
+ ];
+ expect(
+ selectChainRows(rows, { toolCallIds: ["call-1"], agentName: "explorer" }),
+ ).toHaveLength(1);
+ });
+});
+
+describe("extractReadFiles", () => {
+ it("counts read-only tools and ignores mutating ones", () => {
+ const rows: UiMessage[] = [
+ delegateTool(
+ "t1",
+ "Read",
+ { path: "a.ts" },
+ { content: [{ type: "text", text: "x\ny" }] },
+ "call-1",
+ ),
+ delegateTool(
+ "t2",
+ "Read",
+ { path: "a.ts" },
+ { content: [{ type: "text", text: "x" }] },
+ "call-1",
+ ),
+ delegateTool("t3", "Edit", { path: "b.ts" }, { ok: true }, "call-1"),
+ delegateTool(
+ "t4",
+ "Grep",
+ { pattern: "foo" },
+ { content: [{ type: "text", text: "hit" }] },
+ "call-1",
+ ),
+ ];
+ const reads = extractReadFiles(rows);
+ // A repeated path is listed once; Grep's pattern is its target.
+ expect(reads.files).toEqual(["a.ts", "foo"]);
+ // 2 lines for the first Read, 1 for the single-line result, 1 for Grep.
+ expect(reads.lineCount).toBe(4);
+ });
+
+ it("reads text out of a block-shaped tool result", () => {
+ const rows: UiMessage[] = [
+ delegateTool(
+ "t1",
+ "Read",
+ { file_path: "c.ts" },
+ { content: [{ type: "text", text: "one\ntwo\nthree" }] },
+ "call-1",
+ ),
+ ];
+ expect(extractReadFiles(rows)).toEqual({
+ files: ["c.ts"],
+ lineCount: 3,
+ });
+ });
+});
+
+describe("originalTaskFromTranscript", () => {
+ it("recovers the first Task brief", () => {
+ const transcript = [
+ taskRow("call-1", "d1", " explore the parser "),
+ taskRow("call-2", "d2", "continue", { resume: "d1" }),
+ ];
+ expect(originalTaskFromTranscript(transcript, { toolCallIds: ["call-1"] })).toBe(
+ "explore the parser",
+ );
+ });
+
+ it("returns undefined when the row is gone", () => {
+ expect(
+ originalTaskFromTranscript([], { toolCallIds: ["missing"] }),
+ ).toBeUndefined();
+ });
+});
+
+describe("taskObjectiveFromArgs", () => {
+ it("prefers the short description over the full brief", () => {
+ expect(
+ taskObjectiveFromArgs({ description: " audit ", task: "long brief" }),
+ ).toBe("audit");
+ expect(taskObjectiveFromArgs({ task: " long brief " })).toBe("long brief");
+ expect(taskObjectiveFromArgs(undefined)).toBe("");
+ });
+});
+
+describe("seedDelegateMessages", () => {
+ it("prepends the original task once and keeps tool pairs ordered", () => {
+ const rows: UiMessage[] = [
+ delegateAssistant("a1", "looking", "call-1"),
+ delegateTool("t1", "Read", { path: "a.ts" }, { content: "body" }, "call-1"),
+ delegateAssistant("a2", "done", "call-1"),
+ ];
+ const messages = seedDelegateMessages({
+ originalTask: "explore the parser",
+ rows,
+ provider: provider(),
+ model: buildProviderModel(provider()),
+ });
+ expect(messages[0]).toMatchObject({
+ role: "user",
+ content: [{ type: "text", text: "explore the parser" }],
+ });
+ // The assistant row that made the call carries it; the tool result follows
+ // it directly, so the replay stays a well-formed provider transcript.
+ expect(messages.map((message) => message.role)).toEqual([
+ "user",
+ "assistant",
+ "toolResult",
+ "assistant",
+ ]);
+ const assistantWithCall = messages[1];
+ expect(
+ assistantWithCall.role === "assistant" &&
+ assistantWithCall.content.some(
+ (block) => block.type === "toolCall" && block.name === "Read",
+ ),
+ ).toBe(true);
+ });
+
+ it("does not duplicate an original task that is already the first user row", () => {
+ const rows: UiMessage[] = [
+ {
+ id: "u1",
+ role: "user",
+ content: "explore the parser",
+ status: "complete",
+ createdAt: new Date(1_700_000_000_000).toISOString(),
+ parentToolCallId: "call-1",
+ agentName: "explorer",
+ },
+ delegateAssistant("a1", "looking", "call-1"),
+ ];
+ const messages = seedDelegateMessages({
+ originalTask: "explore the parser",
+ rows,
+ provider: provider(),
+ model: buildProviderModel(provider()),
+ });
+ expect(messages.filter((message) => message.role === "user")).toHaveLength(1);
+ });
+
+ it("keeps an orphan tool row well-formed with a synthesized carrier", () => {
+ const rows: UiMessage[] = [
+ delegateTool("t1", "Read", { path: "a.ts" }, { content: "body" }, "call-1"),
+ ];
+ const messages = seedDelegateMessages({
+ originalTask: "explore",
+ rows,
+ provider: provider(),
+ model: buildProviderModel(provider()),
+ });
+ expect(messages).toHaveLength(3);
+ expect(messages[1]).toMatchObject({ role: "assistant", stopReason: "toolUse" });
+ expect(messages[2]).toMatchObject({
+ role: "toolResult",
+ toolCallId: "t1",
+ toolName: "Read",
+ isError: false,
+ });
+ });
+
+ it("skips a failed assistant row but still replays its tool pair", () => {
+ const rows: UiMessage[] = [
+ {
+ ...delegateAssistant("a1", "boom", "call-1"),
+ status: "error",
+ isError: true,
+ },
+ delegateTool("t1", "Read", { path: "a.ts" }, { content: "body" }, "call-1"),
+ ];
+ const messages = seedDelegateMessages({
+ originalTask: "explore",
+ rows,
+ provider: provider(),
+ model: buildProviderModel(provider()),
+ });
+ const assistants = messages.filter((message) => message.role === "assistant");
+ expect(assistants).toHaveLength(1);
+ expect(
+ assistants[0].role === "assistant" &&
+ assistants[0].content.some((block) => block.type === "text"),
+ ).toBe(false);
+ });
+});
+
+describe("rebuildChainsFromTranscript", () => {
+ it("groups resume links into one chain with the latest objective", () => {
+ const transcript: UiMessage[] = [
+ taskRow("call-1", "d1", "explore the parser", { description: "explore" }),
+ delegateAssistant("a1", "found a", "call-1"),
+ taskRow("call-2", "d2", "now cover the lexer", { resume: "d1" }),
+ delegateAssistant("a2", "covered b", "call-2"),
+ ];
+ const chains = rebuildChainsFromTranscript(transcript);
+ expect(chains).toHaveLength(1);
+ expect(chains[0]).toMatchObject({
+ delegateSessionId: "d1",
+ agentName: "explorer",
+ toolCallIds: ["call-1", "call-2"],
+ delegationIds: ["d1", "d2"],
+ latestDelegationId: "d2",
+ latestObjective: "now cover the lexer",
+ originalTask: "explore the parser",
+ });
+ });
+
+ it("starts a new chain when a Task call carries no resume link", () => {
+ const transcript: UiMessage[] = [
+ taskRow("call-1", "d1", "first"),
+ taskRow("call-2", "d2", "second"),
+ ];
+ expect(rebuildChainsFromTranscript(transcript)).toHaveLength(2);
+ });
+
+ it("ignores a resume whose parent row is gone", () => {
+ const transcript: UiMessage[] = [
+ taskRow("call-1", "d1", "continue", { resume: "missing" }),
+ ];
+ expect(rebuildChainsFromTranscript(transcript)).toEqual([]);
+ });
+
+ it("accumulates read files and lines across the chain", () => {
+ const transcript: UiMessage[] = [
+ taskRow("call-1", "d1", "explore"),
+ delegateTool(
+ "t1",
+ "Read",
+ { path: "a.ts" },
+ { content: [{ type: "text", text: "x\ny" }] },
+ "call-1",
+ ),
+ taskRow("call-2", "d2", "more", { resume: "d1" }),
+ delegateTool(
+ "t2",
+ "Read",
+ { path: "b.ts" },
+ { content: [{ type: "text", text: "z" }] },
+ "call-2",
+ ),
+ ];
+ const [chain] = rebuildChainsFromTranscript(transcript);
+ expect(chain.readFiles).toEqual(["a.ts", "b.ts"]);
+ expect(chain.readLineCount).toBe(3);
+ });
+});
+
+describe("read budget", () => {
+ it("gates a chain on its cumulative read lines", () => {
+ expect(isChainWithinReadBudget({ readLineCount: MAX_RESUMABLE_READ_LINES })).toBe(
+ true,
+ );
+ expect(
+ isChainWithinReadBudget({ readLineCount: MAX_RESUMABLE_READ_LINES + 1 }),
+ ).toBe(false);
+ });
+});
+
+describe("listedReadFiles", () => {
+ it("caps the listing and reports the omitted count", () => {
+ const files = ["a", "b", "c", "d"];
+ expect(listedReadFiles(files, 2)).toEqual({
+ files: ["a", "b"],
+ omitted: 2,
+ });
+ expect(listedReadFiles(files, 9)).toEqual({ files, omitted: 0 });
+ });
+});
+
+describe("formatResumableList", () => {
+ const chain = (overrides: Partial<ResumableChain> = {}): ResumableChain => ({
+ delegateSessionId: "s1",
+ toolCallIds: ["call-1"],
+ delegationIds: ["d1"],
+ agentName: "explorer",
+ readFiles: ["a.ts"],
+ readLineCount: 10,
+ latestDelegationId: "d1",
+ latestObjective: "explore",
+ lastActivityAt: 1,
+ ...overrides,
+ });
+
+ it("renders an empty string with nothing reusable", () => {
+ expect(formatResumableList([])).toBe("");
+ });
+
+ it("names the delegation and the files it read", () => {
+ const text = formatResumableList([chain()]);
+ expect(text).toContain("explorer / d1: explore");
+ expect(text).toContain("Files read: a.ts");
+ });
+
+ it("says so when a chain read nothing", () => {
+ const text = formatResumableList([chain({ readFiles: [] })]);
+ expect(text).toContain("Files read: none recorded");
+ });
+
+ it("collapses a long file list", () => {
+ const files = ["a", "b", "c", "d", "e", "f", "g", "h", "i"];
+ const text = formatResumableList([chain({ readFiles: files })]);
+ expect(text).toContain("(+1 more)");
+ });
+});
+
+describe("chain shape", () => {
+ it("carries the fields the registry relies on", () => {
+ const chain: DelegationChain = {
+ delegateSessionId: "s1",
+ toolCallIds: [],
+ delegationIds: [],
+ agentName: "explorer",
+ readFiles: [],
+ readLineCount: 0,
+ lastActivityAt: 0,
+ };
+ expect(chain.latestStatus).toBeUndefined();
+ });
+});
diff --git a/packages/agent-runtime/src/delegation-history.ts b/packages/agent-runtime/src/delegation-history.ts
new file mode 100644
index 000000000..9dc498c2f
--- /dev/null
+++ b/packages/agent-runtime/src/delegation-history.ts
@@ -0,0 +1,533 @@
+/**
+ * Rebuild a delegate's model context from its persisted transcript rows
+ * (ADR 0276).
+ *
+ * Every row a delegate emits lands in the session transcript with
+ * `parentToolCallId` (the `Task` call that spawned it) and `agentName`. Those
+ * rows are written for review and never replayed into the parent's context
+ * (`runtime.ts` skips them on rebuild) — but they carry everything a resumed
+ * delegate needs: tool call/result pairs, thinking blocks, and the original
+ * `task` on the first `Task` tool row's arguments.
+ *
+ * A chain is the sequence of `Task` calls that share one delegate session: the
+ * first call plus every `resume`. Rows are keyed by the *call*, so
+ * reconstructing the chain means selecting every row whose `parentToolCallId`
+ * is one of the chain's calls.
+ *
+ * The conversion mirrors `historyToEntries` in `runtime.ts` (failed assistant
+ * rows stay transcript-only, tool rows attach to the assistant above them, an
+ * orphan tool row gets a synthesized carrier) but is parameterized by the
+ * delegate's own provider: a pinned delegation model is not the session model,
+ * and api/replay details depend on the binding.
+ */
+
+import type {
+ AssistantMessage,
+ Message,
+ Model,
+ Api,
+ ToolResultMessage,
+ UserMessage,
+} from "@earendil-works/pi-ai";
+import {
+ MAX_RESUMABLE_LISTED_FILES,
+ MAX_RESUMABLE_READ_LINES,
+ type UiMessage,
+} from "@pi-desktop/shared";
+import { isRecord, timestampMs, usageToPi } from "./agent-messages.js";
+import {
+ apiBindingForProviderModel,
+ type RuntimeProviderConfig,
+} from "./provider-binding.js";
+
+/** One chain of `Task` calls that share a delegate session. */
+export type DelegationChain = {
+ /** Stable identity across every `resume`; never appears in a tool or prompt. */
+ delegateSessionId: string;
+ /** Every `Task` toolCallId on this chain, oldest first. */
+ toolCallIds: string[];
+ /** Every `delegationId` issued on this chain, oldest first. */
+ delegationIds: string[];
+ agentName: string;
+ /** Read-only tool targets, accumulated across the whole chain. */
+ readFiles: string[];
+ /** Cumulative lines the chain's read-only tools have produced. */
+ readLineCount: number;
+ /** First `task` brief; seeds the resumed run's opening user turn. */
+ originalTask?: string;
+ /** Settled `delegationId` of the chain's latest run, for the prompt listing. */
+ latestDelegationId?: string;
+ /** Latest run's one-line objective, from the `description` or `task` text. */
+ latestObjective?: string;
+ /** Provider/model used by the latest run; resume must keep it. */
+ latestModelId?: string;
+ /** Settled status of the latest run; `running` while it works. Owns the
+ * resumability gate so pruning finished delegation records cannot make a
+ * stopped chain look reusable (ADR 0276). */
+ latestStatus?: string;
+ /** Latest activity timestamp, used for LRU eviction. */
+ lastActivityAt: number;
+};
+
+export type ResumableChain = DelegationChain & {
+ latestDelegationId: string;
+ latestObjective: string;
+};
+
+const READ_TOOLS = new Set(["Read", "Glob", "Grep", "BrowserPreview"]);
+const MISSING_TOOL_RESULT_PLACEHOLDER = "[no tool result recorded]";
+
+export function isReadOnlyToolName(name: string): boolean {
+ return READ_TOOLS.has(name);
+}
+
+/**
+ * Extract read-only tool targets from a delegate's tool rows. Write-tool
+ * targets are deliberately excluded: the parent needs to know what a delegate
+ * *saw*, and write serialization is already the path lock's job.
+ */
+export function extractReadFiles(rows: readonly UiMessage[]): {
+ files: string[];
+ lineCount: number;
+} {
+ const files: string[] = [];
+ let lineCount = 0;
+ for (const row of rows) {
+ if (row.role !== "tool" || !row.toolName || !READ_TOOLS.has(row.toolName)) {
+ continue;
+ }
+ const target = readToolTarget(row);
+ if (target) files.push(target);
+ lineCount += readToolLineCount(row);
+ }
+ return { files: uniquePreserveOrder(files), lineCount };
+}
+
+function uniquePreserveOrder(values: string[]): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const value of values) {
+ if (seen.has(value)) continue;
+ seen.add(value);
+ out.push(value);
+ }
+ return out;
+}
+
+function readToolTarget(row: UiMessage): string | undefined {
+ const args = isRecord(row.toolArgs) ? row.toolArgs : undefined;
+ const direct =
+ typeof args?.path === "string"
+ ? args.path
+ : typeof args?.file_path === "string"
+ ? args.file_path
+ : typeof args?.pattern === "string"
+ ? args.pattern
+ : undefined;
+ return direct?.trim() || undefined;
+}
+
+function readToolLineCount(row: UiMessage): number {
+ const text = toolResultText(row);
+ if (!text) return 0;
+ // A line count is all this gate needs; exact accounting is not load-bearing.
+ return text.split("\n").length;
+}
+
+function toolResultText(row: UiMessage): string | undefined {
+ const raw = row.toolResult;
+ if (typeof raw === "string") return raw;
+ if (!isRecord(raw)) return undefined;
+ const content = raw.content;
+ if (Array.isArray(content)) {
+ return content
+ .map((block) =>
+ isRecord(block) && typeof block.text === "string" ? block.text : "",
+ )
+ .join("\n");
+ }
+ if (typeof raw.text === "string") return raw.text;
+ return undefined;
+}
+
+/**
+ * Select this chain's rows out of a session transcript, in order.
+ *
+ * `Task` tool rows themselves carry no `parentToolCallId` (they belong to the
+ * parent), so callers pass the chain's calls in and get back the delegate's own
+ * rows only.
+ */
+export function selectChainRows(
+ transcript: readonly UiMessage[],
+ chain: Pick<DelegationChain, "toolCallIds" | "agentName">,
+): UiMessage[] {
+ const calls = new Set(chain.toolCallIds);
+ return transcript.filter(
+ (row) =>
+ typeof row.parentToolCallId === "string" &&
+ calls.has(row.parentToolCallId) &&
+ row.agentName === chain.agentName,
+ );
+}
+
+/**
+ * The first user turn of a resumed delegate is the original `task`, recovered
+ * from the persisted `Task` tool arguments. Returns `undefined` when the row or
+ * its arguments are gone (a truncated branch), in which case the chain is not
+ * resumable and the caller reports it as unknown.
+ */
+export function originalTaskFromTranscript(
+ transcript: readonly UiMessage[],
+ chain: Pick<DelegationChain, "toolCallIds">,
+): string | undefined {
+ const first = chain.toolCallIds[0];
+ if (!first) return undefined;
+ const row = transcript.find(
+ (candidate) =>
+ candidate.role === "tool" &&
+ candidate.toolName === "Task" &&
+ candidate.toolCallId === first,
+ );
+ if (!row) return undefined;
+ const args = isRecord(row.toolArgs) ? row.toolArgs : undefined;
+ const task = typeof args?.task === "string" ? args.task.trim() : "";
+ return task || undefined;
+}
+
+export function taskObjectiveFromArgs(args: unknown): string {
+ if (!isRecord(args)) return "";
+ const description =
+ typeof args.description === "string" ? args.description.trim() : "";
+ if (description) return description;
+ const task = typeof args.task === "string" ? args.task.trim() : "";
+ return task;
+}
+
+/**
+ * Convert a delegate's transcript rows into provider messages.
+ *
+ * Mirrors the parent's rebuild: an assistant row carries its text and thinking;
+ * a tool row appends its call to the assistant above it and emits a paired
+ * result. An orphan tool row (its assistant lost to a truncated branch) gets a
+ * synthesized carrier so the pair stays well-formed — providers reject an
+ * unpaired `toolUse`.
+ */
+export function chainRowsToMessages(
+ rows: readonly UiMessage[],
+ provider: RuntimeProviderConfig,
+ model: Model<Api>,
+): Message[] {
+ const api = apiBindingForProviderModel(provider).api;
+ const deepSeekCompletionsReplay =
+ api === "openai-completions" &&
+ (
+ model.compat as
+ | { requiresReasoningContentOnAssistantMessages?: boolean }
+ | undefined
+ )?.requiresReasoningContentOnAssistantMessages === true;
+
+ const messages: Message[] = [];
+ let toolCarrier: AssistantMessage | undefined;
+
+ for (const row of rows) {
+ const timestamp = timestampMs(row.createdAt) || Date.now();
+ if (row.role === "user") {
+ toolCarrier = undefined;
+ if (!(row.content || "").trim()) continue;
+ const userMessage: UserMessage = {
+ role: "user",
+ content: [{ type: "text", text: row.content }],
+ timestamp,
+ };
+ messages.push(userMessage);
+ } else if (row.role === "assistant") {
+ toolCarrier = undefined;
+ // Failed provider responses stay transcript-only: replaying one would
+ // hand the model a stopReason the provider never agreed to.
+ if (row.status === "error" || row.isError || row.error) continue;
+ const content: AssistantMessage["content"] = [];
+ if (row.thinking?.trim()) {
+ content.push({
+ type: "thinking",
+ thinking: row.thinking,
+ ...(deepSeekCompletionsReplay
+ ? { thinkingSignature: "reasoning_content" as const }
+ : {}),
+ });
+ }
+ if (row.content?.trim()) {
+ content.push({ type: "text", text: row.content });
+ }
+ const assistant: AssistantMessage = {
+ role: "assistant",
+ content,
+ api,
+ provider: provider.id,
+ model: provider.modelId,
+ usage: usageToPi(row.usage),
+ stopReason: "stop",
+ timestamp,
+ };
+ messages.push(assistant);
+ toolCarrier = assistant;
+ } else if (row.role === "tool") {
+ if (!row.toolCallId || !row.toolName) continue;
+ if (!toolCarrier) {
+ toolCarrier = {
+ role: "assistant",
+ content: [],
+ api,
+ provider: provider.id,
+ model: provider.modelId,
+ usage: usageToPi(undefined),
+ stopReason: "toolUse",
+ timestamp,
+ };
+ messages.push(toolCarrier);
+ }
+ toolCarrier.content.push({
+ type: "toolCall",
+ id: row.toolCallId,
+ name: row.toolName,
+ arguments: isRecord(row.toolArgs) ? row.toolArgs : {},
+ });
+ toolCarrier.stopReason = "toolUse";
+ messages.push(toolResultFromUi(row, timestamp));
+ }
+ }
+
+ // A call-only turn with no text is a legitimate carrier; an assistant that
+ // ended with neither text nor calls carries nothing to the model.
+ return messages.filter(
+ (message) =>
+ message.role !== "assistant" || message.content.length > 0,
+ );
+}
+
+/** Seed a resumed run: original task as the first user turn, then history. */
+export function seedDelegateMessages(options: {
+ originalTask: string;
+ rows: readonly UiMessage[];
+ provider: RuntimeProviderConfig;
+ model: Model<Api>;
+}): Message[] {
+ const history = chainRowsToMessages(options.rows, options.provider, options.model);
+ const first: UserMessage = {
+ role: "user",
+ content: [{ type: "text", text: options.originalTask }],
+ timestamp: timestampMs(options.rows[0]?.createdAt) || Date.now(),
+ };
+ const rest = history.filter(
+ (message) =>
+ !(
+ message.role === "user" &&
+ typeof message.content !== "string" &&
+ message.content.length === 1 &&
+ message.content[0]?.type === "text" &&
+ message.content[0].text === options.originalTask
+ ),
+ );
+ return [first, ...rest];
+}
+
+function toolResultFromUi(m: UiMessage, timestamp: number): ToolResultMessage {
+ const raw = m.toolResult;
+ const blocks: ToolResultMessage["content"] = [];
+ const rawBlocks =
+ isRecord(raw) && Array.isArray(raw.content) ? raw.content : undefined;
+ if (rawBlocks) {
+ for (const block of rawBlocks) {
+ if (!isRecord(block)) continue;
+ if (block.type === "text" && typeof block.text === "string") {
+ blocks.push({ type: "text", text: block.text });
+ } else if (
+ block.type === "image" &&
+ typeof block.data === "string" &&
+ typeof block.mimeType === "string"
+ ) {
+ blocks.push({
+ type: "image",
+ data: block.data,
+ mimeType: block.mimeType,
+ });
+ }
+ }
+ } else if (typeof raw === "string" && raw.trim()) {
+ blocks.push({ type: "text", text: raw });
+ } else if (raw !== undefined && raw !== null) {
+ blocks.push({ type: "text", text: safeJson(raw) });
+ }
+ if (blocks.length === 0) {
+ blocks.push({
+ type: "text",
+ text:
+ m.toolStatus === "running"
+ ? "[tool call was interrupted before a result was recorded]"
+ : MISSING_TOOL_RESULT_PLACEHOLDER,
+ });
+ }
+ const details = isRecord(raw) ? raw.details : undefined;
+ return {
+ role: "toolResult",
+ toolCallId: m.toolCallId ?? "",
+ toolName: m.toolName ?? "",
+ content: blocks,
+ ...(details !== undefined ? { details } : {}),
+ isError:
+ m.toolStatus === "running" ||
+ m.toolStatus === "error" ||
+ m.toolStatus === "denied" ||
+ m.isError === true,
+ timestamp,
+ };
+}
+
+function safeJson(value: unknown): string {
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return String(value);
+ }
+}
+
+export type RebuiltTaskCall = {
+ toolCallId: string;
+ delegationId: string;
+ agentName: string;
+ resume?: string;
+ objective: string;
+ task?: string;
+ modelId?: string;
+ createdAt: number;
+};
+/**
+ * Scan persisted `Task` tool rows and group them into chains by their
+ * `resume` links. Used at session launch so a restart does not lose
+ * resumability (ADR 0276 §12).
+ */
+export function rebuildChainsFromTranscript(
+ transcript: readonly UiMessage[],
+): DelegationChain[] {
+ const calls: RebuiltTaskCall[] = [];
+ for (const row of transcript) {
+ if (row.role !== "tool" || row.toolName !== "Task" || !row.toolCallId) {
+ continue;
+ }
+ const args = isRecord(row.toolArgs) ? row.toolArgs : undefined;
+ const details =
+ isRecord(row.toolResult) && isRecord(row.toolResult.details)
+ ? row.toolResult.details
+ : undefined;
+ const delegationId =
+ typeof details?.delegationId === "string" ? details.delegationId : "";
+ const agentName =
+ typeof args?.agent === "string"
+ ? args.agent
+ : typeof details?.agent === "string"
+ ? details.agent
+ : "";
+ const resume =
+ typeof args?.resume === "string" ? args.resume.trim() : "";
+ const task = typeof args?.task === "string" ? args.task.trim() : "";
+ const modelId =
+ typeof details?.modelId === "string" ? details.modelId : undefined;
+ calls.push({
+ toolCallId: row.toolCallId,
+ delegationId,
+ agentName,
+ ...(resume ? { resume } : {}),
+ objective: taskObjectiveFromArgs(args),
+ ...(task ? { task } : {}),
+ ...(modelId ? { modelId } : {}),
+ createdAt: timestampMs(row.createdAt) || Date.now(),
+ });
+ }
+
+ const byDelegationId = new Map(calls.map((call) => [call.delegationId, call]));
+ const children = new Map<string, RebuiltTaskCall[]>();
+ const roots: RebuiltTaskCall[] = [];
+ for (const call of calls) {
+ if (!call.resume) {
+ roots.push(call);
+ continue;
+ }
+ const parent = byDelegationId.get(call.resume);
+ if (!parent) {
+ // A resume whose parent is gone is not a chain; skip it.
+ continue;
+ }
+ const siblings = children.get(parent.delegationId) ?? [];
+ siblings.push(call);
+ children.set(parent.delegationId, siblings);
+ }
+
+ const chains: DelegationChain[] = [];
+ for (const root of roots) {
+ const ordered: RebuiltTaskCall[] = [];
+ const walk = (call: RebuiltTaskCall) => {
+ ordered.push(call);
+ for (const child of children.get(call.delegationId) ?? []) {
+ if (child.agentName !== root.agentName) continue;
+ walk(child);
+ }
+ };
+ walk(root);
+ const toolCallIds = ordered.map((call) => call.toolCallId);
+ const rows = selectChainRows(transcript, {
+ toolCallIds,
+ agentName: root.agentName,
+ });
+ const reads = extractReadFiles(rows);
+ const latest = ordered[ordered.length - 1];
+ chains.push({
+ delegateSessionId: root.delegationId,
+ toolCallIds,
+ delegationIds: ordered.map((call) => call.delegationId),
+ agentName: root.agentName,
+ readFiles: reads.files,
+ readLineCount: reads.lineCount,
+ originalTask: root.task,
+ latestDelegationId: latest?.delegationId,
+ latestObjective: latest?.objective ?? root.objective,
+ latestModelId: latest?.modelId,
+ lastActivityAt: latest?.createdAt ?? root.createdAt,
+ });
+ }
+ return chains;
+}
+
+export function isChainWithinReadBudget(
+ chain: Pick<DelegationChain, "readLineCount">,
+ budget = MAX_RESUMABLE_READ_LINES,
+): boolean {
+ return chain.readLineCount <= budget;
+}
+
+export function listedReadFiles(
+ files: readonly string[],
+ limit = MAX_RESUMABLE_LISTED_FILES,
+): { files: string[]; omitted: number } {
+ if (files.length <= limit) return { files: [...files], omitted: 0 };
+ return { files: files.slice(0, limit), omitted: files.length - limit };
+}
+
+export function formatResumableList(chains: readonly ResumableChain[]): string {
+ if (chains.length === 0) return "";
+ const lines = [
+ "Reusable subagent sessions (same conversation only). To continue one, pass its `resume` id on Task. Saying \"reuse\" in prose is not enough; omit `resume` to start a new session. Do not pass `model` when resuming.",
+ ];
+ for (const chain of chains) {
+ const listed = listedReadFiles(chain.readFiles);
+ const files =
+ listed.files.length === 0
+ ? "none recorded"
+ : listed.omitted > 0
+ ? `${listed.files.join(", ")} (+${listed.omitted} more)`
+ : listed.files.join(", ");
+ lines.push(
+ `- ${chain.agentName} / ${chain.latestDelegationId}: ${chain.latestObjective || "(no label)"}`,
+ );
+ lines.push(` Files read: ${files}`);
+ }
+ return lines.join("\n");
+}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 49d9f5dd9..d870d2e1f 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -6803,6 +6803,236 @@ describe("DesktopAgentRuntime subagents", () => {
await runtime.dispose();
});
+
+ describe("resume (ADR 0276)", () => {
+ /** Rows a delegate left in the transcript, tagged with its `Task` call. */
+ function delegateRow(
+ id: string,
+ parentToolCallId: string,
+ overrides: Partial<UiMessage> = {},
+ ): UiMessage {
+ return {
+ id,
+ role: "assistant",
+ content: "reading src/app.ts",
+ createdAt: "2026-08-06T00:00:01.000Z",
+ status: "complete",
+ parentToolCallId,
+ agentName: "explorer",
+ ...overrides,
+ };
+ }
+
+ async function startTask(
+ runtime: DesktopAgentRuntime,
+ toolCallId: string,
+ args: Record<string, unknown>,
+ ) {
+ return taskTool(runtime).execute(toolCallId, args);
+ }
+
+ it("seeds a resumed run with the chain's prior messages and keeps its model", async () => {
+ const history: UiMessage[] = [
+ delegateRow("child-1", "task-1"),
+ {
+ id: "tool-1",
+ role: "tool",
+ content: "",
+ createdAt: "2026-08-06T00:00:02.000Z",
+ toolCallId: "read-1",
+ toolName: "Read",
+ toolArgs: { path: "src/app.ts" },
+ toolResult: {
+ content: [{ type: "text", text: "line one\nline two" }],
+ },
+ toolStatus: "success",
+ parentToolCallId: "task-1",
+ agentName: "explorer",
+ },
+ ];
+ const runtime = createRuntime({ subagents: [explorer], history });
+ (runtime as any).transcriptHistory.push({
+ id: "task-1",
+ role: "tool",
+ content: "",
+ createdAt: "2026-08-06T00:00:00.000Z",
+ toolCallId: "task-1",
+ toolName: "Task",
+ toolArgs: { agent: "explorer", task: "Explore the parser." },
+ toolResult: { details: { delegationId: "del-1", agent: "explorer" } },
+ toolStatus: "success",
+ });
+ (runtime as any).delegationChains.hydrate(
+ (await import("./delegation-history.js")).rebuildChainsFromTranscript(
+ (runtime as any).transcriptHistory,
+ ),
+ );
+
+ subagentRuns.calls.length = 0;
+ subagentRuns.deferred = true;
+ const started = await startTask(runtime, "task-2", {
+ agent: "explorer",
+ task: "Now cover the lexer.",
+ resume: "del-1",
+ });
+ subagentRuns.deferred = false;
+
+ expect((started.details as any).resumedFrom).toBe("del-1");
+ expect(subagentRuns.calls).toHaveLength(1);
+ const options = subagentRuns.calls[0];
+ // The resumed delegate replays the original brief plus its own rows; the
+ // new brief is the user turn `prompt()` adds, not part of the seed.
+ expect(options.task).toBe("Now cover the lexer.");
+ expect(options.initialMessages[0]).toMatchObject({
+ role: "user",
+ content: [{ type: "text", text: "Explore the parser." }],
+ });
+ expect(
+ options.initialMessages.some(
+ (message: any) =>
+ message.role === "assistant" &&
+ message.content.some(
+ (block: any) => block.type === "toolCall" && block.name === "Read",
+ ),
+ ),
+ ).toBe(true);
+ const record = (runtime as any).delegations.get(
+ (started.details as any).delegationId,
+ );
+ expect(record.resumedFrom).toBe("del-1");
+ expect(record.delegateSessionId).toBe("del-1");
+ expect(record.toolCallIdChain).toEqual(["task-1", "task-2"]);
+
+ await runtime.dispose();
+ });
+
+ it("rejects a model override on resume", async () => {
+ const history: UiMessage[] = [delegateRow("child-1", "task-1")];
+ const runtime = createRuntime({ subagents: [explorer], history });
+ (runtime as any).transcriptHistory.push({
+ id: "task-1",
+ role: "tool",
+ content: "",
+ createdAt: "2026-08-06T00:00:00.000Z",
+ toolCallId: "task-1",
+ toolName: "Task",
+ toolArgs: { agent: "explorer", task: "Explore." },
+ toolResult: { details: { delegationId: "del-1" } },
+ toolStatus: "success",
+ });
+
+ subagentRuns.calls.length = 0;
+ const result = await startTask(runtime, "task-2", {
+ agent: "explorer",
+ task: "More.",
+ resume: "del-1",
+ model: "local/local-model",
+ });
+
+ expect(String((result.details as any).error)).toContain(
+ "cannot change its model",
+ );
+ expect(subagentRuns.calls).toHaveLength(0);
+ await runtime.dispose();
+ });
+
+ it("reports an unknown resume id without starting a delegate", async () => {
+ const runtime = createRuntime({ subagents: [explorer] });
+ subagentRuns.calls.length = 0;
+ const result = await startTask(runtime, "task-1", {
+ agent: "explorer",
+ task: "Continue.",
+ resume: "missing",
+ });
+ const message = String((result.details as any).error);
+ expect(message).toContain("Unknown delegation");
+ expect(message).toContain("No reusable subagent sessions");
+ expect(subagentRuns.calls).toHaveLength(0);
+ await runtime.dispose();
+ });
+
+ it("refuses to resume a running delegation", async () => {
+ const runtime = createRuntime({ subagents: [explorer] });
+ subagentRuns.calls.length = 0;
+ subagentRuns.deferred = true;
+ const first = await startTask(runtime, "task-1", {
+ agent: "explorer",
+ task: "Find it.",
+ });
+ const delegationId = (first.details as any).delegationId as string;
+ const second = await startTask(runtime, "task-2", {
+ agent: "explorer",
+ task: "Again.",
+ resume: delegationId,
+ });
+ expect(String((second.details as any).error)).toContain("still running");
+ expect(subagentRuns.calls).toHaveLength(1);
+ subagentRuns.resolveRun?.({
+ agentName: "explorer",
+ status: "completed",
+ report: "done",
+ turns: 1,
+ toolCalls: 0,
+ });
+ subagentRuns.deferred = false;
+ await runtime.dispose();
+ });
+
+ it("marks a chain resumable only after it settles", async () => {
+ const runtime = createRuntime({ subagents: [explorer] });
+ subagentRuns.calls.length = 0;
+ subagentRuns.deferred = true;
+ const started = await startTask(runtime, "task-1", {
+ agent: "explorer",
+ task: "Find it.",
+ });
+ const delegationId = (started.details as any).delegationId as string;
+ const internals = runtime as any;
+ expect(
+ internals.delegationChains.lookup(delegationId).latestStatus,
+ ).toBe("running");
+ subagentRuns.resolveRun?.({
+ agentName: "explorer",
+ status: "completed",
+ report: "done",
+ turns: 1,
+ toolCalls: 0,
+ });
+ await vi.waitFor(() => {
+ expect(
+ internals.delegationChains.lookup(delegationId).latestStatus,
+ ).toBe("completed");
+ });
+ subagentRuns.deferred = false;
+ await runtime.dispose();
+ });
+
+ it("lists a settled delegation in the parent's system prompt", async () => {
+ const runtime = createRuntime({ subagents: [explorer] });
+ subagentRuns.calls.length = 0;
+ subagentRuns.deferred = true;
+ const started = await startTask(runtime, "task-1", {
+ agent: "explorer",
+ task: "Find it.",
+ description: "find the bug",
+ });
+ const delegationId = (started.details as any).delegationId as string;
+ subagentRuns.resolveRun?.({
+ agentName: "explorer",
+ status: "completed",
+ report: "done",
+ turns: 1,
+ toolCalls: 0,
+ });
+ await vi.waitFor(() => {
+ expect((runtime as any).agent.state.systemPrompt).toContain(
+ `explorer / ${delegationId}: find the bug`,
+ );
+ });
+ subagentRuns.deferred = false;
+ await runtime.dispose();
+ });
+ });
});
describe("DesktopAgentRuntime deferred tool restore (#225)", () => {
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index b28584b22..072e61c6c 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -131,6 +131,16 @@ import {
type RuntimeProviderConfig,
} from "./provider-binding.js";
import { PathMutex } from "./path-lock.js";
+import { DelegationChainRegistry } from "./delegation-chain.js";
+import {
+ extractReadFiles,
+ isReadOnlyToolName,
+ originalTaskFromTranscript,
+ rebuildChainsFromTranscript,
+ selectChainRows,
+ seedDelegateMessages,
+ type DelegationChain,
+} from "./delegation-history.js";
import {
composeSubagentSystemPrompt,
SubagentRun,
@@ -308,8 +318,16 @@ function isMissingToolResultPlaceholder(
content[0].text === MISSING_TOOL_RESULT_PLACEHOLDER
);
}
-export const ASK_TOOL_NAME = "asktool";
+/** Narrow view of the `tool_end` agent event; the envelope carries the rest. */
+type ToolEndEvent = {
+ type: "tool_end";
+ toolCallId: string;
+ result: unknown;
+ isError?: boolean;
+};
+
+export const ASK_TOOL_NAME = "asktool";
/**
* Delegation lifecycle (ADR 0089): `Task` starts a subagent in the background
* and returns immediately; `TaskWait` converges on running delegations;
@@ -372,8 +390,15 @@ export type DelegationRecord = {
* `TaskWait` result or the resume-after-idle prompt. Auto-delivery is a
* single shot per record. */
reportDelivered: boolean;
+ /** Stable chain identity; never appears in a tool parameter (ADR 0276). */
+ delegateSessionId: string;
+ /** Every `Task` toolCallId on this chain, oldest first. */
+ toolCallIdChain: string[];
+ /** Prior `delegationId` this run continues, when `Task.resume` was set. */
+ resumedFrom?: string;
};
+
function delegationSummary(record: DelegationRecord): Record<string, unknown> {
return {
delegationId: record.delegationId,
@@ -388,6 +413,7 @@ function delegationSummary(record: DelegationRecord): Record<string, unknown> {
...(record.completedAt ? { completedAt: record.completedAt } : {}),
...(record.result?.modelFailures ? { modelFailures: record.result.modelFailures } : {}),
...(record.result?.error ? { error: record.result.error } : {}),
+ ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}),
};
}
@@ -1428,6 +1454,16 @@ export class DesktopAgentRuntime {
* returns; `TaskWait`/`TaskList`/`TaskStop` drive it afterwards.
*/
private delegations = new Map<string, DelegationRecord>();
+ /** Resumable chains rebuilt from the transcript and updated as Task settles. */
+ private readonly delegationChains = new DelegationChainRegistry();
+ /** Transcript rows used to rebuild a resumed delegate's context (ADR 0276):
+ * the seed history at launch plus every row this session's delegates emit. */
+ private readonly transcriptHistory: UiMessage[];
+ /** Row ids already in `transcriptHistory` from live delegate events, so a
+ * retried stream appends once. */
+ private readonly appendedDelegationRowIds = new Set<string>();
+ /** `toolName` of a delegate's in-flight call; `tool_end` carries no name. */
+ private readonly delegateToolNames = new Map<string, string>();
/** Set by `abort` / `dispose` so a finishing delegate cannot restart the parent. */
private runCancelled = false;
/**
@@ -1613,8 +1649,12 @@ export class DesktopAgentRuntime {
this.models = models;
const runtimeApiKey = providerRequestKey(this.provider);
- this.fullEntries = this.historyToEntries(opts.history ?? []);
+ this.transcriptHistory = [...(opts.history ?? [])];
+ this.fullEntries = this.historyToEntries(this.transcriptHistory);
this.activeCompaction = opts.compaction;
+ this.delegationChains.hydrate(
+ rebuildChainsFromTranscript(this.transcriptHistory),
+ );
const skillsPrompt = pluginSkillsPrompt(this.pluginSkills);
const defaultSystemPrompt = [
DEFAULT_RUNTIME_SYSTEM_PROMPT,
@@ -1843,6 +1883,12 @@ Delegation rules:
const 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(),
+ })
+ : "";
return composeModeSystemPrompt(
this.mode,
[
@@ -1850,10 +1896,22 @@ Delegation rules:
...(optionalToolsPrompt ? [optionalToolsPrompt] : []),
...(projectPrompt ? [projectPrompt] : []),
...(memoryPrompt ? [memoryPrompt] : []),
+ ...(resumablePrompt ? [resumablePrompt] : []),
].join("\n\n"),
);
}
+ /**
+ * 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.
+ */
+ private refreshResumablePrompt(): void {
+ if (this.subagents.length === 0) return;
+ if (!this.agent) return;
+ this.agent.state.systemPrompt = this.composeSystemPrompt();
+ }
+
/**
* 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.
@@ -3561,6 +3619,89 @@ Delegation rules:
};
}
+ /** Every delegation still working; a resume of one is a queueing attempt. */
+ private runningDelegationIds(): Set<string> {
+ return new Set(
+ this.runningDelegations().map((record) => record.delegationId),
+ );
+ }
+
+ /**
+ * Resolve a `Task.resume` id to its chain, or fail with a message that tells
+ * the model how to proceed (ADR 0276). The parent only ever sees
+ * `delegationId`; the chain identity behind it stays internal.
+ */
+ private resolveResumeChain(
+ resume: string,
+ agentName: string,
+ ):
+ | { ok: true; chain: DelegationChain }
+ | { ok: false; message: string } {
+ const lookup = this.delegationChains.resolveResume({
+ resume,
+ agentName,
+ runningDelegationIds: this.runningDelegationIds(),
+ });
+ if (lookup.ok) return lookup;
+ const error = lookup.error;
+ switch (error.kind) {
+ case "unknown":
+ return { ok: false, message: this.unknownResumeMessage(resume) };
+ case "running":
+ return {
+ ok: false,
+ message: `Delegation ${error.delegationId} is still running. Call TaskWait to converge with it first, or start a new delegation. Resuming a running delegation is not queued.`,
+ };
+ case "not-resumable":
+ return {
+ ok: false,
+ message: `Delegation ${resume} ended as "${error.status}" and cannot be resumed. Only completed or failed delegations continue; start a new delegation instead.`,
+ };
+ case "agent-mismatch":
+ return {
+ ok: false,
+ message: `Delegation ${resume} belongs to the ${error.expected} subagent, not ${error.actual}. Resume it with the matching agent name, or start a new delegation.`,
+ };
+ case "over-budget":
+ return {
+ ok: false,
+ message: `Delegation ${resume} has read too much to resume cheaply. Start a new delegation and point it at the specific files it should re-read.`,
+ };
+ }
+ }
+
+ private unknownResumeMessage(resume: string): string {
+ return this.delegationChains.unknownResumeError(
+ resume,
+ this.delegationChains.resumableList({
+ runningDelegationIds: this.runningDelegationIds(),
+ }),
+ );
+ }
+
+ /**
+ * Rebuild the delegate's prior conversation from its transcript rows. The
+ * rows carry `parentToolCallId` for exactly the chain's `Task` calls, so the
+ * replay never picks up the parent's own rows or a sibling delegate's.
+ */
+ private seedResumedDelegate(
+ chain: DelegationChain,
+ provider: RuntimeProviderConfig,
+ ): AgentMessage[] | undefined {
+ const originalTask =
+ chain.originalTask ??
+ originalTaskFromTranscript(this.transcriptHistory, chain);
+ if (!originalTask) return undefined;
+ const rows = selectChainRows(this.transcriptHistory, chain);
+ if (rows.length === 0) return undefined;
+ return seedDelegateMessages({
+ originalTask,
+ rows,
+ provider,
+ model: buildProviderModel(provider),
+ });
+ }
+
/**
* `Task`: delegate one bounded piece of work to a subagent (ADR 0062).
*
@@ -3594,8 +3735,9 @@ Delegation rules:
]),
"`task` is the delegate's only instruction. It cannot see this conversation, and you cannot correct it while it runs, so state the goal, the paths and facts it cannot infer, and exactly what to report back.",
"To run delegates concurrently, emit several Task calls in one assistant message. A message that mixes Task with any other tool runs one call at a time. You may keep working or talk to the user while they run; the runtime delivers their reports when they finish. Call TaskStop only to cancel.",
- `Available subagents:\n${catalog}`,
- ].join("\n\n"),
+ "To continue a previous subagent, pass its `resume` id (the `delegationId` returned by Task). Saying \"reuse\" in prose is not enough. Do not pass `model` when resuming; start a new delegation to change models.",
+ `Available subagents:\\n${catalog}`,
+ ].join("\\n\\n"),
parameters: Type.Object({
agent: Type.String({
description: `Name of the subagent to run: ${names.join(", ")}.`,
@@ -3613,7 +3755,13 @@ Delegation rules:
model: Type.Optional(
Type.String({
description:
- "Override the delegate's model for this run, e.g. 'anthropic/claude-sonnet-4-20250514'. Omit to use the subagent's default. Repeating the definition's own Default model key is the same as omitting this parameter. Only choose a different override from the available delegation model catalog.",
+ "Override the delegate's model for this run, e.g. 'anthropic/claude-sonnet-4-20250514'. Omit to use the subagent's default. Repeating the definition's own Default model key is the same as omitting this parameter. Only choose a different override from the available delegation model catalog. Forbidden when `resume` is set.",
+ }),
+ ),
+ resume: Type.Optional(
+ Type.String({
+ description:
+ "delegationId of a settled subagent in this conversation to continue. Omit to start a new session.",
}),
),
}),
@@ -3635,17 +3783,28 @@ Delegation rules:
isRecord(params) && typeof params.task === "string"
? params.task.trim()
: "";
+ const resume =
+ isRecord(params) && typeof params.resume === "string"
+ ? params.resume.trim()
+ : "";
+ // Model override: Task.model > definition.model pin > session model.
+ const modelOverride =
+ isRecord(params) && typeof params.model === "string"
+ ? params.model.trim()
+ : "";
+ // Resume keeps the chain's model; a new delegation is the way to switch.
+ if (resume && modelOverride) {
+ return this.subagentToolError(
+ toolCallId,
+ `Resuming a subagent cannot change its model. Omit \`model\` to continue ${resume}, or start a new delegation to pick a different model.`,
+ );
+ }
if (!task) {
return this.subagentToolError(
toolCallId,
`Delegating to ${definition.name} needs a non-empty \`task\` brief.`,
);
}
- // Model override: Task.model > definition.model pin > session model.
- const modelOverride =
- isRecord(params) && typeof params.model === "string"
- ? params.model.trim()
- : "";
let provider: RuntimeProviderConfig | undefined;
if (modelOverride) {
if (this.isDefinitionPinOverride(definition, modelOverride)) {
@@ -3712,6 +3871,31 @@ Delegation rules:
}
// The delegate runs in the background (ADR 0089): `Task` returns
// immediately with a delegation id, and TaskWait converges later.
+ const resumeLookup = resume
+ ? this.resolveResumeChain(resume, definition.name)
+ : undefined;
+ if (resume && resumeLookup && !resumeLookup.ok) {
+ return this.subagentToolError(toolCallId, resumeLookup.message);
+ }
+ const resumedChain = resumeLookup?.ok ? resumeLookup.chain : undefined;
+ if (
+ resumedChain?.latestModelId &&
+ resumedChain.latestModelId !== provider.modelId
+ ) {
+ return this.subagentToolError(
+ toolCallId,
+ `Resuming ${resume} continues the ${resumedChain.latestModelId} model. Omit \`model\` to keep it, or start a new delegation to change models.`,
+ );
+ }
+ const initialMessages = resumedChain
+ ? this.seedResumedDelegate(resumedChain, provider)
+ : undefined;
+ if (resume && !initialMessages) {
+ return this.subagentToolError(
+ toolCallId,
+ this.unknownResumeMessage(resume),
+ );
+ }
const delegationId = randomUUID();
const controller = new AbortController();
const thinkingLevel: SubagentThinkingLevel =
@@ -3730,6 +3914,20 @@ Delegation rules:
const completion = new Promise<void>((resolve) => {
resolveCompletion = resolve;
});
+ const objective =
+ isRecord(params) && typeof params.description === "string"
+ ? params.description.trim()
+ : task;
+ const chain = this.delegationChains.start({
+ delegateSessionId: resumedChain?.delegateSessionId ?? delegationId,
+ delegationId,
+ toolCallId,
+ agentName: definition.name,
+ originalTask: resumedChain?.originalTask ?? task,
+ objective,
+ latestModelId: provider.modelId,
+ resumedFrom: resumedChain,
+ });
const record: DelegationRecord = {
delegationId,
taskTurnId: this.turnId,
@@ -3748,6 +3946,9 @@ Delegation rules:
lastPhase: "waiting-model",
startedEpoch: this.turnEpoch,
reportDelivered: false,
+ delegateSessionId: chain.delegateSessionId,
+ toolCallIdChain: [...chain.toolCallIds],
+ ...(resumedChain ? { resumedFrom: resume } : {}),
};
this.delegations.set(delegationId, record);
const scopedTools = this.scopeDelegateTools(tools, definition);
@@ -3783,6 +3984,8 @@ Delegation rules:
// 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(
@@ -3826,6 +4029,7 @@ Delegation rules:
startedAt,
modelId: provider.modelId,
thinkingLevel,
+ ...(resumedChain ? { resumedFrom: resume } : {}),
},
};
},
@@ -3869,9 +4073,11 @@ Delegation rules:
if (result.usage) {
this.turnSubagentUsage = addUsage(this.turnSubagentUsage, result.usage);
}
+ this.delegationChains.settle(record.delegateSessionId, record.status);
this.publishDelegationSettlement(record);
record.resolveCompletion();
this.refreshDelegationWait();
+ this.refreshResumablePrompt();
this.pruneFinishedDelegations();
}
@@ -3981,12 +4187,17 @@ Delegation rules:
if (event.type === "tool_start") {
record.toolCalls += 1;
this.touchDelegationPhase(record, "tool", event.toolName);
+ this.delegateToolNames.set(event.toolCallId, event.toolName);
return;
}
if (event.type === "tool_end") {
this.touchDelegationPhase(record, "waiting-model");
+ this.appendDelegationRow(record, envelope, this.toolRowFromEnvelope(envelope));
return;
}
+ if (event.type === "message_end" && event.message.role === "assistant") {
+ this.appendDelegationRow(record, envelope, event.message);
+ }
if (
(event.type === "message_start" || event.type === "message_update") &&
event.message.role === "assistant"
@@ -4003,6 +4214,56 @@ Delegation rules:
}
}
+ /**
+ * Keep `transcriptHistory` current with what a delegate produced, so a later
+ * `Task.resume` in the same session replays the chain without waiting on
+ * persistence (ADR 0276). A retried stream reuses the row id and appends once.
+ */
+ private appendDelegationRow(
+ record: DelegationRecord,
+ envelope: AgentEventEnvelope,
+ row: UiMessage,
+ ): void {
+ const tagged: UiMessage = {
+ ...row,
+ parentToolCallId: envelope.parentToolCallId ?? row.parentToolCallId,
+ agentName: envelope.agentName ?? row.agentName,
+ };
+ const key =
+ tagged.role === "tool"
+ ? `tool:${tagged.toolCallId ?? ""}`
+ : `message:${tagged.id ?? ""}`;
+ if (key.endsWith(":")) return;
+ if (this.appendedDelegationRowIds.has(key)) return;
+ this.appendedDelegationRowIds.add(key);
+ this.transcriptHistory.push(tagged);
+ if (tagged.role === "tool" && isReadOnlyToolName(tagged.toolName ?? "")) {
+ const { files, lineCount } = extractReadFiles([tagged]);
+ this.delegationChains.noteReads(record.delegateSessionId, files, lineCount);
+ }
+ }
+
+ private toolRowFromEnvelope(envelope: AgentEventEnvelope): UiMessage {
+ const event = envelope.event as ToolEndEvent;
+ const toolName = this.delegateToolNames.get(event.toolCallId) ?? "";
+ const ts = new Date(envelope.ts ?? Date.now()).toISOString();
+ return {
+ id: `delegate-tool-${event.toolCallId}`,
+ role: "tool",
+ content: "",
+ createdAt: ts,
+ toolCompletedAt: ts,
+ toolCallId: event.toolCallId,
+ toolName,
+ toolArgs: undefined,
+ toolResult: event.result,
+ toolStatus: event.isError ? "error" : "success",
+ isError: Boolean(event.isError),
+ parentToolCallId: envelope.parentToolCallId,
+ agentName: envelope.agentName,
+ };
+ }
+
private touchDelegationPhase(
record: DelegationRecord,
phase: AgentActivityAgentPhase,
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index 7ed5946e8..13a85c153 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -26,6 +26,7 @@ import {
type AfterToolCallContext,
type AfterToolCallResult,
type AgentEvent,
+ type AgentMessage,
type AgentTool,
} from "@earendil-works/pi-agent-core";
import type { AssistantMessage } from "@earendil-works/pi-ai";
@@ -129,6 +130,12 @@ export type SubagentRunOptions = {
context: AfterToolCallContext,
) => SubagentToolOutcome | undefined;
signal?: AbortSignal;
+ /**
+ * Prior chain messages that seed this run (ADR 0276). Omitted for a cold
+ * start. The original `task` is still passed to `prompt()` as the new user
+ * turn; these messages are everything that came before it.
+ */
+ initialMessages?: AgentMessage[];
};
/**
@@ -179,7 +186,8 @@ function boundedReport(value: string): string {
export { addUsage };
-/** One delegate execution. Instances are single-use. */
+/** One delegate execution. A resumed run is still a new instance; it is
+ * seeded with the prior chain's messages rather than kept warm in memory. */
export class SubagentRun {
private readonly agent: Agent;
private readonly opts: SubagentRunOptions;
@@ -219,7 +227,7 @@ export class SubagentRun {
model: binding.model,
tools: opts.tools,
thinkingLevel: binding.agentThinkingLevel,
- messages: [],
+ messages: opts.initialMessages ? [...opts.initialMessages] : [],
},
toolExecution: "sequential",
});
diff --git a/packages/shared/src/subagent-definition.ts b/packages/shared/src/subagent-definition.ts
index 98fd3b4f7..664c966d5 100644
--- a/packages/shared/src/subagent-definition.ts
+++ b/packages/shared/src/subagent-definition.ts
@@ -208,6 +208,14 @@ export const MAX_SUBAGENT_DEFINITIONS = 16;
export const MAX_SUBAGENT_PROVIDERS = 8;
/** Running delegates per session, across batches (see ADR 0089). */
export const MAX_SUBAGENT_CONCURRENCY = 10;
+/** Resumable chains kept per subagent name before the oldest is evicted
+ * (ADR 0276). A chain is one delegate session across any number of `resume`s. */
+export const MAX_RESUMABLE_CHAINS_PER_AGENT = 2;
+/** Cumulative lines a chain's read-only tools may read before it leaves the
+ * resumable list and the next delegation for that work runs cold (ADR 0276). */
+export const MAX_RESUMABLE_READ_LINES = 50_000;
+/** Files listed per chain in the parent's resumable-session prompt block. */
+export const MAX_RESUMABLE_LISTED_FILES = 8;
const NAME_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;