pi-subagent-manager 0.11.2 → 0.13.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 -2
- package/docs/custom-agents.md +35 -0
- package/docs/settings.md +12 -3
- package/docs/tools-and-ui.md +12 -7
- package/package.json +1 -1
- package/src/index.ts +96 -8
- package/src/prefs/config.ts +572 -43
- package/src/prefs/settings.ts +6 -4
- package/src/types.ts +16 -0
- package/src/ui/agent-navigation-editor.ts +40 -26
- package/src/ui/live-agent-view.ts +153 -29
- package/src/ui/settings-ui.ts +8 -0
- package/src/ui/status-ui.ts +30 -6
- package/src/ui/ui.ts +223 -56
package/README.md
CHANGED
|
@@ -72,9 +72,11 @@ They inherit your current model until you set preferences. Details: [docs/defaul
|
|
|
72
72
|
| `/agents import` | Import agents from other subagent extensions |
|
|
73
73
|
| `/agents reload` | Reload definitions and settings |
|
|
74
74
|
|
|
75
|
-
A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line; `/agents tree` still opens the full tree. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
|
|
75
|
+
A live **Agents** widget sits above the input box. Choose **Full** (the existing tree) or **Minimal** (colored status counts and running-agent token totals, plus the browser hint) under **Status Widget** in `/agents` settings. In the fullscreen tree, **Enter** opens an agent's live view. Type in the bottom **Steer** input and press **Enter** to send it a steering message, including nested agents. **Tab** switches between input and transcript controls, **Escape** returns, and **i** in the tree opens existing thread actions. A status strip below the previews shows how many agents are running and **Press ← to open subagent browser**. Once the main turn ends and all subagents are idle, the preview collapses to a single status-count line; `/agents tree` still opens the full tree. While subagents are starting or running, press **Left** at the start of the main draft to open it; otherwise Left stays native. Press **Right** at the end of the draft (or in an empty input) to collapse the widget to one line for this session only, without changing saved settings. `/agents tree` remains available regardless of agent activity. See [live navigation](docs/tools-and-ui.md#live-agent-navigation) for controls and compatibility.
|
|
76
76
|
|
|
77
|
-
Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names (off by default; requires a Nerd Font in your terminal). Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
|
|
77
|
+
Experimental features are marked **[labs]** in settings. Enable **[labs] Nerd Font icons** in `/agents` to show role-specific icons beside agent names, with animated progress glyphs for starting/running agents and static icons for settled agents (off by default; requires a Nerd Font in your terminal). Custom agent types can set an optional `icon` or use **[labs] Icon** in `/agents types`. See [icon setup](docs/settings.md#labs-nerd-font-icons-nerdfonticons).
|
|
78
|
+
|
|
79
|
+
Enable **[labs] Final Recap** in `/agents` to automatically ask the idle main agent to summarize detached-agent results, 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).
|
|
78
80
|
|
|
79
81
|
## Docs
|
|
80
82
|
|
package/docs/custom-agents.md
CHANGED
|
@@ -11,6 +11,41 @@ An agent type is one Markdown file: YAML frontmatter on top, system prompt below
|
|
|
11
11
|
|
|
12
12
|
Precedence: **project > user > bundled**. A file with the same `name` as a bundled agent replaces it.
|
|
13
13
|
|
|
14
|
+
## Tweak settings or fork the agent?
|
|
15
|
+
|
|
16
|
+
Two ways to customize a bundled agent. Pick one per agent — a scope (user or
|
|
17
|
+
project) cannot hold both a `.md` and a `.yml` for the same name.
|
|
18
|
+
|
|
19
|
+
| | Tweak settings (`<name>.yml`) | Fork agent (`<name>.md`) |
|
|
20
|
+
|---|---|---|
|
|
21
|
+
| What it is | Settings-only override merged on top of the bundled definition | Full copy that replaces the bundled definition |
|
|
22
|
+
| System prompt | Stays bundled; you keep receiving prompt updates | Copied; you own it, bundled prompt updates no longer apply |
|
|
23
|
+
| Editable | Settings (models, tools, thinking, color, icon, description) | Everything, including name and system prompt |
|
|
24
|
+
| File | Plain YAML mapping, no frontmatter, no Markdown body | YAML frontmatter on top, system prompt below |
|
|
25
|
+
|
|
26
|
+
`~/.pi/agent/subagent-manager/agents/coder.yml`:
|
|
27
|
+
|
|
28
|
+
```yaml
|
|
29
|
+
name: coder
|
|
30
|
+
thinkingLevel: low
|
|
31
|
+
tools:
|
|
32
|
+
allow:
|
|
33
|
+
- read
|
|
34
|
+
- grep
|
|
35
|
+
- agent_update
|
|
36
|
+
- agent_pause
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
Only listed fields override; everything else follows the base definition, so
|
|
40
|
+
untouched settings keep tracking bundled updates. Set an optional field to
|
|
41
|
+
`null` to clear it back to the base state (e.g. `icon: null`). `name`, when
|
|
42
|
+
present, must match the filename. Overrides need a base agent to merge onto —
|
|
43
|
+
a `.yml` without a matching bundled or forked definition is rejected.
|
|
44
|
+
|
|
45
|
+
In `/agents types`, editing a bundled agent asks you to pick one mode first,
|
|
46
|
+
and settings stay locked until you choose. Overrides cannot rename the agent
|
|
47
|
+
or edit the system prompt — fork it instead.
|
|
48
|
+
|
|
14
49
|
These are the only locations read. Other packages' `~/.pi/agent/agents` or `.pi/agents` are ignored — use [`/agents import`](importing-agents.md) for those.
|
|
15
50
|
|
|
16
51
|
## 2. Write the file
|
package/docs/settings.md
CHANGED
|
@@ -16,6 +16,7 @@ All keys are optional. Defaults:
|
|
|
16
16
|
"subagentMode": "opportunistic",
|
|
17
17
|
"widgetMode": "full",
|
|
18
18
|
"nerdFontIcons": false,
|
|
19
|
+
"finalRecap": false,
|
|
19
20
|
"modelSelection": "pick-first-scoped",
|
|
20
21
|
"toolFiltering": "allowed",
|
|
21
22
|
"maxLevels": 3,
|
|
@@ -49,19 +50,27 @@ Controls the subagent status display above the input box. Choose **Status Widget
|
|
|
49
50
|
|
|
50
51
|
| Option | Display |
|
|
51
52
|
| ------------------ | ------- |
|
|
52
|
-
| `full` (default) |
|
|
53
|
+
| `full` (default) | A compact tree with one row per agent, task/state, metrics and navigation hints. |
|
|
53
54
|
| `minimal` | One line of theme-colored status counts plus cumulative input `↑` / output `↓` tokens for agents currently starting or running. |
|
|
54
55
|
|
|
55
|
-
Minimal mode groups starting agents with running agents and excludes the main conversation. Token totals exclude completed, stopped, failed and paused agents. The fullscreen tree remains available via `/agents tree` in either mode.
|
|
56
|
+
Minimal mode groups starting agents with running agents and excludes the main conversation. Token totals exclude completed, stopped, failed and paused agents. The fullscreen tree remains available via `/agents tree` in either mode. In full mode, press **Right (→)** at the end of the main draft (or in an empty input) to collapse to one line for this session only, without saving preferences. Session startup/switch/reload restores the configured mode. **Left (←)** at the start of the draft still opens the full dialog while agents are active.
|
|
56
57
|
|
|
57
58
|
## [labs] Nerd Font icons (`nerdFontIcons`)
|
|
58
59
|
|
|
59
60
|
Experimental features are tagged **[labs]** in settings. **[labs] Nerd Font icons** is an on/off toggle, **off by default**. Enable it in `/agents` and save with **Ctrl+S**, or set `"nerdFontIcons": true` in your settings file. Configure a [Nerd Font](https://www.nerdfonts.com/) in your terminal first; unsupported fonts may show boxes or incorrect glyphs. The extension does not install or detect fonts.
|
|
60
61
|
|
|
61
|
-
When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker.
|
|
62
|
+
When enabled, an agent type’s optional `icon` appears before its readable name in the full widget, thread browsers, live watcher header, and type picker. Starting/running agents use a cycling Nerd Font progress glyph in the widget, fullscreen tree and live watcher header; paused/completed/stopped/failed agents retain static role icons. Active agents without a configured icon also show the progress glyph. The one-line minimal widget animates its aggregate running count, not individual agents. Turning the setting off restores text-only labels without removing configured icons; RPC output remains static. Saved settings apply immediately to newly rendered widgets and dialogs.
|
|
62
63
|
|
|
63
64
|
All six bundled agents have [role-specific icons](default-agents.md#nerd-font-icons). Add or change an icon with **[labs] Icon** in `/agents types`, or the optional `icon` frontmatter field in [your own agent](custom-agents.md#icons-labs). Retained threads keep the icon from their saved agent definition.
|
|
64
65
|
|
|
66
|
+
## [labs] Final Recap (`finalRecap`)
|
|
67
|
+
|
|
68
|
+
**[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.
|
|
69
|
+
|
|
70
|
+
When detached agents finish or fail and the main agent is idle, their results are sent back to the main agent for an automatic summary. The summary is a main-thread response, so child notifications do not become the final visible message. Progress updates do not trigger summaries, and active main-agent work is not interrupted. **Subagent Mode Off** suppresses automatic summaries even if this setting is enabled.
|
|
71
|
+
|
|
72
|
+
**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.
|
|
73
|
+
|
|
65
74
|
## Model Picking (`modelSelection`)
|
|
66
75
|
|
|
67
76
|
Which model an agent gets when its session starts.
|
package/docs/tools-and-ui.md
CHANGED
|
@@ -25,6 +25,8 @@
|
|
|
25
25
|
|
|
26
26
|
Then `agent_wait` or `agent_status` on `/root/controller-security-research`.
|
|
27
27
|
|
|
28
|
+
Child progress and completion notifications are retained in the main agent's context without adding visible chat messages. By default they do not start another turn, keeping the main agent's final response last in the conversation even when detached children finish later. The opt-in **[labs] Final Recap** setting asks an idle main agent to summarize newly completed or failed asynchronous agents; results arriving during a summary are handled after that summary finishes. Progress updates and foreground results do not trigger summaries. Enabling it uses more tokens and context. Use the Agents widget, `/agents tree`, or `agent_output` to inspect child status and answers.
|
|
29
|
+
|
|
28
30
|
## Parallel and nested work
|
|
29
31
|
|
|
30
32
|
- Launch **all independent siblings with `wait: false`, then wait**. Spawning one foreground child and waiting before the next is sequential.
|
|
@@ -58,7 +60,7 @@ Refreshes every second and keeps your selection, collapse state and scroll posit
|
|
|
58
60
|
|
|
59
61
|
### Live agent navigation
|
|
60
62
|
|
|
61
|
-
The fullscreen watcher
|
|
63
|
+
The fullscreen watcher renders steer and agent messages (including thinking) as Markdown, same as pi's main transcript. Tool calls use pi's built-in call formats (`$ command`, `read path:range`, `grep /pattern/ in path`, …) rather than bare JSON; unknown tools fall back to pretty-printed JSON. Tool results and other metadata show their name/status and only the first three wrapped lines of each output preview, followed by `...` when more is hidden. Use **i → Transcript** from the tree for retained tool details. **t** cycles three detail levels with transcript controls focused: **preview** (default: three rows per call, first three rendered thinking lines), **compact** (one line per call, thinking hidden), **full** (complete calls and thinking). Inherited context is initially collapsed (**c** toggles it with transcript controls focused). Watching alone never starts a turn, switches sessions, or changes model/tool/resource ownership. Unsupported/custom content and images use safe text placeholders rather than native rich rendering. Legacy sessions without reliable inherited-prefix metadata show their whole transcript.
|
|
62
64
|
|
|
63
65
|
- The bottom **Steer** input is focused initially. Type and press **Enter** to send to the inspected agent, including nested descendants, through the same service as `agent_steer`: running agents receive queued input; paused/completed/stopped agents resume their retained session. Empty input is ignored. Sending leaves the viewer open; failures are shown and preserve the draft for retry.
|
|
64
66
|
- **Tab** switches between steering input and transcript controls. While typing, **c/t/l/r** are ordinary text and **Home/End** move the input cursor. Pasting never submits by itself.
|
|
@@ -66,11 +68,13 @@ The fullscreen watcher shows steer and agent messages in full, including the in-
|
|
|
66
68
|
- **Ctrl+R** (or **r** with transcript controls focused) retries an unavailable observation without starting a turn. Starting threads are watchable; stopped/completed threads remain readable.
|
|
67
69
|
- Frames are sanitized, viewport-bounded and coalesced during bursts. Exit, root replacement and shutdown release observers/timers. Streaming deltas never enter persisted thread events.
|
|
68
70
|
|
|
69
|
-
####
|
|
71
|
+
#### Arrow-key shortcuts
|
|
70
72
|
|
|
71
73
|
While any subagent is **starting or running**, press physical **Left (←)** at the beginning of the main draft (or in an empty input) to open the subagent browser. With no active subagents, or elsewhere in the draft, Left retains normal cursor movement. `/agents tree` remains available regardless of agent activity. Down is always native editing/history navigation. Autocomplete, jumps, paste and configured shortcuts take precedence. Navigating preserves the main draft/cursor and does not require the root to be idle.
|
|
72
74
|
|
|
73
|
-
|
|
75
|
+
Press physical **Right (→)** at the end of the main draft (or in an empty input) to collapse the full widget to a single status line for this session. This does not save settings or change the configured **Status Widget** mode. Refreshes, agent resumes, new main turns and session-tree navigation keep it collapsed; starting, switching or reloading a session restores the configured mode. Left still opens the full dialog while subagents are active, without expanding the widget. Elsewhere in the draft Right retains normal cursor movement; autocomplete, jumps, paste and shortcuts take precedence.
|
|
76
|
+
|
|
77
|
+
Arrow-key shortcuts are enabled by default in the TUI; `/agents tree` remains available everywhere. Pi has one custom-editor slot: installation is skipped if another factory owns it or an existing draft is nonempty, since the host cannot transfer cursor/undo/expanded-paste state. Load order can still let a later editor replace ours. Initial startup uses Pi's history hydration; replacement installations seed history once. Session-tree rebuilds keep the existing editor instance.
|
|
74
78
|
|
|
75
79
|
While navigation is open, the host fullscreen search shortcut is temporarily disabled through public keybindings to avoid stacking a second host overlay. The prior binding owner is restored only if no other extension replaced it. **Known host limitation:** if an unrelated extension stacks another overlay above navigation, Pi's custom-UI completion can close the newer overlay instead. Avoid concurrent extension-owned overlays; a host identity-targeted completion API is needed to remove this limitation. No private host access or unsupported overlay-lifecycle workaround is used.
|
|
76
80
|
|
|
@@ -83,15 +87,16 @@ The widget above the input editor has two display modes, selected with **Status
|
|
|
83
87
|
- **Full** (default): the existing compact tree, at most twelve lines.
|
|
84
88
|
- **Minimal**: a summary line such as `3 running, 2 stopped, 1 failed, 1 paused ↑12k ↓3k`, with semantic theme colors. Starting agents count as running; completed agents are counted when present. Token totals include only currently starting/running agents, not the main conversation or settled threads. Use `/agents tree` for details.
|
|
85
89
|
|
|
86
|
-
Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree`; **Left** at the start of the draft opens it only while subagents are starting or running. A new main turn or active subagent restores the configured display mode.
|
|
90
|
+
Once the main turn has ended and no subagents are starting or running, either mode collapses to a single status-count line without the browser hint. The full tree remains available via `/agents tree`; **Left** at the start of the draft opens it only while subagents are starting or running. A new main turn or active subagent restores the configured display mode unless Right has collapsed the widget for this session.
|
|
87
91
|
|
|
88
92
|
In full mode:
|
|
89
93
|
|
|
90
|
-
-
|
|
91
|
-
-
|
|
94
|
+
- One row per agent: colored type pill, path, state, task, active time, input `↑` / output `↓` tokens.
|
|
95
|
+
- Activity and lifecycle messages (such as `Completed; session retained`) are omitted to save space; detailed status remains available in `/agents tree` and `agent_status`.
|
|
92
96
|
- Active branches are shown first; the most recent agents within each state are preferred when previews overflow. Overflow is counted, not listed.
|
|
93
97
|
- Time freezes while paused and resumes on continue.
|
|
94
|
-
- A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow.
|
|
98
|
+
- A small status strip below the previews shows the running count (including starting agents) and **Press ← to open subagent browser**, including when agents overflow. The full footer also shows **→ collapse**. Minimal mode keeps **← browser** inline so it stays one line. Browser hints appear only while subagents are starting or running; RPC output omits keyboard hints.
|
|
99
|
+
- With **[labs] Nerd Font icons** enabled, starting/running agents show a cycling progress glyph in the widget and fullscreen tree/live-view headers. Settled agents retain static role icons. The minimal summary also animates its running count. Animation timers stop on settlement or disposal; RPC output stays static.
|
|
95
100
|
|
|
96
101
|
### Interrupts and stopping agents
|
|
97
102
|
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -18,9 +18,11 @@ import type { SavedThread, ThreadEvent } from "./types.ts";
|
|
|
18
18
|
|
|
19
19
|
const REGISTRY_ENTRY = "pi-subagent:registry:v1";
|
|
20
20
|
const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
|
|
21
|
+
const ROOT_SUMMARY_MESSAGE = "pi-subagent:final-recap";
|
|
21
22
|
type RootNotification = {
|
|
22
23
|
rootSessionId: string;
|
|
23
24
|
content: string;
|
|
25
|
+
finalRecap?: boolean;
|
|
24
26
|
details: { mailboxId: string; path: string; state: string };
|
|
25
27
|
};
|
|
26
28
|
|
|
@@ -49,6 +51,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
49
51
|
};
|
|
50
52
|
let generation = 0;
|
|
51
53
|
let rootTurnEnded = false;
|
|
54
|
+
let widgetCollapsed = false;
|
|
55
|
+
let summaryRunning = false;
|
|
56
|
+
let suspendingSummaries = false;
|
|
57
|
+
let summaryTimer: ReturnType<typeof setTimeout> | undefined;
|
|
58
|
+
const cancelSummary = () => {
|
|
59
|
+
if (summaryTimer !== undefined) clearTimeout(summaryTimer);
|
|
60
|
+
summaryTimer = undefined;
|
|
61
|
+
summaryRunning = false;
|
|
62
|
+
};
|
|
52
63
|
let navigation = new AgentNavigationController();
|
|
53
64
|
let navigationEditor: AgentNavigationEditor | undefined;
|
|
54
65
|
let navigationEditorFactory: Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0];
|
|
@@ -85,6 +96,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
85
96
|
(thread.state === "starting" || thread.state === "running")),
|
|
86
97
|
openTree: () => manager && context
|
|
87
98
|
? navigation.open(context, manager.scope("/root"), undefined, limits.nerdFontIcons) : undefined,
|
|
99
|
+
canCollapse: () => manager !== undefined && context?.mode === "tui" &&
|
|
100
|
+
limits.subagentMode !== "off" && !navigation.isOpen && !widgetCollapsed &&
|
|
101
|
+
limits.widgetMode === "full" && manager.list().some((thread) => thread.path !== "/root"),
|
|
102
|
+
collapseWidget: () => {
|
|
103
|
+
widgetCollapsed = true;
|
|
104
|
+
if (context) refreshWidget(context);
|
|
105
|
+
},
|
|
88
106
|
onError: (error) => context?.ui.notify(
|
|
89
107
|
error instanceof Error ? error.message : String(error), "error"),
|
|
90
108
|
});
|
|
@@ -149,12 +167,62 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
149
167
|
{
|
|
150
168
|
customType: "pi-subagent:update",
|
|
151
169
|
content: notification.content,
|
|
152
|
-
|
|
170
|
+
// Keep asynchronous child updates in model context, not the main chat.
|
|
171
|
+
// Idle/settlement delivery can follow the root's final answer; rendering it
|
|
172
|
+
// would leave a child's output as the last visible message. The widget and
|
|
173
|
+
// agent browser provide status/output without displacing the root response.
|
|
174
|
+
display: false,
|
|
153
175
|
details: notification.details,
|
|
154
176
|
},
|
|
155
177
|
{ triggerTurn: false },
|
|
156
178
|
);
|
|
157
179
|
};
|
|
180
|
+
const pendingSummaries = (ctx: ExtensionContext) => {
|
|
181
|
+
const entries = ctx.sessionManager.getBranch();
|
|
182
|
+
const summarized = new Set(entries.flatMap((entry) => {
|
|
183
|
+
if (entry.type !== "custom_message" || entry.customType !== ROOT_SUMMARY_MESSAGE) return [];
|
|
184
|
+
const ids = (entry.details as { mailboxIds?: unknown } | undefined)?.mailboxIds;
|
|
185
|
+
return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
|
|
186
|
+
}));
|
|
187
|
+
return entries.flatMap((entry) => {
|
|
188
|
+
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
189
|
+
const notification = entry.data as RootNotification | undefined;
|
|
190
|
+
return notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
|
|
191
|
+
notification.finalRecap === true && typeof notification.content === "string" &&
|
|
192
|
+
typeof notification.details?.mailboxId === "string" &&
|
|
193
|
+
!summarized.has(notification.details.mailboxId) ? [notification] : [];
|
|
194
|
+
});
|
|
195
|
+
};
|
|
196
|
+
const scheduleSummary = (ctx: ExtensionContext) => {
|
|
197
|
+
if (!limits.finalRecap || limits.subagentMode === "off" || summaryRunning || suspendingSummaries ||
|
|
198
|
+
summaryTimer !== undefined || ctx.isIdle() === false || !pendingSummaries(ctx).length) return;
|
|
199
|
+
const currentGeneration = generation;
|
|
200
|
+
// Coalesce siblings finishing together and leave the settlement boundary before
|
|
201
|
+
// starting a new turn. Recheck settings/session/idle state after the deferral.
|
|
202
|
+
summaryTimer = setTimeout(() => {
|
|
203
|
+
summaryTimer = undefined;
|
|
204
|
+
if (currentGeneration !== generation || context?.sessionManager !== ctx.sessionManager ||
|
|
205
|
+
!limits.finalRecap || limits.subagentMode === "off" || suspendingSummaries || ctx.isIdle() === false) return;
|
|
206
|
+
const notifications = pendingSummaries(ctx);
|
|
207
|
+
if (!notifications.length) return;
|
|
208
|
+
summaryRunning = true;
|
|
209
|
+
try {
|
|
210
|
+
pi.sendMessage({
|
|
211
|
+
customType: ROOT_SUMMARY_MESSAGE,
|
|
212
|
+
content: "Summarize the newly finished asynchronous subagent results for the user. " +
|
|
213
|
+
"Their results are in the preceding subagent notifications; use agent_output if more detail is needed. " +
|
|
214
|
+
"Give a concise main-thread answer covering results and any failures. " +
|
|
215
|
+
"Do not spawn or resume agents solely to summarize.\nAgents: " +
|
|
216
|
+
[...new Set(notifications.map((notification) => notification.details.path))].join(", "),
|
|
217
|
+
display: false,
|
|
218
|
+
details: { mailboxIds: notifications.map((notification) => notification.details.mailboxId) },
|
|
219
|
+
}, { triggerTurn: true });
|
|
220
|
+
} catch (error) {
|
|
221
|
+
summaryRunning = false;
|
|
222
|
+
warnDelivery(error);
|
|
223
|
+
}
|
|
224
|
+
}, 0);
|
|
225
|
+
};
|
|
158
226
|
const restoreRootMailbox = (ctx: ExtensionContext) => {
|
|
159
227
|
if (limits.subagentMode === "off" || ctx.isIdle?.() === false) return;
|
|
160
228
|
const entries = ctx.sessionManager.getBranch();
|
|
@@ -178,9 +246,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
178
246
|
delivered.add(notification.details.mailboxId);
|
|
179
247
|
}
|
|
180
248
|
}
|
|
249
|
+
scheduleSummary(ctx);
|
|
181
250
|
};
|
|
182
251
|
pi.on("agent_settled", async (_event, ctx) => {
|
|
183
|
-
if (context?.sessionManager === ctx.sessionManager)
|
|
252
|
+
if (context?.sessionManager === ctx.sessionManager) {
|
|
253
|
+
summaryRunning = false;
|
|
254
|
+
restoreRootMailbox(ctx);
|
|
255
|
+
}
|
|
184
256
|
});
|
|
185
257
|
const delivery = (event: ThreadEvent) => {
|
|
186
258
|
if (event.kind === "change" || event.kind === "metrics") return;
|
|
@@ -196,6 +268,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
196
268
|
const notification: RootNotification = {
|
|
197
269
|
rootSessionId: requireContext().sessionManager.getSessionId(),
|
|
198
270
|
content: message,
|
|
271
|
+
// Foreground results already handled by a busy main thread do not need
|
|
272
|
+
// another turn. Completions during a summary do need a follow-up summary.
|
|
273
|
+
finalRecap: limits.finalRecap && !suspendingSummaries && event.kind === "settled" &&
|
|
274
|
+
(thread.state === "completed" || thread.state === "failed") &&
|
|
275
|
+
(requireContext().isIdle() || summaryRunning),
|
|
199
276
|
details: {
|
|
200
277
|
mailboxId: randomUUID(),
|
|
201
278
|
path: thread.path,
|
|
@@ -205,7 +282,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
205
282
|
// Persist first; defer delivery until the root is idle and the plugin is enabled.
|
|
206
283
|
// The eventual transcript message carries its ID for branch-local recovery.
|
|
207
284
|
pi.appendEntry(ROOT_MAILBOX_ENTRY, notification);
|
|
208
|
-
|
|
285
|
+
restoreRootMailbox(requireContext());
|
|
209
286
|
} else void requireManager().deliver(event.recipient, message).catch(warnDelivery);
|
|
210
287
|
} catch (error) {
|
|
211
288
|
warnDelivery(error);
|
|
@@ -235,7 +312,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
235
312
|
const refreshWidget = (ctx: ExtensionContext) => {
|
|
236
313
|
if (limits.subagentMode === "off") {
|
|
237
314
|
if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
|
|
238
|
-
} else updateWidget(ctx, requireManager().list(), limits.widgetMode,
|
|
315
|
+
} else updateWidget(ctx, requireManager().list(), widgetCollapsed ? "minimal" : limits.widgetMode,
|
|
316
|
+
limits.nerdFontIcons, rootTurnEnded);
|
|
239
317
|
};
|
|
240
318
|
pi.on("agent_start", async (_event, ctx) => {
|
|
241
319
|
rootTurnEnded = false;
|
|
@@ -266,6 +344,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
266
344
|
});
|
|
267
345
|
|
|
268
346
|
const attachSession = async (ctx: ExtensionContext, installEditor = false, seedHistory = true) => {
|
|
347
|
+
cancelSummary();
|
|
269
348
|
const token = ++generation;
|
|
270
349
|
closeNavigation(installEditor);
|
|
271
350
|
navigation = new AgentNavigationController();
|
|
@@ -274,6 +353,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
274
353
|
inheritedTools.reset();
|
|
275
354
|
context = ctx;
|
|
276
355
|
rootTurnEnded = false;
|
|
356
|
+
if (installEditor) widgetCollapsed = false;
|
|
277
357
|
store = new ConfigStore({
|
|
278
358
|
cwd: ctx.cwd,
|
|
279
359
|
agentDir: getAgentDir(),
|
|
@@ -336,11 +416,18 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
336
416
|
});
|
|
337
417
|
pi.on("session_tree", async (_event, ctx) => attachSession(ctx));
|
|
338
418
|
const stopWorkingThreads = async () => {
|
|
419
|
+
cancelSummary();
|
|
339
420
|
closeNavigation();
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
421
|
+
suspendingSummaries = true;
|
|
422
|
+
try {
|
|
423
|
+
if (!manager) return;
|
|
424
|
+
for (const thread of manager.list()) {
|
|
425
|
+
const state = manager.get(thread.path).state;
|
|
426
|
+
if (state === "starting" || state === "running") await manager.stop("/root", thread.path);
|
|
427
|
+
}
|
|
428
|
+
} finally {
|
|
429
|
+
cancelSummary();
|
|
430
|
+
suspendingSummaries = false;
|
|
344
431
|
}
|
|
345
432
|
};
|
|
346
433
|
// Finish old-thread cancellation while appendEntry still points to the old branch/session.
|
|
@@ -348,6 +435,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
348
435
|
pi.on("session_before_switch", stopWorkingThreads);
|
|
349
436
|
pi.on("session_before_fork", stopWorkingThreads);
|
|
350
437
|
pi.on("session_shutdown", async () => {
|
|
438
|
+
cancelSummary();
|
|
351
439
|
generation++;
|
|
352
440
|
closeNavigation(true);
|
|
353
441
|
await manager?.shutdown();
|