pi-subagent-manager 0.17.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/package.json +1 -1
- package/src/index.ts +200 -73
- package/src/orch/cost-ledger.ts +56 -0
- package/src/orch/manager.ts +52 -9
- package/src/orch/runtime.ts +22 -2
- package/src/types.ts +21 -1
- package/src/ui/cost-footer.ts +187 -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
|
+
- **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/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,17 @@ 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
|
+
);
|
|
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
|
+
};
|
|
42
59
|
let limits = loadManagerSettings({
|
|
43
60
|
cwd: process.cwd(),
|
|
44
61
|
agentDir: getAgentDir(),
|
|
@@ -51,6 +68,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
51
68
|
includeProject: ctx.isProjectTrusted(),
|
|
52
69
|
});
|
|
53
70
|
limits = loaded.settings;
|
|
71
|
+
refreshCostFooter(ctx);
|
|
54
72
|
return loaded.diagnostics;
|
|
55
73
|
};
|
|
56
74
|
let generation = 0;
|
|
@@ -92,32 +110,61 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
92
110
|
if (existingFactory && existingFactory !== navigationEditorFactory) return;
|
|
93
111
|
// The host only transfers raw text, not cursor/undo/expanded-paste state.
|
|
94
112
|
if (ctx.ui.getEditorText?.()) return;
|
|
95
|
-
const history = buildSessionContext(ctx.sessionManager.getBranch()).messages.flatMap(
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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
|
+
);
|
|
101
127
|
navigationEditorFactory = (tui, theme, keys) => {
|
|
102
128
|
const editor = new AgentNavigationEditor(tui, theme, keys, {
|
|
103
129
|
// Initial startup hydrates after session_start; replacement editors do not.
|
|
104
130
|
initialHistory: seedHistory ? history : undefined,
|
|
105
131
|
generation: () => navigationGeneration,
|
|
106
|
-
canOpen: () =>
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
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"),
|
|
115
162
|
collapseWidget: () => {
|
|
116
163
|
widgetCollapsed = true;
|
|
117
164
|
if (context) refreshWidget(context);
|
|
118
165
|
},
|
|
119
|
-
onError: (error) =>
|
|
120
|
-
error instanceof Error ? error.message : String(error), "error"),
|
|
166
|
+
onError: (error) =>
|
|
167
|
+
context?.ui.notify(error instanceof Error ? error.message : String(error), "error"),
|
|
121
168
|
});
|
|
122
169
|
navigationEditor = editor;
|
|
123
170
|
return editor;
|
|
@@ -131,7 +178,10 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
131
178
|
// Migration requires the root's file tools and must not delegate source prompts.
|
|
132
179
|
if (limits.subagentMode === "orchestration") {
|
|
133
180
|
if (!firstRun)
|
|
134
|
-
ctx.ui.notify(
|
|
181
|
+
ctx.ui.notify(
|
|
182
|
+
"Agent import requires Opportunistic mode. Change Subagent Mode in /agents settings.",
|
|
183
|
+
"info",
|
|
184
|
+
);
|
|
135
185
|
return;
|
|
136
186
|
}
|
|
137
187
|
if (importInProgress) return;
|
|
@@ -151,12 +201,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
151
201
|
if (!manager) throw new Error("Subagent threads are not initialized; start a Pi session first");
|
|
152
202
|
return manager;
|
|
153
203
|
};
|
|
154
|
-
const widgetThreads = () =>
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
+
});
|
|
160
213
|
const requireContext = () => {
|
|
161
214
|
if (!context) throw new Error("No active Pi session");
|
|
162
215
|
return context;
|
|
@@ -203,18 +256,28 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
203
256
|
const currentGeneration = generation;
|
|
204
257
|
wakeTimer = setTimeout(() => {
|
|
205
258
|
wakeTimer = undefined;
|
|
206
|
-
if (
|
|
207
|
-
|
|
259
|
+
if (
|
|
260
|
+
currentGeneration !== generation ||
|
|
261
|
+
context?.sessionManager !== ctx.sessionManager ||
|
|
262
|
+
limits.subagentMode === "off" ||
|
|
263
|
+
suspendingSummaries ||
|
|
264
|
+
!wakeRequested
|
|
265
|
+
)
|
|
266
|
+
return;
|
|
208
267
|
if (ctx.isIdle() === false) return; // agent_settled reschedules
|
|
209
268
|
wakeRequested = false;
|
|
210
269
|
try {
|
|
211
|
-
pi.sendMessage(
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
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
|
+
);
|
|
218
281
|
} catch (error) {
|
|
219
282
|
warnDelivery(error);
|
|
220
283
|
}
|
|
@@ -222,45 +285,74 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
222
285
|
};
|
|
223
286
|
const pendingSummaries = (ctx: ExtensionContext) => {
|
|
224
287
|
const entries = ctx.sessionManager.getBranch();
|
|
225
|
-
const summarized = new Set(
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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
|
+
);
|
|
230
295
|
return entries.flatMap((entry) => {
|
|
231
296
|
if (entry.type !== "custom" || entry.customType !== ROOT_MAILBOX_ENTRY) return [];
|
|
232
297
|
const notification = entry.data as RootNotification | undefined;
|
|
233
298
|
return notification?.rootSessionId === ctx.sessionManager.getSessionId() &&
|
|
234
|
-
notification.finalRecap === true &&
|
|
299
|
+
notification.finalRecap === true &&
|
|
300
|
+
typeof notification.content === "string" &&
|
|
235
301
|
typeof notification.details?.mailboxId === "string" &&
|
|
236
|
-
!summarized.has(notification.details.mailboxId)
|
|
302
|
+
!summarized.has(notification.details.mailboxId)
|
|
303
|
+
? [notification]
|
|
304
|
+
: [];
|
|
237
305
|
});
|
|
238
306
|
};
|
|
239
307
|
const scheduleSummary = (ctx: ExtensionContext) => {
|
|
240
|
-
if (
|
|
241
|
-
|
|
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;
|
|
242
319
|
const currentGeneration = generation;
|
|
243
320
|
// Coalesce siblings finishing together and leave the settlement boundary before
|
|
244
321
|
// starting a new turn. Recheck settings/session/idle state after the deferral.
|
|
245
322
|
summaryTimer = setTimeout(() => {
|
|
246
323
|
summaryTimer = undefined;
|
|
247
|
-
if (
|
|
248
|
-
|
|
249
|
-
|
|
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;
|
|
250
334
|
const notifications = pendingSummaries(ctx);
|
|
251
335
|
if (!notifications.length) return;
|
|
252
336
|
summaryRunning = true;
|
|
253
337
|
try {
|
|
254
|
-
pi.sendMessage(
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
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
|
+
);
|
|
264
356
|
} catch (error) {
|
|
265
357
|
summaryRunning = false;
|
|
266
358
|
warnDelivery(error);
|
|
@@ -303,7 +395,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
303
395
|
if (event.kind === "change" || event.kind === "metrics") return;
|
|
304
396
|
const thread = event.thread;
|
|
305
397
|
const fmtMs = (ms: number) => `${Math.round(ms / 1000)}s`;
|
|
306
|
-
const elapsed =
|
|
398
|
+
const elapsed =
|
|
399
|
+
(thread.elapsedMs ?? 0) + (thread.startedAt ? Date.now() - thread.startedAt : 0);
|
|
307
400
|
const message =
|
|
308
401
|
event.kind === "update"
|
|
309
402
|
? `Progress from ${thread.path}: ${event.message}`
|
|
@@ -313,13 +406,17 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
313
406
|
`tokens: ${thread.inputTokens ?? 0} in / ${thread.outputTokens ?? 0} out.\n` +
|
|
314
407
|
`Recent output:\n${event.recentOutput || "(none yet)"}\n` +
|
|
315
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."
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
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."}`;
|
|
319
412
|
try {
|
|
320
413
|
if (event.recipient === "/root") {
|
|
321
|
-
const recap =
|
|
322
|
-
|
|
414
|
+
const recap =
|
|
415
|
+
limits.finalRecap &&
|
|
416
|
+
!suspendingSummaries &&
|
|
417
|
+
event.kind === "settled" &&
|
|
418
|
+
event.async &&
|
|
419
|
+
["completed", "failed", "stopped"].includes(thread.state);
|
|
323
420
|
const notification: RootNotification = {
|
|
324
421
|
rootSessionId: requireContext().sessionManager.getSessionId(),
|
|
325
422
|
content: message,
|
|
@@ -327,8 +424,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
327
424
|
// another turn. Completions during a summary do need a follow-up summary.
|
|
328
425
|
finalRecap: recap,
|
|
329
426
|
// Recap mode defers the turn until every outstanding async agent has reported.
|
|
330
|
-
trigger:
|
|
331
|
-
|
|
427
|
+
trigger:
|
|
428
|
+
!suspendingSummaries &&
|
|
429
|
+
(event.kind === "timeout" || (event.kind === "settled" && event.async && !recap)),
|
|
332
430
|
details: {
|
|
333
431
|
mailboxId: randomUUID(),
|
|
334
432
|
path: thread.path,
|
|
@@ -383,8 +481,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
383
481
|
const refreshWidget = (ctx: ExtensionContext) => {
|
|
384
482
|
if (limits.subagentMode === "off") {
|
|
385
483
|
if (ctx.hasUI) ctx.ui.setWidget("pi-subagent", undefined);
|
|
386
|
-
} else
|
|
387
|
-
|
|
484
|
+
} else
|
|
485
|
+
updateWidget(
|
|
486
|
+
ctx,
|
|
487
|
+
widgetThreads(),
|
|
488
|
+
widgetCollapsed ? "minimal" : limits.widgetMode,
|
|
489
|
+
limits.nerdFontIcons,
|
|
490
|
+
rootTurnEnded,
|
|
491
|
+
limits.loaderStyle,
|
|
492
|
+
);
|
|
388
493
|
};
|
|
389
494
|
pi.on("agent_start", async (_event, ctx) => {
|
|
390
495
|
// A new task must not resurrect the previous task's settled agents. Automatic
|
|
@@ -422,7 +527,11 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
422
527
|
};
|
|
423
528
|
});
|
|
424
529
|
|
|
425
|
-
const attachSession = async (
|
|
530
|
+
const attachSession = async (
|
|
531
|
+
ctx: ExtensionContext,
|
|
532
|
+
installEditor = false,
|
|
533
|
+
seedHistory = true,
|
|
534
|
+
) => {
|
|
426
535
|
cancelSummary();
|
|
427
536
|
const token = ++generation;
|
|
428
537
|
closeNavigation(installEditor);
|
|
@@ -431,6 +540,9 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
431
540
|
if (manager) await manager.shutdown();
|
|
432
541
|
inheritedTools.reset();
|
|
433
542
|
context = ctx;
|
|
543
|
+
costLedger = new CostLedger();
|
|
544
|
+
costLedger.restore(ctx.sessionManager.getEntries());
|
|
545
|
+
costFooter.reset(ctx);
|
|
434
546
|
rootTurnEnded = false;
|
|
435
547
|
if (installEditor) {
|
|
436
548
|
widgetCollapsed = false;
|
|
@@ -459,6 +571,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
459
571
|
if (token !== generation) return;
|
|
460
572
|
refreshWidget(requireContext());
|
|
461
573
|
if (event.kind !== "metrics") persist();
|
|
574
|
+
if (event.kind === "settled") rollupCost(event.thread);
|
|
462
575
|
delivery(event);
|
|
463
576
|
},
|
|
464
577
|
});
|
|
@@ -486,6 +599,8 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
486
599
|
ctx.ui.notify(`Could not restore subagent registry: ${String(error)}`, "error");
|
|
487
600
|
}
|
|
488
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() });
|
|
489
604
|
restoreRootMailbox(ctx);
|
|
490
605
|
refreshWidget(ctx);
|
|
491
606
|
const diagnostics = [...store.diagnostics, ...settingsDiagnostics];
|
|
@@ -518,6 +633,7 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
518
633
|
pi.on("session_before_fork", stopWorkingThreads);
|
|
519
634
|
pi.on("session_shutdown", async () => {
|
|
520
635
|
cancelSummary();
|
|
636
|
+
costFooter.clear();
|
|
521
637
|
generation++;
|
|
522
638
|
closeNavigation(true);
|
|
523
639
|
await manager?.shutdown();
|
|
@@ -596,10 +712,15 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
596
712
|
if (!canOpenDialog(ctx)) return;
|
|
597
713
|
closeNavigation();
|
|
598
714
|
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
|
-
|
|
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
|
+
);
|
|
603
724
|
if (choice !== "confirm" || manager !== current) return;
|
|
604
725
|
const reaped = current.reap(candidates);
|
|
605
726
|
persist();
|
|
@@ -611,7 +732,13 @@ export default function piSubagent(pi: ExtensionAPI): void {
|
|
|
611
732
|
"info",
|
|
612
733
|
);
|
|
613
734
|
} else if (command === "tree") {
|
|
614
|
-
await navigation.open(
|
|
735
|
+
await navigation.open(
|
|
736
|
+
ctx,
|
|
737
|
+
requireManager().scope("/root"),
|
|
738
|
+
rest.join(" ") || undefined,
|
|
739
|
+
limits.nerdFontIcons,
|
|
740
|
+
limits.loaderStyle,
|
|
741
|
+
);
|
|
615
742
|
} else
|
|
616
743
|
ctx.ui.notify(
|
|
617
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
|
+
}
|