pi-subagent-manager 0.17.0 → 0.19.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 +13 -0
- package/package.json +1 -1
- package/src/index.ts +203 -73
- package/src/orch/cost-ledger.ts +56 -0
- package/src/orch/manager.ts +52 -9
- package/src/orch/prompt.ts +1 -1
- package/src/orch/runtime.ts +22 -2
- package/src/orch/tools.ts +15 -3
- package/src/prefs/settings.ts +12 -1
- package/src/types.ts +21 -1
- package/src/ui/cost-footer.ts +213 -0
- package/src/ui/settings-ui.ts +31 -0
- package/src/ui/status-ui.ts +102 -36
- 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
|
+
- Choose **[labs] Cost display** in `/agents settings`: **pi-footer status key** (default), **pi-footer event**, or **Pi status only**. The stable ID/key is **`subagent_cost`**.
|
|
81
|
+
- **`npm:pi-footer`:** with the default status-key mode, add **Extension Status** through `/footer` and select **`subagent_cost`**. Event mode instead requires a **Pi Event Value** widget with **Widget ID** entered manually and **Raw value only** enabled; event IDs are not listed in the status selector.
|
|
82
|
+
- Values publish at session start and immediately on subagent startup, including `$0.0000`, then after settlement/settings changes. Status modes leave your footer untouched; event mode retains the combined-cost fallback when no extension provides `/footer`. See [Cost display settings](docs/settings.md#labs-cost-display-costdisplay).
|
|
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
|
@@ -17,6 +17,7 @@ All keys are optional. Defaults:
|
|
|
17
17
|
"widgetMode": "full",
|
|
18
18
|
"nerdFontIcons": false,
|
|
19
19
|
"loaderStyle": "circle",
|
|
20
|
+
"costDisplay": "pi-footer-status",
|
|
20
21
|
"finalRecap": false,
|
|
21
22
|
"modelSelection": "pick-first-scoped",
|
|
22
23
|
"toolFiltering": "allowed",
|
|
@@ -70,6 +71,18 @@ Choose **Circle** (default), **Braille**, or **Hourglass** in `/agents` settings
|
|
|
70
71
|
|
|
71
72
|
The Labs preview shows every family's running animation frames and completed, paused, failed, and stopped icons, so you can compare all states before choosing. Starting uses the running animation. State indicators always precede the unchanged role icon; the selected family also applies to the minimal widget's counts. In non-animated output, active agents use the family's first frame.
|
|
72
73
|
|
|
74
|
+
## [labs] Cost display (`costDisplay`)
|
|
75
|
+
|
|
76
|
+
Choose the cost output in `/agents settings` and save. The stable ID/key is **`subagent_cost`**.
|
|
77
|
+
|
|
78
|
+
| Value | Output |
|
|
79
|
+
| --- | --- |
|
|
80
|
+
| `pi-footer-status` (default) | Publishes `$0.0000` via Pi’s `setStatus` API. In `/footer`, add **Extension Status** and pick **`subagent_cost`** from the status-key selector. |
|
|
81
|
+
| `pi-footer-event` | Emits `pi-footer:update-widget` with `widgetId: "subagent_cost"`. Add **Pi Event Value**, enter **Widget ID** manually, and enable **Raw value only**. Event IDs do not appear in the status selector. Without an extension providing `/footer`, preserves the combined-cost fallback footer. |
|
|
82
|
+
| `pi-status` | Sets Pi’s status to `Total: $0.0000` — main session + all settled subagents; no pi-footer events or custom footer. |
|
|
83
|
+
|
|
84
|
+
Both status modes use the same public Pi status API: third-party footers may also display Pi status-only output. These modes never replace your footer. The pi-footer modes show the **settled subagent-only** USD subtotal; Pi status shows **main session + all settled subagents**. In all modes, running costs settle on completion, pause, stop, or failure. It publishes on session start/reload, immediately when a subagent starts (even at zero), and after settlement/settings changes. Switching modes clears the previous output; shutdown clears the published value. Nerd Font icons apply when enabled.
|
|
85
|
+
|
|
73
86
|
## [labs] Final Recap (`finalRecap`)
|
|
74
87
|
|
|
75
88
|
**[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.
|
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,7 +19,9 @@ 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";
|
|
@@ -39,6 +45,18 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
39
45
|
includeProject: false,
|
|
40
46
|
});
|
|
41
47
|
let manager: ThreadManager | undefined;
|
|
48
|
+
let costLedger = new CostLedger();
|
|
49
|
+
const costFooter = new CostFooterController(
|
|
50
|
+
pi,
|
|
51
|
+
() => costLedger.totalUsd,
|
|
52
|
+
() => limits.nerdFontIcons,
|
|
53
|
+
() => limits.costDisplay,
|
|
54
|
+
);
|
|
55
|
+
const refreshCostFooter = (ctx: ExtensionContext) => costFooter.refresh(ctx);
|
|
56
|
+
const rollupCost = (thread: ThreadView) => {
|
|
57
|
+
costLedger.settle(thread, (record) => pi.appendEntry(COST_ENTRY, record));
|
|
58
|
+
if (context) refreshCostFooter(context);
|
|
59
|
+
};
|
|
42
60
|
let limits = loadManagerSettings({
|
|
43
61
|
cwd: process.cwd(),
|
|
44
62
|
agentDir: getAgentDir(),
|
|
@@ -51,6 +69,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
51
69
|
includeProject: ctx.isProjectTrusted(),
|
|
52
70
|
});
|
|
53
71
|
limits = loaded.settings;
|
|
72
|
+
refreshCostFooter(ctx);
|
|
54
73
|
return loaded.diagnostics;
|
|
55
74
|
};
|
|
56
75
|
let generation = 0;
|
|
@@ -92,32 +111,61 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
92
111
|
if (existingFactory && existingFactory !== navigationEditorFactory) return;
|
|
93
112
|
// The host only transfers raw text, not cursor/undo/expanded-paste state.
|
|
94
113
|
if (ctx.ui.getEditorText?.()) return;
|
|
95
|
-
const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
114
|
+
const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap(
|
|
115
|
+
(message) => {
|
|
116
|
+
if (message.role !== "user") return [];
|
|
117
|
+
const content = message.content;
|
|
118
|
+
return [
|
|
119
|
+
typeof content === "string"
|
|
120
|
+
? content
|
|
121
|
+
: content
|
|
122
|
+
.filter((block) => block.type === "text")
|
|
123
|
+
.map((block) => block.text)
|
|
124
|
+
.join(""),
|
|
125
|
+
];
|
|
126
|
+
},
|
|
127
|
+
);
|
|
101
128
|
navigationEditorFactory = (tui, theme, keys) => {
|
|
102
129
|
const editor = new AgentNavigationEditor(tui, theme, keys, {
|
|
103
130
|
// Initial startup hydrates after session_start; replacement editors do not.
|
|
104
131
|
initialHistory: seedHistory ? history : undefined,
|
|
105
132
|
generation: () => navigationGeneration,
|
|
106
|
-
canOpen: () =>
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
133
|
+
canOpen: () =>
|
|
134
|
+
manager !== undefined &&
|
|
135
|
+
context?.mode === "tui" &&
|
|
136
|
+
limits.subagentMode !== "off" &&
|
|
137
|
+
!navigation.isOpen &&
|
|
138
|
+
manager
|
|
139
|
+
.list()
|
|
140
|
+
.some(
|
|
141
|
+
(thread) =>
|
|
142
|
+
thread.path !== "/root" &&
|
|
143
|
+
(thread.state === "starting" || thread.state === "running"),
|
|
144
|
+
),
|
|
145
|
+
openTree: () =>
|
|
146
|
+
manager && context
|
|
147
|
+
? navigation.open(
|
|
148
|
+
context,
|
|
149
|
+
manager.scope("/root"),
|
|
150
|
+
undefined,
|
|
151
|
+
limits.nerdFontIcons,
|
|
152
|
+
limits.loaderStyle,
|
|
153
|
+
)
|
|
154
|
+
: undefined,
|
|
155
|
+
canCollapse: () =>
|
|
156
|
+
manager !== undefined &&
|
|
157
|
+
context?.mode === "tui" &&
|
|
158
|
+
limits.subagentMode !== "off" &&
|
|
159
|
+
!navigation.isOpen &&
|
|
160
|
+
!widgetCollapsed &&
|
|
161
|
+
limits.widgetMode === "full" &&
|
|
162
|
+
widgetThreads().some((thread) => thread.path !== "/root"),
|
|
115
163
|
collapseWidget: () => {
|
|
116
164
|
widgetCollapsed = true;
|
|
117
165
|
if (context) refreshWidget(context);
|
|
118
166
|
},
|
|
119
|
-
onError: (error) =>
|
|
120
|
-
error instanceof Error ? error.message : String(error), "error"),
|
|
167
|
+
onError: (error) =>
|
|
168
|
+
context?.ui.notify(error instanceof Error ? error.message : String(error), "error"),
|
|
121
169
|
});
|
|
122
170
|
navigationEditor = editor;
|
|
123
171
|
return editor;
|
|
@@ -131,7 +179,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
131
179
|
// Migration requires the root's file tools and must not delegate source prompts.
|
|
132
180
|
if (limits.subagentMode === "orchestration") {
|
|
133
181
|
if (!firstRun)
|
|
134
|
-
ctx.ui.notify(
|
|
182
|
+
ctx.ui.notify(
|
|
183
|
+
"Agent import requires Opportunistic mode. Change Subagent Mode in /agents settings.",
|
|
184
|
+
"info",
|
|
185
|
+
);
|
|
135
186
|
return;
|
|
136
187
|
}
|
|
137
188
|
if (importInProgress) return;
|
|
@@ -151,12 +202,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
151
202
|
if (!manager) throw new Error("Subagent threads are not initialized; start a Pi session first");
|
|
152
203
|
return manager;
|
|
153
204
|
};
|
|
154
|
-
const widgetThreads = () =>
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
205
|
+
const widgetThreads = () =>
|
|
206
|
+
requireManager()
|
|
207
|
+
.list()
|
|
208
|
+
.filter((thread) => {
|
|
209
|
+
// Resuming a retained session makes it visible for this task, even after it settles again.
|
|
210
|
+
if (thread.state === "starting" || thread.state === "running")
|
|
211
|
+
hiddenWidgetThreads.delete(thread.path);
|
|
212
|
+
return !hiddenWidgetThreads.has(thread.path);
|
|
213
|
+
});
|
|
160
214
|
const requireContext = () => {
|
|
161
215
|
if (!context) throw new Error("No active Pi session");
|
|
162
216
|
return context;
|
|
@@ -203,18 +257,28 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
203
257
|
const currentGeneration = generation;
|
|
204
258
|
wakeTimer = setTimeout(() => {
|
|
205
259
|
wakeTimer = undefined;
|
|
206
|
-
if (
|
|
207
|
-
|
|
260
|
+
if (
|
|
261
|
+
currentGeneration !== generation ||
|
|
262
|
+
context?.sessionManager !== ctx.sessionManager ||
|
|
263
|
+
limits.subagentMode === "off" ||
|
|
264
|
+
suspendingSummaries ||
|
|
265
|
+
!wakeRequested
|
|
266
|
+
)
|
|
267
|
+
return;
|
|
208
268
|
if (ctx.isIdle() === false) return; // agent_settled reschedules
|
|
209
269
|
wakeRequested = false;
|
|
210
270
|
try {
|
|
211
|
-
pi.sendMessage(
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
271
|
+
pi.sendMessage(
|
|
272
|
+
{
|
|
273
|
+
customType: ROOT_WAKE_MESSAGE,
|
|
274
|
+
content:
|
|
275
|
+
"Asynchronous subagent event(s) arrived (see the preceding subagent notifications). " +
|
|
276
|
+
"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).",
|
|
277
|
+
display: false,
|
|
278
|
+
details: {},
|
|
279
|
+
},
|
|
280
|
+
{ triggerTurn: true },
|
|
281
|
+
);
|
|
218
282
|
} catch (error) {
|
|
219
283
|
warnDelivery(error);
|
|
220
284
|
}
|
|
@@ -222,45 +286,74 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
222
286
|
};
|
|
223
287
|
const pendingSummaries = (ctx: ExtensionContext) => {
|
|
224
288
|
const entries = ctx.sessionManager.getBranch();
|
|
225
|
-
const summarized = new Set(
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
289
|
+
const summarized = new Set(
|
|
290
|
+
entries.flatMap((entry) => {
|
|
291
|
+
if (entry.type !== "custom_message" || entry.customType !== ROOT_SUMMARY_MESSAGE) return [];
|
|
292
|
+
const ids = (entry.details as { mailboxIds?: unknown } | undefined)?.mailboxIds;
|
|
293
|
+
return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
|
|
294
|
+
}),
|
|
295
|
+
);
|
|
230
296
|
return entries.flatMap((entry) => {
|
|
231
297
|
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
232
298
|
const notification = entry.data as RootNotification | undefined;
|
|
233
299
|
return notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
|
|
234
|
-
notification.finalRecap === true &&
|
|
300
|
+
notification.finalRecap === true &&
|
|
301
|
+
typeof notification.content === "string" &&
|
|
235
302
|
typeof notification.details?.mailboxId === "string" &&
|
|
236
|
-
!summarized.has(notification.details.mailboxId)
|
|
303
|
+
!summarized.has(notification.details.mailboxId)
|
|
304
|
+
? [notification]
|
|
305
|
+
: [];
|
|
237
306
|
});
|
|
238
307
|
};
|
|
239
308
|
const scheduleSummary = (ctx: ExtensionContext) => {
|
|
240
|
-
if (
|
|
241
|
-
|
|
309
|
+
if (
|
|
310
|
+
!limits.finalRecap ||
|
|
311
|
+
limits.subagentMode === "off" ||
|
|
312
|
+
summaryRunning ||
|
|
313
|
+
suspendingSummaries ||
|
|
314
|
+
summaryTimer !== undefined ||
|
|
315
|
+
ctx.isIdle() === false ||
|
|
316
|
+
(manager?.outstandingAsync() ?? 0) > 0 ||
|
|
317
|
+
!pendingSummaries(ctx).length
|
|
318
|
+
)
|
|
319
|
+
return;
|
|
242
320
|
const currentGeneration = generation;
|
|
243
321
|
// Coalesce siblings finishing together and leave the settlement boundary before
|
|
244
322
|
// starting a new turn. Recheck settings/session/idle state after the deferral.
|
|
245
323
|
summaryTimer = setTimeout(() => {
|
|
246
324
|
summaryTimer = undefined;
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
325
|
+
if (
|
|
326
|
+
currentGeneration !== generation ||
|
|
327
|
+
context?.sessionManager !== ctx.sessionManager ||
|
|
328
|
+
!limits.finalRecap ||
|
|
329
|
+
limits.subagentMode === "off" ||
|
|
330
|
+
suspendingSummaries ||
|
|
331
|
+
ctx.isIdle() === false ||
|
|
332
|
+
(manager?.outstandingAsync() ?? 0) > 0
|
|
333
|
+
)
|
|
334
|
+
return;
|
|
250
335
|
const notifications = pendingSummaries(ctx);
|
|
251
336
|
if (!notifications.length) return;
|
|
252
337
|
summaryRunning = true;
|
|
253
338
|
try {
|
|
254
|
-
pi.sendMessage(
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
339
|
+
pi.sendMessage(
|
|
340
|
+
{
|
|
341
|
+
customType: ROOT_SUMMARY_MESSAGE,
|
|
342
|
+
content:
|
|
343
|
+
"Summarize the newly finished asynchronous subagent results for the user. " +
|
|
344
|
+
"Their results are in the preceding subagent notifications; use agent_output if more detail is needed. " +
|
|
345
|
+
"Give a concise main-thread answer covering results and any failures. " +
|
|
346
|
+
"Do not spawn or resume agents solely to summarize.\nAgents: " +
|
|
347
|
+
[...new Set(notifications.map((notification) => notification.details.path))].join(
|
|
348
|
+
", ",
|
|
349
|
+
),
|
|
350
|
+
display: false,
|
|
351
|
+
details: {
|
|
352
|
+
mailboxIds: notifications.map((notification) => notification.details.mailboxId),
|
|
353
|
+
},
|
|
354
|
+
},
|
|
355
|
+
{ triggerTurn: true },
|
|
356
|
+
);
|
|
264
357
|
} catch (error) {
|
|
265
358
|
summaryRunning = false;
|
|
266
359
|
warnDelivery(error);
|
|
@@ -303,7 +396,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
303
396
|
if (event.kind === "change" || event.kind === "metrics") return;
|
|
304
397
|
const thread = event.thread;
|
|
305
398
|
const fmtMs = (ms: number) => `${Math.round(ms / 1000)}s`;
|
|
306
|
-
const elapsed =
|
|
399
|
+
const elapsed =
|
|
400
|
+
(thread.elapsedMs ?? 0) + (thread.startedAt ? Date.now() - thread.startedAt : 0);
|
|
307
401
|
const message =
|
|
308
402
|
event.kind === "update"
|
|
309
403
|
? `Progress from ${thread.path}: ${event.message}`
|
|
@@ -313,13 +407,17 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
313
407
|
`tokens: ${thread.inputTokens ?? 0} in / ${thread.outputTokens ?? 0} out.\n` +
|
|
314
408
|
`Recent output:\n${event.recentOutput || "(none yet)"}\n` +
|
|
315
409
|
"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."
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
410
|
+
: thread.state === "completed"
|
|
411
|
+
? `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.]" : ""}`
|
|
412
|
+
: `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."}`;
|
|
319
413
|
try {
|
|
320
414
|
if (event.recipient === "/root") {
|
|
321
|
-
const recap =
|
|
322
|
-
|
|
415
|
+
const recap =
|
|
416
|
+
limits.finalRecap &&
|
|
417
|
+
!suspendingSummaries &&
|
|
418
|
+
event.kind === "settled" &&
|
|
419
|
+
event.async &&
|
|
420
|
+
["completed", "failed", "stopped"].includes(thread.state);
|
|
323
421
|
const notification: RootNotification = {
|
|
324
422
|
rootSessionId: requireContext().sessionManager.getSessionId(),
|
|
325
423
|
content: message,
|
|
@@ -327,8 +425,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
327
425
|
// another turn. Completions during a summary do need a follow-up summary.
|
|
328
426
|
finalRecap: recap,
|
|
329
427
|
// Recap mode defers the turn until every outstanding async agent has reported.
|
|
330
|
-
trigger:
|
|
331
|
-
|
|
428
|
+
trigger:
|
|
429
|
+
!suspendingSummaries &&
|
|
430
|
+
(event.kind === "timeout" || (event.kind === "settled" && event.async && !recap)),
|
|
332
431
|
details: {
|
|
333
432
|
mailboxId: randomUUID(),
|
|
334
433
|
path: thread.path,
|
|
@@ -383,8 +482,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
383
482
|
const refreshWidget = (ctx: ExtensionContext) => {
|
|
384
483
|
if (limits.subagentMode === "off") {
|
|
385
484
|
if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
|
|
386
|
-
} else
|
|
387
|
-
|
|
485
|
+
} else
|
|
486
|
+
updateWidget(
|
|
487
|
+
ctx,
|
|
488
|
+
widgetThreads(),
|
|
489
|
+
widgetCollapsed ? "minimal" : limits.widgetMode,
|
|
490
|
+
limits.nerdFontIcons,
|
|
491
|
+
rootTurnEnded,
|
|
492
|
+
limits.loaderStyle,
|
|
493
|
+
);
|
|
388
494
|
};
|
|
389
495
|
pi.on("agent_start", async (_event, ctx) => {
|
|
390
496
|
// A new task must not resurrect the previous task's settled agents. Automatic
|
|
@@ -401,6 +507,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
401
507
|
pi.on("agent_end", async (_event, ctx) => {
|
|
402
508
|
rootTurnEnded = true;
|
|
403
509
|
if (manager) refreshWidget(ctx);
|
|
510
|
+
refreshCostFooter(ctx);
|
|
404
511
|
// A migration can span clarification turns. Reload after each root turn, without converting files.
|
|
405
512
|
if (limits.subagentMode === "off" || !migrationRequested) return;
|
|
406
513
|
store.reload();
|
|
@@ -422,7 +529,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
422
529
|
};
|
|
423
530
|
});
|
|
424
531
|
|
|
425
|
-
const attachSession = async (
|
|
532
|
+
const attachSession = async (
|
|
533
|
+
ctx: ExtensionContext,
|
|
534
|
+
installEditor = false,
|
|
535
|
+
seedHistory = true,
|
|
536
|
+
) => {
|
|
426
537
|
cancelSummary();
|
|
427
538
|
const token = ++generation;
|
|
428
539
|
closeNavigation(installEditor);
|
|
@@ -431,6 +542,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
431
542
|
if (manager) await manager.shutdown();
|
|
432
543
|
inheritedTools.reset();
|
|
433
544
|
context = ctx;
|
|
545
|
+
costLedger = new CostLedger();
|
|
546
|
+
costLedger.restore(ctx.sessionManager.getEntries());
|
|
547
|
+
costFooter.reset(ctx);
|
|
434
548
|
rootTurnEnded = false;
|
|
435
549
|
if (installEditor) {
|
|
436
550
|
widgetCollapsed = false;
|
|
@@ -459,6 +573,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
459
573
|
if (token !== generation) return;
|
|
460
574
|
refreshWidget(requireContext());
|
|
461
575
|
if (event.kind !== "metrics") persist();
|
|
576
|
+
if (event.kind === "settled") rollupCost(event.thread);
|
|
577
|
+
else refreshCostFooter(requireContext());
|
|
462
578
|
delivery(event);
|
|
463
579
|
},
|
|
464
580
|
});
|
|
@@ -486,6 +602,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
486
602
|
ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
|
|
487
603
|
}
|
|
488
604
|
}
|
|
605
|
+
// Recover a persisted settlement whose ledger append was interrupted, including runs paused on reload.
|
|
606
|
+
for (const saved of instance.saved()) rollupCost({ ...saved.view, updatedAt: Date.now() });
|
|
489
607
|
restoreRootMailbox(ctx);
|
|
490
608
|
refreshWidget(ctx);
|
|
491
609
|
const diagnostics = [...store.diagnostics, ...settingsDiagnostics];
|
|
@@ -521,6 +639,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
521
639
|
generation++;
|
|
522
640
|
closeNavigation(true);
|
|
523
641
|
await manager?.shutdown();
|
|
642
|
+
costFooter.clear();
|
|
524
643
|
persist();
|
|
525
644
|
if (context?.hasUI) context.ui.setWidget("pi-subagent", undefined);
|
|
526
645
|
manager = undefined;
|
|
@@ -596,10 +715,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
596
715
|
if (!canOpenDialog(ctx)) return;
|
|
597
716
|
closeNavigation();
|
|
598
717
|
const warning = `${candidates.length} completed agent${candidates.length === 1 ? "" : "s"} will be reaped.\nYou will not be able to resume them anymore.`;
|
|
599
|
-
const choice = await dialogMenu(
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
718
|
+
const choice = await dialogMenu(
|
|
719
|
+
ctx,
|
|
720
|
+
"Reap completed agents?",
|
|
721
|
+
[
|
|
722
|
+
{ id: "confirm", label: "Confirm", help: warning },
|
|
723
|
+
{ id: "cancel", label: "Cancel", help: warning },
|
|
724
|
+
],
|
|
725
|
+
{ selectedId: "cancel" },
|
|
726
|
+
);
|
|
603
727
|
if (choice !== "confirm" || manager !== current) return;
|
|
604
728
|
const reaped = current.reap(candidates);
|
|
605
729
|
persist();
|
|
@@ -611,7 +735,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
611
735
|
"info",
|
|
612
736
|
);
|
|
613
737
|
} else if (command === "tree") {
|
|
614
|
-
await navigation.open(
|
|
738
|
+
await navigation.open(
|
|
739
|
+
ctx,
|
|
740
|
+
requireManager().scope("/root"),
|
|
741
|
+
rest.join(" ") || undefined,
|
|
742
|
+
limits.nerdFontIcons,
|
|
743
|
+
limits.loaderStyle,
|
|
744
|
+
);
|
|
615
745
|
} else
|
|
616
746
|
ctx.ui.notify(
|
|
617
747
|
"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
|
+
}
|