Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
perf(agent-runtime): parallelize independent read-only tool calls
cauliflowere9f1ca7c1917
diff --git a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md b/docs/adr/0062-bounded-subagents-behind-a-task-tool.mdindex 32b8b9de0..cc34ecfd1 100644--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md@@ -85,6 +85,11 @@ must never silently spend the expensive one.### 4. Delegation is one Agent-mode tool, and parallel by construction+Proposed amendment: [parallel read batches](parallel-read-batches.md) allows+Read/Glob/Grep candidates, isolates delegate path-instruction preparation, and+keeps Task mixed with those reads behind the delegate completion boundary. The+original only-Task batch policy below is historical.+The `Task` tool takes `agent`, `task` and an optional short `description`. Thecatalog of available delegates rides in the tool description rather than thesystem prompt, because the two change together.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 4452e1b44..b457aae14 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -28,6 +28,7 @@ Each ADR includes:| s3-only-configuration-backup-sync | [S3-only encrypted configuration backup and synchronization](s3-only-configuration-backup-sync.md) | Accepted; supersedes WebDAV decisions in 0300 / 0301 || remote-provider-import | [Explicit provider import into a running remote Host](remote-provider-import.md) | Accepted for the experimental SSH MVP || remote-project-home-workflow | [Remote projects in the shared Chat home workflow](remote-project-home-workflow.md) | Accepted |+| parallel-read-batches | [Ordered preparation and parallel read batches](parallel-read-batches.md) | Proposed || composer-mcp-invocations | [Composer MCP Invocations](composer-mcp-invocations.md) | Accepted || chronological-system-transcript | [Preserve chronological model system state](chronological-system-transcript.md) | Accepted || mcp-tool-approval-risk | [User MCP tools keep the normal approval path](mcp-tool-approval-risk.md) | Accepted |diff --git a/docs/adr/parallel-read-batches.md b/docs/adr/parallel-read-batches.mdnew file mode 100644index 000000000..66762cb4f--- /dev/null+++ b/docs/adr/parallel-read-batches.md@@ -0,0 +1,55 @@+# ADR: Ordered preparation and parallel read batches++- Status: Proposed+- Date: 2026-10-12++## Context++The runtime globally permits parallel execution but overrides every tool except+Task to sequential. pi consequently serializes independent Read/Glob/Grep calls.+Simply changing those flags is unsafe: file preflight currently changes the+parent prompt, including when invoked through delegated tool closures.++## Decision++Use pi-agent-core's ordered preparation / concurrent execution /+ordered result submission contract. Centralize the Read/Glob/Grep candidate+allowlist and the batch rule that keeps Task mixed with those reads sequential;+unknown tools default to sequential. Keep existing Host permission and capacity+ownership. Do not introduce another batch executor.++Move parent file preflight after mode and extension checks in beforeToolCall.+Use a weak argument-identity map to bind canonical parameters to the validated+call; unused records are collectible after cancellation or rejection. Direct+invocations still run preflight. Delegate preparation has an explicit prompt+sink, and AsyncLocalStorage preserves that sink for direct delegated executions+without sharing mutable current-agent state. Delegate prompt updates use the+same chronological system transcript sections as the parent.++## Consequences++Independent reads/searches overlap without changing writes or Bash policy.+Task-only batches retain fan-out, while a mixed Task/read batch is kept+sequential: a read ordered before `Task` finishes before the delegate starts, and+a read ordered after a writable `Task` in the same batch waits for that delegate+to settle before dispatching to Host, while `Task` itself still returns its ADR+0089 started notice immediately. Per-path shared-read / exclusive-write+locking in `PathMutex` also prevents a parent `Read` from overlapping an+in-flight shared-workspace delegate `Write` or `Edit` on the same file.+Regression tests pin both model orders (read then `Task`, and `Task` then read),+Task-only fan-out, read-only batches, same-path `Edit` vs `Read` serialization,+and a failed delegate that still lets the parent read proceed. Delegate path+rules now follow their own ordered calls instead of mutating the parent.+Instruction resolution claims remain immutable, per-prompt cached promises;+shared caching does not share the prompt mutation sink. Source-order results+still come from pi.++Existing running file RPCs drain on Stop; finer cancellation and Host-owned+file resource leases belong to separate changes.++## Alternatives++- Parallelize execute while retaining prompt updates there: completion order+ would select sibling rules and delegates would still overwrite parent state.+- Serialize all reads behind a prompt mutex: would preserve the bottleneck.+- Fork pi's batch executor: duplicates an already-supported contract.diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 428577b23..9372627f8 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1749,13 +1749,20 @@ merging to the user, and how to resolve a merge conflict).| tools | sequential by default || `Task` calls in one assistant message | parallel; 10 running delegates per session (ADR 0089) |-Tool concurrency is expressed through pi execution modes: every catalog tool is-`sequential` and `Task` alone is `parallel`, and pi runs a batch sequentially as-soon as it contains one sequential tool. So an all-`Task` batch is the only batch-that fans out, and every other ordering guarantee is unchanged. Delegates issue+Tool concurrency is expressed through pi execution modes. In the parallel read batches,+`Read`, `Glob` and `Grep` are parallel candidates; all other catalog tools remain+sequential. Task-only batches retain parallel fan-out, while a batch that mixes+`Task` with any of those file-reading tools is kept sequential: a read before+`Task` finishes before the delegate starts, and a read after a writable `Task`+waits for that delegate to settle before dispatching to Host, while `Task` stays+non-blocking inside that batch too (ADR 0089). Parent and delegate path+instruction updates happen during ordered preparation before parallel execution,+and mutate only their own prompt.+Delegates issuehost calls independently, and host-core's one-mutation-per-session admissionkeeps writes from tearing but leaves two same-path mutations unordered, so the-sidecar serializes `Write`/`Edit` calls that target the same normalized path+sidecar serializes `Write`/`Edit` calls (and coordinates `Read` against in-flight+`Write`/`Edit` on the same workspace path) that target the same normalized pathbefore they reach the host; calls on different paths never wait on each other.This is what keeps the per-path edit-recovery rules of`03-tools-and-permissions.md` §4d meaningful under fan-out.diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 133457018..2e222850c 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -5,6 +5,40 @@## 0. Frozen policy summary+### Parallel read batches++Read, Glob and Grep are the first parallel batch candidates. Task-only batches+retain their existing parallel fan-out; a batch that mixes Task with Read, Glob+or Grep is kept sequential: a read ordered before Task finishes before the+delegate starts, and a read ordered after a writable Task waits for that+delegate to settle before dispatching to Host. Task keeps its ADR 0089 contract+inside that batch: it reports a started delegation and the parent converges with+TaskWait. Any other sequential tool (including Write, Edit, Bash and unknown+tools) makes its entire assistant batch sequential. This is a per-agent batch+rule, not application-wide exclusion or a Shell safety lock. Only the selected+builtin executor receives this allowlist and native path preparation. Same-name+dynamic tools remain sequential. Delegates retain their startup catalog's policy+and provenance across later parent catalog rebuilds.++The pinned pi-agent-core prepares all parallel calls in source order before+launching their execution bodies. Path instruction resolution and prompt updates+occur during that preparation, after existing parent mode/extension checks.+Execution consumes the same normalized arguments. Direct internal invocations+retain preflight. Child preflight updates the child's system transcript only;+it never replaces parent instructions. Sibling instruction chains replace one+another according to preparation order, regardless of completion order.++Permissions, Host capacities, mutation recovery, Hashline validation and tool+result IDs remain authoritative. Completion events may arrive out of order;+model tool results remain in source order. Alongside the mixed Task/read batch+barrier, `PathMutex` coordinates shared reads against exclusive `Write`/`Edit`+calls on the same normalized workspace path so a parent `Read` does not overlap+an in-flight delegate mutation on that file. Stop skips unstarted calls; already+started file RPCs drain through their existing Host lifecycle. Host file+cancellation and resource coordination are separate follow-up work.++See [the ADR](../../adr/parallel-read-batches.md).+| Topic | Decision ||---|---|| Default mode | Agent |diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 1e8b666fd..88c1e707e 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -74,6 +74,45 @@compaction, and terminal Task snapshots through the real React rendering.The headless command does not replace the rendered Electron check above.+### E2E-TOOLS-parallel-read-batches: ordered preparation and parallel reads++- Isolate data/project paths; never run against production profiles.+- A local provider fixture emits two Read calls. Gate real tool-execution+ entrypoints until both enter, release them in reverse order, then inspect the+ follow-up model request: results must retain source toolCallId order and final+ sibling rules must follow preparation order. Repeat with a delegated reader+ and verify parent instructions and permission scope are isolated.+- Add Bash or Edit to the batch: all tools must execute sequentially. Stop+ before execution must skip unstarted calls; running file calls must drain.+- Add Task with a delegate that edits a fixture file alongside a parent Read;+ the batch must stay sequential, Task keeps reporting a started delegation+ (ADR 0089), and the parent Read must not enter Host until the writable+ shared-workspace delegate settles its mutation. Task-only batches must still+ fan out.+- Automated coverage: runtime.test.ts uses the production Runtime and pi loop+ with deterministic Host response barriers, including mixed Bash/Write/Edit+ batches and Stop, plus the mixed Task/read regression in both model orders:+ the Task result stays a started notice, the parent read waits for the writable+ shared-workspace delegate's mutation to settle before entering Host, and a+ failed delegate still releases the batch. `scripts/e2e-task-read-batches.mjs`+ runs the same contract end to end with a real delegate loop: it asserts the+ Host dispatch order `write:start`, `write:end`, `read:start`, `read:end`, that+ the parent reads the written content, and that the Task tool result stays a+ background acknowledgement. subagent.test.ts checks conservative policy+ inheritance.+- Run `node scripts/e2e-parallel-read-batches.mjs` after building agent-runtime,+ shared and host-core. Set `PI_DESKTOP_HOST_BIN` when reusing a shared target.+ It uses a local HTTP provider, real parent/delegate loops and a real Host in+ temporary directories. A gated response proves overlapping Read dispatch;+ actual Read/Glob/Grep results, source-order model results and parent prompt+ isolation are checked. This does not measure blocking filesystem-body overlap,+ production throughput or Electron UI behavior. UI-only project-edit E2E is+ not evidence for agent Edit scheduling.+- Run `node scripts/e2e-task-read-batches.mjs` under the same build and+ `PI_DESKTOP_HOST_BIN` preconditions. Against the pre-fix implementation it+ fails with `read:start` before `write:start`, which is the regression the+ maintainer asked for.+### E2E-STORAGE-custom-location-and-maintenance- **Preconditions:** Dedicated request worktree, current remote-main base, shareddiff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 4811a85ba..c3a5bd2a9 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -1206,10 +1206,12 @@ sidecar 从不直接读取工作区指令。改变的根链| 工具 | 默认情况下是顺序的 || `Task` 通过一条助理消息进行呼叫 | 并行,每会话 10 个运行委托 (ADR 0089) |-工具并发性通过 pi 执行模式来表示:每个目录工具都是-`sequential` 和 `Task` 单独为 `parallel`,并且 pi 按顺序运行批处理-一旦它包含一个顺序工具。因此,全 `Task` 批次是唯一的批次-扇出,并且所有其他订购保证均不变。代表问题+工具并发性通过 pi 执行模式来表示:Read、Glob、Grep 是并行候选,+仅含 Task 的批次保留并行扇出;Task 与这些读取工具混合时整批保持顺序,+且位于可写 Task 之后的同批父代理读取会等待该委托落定后再派发,而该批次里的+Task 自身仍然立即返回启动通知(ADR 0089),父代理用 TaskWait 收敛。其他工具仍为+`sequential`,并且 pi 按顺序运行包含顺序工具的批处理。这样+全 Task 批次仍可扇出,并且所有其他订购保证均不变。代表问题主机独立调用,以及 host-core 的每次会话一次突变准入防止写入撕裂,但留下两个无序的相同路径突变,因此sidecar 序列化针对相同标准化路径的 IPC/`sequential` 调用diff --git a/packages/agent-runtime/src/path-lock.test.ts b/packages/agent-runtime/src/path-lock.test.tsindex c627935a2..ff64621f0 100644--- a/packages/agent-runtime/src/path-lock.test.ts+++ b/packages/agent-runtime/src/path-lock.test.ts@@ -83,4 +83,80 @@ describe("PathMutex", () => {held.resolve();await expect(first).resolves.toBe(1);});++ it("allows concurrent reads on the same path while serializing reads against writes", async () => {+ const mutex = new PathMutex();+ const order: string[] = [];+ const r1Gate = deferred();+ const r2Gate = deferred();+ const wGate = deferred();+ const r3Gate = deferred();++ const r1 = mutex.read("src/app.ts", async () => {+ order.push("r1:start");+ await r1Gate.promise;+ order.push("r1:end");+ });+ const r2 = mutex.read("./src/App.ts", async () => {+ order.push("r2:start");+ await r2Gate.promise;+ order.push("r2:end");+ });+ const w = mutex.run("src/app.ts", async () => {+ order.push("w:start");+ await wGate.promise;+ order.push("w:end");+ });+ const r3 = mutex.read("src/app.ts", async () => {+ order.push("r3:start");+ await r3Gate.promise;+ order.push("r3:end");+ });+ const r4 = mutex.read("src/app.ts", async () => {+ order.push("r4:start");+ await r3Gate.promise;+ order.push("r4:end");+ });++ // `r1` and `r2` overlap; `w` waits for both; `r3` and `r4` wait for `w`.+ expect(order).toEqual(["r1:start", "r2:start"]);+ r1Gate.resolve();+ await r1;+ expect(order).toEqual(["r1:start", "r2:start", "r1:end"]);++ r2Gate.resolve();+ await r2;+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(order).toEqual(["r1:start", "r2:start", "r1:end", "r2:end", "w:start"]);++ wGate.resolve();+ await w;+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(order).toEqual([+ "r1:start",+ "r2:start",+ "r1:end",+ "r2:end",+ "w:start",+ "w:end",+ "r3:start",+ "r4:start",+ ]);++ r3Gate.resolve();+ await Promise.all([r3, r4]);+ expect(order).toEqual([+ "r1:start",+ "r2:start",+ "r1:end",+ "r2:end",+ "w:start",+ "w:end",+ "r3:start",+ "r4:start",+ "r3:end",+ "r4:end",+ ]);+ expect(mutex.busy).toBe(false);+ });});diff --git a/packages/agent-runtime/src/path-lock.ts b/packages/agent-runtime/src/path-lock.tsindex b50c44364..9a1c9930b 100644--- a/packages/agent-runtime/src/path-lock.ts+++ b/packages/agent-runtime/src/path-lock.ts@@ -24,16 +24,24 @@ export function normalizeLockPath(path: unknown): string {.toLowerCase();}+type PathQueueEntry = {+ /** Settled when the latest queued or running exclusive (`run`) holder finishes. */+ writeTail?: Promise<void>;+ /** Settled when every queued or running holder (`run` or `read`) finishes. */+ allTail: Promise<void>;+ holders: number;+};+export class PathMutex {- /** Per path: the tail of the queue, and how many holders are still in it. */- private queues = new Map<string, { tail: Promise<void>; holders: number }>();+ /** Per path: the active queue tails and how many holders are still in it. */+ private queues = new Map<string, PathQueueEntry>();- /** Run `task` once every earlier task for `key` has settled. */+ /** Run `task` exclusively once every earlier read or write for `key` has settled. */async run<T>(key: string, task: () => Promise<T>): Promise<T> {const path = normalizeLockPath(key);if (!path) return task();const entry = this.queues.get(path);- const previous = entry?.tail;+ const previous = entry?.allTail;let release!: () => void;const held = new Promise<void>((resolve) => {release = resolve;@@ -46,23 +54,69 @@ export class PathMutex {): held;if (entry) {- entry.tail = tail;+ entry.writeTail = tail;+ entry.allTail = tail;entry.holders += 1;} else {- this.queues.set(path, { tail, holders: 1 });+ this.queues.set(path, { writeTail: tail, allTail: tail, holders: 1 });}if (previous) await previous.catch(() => undefined);try {return await task();} finally {release();- // Drop the entry once the last holder leaves, so a long session does not- // accumulate one promise per file it ever touched.- const current = this.queues.get(path);- if (current) {- current.holders -= 1;- if (current.holders <= 0) this.queues.delete(path);- }+ this.releaseHolder(path);+ }+ }++ /**+ * Run a read `task` once every earlier write (`run`) for `key` has settled.+ * Concurrent reads on the same path overlap; a subsequent write waits for all+ * earlier reads on that path to finish.+ */+ async read<T>(key: string, task: () => Promise<T>): Promise<T> {+ const path = normalizeLockPath(key);+ if (!path) return task();+ const entry = this.queues.get(path);+ const previousWrite = entry?.writeTail;+ let release!: () => void;+ const held = new Promise<void>((resolve) => {+ release = resolve;+ });+ const readDone = previousWrite+ ? previousWrite.then(+ () => held,+ () => held,+ )+ : held;+ const allTail = entry+ ? Promise.all([entry.allTail, readDone]).then(+ () => undefined,+ () => undefined,+ )+ : readDone;+ if (entry) {+ entry.allTail = allTail;+ entry.holders += 1;+ } else {+ this.queues.set(path, { allTail, holders: 1 });+ }+ if (previousWrite) await previousWrite.catch(() => undefined);+ try {+ return await task();+ } finally {+ release();+ this.releaseHolder(path);+ }+ }++ private releaseHolder(path: string): void {+ // Drop the entry once the last holder leaves, so a long session does not+ // accumulate one promise per file it ever touched.+ const current = this.queues.get(path);+ if (current) {+ current.holders -= 1;+ if (current.holders <= 0) this.queues.delete(path);}}diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 55bafca1e..4332d59f3 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -2,6 +2,7 @@ import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { describe, expect, it, vi, beforeEach } from "vitest";+import { Type } from "typebox";import { type Agent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";import {createAssistantMessageEventStream,@@ -38,6 +39,7 @@ import {} from "./provider-retry.js";import { getGlobalDispatcher } from "undici";import { describeProviderFetchFailure } from "./provider-transport-recovery.js";+import { resolveBatchExecutionMode } from "./tool-execution-policy.js";/*** The delegate loop itself is covered in `subagent.test.ts`; here only the* `Task` wiring around it is under test, so `SubagentRun` is replaced by a@@ -60,14 +62,19 @@ vi.mock("./subagent.js", async (importOriginal) => {...actual,SubagentRun: class {private signal?: AbortSignal;+ private options: any;constructor(options: unknown) {if (subagentRuns.constructorError !== undefined) {throw subagentRuns.constructorError;}subagentRuns.calls.push(options);+ this.options = options;// Per-instance: concurrent delegates must abort on their own signal.this.signal = (options as { signal?: AbortSignal }).signal;}+ setSystemPrompt(prompt: string) {+ this.options.systemPrompt = prompt;+ }run() {if (subagentRuns.deferred) {return new Promise((resolve) => {@@ -225,6 +232,160 @@ function runtimeTool(runtime: DesktopAgentRuntime, name: string): AgentTool {return tool;}+describe("ordered read preparation", () => {+ it.each([+ ["Bash", false], ["Write", false], ["Edit", false], ["Bash", true],+ ] as const)("keeps Read/%s/Read sequential (Stop=%s)", async (middle, stop) => {+ const entered: string[] = [];+ const release = new Map<string, (result: unknown) => void>();+ const host = { call: vi.fn(async (method: string, args: any) => {+ if (method === "project.instructions.resolve") return { entries: [] };+ if (method !== "tools.execute") return undefined;+ entered.push(args.toolCallId);+ return new Promise(resolve => release.set(args.toolCallId, resolve));+ }) };+ const runtime = createRuntime({ host });+ const internal = runtime as any;+ let requests = 0;+ internal.models = { streamSimple: () => {+ const first = ++requests === 1;+ const message = assistantMessage({ content: first ? [+ { type: "toolCall", id: "first", name: "Read", arguments: { path: "a.txt" } },+ { type: "toolCall", id: "middle", name: middle, arguments: middle === "Bash"+ ? { command: "echo fixture" } : middle === "Write"+ ? { path: "a.txt", content: "fixture" } : { path: "a.txt", tag: "ABCD", ops: "PUT >$:\n+fixture" } },+ { type: "toolCall", id: "last", name: "Read", arguments: { path: "a.txt" } },+ ] : [{ type: "text", text: "done" }], stopReason: first ? "toolUse" : "stop" }) as AssistantMessage;+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "start", partial: message });+ stream.push({ type: "done", reason: first ? "toolUse" : "stop", message });+ stream.end(message);+ });+ return stream;+ } };+ let pending: ReturnType<DesktopAgentRuntime["prompt"]> | undefined;+ try {+ pending = runtime.prompt("Run the mixed batch.");+ await vi.waitFor(() => expect(entered).toEqual(["first"]));+ await Promise.resolve();+ expect(entered).toEqual(["first"]);+ release.get("first")!({ ok: true, content: "before" });+ await vi.waitFor(() => expect(entered).toEqual(["first", "middle"]));+ const aborting = stop ? runtime.abort() : undefined;+ release.get("middle")!({ ok: true, content: "after" });+ await aborting;+ if (!stop) {+ await vi.waitFor(() => expect(entered).toEqual(["first", "middle", "last"]));+ release.get("last")!({ ok: true, content: "after" });+ }+ await pending;+ expect(entered).toEqual(stop ? ["first", "middle"] : ["first", "middle", "last"]);+ } finally {+ await runtime.abort();+ for (const resolve of release.values()) resolve({ ok: true, content: "cleanup" });+ await pending;+ await runtime.dispose();+ }+ });++ it("prepares sibling instructions in order, overlaps execution and preserves result IDs", async () => {+ const entered: string[] = [];+ const resolvers = new Map<string, (value: unknown) => void>();+ const requests: AgentMessage[][] = [];+ const host = {+ call: vi.fn(async (method: string, args: any) => {+ if (method === "project.instructions.resolve") {+ return { entries: [{ source: `${args.path}/AGENTS.md`, content: `rules:${args.path}` }] };+ }+ if (method === "tools.execute") {+ entered.push(args.toolCallId);+ return new Promise((resolve) => resolvers.set(args.toolCallId, resolve));+ }+ return undefined;+ }),+ };+ const runtime = createRuntime({ host });+ const internal = runtime as any;+ internal.models = {+ streamSimple: (_model: unknown, context: { messages: AgentMessage[] }) => {+ requests.push([...context.messages]);+ const first = requests.length === 1;+ const message = assistantMessage({+ content: first+ ? ["a", "b"].map((id) => ({ type: "toolCall", id, name: "Read", arguments: { path: `${id}/file.ts` } }))+ : [{ type: "text", text: "done" }],+ stopReason: first ? "toolUse" : "stop",+ }) as AssistantMessage;+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "start", partial: message });+ stream.push({ type: "done", reason: first ? "toolUse" : "stop", message });+ stream.end(message);+ });+ return stream;+ },+ };+ try {+ const pending = runtime.prompt("Read both files.", "user-parallel", "turn-parallel");+ await vi.waitFor(() => expect(entered).toEqual(["a", "b"]));+ // Both entered before either result is released: no timing-based assertion.+ expect(host.call.mock.calls.filter(([method]) => method === "project.instructions.resolve").map(([, args]) => args.path))+ .toEqual(["a/file.ts", "b/file.ts"]);+ expect(internal.agent.state.systemPrompt).toContain("rules:b/file.ts");+ expect(internal.agent.state.systemPrompt).not.toContain("rules:a/file.ts");+ resolvers.get("b")!({ ok: true, content: "B" });+ await Promise.resolve();+ resolvers.get("a")!({ ok: true, content: "A" });+ await pending;+ expect(requests[1].filter((message) => message.role === "toolResult").map((message: any) => message.toolCallId))+ .toEqual(["a", "b"]);+ expect(internal.agent.state.systemPrompt).toContain("rules:b/file.ts");+ } finally {+ for (const resolve of resolvers.values()) resolve({ ok: true, content: "cleanup" });+ await runtime.dispose();+ }+ });++ it("keeps a delegate's direct-call instruction updates out of the parent", async () => {+ const host = { call: vi.fn(async (method: string, args: any) => method === "project.instructions.resolve"+ ? { entries: [{ source: "AGENTS.md", content: `rules:${args.path}` }] }+ : { ok: true, content: "read" }) };+ const runtime = createRuntime({ host });+ const internal = runtime as any;+ const apply = vi.fn();+ const childTools = internal.scopeDelegateTools([runtimeTool(runtime, "Read")], { permission: "default" }, "child", apply);+ try {+ await runtimeTool(runtime, "Read").execute("parent-read", { path: "parent/a.ts" });+ await childTools[0].execute("child-read", { path: "child/b.ts" });+ expect(apply).toHaveBeenCalledWith({ entries: [{ source: "AGENTS.md", content: "rules:child/b.ts" }] });+ expect(internal.agent.state.systemPrompt).toContain("rules:parent/a.ts");+ expect(internal.agent.state.systemPrompt).not.toContain("rules:child/b.ts");+ } finally { await runtime.dispose(); }+ });++ it("prepares delegated reads against the child's prompt and reuses canonical arguments", async () => {+ const host = { call: vi.fn(async (method: string, args: any) => method === "project.instructions.resolve"+ ? { entries: [{ source: "AGENTS.md", content: `rules:${args.path}` }] }+ : { ok: true, content: "read" }) };+ const runtime = createRuntime({ host, subagents: [{ name: "reader", description: "Read", tools: ["Read"], prompt: "Read", source: "builtin" }] });+ subagentRuns.calls.length = 0;+ try {+ await runtimeTool(runtime, "Task").execute("task-prepared", { agent: "reader", task: "Read the child file." });+ const child = subagentRuns.calls[0];+ const args = { file_path: "child/file.ts" };+ await child.beforeToolCall({ toolCall: { name: "Read", id: "child-prepared" }, args });+ expect(child.systemPrompt).toContain("rules:child/file.ts");+ expect((runtime as any).agent.state.systemPrompt).not.toContain("rules:child/file.ts");+ await child.tools.find((tool: AgentTool) => tool.name === "Read").execute("child-prepared", args);+ expect(host.call.mock.calls.filter(([method]) => method === "project.instructions.resolve")).toHaveLength(1);+ expect(host.call).toHaveBeenCalledWith("tools.execute", expect.objectContaining({+ toolCallId: "child-prepared", args: { path: "child/file.ts" },+ }));+ } finally { await runtime.dispose(); }+ });+});+/** Minimal pi-ai assistant message; overrides carry the shape under test. */function assistantMessage(overrides: {content: unknown[];@@ -251,6 +412,329 @@ function assistantMessage(overrides: {};}+describe("Task/read batch execution policy", () => {+ const message = (...names: string[]) => assistantMessage({+ content: names.map((name, index) => ({+ type: "toolCall",+ id: `call-${index}`,+ name,+ arguments: {},+ })),+ }) as AssistantMessage;++ it.each([+ [["Task", "Read"], "sequential"],+ [["Task", "Glob"], "sequential"],+ [["Task", "Grep"], "sequential"],+ [["Task", "Task"], undefined],+ [["Read", "Read"], undefined],+ [["Read", "Glob", "Grep"], undefined],+ ] as const)("resolves %j to %s", (names, expected) => {+ expect(resolveBatchExecutionMode(message(...names))).toBe(expected);+ });+});++describe("Task/read mixed-batch safety", () => {+ /** A parent Task call; the delegate it starts is settled by the test. */+ function taskCall(id: string) {+ return {+ type: "toolCall",+ id,+ name: "Task",+ arguments: { agent: "explorer", task: "Edit target.txt." },+ };+ }++ /** A parent read/search of the workspace the delegate is expected to edit. */+ function readCall(id: string, name: "Read" | "Glob" | "Grep" = "Read") {+ return {+ type: "toolCall",+ id,+ name,+ arguments:+ name === "Read"+ ? { path: "target.txt" }+ : { path: ".", pattern: "target*" },+ };+ }++ /**+ * A parent turn whose first assistant message issues `calls` as one batch.+ * Every `tools.execute` stays pending until the test releases it, so each+ * assertion is about dispatch order and never about elapsed time.+ */+ function setupMixedBatch(+ calls: unknown[] = [taskCall("task"), readCall("read")],+ ) {+ const entered: string[] = [];+ const events: any[] = [];+ const releases = new Map<string, (result: unknown) => void>();+ const host = {+ call: vi.fn(async (method: string, args: any) => {+ if (method === "project.instructions.resolve") return { entries: [] };+ if (method !== "tools.execute") return undefined;+ entered.push(args.toolCallId);+ return new Promise((resolve) => { releases.set(args.toolCallId, resolve); });+ }),+ };+ const runtime = createRuntime({+ host,+ onEvent: (envelope) => { events.push((envelope as any).event); },+ subagents: [{+ name: "explorer",+ description: "Explore files.",+ tools: ["Read", "Write", "Edit"],+ prompt: "Explore files.",+ source: "builtin",+ }],+ });+ const internal = runtime as any;+ let requests = 0;+ internal.models = {+ streamSimple: () => {+ const first = ++requests === 1;+ const message = assistantMessage({+ content: first ? calls : [{ type: "text", text: "done" }],+ stopReason: first ? "toolUse" : "stop",+ }) as AssistantMessage;+ const stream = createAssistantMessageEventStream();+ queueMicrotask(() => {+ stream.push({ type: "start", partial: message });+ stream.push({ type: "done", reason: first ? "toolUse" : "stop", message });+ stream.end(message);+ });+ return stream;+ },+ };+ subagentRuns.deferred = true;+ subagentRuns.instances.length = 0;+ subagentRuns.resolveRun = undefined;+ return {+ runtime,+ internal,+ entered,+ events,+ release: (toolCallId: string) => releases.get(toolCallId),+ };+ }++ async function teardown(runtime: DesktopAgentRuntime) {+ subagentRuns.deferred = false;+ subagentRuns.resolveRun = undefined;+ await runtime.dispose();+ }++ /** The Task tool result the model actually received for one call. */+ function taskToolResult(events: any[], toolCallId = "task") {+ const end = events.find(+ (event) => event.type === "tool_end" && event.toolCallId === toolCallId,+ );+ return end.result as {+ content: Array<{ type: string; text: string }>;+ details: { delegationId: string; status: string };+ };+ }++ function settled(status: "completed" | "failed" = "completed") {+ return status === "completed"+ ? {+ agentName: "explorer",+ status: "completed",+ report: "Edited target.txt.",+ turns: 1,+ toolCalls: 1,+ }+ : {+ agentName: "explorer",+ status: "failed",+ report: "",+ turns: 0,+ toolCalls: 0,+ error: { code: "DELEGATE_FAILED", message: "boom" },+ };+ }++ /** Index of one tool event; a missing event is a broken fixture. */+ function toolIndex(events: any[], type: string, toolCallId: string) {+ const index = events.findIndex(+ (event) => event.type === type && event.toolCallId === toolCallId,+ );+ if (index < 0) throw new Error(`missing ${type} for ${toolCallId}`);+ return index;+ }++ it.each(["Read", "Glob", "Grep"] as const)(+ "returns the started notice while holding a same-batch %s behind a writable delegate's Edit",+ async (readTool) => {+ const batch = setupMixedBatch([taskCall("task"), readCall("read", readTool)]);+ subagentRuns.calls.length = 0;+ try {+ const pending = batch.runtime.prompt("Run the delegate and read its target.");+ await vi.waitFor(() => expect(subagentRuns.instances).toHaveLength(1));+ // ADR 0089 still holds inside a mixed batch: Task is non-blocking.+ await vi.waitFor(() => {+ expect(+ batch.events.some((event) => event.type === "tool_end" && event.toolCallId === "task"),+ ).toBe(true);+ });+ const task = taskToolResult(batch.events);+ expect(task.details.status).toBe("running");+ expect(task.content[0].text).toContain("in the background");+ expect(subagentRuns.instances[0].settled).toBe(false);++ // The writable delegate mutates target.txt while the parent read/search+ // from the same assistant batch is still held back from entering the Host.+ const childEdit = subagentRuns.calls[0].tools.find(+ (tool: AgentTool) => tool.name === "Edit",+ );+ const editPending = childEdit.execute(+ "delegate-edit",+ { path: "target.txt", tag: "ABCD", ops: "PUT >$:\n+updated" },+ undefined,+ undefined,+ );+ await vi.waitFor(() => expect(batch.entered).toEqual(["delegate-edit"]));+ await Promise.resolve();+ expect(batch.entered).toEqual(["delegate-edit"]);+ batch.release("delegate-edit")!({ ok: true, content: "edited" });+ await editPending;++ subagentRuns.resolveRun!(settled());+ await vi.waitFor(() => expect(batch.entered).toEqual(["delegate-edit", "read"]));+ expect(toolIndex(batch.events, "tool_end", "task"))+ .toBeLessThan(toolIndex(batch.events, "tool_start", "read"));+ batch.release("read")!({ ok: true, content: "updated" });+ await pending;+ const read = batch.events.find(+ (event) => event.type === "tool_end" && event.toolCallId === "read",+ );+ expect(read.result.content[0].text).toContain("updated");+ } finally {+ await teardown(batch.runtime);+ }+ },+ );++ it("serializes a parent Read against an in-flight shared-workspace delegate Edit on the same path", async () => {+ const batch = setupMixedBatch([taskCall("task")]);+ subagentRuns.calls.length = 0;+ try {+ await runtimeTool(batch.runtime, "Task").execute("task", {+ agent: "explorer",+ task: "Edit target.txt.",+ });+ const childEdit = subagentRuns.calls[0].tools.find(+ (tool: AgentTool) => tool.name === "Edit",+ );+ const parentRead = runtimeTool(batch.runtime, "Read");++ const editPending = childEdit.execute(+ "delegate-edit",+ { path: "target.txt", tag: "ABCD", ops: "PUT >$:\n+updated" },+ undefined,+ undefined,+ );+ await vi.waitFor(() => expect(batch.entered).toEqual(["delegate-edit"]));++ // A parent read on the same path waits for the delegate's Edit to finish,+ // while a read on an unrelated path proceeds immediately.+ const samePathRead = parentRead.execute("read-same", { path: "./target.txt" }, undefined, undefined);+ const otherPathRead = parentRead.execute("read-other", { path: "other.txt" }, undefined, undefined);+ await vi.waitFor(() => expect(batch.entered).toEqual(["delegate-edit", "read-other"]));+ batch.release("read-other")!({ ok: true, content: "other" });+ await otherPathRead;+ expect(batch.entered).toEqual(["delegate-edit", "read-other"]);++ batch.release("delegate-edit")!({ ok: true, content: "edited" });+ await editPending;+ await vi.waitFor(() =>+ expect(batch.entered).toEqual(["delegate-edit", "read-other", "read-same"]),+ );+ batch.release("read-same")!({ ok: true, content: "updated" });+ await samePathRead;+ subagentRuns.resolveRun!(settled());+ } finally {+ await teardown(batch.runtime);+ }+ });++ it("runs a Read the model ordered first before the Task starts", async () => {+ const batch = setupMixedBatch([readCall("read"), taskCall("task")]);+ try {+ const pending = batch.runtime.prompt("Read the target, then delegate.");+ await vi.waitFor(() => expect(batch.entered).toEqual(["read"]));+ // The Task in this batch has not started a delegate yet, so this read is+ // not racing anything and the batch order alone keeps the file stable.+ expect(subagentRuns.instances).toEqual([]);+ batch.release("read")!({ ok: true, content: "before" });+ await vi.waitFor(() => expect(subagentRuns.instances).toHaveLength(1));+ const read = batch.events.find(+ (event) => event.type === "tool_end" && event.toolCallId === "read",+ );+ expect(read.result.content[0].text).toContain("before");+ expect(toolIndex(batch.events, "tool_end", "read"))+ .toBeLessThan(toolIndex(batch.events, "tool_start", "task"));+ expect(taskToolResult(batch.events).details.status).toBe("running");+ subagentRuns.resolveRun!(settled());+ await pending;+ } finally {+ await teardown(batch.runtime);+ }+ });++ it("settles a failed delegate without disturbing the batch", async () => {+ const batch = setupMixedBatch();+ try {+ const pending = batch.runtime.prompt("Run the delegate and read its target.");+ await vi.waitFor(() => expect(subagentRuns.instances).toHaveLength(1));+ subagentRuns.resolveRun!(settled("failed"));+ await vi.waitFor(() => expect(batch.entered).toEqual(["read"]));+ batch.release("read")!({ ok: true, content: "unchanged" });+ await pending;+ // The Task call already returned its started notice; the failure belongs+ // to the delegation registry and reaches the parent through TaskWait.+ const task = taskToolResult(batch.events);+ expect(task.details.status).toBe("running");+ expect(+ batch.internal.delegations.get(task.details.delegationId).status,+ ).toBe("failed");+ const read = batch.events.find(+ (event) => event.type === "tool_end" && event.toolCallId === "read",+ );+ expect(read.result.content[0].text).toContain("unchanged");+ } finally {+ await teardown(batch.runtime);+ }+ });++ it("starts both delegates of a Task-only batch together", async () => {+ const batch = setupMixedBatch([taskCall("task-a"), taskCall("task-b")]);+ try {+ const pending = batch.runtime.prompt("Delegate the work twice.");+ // Both delegates are running before either settles: Task-only fan-out+ // keeps its parallel behaviour.+ await vi.waitFor(() => expect(subagentRuns.instances).toHaveLength(2));+ await vi.waitFor(() => {+ expect(+ batch.events.filter(+ (event) => event.type === "tool_end" && String(event.toolCallId).startsWith("task-"),+ ),+ ).toHaveLength(2);+ });+ for (const id of ["task-a", "task-b"]) {+ const result = taskToolResult(batch.events, id);+ expect(result.details.status).toBe("running");+ expect(result.content[0].text).toContain("in the background");+ }+ subagentRuns.resolveRun!(settled());+ subagentRuns.resolveRun!(settled());+ await pending;+ } finally {+ await teardown(batch.runtime);+ }+ });+});+function runtimeMatches(runtime: DesktopAgentRuntime,overrides: Partial<RuntimeMatchConfig> = {},@@ -8203,13 +8687,16 @@ describe("DesktopAgentRuntime subagents", () => {} finally { await runtime.dispose(); }});- it("is the only tool allowed to run in parallel", async () => {+ it("allows only Task and read/search tools to run in parallel", async () => {const runtime = createRuntime({ subagents: [explorer] });const catalog = (runtime as any).toolCatalog as Map<string, any>;expect(catalog.get("Task").executionMode).toBe("parallel");for (const [name, tool] of catalog) {- if (name === "Task") continue;+ if (["Task", "Read", "Glob", "Grep"].includes(name)) {+ expect(tool.executionMode).toBe("parallel");+ continue;+ }expect(tool.executionMode).toBe("sequential");}@@ -12620,3 +13107,51 @@ describe("isolated-session subagent worktrees (ADR 0329)", () => {expect(delegateWorktreeNote({ result: "none" }, resume)).toBe("");});});++describe("parallel policy tool provenance", () => {+ const explorer = { name: "explorer", description: "Read", tools: ["Read"], prompt: "Read", source: "builtin" as const };+ it("does not prepare native file work for a parent extension named Read", async () => {+ const host = { call: vi.fn() };+ const runtime = createRuntime({ host });+ const internal = runtime as any;+ const execute = vi.fn(async () => ({ content: [], details: {} }));+ internal.extensionRunner = { hasHandlers: () => false, getAgentTools: () => [{ name: "Read", label: "extension", description: "dynamic",+ parameters: Type.Object({}), execute }] };+ try {+ internal.rebuildToolCatalog();+ const tool = internal.toolCatalog.get("Read");+ expect(tool.executionMode).toBe("sequential");+ const toolCall = { type: "toolCall", name: "Read", id: "dynamic-parent", arguments: {} };+ await expect(internal.agent.beforeToolCall({ toolCall, args: {},+ assistantMessage: { content: [toolCall] }, context: { tools: [tool] } })).resolves.toBeUndefined();+ await tool.execute(toolCall.id, {});+ expect(execute).toHaveBeenCalledOnce();+ expect(host.call.mock.calls.some(([method]) =>+ ["project.instructions.resolve", "tools.prepareFileCall"].includes(method))).toBe(false);+ } finally { internal.extensionRunner = undefined; await runtime.dispose(); }+ });++ it("keeps delegate file preparation tied to selected provenance across parent rebuilds", async () => {+ const host = { call: vi.fn() };+ const runtime = createRuntime({ host, subagents: [explorer] });+ const internal = runtime as any;+ const execute = vi.fn(async () => ({ content: [], details: {} }));+ internal.extensionRunner = { hasHandlers: () => false, getAgentTools: () => [{ name: "Read", label: "extension", description: "dynamic",+ parameters: Type.Object({}), execute }] };+ subagentRuns.calls.length = 0;+ try {+ internal.rebuildToolCatalog();+ await internal.toolCatalog.get("Task").execute("task-dynamic-read", { agent: "explorer", task: "Read." });+ const child = subagentRuns.calls[0];+ const tool = child.tools.find((entry: AgentTool) => entry.name === "Read");+ expect(tool.executionMode).toBe("sequential");+ internal.extensionRunner = undefined;+ internal.rebuildToolCatalog();+ await expect(child.beforeToolCall({ toolCall: { name: "Read", id: "dynamic-child" }, args: {} })).resolves.toBeUndefined();+ await tool.execute("dynamic-child", {});+ expect(execute).toHaveBeenCalledOnce();+ expect(host.call.mock.calls.some(([method]) =>+ ["project.instructions.resolve", "tools.prepareFileCall"].includes(method))).toBe(false);+ } finally { internal.extensionRunner = undefined; await runtime.dispose(); }+ });+});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex ac4c71bb0..468bf1be5 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -4,6 +4,8 @@ import {mutationTerminationAdvice, mutationTerminationMessage,} from "./mutation-recovery.js";import { resolveMcpToolSelection } from "./mcp-tool-selection.js";+import { toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";+import { AsyncLocalStorage } from "node:async_hooks";import { TOOL_ACTIVATION_SECTION, toolDeclarationPolicy, toolActivationSection, restoredToolActivation, syncToolActivation, type ToolDeclarationPolicy } from "./fixed-tool-declarations.js";import { orderSystemRows, SystemTranscriptJournal } from "./system-transcript-journal.js";import { planWorkspaceRequiredResult } from "./plan-workspace-error.js";@@ -517,6 +519,10 @@ export type DelegationStatus =*/export type DelegationRecord = {delegationId: string;+ /** Parent `Task` toolCallId that started this delegation. */+ parentToolCallId?: string;+ /** True when the delegate declares file-mutating tools (`Write` / `Edit`). */+ writable?: boolean;/*** Chain id under which host-core keeps this Write/Edit subagent's own git* worktree in an isolated session (ADR 0329); absent otherwise.@@ -1887,6 +1893,10 @@ export class DesktopAgentRuntime {private commandShell: CommandShellOption;private baseProjectInstructions?: ProjectInstructions;private projectInstructions?: ProjectInstructions;+ /** Weak argument identity binds preparation to the exact validated call, without retained IDs. */+ private preparedPathToolArgs = new WeakMap<object, unknown>();+ private builtinTools = new WeakSet<AgentTool>();+ private instructionExecution = new AsyncLocalStorage<(instructions: ProjectInstructions | undefined) => void>();private projectMemory?: string;/** Per-prompt claims prevent repeated path-resolution RPCs for one directory. */private pathInstructionClaims = new Map<@@ -2326,11 +2336,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// Sequential execution also makes the host-confirmed mode change visible// before the next model request in the same run.beforeToolCall: (context) => this.beforeToolCall(context),- // Every tool except `Task` carries `executionMode: "sequential"`, and pi- // runs a batch sequentially as soon as it contains one such tool. So the- // only batch that actually runs concurrently is a batch of nothing but- // `Task` calls — subagent fan-out (ADR 0062) — and every existing tool- // ordering guarantee is untouched.+ // pi prepares the entire parallel batch in source order before launching+ // execution. Any sequential member still makes the whole batch sequential.toolExecution: "parallel",steeringMode: "all",// pi-agent-core 0.87 replaces shouldStopAfterTurn with finishTurn. A@@ -2679,7 +2686,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (!this.isToolAllowedInMode(context.toolCall.name)) {return { block: true, reason: modeToolDenial(context.toolCall.name, this.mode) };}- return this.extensionToolCall(context);+ const blocked = await this.extensionToolCall(context);+ if (blocked?.block) return blocked;+ await this.preparePathToolCall(context);+ return undefined;}const enterKind = enterToolKind(context.toolCall.name);if (enterKind && this.mode !== "agent") {@@ -3468,7 +3478,6 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.workspaceRoot ?? this.projectPath ?? this.scratchDir,): undefined;- await this.loadPathInstructions(toolName, params);const isBash = toolName === "Bash";const timeoutMs = isBash ? commandTimeoutMs(params) : undefined;let progress = "";@@ -3878,14 +3887,32 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// this line — the lock key, the host call, the transcript record — sees// canonical argument names only (D273).execute: async (toolCallId, rawParams, signal, onUpdate) => {- const params = normalizeToolParams(toolName, rawParams);+ const prepared = typeof rawParams === "object" && rawParams !== null+ && this.preparedPathToolArgs.has(rawParams);+ const params = prepared+ ? this.preparedPathToolArgs.get(rawParams as object)+ : normalizeToolParams(toolName, rawParams);+ if (prepared) this.preparedPathToolArgs.delete(rawParams as object);requireAliasedParams(toolName, params);- return PATH_MUTATING_TOOLS.has(toolName)- ? this.writeLocks.run(- isRecord(params) ? String(params.path ?? "") : "",- () => run(toolCallId, params, signal, onUpdate),- )- : run(toolCallId, params, signal, onUpdate);+ if (READ_ONLY_CORE_TOOLS.has(toolName)) {+ await this.waitForBatchWritableDelegations(toolCallId, signal);+ }+ // Direct/internal invocations retain preflight. pi invocations have+ // already committed instructions in the ordered preparation phase.+ if (!prepared) await this.loadPathInstructions(toolName, params, this.instructionExecution.getStore());+ if (PATH_MUTATING_TOOLS.has(toolName)) {+ return this.writeLocks.run(+ this.pathLockKey(toolCallId, params),+ () => run(toolCallId, params, signal, onUpdate),+ );+ }+ if (toolName === "Read") {+ return this.writeLocks.read(+ this.pathLockKey(toolCallId, params),+ () => run(toolCallId, params, signal, onUpdate),+ );+ }+ return run(toolCallId, params, signal, onUpdate);},};};@@ -3963,6 +3990,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetools.push("PluginScaffold", "PluginPack", "GenerateImages", ...Object.keys(scheduledToolParameters));}const builtins = tools.map(exec);+ for (const tool of builtins) this.builtinTools.add(tool);const jevTools: AgentTool[] =this.mode === "agent" && this.jevApiKey? [createJevClassifierTool(this.jevApiKey)]@@ -4035,6 +4063,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thethis.buildSubagentStopTool(),]: [];+ for (const tool of subagentTools) this.builtinTools.add(tool);const contextTools = this.compactionEnabled? [this.buildContextCompactionTool()]: [];@@ -4064,23 +4093,26 @@ Do not invent objections or turn speculative risks into blockers. Stop when thefor (const tool of this.buildToolDefinitions()) {if (!this.isToolAllowedInMode(tool.name) && !retainModeToolDeclaration(tool.name)) continue;// The execution mode is decided here, in one place, so no tool can grow- // an accidental parallel batch: everything is sequential except `Task`.- // pi runs a whole batch sequentially when it holds one sequential tool,- // so only an all-`Task` batch fans out.+ // an accidental parallel batch: unknown tools remain sequential.+ // pi runs a whole batch sequentially when it holds one sequential tool;+ // the batch-level policy also keeps Task mixed with file reads behind+ // the delegate completion boundary.// The provider-facing schema is settled here too, at the single origin of// every tool, so the session agent and a delegated `Task` run send the// same declaration (#864).- catalog.set(- tool.name,+ const builtin = this.builtinTools.has(tool);+ const catalogTool = withDynamicTaskExecutionMode(withModeExecutionGuard(withExplicitRequired({...tool,- executionMode:- tool.name === SUBAGENT_TOOL_NAME ? "parallel" : "sequential",+ executionMode: builtin ? toolExecutionMode(tool.name) : "sequential",}),() => this.isToolAllowedInMode(tool.name) ? undefined : modeToolDenial(tool.name, this.mode),),+ () => this.agent?.state.messages.at(-1),);+ if (builtin) this.builtinTools.add(catalogTool);+ catalog.set(tool.name, catalogTool);}this.toolCatalog = catalog;this.deferredToolNames = new Set(@@ -4482,7 +4514,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the* collaboration rules are deliberately left out — a delegate has no user to* talk to, and its report format is set by `composeSubagentSystemPrompt`.*/- private subagentGuidance(definition: SubagentDefinition): string[] {+ private subagentGuidance(definition: SubagentDefinition, instructions: ProjectInstructions | null | undefined = this.projectInstructions): string[] {const tools = new Set(resolveSubagentToolNames(definition, [...this.toolCatalog.keys()]),);@@ -4509,7 +4541,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst skillsPrompt = pluginSkillsPrompt(this.pluginSkills);if (skillsPrompt) blocks.push(skillsPrompt);}- const projectPrompt = projectInstructionsPrompt(this.projectInstructions);+ const projectPrompt = projectInstructionsPrompt(instructions ?? undefined);if (projectPrompt) blocks.push(projectPrompt);return blocks;}@@ -4750,7 +4782,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// Set in `rebuildToolCatalog`, which owns every execution mode; repeated// here so the intent survives a tool built outside that path.executionMode: "parallel",- execute: async (toolCallId, params) => {+ execute: async (toolCallId, params, signal) => {const requested = isRecord(params) ? String(params.agent ?? "") : "";const definition = this.subagents.find((candidate) => candidate.name === normalizeSubagentName(requested),@@ -4957,6 +4989,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the});const record: DelegationRecord = {delegationId,+ parentToolCallId: toolCallId,+ writable: declaredToolNames.some((name) => PATH_MUTATING_TOOLS.has(name)),taskTurnId: this.turnId,agentName: definition.name,modelId: provider.modelId,@@ -4981,7 +5015,16 @@ 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, delegationId, worktreeKey);+ const delegatePrompt = (instructions: ProjectInstructions | undefined) => composeSubagentSystemPrompt({+ definition,+ guidance: this.subagentGuidance(definition, instructions ?? null),+ toolNames: declaredToolNames,+ });+ const applyInstructions = (instructions: ProjectInstructions | undefined) => {+ subagentRun.setSystemPrompt(delegatePrompt(instructions));+ };+ const builtinToolNames = new Set(tools.filter((tool) => this.builtinTools.has(tool)).map((tool) => tool.name));+ const scopedTools = this.scopeDelegateTools(tools, definition, delegationId, worktreeKey, applyInstructions);subagentRun = new SubagentRun({definition,sessionId: this.sessionId,@@ -5013,6 +5056,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetoolNames: declaredToolNames,}),tools: scopedTools,+ beforeToolCall: async (context) => {+ await this.preparePathToolCall(context, applyInstructions, builtinToolNames);+ return undefined;+ },onEvent: (envelope) => {this.noteDelegationActivity(record, envelope);this.onEvent(envelope);@@ -5104,8 +5151,11 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetools: AgentTool[],definition: SubagentDefinition,mutationOwner: string,- worktreeKey?: string,+ worktreeKeyOrApply?: string | ((instructions: ProjectInstructions | undefined) => void),+ applyInstructions?: (instructions: ProjectInstructions | undefined) => void,): AgentTool[] {+ const worktreeKey = typeof worktreeKeyOrApply === "string" ? worktreeKeyOrApply : undefined;+ const apply = typeof worktreeKeyOrApply === "function" ? worktreeKeyOrApply : applyInstructions;const scope = definition.permission ?? DEFAULT_SUBAGENT_PERMISSION;return tools.map((tool) => ({...tool,@@ -5116,7 +5166,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}if (worktreeKey) this.delegateWorktrees.set(toolCallId, worktreeKey);try {- return await tool.execute(toolCallId, args, signal, onUpdate);+ return await this.instructionExecution.run(+ apply ?? (() => undefined),+ () => tool.execute(toolCallId, args, signal, onUpdate),+ );} finally {this.delegatePermissionScopes.delete(toolCallId);this.delegateWorktrees.delete(toolCallId);@@ -6197,9 +6250,93 @@ Do not invent objections or turn speculative risks into blockers. Stop when the}}+ private pathLockKey(toolCallId: string, params: unknown): string {+ const rawPath = isRecord(params) ? String(params.path ?? "") : "";+ if (!rawPath) return "";+ const worktreeKey = this.delegateWorktrees.get(toolCallId);+ return worktreeKey ? `${worktreeKey}\0${rawPath}` : rawPath;+ }++ /**+ * When a parent assistant message mixes `Task` with `Read`/`Glob`/`Grep`, any+ * read ordered after a writable `Task` in that same message waits for the+ * preceding writable delegation(s) from that message to settle before reading+ * the workspace, while `Task` itself still returns its ADR 0089 started state.+ */+ private async waitForBatchWritableDelegations(+ toolCallId: string,+ signal?: AbortSignal,+ ): Promise<void> {+ if (!toolCallId || this.mutationOwners.has(toolCallId)) return;+ const messages = this.agent?.state.messages ?? [];+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;+ const toolCalls = message.content.filter(+ (block): block is Extract<AssistantMessage["content"][number], { type: "toolCall" }> =>+ block.type === "toolCall",+ );+ const currentIndex = toolCalls.findIndex((call) => call.id === toolCallId);+ if (currentIndex < 0) continue;+ if (currentIndex === 0) return;+ const precedingTaskIds = new Set(+ toolCalls+ .slice(0, currentIndex)+ .filter((call) => call.name === SUBAGENT_TOOL_NAME)+ .map((call) => call.id),+ );+ if (precedingTaskIds.size === 0) return;+ const running = [...this.delegations.values()].filter(+ (record) =>+ record.status === "running" &&+ record.writable === true &&+ record.parentToolCallId !== undefined &&+ precedingTaskIds.has(record.parentToolCallId),+ );+ if (running.length === 0) return;+ const completions = Promise.all(running.map((record) => record.completion));+ if (!signal) {+ await completions;+ return;+ }+ if (signal.aborted) return;+ await new Promise<void>((resolve) => {+ const onAbort = () => resolve();+ signal.addEventListener("abort", onAbort, { once: true });+ void completions.finally(() => {+ signal.removeEventListener("abort", onAbort);+ resolve();+ });+ });+ return;+ }+ }++ private async preparePathToolCall(+ context: BeforeToolCallContext,+ apply?: (instructions: ProjectInstructions | undefined) => void,+ builtinToolNames?: ReadonlySet<string>,+ ): Promise<void> {+ const name = context.toolCall.name;+ const selected = context.context?.tools?.find((tool) => tool.name === name);+ const builtin = builtinToolNames ? builtinToolNames.has(name) : selected && this.builtinTools.has(selected);+ if (!builtin) return;+ if (!builtinToolNames && READ_ONLY_CORE_TOOLS.has(name)) {+ await this.waitForBatchWritableDelegations(context.toolCall.id);+ }+ if (!PATH_SCOPED_INSTRUCTION_TOOLS.has(name)) return;+ const params = normalizeToolParams(name, context.args);+ requireAliasedParams(name, params);+ await this.loadPathInstructions(name, params, apply);+ if (typeof context.args === "object" && context.args !== null) {+ this.preparedPathToolArgs.set(context.args, params);+ }+ }+private async loadPathInstructions(toolName: string,params: unknown,+ apply?: (instructions: ProjectInstructions | undefined) => void,): Promise<void> {if (this.remoteWorkspace || !PATH_SCOPED_INSTRUCTION_TOOLS.has(toolName)) {return undefined;@@ -6235,7 +6372,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// Rules are scoped to the file currently being accessed. Rebuild the// complete chain so sibling-directory rules never leak into one another// and edits to an existing instruction file take effect immediately.- this.applyProjectInstructions(+ (apply ?? ((instructions) => this.applyProjectInstructions(instructions)))(resolved.fallback ? this.baseProjectInstructions : resolved.instructions,);}diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.tsindex d7124b743..5a245b08c 100644--- a/packages/agent-runtime/src/subagent.test.ts+++ b/packages/agent-runtime/src/subagent.test.ts@@ -27,6 +27,59 @@ const RUN_STATUSES: SubagentRunStatus[] = ["timed_out",];+describe("delegate execution policy", () => {+ it("preserves sequential policy for a same-name dynamic Read", () => {+ const { run } = createRun({ tools: [{+ name: "Read", label: "extension", description: "dynamic", parameters: Type.Object({}),+ executionMode: "sequential", execute: async () => ({ content: [], details: {} }),+ }] });+ expect(run.agent.state.tools[0].executionMode).toBe("sequential");+ });+ it("fails closed for mutations and unknown tools even when supplied a parallel hint", () => {+ const { run } = createRun({ tools: ["Read", "Glob", "Grep", "Write", "Edit", "Bash", "plugin_unknown"].map((name) => ({+ name, label: name, description: name, parameters: Type.Object({}),+ executionMode: "parallel", execute: async () => ({ content: [], details: {} }),+ })) });+ expect(run.agent.toolExecution).toBe("parallel");+ expect(run.agent.state.tools.map((tool: any) => [tool.name, tool.executionMode])).toEqual([+ ["Read", "parallel"], ["Glob", "parallel"], ["Grep", "parallel"],+ ["Write", "sequential"], ["Edit", "sequential"], ["Bash", "sequential"], ["plugin_unknown", "sequential"],+ ]);+ run.setSystemPrompt("child-only path rules");+ expect(run.agent.state.systemPrompt).toBe("child-only path rules");+ });+ it("inherits the parent's mixed Task/read batch policy", () => {+ const { run } = createRun({+ tools: ["Read", "Glob", "Grep", "Task"].map((name) => ({+ name, label: name, description: name, parameters: Type.Object({}),+ executionMode: "parallel",+ execute: async () => ({ content: [], details: {} }),+ })),+ });+ const taskTool = run.agent.state.tools.find((tool: any) => tool.name === "Task");+ const toolCall = (id: string, name: string) => ({+ type: "toolCall", id, name, arguments: {},+ });+ // A delegate runs the same batch policy, so a nested Task mixed with a+ // file read stays sequential there too.+ run.agent.state.messages = [+ ...run.agent.state.messages,+ assistantMessage({ content: [toolCall("a", "Task"), toolCall("b", "Read")] }),+ ];+ expect(taskTool.executionMode).toBe("sequential");+ run.agent.state.messages = [+ ...run.agent.state.messages.slice(0, -1),+ assistantMessage({ content: [toolCall("a", "Read"), toolCall("b", "Glob")] }),+ ];+ expect(taskTool.executionMode).toBe("parallel");+ run.agent.state.messages = [+ ...run.agent.state.messages.slice(0, -1),+ assistantMessage({ content: [toolCall("a", "Task"), toolCall("b", "Task")] }),+ ];+ expect(taskTool.executionMode).toBe("parallel");+ });+});+const provider: RuntimeProviderConfig = {id: "local",name: "Local",diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.tsindex dc8c4dc88..e6975acb3 100644--- a/packages/agent-runtime/src/subagent.ts+++ b/packages/agent-runtime/src/subagent.ts@@ -22,10 +22,14 @@import { mkdirSync, writeFileSync } from "node:fs";import { join } from "node:path";import { randomUUID } from "node:crypto";+import { toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";+import { initialSystemTranscript, replaceSystemPrompt } from "./system-transcript.js";import {Agent,type AfterToolCallContext,type AfterToolCallResult,+ type BeforeToolCallContext,+ type BeforeToolCallResult,type AgentEvent,type AgentLoopTurnUpdate,type AgentMessage,@@ -161,6 +165,8 @@ export type SubagentRunOptions = {/** Host-backed tools, built by the session runtime so a delegate's calls* take the exact same path as the parent's. */tools: AgentTool[];+ /** Ordered preparation owned by this delegate, never the parent's prompt state. */+ beforeToolCall?: (context: BeforeToolCallContext) => Promise<BeforeToolCallResult | undefined>;onEvent: (envelope: AgentEventEnvelope) => void;/*** Result of the parent's own `afterToolCall` bookkeeping for one call, so a@@ -292,18 +298,36 @@ export class SubagentRun {prepareNextTurnWithContext: (context, signal) =>this.prepareNextTurn(context, signal),afterToolCall: async (context) => this.afterToolCall(context),+ beforeToolCall: opts.beforeToolCall,initialState: {systemPrompt: opts.systemPrompt,model: binding.model,- tools: opts.tools,+ // Preserve the parent's provenance decision; a same-name extension must+ // not inherit the builtin allowlist. Also reject unproven parallel hints.+ tools: opts.tools.map((tool) =>+ withDynamicTaskExecutionMode(+ {+ ...tool,+ executionMode:+ tool.executionMode === "parallel"+ ? toolExecutionMode(tool.name)+ : "sequential",+ },+ () => this.agent?.state.messages.at(-1),+ ),+ ),thinkingLevel: binding.agentThinkingLevel,- messages: opts.initialMessages ? [...opts.initialMessages] : [],+ messages: initialSystemTranscript(opts.systemPrompt, opts.tools, opts.initialMessages ? [...opts.initialMessages] : []),},- toolExecution: "sequential",+ toolExecution: "parallel",});this.agent.subscribe((event) => this.handleEvent(event));}+ setSystemPrompt(prompt: string): void {+ this.agent.state.messages = replaceSystemPrompt(this.agent.state.messages, prompt);+ }+async run(): Promise<SubagentRunResult> {const { signal } = this.opts;if (signal?.aborted) {diff --git a/packages/agent-runtime/src/tool-execution-policy.ts b/packages/agent-runtime/src/tool-execution-policy.tsnew file mode 100644index 000000000..f04b16f0c--- /dev/null+++ b/packages/agent-runtime/src/tool-execution-policy.ts@@ -0,0 +1,58 @@+/** Batch policy only: this does not grant permissions or coordinate other agents. */+import type { AssistantMessage } from "@earendil-works/pi-ai";++export function toolExecutionMode(name: string): "parallel" | "sequential" {+ switch (name) {+ case "Read":+ case "Glob":+ case "Grep":+ case "Task":+ return "parallel";+ default:+ return "sequential";+ }+}++/**+ * Keep Task fan-out and read batches parallel, but preserve the old safety+ * boundary for a batch that mixes a background delegate with file reads.+ * Delegate write/resource coordination belongs to a later Host-owned phase.+ */+export function resolveBatchExecutionMode(+ assistantMessage: AssistantMessage,+): "parallel" | "sequential" | undefined {+ const names = assistantMessage.content+ .filter((block): block is Extract<AssistantMessage["content"][number], { type: "toolCall" }> => block.type === "toolCall")+ .map((block) => block.name);+ const hasTask = names.includes("Task");+ const hasFileRead = names.some((name) => name === "Read" || name === "Glob" || name === "Grep");+ return hasTask && hasFileRead ? "sequential" : undefined;+}++export function resolveTaskExecutionMode(+ lastMessage: unknown,+): "parallel" | "sequential" {+ if (+ typeof lastMessage === "object" &&+ lastMessage !== null &&+ (lastMessage as { role?: unknown }).role === "assistant" &&+ Array.isArray((lastMessage as { content?: unknown }).content) &&+ resolveBatchExecutionMode(lastMessage as AssistantMessage) === "sequential"+ ) {+ return "sequential";+ }+ return "parallel";+}++export function withDynamicTaskExecutionMode<+ T extends { name: string; executionMode?: "parallel" | "sequential" },+>(tool: T, getLastMessage: () => unknown): T {+ if (tool.name !== "Task" || tool.executionMode !== "parallel") {+ return tool;+ }+ return Object.defineProperty(tool, "executionMode", {+ enumerable: true,+ configurable: true,+ get: () => resolveTaskExecutionMode(getLastMessage()),+ });+}diff --git a/scripts/e2e-parallel-read-batches.mjs b/scripts/e2e-parallel-read-batches.mjsnew file mode 100644index 000000000..ccd50e1ac--- /dev/null+++ b/scripts/e2e-parallel-read-batches.mjs@@ -0,0 +1,134 @@+// Local provider -> production Runtime/pi -> real Host -> temporary files.+// A response barrier proves concurrent dispatch, not filesystem-body overlap.+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";+import { SubagentRun } from "../packages/agent-runtime/dist/subagent.js";+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";+import { Host, resolveHostBinary } from "./e2e/host.mjs";+import { createSession, configureSession, beginTurn, endTurn } from "./e2e/session.mjs";++const scratch = await mkdtemp(join(tmpdir(), "pi-parallel-read-"));+const workspace = join(scratch, "workspace");+await mkdir(workspace);+await writeFile(join(workspace, "a.txt"), "alpha-marker\n");+await writeFile(join(workspace, "b.txt"), "beta-marker\n");+const calls = [+ { id: "read-a", name: "Read", arguments: { path: "a.txt" } },+ { id: "read-b", name: "Read", arguments: { path: "b.txt" } },+ { id: "glob", name: "Glob", arguments: { pattern: "*.txt" } },+ { id: "grep", name: "Grep", arguments: { pattern: "alpha-marker", path: "." } },+];+const requests = [];+const server = createServer(async (req, res) => {+ try {+ let raw = "";+ for await (const chunk of req) raw += chunk;+ const body = JSON.parse(raw);+ requests.push(body);+ res.writeHead(200, { "content-type": "text/event-stream" });+ const delta = (value, finish = null) => res.write(`data: ${JSON.stringify({+ id: `fixture-${requests.length}`, object: "chat.completion.chunk", created: 1,+ model: body.model, choices: [{ index: 0, delta: value, finish_reason: finish }],+ })}\n\n`);+ if (!body.messages.some(message => message.role === "tool")) {+ delta({ role: "assistant", tool_calls: calls.map((call, index) => ({+ index, id: call.id, type: "function",+ function: { name: call.name, arguments: JSON.stringify(call.arguments) },+ })) });+ delta({}, "tool_calls");+ } else {+ delta({ role: "assistant", content: "parallel-read-complete" });+ delta({}, "stop");+ }+ res.end("data: [DONE]\n\n");+ } catch (error) {+ res.writeHead(500);+ res.end(String(error));+ }+});+await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));+const host = new Host(resolveHostBinary(), join(scratch, "data"));+let runtime, turnId;+const events = [];+const returnedReads = [];+let releaseReads;+let barrier = new Promise(resolve => { releaseReads = resolve; });+let barrierTimeout = setTimeout(releaseReads, 10_000);+try {+ await host.start(PROTOCOL_VERSION);+ const session = await createSession(host, workspace, "Parallel reads");+ await configureSession(host, session, "agent", "auto");+ turnId = await beginTurn(host, session.id);+ const call = host.call.bind(host);+ host.call = async (method, args, timeout) => {+ const result = await call(method, args, timeout);+ if (method === "tools.execute" && ["read-a", "read-b"].includes(args.toolCallId)) {+ returnedReads.push(args.toolCallId);+ if (returnedReads.length === 2) releaseReads();+ await barrier;+ assert.equal(returnedReads.length, 2, "second Read never dispatched before the first response was released");+ }+ return result;+ };+ runtime = new DesktopAgentRuntime({+ host, sessionId: session.id, turnId, mode: "agent", projectPath: workspace,+ provider: {+ id: "fixture", name: "Local fixture", baseUrl: `http://127.0.0.1:${server.address().port}/v1`,+ modelId: "fixture", apiKey: "", authKind: "none", apiStyle: "chat_completions",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+ },+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ thinkingLevel: "off", onEvent: envelope => events.push(envelope.event),+ });+ await runtime.prompt("Read and search the fixture files.", "fixture-user", turnId);+ assert.equal(requests.length, 2);+ assert.deepEqual(returnedReads.slice().sort(), ["read-a", "read-b"]);+ const results = requests[1].messages.filter(message => message.role === "tool");+ assert.deepEqual(results.map(message => message.tool_call_id), calls.map(call => call.id));+ assert.match(JSON.stringify(results[0].content), /alpha-marker/);+ assert.match(JSON.stringify(results[1].content), /beta-marker/);+ assert.match(JSON.stringify(results[2].content), /a\.txt/);+ assert.match(JSON.stringify(results[3].content), /alpha-marker/);+ assert.equal(events.some(event => event.type === "error"), false);+ // Exercise the real delegate loop with the parent's scoped Host tool bridge.+ returnedReads.length = 0;+ clearTimeout(barrierTimeout);+ barrier = new Promise(resolve => { releaseReads = resolve; });+ barrierTimeout = setTimeout(releaseReads, 10_000);+ const definition = { name: "reader", description: "Read", tools: ["Read", "Glob", "Grep"], prompt: "Read", source: "builtin" };+ const names = new Set(definition.tools);+ const tools = [...runtime.toolCatalog.values()].filter(tool => names.has(tool.name));+ let child;+ const apply = instructions => child.setSystemPrompt(`Child rules: ${JSON.stringify(instructions)}`);+ const parentPrompt = runtime.agent.state.systemPrompt;+ child = new SubagentRun({+ definition, sessionId: session.id, turnId, parentToolCallId: "fixture-task",+ task: "Read and search the fixture files.", provider: runtime.provider,+ thinkingLevel: "off", systemPrompt: "Read the fixture files.",+ tools: runtime.scopeDelegateTools(tools, definition, "fixture-delegate", apply),+ beforeToolCall: context => runtime.preparePathToolCall(context, apply, names),+ onEvent: envelope => events.push(envelope.event),+ });+ const report = await child.run();+ assert.equal(report.status, "completed");+ assert.deepEqual(returnedReads.slice().sort(), ["read-a", "read-b"]);+ assert.equal(requests.length, 4);+ assert.deepEqual(requests[3].messages.filter(message => message.role === "tool").map(message => message.tool_call_id), calls.map(call => call.id));+ assert.equal(runtime.agent.state.systemPrompt, parentPrompt);+ await endTurn(host, turnId);+ turnId = undefined;+ console.log("PASS parallel-read E2E: local HTTP provider, parent/delegate concurrent Read dispatch, real Read/Glob/Grep, source-order results, parent prompt isolation");+} finally {+ releaseReads();+ clearTimeout(barrierTimeout);+ await runtime?.dispose();+ if (turnId) await endTurn(host, turnId, "error");+ await host.stop();+ server.closeAllConnections();+ await new Promise(resolve => server.close(resolve));+ await rm(scratch, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });+}diff --git a/scripts/e2e-task-read-batches.mjs b/scripts/e2e-task-read-batches.mjsnew file mode 100644index 000000000..a107afb33--- /dev/null+++ b/scripts/e2e-task-read-batches.mjs@@ -0,0 +1,140 @@+// Local provider -> production Runtime/pi -> real delegate loop -> real Host.+// Proves a mixed Task/read batch stays sequential, holds the subsequent parent+// read until a same-batch writable delegate settles, and keeps Task's ADR 0089+// contract: it reports a started delegation, never the settled report.+import assert from "node:assert/strict";+import { createServer } from "node:http";+import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";+import { Host, resolveHostBinary } from "./e2e/host.mjs";+import { createSession, configureSession, beginTurn, endTurn } from "./e2e/session.mjs";++const DELEGATE_MARKER = "delegate-marker";+const WRITTEN_MARKER = "written-by-delegate-marker";+const scratch = await mkdtemp(join(tmpdir(), "pi-task-read-"));+const workspace = join(scratch, "workspace");+await mkdir(workspace);+await writeFile(join(workspace, "target.txt"), "original-marker\n");++const requests = [];+const server = createServer(async (req, res) => {+ try {+ let raw = "";+ for await (const chunk of req) raw += chunk;+ const body = JSON.parse(raw);+ requests.push(body);+ const isDelegate = JSON.stringify(body.messages[0] ?? {}).includes(DELEGATE_MARKER);+ const hasToolResult = body.messages.some(message => message.role === "tool");+ res.writeHead(200, { "content-type": "text/event-stream" });+ const delta = (value, finish = null) => res.write(`data: ${JSON.stringify({+ id: `fixture-${requests.length}`, object: "chat.completion.chunk", created: 1,+ model: body.model, choices: [{ index: 0, delta: value, finish_reason: finish }],+ })}\n\n`);+ const emitCalls = calls => {+ delta({ role: "assistant", tool_calls: calls.map((call, index) => ({+ index, id: call.id, type: "function",+ function: { name: call.name, arguments: JSON.stringify(call.arguments) },+ })) });+ delta({}, "tool_calls");+ };+ if (isDelegate && !hasToolResult) {+ emitCalls([{ id: "write", name: "Write", arguments: { path: "target.txt", content: `${WRITTEN_MARKER}\n` } }]);+ } else if (isDelegate) {+ delta({ role: "assistant", content: "delegate-done" });+ delta({}, "stop");+ } else if (!hasToolResult) {+ emitCalls([+ { id: "task", name: "Task", arguments: { agent: "editor", task: "Rewrite target.txt." } },+ { id: "read", name: "Read", arguments: { path: "target.txt" } },+ ]);+ } else {+ delta({ role: "assistant", content: "parent-done" });+ delta({}, "stop");+ }+ res.end("data: [DONE]\n\n");+ } catch (error) {+ res.writeHead(500);+ res.end(String(error));+ }+});+await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));++const host = new Host(resolveHostBinary(), join(scratch, "data"));+let runtime, turnId;+const events = [];+// One timeline for both sides: Host dispatches and the Task tool result.+const dispatch = [];+const toolResults = new Map();+try {+ await host.start(PROTOCOL_VERSION);+ const session = await createSession(host, workspace, "Task and read");+ await configureSession(host, session, "agent", "auto");+ turnId = await beginTurn(host, session.id);+ const call = host.call.bind(host);+ host.call = async (method, args, timeout) => {+ if (method !== "tools.execute") return call(method, args, timeout);+ dispatch.push(`${args.toolCallId}:start`);+ const result = await call(method, args, timeout);+ dispatch.push(`${args.toolCallId}:end`);+ toolResults.set(args.toolCallId, result);+ return result;+ };+ runtime = new DesktopAgentRuntime({+ host, sessionId: session.id, turnId, mode: "agent", projectPath: workspace,+ scratchDir: join(scratch, "scratch"),+ provider: {+ id: "fixture", name: "Local fixture", baseUrl: `http://127.0.0.1:${server.address().port}/v1`,+ modelId: "fixture", apiKey: "", authKind: "none", apiStyle: "chat_completions",+ supportsReasoning: false, supportedThinkingLevels: ["off"],+ },+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },+ subagents: [{+ name: "editor",+ description: "Edit files.",+ tools: ["Read", "Write"],+ prompt: `${DELEGATE_MARKER}: rewrite the fixture file.`,+ source: "builtin",+ }],+ thinkingLevel: "off",+ onEvent: envelope => {+ if (envelope.event.type === "tool_end" && envelope.event.toolCallId === "task") {+ dispatch.push("task:end");+ }+ events.push(envelope.event);+ },+ });+ await runtime.prompt("Delegate the rewrite, then read the file.", "fixture-user", turnId);+ const taskEnd = events.find(+ event => event.type === "tool_end" && event.toolCallId === "task",+ );+ assert.ok(taskEnd, "the Task call never reported a tool result");+ // Task returns its started notice first, then the writable delegate finishes+ // its Write before the parent's same-batch Read is dispatched to Host.+ assert.deepEqual(dispatch, ["task:end", "write:start", "write:end", "read:start", "read:end"]);+ // ADR 0089 still holds: Task reported a started delegation, not a report.+ const taskText = JSON.stringify(taskEnd.result);+ assert.match(taskText, /working in the background/);+ assert.match(taskText, /"status":"running"/);+ assert.doesNotMatch(taskText, /delegate-done/);+ // The parent read sees the delegate's mutation instead of racing it.+ const readText = JSON.stringify(toolResults.get("read"));+ assert.match(readText, new RegExp(WRITTEN_MARKER));+ assert.doesNotMatch(readText, /original-marker/);+ // The parent batch, the delegate's tool turn, the delegate's answer and the+ // parent's follow-up. Later parent turns may add requests, never fewer.+ assert.ok(requests.length >= 4, `expected at least 4 model requests, saw ${requests.length}`);+ assert.equal(events.some(event => event.type === "error"), false);+ await endTurn(host, turnId);+ turnId = undefined;+ console.log("PASS task-read E2E: mixed Task/read batch stays sequential, Task stays non-blocking");+} finally {+ await runtime?.dispose();+ if (turnId) await endTurn(host, turnId, "error");+ await host.stop();+ server.closeAllConnections();+ await new Promise(resolve => server.close(resolve));+ await rm(scratch, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 });+}