@henryqw/pi-subagent 29.1.2 → 30.0.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
@@ -13,7 +13,7 @@ The Pi session and checkout that coordinate delegated work.
13
13
  A named capability definition with instructions, tools, trusted extension sources, Skills, optional MCP servers, and an optional Model Class default. A Role does not select isolation.
14
14
 
15
15
  **Model Class**:
16
- A `fast`, `balanced`, `frontier`, or `fav` choice resolved through Pi Task Models.
16
+ A `fast`, `balanced`, `frontier`, `ultra`, or `fav` choice resolved through Pi Task Models.
17
17
 
18
18
  **Direct task**:
19
19
  A bounded task in Main's shared checkout with declared `read` or `write` access. Authorized writes take effect immediately, without rollback or checked integration.
@@ -22,7 +22,7 @@ A bounded task in Main's shared checkout with declared `read` or `write` access.
22
22
  A display and continuation reference for one recorded direct worker, such as `D7.1`. It does not grant ownership of that worker.
23
23
 
24
24
  **Continued worker**:
25
- A new direct worker that resumes a finished worker's saved Pi conversation in a new tab with a new Direct reference.
25
+ A direct worker that resumes a saved Pi conversation after the previous worker stops. It receives a new Direct reference.
26
26
 
27
27
  **Checkout admission**:
28
28
  The exclusive permission held by a direct write request or managed background writer that prevents Main and other direct writers from writing to the shared checkout. Pi Herdr supplies the shared process-local coordinator. Each owner keeps admission until termination is proven or a human explicitly waives a recovered reservation. A waiver does not prove termination; read classification is not a sandbox.
package/README.md CHANGED
@@ -1,131 +1,30 @@
1
1
  # `@henryqw/pi-subagent`
2
2
 
3
- Delegate bounded work to configured Pi Roles through [Herdr](https://herdr.dev/). Direct tasks share your checkout; isolated tasks produce checked candidates for explicit integration. Both return a handle so Main can continue working.
4
-
5
- ![Pi showing six delegated tasks running in parallel](./example.png)
3
+ Delegate bounded tasks to Pi workers. Direct tasks share your checkout. Isolated tasks produce candidates for checked integration.
6
4
 
7
5
  ## Install
8
6
 
9
- Requires Pi 1.5.0 or later in the 1.x series for native user-input status and schema support. Isolated work requires Herdr 0.9.3 or later for both the client and server. The server must run on API protocol 22 or later.
10
-
11
- ```bash
12
- pi install npm:@henryqw/pi-task-models
7
+ ```sh
13
8
  pi install npm:@henryqw/pi-subagent
14
9
  ```
15
10
 
16
- Configure the profiles that your Roles use in `/task-models`. Direct writer termination proof requires native `lsof`.
17
-
18
- **Upgrade to 29.0.0:** Older saved workers without their original lease identity cannot continue. Unverified recovery cannot automatically release checkout protection. Keep their records. If the full reservation scope is known, use `/subagent` to review the evidence and explicitly approve release with the exact typed reservation identity. **This does not stop workers or prove termination; a worker can still change any listed checkout.** If scope is unknown, release stays blocked; restore authoritative evidence first.
11
+ If you use Billion Context for compression, set `pi.subagents` to `false` in `~/.config/billion-context/billion-context.json`. If you set `BILI_CONFIG_FILE`, edit that file instead. Restart Pi after you change the setting.
19
12
 
20
- ## Works with
21
-
22
- | Package | Relationship | Purpose |
23
- | --- | --- | --- |
24
- | [`@henryqw/pi-task-models`](https://pi.henry.wang/extensions/pi-task-models) | Required | Provides model routes for delegated Roles. |
13
+ Configure the required role profiles with `/task-models`. Direct tasks run in native Pi. For visible worker tabs or isolated tasks, use Herdr client and server version 0.9.3 or later.
25
14
 
26
15
  ## Use
27
16
 
28
- Type `/subagent ` to see described choices for `roles`, `recover`, and `prune`. After `prune`, completion offers `cancel`. Completion keeps the full subcommand prefix.
29
-
30
- Ask Main: “Have a scout trace sign-in without editing files.” Main calls `delegate_task` and stays available until progress and results arrive.
17
+ Ask a scout to trace a function and report the relevant files. Main uses `delegate_task` to dispatch the work. Use `/subagent` to inspect or recover a worker.
31
18
 
32
- If Pi Goal is installed, it waits for live subagent results instead of adding empty continuation turns; see the [pending-result contract](./CONTEXT.md#pending-result-event-contract).
19
+ Print and JSON sessions receive the direct result in the tool call. Interactive and remote control sessions receive one follow-up when the workers finish. Set `wait` to `true` for an inline answer in these sessions.
33
20
 
34
- Commands, prompts, and UI are for you. Tools and the packaged skill are for Main, except `git_read`, which is only for Role-declared children. `codemode` scripts can call only `subagent_status`.
21
+ Direct workers share 4,096 bytes of inline answer text per request. A short answer appears once. The result links to a private file for each oversized answer. A chain passes the complete answer to its next worker.
35
22
 
36
- | Surface | Type | Purpose |
37
- | --- | --- | --- |
38
- | `/subagent` | command | Browse work; stop workers, send follow-ups, or delete owned worktrees after confirmation. Without interactive UI, only reports. |
39
- | `/subagent roles` | command | List Role sources, resources, resolved model and thinking level, route errors, and file errors. Read-only; requires no Herdr pane. |
40
- | `/subagent prune` | command | Collect finished tabs and scan leftover worktrees; run again to review and confirm deletion. Requires a running Herdr server. Without interactive UI, only collects and reports. |
41
- | `/subagent prune cancel` | command | Cancel the scan, ready plan, or cleanup. An active removal step can finish; completed removals are not undone. |
42
- | `/review [target] [focus]` | prompt | Tell Main to review a change with parallel `reviewer` tasks and give one ship verdict. See [Review a change](#review-a-change). |
43
- | `/subagent recover` | command | Classify interrupted isolated work in the canonical repository. Send Main request IDs, blockers, and next actions. Requires no UI or Herdr pane. |
44
- | `delegate_task` | tool | Start authorized shared-checkout work or a durable isolated checked graph. With `dryRun: true`, check the request and show the resolved plan without a launch. |
45
- | `subagent_status` | tool | Read saved isolated state, exact identities, failed review verdicts, and allowed continuation. Does not replay work. Supports structured output for `codemode`. |
46
- | `subagent_resume` | tool | Perform the reported `retry`, `verify`, or `finalize` continuation, not staging or integration. Same-worker correction retries accept optional `instruction` text. |
47
- | `subagent_stage` | tool | Stage, resolve, reject, or revise an exact candidate. Rejecting a staged candidate freezes its generation. |
48
- | `subagent_integrate` | tool | Advance dependents, refresh, validate, correct, promote, reconcile, clean up promotion, or release rejected and superseded resources. |
49
- | `subagent_abort` | tool | Terminate an isolated request without discarding retained work. Retained candidates and integration work require release or proof of absence. |
50
- | `git_read` | tool | Let Role-declared children inspect bounded local Git evidence without Bash, tests, network access, or writes. Not available to Main. |
51
- | `pi-subagent` | skill | Guide Main through authorization, delegation, checks, integration, and recovery. |
52
- | Direct status widget (`D`) | ui | Show direct references, names, Role badges, status, routes, elapsed time, measured task tokens, cost, and tool activity in the TUI. |
53
- | Isolated status widget (`I`) | ui | Show recorded task state, Role/model-class badges, and retained workspaces in the TUI. Readiness does not mean promotion. |
23
+ Use the `scout`, `reviewer`, `implementer`, `planner`, or `oracle` role. Main can cancel an owned workflow with `mode: "cancel"` and its exact `id`.
54
24
 
55
- ### Direct workflow
25
+ The [delegation measurements](./docs/measurement.md) compare parent results and report live worker usage.
56
26
 
57
- A read-only task:
58
-
59
- ```json
60
- {
61
- "mode": "direct",
62
- "role": "scout",
63
- "name": "Map sign-in flow",
64
- "task": "Trace sign-in through session creation. Report files and risks. Do not edit files.",
65
- "access": "read"
66
- }
67
- ```
68
-
69
- Choose exactly one shape:
70
-
71
- ```text
72
- Single: { mode: "direct", role, name, task, access, ... }
73
- Parallel: { mode: "direct", tasks: [{ role, name, task, access, ... }] }
74
- Chain: { mode: "direct", chain: [{ role, name, task, access, ... }] }
75
- ```
76
-
77
- Every task requires `access: "read"` or `access: "write"`. Declare `write` for file, Git, or external-resource changes. **Read access is not enforced and is not a sandbox.** The worker keeps its Role's tools.
78
-
79
- Read requests run parallel tasks up to `maxSubagents`. Chains run in order, replace literal `{previous}` with the preceding successful answer, and stop on failure. Any `write` task makes the whole request serial and reserves checkout admission until all owned workers stop.
80
-
81
- Checkout admission is shared with managed background commands from `pi-herdr-tools`. An active or unknown background writer blocks direct writes. Main writes and direct writers block new command launches. Status and read tools remain available. This is process-local coordination, not an operating-system sandbox.
82
-
83
- Direct writer admission survives `/reload` through a native Pi session journal. `/subagent` lists held reservations from all branches, including reservations without a tab. Use local Close for locally owned work. Recovered records cannot stop workers.
84
-
85
- They permit release only from complete saved proof, or through a separate warned human release with an exact typed reservation identity. Reload requires explicit release authority and the matching saved proof or typed waiver evidence. **A human release does not prove termination: a worker can still change any listed checkout.** All evidence stays saved. Missing reservation scope or an incompatible coordinator blocks recovery; see [Reload and session changes](./docs/orchestration.md#reload-and-session-changes).
86
-
87
- Direct writes change Main's checkout immediately, including dirty checkouts, and have no automatic checks or rollback. Preserve unrelated edits. See [Direct contract](./docs/orchestration.md#direct-contract) for write scope and checkout-admission rules.
88
-
89
- Each write task must end with a JSON completion object; [Direct contract](./docs/orchestration.md#direct-contract) gives its format. Plain text, a malformed object, blocked work, or failure stops later dispatch. Success is the worker's report, not independent validation.
90
-
91
- A write task can declare `"paths": ["src/**"]` with repo-relative globs. The result lists new commits and changed paths and flags paths outside `paths`. This is a report only, not enforcement. A read result warns `checkout changed during task; result may be stale`. See [Checkout change reports](./docs/orchestration.md#checkout-change-reports).
92
-
93
- Add `"dryRun": true` to do the launch checks and show the resolved plan; see [Dry run](./docs/orchestration.md#dry-run). It launches nothing.
94
-
95
- The launch returns a task ID and first Herdr tab, not the answer. One follow-up delivers results when the workflow finishes. The results show the tokens and cost of each worker and the total cost of the request. Busy Main receives it after its current turn; idle Main starts a turn. Failed partial output stays marked as partial, never success. Worker output carries no user authority.
96
-
97
- Answers above the shared 40 KiB budget and packets above 64 KiB go to private files. A packet line above 50 KiB needs a Role with `bash`. See [Direct results and records](./docs/orchestration.md#direct-results-and-records).
98
-
99
- To continue a finished worker, add `"continueFrom": "D7.1"` with the same `role`; see [Continue or stop one direct worker](./docs/orchestration.md#continue-or-stop-one-direct-worker). Its saved original lease identity is required. A current or replacement lease cannot supply missing historical proof.
100
-
101
- ### Review a change
102
-
103
- Run `/review` to review uncommitted changes against `HEAD`. To review other work, give one target:
104
-
105
- | Target | Reviewed change |
106
- | --- | --- |
107
- | `A..B` | From `A` to `B` |
108
- | `feature-branch` | From the merge-base with `main` to the branch |
109
- | `a1b2c3d` | The commit against its first parent |
110
- | `#42` | The pull request head against its merge-base with the pull request base |
111
-
112
- Text after the target adds a review focus, for example `/review #42 cache invalidation`. If the first word is not a target, Main reviews uncommitted changes and uses all text as the focus. Main changes the target to exact local commit IDs. Main groups changed files by location, starts one read-only `reviewer` task for each group, and merges the findings.
113
-
114
- The verdict is **Ship** only if each reviewer task succeeded and answered exactly `PASS`. Otherwise, the verdict is **Do not ship**, with the findings in priority order. If the checkout changed during a review task, the verdict is also **Do not ship**, and you must run the review again. Main does not fix findings. If another `/review` prompt template loads first, Pi keeps that template and reports a name collision.
115
-
116
- ### Several repositories in one workspace
117
-
118
- Add an explicit `repositories` map to `delegate_task` to select independent Git repositories in a non-Git workspace. One isolated worker can change the complete set. Use `subagent_workspace` for status, checks, serial promotion, and recovery.
119
-
120
- Workspace mode supports one changeset task with repository-specific checks and optional read-only root inputs. It rejects dependencies and judgment. Saved worker idle and maximum limits apply. Each committed root test script stays pinned, regardless of the check command; repositories without that script can use native checks. Promotion is not atomic and never rolls back. See [Checked workspace tasks](./docs/workspace.md) for the request, limits, and partial-promotion procedure.
121
-
122
- Direct requests can select the same repository set for admission and labelled change reports. This does not provide a sandbox.
123
-
124
- ### Isolated workflow
125
-
126
- ![Isolated workers commit checked candidates; Main stages ready work while siblings run, advances dependents, validates the combined tip, and explicitly promotes](./docs/orchestration-architecture.svg)
127
-
128
- Use isolated mode for checked implementation. An isolated request has one durable ID, one goal, and 1 to 8 text or changeset tasks:
27
+ Direct writes immediately affect your checkout. The extension holds the checkout until it verifies that the worker and its lease holders stopped. Use isolated mode for work that requires validation before integration.
129
28
 
130
29
  ```json
131
30
  {
@@ -147,147 +46,4 @@ Use isolated mode for checked implementation. An isolated request has one durabl
147
46
  }
148
47
  ```
149
48
 
150
- Workers see only Main's committed HEAD, not uncommitted edits. Candidates must be committed and clean. Changesets need focused checks, and the root `package.json` needs a test script. Inspect ready candidates with `subagent_status`.
151
-
152
- - `subagent_stage` stages exact candidates while siblings run; resolve conflicts in the integration checkout.
153
- - `subagent_integrate advance` runs dependents on a staged snapshot.
154
- - `subagent_integrate validate` checks the combined integration tip after the wave settles, with final checks and any final judgment.
155
- - `subagent_integrate promote` explicitly promotes passing work.
156
-
157
- Staging, validation, and promotion require clean, unchanged Main. After a definitive check or review failure, Main can record one integration correction with `subagent_integrate correct` and validate again. See [Isolated contract](./docs/orchestration.md#isolated-contract) and [Exact integration actions](./docs/orchestration.md#exact-integration-actions).
158
-
159
- ### Inspect work
160
-
161
- Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows have **Direct**, **Isolated**, and **Orphaned · parent checkout removed** group labels. On a wide terminal, each row shows its group beside its reference and status. Group headings are not actions. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history.
162
-
163
- In the terminal, Pi's native input and selection list replace the editor and use at most half the terminal height. The menu does not cover the report or the transcript.
164
-
165
- The selected row has an arrow. A detail preview wraps the selected row's context when space permits. Narrow terminals keep the reference and status before the goal. Very short terminals hide the search field, preview, or extra hints. While the menu waits for your selection, Pi reports that it needs user input.
166
-
167
- Type to filter the current menu by reference, record identifier, Role, name, or status. Search includes details that do not fit in a row. The menu shows the number of matching rows and the total row count, including actions. Search changes no records. The menu keeps the filter and selected record when you return from details. Select **Refresh** to load current status; search and navigation use the loaded inventory only.
168
-
169
- | Default key | Action |
170
- | --- | --- |
171
- | `Up` / `Down` | Move to another row. |
172
- | `PageUp` / `PageDown` | Move one page within the list, not the transcript. |
173
- | `Enter` | Select a row or toggle it in a multiple-selection menu. |
174
- | `Ctrl+U` | Clear the filter and show all rows. |
175
- | `Escape` | Cancel the menu without selecting a row. |
176
-
177
- Key hints show Pi's configured bindings. In fullscreen mode, move through rows with the mouse wheel and click a row to select it. In regular mode, use the keyboard; the terminal owns mouse input.
178
-
179
- Each work row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed. Status text stays beside the reference; color is not required. Terminal requests stay hidden until you select **Completed / history**; this filter deletes no records. `/subagent` reports show as transcript entries that the model does not get.
180
-
181
- **Select multiple…** and prune review keep the filter after each toggle. The title shows the selected count, including selected rows hidden by the filter. Search does not select or clear rows. Clear the filter to reach **Select all**, **Clear**, or **Continue**. **Select all** selects every offered row, not only matches. **Continue** uses the selected rows; cancellation returns no selection.
182
-
183
- Every isolated request, including an orphaned request, has **Close and delete worktrees (discard work)**. Select it to review owned resources and confirm deletion. **This permanently deletes committed, uncommitted, and ignored content in the listed checkouts.** Cancel makes no change, and agents and tools cannot trigger this action. **Select multiple…** applies one action to many rows, with one confirmation. See [Close and delete isolated worktrees](./docs/orchestration.md#close-and-delete-isolated-worktrees) for guards and partial cleanup.
184
-
185
- Inspection needs a Herdr pane, the configured `scout` Role, and the `fast` route. If it cannot start, the request stays unchanged; Main can use `subagent_status` to read state. See [Inspect and revise active work](./docs/orchestration.md#inspect-and-revise-active-work), [Status widgets](./docs/orchestration.md#status-widgets), and [Choose a delegation mode](./docs/orchestration.md#choose-a-delegation-mode).
186
-
187
- ## Config
188
-
189
- Package-owned: `~/.pi/agent/config/pi-subagent/config.json`. The extension never writes it. For the shared rules, see [Config files](https://pi.henry.wang/overview#config-files).
190
-
191
- | Name | Description | Values | Default |
192
- | --- | --- | --- | --- |
193
- | `maxSubagents` | Concurrent direct workers and ephemeral children | Safe integer ≥ 1 | `5` |
194
- | `maxTurns` | Provider turns per child | Safe integer ≥ 1 | `50` |
195
- | `maxTokens` | Optional tokens per child | Safe integer ≥ 1 | Unlimited |
196
- | `maxCorrections` | Same-worker corrections per isolated request, including Main's `revise` and `retry` corrections | Safe integer ≥ 0 | `1` |
197
- | `timeout.idleMinutes` | Direct worker and ephemeral child idle timeout | Positive; within Node's timer range | `10` |
198
- | `timeout.maxMinutes` | Ephemeral child hard runtime | Greater than idle; within Node's timer range | `30` |
199
- | `roleDefaults` | Shared resources for built-in and user Roles | Object with `extensions`, `tools`, or `skills` arrays; same validation as Role fields | — |
200
-
201
- `roleDefaults` entries precede Role entries; merging removes duplicates before resource resolution. Use it for a provider extension that every child needs. Limits come only from this file. Requests cannot override or replenish them. Durable requests keep recorded policy; a lower current correction limit can tighten recovery. There is no whole-run timeout.
202
-
203
- The extension reads config at launch, `delegate_task`, later direct workers, isolated Role launches, `/subagent roles`, and status inspection.
204
-
205
- An invalid or misspelled `maxTokens`, or a file problem, blocks delegation, with no fallback to unlimited tokens. Running workers keep their limits; if the problem existed at session start, run `/reload` after you correct the file.
206
-
207
- ### Roles
208
-
209
- Role Markdown files in `~/.pi/agent/config/pi-subagent/` require frontmatter and a Markdown system prompt.
210
-
211
- | Field | Requirement |
212
- | --- | --- |
213
- | `name`, `description` | Required non-empty text without terminal control characters |
214
- | `modelClass` | Optional `fast`, `balanced`, `frontier`, or `fav` default |
215
- | `tools` | Required base or internal tool-name array; `[]` selects none. Name `codemode` or `git_read` to activate it. |
216
- | `extensions` | Required array of trusted absolute paths, supported package sources, or Pi built-ins such as `builtin:codemode` |
217
- | `skills` | Required array of effective Pi Skill names |
218
- | `mcps` | Optional exact global Model Context Protocol (MCP) server names from `~/.pi/agent/mcp.json`, using native `mcpServers` format. Omitted or `[]` denies access to `mcp.json` servers. Servers that Role extensions register always connect. |
219
- | body | Required system instructions |
220
-
221
- The package ships `implementer`, `reviewer`, and `scout`; same-name user Roles override built-ins. Roles define capabilities, not access or isolation. Unknown frontmatter keys invalidate that file. Other valid Roles load; duplicate names become unavailable. Delegation to an invalid file's claimed Role fails with that file's error. Inspect `/subagent roles`.
222
-
223
- The built-in reviewer answers exactly `PASS` or gives prioritized findings in the format of [`reviewer.md`](./examples/roles/reviewer.md).
224
-
225
- The built-in reviewer and scout include `git_read`; existing user reviewers and scouts must add it to `tools`. No additional extension or Bash access is necessary. See [Reviewer Git inspection](./docs/orchestration.md#reviewer-git-inspection) for operations, parameters, limits, and Git requirements.
226
-
227
- When a direct or isolated worker starts with a configured fallback, Pi Subagent warns in the parent session that created it. The warning names the profile, selected `provider/model`, and thinking level. It uses the user interface (UI) when available. Without a UI, it adds a displayed parent-session message that does not start a turn.
228
-
229
- The same profile and fallback route warn once in the active parent session. A session change resets these warnings. A different fallback model or thinking level gets a new warning. Dry runs, preflight, unused launch preparation, and cancelled or replaced sessions do not consume warnings. Isolated text and judgment workers report fallback use on their first child activity.
230
-
231
- Route selection does not change. An available primary produces no fallback warning. A direct `model` override produces no fallback warning because it replaces the configured model. It still keeps the resolved thinking level.
232
-
233
- Children load only declared resources and required adapters. Roles must list their model provider extension. `codemode` requires both `builtin:codemode` in `extensions` and `codemode` in `tools`. For discovery without scripts, add `builtin:tool-search` to `extensions` and `tool_search` to `tools`. Missing Skills, tools, MCP servers, Roles, or routes fail before productive work. Main-only delegation/recovery tools and `ask_question` stay unavailable to children.
234
-
235
- The global `mcp.json` can start with a byte-order mark, as supported by Pi since 1.4. The `oauth.clientRegistration` field accepts `auto` for automatic selection, `dcr` for dynamic client registration, or `cimd` for a client ID metadata document. OAuth, the authorization protocol, keeps Pi's callback and secure-transport checks.
236
-
237
- Every selected MCP server keeps its validated `exposure` and `toolExposure`, with or without `codemode`. An absent exposure keeps Pi's native `codemode` default. Hidden tools stay unreachable. MCP configuration never activates `codemode` automatically.
238
-
239
- **Upgrade to 28.0.0:** Roles without `codemode` no longer force servers to direct exposure or remove per-tool restrictions. Select a discovery tool, or configure only permitted tools as `direct` in the global `toolExposure`. See [Migrate MCP exposure](./docs/orchestration.md#migrate-mcp-exposure-to-2800) for configuration and library changes.
240
-
241
- Read [Role and resource policy](./docs/orchestration.md#role-and-resource-policy) for extension exposure, MCP validation, OAuth constraints, and child budgets. Project MCP overrides cannot change a Role's global allowlist or exposure.
242
-
243
- ## API
244
-
245
- | Surface | Type | Purpose |
246
- | --- | --- | --- |
247
- | `loadRoleCatalog`, `findRole`, `parseRoleName`, `parseRoleDefaults` | functions | Load, validate, and select Roles with shared defaults and per-file errors. |
248
- | `registerRoleDefaultsReporting(pi, agentDir?)` | function | Report problems at session start, once per session. Returns `report(ctx)`; call before a lazy `loadRoleCatalog`. |
249
- | `resolveRoleSkills`, `resolveRoleLaunch`, `resolveConfiguredRoleLaunch` | functions | Resolve effective Pi resources and model routes. Role launch results include optional `fallback` identity without a notification. |
250
- | `prepareRoleLaunch`, `finalizeRoleLaunch` | functions | Prepare Role prompts, arguments, and tool policy. |
251
- | `createEphemeralSubagentExecutor` | function | Run bounded no-session Pi children through a FIFO pool. |
252
- | `createChildWorktree`, `finalizeChildWorktree` | functions | Create and conservatively finalize child worktrees. |
253
- | `prepareExactReviewEvidence` | function | Prepare private exact base-to-tip review evidence. |
254
- | `ExecuteRequestSchema`, `StageRequestSchema`, `IntegrationActionSchema` | schemas | Validate checked request and integration inputs. |
255
- | `IsolatedRunner`, `FileRunStore` | classes | Run checked work and persist request state. |
256
- | `RoleLaunchRuntime`, `HerdrHostRuntime`, `CheckedGitRuntime` | classes | Supply launch, host, and Git behavior. |
257
- | `ExecutionPolicySnapshot`, `RunState`, `CoordinatorRuntime` | types | Describe saved policy, state, and runner integration. |
258
-
259
- See [Role launch API](./docs/orchestration.md#role-launch-api) and [Ephemeral executor API](./docs/orchestration.md#ephemeral-executor-api).
260
-
261
- ## State and storage
262
-
263
- Private durable state lives under `config/pi-subagent/state/`. Isolated worker sessions use mode `0600` under `config/pi-subagent/leases/`.
264
-
265
- Sessions are removed only after exact worker-tab cleanup. Subagent Collection keeps them. They can contain prompts and answers: do not share them. Unfinished requests from older versions block new isolated work until you recover them; the error names the file.
266
-
267
- ## Limits and recovery
268
-
269
- The extension never pushes, opens pull requests, publishes, deploys, or silently falls back to Main. It force-deletes recoverable work only after the user confirms **Close and delete worktrees (discard work)** in `/subagent` or a force removal in `/subagent prune`.
270
-
271
- Role extensions and MCP servers are trusted executable code, not a sandbox. Select the smallest resource set and authorize write scope explicitly. Admission coordinates this Main's Pi calls, not other sessions, trusted extension lifecycle code, or external processes. Concurrent edits can make direct reads stale.
272
-
273
- For uncertain direct termination, open `/subagent`, select the exact workflow, and choose **Close/cancel-and-release ALL owned workers in this workflow**. This stops all owned workers, not only the selected one. Resolve reported blockers and repeat the action.
274
-
275
- Recorded-only tasks cannot use local Close. Their separate recovery action requires complete saved proof or the warned human release. Restarting Pi does not prove termination. Inspect partial changes before new writes; never blindly repeat commits or delete work.
276
-
277
- After Close/cancel-and-release proves pane absence, it terminates the processes that hold the exact private process lease of an owned worker (`SIGTERM`, then `SIGKILL`). Automatic completion, continuation, and Subagent Collection never send signals.
278
-
279
- Unverified tab allocations retain evidence but offer no Close action. Reconcile them manually against Herdr; do not recreate tabs, guess IDs, or restart to bypass admission. See [Direct contract](./docs/orchestration.md#direct-contract).
280
-
281
- After coordinator interruption, restart Pi and run `/subagent recover` in the canonical repository. Use `subagent_status` for exact evidence; never take over a live productive lease or replay uncertain prompts, merges, or promotion. For aborted requests with retained resources, resolve blockers and repeat `subagent_abort`. See [Recover after interruption](./docs/orchestration.md#recover-after-interruption) and [Recovery and state](./docs/orchestration.md#recovery-and-state).
282
-
283
- ![Main, its coordinator extension, and a Herdr subagent through checked work, worker failure, and coordinator interruption](./docs/worker-lifecycle.svg)
284
-
285
- ### Subagent Collection
286
-
287
- Pi closes completed worker tabs when a workspace has more than 10 tabs, and on every `/subagent prune`. It keeps sessions, worktrees, candidates, and recovery records, so `continueFrom` still works. It never closes user tabs, root tabs, active work, or workers of ready candidates. Collection needs no deletion approval. See [Subagent Collection](./docs/orchestration.md#subagent-collection).
288
-
289
- ### Worktree pruning
290
-
291
- Run `/subagent prune` to scan leftover worktrees and branches in the background. When notified, run the command again to review the plan and confirm removal. `/subagent prune cancel` stops new removal steps; an active step can finish.
292
-
293
- Removing a checkout deletes its ignored files only after a separate confirmation naming those entries. If you select an item that an unfinished request owns, the command closes and deletes that whole request after its review and confirmation. **If you select unowned work with unique commits or changes, a separate confirmation permits its permanent deletion.** See [Prune leftover worktrees](./docs/orchestration.md#prune-leftover-worktrees) before removal.
49
+ See the [orchestration contract](./docs/orchestration.md) for roles, parallel tasks, cancellation, recovery, and checked integration.
@@ -25,7 +25,7 @@ export interface DirectHandle {
25
25
  }
26
26
  export declare function exactDirectTerminalTurn(jsonl: string, prompt: string): boolean;
27
27
  /** Refuse continuation unless the saved session's exact recorded turn is terminal and no later user turn exists. */
28
- export declare function assertSettledDirectSession(sessionFile: string, turn: string): Promise<void>;
28
+ export declare function assertSettledDirectSession(sessionFile: string, turn: string, provedStopped?: boolean): Promise<void>;
29
29
  export declare function exactDirectAnswer(jsonl: string, prompt: string, requireSuccess?: boolean): string;
30
30
  /** Measured from one session read; each field is absent when no turn record carried it. */
31
31
  export interface DirectUsage {
@@ -87,7 +87,7 @@ export function exactDirectTerminalTurn(jsonl, prompt) {
87
87
  }
88
88
  const turnSuffix = (turn) => `\n\nTurn identity: ${turn}`;
89
89
  /** Refuse continuation unless the saved session's exact recorded turn is terminal and no later user turn exists. */
90
- export async function assertSettledDirectSession(sessionFile, turn) {
90
+ export async function assertSettledDirectSession(sessionFile, turn, provedStopped = false) {
91
91
  const info = await stat(sessionFile).catch((error) => {
92
92
  throw new Error(`Saved Pi session ${sessionFile} is missing or unreadable`, { cause: error });
93
93
  });
@@ -95,15 +95,25 @@ export async function assertSettledDirectSession(sessionFile, turn) {
95
95
  throw new Error(`Saved Pi session ${sessionFile} exceeds 16 MiB`);
96
96
  const jsonl = await readFile(sessionFile, "utf8");
97
97
  let prompt;
98
+ let leaf;
98
99
  for (const line of jsonl.trimEnd().split("\n")) {
99
100
  const entry = JSON.parse(line);
100
101
  const message = entry?.type === "message" ? entry.message : undefined;
101
102
  const text = message?.role === "user" && Array.isArray(message.content) && message.content.length === 1
102
103
  ? message.content[0]?.text : undefined;
103
- if (typeof text === "string" && text.endsWith(turnSuffix(turn)))
104
+ if (typeof text === "string" && text.endsWith(turnSuffix(turn))) {
105
+ if (prompt !== undefined)
106
+ throw new Error("Saved Pi session repeats the recorded turn identity.");
104
107
  prompt = text;
108
+ leaf = field(entry.id, "user entry id");
109
+ }
110
+ else if (provedStopped && leaf !== undefined) {
111
+ if (message?.role === "user" || entry.parentId !== leaf)
112
+ throw new Error("Stopped worker session contains a later user turn or a different branch.");
113
+ leaf = field(entry.id, "session entry id");
114
+ }
105
115
  }
106
- if (prompt === undefined || !exactDirectTerminalTurn(jsonl, prompt)) {
116
+ if (prompt === undefined || (!provedStopped && !exactDirectTerminalTurn(jsonl, prompt))) {
107
117
  throw new Error(`Saved Pi session ${sessionFile} has no terminal final turn for the recorded prompt; the worker may still be running`);
108
118
  }
109
119
  }
@@ -520,7 +530,7 @@ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => proce
520
530
  // Exclusive creation refuses a worker-planted file, symlink, or FIFO at this predictable path.
521
531
  const file = join(dirname(sessionFile), `answer-${turn}.md`);
522
532
  await writeFile(file, text, { flag: "wx", mode: 0o600 });
523
- return { text, answerFile: file, inline: `${utf8Prefix(text, maxBytes)}\n\n[Answer truncated to ${maxBytes} of ${bytes} bytes; read the full answer at ${file}]` };
533
+ return { text, answerFile: file, inline: `${utf8Prefix(text, maxBytes)}\n\n[Answer truncated to ${maxBytes} of ${bytes} bytes; full answer saved]` };
524
534
  };
525
535
  const maybeAnswer = async () => {
526
536
  try {
@@ -35,6 +35,8 @@ export interface EphemeralSubagentRunInput {
35
35
  onUpdate?: (text: string) => void;
36
36
  onTokens?: (tokens: number) => void;
37
37
  onActivity?: (event: EphemeralSubagentActivityEvent) => void;
38
+ /** Distinguish confirmed absence before spawn from an observed process exit. */
39
+ onProcessEnd?: (reason: "not-started" | "exited") => void;
38
40
  prepare: () => Promise<{
39
41
  launch: PiLaunch;
40
42
  task: string;
@@ -70,7 +72,9 @@ export interface EphemeralSubagentExecutor {
70
72
  * Creates a bounded ephemeral executor for callers already running inside Pi.
71
73
  * It reuses the active Pi process invocation; it does not resolve a standalone Pi installation.
72
74
  */
73
- export declare function createEphemeralSubagentExecutor(options: EphemeralSubagentExecutorOptions): EphemeralSubagentExecutor;
75
+ export declare function createEphemeralSubagentExecutor(options: EphemeralSubagentExecutorOptions): EphemeralSubagentExecutor & {
76
+ withLimits(options: EphemeralSubagentExecutorOptions): EphemeralSubagentExecutor;
77
+ };
74
78
  /** Longest prefix of `text` within `maxBytes` UTF-8 bytes, never splitting a code point. */
75
79
  export declare function utf8Prefix(text: string, maxBytes: number): string;
76
80
  export declare function capEphemeralSubagentOutput(text: string): string;
package/dist/ephemeral.js CHANGED
@@ -110,6 +110,9 @@ function validateRunInput(value) {
110
110
  if (input.onActivity !== undefined && typeof input.onActivity !== "function") {
111
111
  throw new TypeError("run.onActivity must be a function.");
112
112
  }
113
+ if (input.onProcessEnd !== undefined && typeof input.onProcessEnd !== "function") {
114
+ throw new TypeError("run.onProcessEnd must be a function.");
115
+ }
113
116
  return value;
114
117
  }
115
118
  function record(value, field) {
@@ -162,43 +165,45 @@ export function createEphemeralSubagentExecutor(options) {
162
165
  throw new EphemeralSubagentError("prepare", cause.message, cause);
163
166
  }
164
167
  const invocation = piInvocation();
165
- let active = 0;
168
+ // All workflow budgets share one FIFO. Honor both the waiting and active budgets.
169
+ const active = new Set();
166
170
  const queue = [];
167
- const acquire = (signal) => {
171
+ const drain = () => {
172
+ while (queue.length && active.size < queue[0].limit) {
173
+ if ([...active].some(({ limit }) => active.size >= limit))
174
+ break;
175
+ queue.shift().grant();
176
+ }
177
+ };
178
+ const acquire = (limit, signal) => {
168
179
  if (signal?.aborted)
169
180
  return Promise.reject(abortError(signal));
170
- if (active < validated.maxConcurrency) {
171
- active += 1;
172
- return Promise.resolve();
173
- }
174
181
  return new Promise((resolve, reject) => {
182
+ const permit = {
183
+ limit,
184
+ grant() {
185
+ signal?.removeEventListener("abort", abort);
186
+ active.add(permit);
187
+ resolve(() => {
188
+ active.delete(permit);
189
+ drain();
190
+ });
191
+ },
192
+ };
175
193
  const abort = () => {
176
- const index = queue.indexOf(grant);
177
- if (index < 0)
178
- return;
179
- queue.splice(index, 1);
180
- signal?.removeEventListener("abort", abort);
194
+ queue.splice(queue.indexOf(permit), 1);
181
195
  reject(abortError(signal));
196
+ drain();
182
197
  };
183
- const grant = () => {
184
- signal?.removeEventListener("abort", abort);
185
- resolve();
186
- };
187
- queue.push(grant);
198
+ queue.push(permit);
188
199
  signal?.addEventListener("abort", abort, { once: true });
200
+ drain();
189
201
  });
190
202
  };
191
- const release = () => {
192
- const grant = queue.shift();
193
- if (grant)
194
- grant();
195
- else
196
- active -= 1;
197
- };
198
- return {
203
+ const scoped = (budget) => ({
199
204
  async run(value) {
200
205
  const input = validateRunInput(value);
201
- await acquire(input.signal);
206
+ const release = await acquire(budget.maxConcurrency, input.signal);
202
207
  try {
203
208
  if (input.signal?.aborted)
204
209
  throw abortError(input.signal);
@@ -207,17 +212,27 @@ export function createEphemeralSubagentExecutor(options) {
207
212
  prepared = validatePrepared(await input.prepare());
208
213
  }
209
214
  catch (cause) {
215
+ notifyNotStarted(input);
210
216
  if (input.signal?.aborted)
211
217
  throw abortError(input.signal, cause);
212
218
  throw new EphemeralSubagentError("prepare", cause instanceof Error ? cause.message : String(cause), cause);
213
219
  }
214
- return await runPi(prepared, input, validated, invocation);
220
+ return await runPi(prepared, input, budget, invocation);
215
221
  }
216
222
  finally {
217
223
  release();
218
224
  }
219
225
  },
220
- };
226
+ });
227
+ return { ...scoped(validated), withLimits: (limits) => scoped(validateOptions(limits)) };
228
+ }
229
+ function notifyNotStarted(input) {
230
+ try {
231
+ input.onProcessEnd?.("not-started");
232
+ }
233
+ catch (cause) {
234
+ throw new EphemeralSubagentError("callback", "Subagent onProcessEnd callback failed.", cause);
235
+ }
221
236
  }
222
237
  function piInvocation() {
223
238
  const currentScript = process.argv[1];
@@ -377,8 +392,10 @@ export function formatDuration(milliseconds) {
377
392
  return hours ? `${hours}h ${minutes}m` : minutes ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
378
393
  }
379
394
  async function runPi(prepared, input, budget, invocation) {
380
- if (input.signal?.aborted)
395
+ if (input.signal?.aborted) {
396
+ notifyNotStarted(input);
381
397
  throw abortError(input.signal);
398
+ }
382
399
  const timeoutPolicy = budget.timeout;
383
400
  return await new Promise((resolve, reject) => {
384
401
  const args = [...invocation.args, "--mode", "json", "-p", ...prepared.launch.args, `Task: ${prepared.task}`];
@@ -405,6 +422,7 @@ async function runPi(prepared, input, budget, invocation) {
405
422
  });
406
423
  }
407
424
  catch (cause) {
425
+ notifyNotStarted(input);
408
426
  reject(new EphemeralSubagentError("spawn", cause instanceof Error ? cause.message : String(cause), cause));
409
427
  return;
410
428
  }
@@ -885,11 +903,25 @@ async function runPi(prepared, input, budget, invocation) {
885
903
  }
886
904
  onChildError = (error) => {
887
905
  spawnError = error;
906
+ if (child.pid === undefined) {
907
+ try {
908
+ input.onProcessEnd?.("not-started");
909
+ }
910
+ catch (cause) {
911
+ failCallback("onProcessEnd", cause);
912
+ }
913
+ }
888
914
  if (input.signal?.aborted)
889
915
  aborted = true;
890
916
  };
891
917
  onChildExit = () => {
892
918
  childExited = true;
919
+ try {
920
+ input.onProcessEnd?.("exited");
921
+ }
922
+ catch (error) {
923
+ failCallback("onProcessEnd", error);
924
+ }
893
925
  clearTimer(deadlineTimer);
894
926
  clearTimer(killTimer);
895
927
  void killTree(true);
package/dist/index.d.ts CHANGED
@@ -129,7 +129,16 @@ export declare function createSubagentConfigStore(agentDir?: string): import("@h
129
129
  * one record, so each issue shows one time in each session, also with the pi-subagent extension active.
130
130
  */
131
131
  export declare function registerRoleDefaultsReporting(pi: Pick<ExtensionAPI, "on">, agentDir?: string): (ctx: Pick<ExtensionContext, "hasUI" | "ui">) => void;
132
- declare const BUILTIN_ROLE_NAMES: readonly ["implementer", "reviewer", "scout"];
132
+ declare const BUILTIN_ROLE_NAMES: readonly ["implementer", "reviewer", "scout", "planner", "oracle"];
133
+ export declare const DIRECT_ROLE_TASKS: {
134
+ readonly role: "implementer" | "oracle" | "planner" | "reviewer" | "scout";
135
+ readonly id: "pi-subagent/implementer" | "pi-subagent/oracle" | "pi-subagent/planner" | "pi-subagent/reviewer" | "pi-subagent/scout";
136
+ readonly label: "Delegate implementer" | "Delegate oracle" | "Delegate planner" | "Delegate reviewer" | "Delegate scout";
137
+ readonly purpose: "Select the direct implementer worker route." | "Select the direct oracle worker route." | "Select the direct planner worker route." | "Select the direct reviewer worker route." | "Select the direct scout worker route.";
138
+ readonly defaultProfile: "balanced" | "fast";
139
+ }[];
140
+ /** Reuse an existing role assignment during cutover. Native assignments take priority in the route resolver. */
141
+ export declare function directRoleTask(role: string, agentDir?: string): ModelTask;
133
142
  export type BuiltinRoleName = (typeof BUILTIN_ROLE_NAMES)[number];
134
143
  export declare function loadBuiltinRole(name: BuiltinRoleName): Role;
135
144
  /**
package/dist/index.js CHANGED
@@ -12,8 +12,6 @@ export { loadRoleMcpConfig, parseRoleMcpAllowlist } from "./mcp-role.js";
12
12
  export { addUsage, capEphemeralSubagentOutput, createEphemeralSubagentExecutor, DEFAULT_MAX_TURNS, EphemeralSubagentError, EXECUTION_BUDGET_ENV, formatDuration, } from "./ephemeral.js";
13
13
  export { createChildWorktree, finalizeChildWorktree, inspectIndexFlags, inspectWorktreeDirty, WorktreeSetupError, } from "./worktree.js";
14
14
  export { prepareExactReviewEvidence, REVIEW_MAX_PATCH_BYTES, REVIEW_MAX_PATHS, } from "./review-evidence.js";
15
- const CODEX_ALIAS = /^openai-codex-(?:[2-9]|[1-9]\d+)$/;
16
- const MULTI_CODEX_EXTENSION = fileURLToPath(import.meta.resolve("@henryqw/pi-multi-codex/extensions/multi-codex.ts"));
17
15
  const ROLE_MCP_EXTENSION = fileURLToPath(new URL("../extensions/role-mcp.ts", import.meta.url));
18
16
  const ROLE_TOOLS_EXTENSION = fileURLToPath(new URL("../extensions/role-tools.ts", import.meta.url));
19
17
  const GIT_READ_EXTENSION = fileURLToPath(new URL("../extensions/git-read.ts", import.meta.url));
@@ -268,7 +266,21 @@ function applyRoleDefaults(role, defaults) {
268
266
  };
269
267
  }
270
268
  // Built-in Roles resolved from the package-shipped Markdown relative to this module.
271
- const BUILTIN_ROLE_NAMES = ["implementer", "reviewer", "scout"];
269
+ const BUILTIN_ROLE_NAMES = ["implementer", "reviewer", "scout", "planner", "oracle"];
270
+ const previousRoleNames = { implementer: "worker", reviewer: "reviewer", scout: "researcher", planner: "planner", oracle: "oracle" };
271
+ export const DIRECT_ROLE_TASKS = BUILTIN_ROLE_NAMES.map((role) => ({
272
+ role, id: `pi-subagent/${role}`, label: `Delegate ${role}`, purpose: `Select the direct ${role} worker route.`,
273
+ defaultProfile: role === "scout" ? "fast" : "balanced",
274
+ }));
275
+ /** Reuse an existing role assignment during cutover. Native assignments take priority in the route resolver. */
276
+ export function directRoleTask(role, agentDir = getAgentDir()) {
277
+ const task = DIRECT_ROLE_TASKS.find((candidate) => candidate.role === role);
278
+ if (!task)
279
+ return DELEGATE_TASK;
280
+ const { tasks } = loadTaskModelsConfig(agentDir).value;
281
+ const inherited = tasks[`billion-context/acp-${previousRoleNames[task.role]}`];
282
+ return { id: task.id, label: task.label, purpose: task.purpose, defaultProfile: inherited ?? task.defaultProfile };
283
+ }
272
284
  /** Single-file Role parser shared by built-in and user roles. */
273
285
  function parseRoleFile(file, raw) {
274
286
  let parsed;
@@ -466,7 +478,6 @@ function prepareRoleLaunchFromSkills(ctx, input, skills) {
466
478
  }
467
479
  const extensions = [
468
480
  ...selectedExtensions,
469
- ...(CODEX_ALIAS.test(input.route.model.provider) ? [MULTI_CODEX_EXTENSION] : []),
470
481
  // Always loaded: it connects the servers that Role extensions register; `mcps` gates only mcp.json.
471
482
  ROLE_MCP_EXTENSION,
472
483
  ...(role.tools.includes("git_read") ? [GIT_READ_EXTENSION] : []),