@henryqw/pi-subagent 5.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CONTEXT.md CHANGED
@@ -2,21 +2,21 @@
2
2
 
3
3
  ## Purpose
4
4
 
5
- Provide validated built-in and user Roles, shared task-model Pi launch policy, generic managed Herdr Subagent hosting, generic `delegate_task` delegation, and package-owned `delegate_flow` Git orchestration. `delegate_task` remains a flat bounded delegation tool; Flow uses effective Implementer and Reviewer Roles while owning its fixed implementation, validation, exact review, integration, and cleanup mechanics. The bundled Main-side Skill adds no runtime behavior or changes generic fallback.
5
+ Provide validated built-in and user Roles, shared task-model Pi launch policy, generic managed Herdr Subagent hosting, generic `delegate_task` delegation, and package-owned `delegate_flow` Git orchestration. Main plans and orchestrates; `delegate_task` remains a flat bounded delegation tool, while Flow uses the effective Implementer and only invokes its effective Reviewer for explicit judgment criteria after authoritative validation. The bundled Main-side Skill adds no runtime behavior or changes generic fallback.
6
6
 
7
7
  ## Domain glossary
8
8
 
9
- - **Main**: Pi session delegating work.
9
+ - **Main**: Pi session that plans and orchestrates delegated work.
10
10
  - **Subagent**: isolated Pi child process handling one task.
11
11
  - **Role**: package-shipped built-in or user-owned Markdown definition of a reusable responsibility, with a name, description, system instructions, required `tools`, `extensions`, and `skills` arrays, and optional isolation.
12
- - **Model Class**: `fast`, `balanced`, `frontier`, or `fav`, assigned in shared task-model settings or overridden by Main from task complexity.
12
+ - **Model Class**: `fast`, `balanced`, `frontier`, or `fav`, resolved through shared task-model settings; Main normally selects `fast`, may select `balanced` upfront for obvious complexity, and leaves direct model/thinking overrides to explicit user requests.
13
13
  - **Route**: configured model and thinking-level pair selected from a shared Model Class profile; the primary route precedes its optional fallback.
14
14
  - **Delegated Task**: one bounded work request sent from Main to one Role.
15
15
  - **Workflow**: generic orchestration of one or more Delegated Tasks; `delegate_task` owns its selected mode, while library callers compose executor runs in JavaScript.
16
16
  - **Workflow Mode**: `delegate_task` tool policy selected per call for `single`, `parallel`, or `chain` execution; not a Role property or executor API.
17
17
  - **Flow**: package-owned, memory-only Git implementation and integration workflow started by `delegate_flow`.
18
- - **Unit Worktree**: one Flow-owned worktree and branch for one Flow unit; it is reused for rebase, validation, review, and one repair.
19
- - **Review Packet**: exact `{base, tip, patchPath}` evidence delivered to the Flow Reviewer in the Unit Worktree.
18
+ - **Unit Worktree**: one Flow-owned worktree and branch for one Flow unit; it is reused for rebase, validation, optional exact review, and one repair.
19
+ - **Review Packet**: exact `{base, tip, patchPath}` evidence delivered to the Flow Reviewer only for a unit's explicit `review` criterion.
20
20
  - **Resource Policy**: Role ownership of base tools, extensions, and Skill names, plus explicit caller additions of tools, extensions, and environment through `createRoleLaunch`.
21
21
  - **Pi Launch**: reusable `{env,args}` policy for one Role, resolved model route, explicit caller resources, and project trust.
22
22
  - **Ephemeral Executor**: mechanism that receives a prepared Pi Launch, runs one bounded Delegated Task in one no-session child process, and returns its result without discovering resources or composing a Workflow.
@@ -28,11 +28,11 @@ Provide validated built-in and user Roles, shared task-model Pi launch policy, g
28
28
  - Up to five active ephemeral `delegate_task` children run per Main by default, configurable via `maxSubagents` in `~/.pi/agent/config/pi-subagent/pi-subagent.json` or the `PI_SUBAGENT_MAX_SUBAGENTS` environment variable; excess calls wait FIFO. Queued calls do not start a child or consume child timeout. Managed Herdr workers are unaffected.
29
29
  - Ambient child extensions and Skills stay disabled. Every Role requires `tools`, `extensions`, and `skills` YAML arrays, and every launch installs the Role tool policy. `tools: []` activates no base built-ins but does activate all tools from explicitly selected trusted extension bundles and explicit caller tool additions; `skills: []` selects no separately named Role Skills but trusted selected extension Skills still load; `extensions: []` selects no Role extension bundle. A Role/caller explicitly selected extension is a trusted atomic capability bundle: all tools it registers and all Skills supplied through its Pi package metadata or dynamic `resources_discover` load alongside separately named Role Skills. This intentionally includes the extension's executable lifecycle/prompt behavior; pi-subagent does not infer or externally narrow undocumented dependencies, and loading an extension is not sandboxing. Scope children by selecting fewer trusted extensions; finer granularity requires separate entry points/configuration or an upstream split. Explicit Role/caller tool names still verify against the final filtered registry, while parent-only recursive orchestration tools remain excluded.
30
30
  - Role Skill names resolve through Main's effective Pi Skill registry; unavailable names warn and skip without blocking delegation. Explicit Role/caller tool names verify against the final filtered child registry after explicit provider `session_start` handlers, and unavailable names fail before the first turn.
31
- - Main selects Role and may override Model Class and thinking level per task; omitted class uses shared `pi-subagent/delegateTask` assignment, initially `balanced`. Library callers select Role plus their own shared task ID.
31
+ - Main policy populates direct `model` and `thinking` only for explicit user overrides; otherwise it selects only `modelClass` (`fast` normally, `balanced` upfront for obvious complexity). This has no provenance tracking or runtime enforcement. An omitted class uses the shared `pi-subagent/delegateTask` assignment; library callers select a Role plus their own shared task ID.
32
32
  - The selected profile resolves primary then fallback only before launch when a route, model, or thinking level is unavailable. If neither route is usable, launch rejects with `Run /task-models`; a started child is never retried by this package.
33
33
  - User Role Markdown files and Subagent JSON config live only in the user `config/pi-subagent` directory; model routes live in shared `config/pi-task-models.json`. Package-shipped built-in Roles (`implementer`, `reviewer`) resolve from the package's own `examples/roles/` Markdown through the same parser; a same-named user file explicitly overrides a built-in for `delegate_task` and `delegate_flow`.
34
- - `delegate_flow` accepts 1–8 independent units with direct validation commands. At Flow start, it resolves and freezes the effective Implementer and Reviewer Roles through any continuation. One active Flow creates every Unit Worktree before launching Implementers in parallel, then processes settled units in declared order. For each unit Flow rebases in place when earlier units advanced Main, validates in that worktree, sends the exact Review Packet to the Reviewer in the same worktree, and integrates only exact `PASS` using `git merge --ff-only` with the full reviewed OID.
35
- - Flow is memory-only. Only a post-rebase commit drop produces a no-op (`base === tip`); it validates, skips Reviewer and merge, then cleans up ordinarily. Initial zero-commit implementations block. Implementer, validation, or reviewer blocks allow one `delegate_flow_continue({ guidance })` repair in the same worktree; a second block is terminal. Rebase and evidence/Reviewer/infrastructure failures retain worktrees. A reported fast-forward failure retains its worktree unless Main is clean at the exact reviewed tip, which completes with the merge diagnostic as a warning. Cleanup uses non-forced worktree removal and branch deletion; cleanup refusal is a completion warning.
34
+ - `delegate_flow` accepts 1–8 independent units with direct validation commands, optional `modelClass`, and optional non-empty `review` judgment text. Omitted classes use the shared `pi-subagent/delegateTask` assignment; each unit's current class resolves through its shared profile route for its Implementer and, when `review` exists, Reviewer. At Flow start it always resolves/freezes the effective Implementer and resolves/freezes a Reviewer only when at least one requested unit has `review`. One active Flow creates every Unit Worktree before launching Implementers in parallel, then processes settled units in declared order. For each unit Flow rebases in place when earlier units advanced Main, inspects committed Git state, and runs declared validation. Validation is authoritative for objective verification: units without `review` fast-forward their exact validated tip; units with `review` send the exact Review Packet to the Reviewer in the same worktree and require exact `PASS` before the same guarded `git merge --ff-only` path.
35
+ - Flow is memory-only. Only a post-rebase commit drop produces a no-op (`base === tip`); it validates, skips Reviewer and merge, then cleans up ordinarily. Initial zero-commit implementations block. Implementer, validation, or reviewer blocks allow one `delegate_flow_continue({ guidance, modelClass? })` repair in the same worktree; omission retains the Unit's current class and presence replaces it for that repair. A second block is terminal. Rebase and evidence/Reviewer/infrastructure failures retain worktrees. A reported fast-forward failure retains its worktree unless Main is clean at the exact integrated tip, which completes with the merge diagnostic as a warning. Cleanup uses non-forced worktree removal and branch deletion; cleanup refusal is a completion warning.
36
36
  - Flow has no graph, saved recovery, automatic retry, aggregate review, or post-merge validation. It never changes generic `delegate_task` Role resolution, isolation, non-Git fallback, or ordinary direct plan/file review.
37
37
  - Numbered Codex routes prefer Main's active account slot and explicitly load the multi-Codex child extension.
38
38
  - Generic Herdr host functions validate workspace ownership and provisioning identity while callers retain domain state, prompts, and lifecycle decisions.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # `@henryqw/pi-subagent`
2
2
 
3
- Delegate bounded work to isolated Pi child processes. Generic `delegate_task` selects one flat single, parallel, or chain mode. Package-owned `delegate_flow` runs a fixed Git implementation-and-review Flow. Package authors can reuse the same Role launch policy and active-Pi executor from JavaScript.
3
+ Delegate bounded work to isolated Pi child processes. Main plans and orchestrates; generic `delegate_task` selects one flat single, parallel, or chain mode. Package-owned `delegate_flow` runs a fixed Git implementation-and-verification Flow. Package authors can reuse the same Role launch policy and active-Pi executor from JavaScript.
4
4
 
5
5
  ## Why
6
6
 
@@ -30,6 +30,8 @@ pi install npm:@henryqw/pi-subagent
30
30
  | `delegate_flow` | tool | Package-owned parallel implementation and declared-order Git integration for 1–8 independent units. |
31
31
  | `delegate_flow_continue` | tool | Repair the blocked Flow unit once in its existing worktree. |
32
32
 
33
+ All three delegation tool blocks use a compact self-rendered shell and never exceed five physical lines, including Pi's leading spacer: one call line plus at most three result lines in either collapsed or expanded view.
34
+
33
35
  ### `delegate_task`
34
36
 
35
37
  Select exactly one shape:
@@ -45,13 +47,13 @@ Select exactly one shape:
45
47
  { chain: [{ role, task, model?, modelClass?, thinking? }], background? }
46
48
  ```
47
49
 
48
- `model` is `provider/modelId` and overrides `modelClass`. `modelClass` is `fast`, `balanced`, `frontier`, or `fav`; omission uses the shared `pi-subagent/delegateTask` assignment. `background` applies to the entire selected mode and is never a per-delegation field.
50
+ `model` is `provider/modelId` and overrides `modelClass`. Main populates `model` and `thinking` only for an explicit user override; otherwise it chooses only `modelClass`—`fast` normally, or `balanced` upfront for obviously complex work. This is Main policy only: the runtime records no provenance and does not enforce it. `modelClass` is `fast`, `balanced`, `frontier`, or `fav`; omission uses the shared `pi-subagent/delegateTask` assignment. `background` applies to the entire selected mode and is never a per-delegation field.
49
51
 
50
52
  Parallel mode starts entries concurrently, waits for every entry, and reports them in input order. Chain mode is sequential and fail-fast; every literal `{previous}` receives only the immediately preceding successful assistant output. Foreground failures throw after retaining bounded sibling and recovery evidence. One tool call has one aggregate 50 KiB Main-visible transport cap, not 50 KiB per child.
51
53
 
52
54
  Background workflows are session-scoped. Session shutdown or reload aborts them and may deliver only recoverable-work evidence or no follow-up message.
53
55
 
54
- The transient status widget owns live progress: spinner or terminal state, wrapped task summary, model, thinking level, tokens, and duration; at capacity, it evicts the oldest terminal row so new active work remains visible, and terminal rows otherwise clear on the next real user input. The final `delegate_task` block is deliberately minimal: bounded final summaries, role attribution for parallel/chain, and only retained-worktree recovery paths. It has no expanded view.
56
+ The transient two-line status widget owns deterministic live progress: status and task summary above thinking or the active tool (with elapsed time and path basename), completed turns, started tools, model, thinking level, tokens, and total duration; terminal activity is Done, Failed, or Stopped. At capacity, it evicts the oldest terminal row so new active work remains visible, and terminal rows otherwise clear on the next real user input. The final `delegate_task` block is deliberately minimal: bounded final summaries, role attribution for parallel/chain, and only retained-worktree recovery paths. It has no expanded view.
55
57
 
56
58
  Each delegation resolves its own Role, resources, route, and optional worktree request. When available, `isolation: worktree` gives each entry a deterministic separate worktree; non-Git or unborn-`HEAD` contexts may use Main's cwd. Siblings and chain steps never implicitly share one created worktree.
57
59
 
@@ -59,18 +61,20 @@ See [Orchestration, isolation, and the public API](./docs/orchestration.md) for
59
61
 
60
62
  ### `delegate_flow`
61
63
 
62
- Use Flow only for independent, commuting Git changes. It accepts 1–8 uniquely identified units, each with a bounded task and direct command/argument validation gate:
64
+ Use Flow only for independent, commuting Git changes. It accepts 1–8 uniquely identified units, each with a bounded task, optional `modelClass`, direct command/argument validation gate, and optional non-empty `review` judgment criterion:
63
65
 
64
66
  ```text
65
- delegate_flow({ units: [{ id, task, validation: [{ command, args }] }] })
66
- delegate_flow_continue({ guidance })
67
+ delegate_flow({ units: [{ id, task, modelClass?, validation: [{ command, args }], review? }] })
68
+ delegate_flow_continue({ guidance, modelClass? })
67
69
  ```
68
70
 
69
- One memory-only Flow may be active. At start it resolves the effective `implementer` and `reviewer` Roles, including same-named user overrides, and freezes them through any continuation. Overrides must remain compatible with Flow: Implementers commit scoped work, and Reviewers inspect the exact packet and emit exactly `PASS` only with zero findings. It creates one Unit Worktree per unit, runs Implementers in parallel, then processes settled results in declared order. For each unit, Flow rebases onto the current Flow Main when needed, runs its declared validation, gives the Reviewer the exact `{base, tip, patchPath}` packet in that same worktree, and only exact `PASS` permits `git merge --ff-only` of the full reviewed OID. It removes the worktree and branch non-forcibly after integration; a refusal is a completion warning with the retained worktree path and/or branch.
71
+ Objective verification is authoritative. Flow always inspects committed Git state and runs declared validation. A unit without `review` skips review evidence and Reviewer launch, then fast-forwards its exact validated tip through the existing guarded `git merge --ff-only` path. Add `review` only for an explicit judgment that automation cannot establish; that unit retains the exact `{base, tip, patchPath}` protocol and requires exact `PASS` before the same integration path.
72
+
73
+ One memory-only Flow may be active. At start it resolves/freezes the effective `implementer` Role, including a same-named user override, and resolves/freezes the effective `reviewer` only if at least one requested unit has `review`. Omitted `modelClass` uses the shared `pi-subagent/delegateTask` assignment; a selected class resolves through its shared profile model-and-thinking route for the unit's Implementer and, when applicable, Reviewer. It creates one Unit Worktree per unit, runs Implementers in parallel, then processes settled results in declared order. It removes the worktree and branch non-forcibly after integration; a refusal is a completion warning with the retained worktree path and/or branch.
70
74
 
71
- A rebase that drops all unit commits is a no-op: Flow validates it, skips Reviewer and merge, then cleans up ordinarily. Implementer, validation, or review blocks can be repaired once through `delegate_flow_continue` in the same worktree. Rebase and infrastructure failures are terminal. A reported fast-forward failure completes with its diagnostic as a warning only when Git left Main clean at the exact reviewed tip; otherwise it is terminal and retains the affected worktree. Flow has no graph, saved recovery, automatic retry, aggregate review, or post-merge gate.
75
+ A rebase that drops all unit commits is a no-op: Flow validates it, skips Reviewer and merge, then cleans up ordinarily. Implementer, validation, or review blocks can be repaired once through `delegate_flow_continue` in the same worktree. Omitted continuation `modelClass` retains the blocked unit's current class; a supplied class replaces it for that one repair. Rebase and infrastructure failures are terminal. A reported fast-forward failure completes with its diagnostic as a warning only when Git left Main clean at the exact integrated tip; otherwise it is terminal and retains the affected worktree. Flow has no graph, saved recovery, automatic retry, aggregate review, or post-merge gate.
72
76
 
73
- `delegate_task` remains generic with its ordinary isolation behavior. Flow uses the same effective Role resolution for `implementer` and `reviewer`; without user overrides, the package-shipped Roles remain the defaults.
77
+ `delegate_task` remains generic with its ordinary isolation behavior. Flow uses the package-shipped Implementer by default and the package-shipped Reviewer only when a unit requests review; same-named user Roles remain supported overrides.
74
78
 
75
79
  ## Config
76
80
 
@@ -109,7 +113,7 @@ An unreadable or invalid Role file fails role loading fast; duplicate role names
109
113
  The package ships two working built-in Roles, always available without any configuration:
110
114
 
111
115
  - `implementer`: focused edits requesting worktree isolation; commits completed scoped changes locally and never pushes or opens PRs without authorization
112
- - `reviewer`: read-only correctness review of supplied plans/files, or of Flow's exact `{base, tip, patchPath}` packet in its Unit Worktree; never edits or commits
116
+ - `reviewer`: read-only correctness review of supplied plans/files, or—only when a Flow unit declares `review`—of Flow's exact `{base, tip, patchPath}` packet in its Unit Worktree; never edits or commits
113
117
 
114
118
  A same-named Markdown file in `~/.pi/agent/config/pi-subagent/` explicitly overrides the built-in default.
115
119
 
@@ -131,7 +135,7 @@ The package never installs or writes Role configuration. Sample names are not bu
131
135
 
132
136
  ## Skill
133
137
 
134
- The bundled [`pi-subagent-delegated-development`](./skills/pi-subagent-delegated-development/SKILL.md) Skill is Main-side policy only. `delegate_flow` owns its fixed Git mechanics; the Skill adds no runtime code, configuration, or Role installation. Generic orchestration remains outside the executor under [ADR 001](./docs/adr/001-composable-ephemeral-execution.md).
138
+ The bundled [`pi-subagent-delegated-development`](./skills/pi-subagent-delegated-development/SKILL.md) Skill is Main-side planner/orchestrator policy only. `delegate_flow` owns its fixed Git mechanics and validation authority; the Skill adds no runtime code, configuration, or Role installation. Generic orchestration remains outside the executor under [ADR 001](./docs/adr/001-composable-ephemeral-execution.md).
135
139
 
136
140
  A Role explicitly owns base tools, extensions, named Skills, instructions, and optional `isolation: worktree`. Every launch installs its Role tool policy: `tools: []` activates no base built-ins, while trusted selected extension tools and explicit caller tool additions still activate. `skills: []` selects no separately named Role Skills, while trusted selected extension Skills still load; `extensions: []` selects no Role extension bundle. Ambient extension and Skill discovery is disabled in children. Selecting an extension explicitly is selecting a trusted atomic capability bundle, not just a provider path: every tool it registers and every Skill supplied through its Pi package metadata or dynamic `resources_discover` loads alongside separately named Role Skills. This is intentional because an extension may depend on its own tools, Skills, lifecycle, and prompt behavior; loading it permits that executable behavior and is not sandboxing. To scope a child, select fewer trusted extensions. Finer-grained selection requires separate extension entry points/configuration or an upstream split—pi-subagent does not infer or externally narrow undocumented dependencies. Parent-only recursive orchestration tools stay excluded. Explicit Role or caller tool names are verified against the child’s final filtered active registry after provider extensions finish `session_start`; all unavailable names fail before the first model turn with provider-extension guidance, while unavailable named Skills warn and skip.
137
141
 
@@ -8,10 +8,23 @@ export interface EphemeralSubagentExecutorOptions {
8
8
  maxConcurrency: number;
9
9
  timeout: EphemeralSubagentTimeout;
10
10
  }
11
+ export type EphemeralSubagentActivityEvent = {
12
+ type: "tool_execution_start";
13
+ toolCallId: string;
14
+ toolName: string;
15
+ path?: string;
16
+ } | {
17
+ type: "tool_execution_end";
18
+ toolCallId: string;
19
+ toolName: string;
20
+ } | {
21
+ type: "message_end";
22
+ };
11
23
  export interface EphemeralSubagentRunInput {
12
24
  signal?: AbortSignal;
13
25
  onUpdate?: (text: string) => void;
14
26
  onTokens?: (tokens: number) => void;
27
+ onActivity?: (event: EphemeralSubagentActivityEvent) => void;
15
28
  prepare: () => Promise<{
16
29
  launch: PiLaunch;
17
30
  task: string;
package/dist/ephemeral.js CHANGED
@@ -4,6 +4,9 @@ import { basename } from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  const MAX_OUTPUT_BYTES = 50 * 1024;
6
6
  const MAX_JSON_EVENT_BYTES = 1024 * 1024;
7
+ const MAX_ACTIVITY_TEXT_BYTES = 4 * 1024;
8
+ // A JSON string byte can take six source bytes (for example, \u0000).
9
+ const MAX_ACTIVITY_PREFIX_BYTES = 2 * MAX_ACTIVITY_TEXT_BYTES * 6 + 1024;
7
10
  const MAX_TIMER_DELAY_MS = 2_147_483_647;
8
11
  const POST_EXIT_STDIO_IDLE_MS = 250;
9
12
  const POST_EXIT_STDIO_HARD_MS = 1_000;
@@ -34,6 +37,8 @@ const PI_JSON_EVENTS = {
34
37
  };
35
38
  const CONSUMED_JSON_EVENTS = new Set(["message_start", "message_update", "message_end"]);
36
39
  const JSON_EVENT_TYPE = /^\s*\{\s*"type"\s*:\s*"([^"\\]+)"/;
40
+ const JSON_STRING = `"(?:[^"\\\\\u0000-\u001f]|\\\\(?:["\\\\/bfnrt]|u[0-9a-fA-F]{4}))*"`;
41
+ const JSON_OVERSIZED_TOOL_START = new RegExp(`^\\s*\\{\\s*"type"\\s*:\\s*"tool_execution_start"\\s*,\\s*"toolCallId"\\s*:\\s*(${JSON_STRING})\\s*,\\s*"toolName"\\s*:\\s*(${JSON_STRING})(?=\\s*,)`);
37
42
  export class EphemeralSubagentError extends Error {
38
43
  name = "EphemeralSubagentError";
39
44
  code;
@@ -85,11 +90,15 @@ function validateRunInput(value) {
85
90
  if (input.onTokens !== undefined && typeof input.onTokens !== "function") {
86
91
  throw new TypeError("run.onTokens must be a function.");
87
92
  }
93
+ if (input.onActivity !== undefined && typeof input.onActivity !== "function") {
94
+ throw new TypeError("run.onActivity must be a function.");
95
+ }
88
96
  return {
89
97
  signal: input.signal,
90
98
  prepare: input.prepare,
91
99
  onUpdate: input.onUpdate,
92
100
  onTokens: input.onTokens,
101
+ onActivity: input.onActivity,
93
102
  };
94
103
  }
95
104
  function record(value, field) {
@@ -229,6 +238,33 @@ function assistantText(message) {
229
238
  .join("\n");
230
239
  return text || undefined;
231
240
  }
241
+ function activityTooLong(value) {
242
+ return typeof value === "string" && Buffer.byteLength(value, "utf8") > MAX_ACTIVITY_TEXT_BYTES;
243
+ }
244
+ function hasTerminalControlChars(text) {
245
+ return Array.from(text).some((character) => {
246
+ const code = character.codePointAt(0);
247
+ return code <= 0x1f || code >= 0x7f && code <= 0x9f || code === 0x2028 || code === 0x2029;
248
+ });
249
+ }
250
+ function activityText(value) {
251
+ return typeof value === "string" && value.trim().length > 0 && !activityTooLong(value) && !hasTerminalControlChars(value);
252
+ }
253
+ function oversizedToolStart(prefix) {
254
+ const match = JSON_OVERSIZED_TOOL_START.exec(prefix);
255
+ if (!match)
256
+ return;
257
+ try {
258
+ const toolCallId = JSON.parse(match[1]);
259
+ const toolName = JSON.parse(match[2]);
260
+ if (!activityText(toolCallId) || !activityText(toolName))
261
+ return;
262
+ return { type: "tool_execution_start", toolCallId, toolName };
263
+ }
264
+ catch {
265
+ return;
266
+ }
267
+ }
232
268
  function utf8Prefix(text, maxBytes) {
233
269
  return new StringDecoder().write(Buffer.from(text).subarray(0, maxBytes));
234
270
  }
@@ -471,16 +507,26 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
471
507
  signalCallbackFailure();
472
508
  stop(true);
473
509
  };
510
+ let activityQueue = Promise.resolve();
474
511
  const invokeCallback = (name, callback, value) => {
475
512
  if (!callback || callbackFailure)
476
513
  return;
477
514
  let pending;
478
- try {
479
- pending = Promise.resolve(callback(value)).then(undefined, (cause) => { failCallback(name, cause); });
515
+ if (name === "onActivity") {
516
+ pending = activityQueue.then(() => {
517
+ if (!callbackFailure)
518
+ return callback(value);
519
+ }).catch((cause) => { failCallback(name, cause); });
520
+ activityQueue = pending;
480
521
  }
481
- catch (cause) {
482
- failCallback(name, cause);
483
- return;
522
+ else {
523
+ try {
524
+ pending = Promise.resolve(callback(value)).then(undefined, (cause) => { failCallback(name, cause); });
525
+ }
526
+ catch (cause) {
527
+ failCallback(name, cause);
528
+ return;
529
+ }
484
530
  }
485
531
  pendingCallbacks.add(pending);
486
532
  void pending.then(() => pendingCallbacks.delete(pending));
@@ -550,6 +596,29 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
550
596
  }
551
597
  return;
552
598
  }
599
+ if (record.type === "tool_execution_start" || record.type === "tool_execution_end") {
600
+ const { toolCallId, toolName } = record;
601
+ if (!activityText(toolCallId) || !activityText(toolName))
602
+ return;
603
+ if (record.type === "tool_execution_start") {
604
+ const args = record.args;
605
+ const path = args && typeof args === "object" && !Array.isArray(args)
606
+ ? args.path
607
+ : undefined;
608
+ if (activityTooLong(path))
609
+ return;
610
+ invokeCallback("onActivity", input.onActivity, {
611
+ type: "tool_execution_start",
612
+ toolCallId,
613
+ toolName,
614
+ ...(activityText(path) ? { path } : {}),
615
+ });
616
+ }
617
+ else {
618
+ invokeCallback("onActivity", input.onActivity, { type: "tool_execution_end", toolCallId, toolName });
619
+ }
620
+ return;
621
+ }
553
622
  if (record.type !== "message_end")
554
623
  return;
555
624
  const text = assistantText(record.message);
@@ -566,6 +635,7 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
566
635
  currentTokens = 0;
567
636
  currentUsage = undefined;
568
637
  invokeCallback("onTokens", input.onTokens, completedTokens);
638
+ invokeCallback("onActivity", input.onActivity, { type: "message_end" });
569
639
  }
570
640
  if (typeof message.stopReason === "string")
571
641
  stopReason = message.stopReason;
@@ -628,7 +698,9 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
628
698
  const end = newline === -1 ? data.length : newline;
629
699
  const part = data.slice(offset, end);
630
700
  if (!ignoreLine) {
631
- linePrefix += part.slice(0, Math.max(0, 256 - linePrefix.length));
701
+ const remainingPrefix = MAX_ACTIVITY_PREFIX_BYTES - Buffer.byteLength(linePrefix, "utf8");
702
+ if (remainingPrefix > 0)
703
+ linePrefix += utf8Prefix(part, remainingPrefix);
632
704
  const eventType = JSON_EVENT_TYPE.exec(linePrefix)?.[1];
633
705
  if (eventType && !lineEventType)
634
706
  lineEventType = eventType;
@@ -652,6 +724,13 @@ async function runPi(prepared, input, timeoutPolicy, invocation) {
652
724
  return;
653
725
  if (!ignoreLine)
654
726
  processLine(lineParts.join(""));
727
+ else if (lineEventType === "tool_execution_start") {
728
+ const activity = oversizedToolStart(linePrefix);
729
+ if (activity) {
730
+ observeEvent();
731
+ invokeCallback("onActivity", input.onActivity, activity);
732
+ }
733
+ }
655
734
  if (callbackFailure)
656
735
  return;
657
736
  lineParts = [];
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { type HerdrExecutor } from "@henryqw/pi-herdr";
3
3
  import { type AvailableModel, type ProfileName, type ResolvedTaskRoute, type ThinkingLevel } from "@henryqw/pi-task-models";
4
- export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, EphemeralSubagentError, formatDuration, type EphemeralSubagentErrorCode, type EphemeralSubagentExecutor, type EphemeralSubagentExecutorOptions, type EphemeralSubagentResult, type EphemeralSubagentRunInput, type EphemeralSubagentTimeout, } from "./ephemeral.ts";
4
+ export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, EphemeralSubagentError, formatDuration, type EphemeralSubagentActivityEvent, type EphemeralSubagentErrorCode, type EphemeralSubagentExecutor, type EphemeralSubagentExecutorOptions, type EphemeralSubagentResult, type EphemeralSubagentRunInput, type EphemeralSubagentTimeout, } from "./ephemeral.ts";
5
5
  export { createChildWorktree, finalizeChildWorktree, inspectIndexFlags, inspectWorktreeDirty, WorktreeSetupError, worktreeContextNote, type WorktreeDirtyInspection, type WorktreeInfo, type WorktreePayload, } from "./worktree.ts";
6
6
  export { prepareExactReviewEvidence, REVIEW_MAX_PATCH_BYTES, REVIEW_MAX_PATHS, type PreparedReviewEvidence, type PrepareExactReviewEvidenceInput, } from "./review-evidence.ts";
7
7
  export declare const ROLE_TOOL_POLICY_FLAG = "pi-subagent-role-tools";
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## Decision
4
4
 
5
- The public task executor is an execution mechanism: it receives a prepared Pi Launch, runs one bounded Delegated Task, and returns the result. `delegate_task` selects its flat `single`, `parallel`, or `chain` tool policy; those modes are not executor primitives.
5
+ The public task executor is an execution mechanism: it receives a prepared Pi Launch, runs one bounded Delegated Task, and returns the result. Main plans and orchestrates; `delegate_task` selects its flat `single`, `parallel`, or `chain` tool policy, while those modes are not executor primitives.
6
6
 
7
7
  Generic callers compose workflows with JavaScript. Fan-out and fan-in use promises and collections; sequencing uses ordinary control flow; review loops use explicit caller-owned bounds. The package does not define a recursive workflow AST.
8
8
 
@@ -14,6 +14,8 @@ Resource Policy is split at launch preparation:
14
14
 
15
15
  Built-in `implementer` and `reviewer` Roles ship as Markdown in `examples/roles/` and use the same parser as user Roles. For generic delegation, a same-named user Role explicitly overrides a built-in. The package does not install, copy, or write user configuration.
16
16
 
17
+ Main populates direct `model` and `thinking` only for explicit user overrides; otherwise it chooses only `modelClass` (`fast` normally, `balanced` upfront for obvious complexity). This is tool policy, not executor provenance tracking or runtime enforcement.
18
+
17
19
  ## Scope boundary
18
20
 
19
21
  `delegate_flow` is a fixed package-owned Git workflow, documented in [ADR 002](./002-package-owned-delegate-flow-orchestration.md). It reuses the prepared-child runner but is not a general executor workflow primitive: it has its own fixed unit, worktree, validation, review, integration, and cleanup contract. `delegate_task` and library callers remain generic.
@@ -2,21 +2,21 @@
2
2
 
3
3
  ## Decision
4
4
 
5
- `delegate_task` remains the generic bounded Role tool described by [ADR 001](./001-composable-ephemeral-execution.md). `delegate_flow` is a separate package-owned Git workflow with this fixed interface:
5
+ `delegate_task` remains the generic bounded Role tool described by [ADR 001](./001-composable-ephemeral-execution.md). Main plans and orchestrates; `delegate_flow` is a separate package-owned Git workflow with this fixed interface:
6
6
 
7
7
  ```ts
8
- delegate_flow({ units: [{ id, task, validation: [{ command, args }] }] });
9
- delegate_flow_continue({ guidance });
8
+ delegate_flow({ units: [{ id, task, modelClass?, validation: [{ command, args }], review? }] });
9
+ delegate_flow_continue({ guidance, modelClass? });
10
10
  ```
11
11
 
12
- A Flow accepts 1–8 independent units with unique IDs. Only one memory-only Flow may be active. At start it resolves the effective `implementer` and `reviewer` Roles, including same-named user overrides, and freezes them through any continuation. It requires a clean committed attached Main branch and creates one Unit Worktree per unit before launching Implementers in parallel. All started Implementers settle; Flow then processes units in declared order.
12
+ A Flow accepts 1–8 independent units with unique IDs. `modelClass` is optional and otherwise uses the shared `pi-subagent/delegateTask` assignment; its class resolves through the existing `pi-task-models` profile model-and-thinking route for the unit's Implementer and, when applicable, Reviewer. `review` is optional non-empty text for the explicit judgment that declared validation cannot establish.
13
13
 
14
- For each unit, Flow verifies Main, rebases the Unit Worktree in place when earlier Flow units advanced Main, runs the declared validation commands there, and gives the Reviewer the exact `{base, tip, patchPath}` packet in that same worktree. Reviewer output whose trimmed text equals `PASS` approves. Flow then fast-forwards Main with the full reviewed OID and uses non-forced worktree removal and branch deletion. Cleanup refusal does not undo integration; it returns completion with retained worktree path and/or branch warnings.
14
+ Only one memory-only Flow may be active. At start it resolves/freezes the effective `implementer` Role, including a same-named user override. It resolves/freezes the effective `reviewer` Role only when at least one requested unit has `review`. It requires a clean committed attached Main branch and creates one Unit Worktree per unit before launching Implementers in parallel. All started Implementers settle; Flow then processes units in declared order.
15
15
 
16
- If rebase drops all unit commits, `base === tip` is a no-op. Flow validates the state, skips Reviewer and merge, then cleans up ordinarily.
16
+ For each unit, Flow verifies Main, rebases the Unit Worktree in place when earlier Flow units advanced Main, inspects committed Git state, and runs declared validation. Validation is authoritative for objective verification. Without `review`, Flow skips exact evidence and Reviewer launch, then fast-forwards the exact validated tip through the existing guarded `git merge --ff-only` path. With `review`, it gives the Reviewer the exact `{base, tip, patchPath}` packet in that same worktree; only trimmed output exactly equal to `PASS` permits the same full-OID fast-forward. Cleanup uses non-forced worktree removal and branch deletion; cleanup refusal does not undo integration and returns completion with retained-work warnings.
17
17
 
18
- Implementer failure, dirty or missing committed work, validation failure, and reviewer findings block the first affected declared unit. `delegate_flow_continue({ guidance })` reruns the Flow's frozen Implementer Role in that same Unit Worktree once and derives, validates, and reviews again. A second block is terminal. A failed rebase is aborted and terminates as an infrastructure failure with Git diagnostics; other infrastructure failures also terminate it. A reported fast-forward failure completes with its diagnostic as a warning only when Main is clean at the exact reviewed tip; otherwise it is terminal. Terminal outcomes retain worktrees for Main to reslice, and earlier integrations are never rolled back.
18
+ If rebase drops all unit commits, `base === tip` is a no-op. Flow validates the state, skips Reviewer and merge, then cleans up ordinarily. Implementer failure, dirty or missing committed work, validation failure, and reviewer findings block the first affected declared unit. `delegate_flow_continue({ guidance, modelClass? })` launches a fresh ephemeral child with the frozen Implementer Role in that same Unit Worktree once, with original requirements, authoritative validation, previous block evidence, and Main guidance. Omitted continuation class retains the Unit's current class; a supplied class replaces it for that one repair, including any subsequent Reviewer launch. A second block is terminal. Failed rebase, evidence/Reviewer, and other infrastructure failures retain worktrees. A reported fast-forward failure completes with its diagnostic as a warning only when Main is clean at the exact integrated tip; otherwise it is terminal. Earlier integrations are never rolled back.
19
19
 
20
20
  ## Consequences
21
21
 
22
- Flow owns its narrow deterministic Git protocol while allowing user-owned Implementer and Reviewer policy through same-named Role overrides. Overrides do not change Flow's validation, exact review packet, approval, integration, or cleanup protocol. Flow has no dependency graph, saved recovery, automatic retry, aggregate review, or post-merge validation. Units that overlap files, APIs, schemas, generated output, package metadata, lockfiles, or invariants must be combined or sequenced outside Flow.
22
+ Flow owns narrow deterministic Git mechanics while allowing user-owned Implementer and conditional Reviewer policy through same-named Role overrides. Overrides do not change validation authority, exact review protocol, approval, integration, or cleanup. Flow has no dependency graph, saved recovery, automatic retry, aggregate review, post-merge validation, Planner Role, or generic-role restriction. Units that overlap files, APIs, schemas, generated output, package metadata, lockfiles, or invariants must be combined or sequenced outside Flow.
@@ -10,9 +10,9 @@ caller-owned task, cwd, signal ────────────────
10
10
  active-Pi ephemeral executor
11
11
  ```
12
12
 
13
- `delegate_task` owns its flat single/parallel/chain policy. The public executor runs one prepared delegation. Downstream packages compose their own workflows with ordinary JavaScript and own semantic protocols, shared workspace/state, retry decisions, and bounds. There is no recursive workflow AST.
13
+ Main plans and orchestrates. `delegate_task` owns its flat single/parallel/chain policy, while the public executor runs one prepared delegation. Downstream packages compose their own workflows with ordinary JavaScript and own semantic protocols, shared workspace/state, retry decisions, and bounds. There is no recursive workflow AST.
14
14
 
15
- `delegate_flow` is the exception: it is a fixed package-owned Git workflow, not an executor primitive or general workflow language. It uses the effective `implementer` and `reviewer` Roles and the same prepared-child runner; its contract is below.
15
+ `delegate_flow` is the exception: it is a fixed package-owned Git workflow, not an executor primitive or general workflow language. It uses the effective `implementer` Role and, only for explicit judgment review, the effective `reviewer` Role through the same prepared-child runner; its contract is below.
16
16
 
17
17
  ## Frozen `delegate_task` contract
18
18
 
@@ -67,11 +67,11 @@ Single mode puts one delegation's fields at the top level.
67
67
  | --- | --- | --- |
68
68
  | `role` | yes | Name of a Role in the user's effective `config/pi-subagent` directory or a package-shipped built-in (`implementer`, `reviewer`); a same-named user file overrides the built-in. |
69
69
  | `task` | yes | Non-empty bounded task packet. |
70
- | `model` | no | Designated `provider/modelId`; takes precedence over `modelClass`. |
71
- | `modelClass` | no | `fast`, `balanced`, `frontier`, or `fav`; omission uses shared task assignment. |
72
- | `thinking` | no | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`; route selection skips models that cannot honor it. |
70
+ | `model` | no | Designated `provider/modelId`; takes precedence over `modelClass`, and Main supplies it only for an explicit user override. |
71
+ | `modelClass` | no | `fast`, `balanced`, `frontier`, or `fav`; Main normally chooses `fast`, may choose `balanced` upfront for obvious complexity, and omission uses shared task assignment. |
72
+ | `thinking` | no | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`; Main supplies it only for an explicit user override. Route selection skips models that cannot honor it. |
73
73
 
74
- Those five fields are the complete delegation object. `tasks`, `chain`, and `background` cannot be nested. Route fallback occurs only before launch; a started child is never retried by this package.
74
+ Those five fields are the complete delegation object. The direct-model/thinking rule is Main-facing policy only: the runtime adds no provenance tracking or enforcement. `tasks`, `chain`, and `background` cannot be nested. Route fallback occurs only before launch; a started child is never retried by this package.
75
75
 
76
76
  ### Background, failures, and transport
77
77
 
@@ -83,9 +83,9 @@ All Main-visible text for one tool call shares one aggregate 50 KiB UTF-8 transp
83
83
 
84
84
  ## `delegate_flow`
85
85
 
86
- `delegate_flow({ units })` accepts 1–8 units with unique non-empty `id` and `task` fields plus one or more direct `{command, args}` validation commands. `delegate_flow_continue({ guidance })` is available only for the one blocked unit of the active Flow.
86
+ `delegate_flow({ units })` accepts 1–8 units with unique non-empty `id` and `task`, one or more direct `{command, args}` validation commands, optional `modelClass`, and optional non-empty `review` text. `delegate_flow_continue({ guidance, modelClass? })` is available only for the one blocked unit of the active Flow.
87
87
 
88
- A Flow is memory-only and permits one active Flow. At start it resolves the effective `implementer` and `reviewer` Roles, including same-named user overrides, and freezes them through any continuation. Overrides must preserve the Flow Role protocols: Implementers commit scoped work, and Reviewers inspect the exact packet and emit exactly `PASS` only with zero findings. It requires clean committed Git Main and creates every Unit Worktree before launching work; setup failure launches no Implementer. Each unit gets exactly one worktree and one Implementer. Implementers run in parallel and all settle. Flow then processes units in declared order:
88
+ A Flow is memory-only and permits one active Flow. At start it always resolves/freezes the effective `implementer` Role, including a same-named user override. It resolves/freezes the effective `reviewer` only if at least one requested unit declares `review`. Omitted unit classes use the shared `pi-subagent/delegateTask` assignment; a selected class resolves through its existing `pi-task-models` profile model-and-thinking route for the unit's Implementer and, when applicable, Reviewer. It requires clean committed Git Main and creates every Unit Worktree before launching work; setup failure launches no Implementer. Each unit gets exactly one worktree and one Implementer. Implementers run in parallel and all settle. Flow then processes units in declared order:
89
89
 
90
90
  ```text
91
91
  Implementers (parallel, one Unit Worktree each)
@@ -93,19 +93,20 @@ Implementers (parallel, one Unit Worktree each)
93
93
  v
94
94
  for each declared unit:
95
95
  rebase in its Unit Worktree when earlier units advanced Main
96
- run declared validation in that worktree
97
- read-only Reviewer receives exact {base, tip, patchPath} there
98
- exact PASS git merge --ff-only <full reviewed OID>
96
+ inspect committed state; run declared validation (objective authority)
97
+ ├─ no review: git merge --ff-only <exact validated tip>
98
+ └─ review: Reviewer receives exact {base, tip, patchPath}
99
+ exact PASS → git merge --ff-only <full reviewed OID>
99
100
  git worktree remove; git branch -d
100
101
  ```
101
102
 
102
- Flow derives identity from Git, not child output. Reviewer reads the exact patch as authoritative and may use the same worktree only for referenced context. A full-OID fast-forward is the only integration path. Cleanup is non-forced; after a successful integration, cleanup refusal returns `completed` with a retained path/branch warning.
103
+ Flow derives identity from Git, not child output. Add `review` only for an explicit judgment criterion that automated validation cannot establish; it is not a second generic verification pass. The Reviewer reads the exact patch as authoritative and may use the same worktree only for referenced context. A full-OID fast-forward is the only integration path. Cleanup is non-forced; after a successful integration, cleanup refusal returns `completed` with a retained path/branch warning.
103
104
 
104
- If rebase drops all unit commits, `base === tip` is a no-op: Flow validates current state, skips Reviewer and merge, then cleans up ordinarily. Implementer failure, dirty or missing committed work, validation failure, or reviewer findings block the first affected declared unit. `delegate_flow_continue({ guidance })` reruns the Flow's frozen Implementer Role in that same worktree once, then repeats derivation, validation, and review with fresh exact evidence. A second block is terminal. A failed rebase is aborted and terminates as an infrastructure failure with Git diagnostics; other infrastructure failures are terminal. A reported fast-forward failure completes with its diagnostic as a warning only when Main is clean at the exact reviewed tip; otherwise it is terminal. Terminal outcomes retain worktrees for Main to reslice. Earlier integrated units are never rolled back.
105
+ If rebase drops all unit commits, `base === tip` is a no-op: Flow validates current state, skips Reviewer and merge, then cleans up ordinarily. Implementer failure, dirty or missing committed work, validation failure, or reviewer findings block the first affected declared unit. `delegate_flow_continue({ guidance, modelClass? })` reruns the Flow's frozen Implementer Role in that same worktree once, then repeats derivation, validation, and conditional review with fresh exact evidence. Omitting continuation `modelClass` retains the blocked unit's current class; providing it replaces that class for the one repair. A second block is terminal. A failed rebase is aborted and terminates as an infrastructure failure with Git diagnostics; other infrastructure failures are terminal. A reported fast-forward failure completes with its diagnostic as a warning only when Main is clean at the exact integrated tip; otherwise it is terminal. Terminal outcomes retain worktrees for Main to reslice. Earlier integrated units are never rolled back.
105
106
 
106
107
  Flow has no dependency graph, saved state, automatic retry, aggregate review, or post-merge validation. Use it only for commuting changes; combine or sequence units that overlap files, APIs, schemas, generated output, package metadata, lockfiles, or invariants.
107
108
 
108
- `delegate_task` remains generic: its optional worktree isolation, non-Git behavior, and direct plan/file review are unchanged. Flow uses the same effective Role resolution for `implementer` and `reviewer`, with package-shipped Roles as defaults.
109
+ `delegate_task` remains generic: its optional worktree isolation, non-Git behavior, and direct plan/file review are unchanged. Flow uses package-shipped Roles as defaults while retaining same-named user Role overrides; the Reviewer is needed only for a requested review criterion.
109
110
 
110
111
  ## Per-delegation resources and isolation
111
112
 
@@ -164,7 +165,7 @@ const executorOptions = {
164
165
  };
165
166
  ```
166
167
 
167
- Concurrency is FIFO. `run` accepts optional `signal`, `onUpdate(text)`, and `onTokens(number)` callbacks plus required `prepare()`. A queued run receives its permit before `prepare` executes, so resource and route resolution can use the latest Pi state. Queued time does not consume child timeout. `maxConcurrency`, `idleMs`, and `maxMs` must be positive; `maxMs` must exceed `idleMs`.
168
+ Concurrency is FIFO. `run` accepts optional `signal`, `onUpdate(text)`, `onTokens(number)`, and `onActivity(event)` callbacks plus required `prepare()`. A queued run receives its permit before `prepare` executes, so resource and route resolution can use the latest Pi state. Queued time does not consume child timeout. `maxConcurrency`, `idleMs`, and `maxMs` must be positive; `maxMs` must exceed `idleMs`.
168
169
 
169
170
  The executor is **active-Pi-only**. It reuses the currently running Pi invocation and does not locate or support a standalone Node.js Pi installation. Once direct Pi exits, stdout/stderr drain normally until EOF; an escaped descendant retaining either stream is cut off after short output inactivity or a one-second hard deadline so it cannot retain the FIFO permit.
170
171
 
@@ -230,6 +231,18 @@ async function runRole(role, task, options = {}) {
230
231
 
231
232
  `run` resolves to `EphemeralSubagentResult`. Both outcome variants contain `exitCode`, `output`, `stderr`, and optional `stopReason`, `errorMessage`, and `usage`. A launched child/model failure is a typed `{ outcome: "failure", ... }` result. Abort, timeout, spawn, protocol, preparation, and callback failures reject with `EphemeralSubagentError` and a stable `code`. Assistant `output` and `stderr` are bounded, and `usage` contains aggregate child usage when Pi supplies it.
232
233
 
234
+ ### Activity callbacks
235
+
236
+ The optional `onActivity` callback receives structured activity events serially in child JSON-event order. This ordering applies only to `onActivity`; `onUpdate` and `onTokens` remain independent. A thrown or rejected activity callback fails the run with an `EphemeralSubagentError` whose code is `callback`.
237
+
238
+ | Event type | Fields |
239
+ | --- | --- |
240
+ | `tool_execution_start` | `toolCallId: string`, `toolName: string`, `path?: string` |
241
+ | `tool_execution_end` | `toolCallId: string`, `toolName: string` |
242
+ | `message_end` | none |
243
+
244
+ Activity text is limited to 4 KiB per field. An invalid `toolCallId` or `toolName`, or an oversized `path`, drops the event. A blank path or one containing C0/C1 terminal controls or Unicode line/paragraph separators is omitted from an otherwise valid start event.
245
+
233
246
  The low-level executor does not interpret `Role.isolation`, discover resources, compose modes, create shared state, or promote child failure outcomes to tool errors. A direct caller that wants worktrees must call `createChildWorktree` after the permit, choose the returned `cwd`, call `finalizeChildWorktree` on every exit path, and preserve its recovery payload.
234
247
 
235
248
  Generic managed Herdr exports (`managedSubagentWorkspaceId`, reconciliation helpers, `startManagedSubagent`, prompting/listing, and retirement) consume the same launch policy for durable workers. They intentionally contain no workflow prompts, semantic state, or retry policy.
@@ -356,7 +369,7 @@ The package ships two working built-in Roles, validated by the same parser as us
356
369
  | Built-in | Behavior |
357
370
  | --- | --- |
358
371
  | `implementer` | Focused implementation requesting `isolation: worktree`; commits scoped changes locally, never pushes or opens PRs without authorization. Non-Git or unborn-`HEAD` contexts may use Main's cwd. |
359
- | `reviewer` | Read-only correctness review of supplied plans/files, or Flow's exact `{base, tip, patchPath}` packet in its Unit Worktree; never edits or commits. |
372
+ | `reviewer` | Read-only correctness review of supplied plans/files, or—when a Flow unit declares `review`—Flow's exact `{base, tip, patchPath}` packet in its Unit Worktree; never edits or commits. |
360
373
 
361
374
  A same-named Markdown file in `config/pi-subagent/` explicitly overrides the built-in default.
362
375
 
@@ -376,6 +389,6 @@ cp <package-install-dir>/examples/roles/scout.md ~/.pi/agent/config/pi-subagent/
376
389
 
377
390
  The package never creates, copies, updates, or removes files in `~/.pi/agent/config/pi-subagent/`. Once copied, the files and their names are entirely user-owned.
378
391
 
379
- The bundled [`pi-subagent-delegated-development`](../skills/pi-subagent-delegated-development/SKILL.md) Skill is Main-side policy only. `delegate_flow` owns its fixed Git mechanics; the Skill defines no runtime code or configuration. `delegate_task` remains the generic flat single/parallel/chain mechanism.
392
+ The bundled [`pi-subagent-delegated-development`](../skills/pi-subagent-delegated-development/SKILL.md) Skill is Main-side planner/orchestrator policy only. `delegate_flow` owns its fixed Git mechanics and objective validation authority; the Skill defines no runtime code or configuration. `delegate_task` remains the generic flat single/parallel/chain mechanism.
380
393
 
381
394
  See [ADR 001](./adr/001-composable-ephemeral-execution.md) for the executor boundary and [ADR 002](./adr/002-package-owned-delegate-flow-orchestration.md) for Flow.
@@ -15,9 +15,9 @@ Perform a read-only correctness review of one bounded change.
15
15
  Support exactly two review modes:
16
16
 
17
17
  1. For ordinary delegation, review the supplied plan and explicitly named files directly. Do not prepare Git, require commits, or require a patch packet.
18
- 2. For Flow exact review, require a Review Packet `{base, tip, patchPath}` and the same assigned Unit Worktree context. Read that exact patch as authoritative, then read only the files it references and relevant contract context. Do not infer a diff from a branch or another worktree.
18
+ 2. For Flow exact review, only when the task supplies an explicit judgment criterion, require a Review Packet `{base, tip, patchPath}` and the same assigned Unit Worktree context. Declared validation is authoritative for objective verification; judge only that criterion. Read the exact patch as authoritative, then read only the files it references and relevant criterion context. Do not infer a diff from a branch or another worktree.
19
19
 
20
- In either mode, review only the supplied requirements and explicitly referenced context. Use only `read`, `grep`, `find`, or `ls` for that review. Check correctness, regressions, trust-boundary validation, error handling, and missing high-value tests. Do not run commands or tests. Never manage Main, Git, or tests; never edit or write files, commit, push, or otherwise modify state.
20
+ In either mode, review only the supplied requirements and explicitly referenced context. Use only `read`, `grep`, `find`, or `ls` for that review. For ordinary delegation, check correctness, regressions, trust-boundary validation, error handling, and missing high-value tests. Do not run commands or tests. Never manage Main, Git, or tests; never edit or write files, commit, push, or otherwise modify state.
21
21
 
22
22
  Never invoke external LLM APIs, SDKs, agent harnesses, or model CLIs.
23
23