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.
@@ -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 {
@@ -17,7 +17,7 @@ export function subagentPrompt(settings: ManagerSettings): string | undefined {
17
17
  policy,
18
18
  "Call agent_types before choosing a type. Use task-based kebab-case paths, not type names. Choose context via agent_spawn path: /root/task forks the lexical parent's conversation; /task starts fresh with no inherited history. Use fresh agents for adversarial review or clean-slate research; give them a self-contained task without the current thread's conclusions.",
19
19
  waitingPolicy,
20
- "Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. When a timeout event shows a child still progressing, call agent_steer with only timeoutMs (no message; re-arms without steering) to re-arm it, or agent_wait/agent_steer/agent_stop.",
20
+ 'Use agent_status to inspect and agent_output for full results. Completion, failure or stop of a wait:false agent is delivered to you as a message event that starts a new turn when you are idle (with Final Recap on, once after all outstanding async agents have finished). Pass timeoutMs to agent_spawn to get a status event if a child runs long; the child is not killed. Valid range 30000–300000 ms; omit for no timeout. To extend a running background agent\'s reporting timer, before or after a timeout event, call agent_steer({path: "/root/task", timeoutMs: 120000}) with message omitted entirely. This resets the timer from now (replacing any pending timer), without sending input, interrupting or resuming the agent; it requires the agent to still be running. After re-arming, end your turn to remain available while it works. For other timeout responses, follow the waiting policy above, send steering input or stop the agent.',
21
21
  "Use agent_steer to send input or resume retained sessions. Paused agents have no final answer; completed agents hand back results. Both retain their session.",
22
22
  `Maximum depth: ${settings.maxLevels} levels including L1. Shared concurrency: ${settings.maxConcurrent} active threads; waiting parents count.`,
23
23
  ].join("\n");
@@ -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/orch/tools.ts CHANGED
@@ -113,11 +113,23 @@ export function agentTools(
113
113
  ),
114
114
  make(
115
115
  "agent_steer",
116
- "Send input to a descendant and/or re-arm its report-only timeout. With message: working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. With timeoutMs (30000–300000): the timeout fires that many ms from now, replacing any pending timer. timeoutMs WITHOUT message only re-arms the timeout of a running child (error if not running) and does not steer or resume it; with both, steer and re-arm. At least one is required. Returns immediately; use agent_wait for the result.",
116
+ 'Send input to a descendant and/or re-arm its report-only timeout. With message: working threads receive queued steering; completed, stopped and paused threads resume the SAME session with its previous context. With timeoutMs (30000–300000): the timeout fires that many ms from now, replacing any pending timer. To extend a running background agent\'s reporting timer without sending input, call agent_steer({path: "/root/task", timeoutMs: 120000}) and omit message entirely. This resets the timer to 120000 ms from now, not an addition to the old deadline. timeoutMs WITHOUT message only re-arms the timeout of a running child (error if not running) and does not steer, interrupt or resume it; with both, steer and re-arm. At least one is required. Returns immediately; use agent_wait for the result.',
117
117
  Type.Object({
118
118
  path,
119
- message: Type.Optional(text),
120
- timeoutMs: Type.Optional(Type.Integer({ minimum: 30000, maximum: 300000 })),
119
+ message: Type.Optional(
120
+ Type.String({
121
+ minLength: 1,
122
+ description: "Input to send or resume with. Omit entirely for a timer-only re-arm.",
123
+ }),
124
+ ),
125
+ timeoutMs: Type.Optional(
126
+ Type.Integer({
127
+ minimum: 30000,
128
+ maximum: 300000,
129
+ description:
130
+ "Reset the report-only timer to this many ms from now, replacing any pending timer. With no message, only re-arms a running agent; does not send input, interrupt or resume it.",
131
+ }),
132
+ ),
121
133
  }),
122
134
  async (params) =>
123
135
  result(compact(await threads().steer(params.path, params.message, params.timeoutMs))),
@@ -19,6 +19,9 @@ export type SubagentMode = (typeof SUBAGENT_MODES)[number];
19
19
  export const WIDGET_MODES = ["full", "minimal"] as const;
20
20
  export type WidgetMode = (typeof WIDGET_MODES)[number];
21
21
 
22
+ export const COST_DISPLAY_MODES = ["pi-footer-event", "pi-footer-status", "pi-status"] as const;
23
+ export type CostDisplayMode = (typeof COST_DISPLAY_MODES)[number];
24
+
22
25
  export const LOADER_STYLES = ["circle", "braille", "hourglass"] as const;
23
26
  export type LoaderStyle = (typeof LOADER_STYLES)[number];
24
27
 
@@ -36,6 +39,7 @@ export interface ManagerSettings {
36
39
  subagentMode: SubagentMode;
37
40
  toolFiltering: ToolFilteringMode;
38
41
  widgetMode: WidgetMode;
42
+ costDisplay: CostDisplayMode;
39
43
  nerdFontIcons: boolean;
40
44
  loaderStyle: LoaderStyle;
41
45
  finalRecap: boolean;
@@ -53,13 +57,14 @@ export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
53
57
  subagentMode: "opportunistic",
54
58
  toolFiltering: "allowed",
55
59
  widgetMode: "full",
60
+ costDisplay: "pi-footer-status",
56
61
  nerdFontIcons: false,
57
62
  loaderStyle: "circle",
58
63
  finalRecap: false,
59
64
  };
60
65
 
61
66
  const KEYS = [
62
- "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "nerdFontIcons", "loaderStyle", "finalRecap",
67
+ "maxLevels", "maxConcurrent", "maxThreads", "modelSelection", "subagentMode", "toolFiltering", "widgetMode", "costDisplay", "nerdFontIcons", "loaderStyle", "finalRecap",
63
68
  ] as const;
64
69
  const MAX_LEVELS = 32;
65
70
 
@@ -100,6 +105,7 @@ function requirement(key: (typeof KEYS)[number]): string {
100
105
  if (key === "nerdFontIcons" || key === "finalRecap") return `${key} must be a boolean`;
101
106
  if (key === "subagentMode") return "subagentMode must be off, opportunistic or orchestration";
102
107
  if (key === "widgetMode") return "widgetMode must be full or minimal";
108
+ if (key === "costDisplay") return "costDisplay must be pi-footer-event, pi-footer-status or pi-status";
103
109
  if (key === "loaderStyle") return "loaderStyle must be circle, braille or hourglass";
104
110
  if (key === "toolFiltering") return "toolFiltering must be allowed, all-except-blocked or all";
105
111
  if (key === "modelSelection")
@@ -154,6 +160,11 @@ function parseSettings(content: string): Partial<ManagerSettings> {
154
160
  layer.widgetMode = value as WidgetMode;
155
161
  continue;
156
162
  }
163
+ if (key === "costDisplay") {
164
+ if (!COST_DISPLAY_MODES.includes(value as CostDisplayMode)) throw new Error(requirement(key));
165
+ layer.costDisplay = value as CostDisplayMode;
166
+ continue;
167
+ }
157
168
  if (key === "loaderStyle") {
158
169
  if (!LOADER_STYLES.includes(value as LoaderStyle)) throw new Error(requirement(key));
159
170
  layer.loaderStyle = value as LoaderStyle;
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,213 @@
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
+ import type { CostDisplayMode } from "../prefs/settings.ts";
6
+
7
+ export function footerUsage(entries: readonly SessionEntry[]) {
8
+ const totals = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
9
+ let cacheHit: number | undefined;
10
+ const add = (usage: Usage | undefined) => {
11
+ if (!usage) return;
12
+ totals.input += usage.input;
13
+ totals.output += usage.output;
14
+ totals.cacheRead += usage.cacheRead;
15
+ totals.cacheWrite += usage.cacheWrite;
16
+ totals.cost += usage.cost.total;
17
+ };
18
+ for (const entry of entries) {
19
+ if (entry.type === "usage") add(entry.usage);
20
+ else if (entry.type === "message") {
21
+ if (entry.message.role === "assistant") {
22
+ add(entry.message.usage);
23
+ const usage = entry.message.usage;
24
+ const prompt = usage.input + usage.cacheRead + usage.cacheWrite;
25
+ cacheHit = prompt ? (usage.cacheRead / prompt) * 100 : undefined;
26
+ } else if (entry.message.role === "toolResult") add(entry.message.usage);
27
+ } else if (entry.type === "branch_summary" || entry.type === "compaction") add(entry.usage);
28
+ }
29
+ return { ...totals, cacheHit };
30
+ }
31
+ export const COST_WIDGET_ID = "subagent_cost";
32
+ export const COST_WIDGET_EVENT = "pi-footer:update-widget";
33
+ export const COST_ICON = "\uf0d6";
34
+
35
+ export function formatSubagentCost(cost: number, nerdFontIcons: boolean): string {
36
+ return `${nerdFontIcons ? COST_ICON + " " : ""}$${cost.toFixed(4)}`;
37
+ }
38
+
39
+ /** Any extension-owned /footer takes priority; never infer activity from installed packages alone. */
40
+ export function hasExternalFooter(pi: Pick<ExtensionAPI, "getCommands">): boolean {
41
+ return pi
42
+ .getCommands()
43
+ .some((command) => command.name === "footer" && command.source === "extension");
44
+ }
45
+
46
+ export class CostFooterController {
47
+ private installed = false;
48
+ private requestRender: (() => void) | undefined;
49
+
50
+ private publishedMode: CostDisplayMode | undefined;
51
+ private statusContext: ExtensionContext | undefined;
52
+ constructor(
53
+ private readonly pi: Pick<ExtensionAPI, "getCommands" | "events">,
54
+ private readonly subagentCost: () => number,
55
+ private readonly nerdFontIcons: () => boolean,
56
+ private readonly displayMode: () => CostDisplayMode = () => "pi-footer-status",
57
+ ) {}
58
+
59
+ refresh(ctx: ExtensionContext): void {
60
+ const mode = this.displayMode();
61
+ const value = formatSubagentCost(this.subagentCost(), this.nerdFontIcons());
62
+ if (this.publishedMode !== undefined && this.publishedMode !== mode) {
63
+ this.clear();
64
+ this.reset(ctx);
65
+ }
66
+ this.publishedMode = mode;
67
+ if (mode !== "pi-footer-event") {
68
+ if (ctx.hasUI) {
69
+ this.statusContext = ctx;
70
+ const statusValue =
71
+ mode === "pi-status"
72
+ ? `Total: ${formatSubagentCost(
73
+ footerUsage(ctx.sessionManager.getEntries()).cost + this.subagentCost(),
74
+ this.nerdFontIcons(),
75
+ )}`
76
+ : value;
77
+ ctx.ui.setStatus(COST_WIDGET_ID, statusValue);
78
+ }
79
+ return;
80
+ }
81
+ // Event mode also works in headless sessions; status modes need a UI consumer.
82
+ this.pi.events.emit(COST_WIDGET_EVENT, { widgetId: COST_WIDGET_ID, value });
83
+ if (hasExternalFooter(this.pi)) {
84
+ // Do not clear setFooter here: it could already belong to pi-footer.
85
+ this.installed = false;
86
+ this.requestRender = undefined;
87
+ return;
88
+ }
89
+ if (this.installed) {
90
+ this.requestRender?.();
91
+ return;
92
+ }
93
+ if (this.subagentCost() <= 0 || !ctx.hasUI || ctx.mode !== "tui") return;
94
+ this.requestRender = installCostFooter(ctx, this.subagentCost);
95
+ this.installed = true;
96
+ }
97
+
98
+ reset(ctx: ExtensionContext): void {
99
+ if (this.installed && !hasExternalFooter(this.pi)) ctx.ui.setFooter(undefined);
100
+ this.installed = false;
101
+ this.requestRender = undefined;
102
+ }
103
+
104
+ clear(): void {
105
+ if (this.publishedMode === "pi-footer-event")
106
+ this.pi.events.emit(COST_WIDGET_EVENT, { widgetId: COST_WIDGET_ID, value: null });
107
+ this.statusContext?.ui.setStatus(COST_WIDGET_ID, undefined);
108
+ this.statusContext = undefined;
109
+ this.publishedMode = undefined;
110
+ }
111
+ }
112
+
113
+ const tokens = (n: number) =>
114
+ n < 1000
115
+ ? String(n)
116
+ : n < 10000
117
+ ? `${(n / 1000).toFixed(1)}k`
118
+ : n < 1000000
119
+ ? `${Math.round(n / 1000)}k`
120
+ : `${(n / 1000000).toFixed(1)}M`;
121
+
122
+ /** Public extension UI APIs only: never inject fake usage/messages into Pi's transcript. */
123
+ export function installCostFooter(
124
+ ctx: ExtensionContext,
125
+ subagentCost: () => number,
126
+ ): (() => void) | undefined {
127
+ if (!ctx.hasUI || ctx.mode !== "tui" || !ctx.ui.setFooter) return;
128
+ let requestRender: (() => void) | undefined;
129
+ ctx.ui.setFooter((tui, theme, footerData) => {
130
+ requestRender = () => tui.requestRender();
131
+ const unsubscribe = footerData.onBranchChange(() => tui.requestRender());
132
+ let entryCount = -1;
133
+ let totals = footerUsage([]);
134
+ return {
135
+ dispose: unsubscribe,
136
+ invalidate() {
137
+ entryCount = -1;
138
+ },
139
+ render(width: number) {
140
+ const entries = ctx.sessionManager.getEntries();
141
+ const count = entries.length;
142
+ if (count !== entryCount) {
143
+ totals = footerUsage(entries);
144
+ entryCount = count;
145
+ }
146
+ const branch = footerData.getGitBranch();
147
+ const name = ctx.sessionManager.getSessionName();
148
+ const cwd =
149
+ ctx.cwd === homedir()
150
+ ? "~"
151
+ : ctx.cwd.startsWith(homedir() + "/")
152
+ ? "~" + ctx.cwd.slice(homedir().length)
153
+ : ctx.cwd;
154
+ const location = cwd + (branch ? ` (${branch})` : "") + (name ? ` • ${name}` : "");
155
+ const parts: string[] = [];
156
+ if (totals.input) parts.push(`↑${tokens(totals.input)}`);
157
+ if (totals.output) parts.push(`↓${tokens(totals.output)}`);
158
+ if (totals.cacheRead) parts.push(`R${tokens(totals.cacheRead)}`);
159
+ if (totals.cacheWrite) parts.push(`W${tokens(totals.cacheWrite)}`);
160
+ if ((totals.cacheRead || totals.cacheWrite) && totals.cacheHit !== undefined)
161
+ parts.push(`CH${totals.cacheHit.toFixed(1)}%`);
162
+ // Pi's own usage and each child's own usage are disjoint. Never aggregate a parent's descendants twice.
163
+ const subscription =
164
+ ctx.model &&
165
+ (ctx.model.provider === "kimi-coding" || ctx.modelRegistry?.isUsingOAuth(ctx.model));
166
+ parts.push(`$${(totals.cost + subagentCost()).toFixed(3)}${subscription ? " (sub)" : ""}`);
167
+ const context = ctx.getContextUsage();
168
+ if (context) {
169
+ const text = `${context.percent === null ? "?" : context.percent.toFixed(1) + "%"}/${tokens(context.contextWindow)}`;
170
+ parts.push(
171
+ theme.fg(
172
+ (context.percent ?? 0) > 90
173
+ ? "error"
174
+ : (context.percent ?? 0) > 70
175
+ ? "warning"
176
+ : "dim",
177
+ text,
178
+ ),
179
+ );
180
+ }
181
+ const left = truncateToWidth(parts.join(" "), width, "");
182
+ let right = ctx.model?.id ?? "no-model";
183
+ if (ctx.model?.reasoning) right += ` • ${ctx.thinkingLevel ?? "off"}`;
184
+ if (footerData.getAvailableProviderCount() > 1 && ctx.model) {
185
+ const withProvider = `(${ctx.model.provider}) ${right}`;
186
+ if (visibleWidth(left) + 2 + visibleWidth(withProvider) <= width) right = withProvider;
187
+ }
188
+ const available = width - visibleWidth(left) - 2;
189
+ const stats =
190
+ available > 0
191
+ ? left +
192
+ " ".repeat(
193
+ Math.max(2, width - visibleWidth(left) - Math.min(available, visibleWidth(right))),
194
+ ) +
195
+ truncateToWidth(right, available, "")
196
+ : left;
197
+ const lines = [truncateToWidth(theme.fg("dim", location), width), theme.fg("dim", stats)];
198
+ const statuses = [...footerData.getExtensionStatuses()]
199
+ .sort(([a], [b]) => a.localeCompare(b))
200
+ .map(([, text]) =>
201
+ text
202
+ .replace(/[\r\n\t]/g, " ")
203
+ .replace(/ +/g, " ")
204
+ .trim(),
205
+ );
206
+ if (statuses.length)
207
+ lines.push(truncateToWidth(theme.fg("dim", statuses.join(" ")), width));
208
+ return lines;
209
+ },
210
+ };
211
+ });
212
+ return () => requestRender?.();
213
+ }
@@ -8,6 +8,7 @@ import {
8
8
  } from "./dialog.ts";
9
9
  import {
10
10
  DEFAULT_MANAGER_SETTINGS,
11
+ type CostDisplayMode,
11
12
  LOADER_STYLES,
12
13
  type LoaderStyle,
13
14
  loadManagerSaveScope,
@@ -117,6 +118,24 @@ const WIDGET_MODE_OPTIONS = [
117
118
  const WIDGET_MODE_HELP =
118
119
  "Full: detailed agent status rows above the input box.\nMinimal: one-line status counts and cumulative input/output tokens for active (starting/running) agents.\nSave and apply to update the widget immediately.";
119
120
 
121
+ const COST_DISPLAY_OPTIONS = [
122
+ {
123
+ id: "pi-footer-event",
124
+ label: "pi-footer event",
125
+ help: "Publish settled subagent-only USD via pi-footer:update-widget with Widget ID subagent_cost. Add a Pi Event Value widget manually and enable Raw value only. Without an external /footer, retain the combined-cost fallback.",
126
+ },
127
+ {
128
+ id: "pi-footer-status",
129
+ label: "pi-footer status key",
130
+ help: "Publish settled subagent-only USD under status key subagent_cost for pi-footer’s Extension Status selector, including $0.0000 before any cost settles. Does not replace your footer.",
131
+ },
132
+ {
133
+ id: "pi-status",
134
+ label: "Pi status only",
135
+ help: "Only update Pi’s status with total USD cost: main session + all settled subagents. pi-footer modes show subagent-only cost. No pi-footer events or custom footer. Third-party footers may also consume this status key.",
136
+ },
137
+ ] as const;
138
+
120
139
  const MODEL_SELECTION_OPTIONS = [
121
140
  {
122
141
  id: "pick-first-available",
@@ -207,6 +226,12 @@ async function configureAgentsDialog(
207
226
  value: WIDGET_MODE_OPTIONS.find((mode) => mode.id === draft.widgetMode)!.label,
208
227
  help: WIDGET_MODE_HELP,
209
228
  },
229
+ {
230
+ id: "costDisplay",
231
+ label: "[labs] Cost display",
232
+ value: COST_DISPLAY_OPTIONS.find((mode) => mode.id === draft.costDisplay)!.label,
233
+ help: "Choose pi-footer event, pi-footer status key (default), or Pi status only. ID: subagent_cost. pi-footer modes: settled subagent-only USD. Pi status: main session + all settled subagents; publishes on session start and as soon as a subagent starts. Save to apply immediately.",
234
+ },
210
235
  {
211
236
  id: "nerdFontIcons",
212
237
  label: "[labs] Nerd Font icons",
@@ -306,6 +331,12 @@ async function configureAgentsDialog(
306
331
  });
307
332
  if (WIDGET_MODE_OPTIONS.some((option) => option.id === mode))
308
333
  draft.widgetMode = mode as WidgetMode;
334
+ } else if (action === "costDisplay") {
335
+ const mode = await dialogMenu(ctx, "[labs] Cost display", [...COST_DISPLAY_OPTIONS], {
336
+ selectedId: draft.costDisplay,
337
+ });
338
+ if (COST_DISPLAY_OPTIONS.some((option) => option.id === mode))
339
+ draft.costDisplay = mode as CostDisplayMode;
309
340
  } else if (action === "nerdFontIcons") {
310
341
  draft.nerdFontIcons = !draft.nerdFontIcons;
311
342
  } else if (action === "loaderStyle") {