@henryqw/pi-subagent 27.13.1 → 27.14.1
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 +3 -0
- package/README.md +34 -83
- package/dist/collection.d.ts +4 -0
- package/dist/collection.js +17 -0
- package/dist/direct-herdr.d.ts +2 -0
- package/dist/direct-herdr.js +32 -0
- package/dist/herdr-runtime.d.ts +3 -0
- package/dist/herdr-runtime.js +13 -1
- package/dist/runner.d.ts +6 -0
- package/dist/runner.js +50 -0
- package/docs/orchestration.md +16 -2
- package/example.png +0 -0
- package/extensions/isolated.ts +10 -0
- package/extensions/subagent-command.ts +15 -1
- package/extensions/subagent.ts +69 -0
- package/package.json +1 -1
package/CONTEXT.md
CHANGED
|
@@ -56,6 +56,9 @@ The guarded transfer of a validated integration generation into unchanged, clean
|
|
|
56
56
|
**Release**:
|
|
57
57
|
Main's explicit cleanup of an exact rejected worker or superseded generation after proving that it is no longer selected. Release does not discard dirty, conflicted, or uncertain work.
|
|
58
58
|
|
|
59
|
+
**Subagent Collection**:
|
|
60
|
+
Tab-only cleanup of verified completed workers. It preserves sessions, leases, worktrees, candidates, and recovery records. A workspace with more than 10 tabs triggers an automatic attempt; `/subagent prune` attempts it at any count. Live isolated revision workers are not completed resources.
|
|
61
|
+
|
|
59
62
|
**Discard**:
|
|
60
63
|
The user-confirmed deletion of owned isolated resources from `/subagent`, including committed, uncommitted, and ignored content. Unlike Release, only the user can trigger it.
|
|
61
64
|
|
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ Delegate bounded work to configured Pi Roles through [Herdr](https://herdr.dev/)
|
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
9
|
-
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.
|
|
9
|
+
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
10
|
|
|
11
11
|
```bash
|
|
12
12
|
pi install npm:@henryqw/pi-task-models
|
|
@@ -25,15 +25,15 @@ Configure the profiles that your Roles use in `/task-models`. Direct writer term
|
|
|
25
25
|
|
|
26
26
|
Ask Main: “Have a scout trace sign-in without editing files.” Main calls `delegate_task` and stays available until progress and results arrive.
|
|
27
27
|
|
|
28
|
-
If Pi Goal is installed, it waits for live
|
|
28
|
+
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).
|
|
29
29
|
|
|
30
|
-
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.
|
|
30
|
+
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`.
|
|
31
31
|
|
|
32
32
|
| Surface | Type | Purpose |
|
|
33
33
|
| --- | --- | --- |
|
|
34
|
-
| `/subagent` | command | Browse
|
|
34
|
+
| `/subagent` | command | Browse work; stop workers, send follow-ups, or delete owned worktrees after confirmation. Without interactive UI, only reports. |
|
|
35
35
|
| `/subagent roles` | command | List Role sources, resources, resolved model and thinking level, route errors, and file errors. Read-only; requires no Herdr pane. |
|
|
36
|
-
| `/subagent prune` | command |
|
|
36
|
+
| `/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. |
|
|
37
37
|
| `/subagent prune cancel` | command | Cancel the scan, ready plan, or cleanup. An active removal step can finish; completed removals are not undone. |
|
|
38
38
|
| `/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). |
|
|
39
39
|
| `/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. |
|
|
@@ -48,8 +48,6 @@ Commands, prompts, and UI are for you. Tools and the packaged skill are for Main
|
|
|
48
48
|
| 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. |
|
|
49
49
|
| Isolated status widget (`I`) | ui | Show recorded task state, Role/model-class badges, and retained workspaces in the TUI. Readiness does not mean promotion. |
|
|
50
50
|
|
|
51
|
-
`delegate_task`, `subagent_resume`, `subagent_stage`, `subagent_integrate`, and `subagent_abort` are model-only. Main must make these decisions visibly; `codemode` scripts can call only `subagent_status`.
|
|
52
|
-
|
|
53
51
|
### Direct workflow
|
|
54
52
|
|
|
55
53
|
A read-only task:
|
|
@@ -80,27 +78,17 @@ Checkout admission is shared with managed background commands from `pi-herdr-too
|
|
|
80
78
|
|
|
81
79
|
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.
|
|
82
80
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
```json
|
|
86
|
-
{"outcome":"succeeded","answer":"Scoped commit completed."}
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
`outcome` accepts `succeeded`, `failed`, or `blocked`; `answer` must be non-empty. Plain text, malformed completion, blocked work, or failure stops later dispatch. Success is the worker's report, not independent validation. Checkout admission depends on proved termination, not the reported outcome.
|
|
81
|
+
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
82
|
|
|
91
|
-
A write task can declare `"paths": ["src/**"]` with repo-relative globs.
|
|
83
|
+
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
84
|
|
|
93
|
-
|
|
85
|
+
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
86
|
|
|
95
87
|
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
88
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
A task packet above 64 KiB uses a private file, including the full previous answer in a chain. The worker must read the complete packet with its Role's tools before it acts.
|
|
89
|
+
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).
|
|
100
90
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
To continue a finished worker, add `"continueFrom": "D7.1"` with the same `role`. This opens a new tab with the saved conversation and a new reference. Continue the newest reference from the original checkout and workspace. For eligibility and stop behavior, see [Continue or stop one direct worker](./docs/orchestration.md#continue-or-stop-one-direct-worker).
|
|
91
|
+
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).
|
|
104
92
|
|
|
105
93
|
### Review a change
|
|
106
94
|
|
|
@@ -113,7 +101,7 @@ Run `/review` to review uncommitted changes against `HEAD`. To review other work
|
|
|
113
101
|
| `a1b2c3d` | The commit against its first parent |
|
|
114
102
|
| `#42` | The pull request head against its merge-base with the pull request base |
|
|
115
103
|
|
|
116
|
-
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.
|
|
104
|
+
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.
|
|
117
105
|
|
|
118
106
|
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.
|
|
119
107
|
|
|
@@ -143,56 +131,24 @@ Use isolated mode for checked implementation. An isolated request has one durabl
|
|
|
143
131
|
}
|
|
144
132
|
```
|
|
145
133
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
Workers use Main's pinned committed branch, HEAD, and tree, not staged, unstaged, or untracked edits. Branch or HEAD changes block new waves. Candidates must be committed with no tracked or untracked changes. Ignored generated files permit candidacy but prevent automatic cleanup.
|
|
149
|
-
|
|
150
|
-
New isolated worktree names use the request and task IDs, plus an identity suffix. Integration names use the request ID and `integration-<generation>`. Herdr workspace and tab labels show the worker worktree name. Names do not use goals or requirements. Saved worktrees and labels keep their exact names for recovery and cleanup.
|
|
151
|
-
|
|
152
|
-
Keep the durable ID; Main can work or end its turn without polling. Inspect ready candidates with `subagent_status`.
|
|
134
|
+
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`.
|
|
153
135
|
|
|
154
136
|
- `subagent_stage` stages exact candidates while siblings run; resolve conflicts in the integration checkout.
|
|
155
137
|
- `subagent_integrate advance` runs dependents on a staged snapshot.
|
|
156
138
|
- `subagent_integrate validate` checks the combined integration tip after the wave settles, with final checks and any final judgment.
|
|
157
139
|
- `subagent_integrate promote` explicitly promotes passing work.
|
|
158
140
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
Combined validation can reuse a passed preliminary check of a staged candidate. The candidate must have the same tree as the combined tip, and the check must have the identical command and argv. Then the final check does not run again. This usually occurs when you stage one candidate onto unchanged Main. Status shows each reused result and its candidate. Final judgment still runs.
|
|
162
|
-
|
|
163
|
-
Reuse assumes that checks use only tracked content. Ignored files, for example `node_modules`, can be different between worktrees.
|
|
164
|
-
|
|
165
|
-
The extension sends follow-ups when a candidate becomes ready, a worker needs attention, and the wave finishes. A missed follow-up does not authorize replay. Read [Isolated contract](./docs/orchestration.md#isolated-contract) and [Exact integration actions](./docs/orchestration.md#exact-integration-actions) for graph, judgment, revision, refresh, and release details.
|
|
141
|
+
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).
|
|
166
142
|
|
|
167
143
|
### Inspect work
|
|
168
144
|
|
|
169
|
-
Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions.
|
|
170
|
-
|
|
171
|
-
In the terminal, use the Up and Down arrow keys to scroll through menu rows. Enter selects a row; Escape cancels the menu. The list fits the terminal height and keeps the current row visible when you resize the terminal. The menu shows your configured selection keys. In multiple-choice menus, the menu keeps the current row in view after you mark or clear it. Scroll to **Select all**, **Clear**, **Continue**, or **Cancel** below the work rows.
|
|
172
|
-
|
|
173
|
-
Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. The extension calculates it from local and saved evidence without a model call. Without interactive UI, `/subagent` sends this report before the request list.
|
|
174
|
-
|
|
175
|
-
A direct workflow is working only when this Pi process owns it and has a running worker. Direct work with a delivered result shows its outcome under **Completed / history** and is not in the report. Other recorded-only direct work shows as unverified. An isolated request is working only when its status is active and a live run holds the repository lease. Without a live lease, an active request shows as interrupted; run `/subagent recover`.
|
|
145
|
+
Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. 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.
|
|
176
146
|
|
|
177
|
-
Each row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed.
|
|
147
|
+
Each row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed. 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.
|
|
178
148
|
|
|
179
|
-
|
|
149
|
+
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.
|
|
180
150
|
|
|
181
|
-
|
|
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.
|
|
184
|
-
|
|
185
|
-
Select **Select multiple…** to apply one action to many rows. Select a row to mark it `[x]` or clear it, or use **Select all** or **Clear**, then select **Continue**. The next menu shows only the actions that apply. **Close and delete worktrees (discard work)** applies to isolated requests. **Close/cancel-and-release ALL owned workers** applies to direct workflows that can close. Each request shows its review, then one confirmation covers all of them.
|
|
186
|
-
|
|
187
|
-
The command reports the number of selected rows that the action skipped.
|
|
188
|
-
|
|
189
|
-
Only shown resources can be removed; live jobs, uncertain ownership, or other Herdr panes can block removal. Agents and tools cannot trigger this action. See [Close and delete isolated worktrees](./docs/orchestration.md#close-and-delete-isolated-worktrees) for guards and partial cleanup.
|
|
190
|
-
|
|
191
|
-
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) for inspection and follow-up details.
|
|
192
|
-
|
|
193
|
-
See [Status widgets](./docs/orchestration.md#status-widgets) for reference numbering, token counts, and activity metrics, and [Choose a delegation mode](./docs/orchestration.md#choose-a-delegation-mode) for routing guidance.
|
|
194
|
-
|
|
195
|
-

|
|
151
|
+
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).
|
|
196
152
|
|
|
197
153
|
## Config
|
|
198
154
|
|
|
@@ -212,12 +168,7 @@ Package-owned: `~/.pi/agent/config/pi-subagent/config.json`. Missing files silen
|
|
|
212
168
|
|
|
213
169
|
The extension reports each new problem once per session. It reads config at launch, `delegate_task`, later direct workers, isolated Role launches, `/subagent roles`, and status inspection.
|
|
214
170
|
|
|
215
|
-
|
|
216
|
-
- Invalid `maxSubagents`, `maxTurns`, `maxCorrections`, or `timeout` values warn and use finite defaults. If maximum timeout does not exceed idle timeout, the whole `timeout` uses defaults.
|
|
217
|
-
- Unknown or invalid `roleDefaults` keys warn; only those keys are ignored, so Roles receive fewer default resources.
|
|
218
|
-
- Invalid or misspelled `maxTokens` blocks delegation. Malformed JSON, invalid UTF-8, files above 64 KiB, and unreadable files also block delegation. The extension does not fall back to unlimited tokens.
|
|
219
|
-
|
|
220
|
-
`/subagent` remains available during a block. Correct the file to enable delegation. The next worker or isolated Role launch fails while the block remains; running workers retain their original limits. If the problem existed at session start, also run `/reload`, because that session took default execution limits.
|
|
171
|
+
Invalid limits warn and use defaults. Invalid or misspelled `maxTokens`, malformed or unreadable files, invalid UTF-8, and files above 64 KiB block 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.
|
|
221
172
|
|
|
222
173
|
### Roles
|
|
223
174
|
|
|
@@ -233,13 +184,9 @@ Role Markdown files in `~/.pi/agent/config/pi-subagent/` require frontmatter and
|
|
|
233
184
|
| `mcps` | Optional exact global 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. |
|
|
234
185
|
| body | Required system instructions |
|
|
235
186
|
|
|
236
|
-
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
|
|
237
|
-
|
|
238
|
-
The built-in reviewer answers exactly `PASS` when it finds no actionable correctness risk. Otherwise, each finding starts with a priority and a confidence (`high`, `medium`, or `low`), for example `[P1] confidence: high`. Then it gives file and line evidence, the trigger, the impact, and the smallest fix. Each finding blocks approval.
|
|
187
|
+
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`.
|
|
239
188
|
|
|
240
|
-
-
|
|
241
|
-
- `P1`: wrong behavior under a realistic condition.
|
|
242
|
-
- `P2`: wrong behavior in a narrow edge case with limited impact.
|
|
189
|
+
The built-in reviewer answers exactly `PASS` or gives prioritized findings in the format of [`reviewer.md`](./examples/roles/reviewer.md).
|
|
243
190
|
|
|
244
191
|
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.
|
|
245
192
|
|
|
@@ -263,30 +210,34 @@ Read [Role and resource policy](./docs/orchestration.md#role-and-resource-policy
|
|
|
263
210
|
| `RoleLaunchRuntime`, `HerdrHostRuntime`, `CheckedGitRuntime` | classes | Supply launch, host, and Git behavior. |
|
|
264
211
|
| `ExecutionPolicySnapshot`, `RunState`, `CoordinatorRuntime` | types | Describe saved policy, state, and runner integration. |
|
|
265
212
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
The executor accepts concurrency, turn/token, idle/hard-runtime limits, and abort, output, token, and activity callbacks. Queue time uses no child timeout; resources resolve after admission. See [Ephemeral executor API](./docs/orchestration.md#ephemeral-executor-api) for bounded output, abort results, errors, and accounting.
|
|
213
|
+
See [Role launch API](./docs/orchestration.md#role-launch-api) and [Ephemeral executor API](./docs/orchestration.md#ephemeral-executor-api).
|
|
269
214
|
|
|
270
215
|
## State and storage
|
|
271
216
|
|
|
272
|
-
Private durable state lives under `config/pi-subagent/state/`. Isolated worker sessions use mode `0600` under `config/pi-subagent/leases
|
|
217
|
+
Private durable state lives under `config/pi-subagent/state/`. Isolated worker sessions use mode `0600` under `config/pi-subagent/leases/`.
|
|
273
218
|
|
|
274
|
-
Sessions are removed only after exact worker-tab cleanup. They can contain prompts and answers: do not share them.
|
|
219
|
+
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.
|
|
275
220
|
|
|
276
221
|
## Limits and recovery
|
|
277
222
|
|
|
223
|
+
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`.
|
|
224
|
+
|
|
278
225
|
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.
|
|
279
226
|
|
|
280
227
|
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. Recorded-only tasks cannot release admission. Restarting Pi does not prove termination. Inspect partial changes before new writes; never blindly repeat commits or delete work.
|
|
281
228
|
|
|
282
229
|
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).
|
|
283
230
|
|
|
284
|
-
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. See [Recover after interruption](./docs/orchestration.md#recover-after-interruption) and [Recovery and state](./docs/orchestration.md#recovery-and-state).
|
|
231
|
+
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).
|
|
232
|
+
|
|
233
|
+

|
|
234
|
+
|
|
235
|
+
### Subagent Collection
|
|
285
236
|
|
|
286
|
-
|
|
237
|
+
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).
|
|
287
238
|
|
|
288
|
-
|
|
239
|
+
### Worktree pruning
|
|
289
240
|
|
|
290
|
-
|
|
241
|
+
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.
|
|
291
242
|
|
|
292
|
-
|
|
243
|
+
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.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
/** A collection trigger, not a limit on tabs or workers. */
|
|
3
|
+
export declare const COLLECTION_TAB_TRIGGER = 10;
|
|
4
|
+
export declare function workspaceNeedsCollection(pi: Pick<ExtensionAPI, "exec">, cwd: string, workspaceId: string): Promise<boolean>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createHerdrClient } from "@henryqw/pi-herdr";
|
|
2
|
+
/** A collection trigger, not a limit on tabs or workers. */
|
|
3
|
+
export const COLLECTION_TAB_TRIGGER = 10;
|
|
4
|
+
export async function workspaceNeedsCollection(pi, cwd, workspaceId) {
|
|
5
|
+
const response = await createHerdrClient(pi.exec.bind(pi)).json(["tab", "list", "--workspace", workspaceId], { cwd, timeout: 5_000 });
|
|
6
|
+
const result = response.result;
|
|
7
|
+
if (result?.type !== "tab_list" || !Array.isArray(result.tabs))
|
|
8
|
+
throw new Error("Malformed Herdr collection tab list.");
|
|
9
|
+
const ids = new Set();
|
|
10
|
+
for (const tab of result.tabs) {
|
|
11
|
+
if (!tab || tab.workspace_id !== workspaceId || typeof tab.tab_id !== "string" || !tab.tab_id || ids.has(tab.tab_id)) {
|
|
12
|
+
throw new Error("Herdr collection tab list has uncertain workspace or tab identity.");
|
|
13
|
+
}
|
|
14
|
+
ids.add(tab.tab_id);
|
|
15
|
+
}
|
|
16
|
+
return ids.size > COLLECTION_TAB_TRIGGER;
|
|
17
|
+
}
|
package/dist/direct-herdr.d.ts
CHANGED
|
@@ -66,6 +66,8 @@ export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: s
|
|
|
66
66
|
* A task result or Ctrl-C acknowledgement is not termination evidence.
|
|
67
67
|
* `settledOnly` refuses to close a listed agent that is not idle or done. */
|
|
68
68
|
stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, settledOnly?: boolean): Promise<void>;
|
|
69
|
+
/** Collection preserves the saved conversation and private lease for continuation and recovery. */
|
|
70
|
+
collect(tab: DirectTab, current: () => boolean): Promise<boolean>;
|
|
69
71
|
/** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
|
|
70
72
|
start(launch: ResolvedRoleLaunch & Pick<PreparedRoleLaunch, "tools">, name: string, label: string, task: string, signal: AbortSignal, onTab: (tab: DirectTab) => void, requireSuccess?: boolean, resume?: Pick<DirectTab, "sessionFile" | "leasePath">): Promise<DirectHandle>;
|
|
71
73
|
};
|
package/dist/direct-herdr.js
CHANGED
|
@@ -351,6 +351,38 @@ export function createDirectHerdr(pi, cwd, idleMs) {
|
|
|
351
351
|
}
|
|
352
352
|
requireCurrent();
|
|
353
353
|
},
|
|
354
|
+
/** Collection preserves the saved conversation and private lease for continuation and recovery. */
|
|
355
|
+
async collect(tab, current) {
|
|
356
|
+
if (tab.workspaceId !== workspaceId || tab.cwd !== workingDir || !current())
|
|
357
|
+
throw new Error("Direct collection scope changed.");
|
|
358
|
+
const before = await herdr.exec(["tab", "get", tab.tabId], options());
|
|
359
|
+
if (!before.killed && hasHerdrErrorCode(before, "tab_not_found"))
|
|
360
|
+
return false;
|
|
361
|
+
if (before.code !== 0 || before.killed)
|
|
362
|
+
throw new Error("Direct collection tab presence is uncertain.");
|
|
363
|
+
const original = object(result(JSON.parse(before.stdout), "tab_info").tab, "collection tab");
|
|
364
|
+
if (original.tab_id !== tab.tabId || original.workspace_id !== workspaceId || ![0, 1].includes(original.pane_count)) {
|
|
365
|
+
throw new Error("Direct collection tab identity or pane count changed.");
|
|
366
|
+
}
|
|
367
|
+
await assertSettledDirectSession(tab.sessionFile, tab.turn);
|
|
368
|
+
await this.stop(tab, current, true);
|
|
369
|
+
const response = await herdr.exec(["tab", "get", tab.tabId], options());
|
|
370
|
+
if (!response.killed && hasHerdrErrorCode(response, "tab_not_found"))
|
|
371
|
+
return true;
|
|
372
|
+
if (response.code !== 0 || response.killed)
|
|
373
|
+
throw new Error("Direct collection tab presence is uncertain.");
|
|
374
|
+
const saved = object(result(JSON.parse(response.stdout), "tab_info").tab, "collection tab");
|
|
375
|
+
if (saved.tab_id !== tab.tabId || saved.workspace_id !== workspaceId || saved.pane_count !== 0) {
|
|
376
|
+
throw new Error("Direct collection requires the exact empty worker tab.");
|
|
377
|
+
}
|
|
378
|
+
if (!current())
|
|
379
|
+
throw new Error("Direct collection scope changed.");
|
|
380
|
+
result(await herdr.json(["tab", "close", tab.tabId], options()), "ok");
|
|
381
|
+
const after = await herdr.exec(["tab", "get", tab.tabId], options());
|
|
382
|
+
if (after.killed || !hasHerdrErrorCode(after, "tab_not_found"))
|
|
383
|
+
throw new Error("Direct collection tab absence is unproved.");
|
|
384
|
+
return true;
|
|
385
|
+
},
|
|
354
386
|
/** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
|
|
355
387
|
async start(launch, name, label, task, signal, onTab, requireSuccess = false, resume) {
|
|
356
388
|
const reader = directTaskReader(task, launch.tools);
|
package/dist/herdr-runtime.d.ts
CHANGED
|
@@ -101,6 +101,9 @@ export declare class HerdrHostRuntime implements HostRuntime {
|
|
|
101
101
|
kind: HostCleanupKind;
|
|
102
102
|
task: TaskRequest;
|
|
103
103
|
attempt: TaskAttempt;
|
|
104
|
+
collection?: {
|
|
105
|
+
current(): boolean;
|
|
106
|
+
};
|
|
104
107
|
}, context: OperationContext): Promise<{
|
|
105
108
|
outcome: "completed" | "absent";
|
|
106
109
|
} | {
|
package/dist/herdr-runtime.js
CHANGED
|
@@ -687,6 +687,15 @@ export class HerdrHostRuntime {
|
|
|
687
687
|
return { outcome: "blocked", failure: "Host cleanup requires exact worker termination or a definitive absent-agent allocation." };
|
|
688
688
|
}
|
|
689
689
|
try {
|
|
690
|
+
if (input.collection) {
|
|
691
|
+
if (!input.collection.current() || input.kind !== "worker_tab" || !terminationProven) {
|
|
692
|
+
throw new Error("Collection requires a current scope and a terminated worker tab.");
|
|
693
|
+
}
|
|
694
|
+
const proof = await this.reconcileWorkerTermination({ task: input.task, attempt: input.attempt,
|
|
695
|
+
workerId: input.attempt.termination.workerId, candidate: input.attempt.termination.candidate }, context);
|
|
696
|
+
if (proof.outcome !== "terminated")
|
|
697
|
+
throw new Error(proof.outcome === "unknown" ? proof.failure : "Worker is active; tab retained.");
|
|
698
|
+
}
|
|
690
699
|
if (input.kind === "worker_tab") {
|
|
691
700
|
const owned = ownedIntent(input.attempt, "worker_tab");
|
|
692
701
|
const workspace = ownedIntent(input.attempt, "workspace");
|
|
@@ -724,6 +733,8 @@ export class HerdrHostRuntime {
|
|
|
724
733
|
if (workspaceIsAbsent || tab.workspace_id !== workspaceId || tab.label !== allocation.label || tab.pane_count !== 0) {
|
|
725
734
|
return { outcome: "blocked", failure: "The exact saved worker tab no longer matches its owned empty tab identity." };
|
|
726
735
|
}
|
|
736
|
+
if (input.collection && !input.collection.current())
|
|
737
|
+
throw new Error("Collection scope changed; tab retained.");
|
|
727
738
|
const closed = await this.herdr.exec(["tab", "close", tabId], this.processOptions(allocation.worktreeCwd, context, HERDR_OPERATION_CAP_MS));
|
|
728
739
|
if (closed.code !== 0 || closed.killed)
|
|
729
740
|
return { outcome: "blocked", failure: safeText(herdrCommandFailure(["tab", "close"], closed)) };
|
|
@@ -732,7 +743,8 @@ export class HerdrHostRuntime {
|
|
|
732
743
|
return { outcome: "blocked", failure: "The exact saved worker tab still exists after close." };
|
|
733
744
|
}
|
|
734
745
|
}
|
|
735
|
-
|
|
746
|
+
if (!input.collection)
|
|
747
|
+
await this.removeLeaseArtifacts(allocation, input.attempt.correlationToken, paneId, tabId, context);
|
|
736
748
|
return tab ? { outcome: "completed" } : { outcome: "absent" };
|
|
737
749
|
}
|
|
738
750
|
const workerCleanup = input.attempt.cleanup.find((step) => step.kind === "worker_tab");
|
package/dist/runner.d.ts
CHANGED
|
@@ -190,6 +190,10 @@ export interface HostRuntime {
|
|
|
190
190
|
cleanupHost(input: {
|
|
191
191
|
requestId: ExecuteRequest["id"];
|
|
192
192
|
kind: HostCleanupKind;
|
|
193
|
+
/** Tab-only collection keeps all session and lease evidence. */
|
|
194
|
+
collection?: {
|
|
195
|
+
current(): boolean;
|
|
196
|
+
};
|
|
193
197
|
task: TaskRequest;
|
|
194
198
|
attempt: TaskAttempt;
|
|
195
199
|
}, context: OperationContext): Promise<{
|
|
@@ -331,6 +335,8 @@ export declare class IsolatedRunner {
|
|
|
331
335
|
invalidIds: string[];
|
|
332
336
|
states: RunState[];
|
|
333
337
|
}>;
|
|
338
|
+
/** Collect only already terminated worker tabs. Do not change saved state or candidate resources. */
|
|
339
|
+
collectTabs(root: string, eligible: (workspaceId: string) => Promise<boolean>, current: () => boolean): Promise<string[]>;
|
|
334
340
|
/** True while a live productive run holds this root's lease; the lease does not name its request. */
|
|
335
341
|
hasProductiveRunLease(root: string): Promise<boolean>;
|
|
336
342
|
/** Classify orphaned work under the same repository lease as productive execution.
|
package/dist/runner.js
CHANGED
|
@@ -641,6 +641,56 @@ export class IsolatedRunner {
|
|
|
641
641
|
})),
|
|
642
642
|
})) };
|
|
643
643
|
}
|
|
644
|
+
/** Collect only already terminated worker tabs. Do not change saved state or candidate resources. */
|
|
645
|
+
async collectTabs(root, eligible, current) {
|
|
646
|
+
root = realpathSync.native(root);
|
|
647
|
+
const candidates = (states) => states.flatMap((state) => state.tasks.flatMap((task) => task.kind !== "changeset" ? []
|
|
648
|
+
: task.attempts.flatMap((attempt) => {
|
|
649
|
+
const workspace = allocationByKind(attempt, "workspace");
|
|
650
|
+
return attempt.termination?.status === "terminated" && workspace?.status === "owned" && workspace.workspaceId
|
|
651
|
+
&& !attempt.cleanup.some((step) => step.kind === "worker_tab" && step.status === "completed")
|
|
652
|
+
? [{ state, task, attempt, workspaceId: workspace.workspaceId }] : [];
|
|
653
|
+
})));
|
|
654
|
+
const listed = await this.listRequests(root);
|
|
655
|
+
const report = listed.invalidIds.map((id) => `Retained unreadable isolated request ${id}.`);
|
|
656
|
+
const workspaces = new Set();
|
|
657
|
+
for (const id of new Set(candidates(listed.states).map(({ workspaceId }) => workspaceId))) {
|
|
658
|
+
if (!current())
|
|
659
|
+
return report;
|
|
660
|
+
if (await eligible(id))
|
|
661
|
+
workspaces.add(id);
|
|
662
|
+
}
|
|
663
|
+
if (!workspaces.size || !current())
|
|
664
|
+
return report;
|
|
665
|
+
try {
|
|
666
|
+
return await this.withProductiveRun(root, async (lifecycle) => await this.store.withLock(root, async () => {
|
|
667
|
+
// Reload under the productive lease; the earlier inventory grants no mutation authority.
|
|
668
|
+
for (const { state, task, attempt, workspaceId } of candidates((await this.listRequests(root)).states)) {
|
|
669
|
+
if (!current())
|
|
670
|
+
return report;
|
|
671
|
+
if (!workspaces.has(workspaceId))
|
|
672
|
+
continue;
|
|
673
|
+
const scope = new DeadlineScope(this.coordinatorRuntime.now() + CLEANUP_SAFETY_BUDGET_MS, () => this.coordinatorRuntime.now());
|
|
674
|
+
try {
|
|
675
|
+
const result = await scope.call((context) => this.hostRuntime.cleanupHost({
|
|
676
|
+
requestId: state.request.id, kind: "worker_tab", task: changesetTaskRequest(state, task.taskId), attempt, collection: { current },
|
|
677
|
+
}, context));
|
|
678
|
+
if (result.outcome !== "absent")
|
|
679
|
+
report.push(`${state.request.id}/${task.taskId}/${attempt.number}: ${result.outcome === "blocked" ? `retained: ${result.failure}` : "worker tab collected"}.`);
|
|
680
|
+
}
|
|
681
|
+
finally {
|
|
682
|
+
scope.close();
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return report;
|
|
686
|
+
}, { productiveRunLease: lifecycle.lease }));
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
if (!(error instanceof ProductiveRunLeaseBusyError))
|
|
690
|
+
throw error;
|
|
691
|
+
return ["Isolated tabs retained: a productive run owns this checkout. Retry after it finishes."];
|
|
692
|
+
}
|
|
693
|
+
}
|
|
644
694
|
/** True while a live productive run holds this root's lease; the lease does not name its request. */
|
|
645
695
|
async hasProductiveRunLease(root) {
|
|
646
696
|
return await this.store.hasProductiveRunLease(root);
|
package/docs/orchestration.md
CHANGED
|
@@ -416,11 +416,25 @@ To close and delete many requests, select **Select multiple…** in `/subagent`,
|
|
|
416
416
|
|
|
417
417
|
The report lists removed, skipped, and failed resources. After complete cleanup, the request is `aborted`, candidates are `released`, and integration generations are superseded with completed cleanup. Partial cleanup remains visible as retained work. Reopen the request to review the remaining resources. Abort, prune, and release keep their existing preservation rules.
|
|
418
418
|
|
|
419
|
+
### Subagent Collection
|
|
420
|
+
|
|
421
|
+
Subagent Collection closes only verified completed worker tabs. It keeps saved sessions, process leases, worktrees, candidates, and recovery records. It never closes a workspace or its root tab.
|
|
422
|
+
|
|
423
|
+
Automatic collection checks each relevant workspace after direct `delegate_task` launches, after direct or isolated workflows finish, and when Main settles. More than 10 tabs in that workspace triggers collection. Ten is a trigger, not a maximum. Collection can close all eligible tabs, even after the count falls below 10. User tabs count toward the trigger but are never collection targets. There is no timer: changes from other clients wait for the next check.
|
|
424
|
+
|
|
425
|
+
Direct collection uses exact records on the current Pi session branch, in the current checkout and Herdr workspace. It requires the recorded final session turn. If the exact agent remains, it must be idle or done. Active local tasks, continued sessions, unverified allocations, and uncertain identities stay open. Pane absence and two empty process-lease scans must pass before an empty tab can close. Saved conversations remain available for `continueFrom`.
|
|
426
|
+
|
|
427
|
+
Isolated collection uses saved requests in the current checkout. It requires saved termination proof, then verifies agent and pane absence and two empty process-lease scans again. A live productive lease blocks collection. **Ready candidates keep their live workers because Main can still request a revision.** Workspaces, root tabs, orphaned requests, and requests in other checkouts stay unchanged. Use their existing recovery or cleanup actions.
|
|
428
|
+
|
|
429
|
+
Every `/subagent prune` call tries collection without the tab-count trigger, including calls while a worktree scan is busy. Collection runs before worktree review and does not require deletion approval. Collection failure does not prevent that review. Worktree and branch deletion still require the existing review and confirmation. `/subagent prune cancel` stops new collection steps; a dispatched close can finish.
|
|
430
|
+
|
|
419
431
|
### Prune leftover worktrees
|
|
420
432
|
|
|
433
|
+
Each `/subagent prune` call first runs [Subagent Collection](#subagent-collection), which closes only verified completed worker tabs and keeps their evidence. This separate action has no tab-count requirement and runs even if worktree review fails or has no candidates. It does not grant permission to delete worktrees or branches. A later cancellation does not reopen collected tabs.
|
|
434
|
+
|
|
421
435
|
Run `/subagent prune` to scan leftover worker and integration checkouts under `.worktrees/`. In interactive mode, the command starts a background scan, shows progress, and returns without waiting. It inspects at most four candidates at once. Candidates that share one checkout, including path aliases, are inspected one at a time. The results stay sorted and include every blocker.
|
|
422
436
|
|
|
423
|
-
When the scan is ready, the command sends a notification. It does not open a dialog. Run `/subagent prune` again to review that plan. Repeated commands during a scan, review, or cleanup show its status; they do not start another operation. All selection and confirmation dialogs stay in the foreground, including the review of whole owning requests. After confirmation, cleanup runs in the background. It removes items one at a time and reports removed, skipped, and failed items.
|
|
437
|
+
When the scan is ready, the command sends a notification. It does not open a dialog. Run `/subagent prune` again to review that plan. Repeated commands during a scan, review, or cleanup show its status; they do not start another worktree operation. Tab collection remains independent. All selection and confirmation dialogs stay in the foreground, including the review of whole owning requests. After confirmation, cleanup runs in the background. It removes items one at a time and reports removed, skipped, and failed items.
|
|
424
438
|
|
|
425
439
|
Use `/subagent prune cancel` to cancel a scan, ready plan, or cleanup. Cancellation stops new removal steps. An active step can finish; completed removals are not undone. The final cleanup report includes completed steps and partial removal, such as a removed checkout whose branch was kept. Wait for the active step to finish before starting another scan.
|
|
426
440
|
|
|
@@ -451,7 +465,7 @@ The list shows removable items first. The command never cuts a long list silentl
|
|
|
451
465
|
|
|
452
466
|
The command checks each item again immediately before removal and skips an item that changed. It checks ownership, the productive lease, Herdr panes, checkout state, the branch tip, ignored entries, and the launching session. The command deletes a branch only if it still points at the reviewed tip. It does not run automatic request-abort cleanup, because that separate workflow can remove other resources. If an aborted request still shows retained resources, inspect `subagent_status` and repeat `subagent_abort` to reconcile its saved cleanup state.
|
|
453
467
|
|
|
454
|
-
Without interactive
|
|
468
|
+
Without an interactive user interface, the command still collects eligible tabs. It then waits for the worktree scan and reports its results. It never deletes worktrees or branches in this mode.
|
|
455
469
|
|
|
456
470
|
A non-regular or unreadable state entry can block every item because its resource ownership is unknown. State files never change directly.
|
|
457
471
|
|
package/example.png
CHANGED
|
Binary file
|
package/extensions/isolated.ts
CHANGED
|
@@ -519,6 +519,7 @@ export interface IsolatedSurface {
|
|
|
519
519
|
plan(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof formatExecutePlan>>;
|
|
520
520
|
execute(request: ExecuteRequest, signal: AbortSignal | undefined, ctx: ExtensionContext): Promise<ReturnType<typeof toolResult>>;
|
|
521
521
|
inventory(cwd: string, current?: () => boolean): Promise<IsolatedInventory>;
|
|
522
|
+
collectTabs(cwd: string, eligible: (workspaceId: string) => Promise<boolean>, current: () => boolean): Promise<string[]>;
|
|
522
523
|
recover(cwd: string): Promise<string>;
|
|
523
524
|
prunePlan(cwd: string, current?: () => boolean, progress?: PruneProgress): Promise<PrunePlan>;
|
|
524
525
|
discardPlan(cwd: string, request: IsolatedRequest): Promise<DiscardPlan>;
|
|
@@ -537,6 +538,8 @@ export interface RegisterIsolatedOptions {
|
|
|
537
538
|
/** Report new config issues, and throw when the config now blocks delegation, before each deferred Role launch. */
|
|
538
539
|
beforeRoleLaunch?(ctx: ExtensionContext): void;
|
|
539
540
|
componentsFactory?: CreateIsolatedComponents;
|
|
541
|
+
/** Notification after productive work releases its lease. */
|
|
542
|
+
onFinished?(ctx: ExtensionContext): void;
|
|
540
543
|
}
|
|
541
544
|
|
|
542
545
|
/** Register lifecycle surfaces; delegate_task remains the only start tool. */
|
|
@@ -725,6 +728,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
725
728
|
return;
|
|
726
729
|
}
|
|
727
730
|
deliver("terminal", `${response.text}\n\nState: ${JSON.stringify(publicState(response.state, PUBLIC_EVIDENCE_MAX_BYTES))}`, response);
|
|
731
|
+
if (canDeliver()) options.onFinished?.(ctx);
|
|
728
732
|
},
|
|
729
733
|
(error: unknown) => {
|
|
730
734
|
finish();
|
|
@@ -735,6 +739,7 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
735
739
|
return;
|
|
736
740
|
}
|
|
737
741
|
deliver("terminal", `Pi Subagent ${id} stopped: ${boundedPublicText(error instanceof Error ? error.message : String(error))}. Use subagent_status to inspect the durable request before choosing an explicit recovery action.`);
|
|
742
|
+
if (canDeliver()) options.onFinished?.(ctx);
|
|
738
743
|
},
|
|
739
744
|
);
|
|
740
745
|
const state = await durable;
|
|
@@ -852,6 +857,11 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
|
|
|
852
857
|
const leaseLive = await getComponents().runner.hasProductiveRunLease(root);
|
|
853
858
|
return { root, leaseLive, requests: [...requests, ...orphans.requests], invalidIds: [...new Set([...invalidIds, ...orphans.invalidIds])] };
|
|
854
859
|
},
|
|
860
|
+
async collectTabs(cwd, eligible, current) {
|
|
861
|
+
const root = await lookupRoot(cwd);
|
|
862
|
+
requireCurrent(current);
|
|
863
|
+
return await getComponents().runner.collectTabs(root, eligible, () => current() && !sessionClosed);
|
|
864
|
+
},
|
|
855
865
|
async recover(cwd) {
|
|
856
866
|
const root = await lookupRoot(cwd);
|
|
857
867
|
const { requests, invalidIds, leaseBusy } = await getComponents().runner.recoverRepository(root);
|
|
@@ -77,6 +77,8 @@ export interface SubagentCommandAdapter {
|
|
|
77
77
|
stopDirect(task: DirectTask, entryId: string, current: () => boolean): Promise<string>;
|
|
78
78
|
isolated(cwd: string, current: () => boolean): Promise<IsolatedInventory>;
|
|
79
79
|
recover(cwd: string): Promise<string>;
|
|
80
|
+
/** Tab collection is independent of worktree deletion review and confirmation. */
|
|
81
|
+
collect(ctx: ExtensionContext, current: () => boolean): Promise<string>;
|
|
80
82
|
/** Read-only review of pi-subagent worktrees and branches in the canonical repository. */
|
|
81
83
|
prunePlan(cwd: string, current?: () => boolean, progress?: PruneProgress): Promise<PrunePlan>;
|
|
82
84
|
discardPlan(cwd: string, request: IsolatedRequest): Promise<DiscardPlan>;
|
|
@@ -415,6 +417,7 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
415
417
|
};
|
|
416
418
|
let pruneJob: PruneJob | undefined;
|
|
417
419
|
let generation = 0;
|
|
420
|
+
let collectionGeneration = 0;
|
|
418
421
|
const clearPruneStatus = (job: PruneJob) => {
|
|
419
422
|
if (job.indicator) job.ctx.ui.setStatus("subagent-prune", undefined);
|
|
420
423
|
job.indicator = false;
|
|
@@ -476,11 +479,22 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
476
479
|
const notify = (message: string) => ctx.hasUI ? ctx.ui.notify(message, "info") : deliver(ctx, textReport("info", message));
|
|
477
480
|
if (pruneJob && !pruneJob.current()) cancelPrune(pruneJob);
|
|
478
481
|
if (command === "prune cancel") {
|
|
482
|
+
collectionGeneration++;
|
|
479
483
|
const job = pruneJob;
|
|
480
484
|
if (job) cancelPrune(job);
|
|
481
485
|
notify(job ? "Prune cancelled. An active step can finish; completed removals are not undone." : "No prune operation is active.");
|
|
482
486
|
return;
|
|
483
487
|
}
|
|
488
|
+
const collection = collectionGeneration;
|
|
489
|
+
const collectionCurrent = () => current() && collection === collectionGeneration;
|
|
490
|
+
try {
|
|
491
|
+
const report = await adapter.collect(ctx, collectionCurrent);
|
|
492
|
+
if (!collectionCurrent()) return;
|
|
493
|
+
deliver(ctx, textReport("info", report), "pi-subagent-collection");
|
|
494
|
+
} catch (error) {
|
|
495
|
+
if (!collectionCurrent()) return;
|
|
496
|
+
deliver(ctx, textReport("warning", `Subagent Collection failed: ${errorText(error)}. Worktree review remains separate.`));
|
|
497
|
+
}
|
|
484
498
|
if (pruneJob && pruneJob.state.kind !== "ready") {
|
|
485
499
|
notify(pruneJob.cancelled ? "Prune is stopping; wait for the active step." : `${pruneJob.status}. Use /subagent prune cancel to stop.`);
|
|
486
500
|
return;
|
|
@@ -500,7 +514,7 @@ export function registerSubagentCommand(pi: ExtensionAPI, adapter: SubagentComma
|
|
|
500
514
|
} else {
|
|
501
515
|
job.state = { kind: "ready", plan };
|
|
502
516
|
pruneStatus(job, "Prune ready · /subagent prune");
|
|
503
|
-
ctx.ui.notify("Prune scan ready. Run /subagent prune to review it. No
|
|
517
|
+
ctx.ui.notify("Prune scan ready. Run /subagent prune to review it. No worktrees or branches were removed.", "info");
|
|
504
518
|
}
|
|
505
519
|
} catch (error) {
|
|
506
520
|
if (job.current() && !job.cancelled) deliver(ctx, textReport("error", `Prune scan failed: ${errorText(error)}`));
|
package/extensions/subagent.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { directRef, registerSubagentCommand, type DirectDisplay, type DirectTask
|
|
|
11
11
|
import { MODEL_CLASS_GUIDANCE } from "./model-class-policy.ts";
|
|
12
12
|
import { compactCost, compactTokens, ENTRY_STATUS_PRESENTATION, formatWorkflowResult, workerOutputForMain, type BackgroundWorkflowTransportDetails, type WorkflowTransportEntry } from "./result-transport.ts";
|
|
13
13
|
import { checkoutNote, DelegateTaskParameters, identifyWorkflowEntries, parseDelegateTask, runForegroundWorkflow, snapshotCheckout, writesCheckout, type CheckoutSnapshot, type ParsedWorkflow, type WorkflowEntry } from "./workflow.ts";
|
|
14
|
+
import { workspaceNeedsCollection } from "../dist/collection.js";
|
|
14
15
|
import { assertSettledDirectSession, createDirectHerdr, DirectAllocationError, directTaskReader, type DirectAllocation, type DirectHandle, type DirectTab, type DirectToolActivity, type DirectUsage } from "../dist/direct-herdr.js";
|
|
15
16
|
import { materializeTransientLaunch } from "../dist/launch-runtime.js";
|
|
16
17
|
const WIDGET_KEY = "subagent-status";
|
|
@@ -252,6 +253,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
252
253
|
policy: initialPolicy,
|
|
253
254
|
currentPolicy,
|
|
254
255
|
beforeRoleLaunch,
|
|
256
|
+
onFinished: (ctx) => automaticCollection(ctx),
|
|
255
257
|
});
|
|
256
258
|
let directSequence = 0;
|
|
257
259
|
const directTasks = new Map<string, {
|
|
@@ -269,6 +271,66 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
269
271
|
&& tab.paneId === saved.paneId && tab.sessionFile === saved.sessionFile;
|
|
270
272
|
});
|
|
271
273
|
let sessionEpoch = 0;
|
|
274
|
+
let collectionEpoch = 0;
|
|
275
|
+
let collecting: Promise<string[]> | undefined;
|
|
276
|
+
let pendingCollection: (() => void) | undefined;
|
|
277
|
+
pi.on("session_tree", () => { collectionEpoch++; });
|
|
278
|
+
const collectTabs = async (ctx: ExtensionContext, manual: boolean, current: () => boolean): Promise<string[]> => {
|
|
279
|
+
while (collecting) await collecting;
|
|
280
|
+
if (!current()) return [];
|
|
281
|
+
const work = async () => {
|
|
282
|
+
const report: string[] = [];
|
|
283
|
+
let triggered = manual;
|
|
284
|
+
const workspaces = new Map<string, Promise<boolean>>();
|
|
285
|
+
const eligible = (id: string) => {
|
|
286
|
+
if (!workspaces.has(id)) workspaces.set(id, manual ? Promise.resolve(true) : workspaceNeedsCollection(pi, ctx.cwd, id).then((due) => { triggered ||= due; return due; }));
|
|
287
|
+
return workspaces.get(id)!;
|
|
288
|
+
};
|
|
289
|
+
const records = ctx.sessionManager.getBranch().flatMap((entry) => entry.type === "custom" && entry.customType === DIRECT_TAB_TYPE
|
|
290
|
+
? [entry.data as DirectTabRecord] : []);
|
|
291
|
+
const seen = new Set<string>();
|
|
292
|
+
for (const tab of records) {
|
|
293
|
+
if (!current()) break;
|
|
294
|
+
if (!tab.turn || !tab.workspaceId || !tab.cwd || seen.has(tab.tabId)) continue;
|
|
295
|
+
seen.add(tab.tabId);
|
|
296
|
+
const unowned = () => current() && !directTasks.has(tab.taskId)
|
|
297
|
+
&& ![...directTasks.values()].some((task) => task.continues?.has(tab.sessionFile));
|
|
298
|
+
if (!unowned()) continue;
|
|
299
|
+
try {
|
|
300
|
+
if (!await eligible(tab.workspaceId) || !unowned()) continue;
|
|
301
|
+
const herdr = createDirectHerdr(pi, ctx.cwd, currentPolicy().childIdleMs);
|
|
302
|
+
if (await herdr.collect(tab as DirectTab, unowned)) report.push(`${tab.tabId}: direct worker tab collected.`);
|
|
303
|
+
} catch (error) { report.push(`${tab.tabId}: retained: ${boundedError(error).message}`); }
|
|
304
|
+
}
|
|
305
|
+
if (current()) {
|
|
306
|
+
try { report.push(...await isolatedSurface.collectTabs(ctx.cwd, eligible, current)); }
|
|
307
|
+
catch (error) { report.push(`Isolated tabs retained: ${boundedError(error).message}`); }
|
|
308
|
+
}
|
|
309
|
+
return triggered ? report : [];
|
|
310
|
+
};
|
|
311
|
+
collecting = work();
|
|
312
|
+
try { return await collecting; } finally {
|
|
313
|
+
collecting = undefined;
|
|
314
|
+
const pending = pendingCollection;
|
|
315
|
+
pendingCollection = undefined;
|
|
316
|
+
pending?.();
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
const automaticCollection = (ctx: ExtensionContext) => {
|
|
320
|
+
if (process.env.HERDR_ENV !== "1") return;
|
|
321
|
+
const epoch = sessionEpoch;
|
|
322
|
+
const tree = collectionEpoch;
|
|
323
|
+
const session = ctx.sessionManager.getSessionId();
|
|
324
|
+
const branch = ctx.sessionManager.getBranch().map((entry) => entry.id);
|
|
325
|
+
const existing = new Set(ctx.sessionManager.getEntries().map((entry) => entry.id));
|
|
326
|
+
const current = () => epoch === sessionEpoch && tree === collectionEpoch && session === ctx.sessionManager.getSessionId()
|
|
327
|
+
&& branch.every((id, index) => ctx.sessionManager.getBranch()[index]?.id === id)
|
|
328
|
+
&& ctx.sessionManager.getBranch().slice(branch.length).every((entry) => !existing.has(entry.id));
|
|
329
|
+
if (collecting) { pendingCollection = () => { if (current()) automaticCollection(ctx); }; return; }
|
|
330
|
+
void collectTabs(ctx, false, current).then((report) => {
|
|
331
|
+
if (current() && report.length && ctx.hasUI) ctx.ui.notify(capOutput(`Subagent Collection: closes only verified completed worker tabs.\n${report.join("\n")}`), "info");
|
|
332
|
+
}).catch((error) => { if (current() && ctx.hasUI) ctx.ui.notify(`Subagent Collection failed: ${boundedError(error).message}`, "warning"); });
|
|
333
|
+
};
|
|
272
334
|
pi.events.on("pi-subagent:pending-result", (data) => {
|
|
273
335
|
if (!data || typeof data !== "object" || !("sessionId" in data) || typeof data.sessionId !== "string"
|
|
274
336
|
|| !("pending" in data) || typeof data.pending !== "boolean") return;
|
|
@@ -353,6 +415,10 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
353
415
|
await local.stopWorker.stop(entryId, current);
|
|
354
416
|
return "Worker stopped; pane absence and empty lease scans proved. Other workers continue; Main receives one result when the workflow finishes.";
|
|
355
417
|
},
|
|
418
|
+
async collect(ctx, current) {
|
|
419
|
+
const report = await collectTabs(ctx, true, current);
|
|
420
|
+
return capOutput(`Subagent Collection: closes only verified completed worker tabs.\n${report.length ? report.join("\n") : "No eligible tabs to close."}\nSessions, worktrees, candidates, and recovery evidence kept. Worktree deletion requires separate review and confirmation.`);
|
|
421
|
+
},
|
|
356
422
|
isolated: isolatedSurface.inventory,
|
|
357
423
|
recover: (cwd) => isolatedSurface.recover(cwd),
|
|
358
424
|
prunePlan: (cwd, current, progress) => isolatedSurface.prunePlan(cwd, current, progress),
|
|
@@ -601,6 +667,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
601
667
|
});
|
|
602
668
|
pi.on("agent_settled", (_event, ctx) => {
|
|
603
669
|
latestCtx = ctx;
|
|
670
|
+
automaticCollection(ctx);
|
|
604
671
|
});
|
|
605
672
|
|
|
606
673
|
const reportDirect = (
|
|
@@ -866,6 +933,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
866
933
|
handles.push(handle);
|
|
867
934
|
handleByEntry.set(entry.id, handle);
|
|
868
935
|
if (widgetItems.has(entry.id)) tokenHandles.set(entry.id, handle);
|
|
936
|
+
if (launchEpoch === sessionEpoch) automaticCollection(ctx);
|
|
869
937
|
return handle;
|
|
870
938
|
};
|
|
871
939
|
// The first tab is verified before returning a handle; subsequent independent
|
|
@@ -961,6 +1029,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
|
|
|
961
1029
|
local.pendingResult = undefined;
|
|
962
1030
|
if (!controller.signal.aborted) reportDirect(launchEpoch, taskId, ref, workflow.mode, [...states.values()], tabs, local.recovery);
|
|
963
1031
|
resolveSettled();
|
|
1032
|
+
if (launchEpoch === sessionEpoch) automaticCollection(ctx);
|
|
964
1033
|
}
|
|
965
1034
|
})();
|
|
966
1035
|
return {
|