pi-subagent-manager 0.16.0 → 0.18.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 +6 -0
- package/docs/settings.md +2 -0
- package/docs/tools-and-ui.md +24 -18
- package/package.json +1 -1
- package/src/index.ts +236 -61
- package/src/orch/cost-ledger.ts +56 -0
- package/src/orch/manager.ts +155 -14
- package/src/orch/prompt.ts +1 -1
- package/src/orch/runtime.ts +22 -2
- package/src/orch/tools.ts +17 -4
- package/src/types.ts +26 -3
- package/src/ui/cost-footer.ts +187 -0
- package/src/ui/status-ui.ts +102 -36
- package/src/ui/tool-picker.ts +96 -6
- package/src/ui/ui.ts +129 -210
package/README.md
CHANGED
|
@@ -75,6 +75,12 @@ They inherit your current model until you set preferences. Details: [docs/defaul
|
|
|
75
75
|
|
|
76
76
|
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. A fresh prompt hides previously settled agents from the widget; they reappear only when resumed, and `/agents tree` always keeps them available. 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.
|
|
77
77
|
|
|
78
|
+
**Cost accounting:** Agent rows show estimated USD cost (including cache reads/writes) when reported. Completed, paused, stopped, and failed agents roll up only newly incurred cost. Accounting survives resume, reload, branch navigation, and reaping; nested agents' own costs are counted once. Running-agent costs remain in their rows until settlement. This changes the footer display, not Pi's native session statistics.
|
|
79
|
+
|
|
80
|
+
- **Default footer:** when no extension provides `/footer`, a default-style footer shows the combined main-agent + settled subagent cost in place of the usual cost.
|
|
81
|
+
- **`npm:pi-footer`:** its footer/layout is left untouched. Add a **Pi Event Value** widget through `/footer`, set **Widget ID** to `subagent_cost`, and enable **Raw value only**. This shows the settled **subagent-only** USD subtotal, e.g. `$0.0123`; its existing Session Cost widget still shows main-session cost. The subtotal includes a currency Nerd Font icon when **[labs] Nerd Font icons** is on in `/agents settings`. Values republish on session start/reload and after settlement/settings changes.
|
|
82
|
+
- Other extensions registering `/footer` also keep ownership; the fallback cannot safely compose with unrelated custom-footer extensions that expose no `/footer` command.
|
|
83
|
+
|
|
78
84
|
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). Loaders appear **before**, never instead of, the role icon. Choose Circle, Braille, or Hourglass under **[labs] Loader style**, with previews of every animation frame and each family's completed, paused, failed, and stopped icons. 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).
|
|
79
85
|
|
|
80
86
|
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).
|
package/docs/settings.md
CHANGED
|
@@ -76,6 +76,8 @@ The Labs preview shows every family's running animation frames and completed, pa
|
|
|
76
76
|
|
|
77
77
|
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.
|
|
78
78
|
|
|
79
|
+
With Final Recap on, async completion events no longer wake the main agent one by one; the recap turn starts once every outstanding async agent has reported (spawn-timeout events still wake it).
|
|
80
|
+
|
|
79
81
|
**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.
|
|
80
82
|
|
|
81
83
|
## Model Picking (`modelSelection`)
|
package/docs/tools-and-ui.md
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
# Tools and UI
|
|
2
2
|
|
|
3
|
+
## Tool picker
|
|
4
|
+
|
|
5
|
+
The allow/block tool picker lists session tools flat, except MCP tools named `mcp__<mcp>__<tool>`: those are grouped under one `mcp__<mcp>` row, collapsed by default. The row shows `[x]`, `[ ]` or `[-]` (mixed) and Enter toggles every tool in the group. Right expands the group, Left collapses it (Left on a child also collapses and selects the group). While searching, matching groups are expanded automatically.
|
|
6
|
+
|
|
3
7
|
## Model-facing tools
|
|
4
8
|
|
|
5
9
|
| Tool | Purpose |
|
|
6
10
|
| -------------- | ---------------------------------------------------- |
|
|
7
11
|
| `agent_types` | Names, descriptions, resolved models and thinking |
|
|
8
|
-
| `agent_spawn` | Start `{path, type, task, wait?}`. Waits by default. |
|
|
12
|
+
| `agent_spawn` | Start `{path, type, task, wait?, timeoutMs?}`. Waits by default. |
|
|
9
13
|
| `agent_wait` | Wait for settlement; optional `timeoutMs` |
|
|
10
|
-
| `agent_steer` | Send `{path, message}`; queues
|
|
14
|
+
| `agent_steer` | Send `{path, message?, timeoutMs?}`; queues/resumes and/or re-arms timeout|
|
|
11
15
|
| `agent_status` | Inspect one path or list visible threads |
|
|
12
16
|
| `agent_update` | Child: report progress |
|
|
13
17
|
| `agent_pause` | Child: pause without an answer |
|
|
@@ -30,7 +34,9 @@ are omitted. Spawning under another parent path can change inherited settings.
|
|
|
30
34
|
|
|
31
35
|
Then `agent_wait` or `agent_status` on `/root/controller-security-research`.
|
|
32
36
|
|
|
33
|
-
Child progress and completion notifications are retained in the main agent's context without adding visible chat messages.
|
|
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.
|
|
38
|
+
|
|
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.
|
|
34
40
|
|
|
35
41
|
## Parallel and nested work
|
|
36
42
|
|
|
@@ -41,26 +47,26 @@ Child progress and completion notifications are retained in the main agent's con
|
|
|
41
47
|
|
|
42
48
|
## Commands
|
|
43
49
|
|
|
44
|
-
| Command | Does
|
|
45
|
-
| ----------------------------- |
|
|
46
|
-
| `/agents`, `/agents settings` | [Settings](settings.md) dialog. **Agent definitions** jumps to the type editor.
|
|
47
|
-
| `/agents types` | Type browser and editor — see [custom agents](custom-agents.md#editing-in-the-tui)
|
|
48
|
-
| `/agents tree [path]` | Live full tree; optional path preselects.
|
|
49
|
-
| `/agents import` | [Import picker](importing-agents.md)
|
|
50
|
-
| `/agents reload` | Reload definitions and settings; show diagnostics
|
|
50
|
+
| Command | Does |
|
|
51
|
+
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
52
|
+
| `/agents`, `/agents settings` | [Settings](settings.md) dialog. **Agent definitions** jumps to the type editor. |
|
|
53
|
+
| `/agents types` | Type browser and editor — see [custom agents](custom-agents.md#editing-in-the-tui) |
|
|
54
|
+
| `/agents tree [path]` | Live full tree; optional path preselects. |
|
|
55
|
+
| `/agents import` | [Import picker](importing-agents.md) |
|
|
56
|
+
| `/agents reload` | Reload definitions and settings; show diagnostics |
|
|
51
57
|
| `/agents reap` | Show the eligible count and a Confirm/Cancel dialog, then forget completed agents and free retained-thread slots. Active parents and ancestors of retained threads are preserved; reaped agents cannot be resumed. Session files are not deleted. |
|
|
52
58
|
|
|
53
59
|
### `/agents tree` keys
|
|
54
60
|
|
|
55
|
-
| Key | Action
|
|
56
|
-
| ----------- |
|
|
57
|
-
| ↑↓ | Select
|
|
58
|
-
| ←→ | Collapse / expand
|
|
59
|
-
| PgUp / PgDn | Scroll
|
|
60
|
-
| Enter | Watch thread; Main returns to the editor
|
|
61
|
+
| Key | Action |
|
|
62
|
+
| ----------- | ------------------------------------------------- |
|
|
63
|
+
| ↑↓ | Select |
|
|
64
|
+
| ←→ | Collapse / expand |
|
|
65
|
+
| PgUp / PgDn | Scroll |
|
|
66
|
+
| Enter | Watch thread; Main returns to the editor |
|
|
61
67
|
| i | Existing actions: steer, stop, output, transcript |
|
|
62
|
-
| Esc | Watcher → saved tree → Main
|
|
63
|
-
| Ctrl+Q | Return directly to Main
|
|
68
|
+
| Esc | Watcher → saved tree → Main |
|
|
69
|
+
| Ctrl+Q | Return directly to Main |
|
|
64
70
|
|
|
65
71
|
Refreshes every second and keeps your selection, collapse state and scroll position.
|
|
66
72
|
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -3,7 +3,11 @@ import { buildSessionContext, getAgentDir } from "@earendil-works/pi-coding-agen
|
|
|
3
3
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { fuzzyFilter } from "@earendil-works/pi-tui";
|
|
5
5
|
import { ConfigStore } from "./prefs/config.ts";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
IMPORT_REQUEST_PREFIX,
|
|
8
|
+
markImportOffered,
|
|
9
|
+
offerAgentImport,
|
|
10
|
+
} from "./prefs/agent-import.ts";
|
|
7
11
|
import { ThreadManager } from "./orch/manager.ts";
|
|
8
12
|
import { loadManagerSettings } from "./prefs/settings.ts";
|
|
9
13
|
import { configureAgents } from "./ui/settings-ui.ts";
|
|
@@ -15,15 +19,20 @@ import { subagentPrompt } from "./orch/prompt.ts";
|
|
|
15
19
|
import { agentTools } from "./orch/tools.ts";
|
|
16
20
|
import { editAgentTypes, updateWidget } from "./ui/ui.ts";
|
|
17
21
|
import { canOpenDialog, dialogMenu } from "./ui/dialog.ts";
|
|
18
|
-
import type { SavedThread, ThreadEvent } from "./types.ts";
|
|
22
|
+
import type { SavedThread, ThreadEvent, ThreadView } from "./types.ts";
|
|
23
|
+
import { COST_ENTRY, CostLedger } from "./orch/cost-ledger.ts";
|
|
24
|
+
import { CostFooterController } from "./ui/cost-footer.ts";
|
|
19
25
|
|
|
20
26
|
const REGISTRY_ENTRY = "pi-subagent:registry:v1";
|
|
21
27
|
const ROOT_MAILBOX_ENTRY = "pi-subagent:root-mailbox:v1";
|
|
22
28
|
const ROOT_SUMMARY_MESSAGE = "pi-subagent:final-recap";
|
|
29
|
+
const ROOT_WAKE_MESSAGE = "pi-subagent:wake";
|
|
23
30
|
type RootNotification = {
|
|
24
31
|
rootSessionId: string;
|
|
25
32
|
content: string;
|
|
26
33
|
finalRecap?: boolean;
|
|
34
|
+
/** Start a main-agent turn so it reacts to this event (async completion, spawn timeout). */
|
|
35
|
+
trigger?: boolean;
|
|
27
36
|
details: { mailboxId: string; path: string; state: string };
|
|
28
37
|
};
|
|
29
38
|
|
|
@@ -36,6 +45,17 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
36
45
|
includeProject: false,
|
|
37
46
|
});
|
|
38
47
|
let manager: ThreadManager | undefined;
|
|
48
|
+
let costLedger = new CostLedger();
|
|
49
|
+
const costFooter = new CostFooterController(
|
|
50
|
+
pi,
|
|
51
|
+
() => costLedger.totalUsd,
|
|
52
|
+
() => limits.nerdFontIcons,
|
|
53
|
+
);
|
|
54
|
+
const refreshCostFooter = (ctx: ExtensionContext) => costFooter.refresh(ctx);
|
|
55
|
+
const rollupCost = (thread: ThreadView) => {
|
|
56
|
+
costLedger.settle(thread, (record) => pi.appendEntry(COST_ENTRY, record));
|
|
57
|
+
if (context) refreshCostFooter(context);
|
|
58
|
+
};
|
|
39
59
|
let limits = loadManagerSettings({
|
|
40
60
|
cwd: process.cwd(),
|
|
41
61
|
agentDir: getAgentDir(),
|
|
@@ -48,6 +68,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
48
68
|
includeProject: ctx.isProjectTrusted(),
|
|
49
69
|
});
|
|
50
70
|
limits = loaded.settings;
|
|
71
|
+
refreshCostFooter(ctx);
|
|
51
72
|
return loaded.diagnostics;
|
|
52
73
|
};
|
|
53
74
|
let generation = 0;
|
|
@@ -57,7 +78,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
57
78
|
let summaryRunning = false;
|
|
58
79
|
let suspendingSummaries = false;
|
|
59
80
|
let summaryTimer: ReturnType<typeof setTimeout> | undefined;
|
|
81
|
+
let wakeRequested = false;
|
|
82
|
+
let wakeTimer: ReturnType<typeof setTimeout> | undefined;
|
|
83
|
+
const cancelWake = () => {
|
|
84
|
+
if (wakeTimer !== undefined) clearTimeout(wakeTimer);
|
|
85
|
+
wakeTimer = undefined;
|
|
86
|
+
wakeRequested = false;
|
|
87
|
+
};
|
|
60
88
|
const cancelSummary = () => {
|
|
89
|
+
cancelWake();
|
|
61
90
|
if (summaryTimer !== undefined) clearTimeout(summaryTimer);
|
|
62
91
|
summaryTimer = undefined;
|
|
63
92
|
summaryRunning = false;
|
|
@@ -81,32 +110,61 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
81
110
|
if (existingFactory && existingFactory !== navigationEditorFactory) return;
|
|
82
111
|
// The host only transfers raw text, not cursor/undo/expanded-paste state.
|
|
83
112
|
if (ctx.ui.getEditorText?.()) return;
|
|
84
|
-
const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap(
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
113
|
+
const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap(
|
|
114
|
+
(message) => {
|
|
115
|
+
if (message.role !== "user") return [];
|
|
116
|
+
const content = message.content;
|
|
117
|
+
return [
|
|
118
|
+
typeof content === "string"
|
|
119
|
+
? content
|
|
120
|
+
: content
|
|
121
|
+
.filter((block) => block.type === "text")
|
|
122
|
+
.map((block) => block.text)
|
|
123
|
+
.join(""),
|
|
124
|
+
];
|
|
125
|
+
},
|
|
126
|
+
);
|
|
90
127
|
navigationEditorFactory = (tui, theme, keys) => {
|
|
91
128
|
const editor = new AgentNavigationEditor(tui, theme, keys, {
|
|
92
129
|
// Initial startup hydrates after session_start; replacement editors do not.
|
|
93
130
|
initialHistory: seedHistory ? history : undefined,
|
|
94
131
|
generation: () => navigationGeneration,
|
|
95
|
-
canOpen: () =>
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
132
|
+
canOpen: () =>
|
|
133
|
+
manager !== undefined &&
|
|
134
|
+
context?.mode === "tui" &&
|
|
135
|
+
limits.subagentMode !== "off" &&
|
|
136
|
+
!navigation.isOpen &&
|
|
137
|
+
manager
|
|
138
|
+
.list()
|
|
139
|
+
.some(
|
|
140
|
+
(thread) =>
|
|
141
|
+
thread.path !== "/root" &&
|
|
142
|
+
(thread.state === "starting" || thread.state === "running"),
|
|
143
|
+
),
|
|
144
|
+
openTree: () =>
|
|
145
|
+
manager && context
|
|
146
|
+
? navigation.open(
|
|
147
|
+
context,
|
|
148
|
+
manager.scope("/root"),
|
|
149
|
+
undefined,
|
|
150
|
+
limits.nerdFontIcons,
|
|
151
|
+
limits.loaderStyle,
|
|
152
|
+
)
|
|
153
|
+
: undefined,
|
|
154
|
+
canCollapse: () =>
|
|
155
|
+
manager !== undefined &&
|
|
156
|
+
context?.mode === "tui" &&
|
|
157
|
+
limits.subagentMode !== "off" &&
|
|
158
|
+
!navigation.isOpen &&
|
|
159
|
+
!widgetCollapsed &&
|
|
160
|
+
limits.widgetMode === "full" &&
|
|
161
|
+
widgetThreads().some((thread) => thread.path !== "/root"),
|
|
104
162
|
collapseWidget: () => {
|
|
105
163
|
widgetCollapsed = true;
|
|
106
164
|
if (context) refreshWidget(context);
|
|
107
165
|
},
|
|
108
|
-
onError: (error) =>
|
|
109
|
-
error instanceof Error ? error.message : String(error), "error"),
|
|
166
|
+
onError: (error) =>
|
|
167
|
+
context?.ui.notify(error instanceof Error ? error.message : String(error), "error"),
|
|
110
168
|
});
|
|
111
169
|
navigationEditor = editor;
|
|
112
170
|
return editor;
|
|
@@ -120,7 +178,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
120
178
|
// Migration requires the root's file tools and must not delegate source prompts.
|
|
121
179
|
if (limits.subagentMode === "orchestration") {
|
|
122
180
|
if (!firstRun)
|
|
123
|
-
ctx.ui.notify(
|
|
181
|
+
ctx.ui.notify(
|
|
182
|
+
"Agent import requires Opportunistic mode. Change Subagent Mode in /agents settings.",
|
|
183
|
+
"info",
|
|
184
|
+
);
|
|
124
185
|
return;
|
|
125
186
|
}
|
|
126
187
|
if (importInProgress) return;
|
|
@@ -140,12 +201,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
140
201
|
if (!manager) throw new Error("Subagent threads are not initialized; start a Pi session first");
|
|
141
202
|
return manager;
|
|
142
203
|
};
|
|
143
|
-
const widgetThreads = () =>
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
204
|
+
const widgetThreads = () =>
|
|
205
|
+
requireManager()
|
|
206
|
+
.list()
|
|
207
|
+
.filter((thread) => {
|
|
208
|
+
// Resuming a retained session makes it visible for this task, even after it settles again.
|
|
209
|
+
if (thread.state === "starting" || thread.state === "running")
|
|
210
|
+
hiddenWidgetThreads.delete(thread.path);
|
|
211
|
+
return !hiddenWidgetThreads.has(thread.path);
|
|
212
|
+
});
|
|
149
213
|
const requireContext = () => {
|
|
150
214
|
if (!context) throw new Error("No active Pi session");
|
|
151
215
|
return context;
|
|
@@ -184,47 +248,111 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
184
248
|
},
|
|
185
249
|
{ triggerTurn: false },
|
|
186
250
|
);
|
|
251
|
+
if (notification.trigger === true) wakeRequested = true;
|
|
252
|
+
};
|
|
253
|
+
/** Wake an idle main agent once for all pending async events (coalesced, after the settle boundary). */
|
|
254
|
+
const scheduleWake = (ctx: ExtensionContext) => {
|
|
255
|
+
if (!wakeRequested || wakeTimer !== undefined || limits.subagentMode === "off") return;
|
|
256
|
+
const currentGeneration = generation;
|
|
257
|
+
wakeTimer = setTimeout(() => {
|
|
258
|
+
wakeTimer = undefined;
|
|
259
|
+
if (
|
|
260
|
+
currentGeneration !== generation ||
|
|
261
|
+
context?.sessionManager !== ctx.sessionManager ||
|
|
262
|
+
limits.subagentMode === "off" ||
|
|
263
|
+
suspendingSummaries ||
|
|
264
|
+
!wakeRequested
|
|
265
|
+
)
|
|
266
|
+
return;
|
|
267
|
+
if (ctx.isIdle() === false) return; // agent_settled reschedules
|
|
268
|
+
wakeRequested = false;
|
|
269
|
+
try {
|
|
270
|
+
pi.sendMessage(
|
|
271
|
+
{
|
|
272
|
+
customType: ROOT_WAKE_MESSAGE,
|
|
273
|
+
content:
|
|
274
|
+
"Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
|
|
275
|
+
"React: collect results with agent_output, and for a timeout event decide to wait, steer, stop or re-arm with agent_steer timeoutMs.",
|
|
276
|
+
display: false,
|
|
277
|
+
details: {},
|
|
278
|
+
},
|
|
279
|
+
{ triggerTurn: true },
|
|
280
|
+
);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
warnDelivery(error);
|
|
283
|
+
}
|
|
284
|
+
}, 0);
|
|
187
285
|
};
|
|
188
286
|
const pendingSummaries = (ctx: ExtensionContext) => {
|
|
189
287
|
const entries = ctx.sessionManager.getBranch();
|
|
190
|
-
const summarized = new Set(
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
288
|
+
const summarized = new Set(
|
|
289
|
+
entries.flatMap((entry) => {
|
|
290
|
+
if (entry.type !== "custom_message" || entry.customType !== ROOT_SUMMARY_MESSAGE) return [];
|
|
291
|
+
const ids = (entry.details as { mailboxIds?: unknown } | undefined)?.mailboxIds;
|
|
292
|
+
return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
|
|
293
|
+
}),
|
|
294
|
+
);
|
|
195
295
|
return entries.flatMap((entry) => {
|
|
196
296
|
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
197
297
|
const notification = entry.data as RootNotification | undefined;
|
|
198
298
|
return notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
|
|
199
|
-
notification.finalRecap === true &&
|
|
299
|
+
notification.finalRecap === true &&
|
|
300
|
+
typeof notification.content === "string" &&
|
|
200
301
|
typeof notification.details?.mailboxId === "string" &&
|
|
201
|
-
!summarized.has(notification.details.mailboxId)
|
|
302
|
+
!summarized.has(notification.details.mailboxId)
|
|
303
|
+
? [notification]
|
|
304
|
+
: [];
|
|
202
305
|
});
|
|
203
306
|
};
|
|
204
307
|
const scheduleSummary = (ctx: ExtensionContext) => {
|
|
205
|
-
if (
|
|
206
|
-
|
|
308
|
+
if (
|
|
309
|
+
!limits.finalRecap ||
|
|
310
|
+
limits.subagentMode === "off" ||
|
|
311
|
+
summaryRunning ||
|
|
312
|
+
suspendingSummaries ||
|
|
313
|
+
summaryTimer !== undefined ||
|
|
314
|
+
ctx.isIdle() === false ||
|
|
315
|
+
(manager?.outstandingAsync() ?? 0) > 0 ||
|
|
316
|
+
!pendingSummaries(ctx).length
|
|
317
|
+
)
|
|
318
|
+
return;
|
|
207
319
|
const currentGeneration = generation;
|
|
208
320
|
// Coalesce siblings finishing together and leave the settlement boundary before
|
|
209
321
|
// starting a new turn. Recheck settings/session/idle state after the deferral.
|
|
210
322
|
summaryTimer = setTimeout(() => {
|
|
211
323
|
summaryTimer = undefined;
|
|
212
|
-
if (
|
|
213
|
-
|
|
324
|
+
if (
|
|
325
|
+
currentGeneration !== generation ||
|
|
326
|
+
context?.sessionManager !== ctx.sessionManager ||
|
|
327
|
+
!limits.finalRecap ||
|
|
328
|
+
limits.subagentMode === "off" ||
|
|
329
|
+
suspendingSummaries ||
|
|
330
|
+
ctx.isIdle() === false ||
|
|
331
|
+
(manager?.outstandingAsync() ?? 0) > 0
|
|
332
|
+
)
|
|
333
|
+
return;
|
|
214
334
|
const notifications = pendingSummaries(ctx);
|
|
215
335
|
if (!notifications.length) return;
|
|
216
336
|
summaryRunning = true;
|
|
217
337
|
try {
|
|
218
|
-
pi.sendMessage(
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
338
|
+
pi.sendMessage(
|
|
339
|
+
{
|
|
340
|
+
customType: ROOT_SUMMARY_MESSAGE,
|
|
341
|
+
content:
|
|
342
|
+
"Summarize the newly finished asynchronous subagent results for the user. " +
|
|
343
|
+
"Their results are in the preceding subagent notifications; use agent_output if more detail is needed. " +
|
|
344
|
+
"Give a concise main-thread answer covering results and any failures. " +
|
|
345
|
+
"Do not spawn or resume agents solely to summarize.\nAgents: " +
|
|
346
|
+
[...new Set(notifications.map((notification) => notification.details.path))].join(
|
|
347
|
+
", ",
|
|
348
|
+
),
|
|
349
|
+
display: false,
|
|
350
|
+
details: {
|
|
351
|
+
mailboxIds: notifications.map((notification) => notification.details.mailboxId),
|
|
352
|
+
},
|
|
353
|
+
},
|
|
354
|
+
{ triggerTurn: true },
|
|
355
|
+
);
|
|
228
356
|
} catch (error) {
|
|
229
357
|
summaryRunning = false;
|
|
230
358
|
warnDelivery(error);
|
|
@@ -254,6 +382,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
254
382
|
delivered.add(notification.details.mailboxId);
|
|
255
383
|
}
|
|
256
384
|
}
|
|
385
|
+
scheduleWake(ctx);
|
|
257
386
|
scheduleSummary(ctx);
|
|
258
387
|
};
|
|
259
388
|
pi.on("agent_settled", async (_event, ctx) => {
|
|
@@ -265,22 +394,39 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
265
394
|
const delivery = (event: ThreadEvent) => {
|
|
266
395
|
if (event.kind === "change" || event.kind === "metrics") return;
|
|
267
396
|
const thread = event.thread;
|
|
397
|
+
const fmtMs = (ms: number) => `${Math.round(ms / 1000)}s`;
|
|
398
|
+
const elapsed =
|
|
399
|
+
(thread.elapsedMs ?? 0) + (thread.startedAt ? Date.now() - thread.startedAt : 0);
|
|
268
400
|
const message =
|
|
269
401
|
event.kind === "update"
|
|
270
402
|
? `Progress from ${thread.path}: ${event.message}`
|
|
271
|
-
:
|
|
272
|
-
? `Agent ${thread.path}
|
|
273
|
-
|
|
403
|
+
: event.kind === "timeout"
|
|
404
|
+
? `Agent ${thread.path} hit its ${fmtMs(event.timeoutMs)} spawn timeout and is STILL RUNNING (not stopped). ` +
|
|
405
|
+
`State: ${thread.state}; status: ${thread.status}; elapsed: ${fmtMs(elapsed)}; ` +
|
|
406
|
+
`tokens: ${thread.inputTokens ?? 0} in / ${thread.outputTokens ?? 0} out.\n` +
|
|
407
|
+
`Recent output:\n${event.recentOutput || "(none yet)"}\n` +
|
|
408
|
+
"Decide: agent_steer with timeoutMs only (no message) to be notified again later without disturbing it, agent_wait for it, agent_steer to redirect, agent_stop to cancel, or let it continue."
|
|
409
|
+
: thread.state === "completed"
|
|
410
|
+
? `Agent ${thread.path} completed. Final answer:\n${thread.output?.slice(0, 16000) ?? "(no text)"}${(thread.output?.length ?? 0) > 16000 ? "\n[Output truncated; use agent_output for more.]" : ""}`
|
|
411
|
+
: `Agent ${thread.path} is ${thread.state}: ${thread.status}. ${thread.state === "paused" ? "No answer handback; send input to resume the same session." : "Session retained for further input."}`;
|
|
274
412
|
try {
|
|
275
413
|
if (event.recipient === "/root") {
|
|
414
|
+
const recap =
|
|
415
|
+
limits.finalRecap &&
|
|
416
|
+
!suspendingSummaries &&
|
|
417
|
+
event.kind === "settled" &&
|
|
418
|
+
event.async &&
|
|
419
|
+
["completed", "failed", "stopped"].includes(thread.state);
|
|
276
420
|
const notification: RootNotification = {
|
|
277
421
|
rootSessionId: requireContext().sessionManager.getSessionId(),
|
|
278
422
|
content: message,
|
|
279
423
|
// Foreground results already handled by a busy main thread do not need
|
|
280
424
|
// another turn. Completions during a summary do need a follow-up summary.
|
|
281
|
-
finalRecap:
|
|
282
|
-
|
|
283
|
-
|
|
425
|
+
finalRecap: recap,
|
|
426
|
+
// Recap mode defers the turn until every outstanding async agent has reported.
|
|
427
|
+
trigger:
|
|
428
|
+
!suspendingSummaries &&
|
|
429
|
+
(event.kind === "timeout" || (event.kind === "settled" && event.async && !recap)),
|
|
284
430
|
details: {
|
|
285
431
|
mailboxId: randomUUID(),
|
|
286
432
|
path: thread.path,
|
|
@@ -335,8 +481,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
335
481
|
const refreshWidget = (ctx: ExtensionContext) => {
|
|
336
482
|
if (limits.subagentMode === "off") {
|
|
337
483
|
if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
|
|
338
|
-
} else
|
|
339
|
-
|
|
484
|
+
} else
|
|
485
|
+
updateWidget(
|
|
486
|
+
ctx,
|
|
487
|
+
widgetThreads(),
|
|
488
|
+
widgetCollapsed ? "minimal" : limits.widgetMode,
|
|
489
|
+
limits.nerdFontIcons,
|
|
490
|
+
rootTurnEnded,
|
|
491
|
+
limits.loaderStyle,
|
|
492
|
+
);
|
|
340
493
|
};
|
|
341
494
|
pi.on("agent_start", async (_event, ctx) => {
|
|
342
495
|
// A new task must not resurrect the previous task's settled agents. Automatic
|
|
@@ -374,7 +527,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
374
527
|
};
|
|
375
528
|
});
|
|
376
529
|
|
|
377
|
-
const attachSession = async (
|
|
530
|
+
const attachSession = async (
|
|
531
|
+
ctx: ExtensionContext,
|
|
532
|
+
installEditor = false,
|
|
533
|
+
seedHistory = true,
|
|
534
|
+
) => {
|
|
378
535
|
cancelSummary();
|
|
379
536
|
const token = ++generation;
|
|
380
537
|
closeNavigation(installEditor);
|
|
@@ -383,6 +540,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
383
540
|
if (manager) await manager.shutdown();
|
|
384
541
|
inheritedTools.reset();
|
|
385
542
|
context = ctx;
|
|
543
|
+
costLedger = new CostLedger();
|
|
544
|
+
costLedger.restore(ctx.sessionManager.getEntries());
|
|
545
|
+
costFooter.reset(ctx);
|
|
386
546
|
rootTurnEnded = false;
|
|
387
547
|
if (installEditor) {
|
|
388
548
|
widgetCollapsed = false;
|
|
@@ -411,6 +571,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
411
571
|
if (token !== generation) return;
|
|
412
572
|
refreshWidget(requireContext());
|
|
413
573
|
if (event.kind !== "metrics") persist();
|
|
574
|
+
if (event.kind === "settled") rollupCost(event.thread);
|
|
414
575
|
delivery(event);
|
|
415
576
|
},
|
|
416
577
|
});
|
|
@@ -438,6 +599,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
438
599
|
ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
|
|
439
600
|
}
|
|
440
601
|
}
|
|
602
|
+
// Recover a persisted settlement whose ledger append was interrupted, including runs paused on reload.
|
|
603
|
+
for (const saved of instance.saved()) rollupCost({ ...saved.view, updatedAt: Date.now() });
|
|
441
604
|
restoreRootMailbox(ctx);
|
|
442
605
|
refreshWidget(ctx);
|
|
443
606
|
const diagnostics = [...store.diagnostics, ...settingsDiagnostics];
|
|
@@ -470,6 +633,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
470
633
|
pi.on("session_before_fork", stopWorkingThreads);
|
|
471
634
|
pi.on("session_shutdown", async () => {
|
|
472
635
|
cancelSummary();
|
|
636
|
+
costFooter.clear();
|
|
473
637
|
generation++;
|
|
474
638
|
closeNavigation(true);
|
|
475
639
|
await manager?.shutdown();
|
|
@@ -548,10 +712,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
548
712
|
if (!canOpenDialog(ctx)) return;
|
|
549
713
|
closeNavigation();
|
|
550
714
|
const warning = `${candidates.length} completed agent${candidates.length === 1 ? "" : "s"} will be reaped.\nYou will not be able to resume them anymore.`;
|
|
551
|
-
const choice = await dialogMenu(
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
715
|
+
const choice = await dialogMenu(
|
|
716
|
+
ctx,
|
|
717
|
+
"Reap completed agents?",
|
|
718
|
+
[
|
|
719
|
+
{ id: "confirm", label: "Confirm", help: warning },
|
|
720
|
+
{ id: "cancel", label: "Cancel", help: warning },
|
|
721
|
+
],
|
|
722
|
+
{ selectedId: "cancel" },
|
|
723
|
+
);
|
|
555
724
|
if (choice !== "confirm" || manager !== current) return;
|
|
556
725
|
const reaped = current.reap(candidates);
|
|
557
726
|
persist();
|
|
@@ -563,7 +732,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
563
732
|
"info",
|
|
564
733
|
);
|
|
565
734
|
} else if (command === "tree") {
|
|
566
|
-
await navigation.open(
|
|
735
|
+
await navigation.open(
|
|
736
|
+
ctx,
|
|
737
|
+
requireManager().scope("/root"),
|
|
738
|
+
rest.join(" ") || undefined,
|
|
739
|
+
limits.nerdFontIcons,
|
|
740
|
+
limits.loaderStyle,
|
|
741
|
+
);
|
|
567
742
|
} else
|
|
568
743
|
ctx.ui.notify(
|
|
569
744
|
"Usage: /agents [tree [path] | settings | types | import | reload | reap]",
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ThreadView } from "../types.ts";
|
|
3
|
+
|
|
4
|
+
export const COST_ENTRY = "pi-subagent:cost:v1";
|
|
5
|
+
export interface CostRecord {
|
|
6
|
+
threadId: string;
|
|
7
|
+
totalUsd: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Whole-session accounting, like Pi's footer (not branch-local context). */
|
|
11
|
+
export class CostLedger {
|
|
12
|
+
private totals = new Map<string, number>();
|
|
13
|
+
|
|
14
|
+
restore(entries: readonly SessionEntry[]): void {
|
|
15
|
+
this.totals.clear();
|
|
16
|
+
for (const entry of entries) {
|
|
17
|
+
if (entry.type !== "custom" || entry.customType !== COST_ENTRY) continue;
|
|
18
|
+
const data = entry.data as Partial<CostRecord> | undefined;
|
|
19
|
+
if (
|
|
20
|
+
!data ||
|
|
21
|
+
typeof data.threadId !== "string" ||
|
|
22
|
+
!data.threadId ||
|
|
23
|
+
typeof data.totalUsd !== "number" ||
|
|
24
|
+
!Number.isFinite(data.totalUsd) ||
|
|
25
|
+
data.totalUsd < 0
|
|
26
|
+
)
|
|
27
|
+
continue;
|
|
28
|
+
// High-water marks make duplicate records and branch rewinds harmless.
|
|
29
|
+
this.totals.set(data.threadId, Math.max(this.totals.get(data.threadId) ?? 0, data.totalUsd));
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
get totalUsd(): number {
|
|
34
|
+
return [...this.totals.values()].reduce((sum, cost) => sum + cost, 0);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Only inactive agents' authoritative own usage may enter the rollup. */
|
|
38
|
+
settle(thread: ThreadView, append: (record: CostRecord) => void): number {
|
|
39
|
+
if (
|
|
40
|
+
thread.path === "/root" ||
|
|
41
|
+
thread.state === "starting" ||
|
|
42
|
+
thread.state === "running" ||
|
|
43
|
+
!thread.costId ||
|
|
44
|
+
thread.costUsd === undefined ||
|
|
45
|
+
!Number.isFinite(thread.costUsd) ||
|
|
46
|
+
thread.costUsd <= (this.totals.get(thread.costId) ?? 0)
|
|
47
|
+
)
|
|
48
|
+
return 0;
|
|
49
|
+
const previous = this.totals.get(thread.costId) ?? 0;
|
|
50
|
+
const record = { threadId: thread.costId, totalUsd: thread.costUsd };
|
|
51
|
+
// Never advance the cursor on a failed persistence write.
|
|
52
|
+
append(record);
|
|
53
|
+
this.totals.set(record.threadId, record.totalUsd);
|
|
54
|
+
return record.totalUsd - previous;
|
|
55
|
+
}
|
|
56
|
+
}
|