pi-subagent-manager 0.28.0 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/docs/async-lifecycle.md +153 -0
- package/docs/development.md +1 -0
- package/docs/settings.md +32 -2
- package/docs/tools-and-ui.md +1 -1
- package/package.json +1 -1
- package/src/index.ts +166 -118
- package/src/orch/housekeeping.ts +338 -0
- package/src/orch/manager.ts +69 -0
- package/src/orch/runtime.ts +26 -3
- package/src/prefs/config.ts +22 -0
- package/src/prefs/settings.ts +20 -3
- package/src/types.ts +24 -1
- package/src/ui/model-picker.ts +216 -0
- package/src/ui/settings-ui.ts +53 -0
- package/src/ui/status-ui.ts +2 -2
- package/src/ui/thread-tree.ts +10 -0
- package/src/ui/ui.ts +49 -8
package/README.md
CHANGED
|
@@ -88,15 +88,18 @@ Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Fo
|
|
|
88
88
|
|
|
89
89
|
Enable **[labs] Enable subagent extensions** in `/agents settings` to reload configured user and trusted-project extension hooks in each subagent’s separate session. It is off by default and experimental: hooks that assume main-session state can cause bugs or unintended consequences. This is configured-file discovery, **not exact main-session inheritance**; CLI-only, inline, and built-in extensions are not reloaded. See [subagent extension settings](docs/settings.md#labs-enable-subagent-extensions-subagentextensions) and read the [limitations](docs/subagent-extension-limitations.md) before enabling.
|
|
90
90
|
|
|
91
|
-
Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to
|
|
91
|
+
Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to collect detached-agent results and continue unfinished work, or recap when the overall task is complete, keeping the final response in the main thread. It is off by default and suppressed by Subagent Mode Off. **Enabling it may cause extra model turns and uses more tokens and context.** See [Final Recap](docs/settings.md#labs-final-recap-finalrecap).
|
|
92
92
|
|
|
93
93
|
**[labs] Checklist integration** is always listed in `/agents settings` but can only be turned on while a loaded, active [pi-checklist](https://github.com/championswimmer/pi-checklist) ≥3.0.0 has task meta enabled (`/checklist settings meta`). When on and eligible, the main agent's prompt explains tagging tasks with `meta.agent`; in Orchestration mode the main agent must use the checklist. See [Checklist integration](docs/settings.md#labs-checklist-integration-checklistintegration).
|
|
94
94
|
|
|
95
|
+
Enable **[labs] Housekeeping model** in `/agents settings` and pick a model (from your scoped and other available models) to have it write a one-line summary of what each running agent is doing, shown in `/agents tree` instead of the raw tool-call line. It is off by default, never persisted, and falls back to the normal status whenever it is disabled, unavailable or fails. It sends each agent's task and recent activity to the model you pick and uses extra tokens not counted in cost totals. See [Housekeeping model](docs/settings.md#labs-housekeeping-model-housekeepingenabled-housekeepingmodel).
|
|
96
|
+
|
|
95
97
|
## Docs
|
|
96
98
|
|
|
97
99
|
- [Your own agent](docs/custom-agents.md) — walkthrough for writing an agent type
|
|
98
100
|
- [Settings](docs/settings.md) — every setting and option, and when to use each
|
|
99
101
|
- [Threads and lifecycle](docs/threads.md) — paths, context, pause/resume, persistence
|
|
102
|
+
- [Asynchronous lifecycle](docs/async-lifecycle.md) — flow and timing diagrams for completion, wakes, and continuation
|
|
100
103
|
- [Tools and UI](docs/tools-and-ui.md) — model-facing tools, parallel work, dialogs
|
|
101
104
|
- [Importing agents](docs/importing-agents.md) — migrate from other pi subagent packages
|
|
102
105
|
- [Bundled agents](docs/default-agents.md) — routing, tool boundaries, model suggestions
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# Asynchronous completion and main-agent wakes
|
|
2
|
+
|
|
3
|
+
A detached spawn (`wait: false`) returns while its agent is still working. Completion and reporting timeouts are separate signals: finishing cancels the agent's reporting timer, then reevaluates whether the main agent should run. It never waits for that timer to expire.
|
|
4
|
+
|
|
5
|
+
With [Final Recap](settings.md#labs-final-recap-finalrecap) enabled, completed, failed, and stopped detached agents contribute to a pending completion batch. The batch becomes ready when **no detached agent is starting or running**, including nested descendants. Without Final Recap, detached settlements request ordinary wakes instead of waiting for a batch. Progress alone does not request a turn; foreground results do not request an extra completion turn. A detached pause requests an ordinary wake, not a final-result recap.
|
|
6
|
+
|
|
7
|
+
The scheduler knows whether a batch is ready—not whether the user's task is finished. Both kinds of trigger tell the main agent to collect results and continue unfinished work, or give a final recap if the overall task is complete.
|
|
8
|
+
|
|
9
|
+
## Delivery and scheduling flow
|
|
10
|
+
|
|
11
|
+
Root-directed events are persisted before delivery. When main is idle, their notifications enter model context without triggering a turn or appearing as the final visible chat message. A single scheduler then chooses a completion/continuation trigger or an ordinary wake.
|
|
12
|
+
|
|
13
|
+
```mermaid
|
|
14
|
+
flowchart TD
|
|
15
|
+
Event["Progress, timeout, or settlement"] --> Recipient{"Recipient is /root?"}
|
|
16
|
+
Recipient -->|Yes| Mailbox["Persist root mailbox notification"]
|
|
17
|
+
Recipient -->|No| Parent["Deliver notification to lexical parent"]
|
|
18
|
+
Parent --> Nested{"Settlement?"}
|
|
19
|
+
Nested -->|Yes| Reconcile["Reevaluate root mailbox and scheduler"]
|
|
20
|
+
Nested -->|No| Stop["No root scheduling change"]
|
|
21
|
+
Mailbox --> Reconcile
|
|
22
|
+
Reconcile --> Enabled{"Enabled and not cancelling?"}
|
|
23
|
+
Enabled -->|No| Hold["Do not deliver or start a turn"]
|
|
24
|
+
Enabled -->|Yes| Drain["Deliver pending notifications if main is idle"]
|
|
25
|
+
Drain --> Reserved{"Timer queued or automatic turn reserved?"}
|
|
26
|
+
Reserved -->|Yes| Retain["Leave pending work for reevaluation"]
|
|
27
|
+
Reserved -->|No| Pending{"Ready completion batch or wake intent?"}
|
|
28
|
+
Pending -->|No| Retain
|
|
29
|
+
Pending -->|Yes| Timer["Defer: 0 ms if idle, 100 ms if busy"]
|
|
30
|
+
Timer --> Valid{"Same session and generation, still enabled?"}
|
|
31
|
+
Valid -->|No| Hold
|
|
32
|
+
Valid -->|Yes| Idle{"Main idle?"}
|
|
33
|
+
Idle -->|No| Reconcile
|
|
34
|
+
Idle -->|Yes| Flush["Drain mailbox and recheck live state"]
|
|
35
|
+
Flush --> Batch{"Final Recap on, no outstanding async agents, pending results?"}
|
|
36
|
+
Batch -->|Yes| Recap["Reserve one completion/continuation turn"]
|
|
37
|
+
Batch -->|No| Wake{"Wake intent remains?"}
|
|
38
|
+
Wake -->|Yes| Normal["Reserve one ordinary wake turn"]
|
|
39
|
+
Wake -->|No| Retain
|
|
40
|
+
Recap --> Main["Main collects results and decides what remains"]
|
|
41
|
+
Normal --> Main
|
|
42
|
+
Main --> Settled["Main agent_settled releases reservation"]
|
|
43
|
+
Settled --> Reconcile
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
A report-only timeout requests a wake while the child is **still running**; it does not stop the child. If a ready completion batch and timeout wake are pending at the same scheduling boundary, the completion trigger takes priority and clears the pending wake intent. Their notifications are available in that one turn. A timeout turn that already started is not retroactively merged with a later completion.
|
|
47
|
+
|
|
48
|
+
The 0 ms deferral leaves the current settlement boundary and coalesces events already arriving together. The 100 ms busy retry also covers compaction, so delivery does not depend solely on a later main-agent `agent_settled` event. These are scheduling delays, not guaranteed response deadlines.
|
|
49
|
+
|
|
50
|
+
## Timing: siblings finish before their reporting timers
|
|
51
|
+
|
|
52
|
+
This example has Final Recap on. Time runs downward; all three agents finish before their report deadlines.
|
|
53
|
+
|
|
54
|
+
```mermaid
|
|
55
|
+
sequenceDiagram
|
|
56
|
+
participant Main as Main agent
|
|
57
|
+
participant A as Agent A
|
|
58
|
+
participant B as Agent B
|
|
59
|
+
participant C as Agent C
|
|
60
|
+
participant S as Root scheduler
|
|
61
|
+
Main->>A: Spawn detached with reporting timer
|
|
62
|
+
Main->>B: Spawn detached with reporting timer
|
|
63
|
+
Main->>C: Spawn detached with reporting timer
|
|
64
|
+
Note over Main: Main settles and becomes idle
|
|
65
|
+
A-->>S: Completed, cancel A's timer
|
|
66
|
+
Note over S: Retain result, two async agents remain
|
|
67
|
+
B-->>S: Completed, cancel B's timer
|
|
68
|
+
Note over S: Retain result, one async agent remains
|
|
69
|
+
C-->>S: Completed, cancel C's timer
|
|
70
|
+
Note over S: Zero outstanding, defer and recheck
|
|
71
|
+
S->>Main: One completion/continuation trigger
|
|
72
|
+
Note over Main,C: No reporting timer had to expire
|
|
73
|
+
alt More work remains
|
|
74
|
+
Main->>Main: Collect results and continue the task
|
|
75
|
+
opt Another detached batch is needed
|
|
76
|
+
Main->>C: Spawn new work or resume retained work
|
|
77
|
+
end
|
|
78
|
+
else Overall task is complete
|
|
79
|
+
Main->>Main: Give final recap
|
|
80
|
+
end
|
|
81
|
+
Main-->>S: agent_settled, release turn reservation
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
“Batch” is a scheduling group, not a separate job object. Readiness is checked against the manager's current detached-agent count. New detached work can make the next completion batch wait again.
|
|
85
|
+
|
|
86
|
+
## Timing: a nested descendant finishes last
|
|
87
|
+
|
|
88
|
+
A nested result still belongs to its lexical parent. Its settlement must also reevaluate the root scheduler because the global outstanding count includes that descendant.
|
|
89
|
+
|
|
90
|
+
```mermaid
|
|
91
|
+
sequenceDiagram
|
|
92
|
+
participant Main as Main agent
|
|
93
|
+
participant A as Parent A
|
|
94
|
+
participant B as Sibling B
|
|
95
|
+
participant C as Child C
|
|
96
|
+
participant S as Root scheduler
|
|
97
|
+
Main->>A: Spawn detached
|
|
98
|
+
Main->>B: Spawn detached
|
|
99
|
+
A->>C: Spawn detached child
|
|
100
|
+
A-->>S: A completes, retain root result
|
|
101
|
+
B-->>S: B completes, retain root result
|
|
102
|
+
Note over S: C is still active, so no completion turn
|
|
103
|
+
C-->>A: C completes, deliver result to retained parent
|
|
104
|
+
C-->>S: Settlement reevaluates global readiness
|
|
105
|
+
Note over S: Zero outstanding, root batch is ready
|
|
106
|
+
S->>Main: Completion/continuation trigger for pending root results
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
C's result is not copied into the root mailbox by this path. The main agent can inspect descendant output when needed. Delivery to a retained parent does not itself restart that parent.
|
|
110
|
+
|
|
111
|
+
## Timing: busy main, coalesced signals, and follow-up work
|
|
112
|
+
|
|
113
|
+
Final Recap is on here. A timeout and the last completion arrive during compaction. Later, the automatic turn launches dependent work that finishes before main settles.
|
|
114
|
+
|
|
115
|
+
```mermaid
|
|
116
|
+
sequenceDiagram
|
|
117
|
+
participant Main as Main agent
|
|
118
|
+
participant Child as Detached agent
|
|
119
|
+
participant S as Root scheduler
|
|
120
|
+
Note over Main: Busy with compaction
|
|
121
|
+
Child-->>S: Report timeout, child keeps running
|
|
122
|
+
S->>S: Persist notification, retain wake intent
|
|
123
|
+
Child-->>S: Last completion, clear reporting timer
|
|
124
|
+
S->>S: Persist result, completion batch ready
|
|
125
|
+
loop While main remains busy
|
|
126
|
+
S->>S: Retry after 100 ms, recheck session and idle state
|
|
127
|
+
end
|
|
128
|
+
Note over Main: Compaction ends, no agent_settled required
|
|
129
|
+
S->>Main: Deliver notifications and one completion trigger
|
|
130
|
+
Note over S: Clear wake intent, reserve automatic turn
|
|
131
|
+
Main->>Child: Launch dependent detached work
|
|
132
|
+
Child-->>S: Dependent work completes while main is busy
|
|
133
|
+
S->>S: Retain new result, do not interrupt main
|
|
134
|
+
Main-->>S: agent_settled, release reservation
|
|
135
|
+
S->>S: Reevaluate pending results and defer
|
|
136
|
+
S->>Main: One follow-up completion/continuation trigger
|
|
137
|
+
Main->>Main: Continue remaining work or give final recap
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Settings, cancellation, and persistence
|
|
141
|
+
|
|
142
|
+
- **Subagent Mode Off:** suppresses notification delivery and automatic turns. Matching-session mailbox entries remain available for reconciliation when enabled. **Final Recap off** changes detached completion behavior to ordinary wakes; it is not a master switch for all automatic turns.
|
|
143
|
+
- **One automatic turn at a time:** `rootTurnRunning` reserves a requested turn until main's `agent_settled`. Results arriving during it remain pending for a follow-up. The reservation covers both ordinary wakes and completion/continuation turns.
|
|
144
|
+
- **Session changes:** tree navigation, switching, and forking cancel scheduled work and suppress cancellation-generated turns while stopping old threads. Attaching a session changes the generation; shutdown cancels the timer and changes the generation too. Deferred callbacks recheck session identity and generation before acting.
|
|
145
|
+
- **Branch-local recovery:** root mailbox entries carry `rootSessionId` and a unique `details.mailboxId`. Delivered `pi-subagent:update` messages identify notifications already placed in context. Completion-trigger messages (`pi-subagent:final-recap`) record the completion `mailboxIds` consumed by that batch, so reconciliation does not recap those same IDs again. Ordinary wake intent is an in-memory flag, not a separate durable acknowledgment log.
|
|
146
|
+
|
|
147
|
+
These records track notification delivery and trigger consumption, not successful completion of the user's task. The scheduler calls `pi.sendMessage` with `triggerTurn: true`; it does not receive an acknowledgment that the resulting model turn succeeded.
|
|
148
|
+
|
|
149
|
+
## Implementation and regression coverage
|
|
150
|
+
|
|
151
|
+
- [`src/index.ts`](../src/index.ts): `delivery`, `pendingRootNotifications`, `pendingSummaries`, `scheduleRootTurn`, and session lifecycle hooks.
|
|
152
|
+
- [`src/orch/manager.ts`](../src/orch/manager.ts): `outstandingAsync`, reporting timers, and terminal-state settlement.
|
|
153
|
+
- [`tests/final-recap-integration.test.ts`](../tests/final-recap-integration.test.ts): all six completion orders for three timed siblings, nested-last completion, busy-state retry, timeout/completion coalescing, and completion during an automatic continuation. The compaction case simulates the SDK's busy state; it does not run a content-compaction pass.
|
package/docs/development.md
CHANGED
|
@@ -20,6 +20,7 @@ Tests run offline with no model credentials. Scripted-provider SDK tests cover n
|
|
|
20
20
|
| `src/orch/mailbox.ts` | Input persistence, replay, transcript reconciliation |
|
|
21
21
|
| `src/orch/tools.ts` | Caller-bound model tools |
|
|
22
22
|
| `src/orch/prompt.ts` | System-prompt guidance per mode |
|
|
23
|
+
| `src/orch/housekeeping.ts` | [labs] Housekeeping summarizer: throttling, cancellation, model resolution and the one-line summary call |
|
|
23
24
|
| `src/prefs/config.ts` | Frontmatter validation, precedence, atomic saves |
|
|
24
25
|
| `src/prefs/settings.ts` | Manager settings, validation, safe paths |
|
|
25
26
|
| `src/prefs/models.ts` | Model selection |
|
package/docs/settings.md
CHANGED
|
@@ -23,6 +23,8 @@ All keys are optional. Defaults:
|
|
|
23
23
|
"finalRecap": false,
|
|
24
24
|
"subagentExtensions": false,
|
|
25
25
|
"checklistIntegration": false,
|
|
26
|
+
"housekeepingEnabled": false,
|
|
27
|
+
"housekeepingModel": "",
|
|
26
28
|
"modelSelection": "pick-first-scoped",
|
|
27
29
|
"toolFiltering": "allowed",
|
|
28
30
|
"maxLevels": 3,
|
|
@@ -129,12 +131,40 @@ pi-checklist exposes no runtime API, events or version query, so this is a sourc
|
|
|
129
131
|
|
|
130
132
|
**[labs] Final Recap** is an experimental on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"finalRecap": true` in your settings file.
|
|
131
133
|
|
|
132
|
-
When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent
|
|
134
|
+
When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent. It collects results and continues any unfinished work; only when the overall task is complete does it give a final recap. The response stays in the main thread, so child notifications do not become the final visible message. Progress updates do not trigger turns, and active main-agent work is not interrupted. **Subagent Mode Off** suppresses automatic turns even if this setting is enabled.
|
|
133
135
|
|
|
134
|
-
With Final Recap on, async completion events no longer wake the main agent one by one; the
|
|
136
|
+
With Final Recap on, async completion events no longer wake the main agent one by one; the completion/continuation turn starts once every outstanding async agent has reported, including nested descendants. Reporting timers need not expire: completion cancels them and reevaluates batch readiness immediately. Spawn-timeout events still wake the main agent; a timeout wake and a ready completion batch are coalesced into one turn.
|
|
137
|
+
|
|
138
|
+
The scheduler retains pending notifications while the main agent is busy (including compaction), then retries once it is idle. A single turn reservation prevents duplicate wakes. Session switches and shutdown cancel scheduled delivery; completed batch IDs are persisted to avoid replaying consumed results. See the [asynchronous lifecycle flow and timing diagrams](async-lifecycle.md) for sibling completion, nested agents, timeout coalescing, and follow-up work.
|
|
135
139
|
|
|
136
140
|
**Enabling Final Recap may cause extra model turns and uses more tokens and context.** Leave it off if you prefer to inspect results manually in `/agents tree` or request a summary yourself.
|
|
137
141
|
|
|
142
|
+
## [labs] Housekeeping model (`housekeepingEnabled`, `housekeepingModel`)
|
|
143
|
+
|
|
144
|
+
Experimental, **off by default**. A small model of your choice writes a **one-line summary of what each running agent is doing right now**, shown in the fullscreen tree (`/agents tree`) in place of the raw tool-call line (for example `Running the auth unit tests` instead of `Tool: bash`).
|
|
145
|
+
|
|
146
|
+
Open **[labs] Housekeeping model** in `/agents settings` and set two things, then save with **Ctrl+S**:
|
|
147
|
+
|
|
148
|
+
| Key | Meaning |
|
|
149
|
+
| --- | --- |
|
|
150
|
+
| `housekeepingEnabled` | The opt-in toggle (`false` by default). |
|
|
151
|
+
| `housekeepingModel` | `provider/model-id` of the housekeeping model, or `""` for none. |
|
|
152
|
+
|
|
153
|
+
Pick the model in the dialog's searchable picker. It lists **scoped models first** (the main session's `/scoped-models`), then **every other available model** (any model with working credentials). A small, fast, inexpensive model is usually enough. Turning **Summaries** Off keeps the chosen model for later; **No model** clears it. Both keys follow the normal Global / Current Project layering, and the dots show where each is saved.
|
|
154
|
+
|
|
155
|
+
**What it does**
|
|
156
|
+
|
|
157
|
+
- After an agent's tool or text activity, the agent's task and its last few activity lines (tool names, a short single-line argument snippet such as a command or path, and assistant text) are sent to the housekeeping model, which replies with a single line of at most 80 characters.
|
|
158
|
+
- The summary is shown only while the agent is **starting or running**. Completed, failed, paused and stopped agents show their real status as before. The compact widget (which shows each agent's task) and the live agent view are unchanged. The original status stays available on the thread (`agent_status` returns both `status` and `summary`).
|
|
159
|
+
- An explicit `agent_update` progress message or pause reason replaces the summary until fresh activity arrives.
|
|
160
|
+
- Summaries are display-only and live-only: they are never written to the session registry, restored after a reload, or counted in cost totals.
|
|
161
|
+
|
|
162
|
+
**Never worse than off.** If the feature is disabled, no model is selected, the model is unknown, lacks credentials, or the request fails, times out or returns nothing usable, agents show exactly the status they would show without the feature. The first failure after you change settings or switch sessions produces one warning; failed calls then back off and stop for that run after three consecutive failures. Subagent Mode **Off** also turns it off.
|
|
163
|
+
|
|
164
|
+
**Throttling.** Each agent has at most one housekeeping call in flight and at most one every 10 seconds (activity during a call is coalesced into the next one, after a 1.5 s quiet period), with exponential backoff after failures. At most two calls run at once across all agents, each times out after 20 seconds, and a call is cancelled — and a late answer discarded — when the agent settles or restarts, the toggle or model changes, or the session changes.
|
|
165
|
+
|
|
166
|
+
**Privacy and cost.** The housekeeping model sees each agent's task and recent activity text, including command and path snippets, so choose a provider you are comfortable sending that to. Calls use extra tokens at that model's price and are **not** included in the subagent cost total or the main session's cost.
|
|
167
|
+
|
|
138
168
|
## Model Picking (`modelSelection`)
|
|
139
169
|
|
|
140
170
|
Which model an agent gets when its session starts.
|
package/docs/tools-and-ui.md
CHANGED
|
@@ -34,7 +34,7 @@ are omitted. Spawning under another parent path can change inherited settings.
|
|
|
34
34
|
|
|
35
35
|
Then `agent_wait` or `agent_status` on `/root/controller-security-research`.
|
|
36
36
|
|
|
37
|
-
Child progress and completion notifications are retained in the main agent's context without adding visible chat messages. When a detached (`wait: false`) agent completes, fails or is stopped, the main agent receives a message event that starts a new turn if it is idle (or right after its current turn settles), so it never has to poll. Progress updates and foreground results do not start a turn. The opt-in **[labs] Final Recap** setting changes this: completion messages for async agents are recorded without waking the main agent, and once **all outstanding async agents have reported**, one recap turn summarizes them. Enabling it uses more tokens and context. Use the Agents widget, `/agents tree`, or `agent_output` to inspect child status and answers.
|
|
37
|
+
Child progress and completion notifications are retained in the main agent's context without adding visible chat messages. When a detached (`wait: false`) agent completes, fails or is stopped, the main agent receives a message event that starts a new turn if it is idle (or right after its current turn settles), so it never has to poll. Progress updates and foreground results do not start a turn. The opt-in **[labs] Final Recap** setting changes this: completion messages for async agents are recorded without waking the main agent, and once **all outstanding async agents have reported**, one recap turn summarizes them. Enabling it uses more tokens and context. Use the Agents widget, `/agents tree`, or `agent_output` to inspect child status and answers. With the opt-in **[labs] Housekeeping model**, `/agents tree` shows a model-written one-line summary of each running agent's current work in place of its raw tool-call line (see [settings](settings.md#labs-housekeeping-model-housekeepingenabled-housekeepingmodel)).
|
|
38
38
|
|
|
39
39
|
`agent_spawn` accepts an optional `timeoutMs` (30000–300000, i.e. 30s–5min; out-of-range values are rejected; no timeout when omitted). If the child is still running when it elapses, the parent receives an event (always waking an idle main agent, even in recap mode) with the child's state, status, elapsed time, tokens and recent output. The child is **not** stopped; the parent decides to wait, steer or stop it. The timer is cleared when the child completes, fails, stops or is cancelled, and on session shutdown. It is not re-armed when a child is later resumed with `agent_steer`. `agent_steer` also accepts `timeoutMs` (same 30s–5min range) and `message` is then optional: `timeoutMs` alone only re-arms a running child's timer from now (no steering or resume; error if the child is not running), e.g. after a timeout event shows it is still progressing; with both, the child is steered/resumed and the timer re-armed. At least one of the two is required.
|
|
40
40
|
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -14,6 +14,11 @@ import { configureAgents } from "./ui/settings-ui.ts";
|
|
|
14
14
|
import { AgentNavigationController } from "./ui/status-ui.ts";
|
|
15
15
|
import { AgentNavigationEditor } from "./ui/agent-navigation-editor.ts";
|
|
16
16
|
import { createDriverFactory } from "./orch/runtime.ts";
|
|
17
|
+
import {
|
|
18
|
+
createHousekeepingCompleter,
|
|
19
|
+
HousekeepingSummarizer,
|
|
20
|
+
resolveHousekeepingModel,
|
|
21
|
+
} from "./orch/housekeeping.ts";
|
|
17
22
|
import { createInheritedToolSource } from "./orch/inherited-tools.ts";
|
|
18
23
|
import { subagentPrompt } from "./orch/prompt.ts";
|
|
19
24
|
import { ChecklistMetaMirror, checklistStatus } from "./orch/checklist-integration.ts";
|
|
@@ -65,6 +70,35 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
65
70
|
agentDir: getAgentDir(),
|
|
66
71
|
includeProject: false,
|
|
67
72
|
}).settings;
|
|
73
|
+
// [labs] Housekeeping: inert unless opted in, a model is chosen, and it resolves with credentials.
|
|
74
|
+
const housekeeping = new HousekeepingSummarizer({
|
|
75
|
+
isEnabled: () =>
|
|
76
|
+
limits.subagentMode !== "off" &&
|
|
77
|
+
limits.housekeepingEnabled &&
|
|
78
|
+
limits.housekeepingModel !== "" &&
|
|
79
|
+
context !== undefined &&
|
|
80
|
+
resolveHousekeepingModel(context, limits.housekeepingModel) !== undefined,
|
|
81
|
+
complete: createHousekeepingCompleter(
|
|
82
|
+
() => context,
|
|
83
|
+
() => limits.housekeepingModel,
|
|
84
|
+
),
|
|
85
|
+
apply: (path, run, summary) => manager?.setSummary(path, run, summary) ?? false,
|
|
86
|
+
clear: (path, run) => void manager?.clearSummary(path, run),
|
|
87
|
+
onFailure: (message) =>
|
|
88
|
+
context?.ui.notify(
|
|
89
|
+
`Housekeeping summaries failed (${message}); showing normal agent status instead.`,
|
|
90
|
+
"warning",
|
|
91
|
+
),
|
|
92
|
+
});
|
|
93
|
+
let housekeepingKey = "";
|
|
94
|
+
/** Settings changed: drop in-flight work and stale summaries so the new choice starts clean. */
|
|
95
|
+
const syncHousekeeping = () => {
|
|
96
|
+
const key = `${limits.subagentMode === "off"}|${limits.housekeepingEnabled}|${limits.housekeepingModel}`;
|
|
97
|
+
if (key === housekeepingKey) return;
|
|
98
|
+
housekeepingKey = key;
|
|
99
|
+
housekeeping.cancelAll();
|
|
100
|
+
manager?.clearSummaries();
|
|
101
|
+
};
|
|
68
102
|
const loadLimits = (ctx: ExtensionContext) => {
|
|
69
103
|
const loaded = loadManagerSettings({
|
|
70
104
|
cwd: ctx.cwd,
|
|
@@ -72,6 +106,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
72
106
|
includeProject: ctx.isProjectTrusted(),
|
|
73
107
|
});
|
|
74
108
|
limits = loaded.settings;
|
|
109
|
+
syncHousekeeping();
|
|
75
110
|
refreshCostFooter(ctx);
|
|
76
111
|
return loaded.diagnostics;
|
|
77
112
|
};
|
|
@@ -81,21 +116,16 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
81
116
|
let rootTurnEnded = false;
|
|
82
117
|
const hiddenWidgetThreads = new Set<string>();
|
|
83
118
|
let widgetCollapsed = false;
|
|
84
|
-
let
|
|
119
|
+
let rootTurnRunning = false;
|
|
85
120
|
let suspendingSummaries = false;
|
|
86
|
-
|
|
121
|
+
// One arbiter owns both timeout wakes and completion/continuation turns.
|
|
122
|
+
let rootTurnTimer: ReturnType<typeof setTimeout> | undefined;
|
|
87
123
|
let wakeRequested = false;
|
|
88
|
-
let wakeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
89
|
-
const cancelWake = () => {
|
|
90
|
-
if (wakeTimer !== undefined) clearTimeout(wakeTimer);
|
|
91
|
-
wakeTimer = undefined;
|
|
92
|
-
wakeRequested = false;
|
|
93
|
-
};
|
|
94
124
|
const cancelSummary = () => {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
125
|
+
if (rootTurnTimer !== undefined) clearTimeout(rootTurnTimer);
|
|
126
|
+
rootTurnTimer = undefined;
|
|
127
|
+
wakeRequested = false;
|
|
128
|
+
rootTurnRunning = false;
|
|
99
129
|
};
|
|
100
130
|
// Right at a tree leaf steps tree → full: leave any session collapse behind.
|
|
101
131
|
const returnToWidget = () => {
|
|
@@ -275,39 +305,6 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
275
305
|
);
|
|
276
306
|
if (notification.trigger === true) wakeRequested = true;
|
|
277
307
|
};
|
|
278
|
-
/** Wake an idle main agent once for all pending async events (coalesced, after the settle boundary). */
|
|
279
|
-
const scheduleWake = (ctx: ExtensionContext) => {
|
|
280
|
-
if (!wakeRequested || wakeTimer !== undefined || limits.subagentMode === "off") return;
|
|
281
|
-
const currentGeneration = generation;
|
|
282
|
-
wakeTimer = setTimeout(() => {
|
|
283
|
-
wakeTimer = undefined;
|
|
284
|
-
if (
|
|
285
|
-
currentGeneration !== generation ||
|
|
286
|
-
context?.sessionManager !== ctx.sessionManager ||
|
|
287
|
-
limits.subagentMode === "off" ||
|
|
288
|
-
suspendingSummaries ||
|
|
289
|
-
!wakeRequested
|
|
290
|
-
)
|
|
291
|
-
return;
|
|
292
|
-
if (ctx.isIdle() === false) return; // agent_settled reschedules
|
|
293
|
-
wakeRequested = false;
|
|
294
|
-
try {
|
|
295
|
-
pi.sendMessage(
|
|
296
|
-
{
|
|
297
|
-
customType: ROOT_WAKE_MESSAGE,
|
|
298
|
-
content:
|
|
299
|
-
"Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
|
|
300
|
-
"React: collect results with agent_output, and for a timeout event decide to wait, steer, stop or re-arm with agent_steer using path and timeoutMs only (omit message; resets the reporting timer from now without interrupting the running agent).",
|
|
301
|
-
display: false,
|
|
302
|
-
details: {},
|
|
303
|
-
},
|
|
304
|
-
{ triggerTurn: true },
|
|
305
|
-
);
|
|
306
|
-
} catch (error) {
|
|
307
|
-
warnDelivery(error);
|
|
308
|
-
}
|
|
309
|
-
}, 0);
|
|
310
|
-
};
|
|
311
308
|
const pendingSummaries = (ctx: ExtensionContext) => {
|
|
312
309
|
const entries = ctx.sessionManager.getBranch();
|
|
313
310
|
const summarized = new Set(
|
|
@@ -329,63 +326,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
329
326
|
: [];
|
|
330
327
|
});
|
|
331
328
|
};
|
|
332
|
-
const
|
|
333
|
-
if (
|
|
334
|
-
!limits.finalRecap ||
|
|
335
|
-
limits.subagentMode === "off" ||
|
|
336
|
-
summaryRunning ||
|
|
337
|
-
suspendingSummaries ||
|
|
338
|
-
summaryTimer !== undefined ||
|
|
339
|
-
ctx.isIdle() === false ||
|
|
340
|
-
(manager?.outstandingAsync() ?? 0) > 0 ||
|
|
341
|
-
!pendingSummaries(ctx).length
|
|
342
|
-
)
|
|
343
|
-
return;
|
|
344
|
-
const currentGeneration = generation;
|
|
345
|
-
// Coalesce siblings finishing together and leave the settlement boundary before
|
|
346
|
-
// starting a new turn. Recheck settings/session/idle state after the deferral.
|
|
347
|
-
summaryTimer = setTimeout(() => {
|
|
348
|
-
summaryTimer = undefined;
|
|
349
|
-
if (
|
|
350
|
-
currentGeneration !== generation ||
|
|
351
|
-
context?.sessionManager !== ctx.sessionManager ||
|
|
352
|
-
!limits.finalRecap ||
|
|
353
|
-
limits.subagentMode === "off" ||
|
|
354
|
-
suspendingSummaries ||
|
|
355
|
-
ctx.isIdle() === false ||
|
|
356
|
-
(manager?.outstandingAsync() ?? 0) > 0
|
|
357
|
-
)
|
|
358
|
-
return;
|
|
359
|
-
const notifications = pendingSummaries(ctx);
|
|
360
|
-
if (!notifications.length) return;
|
|
361
|
-
summaryRunning = true;
|
|
362
|
-
try {
|
|
363
|
-
pi.sendMessage(
|
|
364
|
-
{
|
|
365
|
-
customType: ROOT_SUMMARY_MESSAGE,
|
|
366
|
-
content:
|
|
367
|
-
"Summarize the newly finished asynchronous subagent results for the user. " +
|
|
368
|
-
"Their results are in the preceding subagent notifications; use agent_output if more detail is needed. " +
|
|
369
|
-
"Give a concise main-thread answer covering results and any failures. " +
|
|
370
|
-
"Do not spawn or resume agents solely to summarize.\nAgents: " +
|
|
371
|
-
[...new Set(notifications.map((notification) => notification.details.path))].join(
|
|
372
|
-
", ",
|
|
373
|
-
),
|
|
374
|
-
display: false,
|
|
375
|
-
details: {
|
|
376
|
-
mailboxIds: notifications.map((notification) => notification.details.mailboxId),
|
|
377
|
-
},
|
|
378
|
-
},
|
|
379
|
-
{ triggerTurn: true },
|
|
380
|
-
);
|
|
381
|
-
} catch (error) {
|
|
382
|
-
summaryRunning = false;
|
|
383
|
-
warnDelivery(error);
|
|
384
|
-
}
|
|
385
|
-
}, 0);
|
|
386
|
-
};
|
|
387
|
-
const restoreRootMailbox = (ctx: ExtensionContext) => {
|
|
388
|
-
if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
|
|
329
|
+
const pendingRootNotifications = (ctx: ExtensionContext) => {
|
|
389
330
|
const entries = ctx.sessionManager.getBranch();
|
|
390
331
|
const delivered = new Set(
|
|
391
332
|
entries.flatMap((entry) => {
|
|
@@ -394,25 +335,115 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
394
335
|
return typeof id === "string" ? [id] : [];
|
|
395
336
|
}),
|
|
396
337
|
);
|
|
397
|
-
|
|
398
|
-
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY)
|
|
338
|
+
return entries.flatMap((entry) => {
|
|
339
|
+
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
399
340
|
const notification = entry.data as RootNotification | undefined;
|
|
400
341
|
if (
|
|
401
|
-
notification?.rootSessionId
|
|
402
|
-
typeof notification.content
|
|
403
|
-
typeof notification.details?.mailboxId
|
|
404
|
-
|
|
405
|
-
)
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
|
|
342
|
+
notification?.rootSessionId !== ctx.sessionManager.getSessionId() ||
|
|
343
|
+
typeof notification.content !== "string" ||
|
|
344
|
+
typeof notification.details?.mailboxId !== "string" ||
|
|
345
|
+
delivered.has(notification.details.mailboxId)
|
|
346
|
+
)
|
|
347
|
+
return [];
|
|
348
|
+
delivered.add(notification.details.mailboxId);
|
|
349
|
+
return [notification];
|
|
350
|
+
});
|
|
351
|
+
};
|
|
352
|
+
const scheduleRootTurn = (ctx: ExtensionContext) => {
|
|
353
|
+
if (
|
|
354
|
+
limits.subagentMode === "off" ||
|
|
355
|
+
rootTurnRunning ||
|
|
356
|
+
suspendingSummaries ||
|
|
357
|
+
rootTurnTimer !== undefined
|
|
358
|
+
)
|
|
359
|
+
return;
|
|
360
|
+
// Include undelivered mailbox entries: a completion may arrive while Pi is
|
|
361
|
+
// compacting, which does not necessarily produce an agent_settled event.
|
|
362
|
+
if (
|
|
363
|
+
!wakeRequested &&
|
|
364
|
+
!(limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0 && pendingSummaries(ctx).length > 0) &&
|
|
365
|
+
!pendingRootNotifications(ctx).some((notification) => notification.trigger === true)
|
|
366
|
+
)
|
|
367
|
+
return;
|
|
368
|
+
const currentGeneration = generation;
|
|
369
|
+
// Zero-delay deferral crosses the SDK settlement boundary; busy retries also
|
|
370
|
+
// cover compaction and other non-agent busy periods. Reporting timers are
|
|
371
|
+
// deliberately irrelevant to completion readiness.
|
|
372
|
+
rootTurnTimer = setTimeout(
|
|
373
|
+
() => {
|
|
374
|
+
rootTurnTimer = undefined;
|
|
375
|
+
if (
|
|
376
|
+
currentGeneration !== generation ||
|
|
377
|
+
context?.sessionManager !== ctx.sessionManager ||
|
|
378
|
+
limits.subagentMode === "off" ||
|
|
379
|
+
suspendingSummaries ||
|
|
380
|
+
rootTurnRunning
|
|
381
|
+
)
|
|
382
|
+
return;
|
|
383
|
+
if (ctx.isIdle() === false) {
|
|
384
|
+
scheduleRootTurn(ctx);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
drainRootMailbox(ctx);
|
|
388
|
+
const notifications =
|
|
389
|
+
limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0
|
|
390
|
+
? pendingSummaries(ctx)
|
|
391
|
+
: [];
|
|
392
|
+
if (!notifications.length && !wakeRequested) return;
|
|
393
|
+
const wasWakeRequested = wakeRequested;
|
|
394
|
+
wakeRequested = false;
|
|
395
|
+
rootTurnRunning = true; // Also reserves a normal wake until agent_settled.
|
|
396
|
+
try {
|
|
397
|
+
pi.sendMessage(
|
|
398
|
+
notifications.length
|
|
399
|
+
? {
|
|
400
|
+
customType: ROOT_SUMMARY_MESSAGE,
|
|
401
|
+
content:
|
|
402
|
+
"The asynchronous subagent batch has finished. Collect and inspect its results " +
|
|
403
|
+
"(use agent_output if more detail is needed), then continue any unfinished work in the user's task. " +
|
|
404
|
+
"If the overall task is complete, give a concise final recap covering results and failures. " +
|
|
405
|
+
"Do not spawn or resume agents solely to summarize.\nAgents: " +
|
|
406
|
+
[
|
|
407
|
+
...new Set(notifications.map((notification) => notification.details.path)),
|
|
408
|
+
].join(", "),
|
|
409
|
+
display: false,
|
|
410
|
+
details: {
|
|
411
|
+
mailboxIds: notifications.map((notification) => notification.details.mailboxId),
|
|
412
|
+
},
|
|
413
|
+
}
|
|
414
|
+
: {
|
|
415
|
+
customType: ROOT_WAKE_MESSAGE,
|
|
416
|
+
content:
|
|
417
|
+
"Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
|
|
418
|
+
"Collect results with agent_output and continue any unfinished work; recap when the overall task is complete. " +
|
|
419
|
+
"For a timeout event decide to wait, steer, stop or re-arm with agent_steer using path and timeoutMs only " +
|
|
420
|
+
"(omit message; resets the reporting timer from now without interrupting the running agent).",
|
|
421
|
+
display: false,
|
|
422
|
+
details: {},
|
|
423
|
+
},
|
|
424
|
+
{ triggerTurn: true },
|
|
425
|
+
);
|
|
426
|
+
} catch (error) {
|
|
427
|
+
rootTurnRunning = false;
|
|
428
|
+
wakeRequested = wasWakeRequested;
|
|
429
|
+
warnDelivery(error);
|
|
430
|
+
}
|
|
431
|
+
},
|
|
432
|
+
ctx.isIdle() === false ? 100 : 0,
|
|
433
|
+
);
|
|
434
|
+
rootTurnTimer.unref?.();
|
|
435
|
+
};
|
|
436
|
+
const drainRootMailbox = (ctx: ExtensionContext) => {
|
|
437
|
+
if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
|
|
438
|
+
for (const notification of pendingRootNotifications(ctx)) sendRootNotification(notification);
|
|
439
|
+
};
|
|
440
|
+
const restoreRootMailbox = (ctx: ExtensionContext) => {
|
|
441
|
+
drainRootMailbox(ctx);
|
|
442
|
+
scheduleRootTurn(ctx);
|
|
412
443
|
};
|
|
413
444
|
pi.on("agent_settled", async (_event, ctx) => {
|
|
414
445
|
if (context?.sessionManager === ctx.sessionManager) {
|
|
415
|
-
|
|
446
|
+
rootTurnRunning = false;
|
|
416
447
|
restoreRootMailbox(ctx);
|
|
417
448
|
}
|
|
418
449
|
});
|
|
@@ -462,7 +493,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
462
493
|
// The eventual transcript message carries its ID for branch-local recovery.
|
|
463
494
|
pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
|
|
464
495
|
restoreRootMailbox(requireContext());
|
|
465
|
-
} else
|
|
496
|
+
} else {
|
|
497
|
+
void requireManager().deliver(event.recipient, message).catch(warnDelivery);
|
|
498
|
+
// Global outstandingAsync includes nested descendants, so their last
|
|
499
|
+
// settlement must unblock a root batch even when its parent has finished.
|
|
500
|
+
if (event.kind === "settled") restoreRootMailbox(requireContext());
|
|
501
|
+
}
|
|
466
502
|
} catch (error) {
|
|
467
503
|
warnDelivery(error);
|
|
468
504
|
}
|
|
@@ -521,7 +557,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
521
557
|
pi.on("agent_start", async (_event, ctx) => {
|
|
522
558
|
// A new task must not resurrect the previous task's settled agents. Automatic
|
|
523
559
|
// final-recap turns still belong to that task and keep its results visible.
|
|
524
|
-
if (manager && !
|
|
560
|
+
if (manager && !rootTurnRunning) {
|
|
525
561
|
for (const thread of manager.list()) {
|
|
526
562
|
if (thread.state !== "starting" && thread.state !== "running")
|
|
527
563
|
hiddenWidgetThreads.add(thread.path);
|
|
@@ -565,6 +601,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
565
601
|
seedHistory = true,
|
|
566
602
|
) => {
|
|
567
603
|
cancelSummary();
|
|
604
|
+
housekeeping.cancelAll();
|
|
568
605
|
const token = ++generation;
|
|
569
606
|
closeNavigation(installEditor);
|
|
570
607
|
navigation = new AgentNavigationController(returnToWidget);
|
|
@@ -601,8 +638,18 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
601
638
|
const message = error instanceof Error ? error.message : String(error);
|
|
602
639
|
context?.ui.notify(`Subagent ${event.kind} notification failed: ${message}`, "warning");
|
|
603
640
|
},
|
|
641
|
+
onActivity: (activity) => {
|
|
642
|
+
if (token === generation) housekeeping.notify(activity);
|
|
643
|
+
},
|
|
604
644
|
onEvent: (event) => {
|
|
605
645
|
if (token !== generation) return;
|
|
646
|
+
// Settled agents and explicit progress reports (which replace the summary) cancel pending
|
|
647
|
+
// housekeeping so an older request cannot reapply stale text; fresh activity reschedules.
|
|
648
|
+
if (
|
|
649
|
+
event.kind === "update" ||
|
|
650
|
+
(event.thread.state !== "starting" && event.thread.state !== "running")
|
|
651
|
+
)
|
|
652
|
+
housekeeping.settle(event.thread.path);
|
|
606
653
|
refreshWidget(requireContext());
|
|
607
654
|
if (event.kind !== "metrics") persist();
|
|
608
655
|
if (event.kind === "settled") rollupCost(event.thread);
|
|
@@ -668,6 +715,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
668
715
|
pi.on("session_before_fork", stopWorkingThreads);
|
|
669
716
|
pi.on("session_shutdown", async () => {
|
|
670
717
|
cancelSummary();
|
|
718
|
+
housekeeping.cancelAll();
|
|
671
719
|
generation++;
|
|
672
720
|
closeNavigation(true);
|
|
673
721
|
await manager?.shutdown();
|