Skip to content

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

perf(agent-runtime): order parallel tool batches by resource conflicts

cauliflowerb8eed01dc8c5
diff --git a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
index cc34ecfd1..c30569638 100644
--- a/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
+++ b/docs/adr/0062-bounded-subagents-behind-a-task-tool.md
@@ -85,9 +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
+Proposed amendment: [parallel file batches](parallel-read-batches.md) allows
+Read/Glob/Grep/Write/Edit candidates, isolates delegate path-instruction
+preparation, keeps a batch that mixes Task with those file tools sequential, and
+holds a read or search ordered after a writable Task 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`. The
diff --git a/docs/adr/README.md b/docs/adr/README.md
index d8c28ca6d..ae251122d 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -31,7 +31,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 |
+| parallel-read-batches | [Ordered preparation and parallel file 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.md
index 66762cb4f..e6fad3806 100644
--- a/docs/adr/parallel-read-batches.md
+++ b/docs/adr/parallel-read-batches.md
@@ -1,7 +1,10 @@
-# ADR: Ordered preparation and parallel read batches
+# ADR: Ordered preparation and parallel file batches
- Status: Proposed
- Date: 2026-10-12
+- Amended: 2026-10-28 by `perf(agent-runtime): order parallel tool batches by
+ resource conflicts` (Write/Edit join parallel batches, ordered by resource
+ claims)
## Context
@@ -18,6 +21,20 @@ 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.
+Amendment (2026-10-28): Write and Edit join the candidates. The allowlist
+becomes one execution spec table in `tool-execution-policy.ts`: each candidate
+declares its pi mode and, for file tools, the resources one call claims (a
+shared or exclusive claim on a lexical path key or on the whole workspace). A
+batch-local planner orders a parallel batch by those claims: each call waits
+only for earlier calls of the same assistant message whose claims conflict.
+Claims are registered at the end of the runtime's `beforeToolCall`; waiting and
+releasing wrap the catalog executor outside the mode guard and every argument
+check (a delegate's scoping wrapper calls that same executor), so a call that
+throws, is rejected or aborts still releases its successors. A Task mixed
+with any file tool, including Write and Edit, keeps the whole batch sequential.
+Host-core, `PathMutex`, Bash/Task semantics and the delegate completion barrier
+for reads are unchanged.
+
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
@@ -47,9 +64,28 @@ still come from pi.
Existing running file RPCs drain on Stop; finer cancellation and Host-owned
file resource leases belong to separate changes.
+With the amendment, a read and an unrelated write in one batch overlap, and
+same-file work keeps source order (for example `[Read a, Edit a, Read b, Write
+c]` holds only Edit a behind Read a). The rules are conservative: Glob and Grep
+claim the whole workspace, so they keep source order against every write in the
+batch; an Edit with `MV`, `REM` or a named `@register` (kept per session by
+host-core) claims the whole workspace exclusively; two
+paths with the same file name are treated as one file, because host-core writes
+are not atomic and a lexical key cannot see every alias. Host still admits one
+mutation per session, so several non-conflicting writes of one batch queue in
+Host, may run out of source order and are subject to its 30-second admission
+timeout; results still reach the model in source order. Bash, TodoWrite,
+plugin/MCP and unknown tools keep their batch sequential. A Rust-side mirror of
+the claim table and Host resource leases are deferred to the Host change that
+would consume them.
+
## 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.
+- Keep Write/Edit sequential and rely on `PathMutex`: any write still
+ serializes its whole batch, including unrelated reads.
+- Wait and release inside the builtin executor: argument validation and the
+ mode guard can fail before that code runs, leaving successors waiting forever.
diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.md
index eab8cb2e0..83bbccf1a 100644
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@ -1784,13 +1784,16 @@ 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. 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
+Tool concurrency is expressed through pi execution modes. In parallel file
+batches, `Read`, `Glob`, `Grep`, `Write` and `Edit` are parallel candidates; all
+other catalog tools remain sequential. Inside a parallel batch a call waits only
+for earlier calls of the same assistant message whose resource claims conflict
+(`03-tools-and-permissions.md` §0, "Parallel file batches"). Task-only batches
+retain parallel fan-out, while a batch that mixes `Task` with any of those file
+tools is kept sequential: a file call before `Task` finishes before the delegate
+starts, and a read or search 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 issue
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 42fe8271c..820179db4 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -5,35 +5,83 @@
## 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.
+### Parallel file batches
+
+Read, Glob, Grep, Write and Edit are parallel batch candidates. Task-only
+batches retain their existing parallel fan-out; a batch that mixes Task with
+Read, Glob, Grep, Write or Edit is kept sequential: a file call ordered before
+Task finishes before the delegate starts, and a Read, Glob or Grep ordered after
+a writable Task waits for that delegate to settle before dispatching to Host. A
+Write or Edit ordered after Task only runs after the Task call returns; it does
+not wait for the delegate to settle. 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 Bash, TodoWrite, plugin/MCP 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, native path preparation and
+resource claims. Same-name dynamic tools remain sequential. Delegates retain
+their startup catalog's policy and provenance across later parent catalog
+rebuilds.
+
+Inside a parallel batch, calls are ordered by the resources they claim. Each
+builtin file call records its claims at the end of the runtime's
+`beforeToolCall` preparation, after every runtime check that can block it. At
+execution it waits only for earlier calls of the same assistant message whose
+claims conflict; the batch does not hold back any other call.
+
+| Tool | Claim |
+|---|---|
+| Read | shared on its `path`; shared on the whole workspace without a `path` |
+| Glob, Grep | shared on the whole workspace |
+| Write | exclusive on its `path`; exclusive on the whole workspace without a `path` |
+| Edit | exclusive on its `path`; exclusive on the whole workspace when an `ops` line starts (after optional whitespace) with `MV` or `REM`, when a `CUT` or `PUT` header names an `@register`, or without a `path` |
+
+Two shared claims never conflict. Any exclusive claim conflicts with a
+whole-workspace claim and with a path claim on the same file. So Glob and Grep
+keep source order against every Write and Edit in the batch, and an Edit with
+`MV`, `REM` or a named register keeps source order against every other file call
+in the batch. Named registers are kept per session by host-core, so a `CUT @x`
+and a later `PUT @x` on another file must not reorder.
+For example, `[Read a, Edit a, Read b, Write c]` starts Read a, Read b and
+Write c together, and Edit a starts after Read a ends.
+
+Path keys are lexical and never touch the filesystem: backslashes become `/`,
+a relative path is joined to the session's workspace root (the project path
+unless the session is isolated), `.` and `..` segments collapse, a trailing
+`/` is dropped and the key is lowercased. Two keys also name the same file when
+their file names match: this basename fallback is deliberately conservative,
+because aliases a lexical key cannot see (symbolic links, a delegate's worktree
+spelling) would otherwise overlap a read with a non-atomic Host write.
+Same-named files in different directories only lose overlap.
+
+A call that fails, is rejected (for example by the mode guard after a
+mid-turn mode switch) or is aborted still releases the calls ordered behind it;
+failure does not cascade. A call still waiting for its turn when the user stops
+fails with `TOOL_ABORTED` before reaching Host. Claims order calls only inside
+one assistant message; they are not a cross-agent lock.
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.
+retain preflight and are not ordered by claims. 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
+result IDs remain authoritative. Host still admits one mutation per session at
+a time, so non-conflicting Writes and Edits of one batch queue in Host and may
+run in a different order than the model wrote them; a call that waits in that
+queue longer than the Host's 30-second admission timeout fails with
+`HOST_OVERLOADED`.
+Permission approval happens before admission, so several same-batch calls can
+await approval together and each decision applies only to its own call.
+Completion events may arrive out of order; model tool results remain in source
+order. Alongside the mixed Task batch barrier, `PathMutex` coordinates shared
+reads against exclusive `Write`/`Edit` calls on the same normalized workspace
+path across the parent and its delegates, 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.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7f57bbb6b..38a701f50 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -231,7 +231,7 @@
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
+### E2E-TOOLS-parallel-read-batches: ordered preparation and parallel file batches
- Isolate data/project paths; never run against production profiles.
- A local provider fixture emits two Read calls. Gate real tool-execution
@@ -239,8 +239,15 @@
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 Bash to the batch: all tools must execute sequentially. Add Write or
+ Edit instead: calls are ordered by resource conflicts. `[Read a, Write b,
+ Read c]` must dispatch all three to Host before any response returns, write
+ b's content and keep source-order results; `[Read a, Edit a]`, with the tag of
+ a real Read, must reach Host as `read:start`, `read:end`, `edit:start` and
+ succeed. Two same-batch Writes to different files must each leave a review
+ snapshot that rolls back its own file; in ask mode both must await approval
+ together and denying one must not affect the other. 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
@@ -248,7 +255,10 @@
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:
+ batches and Stop, conflict-ordered file batches for the parent and a real
+ delegate loop, calls that fail argument checks or the mode guard while still
+ releasing their successors, mixed Task/Write batches in both orders, and 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`
@@ -260,9 +270,11 @@
- 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,
+ temporary directories. A gated response proves overlapping Read dispatch and
+ overlapping `[Read, Write, Read]` dispatch; actual Read/Glob/Grep results,
+ source-order model results, parent prompt isolation, the `[Read a, Edit a]`
+ Host order with a real tag, two-Write rollback and concurrent ask-mode
+ approvals 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
diff --git a/packages/agent-runtime/src/batch-planner.test.ts b/packages/agent-runtime/src/batch-planner.test.ts
new file mode 100644
index 000000000..4c6312fe6
--- /dev/null
+++ b/packages/agent-runtime/src/batch-planner.test.ts
@@ -0,0 +1,315 @@
+import { describe, expect, it } from "vitest";
+import { Type } from "typebox";
+import type { AgentTool } from "@earendil-works/pi-agent-core";
+import { BatchPlanner, claimsConflict, sameFile, withBatchTurn } from "./batch-planner.js";
+import { resourcePathKey, TOOL_EXECUTION_SPECS, type ResourceClaim } from "./tool-execution-policy.js";
+
+const path = (key: string, access: "shared" | "exclusive"): ResourceClaim => ({ kind: "path", key, access });
+const tree = (access: "shared" | "exclusive"): ResourceClaim => ({ kind: "tree", access });
+const claims = (name: string, params: unknown, base = "/root") => TOOL_EXECUTION_SPECS[name]!.claims!(params, base);
+
+/** Resolves on the next macrotask, after every pending microtask has run. */
+const settledTurn = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+function track(promise: Promise<unknown>) {
+ const state = { done: false };
+ void promise.then(() => { state.done = true; }, () => { state.done = true; });
+ return state;
+}
+
+describe("claim conflicts", () => {
+ it.each([
+ ["path S / path S", path("a", "shared"), path("a", "shared"), false],
+ ["path X / path X, same file", path("/r/a", "exclusive"), path("/r/a", "exclusive"), true],
+ ["path S / path X, same file", path("/r/a", "shared"), path("/r/a", "exclusive"), true],
+ ["path X / path S, other file", path("/r/a", "exclusive"), path("/r/b", "shared"), false],
+ ["tree S / tree S", tree("shared"), tree("shared"), false],
+ ["tree S / path X", tree("shared"), path("/r/a", "exclusive"), true],
+ ["path X / tree S", path("/r/a", "exclusive"), tree("shared"), true],
+ ["tree S / path S", tree("shared"), path("/r/a", "shared"), false],
+ ["tree X / path S", tree("exclusive"), path("/r/a", "shared"), true],
+ ["tree X / tree S", tree("exclusive"), tree("shared"), true],
+ ["path S / tree X", path("/r/a", "shared"), tree("exclusive"), true],
+ ] as const)("%s → %s", (_label, a, b, expected) => {
+ expect(claimsConflict([a], [b])).toBe(expected);
+ });
+
+ it("never orders a call that declares no claims", () => {
+ expect(claimsConflict([], [tree("exclusive")])).toBe(false);
+ expect(claimsConflict([tree("exclusive")], [])).toBe(false);
+ });
+});
+
+describe("resource path keys", () => {
+ const key = (raw: string) => resourcePathKey(raw, "/root");
+
+ it.each([
+ ["a.ts", "./a.ts"],
+ ["src\\a.ts", "src/a.ts"],
+ ["/root/a.ts", "a.ts"],
+ ["A.ts", "a.ts"],
+ ["src/../a.ts", "a.ts"],
+ ["src/", "src"],
+ ])("%s and %s name the same file", (left, right) => {
+ expect(key(left)).toBe(key(right));
+ expect(sameFile(key(left), key(right))).toBe(true);
+ });
+
+ it("keeps absolute Windows, POSIX and UNC paths off the base", () => {
+ expect(resourcePathKey("C:\\Work\\A.ts", "/root")).toBe("c:/work/a.ts");
+ expect(resourcePathKey("/etc/hosts", "C:/root")).toBe("/etc/hosts");
+ expect(resourcePathKey("//server/share/a.ts", "/root")).toBe("/server/share/a.ts");
+ expect(resourcePathKey("a.ts", "C:\\Root")).toBe("c:/root/a.ts");
+ });
+
+ it("treats a shared basename as the same file even in different directories", () => {
+ expect(sameFile(key("x/a.ts"), key("y/a.ts"))).toBe(true);
+ });
+
+ it("keeps different files apart", () => {
+ expect(sameFile(key("a.ts"), key("b.ts"))).toBe(false);
+ });
+});
+
+describe("tool claims", () => {
+ it("declares Read as a shared path and Glob/Grep as a shared tree", () => {
+ expect(claims("Read", { path: "a.ts" })).toEqual([path("/root/a.ts", "shared")]);
+ expect(claims("Read", {})).toEqual([tree("shared")]);
+ expect(claims("Glob", { pattern: "*.ts" })).toEqual([tree("shared")]);
+ expect(claims("Grep", { pattern: "x", path: "src" })).toEqual([tree("shared")]);
+ });
+
+ it("declares Write as an exclusive path, or the whole tree without a path", () => {
+ expect(claims("Write", { path: "a.ts", content: "" })).toEqual([path("/root/a.ts", "exclusive")]);
+ expect(claims("Write", { content: "" })).toEqual([tree("exclusive")]);
+ });
+
+ it.each([
+ ["plain ops", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x" }, [path("/root/a.ts", "exclusive")]],
+ ["MV", { path: "a.ts", tag: "ABCD", ops: "MV b.ts" }, [tree("exclusive")]],
+ ["indented REM after another op", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x\n REM" }, [tree("exclusive")]],
+ ["MV text inside a body row", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+MV b.ts" }, [path("/root/a.ts", "exclusive")]],
+ ["CUT into a named register", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5 @moved" }, [tree("exclusive")]],
+ ["PUT from a named register", { path: "b.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x\nPUT <1 @moved" }, [tree("exclusive")]],
+ ["a register after U+0085, which host-core treats as whitespace", { path: "b.ts", tag: "ABCD", ops: "PUT\u0085<1\u0085@moved" }, [tree("exclusive")]],
+ ["anonymous CUT and PUT in one call", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5\nPUT <1" }, [path("/root/a.ts", "exclusive")]],
+ ["@ text inside a body row", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+mail @someone" }, [path("/root/a.ts", "exclusive")]],
+ ["legacy old_string/new_string", { path: "a.ts", old_string: "a", new_string: "b" }, [path("/root/a.ts", "exclusive")]],
+ ["missing path", { tag: "ABCD", ops: "PUT 1.=1:\n+x" }, [tree("exclusive")]],
+ ["empty path", { path: " ", ops: "PUT 1.=1:\n+x" }, [tree("exclusive")]],
+ ] as const)("declares Edit with %s", (_label, params, expected) => {
+ expect(claims("Edit", params)).toEqual(expected);
+ });
+
+ it("gives Task no claims and leaves unlisted tools sequential without claims", () => {
+ expect(TOOL_EXECUTION_SPECS.Task).toEqual({ mode: "parallel" });
+ expect(TOOL_EXECUTION_SPECS.Bash).toBeUndefined();
+ });
+});
+
+describe("BatchPlanner", () => {
+ /** Registers calls in source order under one batch and returns their keys. */
+ function plan(planner: BatchPlanner, batch: object, calls: Array<[string, unknown]>) {
+ return calls.map(([name, params]) => {
+ const key = { name, params };
+ planner.register(batch, key, claims(name, params));
+ return key;
+ });
+ }
+
+ it("keeps a named-register CUT and PUT on different files in source order", async () => {
+ const planner = new BatchPlanner();
+ // Host keeps named registers per session, so the PUT must see this CUT.
+ const [cut, put] = plan(planner, {}, [
+ ["Edit", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5 @moved" }],
+ ["Edit", { path: "b.ts", tag: "ABCD", ops: "PUT <1 @moved" }],
+ ]);
+ const waiting = track(planner.waitForTurn(put));
+ await settledTurn();
+ expect(waiting.done).toBe(false);
+ planner.settle(cut);
+ await settledTurn();
+ expect(waiting.done).toBe(true);
+ });
+
+ it("orders only the conflicting call in [Read a, Edit a, Read b, Write c]", async () => {
+ const planner = new BatchPlanner();
+ const [readA, editA, readB, writeC] = plan(planner, {}, [
+ ["Read", { path: "a.ts" }],
+ ["Edit", { path: "a.ts", tag: "ABCD", ops: "PUT 1.=1:\n+x" }],
+ ["Read", { path: "b.ts" }],
+ ["Write", { path: "c.ts", content: "" }],
+ ]);
+ const edit = track(planner.waitForTurn(editA));
+ const others = [readA, readB, writeC].map((key) => track(planner.waitForTurn(key)));
+ await settledTurn();
+ expect(others.map((state) => state.done)).toEqual([true, true, true]);
+ expect(edit.done).toBe(false);
+ planner.settle(readA);
+ await settledTurn();
+ expect(edit.done).toBe(true);
+ });
+
+ it("waits for every conflicting predecessor", async () => {
+ const planner = new BatchPlanner();
+ const [first, second, third] = plan(planner, {}, [
+ ["Read", { path: "a.ts" }],
+ ["Read", { path: "./a.ts" }],
+ ["Write", { path: "a.ts", content: "" }],
+ ]);
+ const write = track(planner.waitForTurn(third));
+ planner.settle(first);
+ await settledTurn();
+ expect(write.done).toBe(false);
+ planner.settle(second);
+ await settledTurn();
+ expect(write.done).toBe(true);
+ });
+
+ it("keeps batches apart", async () => {
+ const planner = new BatchPlanner();
+ const [parentRead] = plan(planner, {}, [["Read", { path: "a.ts" }]]);
+ const [childWrite] = plan(planner, {}, [["Write", { path: "a.ts", content: "" }]]);
+ await expect(planner.waitForTurn(childWrite)).resolves.toBeUndefined();
+ planner.settle(parentRead);
+ });
+
+ it("returns at once for an unregistered call", async () => {
+ await expect(new BatchPlanner().waitForTurn({})).resolves.toBeUndefined();
+ });
+
+ it("returns on abort while a predecessor is still running", async () => {
+ const planner = new BatchPlanner();
+ const [, edit] = plan(planner, {}, [
+ ["Read", { path: "a.ts" }],
+ ["Edit", { path: "a.ts", ops: "PUT 1.=1:\n+x" }],
+ ]);
+ const controller = new AbortController();
+ const waiting = track(planner.waitForTurn(edit, controller.signal));
+ await settledTurn();
+ expect(waiting.done).toBe(false);
+ controller.abort();
+ await settledTurn();
+ expect(waiting.done).toBe(true);
+ });
+
+ it("unblocks a successor when a registered predecessor never executes and the batch aborts", async () => {
+ const planner = new BatchPlanner();
+ const batch = {};
+ // The predecessor is registered but never reaches waitForTurn/settle.
+ const [, write] = plan(planner, batch, [
+ ["Read", { path: "a.ts" }],
+ ["Write", { path: "a.ts", content: "" }],
+ ]);
+ const controller = new AbortController();
+ const waiting = track(planner.waitForTurn(write, controller.signal));
+ await settledTurn();
+ expect(waiting.done).toBe(false);
+ controller.abort();
+ await settledTurn();
+ expect(waiting.done).toBe(true);
+ // An already-aborted signal returns at once as well.
+ await expect(planner.waitForTurn(write, controller.signal)).resolves.toBeUndefined();
+ });
+
+ it("settles every registration left in a batch at batch end", async () => {
+ const planner = new BatchPlanner();
+ const batch = {};
+ const [, write] = plan(planner, batch, [
+ ["Read", { path: "a.ts" }],
+ ["Write", { path: "a.ts", content: "" }],
+ ]);
+ const waiting = track(planner.waitForTurn(write));
+ planner.settleBatch(batch);
+ await settledTurn();
+ expect(waiting.done).toBe(true);
+ });
+
+ it("treats settle as idempotent and safe for unknown keys", async () => {
+ const planner = new BatchPlanner();
+ const [read, write] = plan(planner, {}, [
+ ["Read", { path: "a.ts" }],
+ ["Write", { path: "a.ts", content: "" }],
+ ]);
+ planner.settle(read);
+ planner.settle(read);
+ planner.settle({});
+ await expect(planner.waitForTurn(write)).resolves.toBeUndefined();
+ });
+});
+
+describe("withBatchTurn releases every registered call", () => {
+ function tool(execute: AgentTool["execute"]): AgentTool {
+ return { name: "Read", label: "Read", description: "Read", parameters: Type.Object({}), execute };
+ }
+
+ /** [predecessor, successor] on one file; the successor waits for the predecessor. */
+ function batch(planner: BatchPlanner) {
+ const first = { path: "a.ts" };
+ const second = { path: "a.ts", content: "" };
+ const key = {};
+ planner.register(key, first, claims("Read", first));
+ planner.register(key, second, claims("Write", second));
+ return { key, first, second };
+ }
+
+ it.each([
+ ["throws synchronously", () => { throw new Error("invalid arguments"); }],
+ ["rejects", async () => { throw new Error("mode denied"); }],
+ ] as const)("when the inner execute %s", async (_label, execute) => {
+ const planner = new BatchPlanner();
+ const { first, second } = batch(planner);
+ const failing = withBatchTurn(tool(execute as AgentTool["execute"]), planner);
+ const next = withBatchTurn(tool(async () => ({ content: [], details: {} })), planner);
+ const successor = next.execute("second", second as never);
+ await expect(failing.execute("first", first as never)).rejects.toThrow();
+ await expect(successor).resolves.toEqual({ content: [], details: {} });
+ });
+
+ it("releases only after the inner execute settles", async () => {
+ const planner = new BatchPlanner();
+ const { first, second } = batch(planner);
+ let finish!: () => void;
+ const slow = withBatchTurn(tool(() => new Promise((resolve) => {
+ finish = () => resolve({ content: [], details: {} });
+ })), planner);
+ const next = withBatchTurn(tool(async () => ({ content: [], details: {} })), planner);
+ const running = slow.execute("first", first as never);
+ const waiting = track(next.execute("second", second as never));
+ await settledTurn();
+ expect(waiting.done).toBe(false);
+ finish();
+ await running;
+ await settledTurn();
+ expect(waiting.done).toBe(true);
+ });
+
+ it("releases a call that was aborted while waiting for its turn", async () => {
+ const planner = new BatchPlanner();
+ const { key, first, second } = batch(planner);
+ // A later same-file Read in the same batch waits only for the Write; the
+ // first Read keeps running and never settles in this test.
+ const third = { path: "a.ts" };
+ planner.register(key, third, claims("Read", third));
+ const controller = new AbortController();
+ const inner = async (_id: string, _args: unknown, signal?: AbortSignal) => {
+ if (signal?.aborted) throw new Error("tool execution aborted before it started");
+ return { content: [], details: {} };
+ };
+ const write = withBatchTurn(tool(inner as AgentTool["execute"]), planner);
+ const read = withBatchTurn(tool(inner as AgentTool["execute"]), planner);
+ const writing = write.execute("second", second as never, controller.signal);
+ const reading = read.execute("third", third as never);
+ controller.abort();
+ await expect(writing).rejects.toThrow("aborted before it started");
+ // The Write never ran but still released the Read ordered behind it.
+ await expect(reading).resolves.toEqual({ content: [], details: {} });
+ planner.settle(first);
+ });
+
+ it("is a no-op for a direct call that was never registered", async () => {
+ const planner = new BatchPlanner();
+ const wrapped = withBatchTurn(tool(async () => ({ content: [], details: {} })), planner);
+ await expect(wrapped.execute("direct", { path: "a.ts" } as never)).resolves.toEqual({ content: [], details: {} });
+ });
+});
diff --git a/packages/agent-runtime/src/batch-planner.ts b/packages/agent-runtime/src/batch-planner.ts
new file mode 100644
index 000000000..4a17215a0
--- /dev/null
+++ b/packages/agent-runtime/src/batch-planner.ts
@@ -0,0 +1,128 @@
+/**
+ * Orders the calls of one parallel pi batch by the resources they claim.
+ *
+ * pi prepares every call of a parallel batch in source order and then starts
+ * them all at once. Each prepared call registers its claims here; at execution
+ * it waits only for earlier calls of the same batch whose claims conflict, so
+ * unrelated reads and writes overlap while same-file work keeps source order.
+ *
+ * Batch-local only: the parent and its delegates still meet in `PathMutex` and
+ * host-core admission.
+ */
+import type { AgentTool } from "@earendil-works/pi-agent-core";
+import type { ResourceClaim } from "./tool-execution-policy.js";
+
+type PlannedCall = {
+ claims: ResourceClaim[];
+ /** Earlier calls of the same batch that conflict; fixed at registration. */
+ deps: PlannedCall[];
+ settled: Promise<void>;
+ resolve: () => void;
+};
+
+/**
+ * True for two keys that may name one file: the same key, or the same file
+ * name. The basename fallback is deliberately conservative — it also catches
+ * aliases a lexical key cannot see (absolute vs. relative spellings of a
+ * delegate worktree, symlinked directories) because host-core writes are not
+ * atomic. Same-name files in different directories only lose overlap.
+ */
+export function sameFile(left: string, right: string): boolean {
+ return left === right || left.slice(left.lastIndexOf("/") + 1) === right.slice(right.lastIndexOf("/") + 1);
+}
+
+function claimConflicts(left: ResourceClaim, right: ResourceClaim): boolean {
+ if (left.access === "shared" && right.access === "shared") return false;
+ if (left.kind === "tree" || right.kind === "tree") return true;
+ return sameFile(left.key, right.key);
+}
+
+export function claimsConflict(left: readonly ResourceClaim[], right: readonly ResourceClaim[]): boolean {
+ return left.some((a) => right.some((b) => claimConflicts(a, b)));
+}
+
+export class BatchPlanner {
+ /** Keyed by the assistant message, so a finished batch is collected with it. */
+ private batches = new WeakMap<object, PlannedCall[]>();
+ /** Keyed by the args object pi passes to `execute` (see `preparedPathToolArgs`). */
+ private byArgs = new WeakMap<object, PlannedCall>();
+
+ /** Called during preparation, which pi runs in source order. */
+ register(batchKey: object, argsKey: object, claims: ResourceClaim[]): void {
+ let batch = this.batches.get(batchKey);
+ if (!batch) {
+ batch = [];
+ this.batches.set(batchKey, batch);
+ }
+ let resolve!: () => void;
+ const settled = new Promise<void>((done) => { resolve = done; });
+ const call: PlannedCall = {
+ claims,
+ deps: batch.filter((prior) => claimsConflict(prior.claims, claims)),
+ settled,
+ resolve,
+ };
+ batch.push(call);
+ this.byArgs.set(argsKey, call);
+ }
+
+ /**
+ * Waits until every conflicting predecessor settles, or `signal` aborts; the
+ * caller's own abort check then fails the call. Returns at once for a call
+ * that was never registered (a direct, non-pi invocation). No timeout: every
+ * wait ends at a call that really runs or at the batch's abort signal.
+ */
+ async waitForTurn(argsKey: object, signal?: AbortSignal): Promise<void> {
+ const call = this.byArgs.get(argsKey);
+ if (!call || call.deps.length === 0 || signal?.aborted) return;
+ await new Promise<void>((resolve) => {
+ const onAbort = () => resolve();
+ signal?.addEventListener("abort", onAbort, { once: true });
+ void Promise.all(call.deps.map((dep) => dep.settled)).then(() => {
+ signal?.removeEventListener("abort", onAbort);
+ resolve();
+ });
+ });
+ }
+
+ /** Releases the calls ordered behind this one. Idempotent. */
+ settle(argsKey: object): void {
+ const call = this.byArgs.get(argsKey);
+ if (!call) return;
+ this.byArgs.delete(argsKey);
+ call.resolve();
+ }
+
+ /**
+ * Batch-end backstop: settles whatever the batch still holds, such as a call
+ * pi prepared but never started because the run aborted. It cannot replace
+ * {@link withBatchTurn}, because pi only ends a batch after every started
+ * call has returned.
+ */
+ settleBatch(batchKey: unknown): void {
+ if (typeof batchKey !== "object" || batchKey === null) return;
+ for (const call of this.batches.get(batchKey) ?? []) call.resolve();
+ this.batches.delete(batchKey);
+ }
+}
+
+/**
+ * The catalog layer pi calls (a delegate's scoping wrapper calls it in turn).
+ * Waiting and releasing live here, outside every check the tool makes (argument
+ * validation, the mode guard), so a call that throws, rejects or aborts before
+ * reaching the Host still releases its successors.
+ */
+export function withBatchTurn(tool: AgentTool, planner: BatchPlanner): AgentTool {
+ return {
+ ...tool,
+ execute: async (toolCallId, args, signal, onUpdate) => {
+ const key = args as object;
+ try {
+ await planner.waitForTurn(key, signal);
+ return await tool.execute(toolCallId, args, signal, onUpdate);
+ } finally {
+ planner.settle(key);
+ }
+ },
+ };
+}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 1142fdc78..a17c4dd77 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -40,6 +40,7 @@ import {
import { getGlobalDispatcher } from "undici";
import { describeProviderFetchFailure } from "./provider-transport-recovery.js";
import { resolveBatchExecutionMode } from "./tool-execution-policy.js";
+import { BatchPlanner } from "./batch-planner.js";
import { DESKTOP_AGENT_IDENTITY } from "./agent-identity.js";
/**
* The delegate loop itself is covered in `subagent.test.ts`; here only the
@@ -423,6 +424,146 @@ describe("ordered read preparation", () => {
});
});
+function toolCall(id: string, name: string, args: Record<string, unknown>) {
+ return { type: "toolCall", id, name, arguments: args };
+}
+
+/**
+ * pi stream that answers each request with the next scripted tool batch and,
+ * once the script runs out, a final text reply. Records every request.
+ */
+function scriptedStream(batches: unknown[][], requests: AgentMessage[][] = []) {
+ let turn = 0;
+ return (_model: unknown, context: { messages: AgentMessage[] }) => {
+ requests.push([...context.messages]);
+ const calls = batches[turn++];
+ const reason = calls ? "toolUse" : "stop";
+ const message = assistantMessage({
+ content: calls ?? [{ type: "text", text: "done" }],
+ stopReason: reason,
+ }) as AssistantMessage;
+ const stream = createAssistantMessageEventStream();
+ queueMicrotask(() => {
+ stream.push({ type: "start", partial: message });
+ stream.push({ type: "done", reason, message });
+ stream.end(message);
+ });
+ return stream;
+ };
+}
+
+/** Host whose `tools.execute` responses are held until the test releases them. */
+function gatedHost() {
+ 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 finish = (id: string, result: unknown = { ok: true, content: id }) => release.get(id)!(result);
+ const drain = () => { for (const resolve of release.values()) resolve({ ok: true, content: "cleanup" }); };
+ return { host, entered, finish, drain };
+}
+
+function toolResults(request: AgentMessage[]) {
+ return request
+ .filter((message) => message.role === "toolResult")
+ .map((message: any) => ({
+ id: message.toolCallId as string,
+ isError: message.isError as boolean,
+ text: JSON.stringify(message.content),
+ }));
+}
+
+describe("batch turn release", () => {
+ it("releases a parent call that fails argument checks before reaching the Host", async () => {
+ const { host, entered, finish, drain } = gatedHost();
+ const requests: AgentMessage[][] = [];
+ const runtime = createRuntime({ host, projectPath: "/root" });
+ (runtime as any).models = { streamSimple: scriptedStream([[
+ // Grep without `pattern` passes the schema (the alias makes it optional)
+ // and then throws in execute; the Write is ordered behind its tree claim.
+ toolCall("grep", "Grep", { path: "src" }),
+ toolCall("write", "Write", { path: "x.txt", content: "x" }),
+ ]], requests) };
+ try {
+ const pending = runtime.prompt("Search, then write.");
+ await vi.waitFor(() => expect(entered).toEqual(["write"]));
+ finish("write");
+ await pending;
+ const results = toolResults(requests[1]);
+ expect(results.map(({ id, isError }) => [id, isError])).toEqual([["grep", true], ["write", false]]);
+ expect(results[0].text).toContain("`pattern` is required");
+ } finally {
+ drain();
+ await runtime.dispose();
+ }
+ });
+
+ it("releases a parent call rejected by the mode guard after a mid-turn mode switch", async () => {
+ const { host, entered, finish, drain } = gatedHost();
+ const requests: AgentMessage[][] = [];
+ const runtime = createRuntime({ host, projectPath: "/root" });
+ (runtime as any).models = { streamSimple: scriptedStream([[
+ toolCall("read-1", "Read", { path: "x.txt" }),
+ toolCall("write", "Write", { path: "x.txt", content: "x" }),
+ toolCall("read-2", "Read", { path: "x.txt" }),
+ ]], requests) };
+ try {
+ const pending = runtime.prompt("Read, write, read.");
+ await vi.waitFor(() => expect(entered).toEqual(["read-1"]));
+ runtime.setMode("plan");
+ finish("read-1");
+ await vi.waitFor(() => expect(entered).toEqual(["read-1", "read-2"]));
+ finish("read-2");
+ await pending;
+ const results = toolResults(requests[1]);
+ expect(results.map(({ id, isError }) => [id, isError])).toEqual([
+ ["read-1", false], ["write", true], ["read-2", false],
+ ]);
+ expect(results[1].text).toContain("not allowed in plan");
+ } finally {
+ drain();
+ await runtime.dispose();
+ }
+ });
+
+ it("releases a delegate call that fails argument checks before reaching the Host", async () => {
+ const { SubagentRun: RealSubagentRun } = await vi.importActual<typeof import("./subagent.js")>("./subagent.js");
+ const { host, entered, finish, drain } = gatedHost();
+ const writer = { name: "writer", description: "Write", tools: ["Grep", "Write"], prompt: "Write", source: "builtin" as const };
+ const runtime = createRuntime({ host, projectPath: "/root", subagents: [writer] });
+ subagentRuns.calls.length = 0;
+ try {
+ await runtimeTool(runtime, "Task").execute("task-writer", { agent: "writer", task: "Search, then write." });
+ const options = subagentRuns.calls[0];
+ const child = new RealSubagentRun({ ...options, signal: undefined }) as unknown as {
+ agent: { streamFunction: unknown };
+ run: () => Promise<{ status: string }>;
+ };
+ const requests: AgentMessage[][] = [];
+ child.agent.streamFunction = scriptedStream([[
+ toolCall("child-grep", "Grep", { path: "src" }),
+ toolCall("child-write", "Write", { path: "x.txt", content: "x" }),
+ ]], requests);
+ const running = child.run();
+ await vi.waitFor(() => expect(entered).toEqual(["child-write"]));
+ finish("child-write");
+ await expect(running).resolves.toMatchObject({ status: "completed" });
+ expect(toolResults(requests[1]).map(({ id, isError }) => [id, isError])).toEqual([
+ ["child-grep", true], ["child-write", false],
+ ]);
+ } finally {
+ drain();
+ await runtime.dispose();
+ }
+ });
+});
+
/** Minimal pi-ai assistant message; overrides carry the shape under test. */
function assistantMessage(overrides: {
content: unknown[];
@@ -449,6 +590,224 @@ function assistantMessage(overrides: {
};
}
+describe("parallel file batches", () => {
+ /** Starts a parent turn whose first request returns `calls` as one batch. */
+ function startBatch(calls: unknown[], options: { projectPath?: string } = {}) {
+ const gate = gatedHost();
+ const requests: AgentMessage[][] = [];
+ const events: any[] = [];
+ const runtime = createRuntime({
+ host: gate.host,
+ projectPath: options.projectPath ?? "/root",
+ onEvent: (envelope) => { events.push((envelope as any).event); },
+ });
+ (runtime as any).models = { streamSimple: scriptedStream([calls], requests) };
+ const pending = runtime.prompt("Run the file batch.");
+ return { ...gate, runtime, requests, events, pending };
+ }
+
+ async function cleanup(batch: ReturnType<typeof startBatch>) {
+ await batch.runtime.abort();
+ batch.drain();
+ await batch.pending.catch(() => undefined);
+ await batch.runtime.dispose();
+ }
+
+ const editOps = { tag: "ABCD", ops: "PUT 1.=1:\n+x" };
+
+ it("starts [Read a, Read b, Read c, Edit d] together and keeps source-order results", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("read-b", "Read", { path: "b.ts" }),
+ toolCall("read-c", "Read", { path: "c.ts" }),
+ toolCall("edit-d", "Edit", { path: "d.ts", ...editOps }),
+ ]);
+ try {
+ await vi.waitFor(() => expect([...batch.entered].sort()).toEqual(["edit-d", "read-a", "read-b", "read-c"]));
+ for (const id of ["edit-d", "read-c", "read-b", "read-a"]) {
+ batch.finish(id);
+ await Promise.resolve();
+ }
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id }) => id)).toEqual(["read-a", "read-b", "read-c", "edit-d"]);
+ } finally { await cleanup(batch); }
+ });
+
+ it("holds only Edit a behind Read a in [Read a, Edit a, Read b, Write c]", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("edit-a", "Edit", { path: "a.ts", ...editOps }),
+ toolCall("read-b", "Read", { path: "b.ts" }),
+ toolCall("write-c", "Write", { path: "c.ts", content: "c" }),
+ ]);
+ try {
+ await vi.waitFor(() => expect([...batch.entered].sort()).toEqual(["read-a", "read-b", "write-c"]));
+ batch.finish("read-b");
+ batch.finish("write-c");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(batch.entered).not.toContain("edit-a");
+ batch.finish("read-a");
+ await vi.waitFor(() => expect(batch.entered.at(-1)).toBe("edit-a"));
+ batch.finish("edit-a");
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id }) => id)).toEqual(["read-a", "edit-a", "read-b", "write-c"]);
+ } finally { await cleanup(batch); }
+ });
+
+ it.each([
+ ["[Write x, Grep]", [
+ toolCall("first", "Write", { path: "x.ts", content: "x" }),
+ toolCall("second", "Grep", { pattern: "foo" }),
+ ]],
+ ["[Edit a with MV, Read b]", [
+ toolCall("first", "Edit", { path: "a.ts", tag: "ABCD", ops: "MV moved.ts" }),
+ toolCall("second", "Read", { path: "b.ts" }),
+ ]],
+ ["[Edit a with CUT @r, Edit b with PUT @r] (named register)", [
+ toolCall("first", "Edit", { path: "a.ts", tag: "ABCD", ops: "CUT 3.=5 @r" }),
+ toolCall("second", "Edit", { path: "b.ts", tag: "ABCD", ops: "PUT <1 @r" }),
+ ]],
+ ["[Read x/a.ts, Write y/a.ts] (basename fallback)", [
+ toolCall("first", "Read", { path: "x/a.ts" }),
+ toolCall("second", "Write", { path: "y/a.ts", content: "a" }),
+ ]],
+ ] as const)("keeps %s in source order", async (_label, calls) => {
+ const batch = startBatch([...calls]);
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first"]));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(batch.entered).toEqual(["first"]);
+ batch.finish("first");
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first", "second"]));
+ batch.finish("second");
+ await batch.pending;
+ } finally { await cleanup(batch); }
+ });
+
+ it("orders an absolute and a workspace-relative spelling of one file by its full key", async () => {
+ const register = vi.spyOn(BatchPlanner.prototype, "register");
+ const batch = startBatch([
+ toolCall("first", "Read", { path: "/root/a.ts" }),
+ toolCall("second", "Write", { path: "a.ts", content: "a" }),
+ ], { projectPath: "/root" });
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first"]));
+ // The keys match in full, not only through the basename fallback.
+ expect(register.mock.calls.map(([, , claims]) => claims)).toEqual([
+ [{ kind: "path", key: "/root/a.ts", access: "shared" }],
+ [{ kind: "path", key: "/root/a.ts", access: "exclusive" }],
+ ]);
+ batch.finish("first");
+ await vi.waitFor(() => expect(batch.entered).toEqual(["first", "second"]));
+ batch.finish("second");
+ await batch.pending;
+ } finally {
+ register.mockRestore();
+ await cleanup(batch);
+ }
+ });
+
+ it("aborts an Edit still waiting behind a running Read without reaching the Host", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("edit-a", "Edit", { path: "a.ts", ...editOps }),
+ ]);
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["read-a"]));
+ await batch.runtime.abort();
+ await batch.pending.catch(() => undefined);
+ expect(batch.entered).toEqual(["read-a"]);
+ const edit = batch.events.find((event) => event.type === "tool_end" && event.toolCallId === "edit-a");
+ expect(edit.isError).toBe(true);
+ // The TOOL_ABORTED error thrown before the Host call; pi keeps its message.
+ expect(JSON.stringify(edit.result)).toContain("tool execution aborted before it started");
+ } finally { await cleanup(batch); }
+ });
+
+ it("still runs Edit a after Read a fails", async () => {
+ const batch = startBatch([
+ toolCall("read-a", "Read", { path: "a.ts" }),
+ toolCall("edit-a", "Edit", { path: "a.ts", ...editOps }),
+ ]);
+ try {
+ await vi.waitFor(() => expect(batch.entered).toEqual(["read-a"]));
+ batch.finish("read-a", { ok: false, content: "FILE_NOT_FOUND" });
+ await vi.waitFor(() => expect(batch.entered).toEqual(["read-a", "edit-a"]));
+ batch.finish("edit-a");
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id, isError }) => [id, isError])).toEqual([
+ ["read-a", true], ["edit-a", false],
+ ]);
+ } finally { await cleanup(batch); }
+ });
+
+ it("keeps a denied Write from affecting its same-batch sibling", async () => {
+ const batch = startBatch([
+ toolCall("write-a", "Write", { path: "a.ts", content: "a" }),
+ toolCall("write-b", "Write", { path: "b.ts", content: "b" }),
+ ]);
+ try {
+ // Both reach the Host before either result returns.
+ await vi.waitFor(() => expect([...batch.entered].sort()).toEqual(["write-a", "write-b"]));
+ batch.finish("write-a", { ok: false, denied: true, content: "Permission denied by the user." });
+ batch.finish("write-b");
+ await batch.pending;
+ expect(toolResults(batch.requests[1]).map(({ id, isError }) => [id, isError])).toEqual([
+ ["write-a", true], ["write-b", false],
+ ]);
+ } finally { await cleanup(batch); }
+ });
+
+ it("orders a delegate's [Read a, Edit a, Write b] without touching a concurrent parent batch", async () => {
+ const { SubagentRun: RealSubagentRun } = await vi.importActual<typeof import("./subagent.js")>("./subagent.js");
+ const writer = { name: "writer", description: "Edit", tools: ["Read", "Edit", "Write"], prompt: "Edit", source: "builtin" as const };
+ const gate = gatedHost();
+ const runtime = createRuntime({ host: gate.host, projectPath: "/root", subagents: [writer] });
+ const parentRequests: AgentMessage[][] = [];
+ (runtime as any).models = { streamSimple: scriptedStream([[
+ toolCall("parent-read", "Read", { path: "p.ts" }),
+ toolCall("parent-write", "Write", { path: "q.ts", content: "q" }),
+ ]], parentRequests) };
+ subagentRuns.calls.length = 0;
+ let parent: Promise<unknown> | undefined;
+ try {
+ await runtimeTool(runtime, "Task").execute("task-writer", { agent: "writer", task: "Edit a." });
+ const child = new RealSubagentRun({ ...subagentRuns.calls[0], signal: undefined }) as unknown as {
+ agent: { streamFunction: unknown };
+ run: () => Promise<{ status: string }>;
+ };
+ const childRequests: AgentMessage[][] = [];
+ child.agent.streamFunction = scriptedStream([[
+ toolCall("child-read-a", "Read", { path: "a.ts" }),
+ toolCall("child-edit-a", "Edit", { path: "a.ts", ...editOps }),
+ toolCall("child-write-b", "Write", { path: "b.ts", content: "b" }),
+ ]], childRequests);
+ parent = runtime.prompt("Read and write in the parent.");
+ await vi.waitFor(() => expect([...gate.entered].sort()).toEqual(["parent-read", "parent-write"]));
+ const running = child.run();
+ await vi.waitFor(() => expect(gate.entered.slice(2).sort()).toEqual(["child-read-a", "child-write-b"]));
+ gate.finish("child-write-b");
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(gate.entered).not.toContain("child-edit-a");
+ gate.finish("child-read-a");
+ // The child Edit waits only for its own batch's Read; the parent batch is still held.
+ await vi.waitFor(() => expect(gate.entered.at(-1)).toBe("child-edit-a"));
+ gate.finish("child-edit-a");
+ await expect(running).resolves.toMatchObject({ status: "completed" });
+ expect(toolResults(childRequests[1]).map(({ id }) => id)).toEqual(["child-read-a", "child-edit-a", "child-write-b"]);
+ gate.finish("parent-read");
+ gate.finish("parent-write");
+ await parent;
+ expect(toolResults(parentRequests[1]).map(({ id }) => id)).toEqual(["parent-read", "parent-write"]);
+ } finally {
+ await runtime.abort();
+ gate.drain();
+ await parent?.catch(() => undefined);
+ await runtime.dispose();
+ }
+ });
+});
+
describe("Task/read batch execution policy", () => {
const message = (...names: string[]) => assistantMessage({
content: names.map((name, index) => ({
@@ -463,9 +822,13 @@ describe("Task/read batch execution policy", () => {
[["Task", "Read"], "sequential"],
[["Task", "Glob"], "sequential"],
[["Task", "Grep"], "sequential"],
+ [["Task", "Write"], "sequential"],
+ [["Edit", "Task"], "sequential"],
[["Task", "Task"], undefined],
[["Read", "Read"], undefined],
[["Read", "Glob", "Grep"], undefined],
+ [["Write", "Edit"], undefined],
+ [["Read", "Write"], undefined],
] as const)("resolves %j to %s", (names, expected) => {
expect(resolveBatchExecutionMode(message(...names))).toBe(expected);
});
@@ -695,6 +1058,48 @@ describe("Task/read mixed-batch safety", () => {
}
});
+ it("runs [Task, Write] one call at a time without waiting for the delegate to settle", async () => {
+ const batch = setupMixedBatch([
+ taskCall("task"),
+ { type: "toolCall", id: "write", name: "Write", arguments: { path: "notes.txt", content: "n" } },
+ ]);
+ try {
+ const pending = batch.runtime.prompt("Delegate, then write.");
+ await vi.waitFor(() => expect(batch.entered).toEqual(["write"]));
+ // Sequential: the Write was only prepared after the Task call returned.
+ expect(toolIndex(batch.events, "tool_end", "task"))
+ .toBeLessThan(toolIndex(batch.events, "tool_start", "write"));
+ // Unlike a file read, the Write does not wait for the writable delegate.
+ expect(subagentRuns.instances[0].settled).toBe(false);
+ batch.release("write")!({ ok: true, content: "written" });
+ subagentRuns.resolveRun!(settled());
+ await pending;
+ } finally {
+ await teardown(batch.runtime);
+ }
+ });
+
+ it("runs [Write, Task] one call at a time", async () => {
+ const batch = setupMixedBatch([
+ { type: "toolCall", id: "write", name: "Write", arguments: { path: "notes.txt", content: "n" } },
+ taskCall("task"),
+ ]);
+ try {
+ const pending = batch.runtime.prompt("Write, then delegate.");
+ await vi.waitFor(() => expect(batch.entered).toEqual(["write"]));
+ await Promise.resolve();
+ expect(subagentRuns.instances).toEqual([]);
+ batch.release("write")!({ ok: true, content: "written" });
+ await vi.waitFor(() => expect(subagentRuns.instances).toHaveLength(1));
+ expect(toolIndex(batch.events, "tool_end", "write"))
+ .toBeLessThan(toolIndex(batch.events, "tool_start", "task"));
+ subagentRuns.resolveRun!(settled());
+ await pending;
+ } 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 {
@@ -8878,13 +9283,13 @@ describe("DesktopAgentRuntime subagents", () => {
} finally { await runtime.dispose(); }
});
- it("allows only Task and read/search tools to run in parallel", async () => {
+ it("allows only Task and file 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 (["Task", "Read", "Glob", "Grep"].includes(name)) {
+ if (["Task", "Read", "Glob", "Grep", "Write", "Edit"].includes(name)) {
expect(tool.executionMode).toBe("parallel");
continue;
}
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 2b6a4ea02..4e6711515 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -5,7 +5,8 @@ import {
} from "./mutation-recovery.js";
import { DESKTOP_AGENT_IDENTITY } from "./agent-identity.js";
import { resolveMcpToolSelection } from "./mcp-tool-selection.js";
-import { toolExecutionMode, withDynamicTaskExecutionMode } from "./tool-execution-policy.js";
+import { BatchPlanner, withBatchTurn } from "./batch-planner.js";
+import { TOOL_EXECUTION_SPECS, 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";
@@ -1927,6 +1928,8 @@ export class DesktopAgentRuntime {
private delegateWorktrees = new Map<string, string>();
/** Serializes same-path mutations across the parent and its delegates. */
private writeLocks = new PathMutex();
+ /** Orders one parallel batch's calls by the resources they claim. */
+ private batchPlanner = new BatchPlanner();
/** Complete tool registry; only the active subset is sent to the provider. */
private toolCatalog = new Map<string, AgentTool>();
/** Tools intentionally omitted from the initial provider request. */
@@ -2718,6 +2721,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
const blocked = await this.extensionToolCall(context);
if (blocked?.block) return blocked;
await this.preparePathToolCall(context);
+ this.registerBatchCall(context);
return undefined;
}
const enterKind = enterToolKind(context.toolCall.name);
@@ -4169,20 +4173,24 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// The execution mode is decided here, in one place, so no tool can grow
// 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 batch-level policy also keeps Task mixed with any file tool
+ // (Read/Glob/Grep/Write/Edit) sequential; only reads ordered after a
+ // writable Task wait for that delegate to settle.
// 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).
const builtin = this.builtinTools.has(tool);
+ const guarded = withModeExecutionGuard(
+ withExplicitRequired({
+ ...tool,
+ executionMode: builtin ? toolExecutionMode(tool.name) : "sequential",
+ }),
+ () => this.isToolAllowedInMode(tool.name) ? undefined : modeToolDenial(tool.name, this.mode),
+ );
+ // Batch ordering wraps the mode guard: a call the guard rejects must
+ // still release the calls ordered behind it in its batch.
const catalogTool = withDynamicTaskExecutionMode(
- withModeExecutionGuard(
- withExplicitRequired({
- ...tool,
- executionMode: builtin ? toolExecutionMode(tool.name) : "sequential",
- }),
- () => this.isToolAllowedInMode(tool.name) ? undefined : modeToolDenial(tool.name, this.mode),
- ),
+ builtin && TOOL_EXECUTION_SPECS[tool.name]?.claims ? withBatchTurn(guarded, this.batchPlanner) : guarded,
() => this.agent?.state.messages.at(-1),
);
if (builtin) this.builtinTools.add(catalogTool);
@@ -5129,8 +5137,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
tools: scopedTools,
beforeToolCall: async (context) => {
await this.preparePathToolCall(context, applyInstructions, builtinToolNames);
+ this.registerBatchCall(context, builtinToolNames);
return undefined;
},
+ onTurnEnd: (message) => this.batchPlanner.settleBatch(message),
onEvent: (envelope) => {
this.noteDelegationActivity(record, envelope);
this.onEvent(envelope);
@@ -6405,6 +6415,30 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
}
}
+ /**
+ * Records what a prepared builtin call will touch so the batch can order it
+ * (`withBatchTurn`). Runs after every check that can block the call. Tools
+ * without claims are sequential, or Task, whose mixed batches pi already
+ * runs sequentially.
+ */
+ private registerBatchCall(
+ context: BeforeToolCallContext,
+ builtinToolNames?: ReadonlySet<string>,
+ ): void {
+ const name = context.toolCall.name;
+ const claims = TOOL_EXECUTION_SPECS[name]?.claims;
+ if (!claims) return;
+ const selected = context.context?.tools?.find((tool) => tool.name === name);
+ const builtin = builtinToolNames ? builtinToolNames.has(name) : selected && this.builtinTools.has(selected);
+ const batch: unknown = context.assistantMessage;
+ if (!builtin || !isRecord(context.args) || !isRecord(batch)) return;
+ this.batchPlanner.register(
+ batch,
+ context.args,
+ claims(normalizeToolParams(name, context.args), this.workspaceRoot ?? this.projectPath ?? ""),
+ );
+ }
+
private async preparePathToolCall(
context: BeforeToolCallContext,
apply?: (instructions: ProjectInstructions | undefined) => void,
@@ -8829,6 +8863,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
}
break;
case "turn_end":
+ this.batchPlanner.settleBatch(event.message);
if (
this.suppressOverflowRunEnd ||
this.suppressProviderRetryRunEnd ||
diff --git a/packages/agent-runtime/src/subagent.test.ts b/packages/agent-runtime/src/subagent.test.ts
index e5bca748a..92d384110 100644
--- a/packages/agent-runtime/src/subagent.test.ts
+++ b/packages/agent-runtime/src/subagent.test.ts
@@ -35,14 +35,14 @@ describe("delegate execution policy", () => {
expect(run.agent.identity).toEqual(DESKTOP_AGENT_IDENTITY);
});
- it("preserves sequential policy for a same-name dynamic Read", () => {
+ it.each(["Read", "Write", "Edit"])("preserves sequential policy for a same-name dynamic %s", (name) => {
const { run } = createRun({ tools: [{
- name: "Read", label: "extension", description: "dynamic", parameters: Type.Object({}),
+ name, 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", () => {
+ it("runs file tools in parallel batches but fails closed for Bash and unknown tools", () => {
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: {} }),
@@ -50,7 +50,7 @@ describe("delegate execution policy", () => {
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"],
+ ["Write", "parallel"], ["Edit", "parallel"], ["Bash", "sequential"], ["plugin_unknown", "sequential"],
]);
run.setSystemPrompt("child-only path rules");
expect(run.agent.state.systemPrompt).toBe("child-only path rules");
@@ -386,6 +386,17 @@ describe("SubagentRun event forwarding", () => {
expect(events).toEqual([]);
expect(run.turns).toBe(1);
});
+
+ it("hands each finished turn's assistant message to onTurnEnd", () => {
+ const onTurnEnd = vi.fn();
+ const { run, events } = createRun({ onTurnEnd });
+ const message = assistantMessage({ content: [] });
+
+ run.handleEvent({ type: "turn_end", message, toolResults: [] });
+
+ expect(onTurnEnd).toHaveBeenCalledExactlyOnceWith(message);
+ expect(events).toEqual([]);
+ });
});
describe("SubagentRun reporting", () => {
diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.ts
index ea13c27ae..19cbddf45 100644
--- a/packages/agent-runtime/src/subagent.ts
+++ b/packages/agent-runtime/src/subagent.ts
@@ -169,6 +169,8 @@ export type SubagentRunOptions = {
tools: AgentTool[];
/** Ordered preparation owned by this delegate, never the parent's prompt state. */
beforeToolCall?: (context: BeforeToolCallContext) => Promise<BeforeToolCallResult | undefined>;
+ /** After pi ends one turn of this delegate, its tool batch included. */
+ onTurnEnd?: (message: AgentMessage) => void;
onEvent: (envelope: AgentEventEnvelope) => void;
/**
* Result of the parent's own `afterToolCall` bookkeeping for one call, so a
@@ -834,6 +836,9 @@ export class SubagentRun {
case "turn_start":
this.turns += 1;
break;
+ case "turn_end":
+ this.opts.onTurnEnd?.(event.message);
+ break;
case "message_start": {
if (event.message.role !== "assistant") break;
const content = assistantContent((event.message as AssistantMessage).content);
diff --git a/packages/agent-runtime/src/tool-execution-policy.ts b/packages/agent-runtime/src/tool-execution-policy.ts
index f04b16f0c..62c9d6e3c 100644
--- a/packages/agent-runtime/src/tool-execution-policy.ts
+++ b/packages/agent-runtime/src/tool-execution-policy.ts
@@ -1,22 +1,87 @@
-/** Batch policy only: this does not grant permissions or coordinate other agents. */
+/**
+ * Batch policy only: this does not grant permissions or coordinate other agents.
+ * Resource claims only order calls inside one assistant message; they are not a
+ * cross-agent lock (`PathMutex` and host-core keep that role).
+ */
import type { AssistantMessage } from "@earendil-works/pi-ai";
+import { normalizeLockPath } from "./path-lock.js";
+
+export type ResourceAccess = "shared" | "exclusive";
+export type ResourceClaim =
+ /** `key` is a {@link resourcePathKey}. */
+ | { kind: "path"; key: string; access: ResourceAccess }
+ /** The whole workspace. */
+ | { kind: "tree"; access: ResourceAccess };
+
+export type ToolExecutionSpec = {
+ /** pi batch mode; a tool missing from the table is sequential. */
+ mode: "parallel" | "sequential";
+ /** What one call touches, from its normalized params; parallel tools only. */
+ claims?: (params: unknown, base: string) => ResourceClaim[];
+};
+
+export const TOOL_EXECUTION_SPECS: Readonly<Record<string, ToolExecutionSpec>> = {
+ Read: { mode: "parallel", claims: (params, base) => pathClaim(params, base, "shared") },
+ Glob: { mode: "parallel", claims: () => [{ kind: "tree", access: "shared" }] },
+ Grep: { mode: "parallel", claims: () => [{ kind: "tree", access: "shared" }] },
+ Write: { mode: "parallel", claims: (params, base) => pathClaim(params, base, "exclusive") },
+ Edit: { mode: "parallel", claims: (params, base) => editClaims(params, base) },
+ // No file claims; a Task mixed with file tools runs the whole batch
+ // sequentially (`resolveBatchExecutionMode`).
+ Task: { mode: "parallel" },
+};
export function toolExecutionMode(name: string): "parallel" | "sequential" {
- switch (name) {
- case "Read":
- case "Glob":
- case "Grep":
- case "Task":
- return "parallel";
- default:
- return "sequential";
+ return TOOL_EXECUTION_SPECS[name]?.mode ?? "sequential";
+}
+
+/**
+ * Lexical, case-insensitive key for one path argument: relative paths join
+ * `base`, absolute ones (`/x`, `C:/x`, `//server/x`) stay as they are, and
+ * `.`/`..` collapse as in {@link normalizeLockPath}. No filesystem access: a
+ * remote workspace has no local filesystem and preparation must not do I/O.
+ * With an empty `base` a relative path stays unjoined (unlike
+ * `mutationFailureKey`, which falls back to the scratch directory), so
+ * relative/absolute aliases then rely on the basename fallback in `sameFile`.
+ */
+export function resourcePathKey(raw: string, base: string): string {
+ const path = raw.replaceAll("\\", "/");
+ const absolute = path.startsWith("/") || /^[A-Za-z]:/.test(path);
+ return normalizeLockPath(absolute || !base ? path : `${base}/${path}`);
+}
+
+function pathClaim(params: unknown, base: string, access: ResourceAccess): ResourceClaim[] {
+ const path = typeof params === "object" && params !== null
+ ? (params as { path?: unknown }).path
+ : undefined;
+ return typeof path === "string" && path.trim()
+ ? [{ kind: "path", key: resourcePathKey(path.trim(), base), access }]
+ : [{ kind: "tree", access }];
+}
+
+/**
+ * Whole tree for `MV` and `REM`, which touch a second path or the directory
+ * listing, and for a `CUT`/`PUT` header naming an `@register`: host-core keeps
+ * named registers per session, so another file's Edit may read or overwrite it.
+ * U+0085 joins `\s` because host-core splits headers with Rust whitespace.
+ */
+function editClaims(params: unknown, base: string): ResourceClaim[] {
+ const ops = typeof params === "object" && params !== null
+ ? (params as { ops?: unknown }).ops
+ : undefined;
+ if (typeof ops === "string" && /^[\s\u0085]*(?:MV|REM)\b|^[\s\u0085]*(?:CUT|PUT)\b[^\n]*[\s\u0085]@/m.test(ops)) {
+ return [{ kind: "tree", access: "exclusive" }];
}
+ return pathClaim(params, base, "exclusive");
}
+const FILE_TOOL_NAMES = new Set(["Read", "Glob", "Grep", "Write", "Edit"]);
+
/**
- * 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.
+ * Keep Task fan-out and file batches parallel, but preserve the old safety
+ * boundary for a batch that mixes a background delegate with file tools: the
+ * whole batch runs sequentially. Delegate write/resource coordination belongs
+ * to a later Host-owned phase.
*/
export function resolveBatchExecutionMode(
assistantMessage: AssistantMessage,
@@ -25,8 +90,8 @@ export function resolveBatchExecutionMode(
.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;
+ const hasFileTool = names.some((name) => FILE_TOOL_NAMES.has(name));
+ return hasTask && hasFileTool ? "sequential" : undefined;
}
export function resolveTaskExecutionMode(
diff --git a/scripts/e2e-parallel-read-batches.mjs b/scripts/e2e-parallel-read-batches.mjs
index ccd50e1ac..ebdfa1e49 100644
--- a/scripts/e2e-parallel-read-batches.mjs
+++ b/scripts/e2e-parallel-read-batches.mjs
@@ -2,7 +2,8 @@
// 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 { mkdtemp, mkdir, readFile, writeFile, rm } from "node:fs/promises";
+import { existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";
@@ -16,12 +17,16 @@ 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 = [
+await writeFile(join(workspace, "c.txt"), "gamma-marker\n");
+await writeFile(join(workspace, "d.txt"), "delta-marker\n");
+const readCalls = [
{ 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: "." } },
];
+/** Each scenario answers a request with tool calls, or `undefined` for the final text. */
+let respond = body => body.messages.some(message => message.role === "tool") ? undefined : readCalls;
const requests = [];
const server = createServer(async (req, res) => {
try {
@@ -34,14 +39,15 @@ const server = createServer(async (req, res) => {
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")) {
+ const calls = respond(body);
+ if (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");
} else {
- delta({ role: "assistant", content: "parallel-read-complete" });
+ delta({ role: "assistant", content: "batch-complete" });
delta({}, "stop");
}
res.end("data: [DONE]\n\n");
@@ -58,6 +64,30 @@ const returnedReads = [];
let releaseReads;
let barrier = new Promise(resolve => { releaseReads = resolve; });
let barrierTimeout = setTimeout(releaseReads, 10_000);
+/** Host dispatch timeline and results of every tools.execute, by call id. */
+const dispatch = [];
+const hostResults = new Map();
+/** Calls whose Host response waits until all of them have been dispatched. */
+let gated = new Set();
+let gatedEntered = new Set();
+let releaseGate = () => {};
+let gate = Promise.resolve();
+function holdUntilAllEnter(ids) {
+ gated = new Set(ids);
+ gatedEntered = new Set();
+ gate = new Promise(resolve => { releaseGate = resolve; });
+ const timer = setTimeout(releaseGate, 10_000);
+ return () => clearTimeout(timer);
+}
+const toolMessages = request => request.messages.filter(message => message.role === "tool");
+async function runTurn(session, prompt) {
+ turnId = await beginTurn(host, session.id);
+ const before = requests.length;
+ await runtime.prompt(prompt, `fixture-user-${before}`, turnId);
+ await endTurn(host, turnId);
+ turnId = undefined;
+ return requests.slice(before);
+}
try {
await host.start(PROTOCOL_VERSION);
const session = await createSession(host, workspace, "Parallel reads");
@@ -65,13 +95,23 @@ try {
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);
- if (method === "tools.execute" && ["read-a", "read-b"].includes(args.toolCallId)) {
+ dispatch.push(`${args.toolCallId}:end`);
+ hostResults.set(args.toolCallId, result);
+ if (["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");
}
+ if (gated.has(args.toolCallId)) {
+ gatedEntered.add(args.toolCallId);
+ if (gatedEntered.size === gated.size) releaseGate();
+ await gate;
+ assert.equal(gatedEntered.size, gated.size, `${[...gated].join(", ")} did not all dispatch before the first response was released`);
+ }
return result;
};
runtime = new DesktopAgentRuntime({
@@ -87,8 +127,8 @@ try {
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));
+ const results = toolMessages(requests[1]);
+ assert.deepEqual(results.map(message => message.tool_call_id), readCalls.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/);
@@ -105,25 +145,125 @@ try {
let child;
const apply = instructions => child.setSystemPrompt(`Child rules: ${JSON.stringify(instructions)}`);
const parentPrompt = runtime.agent.state.systemPrompt;
+ // The same delegate hooks the runtime installs for a Task run.
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),
+ beforeToolCall: async context => {
+ await runtime.preparePathToolCall(context, apply, names);
+ runtime.registerBatchCall(context, names);
+ return undefined;
+ },
+ onTurnEnd: message => runtime.batchPlanner.settleBatch(message),
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.deepEqual(toolMessages(requests[3]).map(message => message.tool_call_id), readCalls.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");
+ releaseReads();
+ clearTimeout(barrierTimeout);
+
+ // [Read a, Write b, Read c]: no claim conflicts, so all three reach Host
+ // before any response is released, and results keep source order.
+ const mixed = [
+ { id: "mixed-read-a", name: "Read", arguments: { path: "a.txt" } },
+ { id: "mixed-write-b", name: "Write", arguments: { path: "b.txt", content: "written-marker\n" } },
+ { id: "mixed-read-c", name: "Read", arguments: { path: "c.txt" } },
+ ];
+ respond = body => toolMessages(body).some(m => m.tool_call_id === "mixed-read-a") ? undefined : mixed;
+ let stopGate = holdUntilAllEnter(mixed.map(call => call.id));
+ const mixedRequests = await runTurn(session, "Read a, write b, read c.");
+ stopGate();
+ assert.deepEqual([...gatedEntered].sort(), mixed.map(call => call.id).sort());
+ assert.equal(await readFile(join(workspace, "b.txt"), "utf8"), "written-marker\n");
+ const mixedResults = toolMessages(mixedRequests.at(-1)).filter(message => message.tool_call_id.startsWith("mixed-"));
+ assert.deepEqual(mixedResults.map(message => message.tool_call_id), mixed.map(call => call.id));
+ assert.match(JSON.stringify(mixedResults[0].content), /alpha-marker/);
+ assert.match(JSON.stringify(mixedResults[2].content), /gamma-marker/);
+ gated = new Set();
+
+ // [Read a, Edit a]: the Edit claims the file the Read shares, so Host sees
+ // read:start, read:end, edit:start. The Edit uses the tag of a real Read
+ // from the previous model step and must succeed.
+ let tag;
+ respond = body => {
+ const results = toolMessages(body);
+ if (!results.some(m => m.tool_call_id === "tag-read")) {
+ return [{ id: "tag-read", name: "Read", arguments: { path: "a.txt" } }];
+ }
+ if (!results.some(m => m.tool_call_id === "order-edit")) {
+ tag = /\[a\.txt#([0-9A-Fa-f]{4})\]/.exec(JSON.stringify(results.find(m => m.tool_call_id === "tag-read").content))?.[1];
+ assert.ok(tag, "the fixture Read returned no hashline tag");
+ return [
+ { id: "order-read", name: "Read", arguments: { path: "a.txt" } },
+ { id: "order-edit", name: "Edit", arguments: { path: "a.txt", tag, ops: "PUT >$:\n+edited-marker" } },
+ ];
+ }
+ return undefined;
+ };
+ dispatch.length = 0;
+ await runTurn(session, "Read a, then edit it.");
+ assert.deepEqual(
+ dispatch.filter(entry => entry.startsWith("order-")),
+ ["order-read:start", "order-read:end", "order-edit:start", "order-edit:end"],
+ );
+ assert.equal(hostResults.get("order-edit")?.ok, true, `Edit failed: ${JSON.stringify(hostResults.get("order-edit"))}`);
+ assert.match(await readFile(join(workspace, "a.txt"), "utf8"), /alpha-marker\n[\s\S]*edited-marker/);
+
+ // Two same-batch Writes to different files each leave a review snapshot;
+ // rolling both back restores both files.
+ const writes = [
+ { id: "rollback-write-c", name: "Write", arguments: { path: "c.txt", content: "overwritten-c\n" } },
+ { id: "rollback-write-d", name: "Write", arguments: { path: "d.txt", content: "overwritten-d\n" } },
+ ];
+ respond = body => toolMessages(body).some(m => m.tool_call_id === "rollback-write-c") ? undefined : writes;
+ await runTurn(session, "Overwrite c and d.");
+ assert.equal(await readFile(join(workspace, "c.txt"), "utf8"), "overwritten-c\n");
+ assert.equal(await readFile(join(workspace, "d.txt"), "utf8"), "overwritten-d\n");
+ for (const { id } of writes) {
+ const snapshotId = hostResults.get(id)?.content?.review?.snapshotId;
+ assert.ok(snapshotId, `${id} left no review snapshot`);
+ const outcome = await host.call("review.rollback", { sessionId: session.id, snapshotId });
+ assert.equal(outcome.status ?? outcome.outcome?.status, "rolledBack", JSON.stringify(outcome));
+ }
+ assert.equal(await readFile(join(workspace, "c.txt"), "utf8"), "gamma-marker\n");
+ assert.equal(await readFile(join(workspace, "d.txt"), "utf8"), "delta-marker\n");
+
+ // Ask mode: both same-batch Writes wait for approval at the same time;
+ // denying one does not affect the other.
+ await configureSession(host, session, "agent", "ask");
+ const asks = [
+ { id: "ask-write-e", name: "Write", arguments: { path: "e.txt", content: "denied\n" } },
+ { id: "ask-write-f", name: "Write", arguments: { path: "f.txt", content: "approved\n" } },
+ ];
+ respond = body => toolMessages(body).some(m => m.tool_call_id === "ask-write-e") ? undefined : asks;
+ const asked = runTurn(session, "Write e and f.");
+ const permissionFor = id => host.notifications.find(n => n.method === "permissions.request" && n.params?.toolCallId === id);
+ for (let attempt = 0; attempt < 200 && !asks.every(({ id }) => permissionFor(id)); attempt += 1) {
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ assert.ok(asks.every(({ id }) => permissionFor(id)), "both Writes should await approval together");
+ await host.call("permissions.resolve", { requestId: permissionFor("ask-write-e").params.requestId, decision: "deny" });
+ await host.call("permissions.resolve", { requestId: permissionFor("ask-write-f").params.requestId, decision: "allow-once" });
+ const askRequests = await asked;
+ assert.equal(existsSync(join(workspace, "e.txt")), false);
+ assert.equal(await readFile(join(workspace, "f.txt"), "utf8"), "approved\n");
+ const askResults = toolMessages(askRequests.at(-1)).filter(message => message.tool_call_id.startsWith("ask-"));
+ assert.deepEqual(askResults.map(message => message.tool_call_id), asks.map(call => call.id));
+ assert.equal(hostResults.get("ask-write-e")?.ok, false);
+ assert.equal(hostResults.get("ask-write-f")?.ok, true);
+ assert.equal(events.some(event => event.type === "error"), false);
+ console.log("PASS parallel-read E2E: local HTTP provider, parent/delegate concurrent Read dispatch, real Read/Glob/Grep, source-order results, parent prompt isolation; [Read, Write, Read] overlap, [Read a, Edit a] Host order with a real tag, two-Write rollback, concurrent ask-mode approvals");
} finally {
releaseReads();
+ releaseGate();
clearTimeout(barrierTimeout);
await runtime?.dispose();
if (turnId) await endTurn(host, turnId, "error");