pi-better-subagents 0.25.1 → 0.26.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/docs/usage.md CHANGED
@@ -96,66 +96,87 @@ thresholds continue to take precedence for subagent health.
96
96
 
97
97
  | Tool | Blocks? | What it does |
98
98
  |------|---------|--------------|
99
- | `subagent_spawn` | never | Launch a task in a background subagent; returns a run id at once. Params: `prompt`, `name`, `model`, `tools` (allowlist), `exclude_tools`, `sandbox`, `sandbox_dir`, `callback`, `clean`, `cwd`, `git_clone_workspace`, `approve`, `allow_nested`, `retain_session` (keep the completed conversation and workspace available for `subagent_resume`), and the [timing](#run-timing-deadline-ceiling-stuck) overrides `deadline_minutes`, `grace_minutes`, `max_minutes`, `stuck_minutes`. |
100
- | `subagent_spawn_batch` | never | Launch several independent subagents at once. Each job becomes a normal run. Params: `batchName`, `shared` (options applied to every job), `jobs[]` (each needs `prompt`; launch options follow the declared batch schema, which omits `retain_session`), `onCapacity` (`reject` or `launch-available`). |
101
- | `subagent_resume` | never | Continue a completed run in its own saved conversation. Params: `id` (the completed attempt), `prompt` (the next user turn — do not restate the task or role), optional `model`/`thinking` (explicit escalation only; otherwise the saved recipe wins), `callback`, and the timing overrides. Returns a NEW run id with the same native session id and `resumedFrom` lineage. See [continuing a completed subagent](#continuing-a-completed-subagent). |
102
- | `subagent_release` | never | Release `retain_session` protection for a completed conversation and its workspace. Nothing is deleted now and no completed result is rewritten; ordinary cleanup may reclaim the artifacts afterwards. Only the owning foreground session may release. |
99
+ | `subagent_spawn` | never | Launch a task in a background subagent; returns a run id at once. Params: `prompt`, `name`, `model`, `tools` (allowlist), `exclude_tools`, `sandbox`, `sandbox_dir`, `callback`, `clean`, `cwd`, `git_clone_workspace`, `approve`, `allow_nested`, optional `session_id` or `session_name` (continue a saved conversation), and the [timing](#run-timing-deadline-ceiling-stuck) overrides `deadline_minutes`, `grace_minutes`, `max_minutes`, `stuck_minutes`. |
100
+ | `subagent_spawn_batch` | never | Launch several independent subagents at once. Each job becomes a normal run. Params: `batchName`, `shared` (options applied to every job), `jobs[]` (each needs `prompt`; optional per-job `session_id` or `session_name` continues a saved conversation), `onCapacity` (`reject` or `launch-available`). |
103
101
  | `subagent_settings` | never | Read-only effective settings and capacity snapshot. No parameters. Returns `delegationMode`, `maxConcurrent`, per-setting `sources` (`session` or `config`), a stable settings `revision`, `runningCount`, `pendingCount`, `occupiedSlots`, and `availableSlots`. The limit is a ceiling, not a target; spawn admission rechecks live capacity. |
104
- | `subagent_list` | never | Compact current-session list (default 10 rows / 1 KiB page). Params: `all` (machine-global / foreign session), `limit` (default 10, max 100), `cursor`, `max_bytes` (max 4 KiB), `status` (`running`, `completed`, `failed`, `killed`, `exited`, durable `orphaned`, `lost`). Incident counts are compact; no spend/tool histories. |
105
- | `subagent_output` | never | Bounded current-session excerpt (default 1 KiB / 10 lines). Params: `id`, `lines` (`tail_lines` is a deprecated alias), `cursor` (a returned `nextCursor`, `statusCursor`, or `incidentCursor`), `max_bytes` (max 4 KiB; raw 16 KiB default, 64 KiB max), `mode` (`raw` pages retained log bytes), `include` (`["cost"]`, `["tools"]`, or both: opt-in spend and tool-count lines), `all` (foreign-session id). Missing/unreadable logs are gaps, not empty healthy output. |
106
- | `subagent_result` | never | Finished-run answer for the current session (2048-byte page). Params: `id`, `cursor` (a returned `nextCursor` continues the answer; `statusCursor` / `incidentCursor` also accepted), `max_bytes` (maximum 8192 bytes), `lines` (optional line cap per answer page), `mode` (`raw`), `include` (`["cost"]`, `["tools"]`, or both), `all` (foreign-session id). Failures and exceptional lifecycle facts come before progress; no tool-name histories. TUI folding is display-only. |
107
- | `subagent_stop` | never | SIGTERM a running run's process group. |
108
-
109
- ## Continuing a completed subagent
110
-
111
- A finished subagent can be given more work in **its own conversation** instead
112
- of starting a fresh worker that has lost the context. Both single and batch
113
- launches save sessions normally; `subagent_resume` needs no retention flag.
114
- `retain_session` only protects saved artifacts from ordinary cleanup. Releasing
115
- that protection does not prevent resume while the history and workspace still exist:
116
-
117
- | Step | What happens |
118
- |------|--------------|
119
- | `subagent_spawn` with `retain_session: true` | Marks the conversation and its workspace as retained while follow-up may be needed. The child still ends normally and a parked owner occupies **no** concurrency slot. Ordinary one-shot runs omit it and are unchanged. |
120
- | `subagent_resume({ id, prompt, … })` | Starts a NEW attempt: new run id, log, result, timing record, and capacity slot. The native session id, the exact saved conversation, and the frozen launch recipe stay the same, and the new attempt records `resumedFrom`/`rootRunId` lineage. `prompt` is the next user turn; the original task and role instructions already live in the history. |
121
- | `subagent_release({ id })` | Releases retention without deleting anything. Logs, results, and completed metadata stay intact; ordinary cleanup may reclaim the conversation and workspace afterwards. |
122
-
123
- Continuation rules:
124
-
125
- - Only a `completed` attempt can be continued. A running or orphaned attempt
126
- must be stopped first; `failed`, `killed`, and `lost` attempts are not
127
- continuation targets.
128
- - Only the foreground session that launched the run may continue or release it.
129
- - The saved conversation must still exist and must name the same native session
130
- id and workspace. A missing, ambiguous, or mismatched history refuses instead
131
- of starting a replacement conversation, and a missing workspace refuses too.
132
- Continuation passes the exact validated `--session` path; Pi's create-if-missing
133
- fallbacks are never used.
134
- - The attempt keeps the recipe's effective tools, exclusions, clean/nesting and
135
- approval intent, confinement, and model/effort. Pass `model`/`thinking` only to
136
- escalate explicitly for that attempt. Current mandatory human permissions are
137
- re-applied every time; a profile that would change confinement refuses instead
138
- of silently running the conversation under different rules.
139
- - Resolved extension implementations are recorded too. If current tool/provider
140
- configuration would silently replace one, continuation refuses; an explicit model
141
- escalation can select its required provider without changing tool implementations.
142
- - A continuation never prepares another Git clone. It reuses the recorded
143
- workspace, including uncommitted work. Age/size cleanup protects all attempts that
144
- own shared conversation resources while a continuation or pending admission uses them.
145
- - Retain the implementation owner through review fixes. Resume an independent reviewer
146
- only to finish an unfinished review on the same HEAD/scope; after a completed round,
147
- start a fresh reviewer with the retained findings and existing selected review scope.
148
- - One conversation admits one writer. A cross-process lease is held from
149
- admission through child lifetime and finalization; duplicate requests are
150
- refused, and a lease left behind by a dead process (or by an already
151
- finalized attempt) is recovered conservatively. Lease/retention mutations use a
152
- short kernel-owned SQLite transaction; retained launches and continuation require
153
- a runtime with `node:sqlite` (Node 24 recommended). Ordinary one-shot launches
154
- remain available without it. A dead coordinator with no published child metadata
155
- is ambiguous and cannot authorize another writer.
156
- - Retention uses the existing temporary runtime storage. It is a bounded
157
- availability promise, not permanent storage: if system temp is reaped, the
158
- history is gone and continuation refuses with a clear error.
102
+ | `subagent_list` | never | Compact list for the current folder and descendants across foreground sessions (default 10 rows / 1 KiB page). Each row includes `session_id`. Params: `all` (machine-global search), `limit` (default 10, max 100), `cursor`, `max_bytes` (max 4 KiB), `status` (`running`, `completed`, `failed`, `killed`, `exited`, durable `orphaned`, `lost`). Incident counts are compact; no spend/tool histories. Abandoned launch records are reported separately and are never counted as runs. |
103
+ | `subagent_output` | never | Bounded current-session excerpt (default 1 KiB / 10 lines). Params: `id`, `lines` (`tail_lines` is a deprecated alias), `cursor` (a returned `nextCursor`, `statusCursor`, or `incidentCursor`), `max_bytes` (max 4 KiB; raw 16 KiB default, 64 KiB max), `mode` (`raw` pages retained log bytes), `tail` (raw mode: start from the newest retained byte and page backwards; the final step returns an append-ready cursor), `include` (`["cost"]`, `["tools"]`, or both: opt-in spend and tool-count lines), `all` (foreign-session id). Missing/unreadable logs are gaps, not empty healthy output. |
104
+ | `subagent_result` | never | Finished-run answer for the current session (2048-byte page). Params: `id`, `cursor` (a returned `nextCursor` continues the answer; `statusCursor` / `incidentCursor` also accepted), `max_bytes` (maximum 8192 bytes), `lines` (optional line cap per answer page), `mode` (`raw`), `tail` (raw mode: newest bytes first), `include` (`["cost"]`, `["tools"]`, or both), `all` (foreign-session id). Failures and exceptional lifecycle facts come before progress; no tool-name histories. TUI folding is display-only. |
105
+ | `subagent_stop` | never | SIGTERM a running run's process group. The run is terminal, so its completion callback (one per run id) reports `killed`. An abandoned launch record (see below) is removed instead of stopped, and a run a concurrent launch owns is preserved. |
106
+
107
+ ## Finding a saved conversation
108
+
109
+ `subagent_list()` searches the current folder and its descendants, including runs
110
+ from other foreground sessions. Use `subagent_list({ all: true })` for a global
111
+ search. Each row shows both the attempt id and `session_id`; use the session id
112
+ when continuing work. A continuation keeps that session id while receiving a new
113
+ attempt id.
114
+
115
+ ```javascript
116
+ subagent_list()
117
+ subagent_list({ all: true })
118
+ ```
119
+
120
+ Local name lookup follows the same folder scope. A duplicate name is not resolved
121
+ by choosing the newest conversation; use one of the reported session ids instead.
122
+
123
+ ## Continuing a saved conversation
124
+
125
+ Use the same spawn tool for new work and follow-up work:
126
+
127
+ ```javascript
128
+ subagent_spawn({ name: "implementation", prompt: "Implement the change." })
129
+ subagent_spawn({ session_id: "<saved-session-id>", prompt: "Fix the review findings." })
130
+ subagent_spawn({ session_name: "implementation", prompt: "Fix the review findings." })
131
+ ```
132
+
133
+ A launch without a session selector starts a new conversation. With a selector,
134
+ `prompt` is the next user turn; the original task and role are already saved.
135
+ Each attempt gets a new run id, log, timing record, and capacity slot while the
136
+ native session id and history stay the same. The launch recipe preserves the
137
+ worker's role, tools, model, and workspace, including uncommitted changes.
138
+
139
+ A run stopped with `subagent_stop` (status `killed`) can be continued the same
140
+ way. Stopping ends that execution, not the saved conversation or its
141
+ uncommitted workspace: the next attempt reopens the same history and records
142
+ `resumedFrom`, while the stopped attempt's status, log, and result stay as they
143
+ were. A run that ended `failed` or `lost` is still refused; this path recovers
144
+ interrupted work, it does not retry a failed run. The stopped child must also
145
+ have exited: if the stop signal has not taken effect yet (for example the
146
+ process was suspended), continuation is refused until that recorded child exits.
147
+ The saved history and workspace stay intact while the stop settles.
148
+
149
+ `session_name` is an exact display-name match within the current folder and its
150
+ descendants. Several attempts of the same conversation count once. If several
151
+ conversations share the name, spawn reports matching session ids and refuses to
152
+ guess. Use `subagent_list({ all: true })` to find conversations elsewhere and
153
+ pass `session_id`. `name` remains a new-launch label.
154
+
155
+ Single and batch launches save native Pi sessions and completed launch recipes
156
+ durably in the Pi agent directory. No retention flag or release tool is needed.
157
+ Temporary event logs can be cleaned up independently. Missing or manually deleted
158
+ history is never recreated by continuation. Older recipes pointing at temporary
159
+ session files remain usable only while those original files exist.
160
+
161
+ A different foreground session may continue a conversation. The new attempt's
162
+ callback goes to its caller; previous attempts keep their original evidence.
163
+ Only a completed conversation with an existing workspace and verified saved
164
+ history can continue. One conversation admits one writer: active or orphaned
165
+ attempts and live writer leases refuse competing launches. Continuation requires
166
+ a runtime with `node:sqlite` (Node 24 recommended).
167
+
168
+ Current mandatory human permissions apply on every attempt. A change that would
169
+ alter confinement or replace recorded tool implementations refuses continuation.
170
+ Only explicit model/effort escalation changes the saved model choice; a continued
171
+ worker does not silently inherit the caller's model or re-resolve its role.
172
+
173
+ Use per-job `session_id` or `session_name` in `subagent_spawn_batch`. A batch may
174
+ mix fresh and continued jobs. Keep one job per conversation; the writer lease
175
+ rejects competing jobs.
176
+
177
+ If new parameters are missing after an npm upgrade, run `/reload` in Pi.
178
+ Updating files on disk does not replace extension code already loaded in a live
179
+ session.
159
180
 
160
181
  ## Codemode batch launches
161
182
 
@@ -233,10 +254,15 @@ may be fractional. A job's own number (including `0`) wins over `shared`.
233
254
  sandbox command time limit can bound individual commands. With the run ceiling off, a steer stuck behind a
234
255
  hung tool call is never delivered, the deadline stop stays held, and the run
235
256
  is never stopped by that deadline. Opt into a ceiling to bound the whole run.
236
- - The parent reads at most the last 32 MiB of a child log after `/reload`. If
237
- the log is larger and the running tool call started before that window, the
238
- parent cannot see the call, so the hold is lost and grace counts from when
239
- the steer was sent. The child can be stopped mid-call.
257
+ - The parent reads at most the last 32 MiB of a child log after `/reload`. It
258
+ also records the call it last saw open in the run's metadata on each
259
+ supervision tick, so a reload normally keeps the hold and the not-stuck
260
+ accounting even when the call's start is outside that window. The record is
261
+ written by the tick, so a call that started less than one tick (15 s) before
262
+ the reload is not covered; and a record whose call ended while the window was
263
+ lost keeps the hold, and keeps the run from being reported stuck, until the
264
+ next observed tool call starts. Opt into a ceiling when the run needs a hard
265
+ wall-clock bound.
240
266
  - The child confirms delivery by matching the steer's exact text in its
241
267
  conversation. If another extension rewrites user input (an input-transform
242
268
  hook), the text no longer matches, no receipt is written, and grace silently
@@ -255,7 +281,9 @@ harness remembers up to 4096 distinct calls per run as fixed-size hashes of the
255
281
  name and normalized arguments; past that the oldest is forgotten, so a call from
256
282
  long ago counts again. Time the child spends waiting on a running tool call does not count toward the
257
283
  stuck window, so a child in the middle of a 20-minute test run is waiting, not
258
- stuck. A hanging command can be bounded by the sandbox command time limit; the run
284
+ stuck — including after `/reload`: the call the parent saw open is stored in the
285
+ run's metadata, so a bounded log read that no longer contains its start does not
286
+ turn it into "no progress". A hanging command can be bounded by the sandbox command time limit; the run
259
287
  ceiling separately bounds the whole run.
260
288
  The other stuck signal is the existing escalation: the same operation failing
261
289
  three times wakes the parent once as an `Action required` incident
@@ -316,6 +344,14 @@ given.
316
344
  pending records retryable, and `/reload` recovers records explicitly marked
317
345
  pending. `callback:false` sends no model message; read the durable result later
318
346
  with `subagent_result`.
347
+ - **One completion per run.** A run's ordinary notification is identified by
348
+ its run id, so a terminal run is reported once even if its status wording
349
+ changes (failure notes, observation gaps) between queueing and delivery.
350
+ Stopped runs are terminal too: `subagent_stop`, a navigator Close, the reload
351
+ drain, or cleanup that finalizes an orphaned run from its log records the same
352
+ pending completion, so the caller receives one `killed`/`completed`/`failed`
353
+ row instead of discovering the outcome by polling `subagent_list()`. A run
354
+ stopped while the session is shutting down is recovered by the next session.
319
355
  - **Optional busy steering.** In `/harness-settings`, set **Completions while
320
356
  busy** to **Steer active run** to receive ordinary completions during
321
357
  foreground work. Changes autosave to the current session branch and apply
@@ -748,10 +784,12 @@ state. Session shutdown disposes open navigator timers.
748
784
 
749
785
  ## Design notes
750
786
 
751
- - Runtime lives outside any repo, under `$TMPDIR/pi-better-subagents/`
752
- (`runs/<id>/` holds `output.log`, `prompt.md`, `meta.json`; `sessions/` holds
753
- child session state). The `meta.json` sidecar is authoritative, so `list` /
754
- `output` / `result` survive turns, `/reload`, and pi restarts.
787
+ - Temporary run evidence lives outside any repo under `$TMPDIR/pi-better-subagents/`
788
+ (`runs/<id>/` holds `output.log`, `prompt.md`, and `meta.json`). Native child
789
+ sessions and compact completed-attempt recipes persist under the Pi agent
790
+ directory in `subagents/sessions` and `subagents/attempts`. Event-log cleanup
791
+ does not remove the saved conversation or recipe. Existing legacy recipes keep
792
+ their original session paths.
755
793
  - The child runs `--mode json`; `subagent_result` / `subagent_output` **parse**
756
794
  the event stream and return just the bounded final answer (no tool-name history).
757
795
  Non-JSON banner/warning lines fail to parse and are dropped, so the result is
@@ -763,7 +801,49 @@ state. Session shutdown disposes open navigator timers.
763
801
 
764
802
  ## Parent-process scoping
765
803
 
766
- The live widget, default `subagent_list`, concurrency cap, and `session_start` ticker only include runs this pi process spawned (`spawnPid === process.pid`). The on-disk registry stays machine-global for durability. Default `subagent_list` is current-session, newest first, 10 compact rows / 1 KiB. Pass `limit:N` (max 100) or `max_bytes` (max 4 KiB) for an explicit larger page. Pass `all:true` for a global / foreign-session view. Pass `status:[...]` to filter by effective status: `running`, `completed`, `failed`, `killed`, transient `exited`, or durable `orphaned` / `lost`. Id-based `subagent_result` / `subagent_output` default to the current session; pass `all:true` to read a foreign-session id. Unknown ownership is a gap, not “not found”; when the current session identity cannot be read, no run's ownership is treated as verified and `all:true` is required. List pages are reached with the returned `nextCursor` (every run is reachable, not only the first 100). Runs whose metadata is missing or corrupt are reported as gaps and counted on lists, never as nonexistent.
804
+ The live widget, concurrency cap, and supervision ticker track this Pi process's runs. `subagent_list` searches the current folder and its descendants across foreground sessions; `all:true` searches globally. Rows show the attempt id and the native `session_id`, so a listed conversation can be continued explicitly. Results are newest first, with 10 rows / 1 KiB by default. Use `limit` (max 100), `max_bytes` (max 4 KiB), and `status` filters as needed. Cursors are bound to the local folder or global scope and cannot be replayed from a different folder. Id-based `subagent_result` and `subagent_output` keep their current-session scope; use `all:true` to read another session's run evidence. Unknown ownership remains an explicit gap for those evidence tools. Saved conversation discovery and continuation do not require the original foreground session to exist.
805
+
806
+ ## Abandoned launch records
807
+
808
+ A launch creates and claims its run directory, writes `prompt.md`, and prepares
809
+ the sandbox `control/` dir before the child starts and `meta.json` is committed. When that
810
+ preparation fails — or Pi dies inside that window — only those artifacts remain:
811
+ no metadata (nothing was committed) and no `output.log` (the log is created at
812
+ spawn and removed when the spawn itself fails). A launch failure now removes
813
+ them, so this state cannot be created anew.
814
+
815
+ A directory in that state that is left by an older version or a crashed process
816
+ is an **abandoned launch record**, not a run. It has no owner, status, log or
817
+ result, and can never gain any, so `subagent_list` reports it separately as not
818
+ run evidence and does not count it:
819
+
820
+ ```text
821
+ 1 abandoned launch record(s), not run evidence and not counted: the launch
822
+ stopped before any child started (prompt written, no metadata, no log): sa_…
823
+ Cleanup reclaims them after 1 hour; remove one now with subagent_stop <id>.
824
+ ```
825
+
826
+ Every launch's hygiene pass (`runDailyCleanupOnce`, alongside the daily and size
827
+ sweeps) reclaims abandoned launch records older than one hour, or immediately
828
+ with `subagent_stop <id>`. Only the attempt's own run directory, its per-run
829
+ session directory, and a clone workspace it owned are removed.
830
+
831
+ Cleanup never deletes a live attempt. A launch claims its run directory
832
+ (`.launch-attempt.json`: pid + process start identity) before it prepares
833
+ anything, and removes the claim when `meta.json` becomes the record. A record
834
+ whose claim is owned by a live process is not debris at any age, and the purge
835
+ re-classifies under the same per-run metadata lock a launch publishes under, so a
836
+ launch that commits metadata while a purge waits is preserved. In that case
837
+ `subagent_stop` reports `Preserved …` and removes nothing:
838
+
839
+ ```text
840
+ Preserved sa_…: a concurrent launch published this run (running), so nothing
841
+ was removed. Call subagent_stop again to stop the run.
842
+ ```
843
+
844
+ A directory that has a log is deliberately **not** treated as debris either: a
845
+ child may have started and its output is real evidence, so it stays an explicit
846
+ unreadable-record gap until normal retention reclaims it.
767
847
 
768
848
  ## Supervision health (`orphaned` / `lost`)
769
849
 
package/finalization.ts CHANGED
@@ -144,7 +144,7 @@ export function buildSubagentResultText(id: string): string | null {
144
144
  /** Optional paging/raw evidence for the registered result tool. */
145
145
  export function buildSubagentResultPayload(
146
146
  id: string,
147
- request?: { cursor?: string; maxBytes?: unknown; mode?: unknown; all?: unknown },
147
+ request?: { cursor?: string; maxBytes?: unknown; mode?: unknown; all?: unknown; lines?: unknown; include?: unknown; history?: unknown; tail?: unknown },
148
148
  healthLine = "",
149
149
  scopeKey = `parent:${process.pid}`,
150
150
  ): string | null {