Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): isolate delegate mutation recovery and failure results
AR3077a03669b0f0c
diff --git a/Summary.md b/Summary.mdnew file mode 100644index 000000000..ac9d3fec4--- /dev/null+++ b/Summary.md@@ -0,0 +1,13 @@+# PI-Desktop++PI-Desktop is a local-first coding agent application. React renders the UI,+Electron coordinates host services, Rust owns persistence and native tools,+and the Node runtime executes the agent through pi libraries.++## 2026-10-07: Delegate mutation recovery++Mutation counts and recovery graces are isolated by the executing agent.+Exhaustion returns a failed, resumable Task result instead of completing the+delegate and failing the parent. Shared recovery descriptions now live in a+small module rather than growing the runtime entry point. Controlled HTTP+flows cover concurrent Edit and shell patch failures plus Task resume.diff --git a/docs/adr/0207-three-mutation-recovery-failures.md b/docs/adr/0207-three-mutation-recovery-failures.mdindex 0419a9141..81f00ed38 100644--- a/docs/adr/0207-three-mutation-recovery-failures.md+++ b/docs/adr/0207-three-mutation-recovery-failures.md@@ -26,6 +26,16 @@ per-code grace, counters are scoped to the prompt and path, and a successfulmutation clears that path's failure history. Provider retry budgets and othertool concurrency limits are unaffected.+### Delegate ownership correction (2026-10-07)++The prompt scope means the individual executing agent, not the whole session.+Sharing path keys caused concurrent delegates to spend one another's attempts+and report exhaustion on the parent. Recovery keys now include the parent or+delegation owner; parent restarts do not reset detached work. Settlement releases+the delegate's counters and graces. A terminal tool error is carried to the+delegate result so earlier prose cannot classify an exhausted run as completed.+The failed chain and its report remain resumable through the existing Task flow.+## Consequences- The model gets one additional bounded opportunity to correct an Edit ordiff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 00306e26a..6a644bde9 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -329,7 +329,11 @@ keeps only the ordering and loop-guard rules. The agent mutation workflow is:result with an error-specific recovery hint, so the agent stops after reportingthe exact mismatch. Do not hand-edit old unified-diff hunk headers or continue arepair loop.-4. Keep mutations to one path sequential, even when read/search calls are+4. Recovery counters are scoped to the parent turn or the individual delegate+ run. One delegate's failed mutation cannot terminate another delegate or the+ parent. A delegate that exhausts its budget returns a failed, resumable Task+ result while preserving any report text it already produced.+5. Keep mutations to one path sequential, even when read/search calls areissued in parallel.An `EDIT_LINES_UNSEEN` rejection whose reveal was complete is exempt from stepdiff --git a/docs/spec/03-runtime/18-line-anchored-edit-contract.md b/docs/spec/03-runtime/18-line-anchored-edit-contract.mdindex 33c0f7def..0bdaad92b 100644--- a/docs/spec/03-runtime/18-line-anchored-edit-contract.md+++ b/docs/spec/03-runtime/18-line-anchored-edit-contract.md@@ -471,6 +471,11 @@ occurrence, because repeating one of those means the model is guessing.Counting a grace is per code, not per call, so a stale tag followed by unseenlines is two distinct honest failures while the same code twice is not.+Counts and per-code graces belong to the executing parent turn or delegate+run. Parallel delegates working on the same path do not share failures or+successful-write resets. A new parent prompt resets only the parent's recovery+state; still-running delegates retain theirs until they settle.+When the count does reach the limit the tool result carries `terminate: true`and the agent loop stops after that batch. Stopping there must not leave a turnthat merely ends: the runtime finalizes the assistant row with@@ -484,6 +489,11 @@ unseen-line failures continue to direct the model to re-read or use the completereveal. A terminated turn with no message is indistinguishable from a model thatchose to say nothing.+For delegates, exhaustion is reported on the Task result as `failed` with+`MUTATION_RETRY_BUDGET_EXHAUSTED`. Earlier report text is preserved but cannot+turn the failed run into `completed`. The parent and sibling delegates keep+running, and the failed chain remains available through `Task(resume)`.+## 10. Drift recoveryRecovery proves that every anchor still maps to one unchanged region, thendiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a0b4988d8..b7964fd45 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -16927,3 +16927,18 @@ host-created files. The full app's file-preview viewer is covered separately.image model selection and provider configuration remain available.- Coverage: recent-models.test.mjs, recent-model-flow.test.mjs,default-model-picker.test.mjs, and scripts/e2e-composer-model-selection.mjs.+++## Delegate mutation recovery isolation++- Start two Task delegates editing the same file. Delegate A produces text and+ fails three Edits; B fails twice and then completes. A is failed with+ `MUTATION_RETRY_BUDGET_EXHAUSTED`, B completes, and the parent has no mutation+ error. Resume A with a corrected task and verify successful completion.+- Run the same flow with failing shell patch commands. Repeat with one delegate+ to prove that text preceding exhaustion does not become a completed report.+- While a delegate continues, a new parent prompt resets only the parent's+ recovery counters. Both default and explicit delegate permissions retain the+ same isolation.+- Automated provider-boundary flow: `node scripts/e2e-subagent-edit-isolation.mjs`+ with optional `--single` and `--patch`; runtime tests cover parent restart.diff --git a/packages/agent-runtime/src/mutation-recovery.ts b/packages/agent-runtime/src/mutation-recovery.tsnew file mode 100644index 000000000..bfee1c94f--- /dev/null+++ b/packages/agent-runtime/src/mutation-recovery.ts@@ -0,0 +1,67 @@+export const MAX_MUTATION_RECOVERY_FAILURES = 3;+export const BASH_PATCH_FAILURE_KEY = "__bash_patch_command__";+/**+ * Edit failures the line-anchored contract expects and already answers: each+ * one hands back the live tag, or the content of the lines it refused to write+ * blind (spec 18-line-anchored-edit-contract §9.3). One honest retry is the designed response, so each of+ * these codes gets a single free attempt per path before it counts toward the+ * recovery guard. Everything else — malformed ops, bad ranges, a no-op apply —+ * counts immediately, because a second one is the model guessing.+ */+export const RECOVERABLE_MUTATION_ERROR_CODES = new Set([+ "EDIT_TAG_MISMATCH",+ "EDIT_TAG_UNKNOWN",+ "EDIT_LINES_UNSEEN",+]);++export function mutationTerminationAdvice(+ kind: "edit" | "patch-command",+ errorCode?: string,+): string {+ if (kind === "patch-command") {+ return "Use Edit on the specific lines instead of repeating a shell patch command.";+ }+ if (errorCode === "EDIT_PARSE_FAILED") {+ return "Fix the Edit ops syntax and retry with a corrected payload; do not repeat the same ops. A PUT with body rows must end its header with `:`, for example `PUT 48.=48:`.";+ }+ if (errorCode === "EDIT_RANGE_INVALID") {+ return "Correct the Edit range or operation overlap before retrying; re-reading is not needed unless the file changed.";+ }+ if (errorCode === "EDIT_NO_CHANGE") {+ return "Send only changed body rows, or use CUT when the intended result is deletion.";+ }+ if (RECOVERABLE_MUTATION_ERROR_CODES.has(errorCode ?? "")) {+ return errorCode === "EDIT_LINES_UNSEEN"+ ? "Use the revealed lines for one unchanged retry when the reveal is complete; otherwise re-read the range and regenerate the Edit."+ : "Re-read the live file and regenerate the Edit with the fresh tag and narrower anchors.";+ }+ return "Re-read the live file, regenerate a narrower Edit, and avoid repeating the same payload.";+}+export function mutationFailureKey(path: unknown): string {+ return String(path).replaceAll("\\", "/").replace(/^\.\//, "");+}++export function isPatchCommand(command: unknown): boolean {+ if (typeof command !== "string") return false;+ return (+ /(?:^|[;&|]\s*)(?:env\s+|command\s+)?(?:\S+\/)?apply_patch(?:\s|$)/m.test(+ command,+ ) ||+ /\bgit(?:\s+\S+)*\s+apply(?:\s|$)/m.test(command) ||+ /(?:^|[;&|]\s*)(?:env\s+|command\s+)?(?:\S+\/)?patch(?:\s|$)/m.test(+ command,+ )+ );+}++export function mutationTerminationMessage(+ kind: "edit" | "patch-command",+ target: string,+ errorCode?: string,+): string {+ const recovery = mutationTerminationAdvice(kind, errorCode);+ const lastError = errorCode ? ` Last error: ${errorCode}.` : "";+ return kind === "edit"+ ? `Stopped after ${MAX_MUTATION_RECOVERY_FAILURES} failed Edit attempts on ${target}.${lastError} ${recovery}`+ : `Stopped after ${MAX_MUTATION_RECOVERY_FAILURES} failed patch commands.${lastError} ${recovery}`;+}diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 7e366f6c0..8991bd4f2 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2,7 +2,7 @@ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it, vi } from "vitest";-import { type Agent, type AgentMessage } from "@earendil-works/pi-agent-core";+import { type Agent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";import {createAssistantMessageEventStream,getCurrentTools,@@ -782,11 +782,48 @@ describe("DesktopAgentRuntime configuration matching", () => {await runtime.dispose();});+ it.each(["default", "accept-edits"] as const)("keeps %s delegate recovery across a new parent prompt", async (permission) => {+ const host = {+ call: vi.fn(async (method: string) => method === "tools.execute"+ ? { ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: { error: "bad ops" } }+ : undefined),+ };+ const runtime = createRuntime({ host });+ const internal = runtime as unknown as {+ agent: Agent;+ scopeDelegateTools: (tools: AgentTool[], definition: SubagentDefinition, owner: string) => AgentTool[];+ resetRunRecoveryState: () => void;+ pendingMutationTermination?: unknown;+ };+ const edit = internal.agent.state.tools.find((tool) => tool.name === "Edit")!;+ const definition: SubagentDefinition = {+ name: "writer", description: "Edits files", prompt: "Edit the file", source: "user", tools: ["Edit"],+ ...(permission === "accept-edits" ? { permission } : {}),+ };+ const [delegate] = internal.scopeDelegateTools([edit], definition, "writer-run");+ const args = { path: "src/example.ts", tag: "ABCD", ops: "PUT 1.=1:" };+ try {+ expect(await delegate.execute("child-1", args)).not.toHaveProperty("terminate", true);+ expect(await delegate.execute("child-2", args)).not.toHaveProperty("terminate", true);+ expect(await edit.execute("parent-1", args)).not.toHaveProperty("terminate", true);+ internal.resetRunRecoveryState();+ expect(await delegate.execute("child-3", args)).toHaveProperty("terminate", true);+ expect(internal.pendingMutationTermination).toBeUndefined();+ expect(await edit.execute("parent-2", args)).not.toHaveProperty("terminate", true);+ expect(await edit.execute("parent-3", args)).not.toHaveProperty("terminate", true);+ expect(await edit.execute("parent-4", args)).toHaveProperty("terminate", true);+ } finally {+ await runtime.dispose();+ }+ });+it("clears the mutation strike once an edit on that path lands", async () => {const results = [{ ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} },{ ok: true, isError: false, content: { tag: "C3D4" } },{ ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} },+ { ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} },+ { ok: false, isError: true, errorCode: "EDIT_PARSE_FAILED", content: {} },];let editCall = 0;const host = {@@ -808,7 +845,8 @@ describe("DesktopAgentRuntime configuration matching", () => {// Without the reset this failure would be strike three and end the turn.const afterSuccess = await edit.execute("edit-3", args);expect(afterSuccess.terminate).toBeUndefined();- expect((runtime as any).mutationFailureCounts.get("src/example.ts")).toBe(1);+ expect((await edit.execute("edit-4", args)).terminate).toBeUndefined();+ expect((await edit.execute("edit-5", args)).terminate).toBe(true);await runtime.dispose();});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex dae46d927..c45297d42 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1,3 +1,8 @@+import {+ MAX_MUTATION_RECOVERY_FAILURES, BASH_PATCH_FAILURE_KEY,+ RECOVERABLE_MUTATION_ERROR_CODES, mutationFailureKey, isPatchCommand,+ mutationTerminationAdvice, mutationTerminationMessage,+} from "./mutation-recovery.js";import { resolveMcpToolSelection } from "./mcp-tool-selection.js";import { TOOL_ACTIVATION_SECTION, toolDeclarationPolicy, toolActivationSection, restoredToolActivation, syncToolActivation, type ToolDeclarationPolicy } from "./fixed-tool-declarations.js";import { orderSystemRows, SystemTranscriptJournal } from "./system-transcript-journal.js";@@ -201,6 +206,7 @@ import {SUBAGENT_TOOL_NAME,SUBAGENT_WAIT_TOOL_NAME,type SubagentRunResult,+ type SubagentToolOutcome,} from "./subagent.js";import {composeModeSystemPrompt,@@ -402,45 +408,6 @@ export function sessionReferenceBlock(attachment: RuntimePromptAttachment): stri// pi-ai's adapter retry is disabled here so setup and mid-stream 429s share// one runtime-owned budget instead of multiplying nested retry loops.const PROVIDER_REQUEST_MAX_RETRIES = 0;-const MAX_MUTATION_RECOVERY_FAILURES = 3;-const BASH_PATCH_FAILURE_KEY = "__bash_patch_command__";-/**- * Edit failures the line-anchored contract expects and already answers: each- * one hands back the live tag, or the content of the lines it refused to write- * blind (spec 18-line-anchored-edit-contract §9.3). One honest retry is the designed response, so each of- * these codes gets a single free attempt per path before it counts toward the- * recovery guard. Everything else — malformed ops, bad ranges, a no-op apply —- * counts immediately, because a second one is the model guessing.- */-const RECOVERABLE_MUTATION_ERROR_CODES = new Set([- "EDIT_TAG_MISMATCH",- "EDIT_TAG_UNKNOWN",- "EDIT_LINES_UNSEEN",-]);--function mutationTerminationAdvice(- kind: "edit" | "patch-command",- errorCode?: string,-): string {- if (kind === "patch-command") {- return "Use Edit on the specific lines instead of repeating a shell patch command.";- }- if (errorCode === "EDIT_PARSE_FAILED") {- return "Fix the Edit ops syntax and retry with a corrected payload; do not repeat the same ops. A PUT with body rows must end its header with `:`, for example `PUT 48.=48:`.";- }- if (errorCode === "EDIT_RANGE_INVALID") {- return "Correct the Edit range or operation overlap before retrying; re-reading is not needed unless the file changed.";- }- if (errorCode === "EDIT_NO_CHANGE") {- return "Send only changed body rows, or use CUT when the intended result is deletion.";- }- if (RECOVERABLE_MUTATION_ERROR_CODES.has(errorCode ?? "")) {- return errorCode === "EDIT_LINES_UNSEEN"- ? "Use the revealed lines for one unchanged retry when the reveal is complete; otherwise re-read the range and regenerate the Edit."- : "Re-read the live file and regenerate the Edit with the fresh tag and narrower anchors.";- }- return "Re-read the live file, regenerate a narrower Edit, and avoid repeating the same payload.";-}export const TOOL_SEARCH_NAME = "ToolSearch";/** Stands in for a persisted tool row that never recorded a result. */const MISSING_TOOL_RESULT_PLACEHOLDER = "[no tool result recorded]";@@ -1128,23 +1095,6 @@ function boundedText(value: string, maxChars: number): string {return `${text.slice(0, headChars)}${marker}${text.slice(-tailChars)}`;}-function mutationFailureKey(path: unknown): string {- return String(path).replaceAll("\\", "/").replace(/^\.\//, "");-}--function isPatchCommand(command: unknown): boolean {- if (typeof command !== "string") return false;- return (- /(?:^|[;&|]\s*)(?:env\s+|command\s+)?(?:\S+\/)?apply_patch(?:\s|$)/m.test(- command,- ) ||- /\bgit(?:\s+\S+)*\s+apply(?:\s|$)/m.test(command) ||- /(?:^|[;&|]\s*)(?:env\s+|command\s+)?(?:\S+\/)?patch(?:\s|$)/m.test(- command,- )- );-}-type CheckpointPersistResult = "persisted" | "oversized" | "failed";type CompactionRetentionMode = "active_turn" | "completed_turn";@@ -1885,6 +1835,8 @@ export class DesktopAgentRuntime {private mutationFailureCounts = new Map<string, number>();/** `<failure key> <error code>` pairs that already spent their free retry. */private mutationRecoveryGraces = new Set<string>();+ /** Tool-call ownership keeps concurrent delegates' mutation budgets apart. */+ private mutationOwners = new Map<string, string>();/** Why the recovery guard ended the turn, pending its visible error row. */private pendingMutationTermination?: {kind: "edit" | "patch-command";@@ -1892,6 +1844,7 @@ export class DesktopAgentRuntime {lastErrorCode?: string;};private terminatingToolCalls = new Set<string>();+ private delegateMutationTerminations = new Map<string, { code: string; message: string }>();private fullEntries: MessageEntry[];private readonly systemJournal = new SystemTranscriptJournal();private composedSections: Record<string, string> = {};@@ -2399,13 +2352,16 @@ Do not invent objections or turn speculative risks into blockers. Stop when the*/private resolveOwnToolOutcome({toolCall,- }: AfterToolCallContext): AfterToolCallResult | undefined {+ }: AfterToolCallContext): SubagentToolOutcome | undefined {const terminate = this.terminatingToolCalls.delete(toolCall.id);const failed = this.failedHostToolCalls.delete(toolCall.id);+ const error = this.delegateMutationTerminations.get(toolCall.id);+ this.delegateMutationTerminations.delete(toolCall.id);if (!failed) return terminate ? { terminate: true } : undefined;return {isError: true,...(terminate ? { terminate: true } : {}),+ ...(error ? { error } : {}),};}@@ -3441,11 +3397,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetoolName === "Bash" &&failedToolExecution &&isPatchCommand(recordParams?.command);- const failureKey = failedEditPath+ const mutationOwner = this.mutationOwners.get(toolCallId);+ const targetKey = failedEditPath? failedEditPath: failedPatchCommand? BASH_PATCH_FAILURE_KEY: undefined;+ const failureKey = targetKey+ ? `${mutationOwner ?? "parent"}\0${targetKey}`+ : undefined;const mutationFailureKind = failedEditPath? "edit": failedPatchCommand@@ -3480,12 +3440,15 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// progress, so it clears that path's history instead of leaving one// stale strike to terminate the next unrelated failure.if (!failureKey && result.ok) {- const succeededKey =+ const succeededTarget =PATH_MUTATING_TOOLS.has(toolName) && typeof recordParams?.path === "string"? mutationFailureKey(recordParams.path): toolName === "Bash" && isPatchCommand(recordParams?.command)? BASH_PATCH_FAILURE_KEY: undefined;+ const succeededKey = succeededTarget+ ? `${mutationOwner ?? "parent"}\0${succeededTarget}`+ : undefined;if (succeededKey !== undefined) {this.mutationFailureCounts.delete(succeededKey);for (const key of this.mutationRecoveryGraces) {@@ -3500,13 +3463,25 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// The loop stops after this batch, so nothing downstream would// explain why. Hold the reason for agent_end to turn into a visible// row instead of a turn that just ends.- this.pendingMutationTermination = {- kind: mutationFailureKind ?? "edit",- target: failedEditPath ?? "the patch command",- ...(typeof result.errorCode === "string"- ? { lastErrorCode: result.errorCode }- : {}),- };+ if (!mutationOwner) {+ this.pendingMutationTermination = {+ kind: mutationFailureKind ?? "edit",+ target: failedEditPath ?? "the patch command",+ ...(typeof result.errorCode === "string"+ ? { lastErrorCode: result.errorCode }+ : {}),+ };+ } else {+ const kind = mutationFailureKind ?? "edit";+ this.delegateMutationTerminations.set(toolCallId, {+ code: "MUTATION_RETRY_BUDGET_EXHAUSTED",+ message: mutationTerminationMessage(+ kind,+ failedEditPath ?? "the patch command",+ result.errorCode,+ ),+ });+ }}const rawContent = result.content;const imageBlocks: Array<{ type: "image"; data: string; mimeType: string }> = [];@@ -4686,7 +4661,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.delegations.set(delegationId, record);let subagentRun: SubagentRun;try {- const scopedTools = this.scopeDelegateTools(tools, definition);+ const scopedTools = this.scopeDelegateTools(tools, definition, delegationId);subagentRun = new SubagentRun({definition,sessionId: this.sessionId,@@ -4803,23 +4778,25 @@ Do not invent objections or turn speculative risks into blockers. Stop when the};}- /** Wrap a delegate's tools so each call carries the definition's permission- * scope to host-core (ADR 0089). Keyed by tool call id, so concurrent- * delegates with different scopes never cross over. */+ /** Wrap a delegate's tools with its permission and mutation-recovery scope. */private scopeDelegateTools(tools: AgentTool[],definition: SubagentDefinition,+ mutationOwner: string,): AgentTool[] {const scope = definition.permission ?? DEFAULT_SUBAGENT_PERMISSION;- if (scope === DEFAULT_SUBAGENT_PERMISSION) return tools;return tools.map((tool) => ({...tool,execute: async (toolCallId, args, signal, onUpdate) => {- this.delegatePermissionScopes.set(toolCallId, scope);+ this.mutationOwners.set(toolCallId, mutationOwner);+ if (scope !== DEFAULT_SUBAGENT_PERMISSION) {+ this.delegatePermissionScopes.set(toolCallId, scope);+ }try {return await tool.execute(toolCallId, args, signal, onUpdate);} finally {this.delegatePermissionScopes.delete(toolCallId);+ this.mutationOwners.delete(toolCallId);}},}));@@ -4858,6 +4835,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// its calls left behind rather than pinning those arguments for the session.for (const toolCallId of record.pendingToolCallIds ?? []) {this.delegateToolCalls.delete(toolCallId);+ this.delegateMutationTerminations.delete(toolCallId);}record.pendingToolCallIds = undefined;this.publishDelegationSettlement(record);@@ -4866,6 +4844,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the`[agent-runtime] delegation settlement side effect failed (session=${this.sessionId} delegation=${record.delegationId})\n`,);} finally {+ this.clearMutationRecovery(record.delegationId);this.refreshDelegationWait();this.refreshResumablePrompt();this.pruneFinishedDelegations();@@ -6073,6 +6052,16 @@ Do not invent objections or turn speculative risks into blockers. Stop when the);}+ private clearMutationRecovery(owner: string): void {+ const prefix = `${owner}\0`;+ for (const key of this.mutationFailureCounts.keys()) {+ if (key.startsWith(prefix)) this.mutationFailureCounts.delete(key);+ }+ for (const key of this.mutationRecoveryGraces) {+ if (key.startsWith(prefix)) this.mutationRecoveryGraces.delete(key);+ }+ }+/*** Clear the per-run recovery state that every entry point driving the agent* loop must start from. Each recovery arms itself mid-run by setting a@@ -6105,10 +6094,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.suppressProgressTurnRunEnd = false;this.providerRetryAbort?.abort();this.providerRetryAbort = undefined;- this.mutationFailureCounts.clear();- this.mutationRecoveryGraces.clear();+ this.clearMutationRecovery("parent");this.pendingMutationTermination = undefined;- this.terminatingToolCalls.clear();this.turnHadError = false;}@@ -8247,13 +8234,11 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetermination.kind,termination.lastErrorCode,);- const lastError = termination.lastErrorCode- ? ` Last error: ${termination.lastErrorCode}.`- : "";- const message =- termination.kind === "edit"- ? `Stopped after ${MAX_MUTATION_RECOVERY_FAILURES} failed Edit attempts on ${termination.target}.${lastError} ${recovery}`- : `Stopped after ${MAX_MUTATION_RECOVERY_FAILURES} failed patch commands.${lastError} ${recovery}`;+ const message = mutationTerminationMessage(+ termination.kind,+ termination.target,+ termination.lastErrorCode,+ );const error = {code: "MUTATION_RETRY_BUDGET_EXHAUSTED",message,@@ -8806,6 +8791,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.failedHostToolCalls.clear();this.mutationFailureCounts.clear();this.mutationRecoveryGraces.clear();+ this.mutationOwners.clear();+ this.delegateMutationTerminations.clear();this.pendingMutationTermination = undefined;this.terminatingToolCalls.clear();this.delegateToolCalls.clear();diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.tsindex cb2758698..910dd140a 100644--- a/packages/agent-runtime/src/subagent.ts+++ b/packages/agent-runtime/src/subagent.ts@@ -127,6 +127,7 @@ export type SubagentRunResult = {export type SubagentToolOutcome = {isError?: boolean;terminate?: boolean;+ error?: { code: string; message: string };};export type SubagentRunOptions = {@@ -245,6 +246,7 @@ export class SubagentRun {private toolCalls = 0;private usage?: MessageUsage;private streamError?: { code: string; message: string };+ private mutationTermination?: { code: string; message: string };/** Set when a settled message reads as a cancel — `stopReason: "aborted"`, or* a local marker whose preserved cause name is `AbortError`. pi-ai can wrap* an abort that fired before the parent signal flipped, so this is the only@@ -385,6 +387,9 @@ export class SubagentRun {if (this.turnAborted) {return this.result("aborted", "The delegated task was aborted.");}+ if (this.mutationTermination) {+ return this.result("failed", this.lastReportText, this.mutationTermination);+ }if (caughtError) {if (caughtError.code === "TURN_ABORTED") {return this.result("aborted", "The delegated task was aborted.");@@ -741,6 +746,7 @@ export class SubagentRun {const parent = this.opts.resolveToolOutcome?.(context);const terminate = parent?.terminate === true;if (!parent?.isError && !terminate) return undefined;+ if (terminate && parent?.error) this.mutationTermination = parent.error;return {...(parent?.isError ? { isError: true } : {}),...(terminate ? { terminate: true } : {}),diff --git a/scripts/e2e-subagent-edit-isolation.mjs b/scripts/e2e-subagent-edit-isolation.mjsnew file mode 100644index 000000000..6202e539d--- /dev/null+++ b/scripts/e2e-subagent-edit-isolation.mjs@@ -0,0 +1,149 @@+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { mkdirSync, mkdtempSync } from "node:fs";+import { join } from "node:path";+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";++// Real Runtime -> pi Agent -> SubagentRun. Only the provider and host tool+// boundary are deterministic fixtures; no production model or Desktop state.+let sequence = 0;+const labels = process.argv.includes("--single") ? ["A"] : ["A", "B"];+const patchCommand = process.argv.includes("--patch");+const toolName = patchCommand ? "Bash" : "Edit";+const aStopped = Promise.withResolvers();+const completed = new Map([...labels.map((label) => `task_${label}`), "resume_A"]+ .map((id) => [id, Promise.withResolvers()]));+async function bounded(promise, label) {+ let timer;+ try {+ return await Promise.race([promise, new Promise((_, reject) => {+ timer = setTimeout(() => reject(new Error(`Timed out: ${label}`)), 15_000);+ })]);+ } finally {+ clearTimeout(timer);+ }+}+const state = { editCalls: new Map(), parentErrors: [], taskResults: new Map(), taskIds: new Map(), errors: [] };+const reply = (res, model, calls, text = "Finished") => {+ res.writeHead(200, { "content-type": "text/event-stream" });+ const chunk = (delta, finish_reason) => res.write(`data: ${JSON.stringify({+ id: `fixture-${++sequence}`, object: "chat.completion.chunk", created: 1, model,+ choices: [{ index: 0, delta, finish_reason }],+ })}\n\n`);+ chunk(calls ? { role: "assistant", ...(text ? { content: text } : {}), tool_calls: calls.map((call, index) => ({+ index, id: call.id, type: "function", function: { name: call.name, arguments: JSON.stringify(call.args) },+ })) } : { role: "assistant", content: text }, null);+ chunk({}, calls ? "tool_calls" : "stop");+ res.end("data: [DONE]\n\n");+};+const labelFor = (body) => JSON.stringify(body.messages.find((message) => message.role === "user")?.content).includes("Task A") ? "A" : "B";+const server = createServer(async (req, res) => {+ try {+ let raw = "";+ for await (const part of req) raw += part;+ const body = JSON.parse(raw);+ if (body.model === "worker") {+ const latestUser = JSON.stringify(body.messages.filter((message) => message.role === "user").at(-1)?.content);+ if (latestUser.includes("Continue after the stopped edit")) {+ reply(res, body.model, null, "Resumed and completed successfully.");+ return;+ }+ const label = labelFor(body);+ const count = state.editCalls.get(label) ?? 0;+ if (label === "B" && count >= 2) {+ await bounded(aStopped.promise, "delegate A's third Edit");+ reply(res, body.model, null, "Delegate B continued after A stopped.");+ } else {+ state.editCalls.set(label, count + 1);+ reply(res, body.model, [{+ id: `edit_${label}_${count + 1}`, name: toolName,+ args: patchCommand ? { command: "git apply fixture.patch" }+ : { path: "fixture.go", tag: "ABCD", ops: "PUT 1.=1:" },+ }], count === 0 ? "Preparing to edit the shared file." : "");+ }+ return;+ }+ const latestUser = JSON.stringify(body.messages.filter((message) => message.role === "user").at(-1)?.content);+ if (latestUser.includes("Resume Task A") && !state.resumeSent) {+ state.resumeSent = true;+ reply(res, body.model, [{ id: "resume_A", name: "Task",+ args: { agent: "writer", task: "Continue after the stopped edit", resume: state.taskIds.get("task_A") } }]);+ } else if (!state.started) {+ state.started = true;+ reply(res, body.model, labels.map((label) => ({+ id: `task_${label}`, name: "Task", args: { agent: "writer", task: `Task ${label}` },+ })));+ } else reply(res, body.model, null, "Both delegates finished.");+ } catch (error) {+ state.errors.push(error);+ if (!res.headersSent) res.writeHead(500);+ res.end(String(error));+ }+});+await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));+const baseUrl = `http://127.0.0.1:${server.address().port}/v1`;+const provider = (modelId) => ({ id: "fixture", name: "Fixture", modelId, baseUrl,+ apiKey: "", authKind: "none", apiStyle: "openai-chat", supportsReasoning: false,+ supportedThinkingLevels: ["off"] });+const artifactRoot = join(process.cwd(), ".artifacts");+mkdirSync(artifactRoot, { recursive: true });+const projectPath = mkdtempSync(join(artifactRoot, "subagent-edit-isolation-"));+const runtime = new DesktopAgentRuntime({+ sessionId: "fixture-edit-isolation", mode: "agent", provider: provider("parent"), thinkingLevel: "off", projectPath,+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ subagents: [{ name: "writer", description: "Fixture writer", prompt: "Edit the task's file",+ tools: [toolName], source: "user", permission: "accept-edits", model: { providerId: "fixture", modelId: "worker" } }],+ subagentProviders: { "fixture/worker": provider("worker") },+ host: { onNotification: () => () => {}, call: async (method, params) => {+ if (method === "project.instructions.resolve") return { entries: [] };+ if (method === "tools.execute") {+ assert.equal(params.toolName, toolName);+ return { ok: false, isError: true, errorCode: patchCommand ? "TOOL_FAILED" : "EDIT_PARSE_FAILED", content: { error: "malformed mutation" } };+ }+ return {};+ } },+ onEvent: ({ event, parentToolCallId }) => {+ if (parentToolCallId) {+ if (event.type === "tool_end" && event.toolCallId === "edit_A_3" && event.result?.terminate) {+ state.aTerminated = true;+ aStopped.resolve();+ }+ return;+ }+ if (event.type === "error") state.parentErrors.push(event.error);+ if (event.type === "tool_end" && event.result?.details?.delegationId && event.toolCallId.startsWith("task_")) {+ state.taskIds.set(event.toolCallId, event.result.details.delegationId);+ }+ if (event.type === "message_end" && event.message?.toolName === "Task" && event.message.toolResult?.details?.status !== "running") {+ state.taskResults.set(event.message.toolCallId, event.message.toolResult.details);+ completed.get(event.message.toolCallId)?.resolve();+ }+ },+});+try {+ await bounded(runtime.prompt(`Start ${labels.map((label) => `Task ${label}`).join(" and ")}`), "parent turn");+ await bounded(Promise.all(labels.map((label) => completed.get(`task_${label}`).promise)), "delegate results");+ console.log(JSON.stringify({ phase: "initial", editCalls: Object.fromEntries(state.editCalls),+ results: Object.fromEntries([...state.taskResults].map(([id, result]) => [id, { status: result.status, error: result.error }])),+ parentErrors: state.parentErrors.map((error) => error.code) }));+ assert.equal(state.editCalls.get("A"), 3, "delegate A reaches its own third failure");+ assert.equal(state.aTerminated, true);+ assert.equal(state.taskResults.get("task_A")?.status, "failed", "delegate A reports its exhausted budget as a failure");+ assert.equal(state.taskResults.get("task_A")?.error?.code, "MUTATION_RETRY_BUDGET_EXHAUSTED");+ if (labels.includes("B")) {+ assert.equal(state.editCalls.get("B"), 2, "delegate B remains below its own limit");+ assert.equal(state.taskResults.get("task_B")?.status, "completed", "delegate B completes after A stops");+ }+ assert.equal(state.parentErrors.some((error) => error.code === "MUTATION_RETRY_BUDGET_EXHAUSTED"), false);+ assert.equal(state.taskIds.has("task_A"), true);+ await bounded(runtime.prompt("Resume Task A"), "parent resume turn");+ await bounded(completed.get("resume_A").promise, "resumed delegate result");+ assert.equal(state.taskResults.get("resume_A")?.status, "completed");+ assert.deepEqual(state.errors, []);+ console.log(JSON.stringify({ ok: true, editCalls: Object.fromEntries(state.editCalls), parentMutationErrors: 0, resumed: "completed" }));+} finally {+ await runtime.dispose();+ server.closeAllConnections();+ await new Promise((resolve) => server.close(resolve));+ // Keep the isolated fixture directory for post-run inspection.+}