pi-subagent-manager 0.28.0 → 0.28.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/docs/async-lifecycle.md +153 -0
- package/docs/settings.md +4 -2
- package/package.json +1 -1
- package/src/index.ts +119 -118
package/README.md
CHANGED
|
@@ -88,7 +88,7 @@ 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
|
|
|
@@ -97,6 +97,7 @@ Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main ag
|
|
|
97
97
|
- [Your own agent](docs/custom-agents.md) — walkthrough for writing an agent type
|
|
98
98
|
- [Settings](docs/settings.md) — every setting and option, and when to use each
|
|
99
99
|
- [Threads and lifecycle](docs/threads.md) — paths, context, pause/resume, persistence
|
|
100
|
+
- [Asynchronous lifecycle](docs/async-lifecycle.md) — flow and timing diagrams for completion, wakes, and continuation
|
|
100
101
|
- [Tools and UI](docs/tools-and-ui.md) — model-facing tools, parallel work, dialogs
|
|
101
102
|
- [Importing agents](docs/importing-agents.md) — migrate from other pi subagent packages
|
|
102
103
|
- [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/settings.md
CHANGED
|
@@ -129,9 +129,11 @@ pi-checklist exposes no runtime API, events or version query, so this is a sourc
|
|
|
129
129
|
|
|
130
130
|
**[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
131
|
|
|
132
|
-
When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent
|
|
132
|
+
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
133
|
|
|
134
|
-
With Final Recap on, async completion events no longer wake the main agent one by one; the
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
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
137
|
|
|
136
138
|
**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
139
|
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -81,21 +81,16 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
81
81
|
let rootTurnEnded = false;
|
|
82
82
|
const hiddenWidgetThreads = new Set<string>();
|
|
83
83
|
let widgetCollapsed = false;
|
|
84
|
-
let
|
|
84
|
+
let rootTurnRunning = false;
|
|
85
85
|
let suspendingSummaries = false;
|
|
86
|
-
|
|
86
|
+
// One arbiter owns both timeout wakes and completion/continuation turns.
|
|
87
|
+
let rootTurnTimer: ReturnType<typeof setTimeout> | undefined;
|
|
87
88
|
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
89
|
const cancelSummary = () => {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
90
|
+
if (rootTurnTimer !== undefined) clearTimeout(rootTurnTimer);
|
|
91
|
+
rootTurnTimer = undefined;
|
|
92
|
+
wakeRequested = false;
|
|
93
|
+
rootTurnRunning = false;
|
|
99
94
|
};
|
|
100
95
|
// Right at a tree leaf steps tree → full: leave any session collapse behind.
|
|
101
96
|
const returnToWidget = () => {
|
|
@@ -275,39 +270,6 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
275
270
|
);
|
|
276
271
|
if (notification.trigger === true) wakeRequested = true;
|
|
277
272
|
};
|
|
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
273
|
const pendingSummaries = (ctx: ExtensionContext) => {
|
|
312
274
|
const entries = ctx.sessionManager.getBranch();
|
|
313
275
|
const summarized = new Set(
|
|
@@ -329,63 +291,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
329
291
|
: [];
|
|
330
292
|
});
|
|
331
293
|
};
|
|
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;
|
|
294
|
+
const pendingRootNotifications = (ctx: ExtensionContext) => {
|
|
389
295
|
const entries = ctx.sessionManager.getBranch();
|
|
390
296
|
const delivered = new Set(
|
|
391
297
|
entries.flatMap((entry) => {
|
|
@@ -394,25 +300,115 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
394
300
|
return typeof id === "string" ? [id] : [];
|
|
395
301
|
}),
|
|
396
302
|
);
|
|
397
|
-
|
|
398
|
-
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY)
|
|
303
|
+
return entries.flatMap((entry) => {
|
|
304
|
+
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
399
305
|
const notification = entry.data as RootNotification | undefined;
|
|
400
306
|
if (
|
|
401
|
-
notification?.rootSessionId
|
|
402
|
-
typeof notification.content
|
|
403
|
-
typeof notification.details?.mailboxId
|
|
404
|
-
|
|
405
|
-
)
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
|
|
307
|
+
notification?.rootSessionId !== ctx.sessionManager.getSessionId() ||
|
|
308
|
+
typeof notification.content !== "string" ||
|
|
309
|
+
typeof notification.details?.mailboxId !== "string" ||
|
|
310
|
+
delivered.has(notification.details.mailboxId)
|
|
311
|
+
)
|
|
312
|
+
return [];
|
|
313
|
+
delivered.add(notification.details.mailboxId);
|
|
314
|
+
return [notification];
|
|
315
|
+
});
|
|
316
|
+
};
|
|
317
|
+
const scheduleRootTurn = (ctx: ExtensionContext) => {
|
|
318
|
+
if (
|
|
319
|
+
limits.subagentMode === "off" ||
|
|
320
|
+
rootTurnRunning ||
|
|
321
|
+
suspendingSummaries ||
|
|
322
|
+
rootTurnTimer !== undefined
|
|
323
|
+
)
|
|
324
|
+
return;
|
|
325
|
+
// Include undelivered mailbox entries: a completion may arrive while Pi is
|
|
326
|
+
// compacting, which does not necessarily produce an agent_settled event.
|
|
327
|
+
if (
|
|
328
|
+
!wakeRequested &&
|
|
329
|
+
!(limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0 && pendingSummaries(ctx).length > 0) &&
|
|
330
|
+
!pendingRootNotifications(ctx).some((notification) => notification.trigger === true)
|
|
331
|
+
)
|
|
332
|
+
return;
|
|
333
|
+
const currentGeneration = generation;
|
|
334
|
+
// Zero-delay deferral crosses the SDK settlement boundary; busy retries also
|
|
335
|
+
// cover compaction and other non-agent busy periods. Reporting timers are
|
|
336
|
+
// deliberately irrelevant to completion readiness.
|
|
337
|
+
rootTurnTimer = setTimeout(
|
|
338
|
+
() => {
|
|
339
|
+
rootTurnTimer = undefined;
|
|
340
|
+
if (
|
|
341
|
+
currentGeneration !== generation ||
|
|
342
|
+
context?.sessionManager !== ctx.sessionManager ||
|
|
343
|
+
limits.subagentMode === "off" ||
|
|
344
|
+
suspendingSummaries ||
|
|
345
|
+
rootTurnRunning
|
|
346
|
+
)
|
|
347
|
+
return;
|
|
348
|
+
if (ctx.isIdle() === false) {
|
|
349
|
+
scheduleRootTurn(ctx);
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
drainRootMailbox(ctx);
|
|
353
|
+
const notifications =
|
|
354
|
+
limits.finalRecap && (manager?.outstandingAsync() ?? 0) === 0
|
|
355
|
+
? pendingSummaries(ctx)
|
|
356
|
+
: [];
|
|
357
|
+
if (!notifications.length && !wakeRequested) return;
|
|
358
|
+
const wasWakeRequested = wakeRequested;
|
|
359
|
+
wakeRequested = false;
|
|
360
|
+
rootTurnRunning = true; // Also reserves a normal wake until agent_settled.
|
|
361
|
+
try {
|
|
362
|
+
pi.sendMessage(
|
|
363
|
+
notifications.length
|
|
364
|
+
? {
|
|
365
|
+
customType: ROOT_SUMMARY_MESSAGE,
|
|
366
|
+
content:
|
|
367
|
+
"The asynchronous subagent batch has finished. Collect and inspect its results " +
|
|
368
|
+
"(use agent_output if more detail is needed), then continue any unfinished work in the user's task. " +
|
|
369
|
+
"If the overall task is complete, give a concise final recap covering results and failures. " +
|
|
370
|
+
"Do not spawn or resume agents solely to summarize.\nAgents: " +
|
|
371
|
+
[
|
|
372
|
+
...new Set(notifications.map((notification) => notification.details.path)),
|
|
373
|
+
].join(", "),
|
|
374
|
+
display: false,
|
|
375
|
+
details: {
|
|
376
|
+
mailboxIds: notifications.map((notification) => notification.details.mailboxId),
|
|
377
|
+
},
|
|
378
|
+
}
|
|
379
|
+
: {
|
|
380
|
+
customType: ROOT_WAKE_MESSAGE,
|
|
381
|
+
content:
|
|
382
|
+
"Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
|
|
383
|
+
"Collect results with agent_output and continue any unfinished work; recap when the overall task is complete. " +
|
|
384
|
+
"For a timeout event decide to wait, steer, stop or re-arm with agent_steer using path and timeoutMs only " +
|
|
385
|
+
"(omit message; resets the reporting timer from now without interrupting the running agent).",
|
|
386
|
+
display: false,
|
|
387
|
+
details: {},
|
|
388
|
+
},
|
|
389
|
+
{ triggerTurn: true },
|
|
390
|
+
);
|
|
391
|
+
} catch (error) {
|
|
392
|
+
rootTurnRunning = false;
|
|
393
|
+
wakeRequested = wasWakeRequested;
|
|
394
|
+
warnDelivery(error);
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
ctx.isIdle() === false ? 100 : 0,
|
|
398
|
+
);
|
|
399
|
+
rootTurnTimer.unref?.();
|
|
400
|
+
};
|
|
401
|
+
const drainRootMailbox = (ctx: ExtensionContext) => {
|
|
402
|
+
if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
|
|
403
|
+
for (const notification of pendingRootNotifications(ctx)) sendRootNotification(notification);
|
|
404
|
+
};
|
|
405
|
+
const restoreRootMailbox = (ctx: ExtensionContext) => {
|
|
406
|
+
drainRootMailbox(ctx);
|
|
407
|
+
scheduleRootTurn(ctx);
|
|
412
408
|
};
|
|
413
409
|
pi.on("agent_settled", async (_event, ctx) => {
|
|
414
410
|
if (context?.sessionManager === ctx.sessionManager) {
|
|
415
|
-
|
|
411
|
+
rootTurnRunning = false;
|
|
416
412
|
restoreRootMailbox(ctx);
|
|
417
413
|
}
|
|
418
414
|
});
|
|
@@ -462,7 +458,12 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
462
458
|
// The eventual transcript message carries its ID for branch-local recovery.
|
|
463
459
|
pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
|
|
464
460
|
restoreRootMailbox(requireContext());
|
|
465
|
-
} else
|
|
461
|
+
} else {
|
|
462
|
+
void requireManager().deliver(event.recipient, message).catch(warnDelivery);
|
|
463
|
+
// Global outstandingAsync includes nested descendants, so their last
|
|
464
|
+
// settlement must unblock a root batch even when its parent has finished.
|
|
465
|
+
if (event.kind === "settled") restoreRootMailbox(requireContext());
|
|
466
|
+
}
|
|
466
467
|
} catch (error) {
|
|
467
468
|
warnDelivery(error);
|
|
468
469
|
}
|
|
@@ -521,7 +522,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
521
522
|
pi.on("agent_start", async (_event, ctx) => {
|
|
522
523
|
// A new task must not resurrect the previous task's settled agents. Automatic
|
|
523
524
|
// final-recap turns still belong to that task and keep its results visible.
|
|
524
|
-
if (manager && !
|
|
525
|
+
if (manager && !rootTurnRunning) {
|
|
525
526
|
for (const thread of manager.list()) {
|
|
526
527
|
if (thread.state !== "starting" && thread.state !== "running")
|
|
527
528
|
hiddenWidgetThreads.add(thread.path);
|