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.
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
3
  import type {
3
4
  AgentDriver,
@@ -30,10 +31,11 @@ interface Record {
30
31
  started?: Promise<void>;
31
32
  sessionLeafId?: string | null;
32
33
  /** Last authoritative cumulative usage applied from the current driver. */
33
- usageCursor?: { input: number; output: number };
34
+ usageCursor?: { input: number; output: number; costUsd?: number };
34
35
  /** In-progress message usage. Shown live, never persisted. */
35
36
  liveInputTokens?: number;
36
37
  liveOutputTokens?: number;
38
+ liveCostUsd?: number;
37
39
  /** Detached (spawned with wait:false): completion is reported as an event. */
38
40
  async?: boolean;
39
41
  timeoutTimer?: ReturnType<typeof setTimeout>;
@@ -106,11 +108,14 @@ export class ThreadManager {
106
108
  const eligible = new Set(
107
109
  records
108
110
  .filter((record) => !only || only.includes(record.view.path))
109
- .filter((record) => record.view.state === "completed" && (!record.initializing || record.driver))
110
- .filter((record) =>
111
- !records.some(
112
- (other) => active(other.view) && isDescendant(record.view.path, other.view.path),
113
- ),
111
+ .filter(
112
+ (record) => record.view.state === "completed" && (!record.initializing || record.driver),
113
+ )
114
+ .filter(
115
+ (record) =>
116
+ !records.some(
117
+ (other) => active(other.view) && isDescendant(record.view.path, other.view.path),
118
+ ),
114
119
  )
115
120
  .map((record) => record.view.path),
116
121
  );
@@ -198,6 +203,8 @@ export class ThreadManager {
198
203
  type: current.type,
199
204
  color: current.color,
200
205
  icon: current.icon,
206
+ model: current.model,
207
+ thinkingLevel: current.thinkingLevel,
201
208
  state: current.state,
202
209
  task: current.task,
203
210
  status: current.status,
@@ -210,6 +217,8 @@ export class ThreadManager {
210
217
  elapsedMs: record.view.elapsedMs ?? 0,
211
218
  inputTokens: record.view.inputTokens ?? 0,
212
219
  outputTokens: record.view.outputTokens ?? 0,
220
+ costUsd: record.view.costUsd,
221
+ costId: record.view.costId,
213
222
  };
214
223
  const sessionLeafId = this.sessionLeafId(record);
215
224
  if (sessionLeafId !== undefined) view.sessionLeafId = sessionLeafId;
@@ -240,6 +249,9 @@ export class ThreadManager {
240
249
  const { sessionLeafId, ...storedView } = savedView;
241
250
  const view: ThreadView = {
242
251
  ...storedView,
252
+ costId:
253
+ storedView.costId ??
254
+ `legacy:${storedView.sessionFile ?? `${storedView.path}:${storedView.createdAt}`}`,
243
255
  icon: storedView.icon ?? item.definition.icon,
244
256
  updatedAt: Date.now(),
245
257
  elapsedMs: storedView.elapsedMs ?? 0,
@@ -333,6 +345,7 @@ export class ThreadManager {
333
345
  task: args.task,
334
346
  status: "Starting",
335
347
  createdAt: now,
348
+ costId: randomUUID(),
336
349
  updatedAt: now,
337
350
  elapsedMs: 0,
338
351
  inputTokens: 0,
@@ -660,6 +673,7 @@ export class ThreadManager {
660
673
  this.freezeElapsed(record);
661
674
  record.liveInputTokens = 0;
662
675
  record.liveOutputTokens = 0;
676
+ record.liveCostUsd = undefined;
663
677
  markStarted(); // Failed/cancelled initialization must also release callers waiting to steer.
664
678
  this.touch(record);
665
679
  if (!this.disposed && epoch === this.epoch)
@@ -699,6 +713,17 @@ export class ThreadManager {
699
713
  signal,
700
714
  shouldPause: () => record.pauseRequested,
701
715
  onEvent: (event) => {
716
+ if (event.kind === "settings") {
717
+ if (
718
+ record.view.model !== event.model ||
719
+ record.view.thinkingLevel !== event.thinkingLevel
720
+ ) {
721
+ record.view.model = event.model;
722
+ record.view.thinkingLevel = event.thinkingLevel;
723
+ this.touch(record);
724
+ }
725
+ return;
726
+ }
702
727
  if (event.kind === "usage") {
703
728
  this.applyUsage(record, event);
704
729
  return;
@@ -730,6 +755,7 @@ export class ThreadManager {
730
755
  record.usageCursor = { input: 0, output: 0 };
731
756
  record.liveInputTokens = 0;
732
757
  record.liveOutputTokens = 0;
758
+ record.liveCostUsd = undefined;
733
759
  record.view.sessionFile = driver.sessionFile;
734
760
  if (driver.sessionLeafId !== undefined) record.sessionLeafId = driver.sessionLeafId;
735
761
  this.touch(record);
@@ -806,15 +832,25 @@ export class ThreadManager {
806
832
  /** Fold driver-cumulative usage into persisted totals. Partials only refresh the live view. */
807
833
  private applyUsage(
808
834
  record: Record,
809
- event: { inputTokens: number; outputTokens: number; partial?: boolean },
835
+ event: { inputTokens: number; outputTokens: number; costUsd?: number; partial?: boolean },
810
836
  ): void {
811
837
  const cursor = record.usageCursor ?? { input: 0, output: 0 };
838
+ const costUsd =
839
+ event.costUsd !== undefined && Number.isFinite(event.costUsd) && event.costUsd >= 0
840
+ ? Math.max(0, event.costUsd - (cursor.costUsd ?? 0))
841
+ : undefined;
812
842
  if (event.partial) {
813
843
  const input = Math.max(0, event.inputTokens - cursor.input);
814
844
  const output = Math.max(0, event.outputTokens - cursor.output);
815
- if (input === record.liveInputTokens && output === record.liveOutputTokens) return;
845
+ if (
846
+ input === record.liveInputTokens &&
847
+ output === record.liveOutputTokens &&
848
+ costUsd === record.liveCostUsd
849
+ )
850
+ return;
816
851
  record.liveInputTokens = input;
817
852
  record.liveOutputTokens = output;
853
+ record.liveCostUsd = costUsd;
818
854
  if (!this.disposed) this.emit({ kind: "metrics", thread: this.view(record) });
819
855
  return;
820
856
  }
@@ -822,9 +858,15 @@ export class ThreadManager {
822
858
  (record.view.inputTokens ?? 0) + Math.max(0, event.inputTokens - cursor.input);
823
859
  record.view.outputTokens =
824
860
  (record.view.outputTokens ?? 0) + Math.max(0, event.outputTokens - cursor.output);
825
- record.usageCursor = { input: event.inputTokens, output: event.outputTokens };
861
+ if (costUsd !== undefined) record.view.costUsd = (record.view.costUsd ?? 0) + costUsd;
862
+ record.usageCursor = {
863
+ input: event.inputTokens,
864
+ output: event.outputTokens,
865
+ costUsd: event.costUsd ?? cursor.costUsd,
866
+ };
826
867
  record.liveInputTokens = 0;
827
868
  record.liveOutputTokens = 0;
869
+ record.liveCostUsd = undefined;
828
870
  this.touch(record);
829
871
  }
830
872
  private freezeElapsed(record: Record): void {
@@ -878,6 +920,7 @@ export class ThreadManager {
878
920
  if (record.liveInputTokens) view.inputTokens = (view.inputTokens ?? 0) + record.liveInputTokens;
879
921
  if (record.liveOutputTokens)
880
922
  view.outputTokens = (view.outputTokens ?? 0) + record.liveOutputTokens;
923
+ if (record.liveCostUsd !== undefined) view.costUsd = (view.costUsd ?? 0) + record.liveCostUsd;
881
924
  return view;
882
925
  }
883
926
  private record(path: string): Record {
@@ -388,7 +388,10 @@ export function createDriverFactory(
388
388
  const rootActive = new Set(inherited.activeNames);
389
389
  // Preserve deferred/codemode exposure rather than flooding model declarations with MCP tools.
390
390
  const activeToolNames = toolNames.filter(
391
- (name) => localNames.has(name) || rootActive.has(name) || options.type.tools?.allow?.includes(name) && toolFiltering === "allowed",
391
+ (name) =>
392
+ localNames.has(name) ||
393
+ rootActive.has(name) ||
394
+ (options.type.tools?.allow?.includes(name) && toolFiltering === "allowed"),
392
395
  );
393
396
  const customTools = [...options.tools, ...externalTools].filter(
394
397
  (tool) => allowed.has(tool.name) && tool.name !== "codemode" && tool.name !== "tool_search",
@@ -467,6 +470,11 @@ export function createDriverFactory(
467
470
  id: currentModel.id,
468
471
  thinking: session.thinkingLevel,
469
472
  });
473
+ options.onEvent({
474
+ kind: "settings",
475
+ model: modelIdentity(currentModel),
476
+ thinkingLevel: session.thinkingLevel,
477
+ });
470
478
  };
471
479
  const assertScopedRequestAuthorized = (
472
480
  currentIdentity: string | undefined,
@@ -606,6 +614,7 @@ export function createDriverFactory(
606
614
  // Subscribe after inherited/restored history is loaded; only new assistant events are counted.
607
615
  let settledInput = 0;
608
616
  let settledOutput = 0;
617
+ let settledCost: number | undefined;
609
618
  const countedUsage = new WeakSet<object>();
610
619
  let finalOutput = "";
611
620
  let abortPromise: Promise<void> | undefined;
@@ -616,7 +625,14 @@ export function createDriverFactory(
616
625
  const input = usage.input + usage.cacheRead + usage.cacheWrite;
617
626
  const output = usage.output;
618
627
  if (!Number.isFinite(input) || !Number.isFinite(output)) return;
619
- return { input, output, reported: input + output + usage.totalTokens > 0 };
628
+ const total = usage.cost?.total;
629
+ const costUsd = Number.isFinite(total) && total >= 0 ? total : undefined;
630
+ return {
631
+ input,
632
+ output,
633
+ costUsd,
634
+ reported: input + output + usage.totalTokens > 0 || (costUsd ?? 0) > 0,
635
+ };
620
636
  };
621
637
 
622
638
  const ownership = sessionManager
@@ -657,6 +673,8 @@ export function createDriverFactory(
657
673
  kind: "usage",
658
674
  inputTokens: settledInput + usage.input,
659
675
  outputTokens: settledOutput + usage.output,
676
+ costUsd:
677
+ usage.costUsd === undefined ? settledCost : (settledCost ?? 0) + usage.costUsd,
660
678
  partial: true,
661
679
  });
662
680
  } else {
@@ -664,11 +682,13 @@ export function createDriverFactory(
664
682
  if (usage) {
665
683
  settledInput += usage.input;
666
684
  settledOutput += usage.output;
685
+ if (usage.costUsd !== undefined) settledCost = (settledCost ?? 0) + usage.costUsd;
667
686
  }
668
687
  options.onEvent({
669
688
  kind: "usage",
670
689
  inputTokens: settledInput,
671
690
  outputTokens: settledOutput,
691
+ costUsd: settledCost,
672
692
  });
673
693
  const text = event.message.content
674
694
  .filter((block) => block.type === "text")
package/src/types.ts CHANGED
@@ -49,6 +49,9 @@ export interface ThreadView {
49
49
  type: string;
50
50
  color?: string;
51
51
  icon?: string;
52
+ /** Actual runtime selection, not the type's model preferences. */
53
+ model?: string;
54
+ thinkingLevel?: ThinkingLevel;
52
55
  state: ThreadState;
53
56
  task: string;
54
57
  status: string;
@@ -67,8 +70,13 @@ export interface ThreadView {
67
70
  inputTokens?: number;
68
71
  /** Cumulative output tokens. Live views include the in-progress message. */
69
72
  outputTokens?: number;
73
+ /** Cumulative estimated USD cost for this agent's own messages. */
74
+ costUsd?: number;
75
+ /** Stable lifetime identity for cost accounting, retained across resumes/reloads. */
76
+ costId?: string;
70
77
  }
71
78
  export type DriverEvent =
79
+ | { kind: "settings"; model: string; thinkingLevel: ThinkingLevel }
72
80
  | { kind: "activity" | "error"; text: string }
73
81
  | {
74
82
  kind: "checkpoint";
@@ -81,6 +89,8 @@ export type DriverEvent =
81
89
  /** Cumulative own-assistant tokens for this driver instance, excluding inherited history. */
82
90
  inputTokens: number;
83
91
  outputTokens: number;
92
+ /** Cumulative estimated USD cost, when reported by the runtime. */
93
+ costUsd?: number;
84
94
  /** Streaming message_update snapshot. Omit for authoritative message_end. */
85
95
  partial?: boolean;
86
96
  };
@@ -144,6 +154,8 @@ export interface SavedThreadView {
144
154
  type: string;
145
155
  color?: string;
146
156
  icon?: string;
157
+ model?: string;
158
+ thinkingLevel?: ThinkingLevel;
147
159
  state: ThreadState;
148
160
  task: string;
149
161
  status: string;
@@ -157,6 +169,8 @@ export interface SavedThreadView {
157
169
  lastStartedAt?: number;
158
170
  inputTokens?: number;
159
171
  outputTokens?: number;
172
+ costUsd?: number;
173
+ costId?: string;
160
174
  }
161
175
  export interface SavedThread {
162
176
  view: SavedThreadView;
@@ -189,7 +203,13 @@ export type ThreadEvent =
189
203
  | { kind: "update"; thread: ThreadView; message: string; recipient: string }
190
204
  | { kind: "settled"; thread: ThreadView; recipient: string; async: boolean }
191
205
  /** A spawn timeout elapsed while the child is still running. The child is NOT stopped. */
192
- | { kind: "timeout"; thread: ThreadView; recipient: string; timeoutMs: number; recentOutput: string };
206
+ | {
207
+ kind: "timeout";
208
+ thread: ThreadView;
209
+ recipient: string;
210
+ timeoutMs: number;
211
+ recentOutput: string;
212
+ };
193
213
  export interface ManagerOptions {
194
214
  createDriver: DriverFactory;
195
215
  rootSnapshot(): AgentMessage[];
@@ -0,0 +1,187 @@
1
+ import { homedir } from "node:os";
2
+ import type { Usage } from "@earendil-works/pi-ai";
3
+ import type { ExtensionAPI, ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
+
6
+ export function footerUsage(entries: readonly SessionEntry[]) {
7
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
8
+ let cacheHit: number | undefined;
9
+ const add = (usage: Usage | undefined) => {
10
+ if (!usage) return;
11
+ totals.input += usage.input;
12
+ totals.output += usage.output;
13
+ totals.cacheRead += usage.cacheRead;
14
+ totals.cacheWrite += usage.cacheWrite;
15
+ totals.cost += usage.cost.total;
16
+ };
17
+ for (const entry of entries) {
18
+ if (entry.type === "usage") add(entry.usage);
19
+ else if (entry.type === "message") {
20
+ if (entry.message.role === "assistant") {
21
+ add(entry.message.usage);
22
+ const usage = entry.message.usage;
23
+ const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
24
+ cacheHit = prompt ? (usage.cacheRead / prompt) * 100 : undefined;
25
+ } else if (entry.message.role === "toolResult") add(entry.message.usage);
26
+ } else if (entry.type === "branch_summary" || entry.type === "compaction") add(entry.usage);
27
+ }
28
+ return { ...totals, cacheHit };
29
+ }
30
+ export const COST_WIDGET_ID = "subagent_cost";
31
+ export const COST_WIDGET_EVENT = "pi-footer:update-widget";
32
+ export const COST_ICON = "\uf0d6";
33
+
34
+ export function formatSubagentCost(cost: number, nerdFontIcons: boolean): string {
35
+ return `${nerdFontIcons ? COST_ICON + " " : ""}$${cost.toFixed(4)}`;
36
+ }
37
+
38
+ /** Any extension-owned /footer takes priority; never infer activity from installed packages alone. */
39
+ export function hasExternalFooter(pi: Pick<ExtensionAPI, "getCommands">): boolean {
40
+ return pi
41
+ .getCommands()
42
+ .some((command) => command.name === "footer" && command.source === "extension");
43
+ }
44
+
45
+ export class CostFooterController {
46
+ private installed = false;
47
+ private requestRender: (() => void) | undefined;
48
+
49
+ constructor(
50
+ private readonly pi: Pick<ExtensionAPI, "getCommands" | "events">,
51
+ private readonly subagentCost: () => number,
52
+ private readonly nerdFontIcons: () => boolean,
53
+ ) {}
54
+
55
+ refresh(ctx: ExtensionContext): void {
56
+ // Publishing is independent of which footer owns the screen, including headless sessions.
57
+ this.pi.events.emit(COST_WIDGET_EVENT, {
58
+ widgetId: COST_WIDGET_ID,
59
+ value: formatSubagentCost(this.subagentCost(), this.nerdFontIcons()),
60
+ });
61
+ if (hasExternalFooter(this.pi)) {
62
+ // Do not clear setFooter here: it could already belong to pi-footer.
63
+ this.installed = false;
64
+ this.requestRender = undefined;
65
+ return;
66
+ }
67
+ if (this.installed) {
68
+ this.requestRender?.();
69
+ return;
70
+ }
71
+ if (this.subagentCost() <= 0 || !ctx.hasUI || ctx.mode !== "tui") return;
72
+ this.requestRender = installCostFooter(ctx, this.subagentCost);
73
+ this.installed = true;
74
+ }
75
+
76
+ reset(ctx: ExtensionContext): void {
77
+ if (this.installed && !hasExternalFooter(this.pi)) ctx.ui.setFooter(undefined);
78
+ this.installed = false;
79
+ this.requestRender = undefined;
80
+ }
81
+
82
+ clear(): void {
83
+ this.pi.events.emit(COST_WIDGET_EVENT, { widgetId: COST_WIDGET_ID, value: null });
84
+ }
85
+ }
86
+
87
+ const tokens = (n: number) =>
88
+ n < 1000
89
+ ? String(n)
90
+ : n < 10000
91
+ ? `${(n / 1000).toFixed(1)}k`
92
+ : n < 1000000
93
+ ? `${Math.round(n / 1000)}k`
94
+ : `${(n / 1000000).toFixed(1)}M`;
95
+
96
+ /** Public extension UI APIs only: never inject fake usage/messages into Pi's transcript. */
97
+ export function installCostFooter(
98
+ ctx: ExtensionContext,
99
+ subagentCost: () => number,
100
+ ): (() => void) | undefined {
101
+ if (!ctx.hasUI || ctx.mode !== "tui" || !ctx.ui.setFooter) return;
102
+ let requestRender: (() => void) | undefined;
103
+ ctx.ui.setFooter((tui, theme, footerData) => {
104
+ requestRender = () => tui.requestRender();
105
+ const unsubscribe = footerData.onBranchChange(() => tui.requestRender());
106
+ let entryCount = -1;
107
+ let totals = footerUsage([]);
108
+ return {
109
+ dispose: unsubscribe,
110
+ invalidate() {
111
+ entryCount = -1;
112
+ },
113
+ render(width: number) {
114
+ const entries = ctx.sessionManager.getEntries();
115
+ const count = entries.length;
116
+ if (count !== entryCount) {
117
+ totals = footerUsage(entries);
118
+ entryCount = count;
119
+ }
120
+ const branch = footerData.getGitBranch();
121
+ const name = ctx.sessionManager.getSessionName();
122
+ const cwd =
123
+ ctx.cwd === homedir()
124
+ ? "~"
125
+ : ctx.cwd.startsWith(homedir() + "/")
126
+ ? "~" + ctx.cwd.slice(homedir().length)
127
+ : ctx.cwd;
128
+ const location = cwd + (branch ? ` (${branch})` : "") + (name ? ` • ${name}` : "");
129
+ const parts: string[] = [];
130
+ if (totals.input) parts.push(`↑${tokens(totals.input)}`);
131
+ if (totals.output) parts.push(`↓${tokens(totals.output)}`);
132
+ if (totals.cacheRead) parts.push(`R${tokens(totals.cacheRead)}`);
133
+ if (totals.cacheWrite) parts.push(`W${tokens(totals.cacheWrite)}`);
134
+ if ((totals.cacheRead || totals.cacheWrite) && totals.cacheHit !== undefined)
135
+ parts.push(`CH${totals.cacheHit.toFixed(1)}%`);
136
+ // Pi's own usage and each child's own usage are disjoint. Never aggregate a parent's descendants twice.
137
+ const subscription =
138
+ ctx.model &&
139
+ (ctx.model.provider === "kimi-coding" || ctx.modelRegistry?.isUsingOAuth(ctx.model));
140
+ parts.push(`$${(totals.cost + subagentCost()).toFixed(3)}${subscription ? " (sub)" : ""}`);
141
+ const context = ctx.getContextUsage();
142
+ if (context) {
143
+ const text = `${context.percent === null ? "?" : context.percent.toFixed(1) + "%"}/${tokens(context.contextWindow)}`;
144
+ parts.push(
145
+ theme.fg(
146
+ (context.percent ?? 0) > 90
147
+ ? "error"
148
+ : (context.percent ?? 0) > 70
149
+ ? "warning"
150
+ : "dim",
151
+ text,
152
+ ),
153
+ );
154
+ }
155
+ const left = truncateToWidth(parts.join(" "), width, "");
156
+ let right = ctx.model?.id ?? "no-model";
157
+ if (ctx.model?.reasoning) right += ` • ${ctx.thinkingLevel ?? "off"}`;
158
+ if (footerData.getAvailableProviderCount() > 1 && ctx.model) {
159
+ const withProvider = `(${ctx.model.provider}) ${right}`;
160
+ if (visibleWidth(left) + 2 + visibleWidth(withProvider) <= width) right = withProvider;
161
+ }
162
+ const available = width - visibleWidth(left) - 2;
163
+ const stats =
164
+ available > 0
165
+ ? left +
166
+ " ".repeat(
167
+ Math.max(2, width - visibleWidth(left) - Math.min(available, visibleWidth(right))),
168
+ ) +
169
+ truncateToWidth(right, available, "")
170
+ : left;
171
+ const lines = [truncateToWidth(theme.fg("dim", location), width), theme.fg("dim", stats)];
172
+ const statuses = [...footerData.getExtensionStatuses()]
173
+ .sort(([a], [b]) => a.localeCompare(b))
174
+ .map(([, text]) =>
175
+ text
176
+ .replace(/[\r\n\t]/g, " ")
177
+ .replace(/ +/g, " ")
178
+ .trim(),
179
+ );
180
+ if (statuses.length)
181
+ lines.push(truncateToWidth(theme.fg("dim", statuses.join(" ")), width));
182
+ return lines;
183
+ },
184
+ };
185
+ });
186
+ return () => requestRender?.();
187
+ }