oira666_pi-subagent 0.5.14 → 0.6.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.
Files changed (54) hide show
  1. package/README.md +31 -11
  2. package/docs/async-performance.md +79 -0
  3. package/docs/configuration.md +21 -8
  4. package/docs/sessions.md +28 -14
  5. package/docs/usage.md +22 -26
  6. package/extension/activity-widget.ts +95 -0
  7. package/extension/activity.ts +80 -0
  8. package/extension/async-jobs.ts +139 -0
  9. package/extension/broadcast-history.ts +194 -0
  10. package/extension/broadcast.ts +68 -105
  11. package/extension/completion.ts +55 -0
  12. package/extension/events.ts +13 -20
  13. package/extension/execution.ts +33 -2
  14. package/extension/expand-command.ts +118 -49
  15. package/extension/launch-result.ts +27 -0
  16. package/extension/launch-tool.ts +48 -47
  17. package/extension/lead-message-tool.ts +43 -0
  18. package/extension/message-command.ts +63 -0
  19. package/extension/message-tool.ts +246 -0
  20. package/extension/policy.ts +2 -2
  21. package/extension/progress-details.ts +31 -6
  22. package/extension/progress.ts +36 -3
  23. package/extension/prompt-hook.ts +8 -14
  24. package/extension/prompts.ts +1 -1
  25. package/extension/schemas.ts +14 -0
  26. package/extension/session-start.ts +10 -4
  27. package/extension/state.ts +12 -1
  28. package/extension/tool-registration.ts +28 -2
  29. package/extension/usage.ts +199 -52
  30. package/index.ts +4 -0
  31. package/package.json +1 -1
  32. package/render.ts +34 -13
  33. package/resume.ts +43 -8
  34. package/runner/attempt-state.ts +7 -0
  35. package/runner/attempt.ts +56 -36
  36. package/runner/lead-message.ts +37 -0
  37. package/runner/message-index.ts +5 -0
  38. package/runner/options.ts +8 -1
  39. package/runner/parallel.ts +107 -17
  40. package/runner/progress-coalescer.ts +3 -2
  41. package/runner/protocol.ts +145 -9
  42. package/types/contracts.ts +7 -2
  43. package/types/messages.ts +138 -12
  44. package/ui/detail-async.ts +108 -0
  45. package/ui/detail-lines.ts +113 -3
  46. package/ui/detail-model.ts +1 -0
  47. package/ui/detail-selectors.ts +13 -3
  48. package/ui/detail-transcript.ts +32 -30
  49. package/ui/expand-view.ts +29 -2
  50. package/ui/pager-view.ts +18 -29
  51. package/ui/pager.ts +11 -19
  52. package/ui/picker.ts +35 -5
  53. package/ui/tree-live.ts +4 -0
  54. package/extension/resume-tool.ts +0 -298
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # Pi subagent
2
2
 
3
- Delegate tasks to agents running in separate Pi processes. Each worker has its own context and saved session. The parent receives its final text and usage statistics, not its reasoning or tool transcript.
3
+ Delegate tasks to agents running in separate Pi processes. Each worker has its own context and saved session. The lead receives completion text and usage statistics, not the worker's reasoning or tool transcript.
4
+
5
+ Launches return immediately. Completion and worker messages arrive as steering that wakes an idle lead.
4
6
 
5
7
  Requires Pi 0.87.1 or newer, using the `@earendil-works` SDK packages.
6
8
 
@@ -60,7 +62,7 @@ PI_SUBAGENT_DISABLED=1 pi
60
62
 
61
63
  `true` (case-insensitive) also disables it; `PI-SUBAGENT-DISABLED` is an equivalent alias. Other values leave it enabled. The setting applies to the current process and is inherited by children. It is separate from child-extension exclusions, which do not disable anything in the parent. Restart Pi or reload extensions after changing the process environment.
62
64
 
63
- ## Launch and resume
65
+ ## Launch and message workers
64
66
 
65
67
  ```json
66
68
  {
@@ -71,17 +73,29 @@ PI_SUBAGENT_DISABLED=1 pi
71
73
  }
72
74
  ```
73
75
 
74
- Call `subagents` with one or more tasks. Tasks run in parallel, subject to the concurrency limit. Every task requires task text and a descendant allowance. The `agent` argument exists only when user-created agent definitions are available. The `intelligence` argument exists only when two or more enabled presets are configured. These choices are independent; with neither, task items contain only `task` and `max_subagents_allowed`. Use `0` for a worker that will not delegate, or `1` to let it launch one subagent. The caller reserves one slot for the worker plus its descendant allowance.
76
+ Call `subagents` with one or more tasks. It returns `started` immediately, without waiting for worker completion. Tasks run in the background, subject to the concurrency limit. Each completion arrives separately as lead steering, including when the lead is idle. The lead can continue other work after launching workers.
77
+
78
+ Every task requires task text and a descendant allowance. The `agent` argument exists only when user-created agent definitions are available. The `intelligence` argument exists only when two or more enabled presets are configured. These choices are independent; with neither, task items contain only `task` and `max_subagents_allowed`. Use `0` for a worker that will not delegate, or `1` to let it launch one subagent. The caller reserves one slot for the worker plus its descendant allowance.
75
79
 
76
- Workers with zero descendant allowance receive neither active delegation tools nor added delegation guidance. Raising `max_subagents_allowed` on resume restores the tools, subject to the depth limit. This uses Pi's documented `getActiveTools()` and `setActiveTools()` APIs during `session_start`. Workers that spent a positive allowance keep their tools so they can resume existing children.
80
+ Workers with zero descendant allowance receive no delegation tools or added delegation guidance. They still have `message_lead_agent` to contact the lead. Raising `max_subagents_allowed` through `message_subagent` restores delegation tools, subject to the depth limit. Workers that spent a positive allowance keep their tools so they can message existing children.
77
81
 
78
- Workers receive durable human names. Call `resume_subagents` to continue one with its previous context:
82
+ Workers receive durable human names. Call `message_subagent(name, message, max_subagents_allowed?)` to contact one:
79
83
 
80
84
  ```json
81
- { "resumes": [{ "subagent": "John", "task": "Now update the tests." }] }
85
+ { "name": "John", "message": "Now update the tests." }
82
86
  ```
83
87
 
84
- `agent` selects a definition; `subagent` identifies an existing worker. Resumes do not consume new slots. See [sessions and budgets](docs/sessions.md) for budget overrides, forks, and crash recovery.
88
+ A message steers a running worker or resumes an idle worker with its saved context. It does not wait for the worker to finish. `agent` selects a definition at launch; `name` identifies an existing worker. Messaging or resuming a named worker consumes no new worker slot. An optional budget increase can reserve additional descendant slots. See [sessions and budgets](docs/sessions.md) for cap overrides, forks, and crash recovery.
89
+
90
+ A child calls `message_lead_agent(message)` to send nonblocking steering to its lead:
91
+
92
+ ```json
93
+ { "message": "The API change needs a migration. Should I include it?" }
94
+ ```
95
+
96
+ Subagent notifications use Pi's theme-aware custom-message box, distinct from human user messages. Completion and idle reports use the same message styling.
97
+
98
+ The child continues without waiting for a reply. The steering wakes an idle lead; the lead can reply with `message_subagent`. Worker completion uses the same lead-steering delivery path, so no polling or blocking wait tool is needed.
85
99
 
86
100
  Delegate only when parallel work or context isolation saves enough effort to cover worker startup and coordination. Pass existing findings with the task so workers do not repeat your research.
87
101
 
@@ -112,9 +126,11 @@ See [configuration](docs/configuration.md) for frontmatter, layer restrictions,
112
126
 
113
127
  Collapsed results show each child's name, task, status, and most recent activity anywhere in its subtree. `Ctrl+O` expands the newest call from memory without reading historical transcripts.
114
128
 
115
- `/subagent-expand <name>` opens a saved worker transcript. With no name, it opens a searchable picker. Name completion is fuzzy. Each task or resume shows its actual provider/model and thinking level from the worker's session, not the parent's settings. Selected presets also appear as an intelligence label, kept separately for each run. Missing historical model/thinking metadata appears as `unknown`.
129
+ A live single line above the editor shows `Running N: Name elapsed · Name elapsed`, with `+N` for names that do not fit and a separate idle count. It uses live handles and snapshots, not session metadata or disk reads on timer ticks.
130
+
131
+ `/subagent-expand <name>` opens a saved worker transcript. With no name, it opens a searchable picker. Running workers come first in depth order, with top-level workers before nested workers. Live idle parents waiting for children come next; completed or stopped history comes last. Name completion is fuzzy. Each task or resumed turn shows its actual provider/model and thinking level from the worker's session, not the parent's settings. Selected presets also appear as an intelligence label, kept separately for each run. Missing historical model/thinking metadata appears as `unknown`.
116
132
 
117
- [Model presets](docs/configuration.md#caller-selected-intelligence) show labels such as `Nicolas (Junior/code-writer)` in regular tool results. One enabled preset applies automatically to new launches without exposing an `intelligence` argument. Two or more require an explicit `intelligence` choice on every launch item. Omitted or `null` choices reject the whole launch batch before any worker starts. Zero or disabled presets keep the existing launch defaults and show no intelligence label. Without an agent type, labels show `Nicolas (Junior)`; without either qualifier, they show just `Nicolas`. Named resumes do not accept `intelligence`; they retain the original effective model, thinking, and label, even after configuration or parent settings change.
133
+ [Model presets](docs/configuration.md#caller-selected-intelligence) show labels such as `Nicolas (Junior/code-writer)` in regular tool results. One enabled preset applies automatically to new launches without exposing an `intelligence` argument. Two or more require an explicit `intelligence` choice on every launch item. Omitted or `null` choices reject the whole launch batch before any worker starts. Zero or disabled presets keep the existing launch defaults and show no intelligence label. Without an agent type, labels show `Nicolas (Junior)`; without either qualifier, they show just `Nicolas`. `message_subagent` does not accept `intelligence`; workers retain the original effective model, thinking, and label, even after configuration or parent settings change.
118
134
 
119
135
  | Key | Action |
120
136
  | --- | --- |
@@ -126,7 +142,9 @@ Collapsed results show each child's name, task, status, and most recent activity
126
142
  | /, n, N | Search, next match, previous match |
127
143
  | q | Close from any transcript view |
128
144
 
129
- While workers run, steering input can be broadcast to selected names, including nested paths such as `John > Maria`. Only inputs marked as streaming `steer` open the routing prompt. Idle prompts and queued follow-ups remain with the parent.
145
+ `/message_subagent` is the human command for steering live workers. Choose `All (+nested)` for the whole live tree, `All` for top-level workers, `Youngest` for live workers with no running descendants, or `Names (e.g. John, Maria)` for comma-separated names or paths such as `John > Maria`. Then enter the message. There is no `No` choice; Esc cancels. The command does not resume completed workers. Automatic broadcast interception has been removed, so ordinary user input stays with the lead and never opens a routing prompt.
146
+
147
+ A worker that has settled its own turn but still has descendants reports `Idle, waiting for children.` to the lead via steering, followed by its own last answer. Its process stays alive for child messages and completions. `Finished` means the whole subtree has settled, not just the worker's own turn.
130
148
 
131
149
  The `WITH SUBS` footer includes recursive worker usage. Resuming or privately forking a named worker adds usage without increasing the unique-worker count. See [usage accounting](docs/usage.md) for programmatic results.
132
150
 
@@ -149,7 +167,9 @@ Source organization:
149
167
  | `types/` | Runtime contracts, transcript parsing, outcomes, usage aggregation |
150
168
  | `ui/` | Transcript views, trees, navigation and overlays |
151
169
 
152
- Root entry points preserve existing imports. `config.ts` and `agents.ts` discover configuration and definitions. Runtime and test files stay below 350 lines; the name list is static data.
170
+ Root entry points preserve existing imports. The main `index.ts` entry keeps its default extension registration export and the named exports `selectParentModelForSubagent`, `getSubagentsToolDescription`, `collectCombinedUsageStatusLine`, and `collectLiveUsageSummary`. `config.ts` and `agents.ts` discover configuration and definitions. Runtime and test files stay below 350 lines; the name list is static data.
171
+
172
+ See [async performance and memory](docs/async-performance.md) for cache behavior, test evidence, and remaining limits.
153
173
 
154
174
  ## Attribution and license
155
175
 
@@ -0,0 +1,79 @@
1
+ # Async performance and memory review
2
+
3
+ This review covers the implemented async execution, progress transport, accounting, routing caches, live UI, and lifecycle cleanup. The tests measure bookkeeping work and retained data, not production throughput or process scaling.
4
+
5
+ ## Changes
6
+
7
+ - Async reconciliation merges all completions into a launch before rebuilding its summary. Recovery lookup indexes successful completions by session, task, and execution start instead of copying and reversing the completion list for every unfinished worker. Batch accounting unions identity sets once instead of repeatedly copying a growing list.
8
+ - Footer accounting scans only newly appended session entries after checking the previous tail by reference. Parent-only appends reuse delegated totals. New durable completions still reconcile against earlier launches. Reloaded or shortened histories rebuild the cache. Switching files on the same session manager also invalidates it, even when the leaf ID matches. Totals still include off-branch entries, compactions, tool usage, and resumed executions.
9
+ - Live accounting indexes delegation messages separately from ordinary transcript messages. Final-output lookup examines only newly appended finalized messages. Both caches use weak history keys. Finalized messages must remain immutable; replacing the history array is supported, but mutating earlier messages in place is not a supported cache invalidation mechanism.
10
+ - Async batches release each completed worker's transcript before waiting for slower siblings. They retain full final output, failure explanations, own usage, subtree usage, and recovery references. Canonical summaries and non-enumerable compatibility usage totals retain descendant charges. The completion callback receives the original result before release. Synchronous runner callers keep their existing transcript behavior unless they opt into `compactCompletedResults`.
11
+ - Async per-worker updates no longer build a usage tree just to replace one batch slot. Calls without a progress observer construct no per-event details. The existing batch throttle still controls tree snapshots; all independent jobs now also share a 100 ms footer refresh throttle. Accounting updates happen immediately, not on that timer.
12
+ - Nested progress retains async job/task identities and custom completion details. This fixes partial-sibling accounting at ancestors. Finalized message projections use weak keys. Progress skips serialization while stdout needs draining, rather than accumulating transient snapshots behind a blocked protocol pipe. A later heartbeat retries; durable messages and completion delivery do not use this drop policy.
13
+ - Protocol activity detection retains one fixed-size digest per nested call, not a serialized tree. Unchanged snapshots from interleaved siblings no longer reset the semantic watchdog. Resolved attempts ignore late protocol records. Progress callbacks also reject old lifecycle generations before touching accounting or UI callbacks.
14
+ - Completion reservations maintain their current-generation count without scanning the pending map for every reserve/release. An old same-key background job cannot delete its replacement's accounting. Completed jobs leave the registry after cleanup.
15
+ - Async owners enable `cancelOnError`. Infrastructure failures cancel and drain sibling subprocesses before background tracking disappears. A throwing handle callback now terminates its child. Attempt settlement destroys its streams and removes its abort listener; existing timeout and steering cleanup remains in place. Disposed progress coalescers release their callback reference.
16
+ - Repeated completion text no longer causes the message index to discard a different execution's durable accounting. Completion publication retains stderr-only failure explanations without retaining the original transcript in its delivery callback.
17
+
18
+ ### Routing and UI caches
19
+
20
+ - Automatic broadcast interception of ordinary user input has been removed. The human `/message_subagent` command chooses live targets first, then asks for a message. Its choices are `All (+nested)`, `All`, `Youngest`, and `Names (e.g. John, Maria)`. There is no `No` choice; Esc cancels.
21
+ - Routing snapshots are cached per live root. A progress update visits only the roots it reports, using an incremental nested-message index. Flattening, fallback discovery, and sorting happen lazily when target arrays are read, not on every independent job's progress update. Unchanged reads reuse the flattened arrays. Reads validate handle identity and lifecycle generation, so same-count replacements and completed roots do not retain old descendants.
22
+ - The above-editor widget renders one line of running names and elapsed times, with `+N` overflow and an idle count. It reads only live handles and snapshots, never session metadata or disk on its ticks. Activity changes coalesce at 250 ms; a one-second elapsed-time interval runs only while live entries exist. Session restart and shutdown dispose the widget, callback, queued refresh, and interval.
23
+ - `/subagent-expand` lists running workers by depth, top levels before nested workers, then live idle parents waiting for children, then completed or stopped history. Registry reads reuse parsed data while the file path, lifecycle generation, mtime, and size match. Autocomplete does not load transcripts.
24
+ - Parsed transcript details use a separate eight-entry LRU per open overlay. Record metadata, selected session directory, file lists, mtimes, and sizes invalidate entries, including when a private fork appears. Closing the overlay clears its details and refresh timer; stale lifecycle generations close it rather than showing the previous session.
25
+ - At `agent_settled`, a worker with active descendants reports `Idle, waiting for children.` and its own last answer to its lead via steering. The process remains alive with its idle watchdog paused. Final `Finished` status waits for the whole subtree and any continuation to settle.
26
+
27
+ The durable schema remains version 3. No new cache or progress history is serialized into sessions. Completion output remains complete, rather than silently truncated to meet a metadata size limit.
28
+
29
+ ## Evidence
30
+
31
+ The regression tests use operation counts and observable retained data rather than elapsed-time thresholds:
32
+
33
+ | Case | Assertion |
34
+ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------ |
35
+ | 1,000 completions for one launch | 1,000 worker usage reads during reconciliation, not a batch rebuild after each completion |
36
+ | 1,000 parent entry appends | Each assistant usage is read only for its own append; replacing the cached tail forces a rebuild |
37
+ | Parent-only conversation after delegation | Previously recorded delegated details are not revisited |
38
+ | 1,000 live transcript appends | Only the new message is inspected by the delegation index and output lookup |
39
+ | 1,000 independent progress producers | One immediate footer refresh, one trailing refresh, one scheduled timer |
40
+ | 1,000 delivery reservations and releases | One initial pending-map scan |
41
+ | 1,000 progress attempts against a blocked pipe | No snapshot projection or write |
42
+ | Fast worker with a running sibling | Finished transcript is empty while output and subtree accounting remain available |
43
+ | Infrastructure callback failure | Both subprocess lifecycles settle before the async batch rejects |
44
+ | Nested async completion forwarding | Accounting matches before and after JSON projection, including unfinished siblings |
45
+ | 1,000 independent routing updates | One handle lookup per reported root; no global active-map traversal or sorting during updates |
46
+ | Repeated routing reads | Unchanged reads reuse sorted arrays; replacements and completion prune stale targets |
47
+ | Registry and detail navigation | Unchanged files reuse parses; changed files invalidate; overlay detail LRU retains eight entries |
48
+ | Live widget and overlay disposal | Refreshes coalesce; timers and callbacks stop on disposal or session lifecycle changes |
49
+
50
+ Run the focused tests from the repository root:
51
+
52
+ ```sh
53
+ mkdir -p tmp
54
+ TMPDIR="$PWD/tmp" node --import tsx/esm --test \
55
+ test/async-scaling*.test.ts test/broadcast-cache.test.ts \
56
+ test/expand-cache.test.ts test/expand-command-cache.test.ts \
57
+ test/activity-widget.test.ts test/expand-activity-order.test.ts
58
+ ```
59
+
60
+ When running the full suite from inside a subagent, remove inherited delegation identity and budget variables in that shell first. Otherwise root-session fixtures can pick up the caller's registry, depth, and allowance. For Bash:
61
+
62
+ ```sh
63
+ unset "${!PI_SUBAGENT_@}"
64
+ TMPDIR="$PWD/tmp" npm test
65
+ ```
66
+
67
+ The 1,000-item cases exercise bookkeeping only. Small real subprocess fixtures test lifecycle behavior. Neither establishes throughput for 1,000 simultaneous Pi processes or production scaling.
68
+
69
+ ## Remaining limits
70
+
71
+ - Every running agent is a separate Pi/Node process. Concurrency defaults to eight **per call**, not across all independent async jobs. Raising per-call limits or issuing many calls can still exhaust RAM, file descriptors, provider limits, or CPU. There is no new global process scheduler in this change.
72
+ - Pi's `SessionManager.getEntries()` filters the entire session into a defensive array. Leaf changes still incur that shallow copy. New durable delegation messages also trigger reconciliation of earlier relevant launch/completion messages. A long sequence of individually consumed completions can therefore still have quadratic cumulative reconciliation work. This review does not claim linear end-to-end session processing.
73
+ - `types/usage.ts` and `types/details.ts` still rebuild legacy usage trees and identity arrays in general-purpose durable builders. Their final-batch work is separate from the corrected per-completion reconciliation path. Legacy nested transcripts can require recursive traversal. New schema-v3 results do not embed those transcripts.
74
+ - Routing progress updates no longer flatten and sort all jobs. They still traverse changed roots' relevant nested results. A target-array read validates active roots, and an invalidated read flattens and sorts the current targets. This shifts global work to consumers; it does not eliminate it.
75
+ - Opening a selected worker still loads and parses its full transcript files on a detail-cache miss or invalidation. The eight-entry overlay LRU limits retained detail count, not bytes per transcript. Overlay refreshes still stat the registry, and detail validation stats session files. Existing render ordering caches are bounded at 500 entries and cleared on session lifecycle changes.
76
+ - Running transcripts, message-index entries, final answers, and exact execution/agent identity sets grow with the work they represent. The caches use weak ownership, not arbitrary LRU eviction that could lose duplicate detection or accounting. Finished async transcripts are released, but active histories, active output, final answers, and required accounting identities remain unbounded.
77
+ - An incomplete stdout JSONL record can still grow inside `JsonlFramer` until it terminates or the attempt stops. Valid records and final outputs also have no byte limit. Adding a limit needs an explicit oversize-record policy; silently clipping them would lose output or usage data. Stderr and live logs already have bounds.
78
+ - A successful completion send retains its delivery token until the matching custom message starts, or the session lifecycle clears it. A queued message that is never consumed can keep a child waiting and retain a small token. No TTL was added: guessing that delivery happened would let the parent reap a child before its continuation runs. One delivery timer per completion is still scheduled; the new shared throttle only covers progress footer refreshes.
79
+ - The SDK runner retains its earlier failure behavior unless `cancelOnError` is enabled. The extension's async execution path enables it. Custom background implementations that ignore abort signals or never finish cleanup can still prevent shutdown from completing.
@@ -1,5 +1,7 @@
1
1
  # Configuration
2
2
 
3
+ Launch and messaging tools acknowledge work without waiting for completion. The settings below control delegation, saved sessions, and worker processes.
4
+
3
5
  ## Agent frontmatter
4
6
 
5
7
  | Field | Default | Meaning |
@@ -96,22 +98,31 @@ Only user-configurable extension variables have JSON counterparts. Inherited run
96
98
 
97
99
  ## Tool descriptions
98
100
 
99
- In either settings filename, use `tool-prompts` to replace either tool's full model-facing description:
101
+ `tool-prompts` in either settings filename replaces a tool's full model-facing description:
100
102
 
101
103
  ```json
102
104
  {
103
105
  "tool-prompts": {
104
- "subagents": "Your full delegation instructions.",
105
- "resume_subagents": "Your full resume instructions."
106
+ "subagents": "Your full asynchronous delegation instructions.",
107
+ "message_subagent": "Your full named-worker messaging instructions.",
108
+ "message_lead_agent": "Your full child-to-lead messaging instructions."
106
109
  }
107
110
  }
108
111
  ```
109
112
 
110
113
  Missing descriptions retain their defaults. Overrides change written guidance, not schemas, budget checks, or runtime limits. Keep instructions to estimate worker counts and avoid unnecessary delegation.
111
114
 
115
+ Describe launch results as immediate `started` acknowledgements, not final output. Completion arrives as lead steering. `message_subagent` steers running workers or resumes idle ones; the child-only `message_lead_agent` sends nonblocking lead steering. Both completion and child messages wake an idle lead.
116
+
117
+ ## Human messaging and live activity
118
+
119
+ `/message_subagent` selects live targets before asking for message text. Choose `All (+nested)` for all live workers, `All` for top-level workers, `Youngest` for live workers without running descendants, or `Names (e.g. John, Maria)` for comma-separated names or nested paths. There is no `No` choice; Esc cancels. Automatic broadcast interception of ordinary user input has been removed. This human command is separate from the `message_subagent` model tool, which can also resume a saved worker.
120
+
121
+ The TUI shows one live line above the editor, such as `Running 2: John 12s · Maria 8s`, with an overflow count and a separate idle count when needed. Timer ticks use live handles and snapshots, not session metadata or disk reads. `/subagent-expand` lists running workers by depth, top levels before nested workers, then live idle parents waiting for children, then completed or stopped history.
122
+
112
123
  ## Caller-selected intelligence
113
124
 
114
- Define named model presets in `pi-subagent.json` or `pi-subagents.json`. With two or more enabled presets, the calling model must choose a configured `intelligence` preset for every launch item. With exactly one enabled preset, the launch tool hides the argument and automatically uses that preset. With no presets, the argument is absent and existing model/thinking defaults apply to launches. Named resumes never offer or accept an intelligence choice. No router or separate model-selection request is used.
125
+ Define named model presets in `pi-subagent.json` or `pi-subagents.json`. With two or more enabled presets, the calling model must choose a configured `intelligence` preset for every launch item. With exactly one enabled preset, the launch tool hides the argument and automatically uses that preset. With no presets, the argument is absent and existing model/thinking defaults apply to launches. `message_subagent` never offers or accepts an intelligence choice. No router or separate model-selection request is used.
115
126
 
116
127
  ```json
117
128
  {
@@ -153,11 +164,11 @@ Use models available in your Pi installation. Names are arbitrary, unique, non-e
153
164
 
154
165
  A selected or automatic preset overrides the parent model and agent model/thinking settings for a launch. The parent's explicit `--provider` and `--api-key` are not forwarded when a preset is selected. Named resumes use their saved provider and retain a CLI `--api-key` only when that provider matches the parent's explicit `--provider`; otherwise they drop the key. Worker providers use their configured Pi credentials. With multiple presets, omitted or `null` choices reject the entire launch batch before any worker starts or budget changes.
155
166
 
156
- `resume_subagents` retains the original effective model, thinking level, and intelligence label. This also applies to private forks and after restart, preset changes, disabling intelligence, changing the parent model, or editing/deleting the agent definition. A worker launched without a preset remains unlabelled. Pass only `{ subagent, task }` and an optional `max_subagents_allowed`; any `intelligence` argument, including `null`, rejects the resume batch.
167
+ `message_subagent` retains the worker's original effective model, thinking level, and intelligence label, whether it steers a running worker or resumes an idle one. This also applies to private forks and after restart, preset changes, disabling intelligence, changing the parent model, or editing/deleting the agent definition. A worker launched without a preset remains unlabelled. Pass only `{ name, message }` and an optional `max_subagents_allowed`; any `intelligence` argument, including `null`, is invalid.
157
168
 
158
- Tool result rows show the selected preset, for example `Nicolas (Junior/code-writer)`. Display names capitalize only the first character; configured spelling and argument values otherwise stay unchanged. Runs without a preset show `Nicolas (code-writer)`. Runs without an agent type show `Nicolas (Junior)`, or just `Nicolas` when neither qualifier exists. Agent types come only from user-created definitions. With no available types, the launch schema omits `agent` and uses a default worker without agent-specific instructions. Durable results retain their own preset name, and the name registry retains the initial choice. The `/subagent-expand` picker shows the initial preset beside each agent type and lets you search by preset name. Its transcript view shows each task's or resume's recorded intelligence alongside its actual transcript model and thinking level. Later resumes do not relabel earlier work. Missing model or thinking metadata remains `unknown`, even when a preset name is known.
169
+ Tool result rows show the selected preset, for example `Nicolas (Junior/code-writer)`. Display names capitalize only the first character; configured spelling and argument values otherwise stay unchanged. Runs without a preset show `Nicolas (code-writer)`. Runs without an agent type show `Nicolas (Junior)`, or just `Nicolas` when neither qualifier exists. Agent types come only from user-created definitions. With no available types, the launch schema omits `agent` and uses a default worker without agent-specific instructions. Durable results retain their own preset name, and the name registry retains the initial choice. The `/subagent-expand` picker shows the initial preset beside each agent type and lets you search by preset name. Its transcript view shows each task's or resumed turn's recorded intelligence alongside its actual transcript model and thinking level. Later messages do not relabel earlier work. Missing model or thinking metadata remains `unknown`, even when a preset name is known.
159
170
 
160
- `PI_SUBAGENT_INTELLIGENCE=true` enables presets when they exist, which is the default. Set it to `false` or `0` to treat the configuration as having no presets for new launches: the launch tool hides the argument and no automatic preset applies. Named resumes still retain their original settings. Unknown choices or attempts to pass a named hidden argument fail before launching workers. When the argument is hidden, omission or `null` still uses the automatic sole preset or existing defaults.
171
+ `PI_SUBAGENT_INTELLIGENCE=true` enables presets when they exist, which is the default. Set it to `false` or `0` to treat the configuration as having no presets for new launches: the launch tool hides the argument and no automatic preset applies. Named workers still retain their original settings when messaged or resumed. Unknown choices or attempts to pass a named hidden argument fail before launching workers. When the argument is hidden, omission or `null` still uses the automatic sole preset or existing defaults.
161
172
 
162
173
  Configuration follows the trust checks and file order above. A later `subagents-models` block replaces the entire earlier block. An empty list disables selection. Invalid blocks warn and disable selection rather than using a partial list. Nested workers load configuration using the same rules. Reload Pi after changing settings.
163
174
 
@@ -194,7 +205,9 @@ Cycle-blocked tasks fail individually; legal siblings still run. A nested tool e
194
205
 
195
206
  The idle watchdog pauses during tool execution. When the last concurrent tool finishes, a fresh idle window starts. Agent events and changed nested-worker state reset it; unchanged heartbeats do not. Timeout and cancellation terminate the process tree and bound cleanup even if the OS never reports closure.
196
207
 
197
- RPC completion waits for `agent_settled`, not `agent_end`, because Pi may retry, compact, or continue after a low-level run ends. Rejected prompts, signal exits, and exit before settlement are failures.
208
+ Worker-turn completion waits for `agent_settled`, not `agent_end`, because Pi may retry, compact, or continue after a low-level run ends. This wait happens in the background, not inside the lead's launch or messaging tool call.
209
+
210
+ If descendants are still active at `agent_settled`, the runner reports `Idle, waiting for children.` with the worker's own last answer to the lead via steering. The child process stays alive and its idle watchdog pauses while it waits. Child messages and completions can wake it. Final `Finished` status and completion steering wait until the whole subtree and resulting continuations have settled. Rejected prompts, signal exits, and exit before settlement are failures. A finished durable worker remains available for later resume through `message_subagent`.
198
211
 
199
212
  Children inherit provider, authentication, proxy, home, temporary-directory, and Pi environment settings. On Windows, the runner normalizes `Path`/`PATH` and adds Node, `PNPM_HOME`, npm's user bin, `%LOCALAPPDATA%\\pnpm`, and `%SystemRoot%\\System32` to executable search paths.
200
213
 
package/docs/sessions.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # Sessions and budgets
2
2
 
3
+ Workers run asynchronously. Budget reservations and lifetime descendant-cap semantics apply across launches, messages, and recovery.
4
+
5
+ ## Async worker lifecycle
6
+
7
+ `subagents` returns `started` immediately and runs workers in the background. Each worker's completion arrives as steering to its lead and wakes the lead if idle. The launch acknowledgement is not a final result.
8
+
9
+ Workers keep durable names and saved sessions after completing a turn. `message_subagent(name, message, max_subagents_allowed?)` steers a running worker or resumes an idle worker with its saved context. It returns without waiting for completion. A running worker receives steering rather than a second concurrent turn on the same session.
10
+
11
+ A child can call `message_lead_agent(message)` without blocking. The message becomes lead steering and wakes an idle lead. It does not finish the child's turn or wait for a reply. The lead replies through `message_subagent`.
12
+
13
+ `agent_settled` ends a worker's own turn, but does not finish its subtree while descendants remain active. The runner sends `Idle, waiting for children.` and the worker's own last answer to the lead via steering. It keeps the child process alive, pauses its idle watchdog, and lets descendant messages or completions wake it. `Finished` is reported only after the subtree and any resulting continuation have settled. This live idle state differs from a finished worker whose saved session can later be resumed.
14
+
15
+ Humans can use `/message_subagent` to select live targets, then enter a message. The choices are `All (+nested)`, `All`, `Youngest`, and `Names (e.g. John, Maria)`. There is no `No` choice; Esc cancels. This command steers live workers only. Automatic interception of ordinary user input for broadcast routing has been removed.
16
+
3
17
  ## Agent allowances
4
18
 
5
19
  A new main session has 50 agent slots by default. Set `limits.total` in either settings filename or `PI_SUBAGENT_MAX_TOTAL_AGENTS` before starting a new session to change this. The environment takes precedence. `0` blocks new launches but permits named resumes. Invalid values block launches.
@@ -9,8 +23,8 @@ A new main session has 50 agent slots by default. Set `limits.total` in either s
9
23
  - Batch reservations are atomic across processes. If a batch exceeds the caller's remaining allowance, no task starts and no name is allocated.
10
24
  - Siblings cannot borrow each other's slots. Unused, failed, or canceled reservations stay assigned to their branch for later resumes.
11
25
  - Interrupted calls reuse their original reservations during recovery.
12
- - Named resumes consume no new slots and retain the worker's current allowance.
13
- - Workers with a positive descendant cap receive their remaining allowance in the prompt. Workers with a zero cap receive neither delegation tools nor added delegation guidance. A higher cap on resume restores the tools, subject to the depth limit.
26
+ - Messaging or resuming a named worker consumes no new worker slot and retains its current allowance unless an override changes it.
27
+ - Workers with a positive descendant cap receive their remaining allowance in the prompt. Workers with a zero cap receive neither delegation tools nor added delegation guidance, but retain `message_lead_agent`. A higher cap supplied to `message_subagent` restores delegation tools, subject to the depth limit.
14
28
 
15
29
  The main agent sees its remaining count only below 30, to avoid presenting larger caps as spending targets. Delegating workers see their branch allowance. Enforcement is the same regardless of prompt visibility.
16
30
 
@@ -24,51 +38,51 @@ The ledger uses immutable files and atomic hard links beside saved worker sessio
24
38
 
25
39
  ```json
26
40
  {
27
- "resumes": [
28
- { "subagent": "John", "task": "Continue the implementation", "max_subagents_allowed": 10 }
29
- ]
41
+ "name": "John",
42
+ "message": "Continue the implementation",
43
+ "max_subagents_allowed": 10
30
44
  }
31
45
  ```
32
46
 
33
- The override replaces the worker's lifetime descendant cap, excluding itself. It does not grant ten fresh launches. Omit it to retain the existing cap. Provider-generated `null` for this optional field also keeps the cap; explicit `0` still replaces it with zero.
47
+ Pass this to `message_subagent` for either a running or idle worker. The override replaces the worker's lifetime descendant cap, excluding itself. It does not grant ten fresh launches. Omit it to retain the existing cap. Provider-generated `null` for this optional field also keeps the cap; explicit `0` still replaces it with zero.
34
48
 
35
49
  - Increases reserve only additional capacity from the original launcher's allowance.
36
50
  - Decreases cannot remove slots already spent or assigned. They do not refund the parent. Raising a cap to a previously funded value needs no new reservation.
37
51
  - A caller can adjust workers in its own tree. For nested workers, increase the immediate launcher's cap first if needed.
38
- - Overrides in one call must share an original launcher. Split different launchers into separate calls.
52
+ - Each call targets one named worker. Its original launcher funds any increase, not the messaging caller's unrelated branch.
39
53
  - Older workers without reservation records can resume without an override.
40
54
  - Interrupted increases remain funded; retries do not charge twice.
41
55
 
42
56
  ## Names, ownership and forks
43
57
 
44
- Each worker receives a unique name from a bundled list of 1,000 names. Names are not reused within a delegation tree. All entries in `resume_subagents.resumes` run in parallel. The single-entry shorthand `{"subagent":"John","task":"Continue"}` remains accepted.
58
+ Each worker receives a unique name from a bundled list of 1,000 names. Names are not reused within a delegation tree. `message_subagent` targets one durable name per call; it has no batch-resume payload.
45
59
 
46
60
  The shared name registry and ownership identity are recorded in session metadata. An ancestor-session lookup recovers identities from older sessions. This keeps names valid even when Pi assigns new session IDs after resume or branching.
47
61
 
48
- The agent that launched a worker owns its original session. A child may receive an ancestor's worker name in its task. Resuming that name creates a private session fork, leaving the owner's context untouched. Each caller reuses one fork per name, including across restarts. Forks retain the same budget.
62
+ The agent that launched a worker owns its original session. A child may receive an ancestor's worker name in its task. Messaging that name from another caller uses a private session fork, leaving the owner's context untouched. Each caller reuses one fork per name, including across restarts. Forks retain the same budget.
49
63
 
50
- Concurrent resumes of the same session are rejected using both in-process checks and crash-tolerant registry markers. Removed agent definitions do not prevent resume; the registry retains model/tool restrictions and the saved session retains context. Resumes open the saved transcript explicitly, preserving its original working directory even when the caller's directory differs. They do not use Pi's cwd-filtered `--continue` discovery. The runner selects that transcript once before extension discovery and uses its working directory for discovery and process startup. Caller approval applies only when that directory matches the caller's project; otherwise the saved project is explicitly unapproved, including when extension exclusions are disabled.
64
+ Only one turn runs on a worker session at a time. Messages to a running worker steer that turn; messages to an idle worker resume it. Session ownership checks and crash-tolerant registry markers prevent duplicate processes from opening the same transcript. Removed agent definitions do not prevent resume; the registry retains model/tool restrictions and the saved session retains context. Resumes open the saved transcript explicitly, preserving its original working directory even when the caller's directory differs. They do not use Pi's cwd-filtered `--continue` discovery. The runner selects that transcript once before extension discovery and uses its working directory for discovery and process startup. Caller approval applies only when that directory matches the caller's project; otherwise the saved project is explicitly unapproved, including when extension exclusions are disabled.
51
65
 
52
66
  Relative `--skill`, `--prompt-template`, and theme file/directory arguments keep the parent's startup directory as their base, even when a resumed worker runs in another project. Named theme selections and non-filesystem references are forwarded unchanged.
53
67
 
54
68
  ## Crash recovery
55
69
 
56
- Worker sessions live in `sessions-subagents`, beside Pi's normal `sessions` directory. On parent resume or session-tree navigation, the extension checks for an unfinished `subagents` call on the active branch.
70
+ Worker sessions live in `sessions-subagents`, beside Pi's normal `sessions` directory. Async recovery tracks outstanding workers durably on the active branch, even though their launch calls already returned `started`. On parent resume or session-tree navigation, recovery checks that work rather than waiting for an unfinished blocking tool call.
57
71
 
58
72
  - Interactive mode asks whether to resume. Non-UI modes resume automatically.
59
- - Finished siblings reuse their saved output and statistics. Unfinished siblings continue their own sessions.
73
+ - Finished siblings reuse their saved output and statistics without rerunning. Unfinished siblings continue their own sessions. Completion steering wakes an idle lead.
60
74
  - Durable references retain output, usage, model, and tool counts across JSON/session restarts.
61
75
  - Nested workers recover in the same way.
62
76
  - Provider fallback preserves the selected model's effective provider, authentication, endpoints, headers, and environment.
63
77
  - `/resume`, `/new`, `/fork`, and `/reload` discard pending recovery state and callbacks from the previous runtime.
64
78
 
65
- Interrupted `resume_subagents` calls are not replayed automatically. The model can issue them again using the same names.
79
+ Message acknowledgement is separate from worker completion. Recovery uses durable worker state rather than treating an acknowledged message as completed work. Retrying contact uses the same name without allocating a new worker or charging the same funded increase twice.
66
80
 
67
81
  | Variable | Default | Meaning |
68
82
  | --- | --- | --- |
69
83
  | `PI_SUBAGENT_RESUME_PROMPT` | `true` | `false` skips the interactive question and resumes automatically |
70
84
  | `PI_SUBAGENT_DISABLE_RESUME` | `false` | `true` disables automatic crash recovery |
71
- | `DISABLE_RESUMABLE_SUBAGENTS` | `false` | `true`, `on`, or `1` disables name allocation and the named-resume tool |
85
+ | `DISABLE_RESUMABLE_SUBAGENTS` | `false` | `true`, `on`, or `1` disables name allocation and named-worker messaging |
72
86
  | `PI_SUBAGENT_NAMES_FILE` | Internal | Shared registry path, propagated to children |
73
87
  | `PI_SUBAGENT_BUDGET_DIR` | Internal | Reserved branch ledger, propagated and saved in session metadata |
74
88
 
package/docs/usage.md CHANGED
@@ -1,12 +1,20 @@
1
1
  # Usage accounting
2
2
 
3
- ## Result data
3
+ ## Async acknowledgements and completion
4
+
5
+ `subagents` returns `started` immediately, before final output or usage is available. `message_subagent(name, message, max_subagents_allowed?)` also returns without waiting for the worker to finish. It steers a running worker or resumes an idle durable named worker. Neither acknowledgement is a completed worker result.
6
+
7
+ Completion arrives separately as lead steering and wakes an idle lead. A child's nonblocking `message_lead_agent(message)` also sends lead steering, but is not a completion event. Do not count a progress report, question, or launch acknowledgement as final usage.
8
+
9
+ Completion is a custom message with `customType: "subagent_completion"`, display text in `content`, and result data in `details`. It uses `deliverAs: "steer"` with `triggerTurn: true`. Launch receipts carry `asyncJobId`; individual completions carry that ID and `asyncTaskIndex` to identify the launch slot. Results also retain durable worker and execution identities. Include each execution once, even after recovery or repeated delivery. Final statistics do not belong to the launch acknowledgement.
4
10
 
5
- Delegation tool results include `details`. Recognize `subagents`, `resume_subagents`, and the legacy launch name `subagent` when reading old sessions.
11
+ A worker that settles while descendants remain active sends `Idle, waiting for children.` and its own last answer as ordinary lead steering. That is not a final completion or a final usage total. The process remains alive; `Finished` waits for subtree settlement.
6
12
 
7
- The canonical interfaces live in [`types/contracts.ts`](../types/contracts.ts). Avoid maintaining a separate copy of those interfaces.
13
+ ## Result data
14
+
15
+ Result and saved-session interfaces live in [`types/contracts.ts`](../types/contracts.ts). Async identity and reconciliation helpers live in [`types/messages.ts`](../types/messages.ts), re-exported through `types.ts`. Use these definitions rather than maintaining separate copies.
8
16
 
9
- Live results contain:
17
+ Live result details contain:
10
18
 
11
19
  | Field | Meaning |
12
20
  | --- | --- |
@@ -21,36 +29,24 @@ Live results contain:
21
29
 
22
30
  `contextTokens` is the last context-window snapshot, not cumulative usage. It is not summed across agents. Cost is in USD.
23
31
 
24
- Saved parent-session results use compact schema version 3. They omit full worker transcripts and recursive live breakdowns. Instead, `usageSummary` holds the recursive totals and `results` holds durable child references with outcome and recovery data. Do not assume that saved results contain live `messages`, `usageTree`, or aggregate tool counts.
32
+ Saved parent-session results use compact schema version 3. They omit full worker transcripts and recursive live breakdowns. Instead, `usageSummary` holds the recursive totals and `results` holds durable child references with outcome and recovery data. Do not assume that saved results contain live `messages`, `usageTree`, or aggregate tool counts. Async completion preserves durable usage accounting without requiring full worker transcripts in the lead's context.
25
33
 
26
34
  ## Reading RPC events
27
35
 
28
- Current Pi emits tool results as `message_end` events with `message.role === "toolResult"`. Older streams may use `tool_result_end`. Process each tool call only once if a transport delivers both shapes.
36
+ Pi emits tool results as `message_end` events with `message.role === "toolResult"`. Older streams may use `tool_result_end`. Process each tool call only once if a transport delivers both shapes.
29
37
 
30
- ```js
31
- const seen = new Set();
32
- let costUsd = 0;
38
+ A tool-result-only cost accumulator misses async completions. Launch and messaging tool results acknowledge work; completion steering carries the later outcome. Decode custom messages with `customType === SUBAGENT_COMPLETION_TYPE`, whose value is `subagent_completion`, and validate their `details` with `isSubagentDetails`. Ordinary child-to-lead messages, including idle notifications, are not completion usage.
33
39
 
34
- for await (const line of jsonLines) {
35
- const event = JSON.parse(line);
36
- const message = event.message;
37
- if (!["message_end", "tool_result_end"].includes(event.type)) continue;
38
- if (message?.role !== "toolResult") continue;
39
- if (!["subagents", "subagent", "resume_subagents"].includes(message.toolName)) continue;
40
- if (!message.details || seen.has(message.toolCallId)) continue;
41
- seen.add(message.toolCallId);
40
+ `getNestedSubagentResults(messages)` reconciles launch placeholders with individual completions. `asyncJobId(details)` reads the launch identity and `subagentExecutionId(result)` reads the execution identity. These helpers and `SUBAGENT_COMPLETION_TYPE` are exported from `types.ts`. Match a completion to its job and task slot rather than adding the launch placeholder and completion as separate runs.
42
41
 
43
- const details = message.details;
44
- costUsd += details.usageSummary?.costUsd ?? details.aggregatedUsage?.cost ?? 0;
45
- }
46
- ```
47
-
48
- This sums one parent stream. Do not also sum its children's streams, since parent delegation totals already include descendants. Parent-only model usage can be added separately.
42
+ Sum one lead stream's recursive worker totals. Do not also sum its children's streams, since recursive totals already include descendants. Lead-only model usage can be added separately. Repeated completions or overlapping summaries must not add the same worker run twice.
49
43
 
50
44
  ## Interactive footer
51
45
 
52
- The `WITH SUBS` line includes the parent's billed session entries and recursive worker usage. Parent accounting follows Pi's session-statistics rules using `ctx.sessionManager.getEntries()`, including off-branch retries, compacted history, branch summaries, and tool-reported usage. Durable worker summaries add delegated cost once.
46
+ The `WITH SUBS` line includes the parent's billed session entries and recursive worker usage. Parent accounting follows Pi's session-statistics rules using `ctx.sessionManager.getEntries()`, including off-branch retries, compacted history, branch summaries, and tool-reported usage. Durable worker summaries add delegated cost once. Async delivery retains this accounting across idle periods and recovery.
47
+
48
+ The worker count tracks unique identities, not invocations. Messaging, named resumes, and private forks add usage without increasing the count. Older compact history can recover identities from the name registry. This usage count is separate from budget reservations: launching reserves `1 + max_subagents_allowed` slots, while messaging an existing worker allocates no new worker slot. A cap increase can reserve additional descendant capacity from its original launcher.
53
49
 
54
- The worker count tracks unique identities, not invocations. Named resumes and private forks add usage without increasing the count. Older compact history can recover identities from the name registry.
50
+ Pi renders this extension's combined usage through its normal `ctx.ui.setStatus()` footer line. This is separate from the live `Running N` line above the editor, which shows names, elapsed times, overflow, and idle count using live handles and snapshots without session metadata or disk reads on ticks.
55
51
 
56
- Pi renders this extension's combined usage through its normal `ctx.ui.setStatus()` footer line.
52
+ The main `index.ts` entry retains its default registration export and named exports `selectParentModelForSubagent`, `getSubagentsToolDescription`, `collectCombinedUsageStatusLine`, and `collectLiveUsageSummary`. Existing root entry-point imports remain supported.
@@ -0,0 +1,95 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { getActivitySnapshot, type ActivityEntry } from "./activity.js";
3
+ import type { ExtensionState } from "./state.js";
4
+
5
+ export function elapsedLabel(startedAt: number, now: number): string {
6
+ const seconds = Math.max(0, Math.floor((now - startedAt) / 1000));
7
+ if (seconds < 60) return `${seconds}s`;
8
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
9
+ return `${Math.floor(seconds / 3600)}h${Math.floor((seconds % 3600) / 60)}m`;
10
+ }
11
+
12
+ /** One terminal line, with an explicit overflow count instead of wrapping the editor. */
13
+ export function formatActivityLine(entries: ActivityEntry[], width: number, now = Date.now()): string {
14
+ const running = entries.filter((entry) => entry.status === "running");
15
+ const idle = entries.length - running.length;
16
+ const prefix = `Running ${running.length}`;
17
+ const idleSuffix = idle ? ` · ${idle} idle` : "";
18
+ if (!running.length) return truncateToWidth(`${prefix}${idleSuffix}`, Math.max(0, width), "");
19
+ let line = `${prefix}:`;
20
+ for (let i = 0; i < running.length; i++) {
21
+ const entry = running[i];
22
+ const next = `${line}${i ? " ·" : ""} ${entry.name} ${elapsedLabel(entry.startedAt, now)}`;
23
+ const remaining = running.length - i - 1;
24
+ const suffix = `${remaining ? ` · +${remaining}` : ""}${idleSuffix}`;
25
+ if (visibleWidth(next + suffix) > width) {
26
+ return truncateToWidth(`${line} · +${running.length - i}${idleSuffix}`, Math.max(0, width), "");
27
+ }
28
+ line = next;
29
+ }
30
+ return truncateToWidth(line + idleSuffix, Math.max(0, width), "");
31
+ }
32
+
33
+ export function registerActivityWidget(state: ExtensionState): void {
34
+ let dispose = () => {};
35
+ state.pi.on("session_start", (_event, ctx) => {
36
+ dispose();
37
+ if (state.disabled || ctx.mode !== "tui" || !ctx.hasUI || !("setWidget" in ctx.ui)) return;
38
+ const generation = state.lifecycleGeneration;
39
+ let interval: ReturnType<typeof setInterval> | undefined;
40
+ let queued: ReturnType<typeof setTimeout> | undefined;
41
+ let requestRender = () => {};
42
+ let entries = getActivitySnapshot(state);
43
+ let lastRefresh = -Infinity;
44
+ const refresh = () => {
45
+ if (!state.sessionActive || generation !== state.lifecycleGeneration) return;
46
+ lastRefresh = Date.now();
47
+ entries = getActivitySnapshot(state, lastRefresh);
48
+ if (entries.length && !interval) {
49
+ interval = setInterval(refresh, 1000);
50
+ interval.unref?.();
51
+ }
52
+ if (!entries.length && interval) {
53
+ clearInterval(interval);
54
+ interval = undefined;
55
+ }
56
+ requestRender();
57
+ };
58
+ const onChanged = () => {
59
+ if (queued) return;
60
+ queued = setTimeout(
61
+ () => {
62
+ queued = undefined;
63
+ refresh();
64
+ },
65
+ Math.max(0, 250 - (Date.now() - lastRefresh)),
66
+ );
67
+ queued.unref?.();
68
+ };
69
+ state.onActivityChanged = onChanged;
70
+ ctx.ui.setWidget(
71
+ "subagent-running",
72
+ (tui, theme) => {
73
+ requestRender = () => tui.requestRender();
74
+ return {
75
+ render: (width) => [theme.fg("accent", formatActivityLine(entries, width))],
76
+ invalidate() {},
77
+ };
78
+ },
79
+ { placement: "aboveEditor" },
80
+ );
81
+ dispose = () => {
82
+ if (queued) clearTimeout(queued);
83
+ if (interval) clearInterval(interval);
84
+ queued = undefined;
85
+ interval = undefined;
86
+ if (state.onActivityChanged === onChanged) state.onActivityChanged = undefined;
87
+ ctx.ui.setWidget("subagent-running", undefined);
88
+ };
89
+ refresh();
90
+ });
91
+ state.pi.on("session_shutdown", () => {
92
+ dispose();
93
+ dispose = () => {};
94
+ });
95
+ }