@yandy0725/pi-subagents 0.11.0 → 0.11.1

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 CHANGED
@@ -6,7 +6,8 @@ A [pi](https://pi.dev) extension providing a focused, in-process sub-agent core
6
6
 
7
7
  - **In-process & native** — agents share the same pi runtime: same tool names, calling conventions, and UI patterns
8
8
  - **Parallel background agents** — spawn multiple agents with automatic queuing (configurable concurrency, default 4)
9
- - **Live widget UI** — persistent widget showing animated spinners, live tool activity, token counts, and colored status icons
9
+ - **Live widget UI** — persistent widget showing animated spinners, live tool activity, token counts, USD cost, and colored status icons
10
+ - **Parent-session accounting** — child model usage joins the parent footer, `/session`, and `/usage` totals, including background and resumed agents
10
11
  - **Custom agent types** — define agents in `.pi/agents/<name>.md` with YAML frontmatter: system prompts, model, thinking, tools
11
12
  - **Mid-run steering** — inject messages into running agents to redirect work without restarting
12
13
  - **Session resume** — pick up where an agent left off, preserving full conversation context
package/README.zh.md CHANGED
@@ -6,7 +6,8 @@
6
6
 
7
7
  - **进程内原生** — 代理共享同一 pi 运行时:相同的工具名、调用约定和 UI 模式
8
8
  - **并行后台代理** — 同时启动多个代理,自动排队(可配置并发数,默认 4)
9
- - **实时 Widget UI** — 持久化的编辑器上方组件,带动态旋转指示器、实时工具活动、token 计数和彩色状态图标
9
+ - **实时 Widget UI** — 持久化的编辑器上方组件,带动态旋转指示器、实时工具活动、token 计数、美元花销和彩色状态图标
10
+ - **父会话记账** — 子代理模型用量计入父会话 footer、`/session` 和 `/usage` 总花销,覆盖后台与恢复运行的代理
10
11
  - **自定义代理类型** — 在 `.pi/agents/<name>.md` 中通过 YAML frontmatter 定义:系统提示词、模型、思考等级、工具限制
11
12
  - **运行中转向** — 向运行中的代理注入消息,无需重启即可改变工作方向
12
13
  - **会话恢复** — 从上次中断处继续,保留完整对话上下文
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.11.0",
6
+ "version": "0.11.1",
7
7
  "description": "Focused, in-process sub-agent core for pi — autonomous agents plus a typed API and lifecycle events",
8
8
  "license": "MIT",
9
9
  "repository": {
@@ -2,9 +2,18 @@
2
2
  * parent-snapshot.ts — Capture parent session state as a plain data snapshot.
3
3
  */
4
4
 
5
+ import type { Usage } from "@earendil-works/pi-ai";
5
6
  import { buildParentContext } from "../session/context";
6
7
  import type { SessionContext } from "../types";
7
8
 
9
+ /** One model-attributed child usage delta destined for the parent's session totals. */
10
+ export interface ParentUsageRecord {
11
+ provider: string;
12
+ model: string;
13
+ usage: Usage;
14
+ note?: string;
15
+ }
16
+
8
17
  /**
9
18
  * Plain data snapshot of the parent session state captured at spawn time.
10
19
  * Replaces live `ExtensionContext` references so queued agents don't read stale state.
@@ -19,6 +28,8 @@ export interface ParentSnapshot {
19
28
  find(provider: string, modelId: string): unknown;
20
29
  getAvailable?(): Array<{ provider: string; id: string }>;
21
30
  };
31
+ /** Append child usage to the captured parent session, including background completions. */
32
+ recordUsage?: (entry: ParentUsageRecord) => void;
22
33
  /** Pre-built parent conversation text (when inheritContext was requested). */
23
34
  parentContext?: string;
24
35
  }
@@ -31,11 +42,16 @@ export interface ParentSnapshot {
31
42
  */
32
43
  export function buildParentSnapshot(ctx: SessionContext, inheritContext?: boolean): ParentSnapshot {
33
44
  const parentContext = inheritContext ? buildParentContext(ctx) : undefined;
45
+ const sessionManager = ctx.sessionManager;
46
+ const appendUsage = sessionManager.appendUsage?.bind(sessionManager);
34
47
  return {
35
48
  cwd: ctx.cwd,
36
49
  model: ctx.model,
37
50
 
38
51
  modelRegistry: ctx.modelRegistry!,
52
+ recordUsage: appendUsage
53
+ ? ({ provider, model, usage, note }) => appendUsage("subagent", provider, model, usage, note)
54
+ : undefined,
39
55
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- || intentional: converts empty string to undefined as well as null/undefined
40
56
  parentContext: parentContext || undefined,
41
57
  };
@@ -15,6 +15,7 @@ import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
15
15
  import { Subagent, type SubagentLifecycleObserver } from "../lifecycle/subagent";
16
16
  import type { SubagentSession } from "../lifecycle/subagent-session";
17
17
  import { SubagentState, type SubagentStatus } from "../lifecycle/subagent-state";
18
+ import type { LifetimeUsage } from "../lifecycle/usage";
18
19
 
19
20
  import type { RunConfig } from "../runtime";
20
21
  import type { AgentInvocation, CompactionInfo, ParentSessionInfo, SubagentType, ThinkingLevel } from "../types";
@@ -35,6 +36,8 @@ export interface EvictedSubagent {
35
36
  readonly startedAt: number;
36
37
  readonly completedAt: number | undefined;
37
38
  readonly toolUses: number;
39
+ readonly lifetimeUsage?: Readonly<LifetimeUsage>;
40
+ readonly lifetimeCost?: number;
38
41
  /** Short display model name (always shown; falls back to parent model when unset). */
39
42
  readonly modelName?: string;
40
43
  /** Thinking level when explicitly set (e.g. "high", "off"). */
@@ -346,6 +349,8 @@ function toEvictedSubagent(record: Subagent, outputFile: string): EvictedSubagen
346
349
  startedAt: record.startedAt,
347
350
  completedAt: record.completedAt,
348
351
  toolUses: record.toolUses,
352
+ lifetimeUsage: { ...record.lifetimeUsage },
353
+ lifetimeCost: record.lifetimeCost,
349
354
  modelName: record.invocation?.modelName,
350
355
  thinking: record.thinking,
351
356
  outputFile,
@@ -18,7 +18,7 @@
18
18
  * session-event observer be unit-tested without constructing an executor.
19
19
  */
20
20
 
21
- import type { LifetimeUsage } from "../lifecycle/usage";
21
+ import type { LifetimeUsage, LifetimeUsageDelta } from "../lifecycle/usage";
22
22
  import { addUsage } from "../lifecycle/usage";
23
23
  import type { SessionMessage } from "../types";
24
24
 
@@ -70,6 +70,11 @@ export class SubagentState {
70
70
  return this._lifetimeUsage;
71
71
  }
72
72
 
73
+ private _lifetimeCost = 0;
74
+ get lifetimeCost(): number {
75
+ return this._lifetimeCost;
76
+ }
77
+
73
78
  private _compactionCount = 0;
74
79
  get compactionCount(): number {
75
80
  return this._compactionCount;
@@ -107,8 +112,9 @@ export class SubagentState {
107
112
  }
108
113
 
109
114
  /** Accumulate a usage delta into lifetimeUsage. Called by record-observer on message_end. */
110
- addUsage(delta: { input: number; output: number; cacheWrite: number }): void {
115
+ addUsage(delta: LifetimeUsageDelta): void {
111
116
  addUsage(this._lifetimeUsage, delta);
117
+ this._lifetimeCost += delta.cost?.total ?? 0;
112
118
  }
113
119
 
114
120
  /** Increment compaction count. Called by record-observer on compaction_end. */
@@ -12,11 +12,11 @@
12
12
  import type { Model } from "@earendil-works/pi-ai";
13
13
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
14
14
  import type { CreateSubagentSessionParams } from "../lifecycle/create-subagent-session";
15
- import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
15
+ import type { ParentSnapshot, ParentUsageRecord } from "../lifecycle/parent-snapshot";
16
16
  import { RunListeners } from "../lifecycle/run-listeners";
17
17
  import type { SubagentSession, TurnLoopResult } from "../lifecycle/subagent-session";
18
18
  import { SubagentState, type SubagentStatus } from "../lifecycle/subagent-state";
19
- import type { LifetimeUsage } from "../lifecycle/usage";
19
+ import type { LifetimeUsage, LifetimeUsageDelta } from "../lifecycle/usage";
20
20
  import { NotificationState } from "../observation/notification-state";
21
21
  import { subscribeSubagentObserver } from "../observation/record-observer";
22
22
  import type { RunConfig } from "../runtime";
@@ -112,6 +112,9 @@ export class Subagent {
112
112
  get lifetimeUsage(): Readonly<LifetimeUsage> {
113
113
  return this.state.lifetimeUsage;
114
114
  }
115
+ get lifetimeCost(): number {
116
+ return this.state.lifetimeCost;
117
+ }
115
118
  get compactionCount(): number {
116
119
  return this.state.compactionCount;
117
120
  }
@@ -290,6 +293,7 @@ export class Subagent {
290
293
  this.listeners.attachObserver(
291
294
  subscribeSubagentObserver(this.subagentSession, this.state, {
292
295
  onCompact: (info) => this.execution.observer?.onCompacted?.(this, info),
296
+ onUsage: (entry) => this.recordParentUsage(entry),
293
297
  onChange: () => this.notifyChange(),
294
298
  }),
295
299
  );
@@ -357,6 +361,7 @@ export class Subagent {
357
361
  this.listeners.attachObserver(
358
362
  subscribeSubagentObserver(subagentSession, this.state, {
359
363
  onCompact: (info) => this.execution.observer?.onCompacted?.(this, info),
364
+ onUsage: (entry) => this.recordParentUsage(entry),
360
365
  onChange: () => this.notifyChange(),
361
366
  }),
362
367
  );
@@ -377,10 +382,14 @@ export class Subagent {
377
382
  }
378
383
 
379
384
  /** Accumulate a usage delta into lifetimeUsage. Called by record-observer on message_end. */
380
- addUsage(delta: { input: number; output: number; cacheWrite: number }): void {
385
+ addUsage(delta: LifetimeUsageDelta): void {
381
386
  this.state.addUsage(delta);
382
387
  }
383
388
 
389
+ private recordParentUsage(entry: ParentUsageRecord): void {
390
+ this.execution.snapshot.recordUsage?.({ ...entry, note: `Subagent ${this.id}: ${this.description}` });
391
+ }
392
+
384
393
  /** Increment compaction count. Called by record-observer on compaction_end. */
385
394
  incrementCompactions(): void {
386
395
  this.state.incrementCompactions();
@@ -9,6 +9,9 @@
9
9
  */
10
10
  export type LifetimeUsage = { input: number; output: number; cacheWrite: number };
11
11
 
12
+ /** Assistant usage may carry cost in addition to the billed-token subset retained for display. */
13
+ export type LifetimeUsageDelta = LifetimeUsage & { cost?: { total: number } };
14
+
12
15
  /** Sum of lifetime usage components, or 0 if undefined. */
13
16
  export function getLifetimeTotal(u?: LifetimeUsage): number {
14
17
  return u ? u.input + u.output + u.cacheWrite : 0;
@@ -11,6 +11,7 @@ export interface NotificationDetails {
11
11
  turnCount: number;
12
12
  maxTurns?: number;
13
13
  totalTokens: number;
14
+ totalCost: number;
14
15
  durationMs: number;
15
16
  outputFile?: string;
16
17
  error?: string;
@@ -47,6 +48,7 @@ export function formatTaskNotification(record: Subagent, resultMaxLen: number):
47
48
  const status = getStatusLabel(record.status, record.error);
48
49
  const durationMs = record.completedAt ? record.completedAt - record.startedAt : 0;
49
50
  const totalTokens = getLifetimeTotal(record.lifetimeUsage);
51
+ const totalCost = record.lifetimeCost;
50
52
  const contextPercent = record.getContextPercent();
51
53
  const ctxXml = contextPercent !== null ? `<context_percent>${Math.round(contextPercent)}</context_percent>` : "";
52
54
  const compactXml = record.compactionCount ? `<compactions>${record.compactionCount}</compactions>` : "";
@@ -67,7 +69,7 @@ export function formatTaskNotification(record: Subagent, resultMaxLen: number):
67
69
  `<status>${escapeXml(status)}</status>`,
68
70
  `<summary>Subagent "${escapeXml(record.description)}" ${record.status}</summary>`,
69
71
  `<result>${escapeXml(resultPreview)}</result>`,
70
- `<usage><total_tokens>${totalTokens}</total_tokens><tool_uses>${record.toolUses}</tool_uses>${ctxXml}${compactXml}<duration_ms>${durationMs}</duration_ms></usage>`,
72
+ `<usage><total_tokens>${totalTokens}</total_tokens><cost_usd>${totalCost}</cost_usd><tool_uses>${record.toolUses}</tool_uses>${ctxXml}${compactXml}<duration_ms>${durationMs}</duration_ms></usage>`,
71
73
  "</task-notification>",
72
74
  ]
73
75
  .filter(Boolean)
@@ -86,6 +88,7 @@ export function buildNotificationDetails(record: Subagent, resultMaxLen: number)
86
88
  turnCount: record.turnCount,
87
89
  maxTurns: record.maxTurns,
88
90
  totalTokens,
91
+ totalCost: record.lifetimeCost,
89
92
  durationMs: record.completedAt ? record.completedAt - record.startedAt : 0,
90
93
  outputFile: record.outputFile,
91
94
  error: record.error,
@@ -9,11 +9,14 @@
9
9
  * the caller forwards itself to its own lifecycle observer via onCompact.
10
10
  */
11
11
 
12
+ import type { ParentUsageRecord } from "../lifecycle/parent-snapshot";
12
13
  import type { SubagentState } from "../lifecycle/subagent-state";
13
14
  import type { CompactionInfo, SubscribableSession } from "../types";
14
15
 
15
16
  export interface SubagentObserverOptions {
16
17
  onCompact?: (info: CompactionInfo) => void;
18
+ /** Forward each child assistant usage delta to the parent session's persisted totals. */
19
+ onUsage?: (entry: ParentUsageRecord) => void;
17
20
  /** Called after every event's state mutation, so consumers always read post-mutation state. */
18
21
  onChange?: () => void;
19
22
  }
@@ -69,6 +72,12 @@ export function subscribeSubagentObserver(
69
72
  input: u.input,
70
73
  output: u.output,
71
74
  cacheWrite: u.cacheWrite,
75
+ cost: u.cost,
76
+ });
77
+ options?.onUsage?.({
78
+ provider: event.message.provider,
79
+ model: event.message.responseModel ?? event.message.model,
80
+ usage: u,
72
81
  });
73
82
  }
74
83
 
@@ -1,6 +1,6 @@
1
1
  import { Text } from "@earendil-works/pi-tui";
2
2
  import type { NotificationDetails } from "../observation/notification";
3
- import { formatMs, formatTokens, formatTurns } from "../ui/display";
3
+ import { formatCost, formatMs, formatTokens, formatTurns } from "../ui/display";
4
4
 
5
5
  /** Narrow theme interface — only the methods the renderer actually calls. */
6
6
  interface RendererTheme {
@@ -40,6 +40,7 @@ export function createNotificationRenderer() {
40
40
  if (d.turnCount > 0) parts.push(formatTurns(d.turnCount, d.maxTurns));
41
41
  if (d.toolUses > 0) parts.push(`${d.toolUses} tool use${d.toolUses === 1 ? "" : "s"}`);
42
42
  if (d.totalTokens > 0) parts.push(formatTokens(d.totalTokens));
43
+ if (d.totalCost > 0) parts.push(formatCost(d.totalCost));
43
44
  if (d.durationMs > 0) parts.push(formatMs(d.durationMs));
44
45
  if (parts.length) {
45
46
  line += `\n ${parts.map((p) => theme.fg("dim", p)).join(` ${theme.fg("dim", "·")} `)}`;
@@ -66,6 +66,8 @@ export class SubagentEventsObserver implements SubagentManagerObserver {
66
66
  modelName: record.modelName,
67
67
  thinking: record.thinking,
68
68
  outputFile: record.outputFile,
69
+ lifetimeUsage: { ...record.lifetimeUsage },
70
+ lifetimeCost: record.lifetimeCost,
69
71
  });
70
72
 
71
73
  // Skip notification if result was already consumed via get_subagent_result.
@@ -130,6 +130,7 @@ export function toSubagentRecord(record: Subagent): SubagentRecord {
130
130
  toolUses: record.toolUses,
131
131
  startedAt: record.startedAt,
132
132
  lifetimeUsage: record.lifetimeUsage,
133
+ lifetimeCost: record.lifetimeCost,
133
134
  compactionCount: record.compactionCount,
134
135
  };
135
136
 
@@ -29,6 +29,7 @@ export interface SubagentRecord {
29
29
  startedAt: number;
30
30
  completedAt?: number;
31
31
  lifetimeUsage: LifetimeUsage;
32
+ lifetimeCost: number;
32
33
  compactionCount: number;
33
34
  /** Short display model name (always shown; falls back to parent model when unset). */
34
35
  modelName?: string;
@@ -69,7 +70,6 @@ export interface SubagentsService {
69
70
 
70
71
  /** Whether any agents are running or queued. */
71
72
  hasRunning(): boolean;
72
-
73
73
  }
74
74
 
75
75
  /** Event channel constants for pi.events subscriptions. */
@@ -18,6 +18,7 @@
18
18
  import { join } from "node:path";
19
19
  import { type CustomEntry, parseSessionEntries } from "@earendil-works/pi-coding-agent";
20
20
  import type { EvictedSubagent } from "../lifecycle/subagent-manager";
21
+ import type { LifetimeUsage } from "../lifecycle/usage";
21
22
  import type { SubagentStatus } from "../lifecycle/subagent-state";
22
23
  import type { SubagentType } from "../types";
23
24
  import { deriveSubagentSessionDir } from "./session-dir";
@@ -39,6 +40,8 @@ interface PersistedSubagentRecord {
39
40
  modelName?: string;
40
41
  thinking?: string;
41
42
  outputFile?: string;
43
+ lifetimeUsage?: LifetimeUsage;
44
+ lifetimeCost?: number;
42
45
  }
43
46
 
44
47
  /**
@@ -103,6 +106,8 @@ export function recoverEvictedSubagents(
103
106
  modelName: data.modelName,
104
107
  thinking: data.thinking,
105
108
  outputFile,
109
+ lifetimeUsage: data.lifetimeUsage,
110
+ lifetimeCost: data.lifetimeCost,
106
111
  });
107
112
  }
108
113
  // Most-recent-first, matching listEvicted()'s ordering.
@@ -1,7 +1,7 @@
1
1
  import type { AgentToolResult } from "@earendil-works/pi-coding-agent";
2
2
  import type { ParentSnapshot } from "../lifecycle/parent-snapshot";
3
3
  import type { AgentSpawnConfig } from "../lifecycle/subagent-manager";
4
- import { buildDetails, formatLifetimeTokens, getStatusNote, textResult } from "../tools/helpers";
4
+ import { buildDetails, formatLifetimeCost, formatLifetimeTokens, getStatusNote, textResult } from "../tools/helpers";
5
5
  import type { ResolvedSpawnConfig } from "../tools/spawn-config";
6
6
  import type { ParentSessionInfo, Subagent } from "../types";
7
7
  import { type AgentDetails, describeActivity, formatMs, SPINNER } from "../ui/display";
@@ -45,6 +45,7 @@ export async function runForeground(
45
45
  ...presentation.detailBase,
46
46
  toolUses,
47
47
  tokens: recordRef ? formatLifetimeTokens(recordRef) : "",
48
+ cost: recordRef ? formatLifetimeCost(recordRef) : "",
48
49
  // Read activity off the record; fall back to safe defaults before onSessionCreated fires
49
50
  turnCount: recordRef?.turnCount ?? 1,
50
51
  maxTurns: recordRef?.maxTurns ?? execution.effectiveMaxTurns,
@@ -107,6 +108,8 @@ export async function runForeground(
107
108
  const durationMs = (record.completedAt ?? Date.now()) - record.startedAt;
108
109
  const statsParts = [`${record.toolUses} tool uses`];
109
110
  if (tokenText) statsParts.push(tokenText);
111
+ const costText = formatLifetimeCost(record);
112
+ if (costText) statsParts.push(costText);
110
113
  return textResult(
111
114
  `${fallbackNote}Agent completed in ${formatMs(durationMs)} (${statsParts.join(", ")})${getStatusNote(record.status)}.\n\n` +
112
115
  (record.result?.trim() ?? "No output."),
@@ -1,7 +1,7 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
3
  import type { AgentConfigLookup } from "../config/agent-types";
4
- import { formatLifetimeTokens, textResult } from "../tools/helpers";
4
+ import { formatLifetimeCost, formatLifetimeTokens, textResult } from "../tools/helpers";
5
5
  import type { Subagent } from "../types";
6
6
  import { formatDuration, getDisplayName } from "../ui/display";
7
7
 
@@ -51,9 +51,11 @@ export class GetResultTool {
51
51
  const displayName = getDisplayName(record.type, this.registry);
52
52
  const duration = formatDuration(record.startedAt, record.completedAt);
53
53
  const tokens = formatLifetimeTokens(record);
54
+ const cost = formatLifetimeCost(record);
54
55
  const contextPercent = record.getContextPercent();
55
56
  const statsParts = [`Tool uses: ${record.toolUses}`];
56
57
  if (tokens) statsParts.push(tokens);
58
+ if (cost) statsParts.push(cost);
57
59
  if (contextPercent !== null) statsParts.push(`Context: ${Math.round(contextPercent)}%`);
58
60
  if (record.compactionCount) statsParts.push(`Compactions: ${record.compactionCount}`);
59
61
  statsParts.push(`Duration: ${duration}`);
@@ -1,6 +1,6 @@
1
1
  import type { AgentConfigLookup } from "../config/agent-types";
2
2
  import { getLifetimeTotal, type LifetimeUsage } from "../lifecycle/usage";
3
- import { type AgentDetails, formatTokens } from "../ui/display";
3
+ import { type AgentDetails, formatCost, formatTokens } from "../ui/display";
4
4
 
5
5
  /** Parenthetical status note for completed agent result text. */
6
6
  export function getStatusNote(status: string): string {
@@ -27,6 +27,7 @@ export function buildDetails(
27
27
  error?: string;
28
28
  id?: string;
29
29
  lifetimeUsage: LifetimeUsage;
30
+ lifetimeCost?: number;
30
31
  /** Live-activity counters — exposed as getters on Subagent (Phase 18 Step 2). */
31
32
  turnCount?: number;
32
33
  maxTurns?: number;
@@ -37,6 +38,7 @@ export function buildDetails(
37
38
  ...base,
38
39
  toolUses: record.toolUses,
39
40
  tokens: formatLifetimeTokens(record),
41
+ cost: formatLifetimeCost(record),
40
42
  turnCount: record.turnCount,
41
43
  maxTurns: record.maxTurns,
42
44
  durationMs: (record.completedAt ?? Date.now()) - record.startedAt,
@@ -58,6 +60,12 @@ export function formatLifetimeTokens(o: { lifetimeUsage: LifetimeUsage }): strin
58
60
  return t > 0 ? formatTokens(t) : "";
59
61
  }
60
62
 
63
+ /** Format an agent's lifetime USD cost, or "" when zero. */
64
+ export function formatLifetimeCost(o: { lifetimeCost?: number }): string {
65
+ const cost = o.lifetimeCost ?? 0;
66
+ return cost > 0 ? formatCost(cost) : "";
67
+ }
68
+
61
69
  /**
62
70
  * Narrow registry interface needed by buildTypeListText.
63
71
  * Extends AgentConfigLookup with the two name-listing methods.
@@ -105,5 +105,6 @@ export function renderStats(details: AgentDetails, theme: Theme): string {
105
105
  }
106
106
  if (details.toolUses > 0) parts.push(`${details.toolUses} tool use${details.toolUses === 1 ? "" : "s"}`);
107
107
  if (details.tokens) parts.push(details.tokens);
108
+ if (details.cost) parts.push(details.cost);
108
109
  return parts.map((p) => theme.fg("dim", p)).join(` ${theme.fg("dim", "\u00B7")} `);
109
110
  }
@@ -1,6 +1,6 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
- import { formatLifetimeTokens, textResult } from "../tools/helpers";
3
+ import { formatLifetimeCost, formatLifetimeTokens, textResult } from "../tools/helpers";
4
4
  import type { Subagent } from "../types";
5
5
 
6
6
  // ---- Deps interfaces ----
@@ -46,9 +46,11 @@ export class SteerTool {
46
46
  );
47
47
  }
48
48
  const tokens = formatLifetimeTokens(record);
49
+ const cost = formatLifetimeCost(record);
49
50
  const contextPercent = record.getContextPercent();
50
51
  const stateParts: string[] = [];
51
52
  if (tokens) stateParts.push(tokens);
53
+ if (cost) stateParts.push(cost);
52
54
  stateParts.push(`${record.toolUses} tool ${record.toolUses === 1 ? "use" : "uses"}`);
53
55
  if (contextPercent !== null) stateParts.push(`context ${Math.round(contextPercent)}% full`);
54
56
  if (record.compactionCount)
package/src/types.ts CHANGED
@@ -2,7 +2,7 @@
2
2
  * types.ts — Type definitions for the subagent system.
3
3
  */
4
4
 
5
- import type { ThinkingLevel } from "@earendil-works/pi-ai";
5
+ import type { ThinkingLevel, Usage } from "@earendil-works/pi-ai";
6
6
  import type { AgentSessionEvent, SessionContext as SdkSessionContext } from "@earendil-works/pi-coding-agent";
7
7
  import type { ModelRegistry } from "./session/model-resolver";
8
8
 
@@ -91,6 +91,8 @@ export interface SessionContext {
91
91
  getSessionFile(): string | undefined;
92
92
  getSessionId(): string;
93
93
  getBranch(): unknown[];
94
+ /** Persist non-context usage so child LLM calls join footer and session totals. */
95
+ appendUsage?(kind: string, provider: string, model: string, usage: Usage, note?: string): unknown;
94
96
  };
95
97
  }
96
98
 
@@ -174,6 +174,7 @@ export class AgentWidget implements SubagentManagerObserver {
174
174
  completedAt: record.completedAt,
175
175
  error: record.error,
176
176
  lifetimeUsage: record.lifetimeUsage,
177
+ lifetimeCost: record.lifetimeCost,
177
178
  compactionCount: record.compactionCount,
178
179
  turnCount: record.turnCount,
179
180
  maxTurns: record.maxTurns,
package/src/ui/display.ts CHANGED
@@ -22,6 +22,8 @@ export interface AgentDetails {
22
22
  subagentType: string;
23
23
  toolUses: number;
24
24
  tokens: string;
25
+ /** Formatted lifetime USD cost, or empty/undefined when no cost has been recorded. */
26
+ cost?: string;
25
27
  durationMs: number;
26
28
  status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error" | "background";
27
29
  /** Human-readable description of what the agent is currently doing. */
@@ -68,6 +70,11 @@ export function formatTokens(count: number): string {
68
70
  return `${count} token`;
69
71
  }
70
72
 
73
+ /** Format USD cost consistently with Pi's session footer. */
74
+ export function formatCost(cost: number): string {
75
+ return `$${cost.toFixed(3)}`;
76
+ }
77
+
71
78
  /**
72
79
  * Token count with optional context-fill % and compaction-count annotations.
73
80
  * Thresholds for percent: <70% dim, 70–85% warning, ≥85% error.
@@ -21,14 +21,21 @@ import {
21
21
  } from "@earendil-works/pi-coding-agent";
22
22
  import type { AgentConfigLookup } from "../config/agent-types";
23
23
  import type { EvictedSubagent } from "../lifecycle/subagent-manager";
24
+ import { getLifetimeTotal, type LifetimeUsage } from "../lifecycle/usage";
24
25
  import type { SubagentStatus } from "../lifecycle/subagent-state";
25
26
  import type { SessionMessage, SubagentType } from "../types";
26
- import { formatDuration, getDisplayName } from "../ui/display";
27
+ import { formatCost, formatDuration, formatTokens, getDisplayName } from "../ui/display";
27
28
 
28
29
  // ─────────────────────────────────────────────────────────────────────────────
29
30
 
31
+ /** Lifetime token/cost fields shared by live records and persisted descriptors. */
32
+ export interface UsageDisplayFields {
33
+ readonly lifetimeUsage?: Readonly<LifetimeUsage>;
34
+ readonly lifetimeCost?: number;
35
+ }
36
+
30
37
  /** The record fields the navigator reads to label and live-source a transcript. */
31
- export interface NavigableSubagent {
38
+ export interface NavigableSubagent extends UsageDisplayFields {
32
39
  readonly id: string;
33
40
  readonly type: SubagentType;
34
41
  readonly description: string;
@@ -57,10 +64,18 @@ export interface NavigableSubagent {
57
64
  */
58
65
  export type NavigationEntry =
59
66
  | { readonly kind: "live"; readonly label: string; readonly record: NavigableSubagent }
60
- | { readonly kind: "evicted"; readonly label: string; readonly outputFile: string; readonly modelName?: string; readonly thinking?: string };
67
+ | {
68
+ readonly kind: "evicted";
69
+ readonly label: string;
70
+ readonly outputFile: string;
71
+ readonly lifetimeUsage?: Readonly<LifetimeUsage>;
72
+ readonly lifetimeCost?: number;
73
+ readonly modelName?: string;
74
+ readonly thinking?: string;
75
+ };
61
76
 
62
77
  /** The fields `buildLabel` reads — shared by a live record and an evicted descriptor. */
63
- interface LabelFields {
78
+ interface LabelFields extends UsageDisplayFields {
64
79
  readonly type: SubagentType;
65
80
  readonly description: string;
66
81
  readonly status: SubagentStatus;
@@ -108,6 +123,8 @@ export function listNavigableAgents(
108
123
  (descriptor): NavigationEntry => ({
109
124
  kind: "evicted",
110
125
  outputFile: descriptor.outputFile,
126
+ lifetimeUsage: descriptor.lifetimeUsage,
127
+ lifetimeCost: descriptor.lifetimeCost,
111
128
  modelName: descriptor.modelName,
112
129
  thinking: descriptor.thinking,
113
130
  label: buildLabel(descriptor, registry, true),
@@ -166,8 +183,18 @@ function buildLabel(fields: LabelFields, registry: AgentConfigLookup, evicted =
166
183
  const name = getDisplayName(fields.type, registry);
167
184
  const duration = formatDuration(fields.startedAt, fields.completedAt);
168
185
  const modelTag = fields.modelName
169
- ? fields.thinking ? ` · ${fields.modelName} (${fields.thinking})` : ` · ${fields.modelName}`
170
- : fields.thinking ? ` · think:${fields.thinking}` : "";
186
+ ? fields.thinking
187
+ ? ` · ${fields.modelName} (${fields.thinking})`
188
+ : ` · ${fields.modelName}`
189
+ : fields.thinking
190
+ ? ` · think:${fields.thinking}`
191
+ : "";
171
192
  const marker = evicted ? " · evicted (snapshot)" : "";
172
- return `${name} (${fields.description}) · ${fields.toolUses} tools · ${fields.status} · ${duration}${modelTag}${marker}`;
193
+ const tokens = getLifetimeTotal(fields.lifetimeUsage);
194
+ const lifetimeCost = fields.lifetimeCost ?? 0;
195
+ const usageParts: string[] = [];
196
+ if (tokens > 0) usageParts.push(formatTokens(tokens));
197
+ if (lifetimeCost > 0) usageParts.push(formatCost(lifetimeCost));
198
+ const usageTag = usageParts.length > 0 ? ` · ${usageParts.join(" · ")}` : "";
199
+ return `${name} (${fields.description}) · ${fields.toolUses} tools${usageTag} · ${fields.status} · ${duration}${modelTag}${marker}`;
173
200
  }
@@ -25,7 +25,8 @@ import {
25
25
  } from "@earendil-works/pi-tui";
26
26
  import type { AgentConfigLookup } from "../config/agent-types";
27
27
  import type { EvictedSubagent } from "../lifecycle/subagent-manager";
28
- import { describeActivity, type Theme } from "../ui/display";
28
+ import { getLifetimeTotal } from "../lifecycle/usage";
29
+ import { describeActivity, formatCost, formatTokens, type Theme } from "../ui/display";
29
30
  import { TranscriptBody } from "../ui/transcript-body";
30
31
  import {
31
32
  fileSnapshotSource,
@@ -33,6 +34,7 @@ import {
33
34
  liveSource,
34
35
  type NavigableSubagent,
35
36
  type TranscriptSource,
37
+ type UsageDisplayFields,
36
38
  } from "../ui/session-navigation";
37
39
 
38
40
  // ─────────────────────────────────────────────────────────────────────────────
@@ -82,6 +84,8 @@ export interface TranscriptOverlayOptions {
82
84
  modelName?: string;
83
85
  /** Thinking level to show alongside model name, or undefined to omit. */
84
86
  thinking?: string;
87
+ /** Read the latest lifetime usage on each render so a running overlay stays current. */
88
+ getUsage?: () => UsageDisplayFields | undefined;
85
89
  }
86
90
 
87
91
  /**
@@ -126,7 +130,17 @@ export class SessionNavigatorHandler {
126
130
  const markdownTheme = getMarkdownTheme();
127
131
  await ui.custom<undefined>(
128
132
  (tui, theme, _keybindings, done) =>
129
- new TranscriptOverlay({ tui, theme, source, done, cwd, markdownTheme, modelName, thinking }),
133
+ new TranscriptOverlay({
134
+ tui,
135
+ theme,
136
+ source,
137
+ done,
138
+ cwd,
139
+ markdownTheme,
140
+ modelName,
141
+ thinking,
142
+ getUsage: () => (entry.kind === "live" ? entry.record : entry),
143
+ }),
130
144
  {
131
145
  overlay: true,
132
146
  overlayOptions: { anchor: "center", width: "90%", maxHeight: `${VIEWPORT_HEIGHT_PCT}%` },
@@ -176,6 +190,7 @@ export class TranscriptOverlay implements Component {
176
190
  private readonly done: (result: undefined) => void;
177
191
  private readonly modelName?: string;
178
192
  private readonly thinking?: string;
193
+ private readonly getUsage?: () => UsageDisplayFields | undefined;
179
194
  private readonly body: TranscriptBody;
180
195
 
181
196
  /** Throttle bookkeeping for coalescing live-source syncs. */
@@ -191,13 +206,24 @@ export class TranscriptOverlay implements Component {
191
206
  /** Running-agent indicator baked into `renderedLines` — invalidates the cache when it changes. */
192
207
  private renderedIndicator = "";
193
208
 
194
- constructor({ tui, theme, source, done, cwd, markdownTheme, modelName, thinking }: TranscriptOverlayOptions) {
209
+ constructor({
210
+ tui,
211
+ theme,
212
+ source,
213
+ done,
214
+ cwd,
215
+ markdownTheme,
216
+ modelName,
217
+ thinking,
218
+ getUsage,
219
+ }: TranscriptOverlayOptions) {
195
220
  this.tui = tui;
196
221
  this.theme = theme;
197
222
  this.source = source;
198
223
  this.done = done;
199
224
  this.modelName = modelName;
200
225
  this.thinking = thinking;
226
+ this.getUsage = getUsage;
201
227
  this.body = new TranscriptBody({
202
228
  tui,
203
229
  cwd,
@@ -279,9 +305,18 @@ export class TranscriptOverlay implements Component {
279
305
 
280
306
  lines.push(hrTop);
281
307
  const modelPart = this.modelName
282
- ? this.thinking ? ` · ${this.modelName} (${this.thinking})` : ` · ${this.modelName}`
308
+ ? this.thinking
309
+ ? ` · ${this.modelName} (${this.thinking})`
310
+ : ` · ${this.modelName}`
283
311
  : "";
284
- const title = modelPart ? `Subagent session${modelPart}` : "Subagent session";
312
+ const usage = this.getUsage?.();
313
+ const tokens = getLifetimeTotal(usage?.lifetimeUsage);
314
+ const lifetimeCost = usage?.lifetimeCost ?? 0;
315
+ const usageParts: string[] = [];
316
+ if (tokens > 0) usageParts.push(formatTokens(tokens));
317
+ if (lifetimeCost > 0) usageParts.push(formatCost(lifetimeCost));
318
+ const usagePart = usageParts.length > 0 ? ` · ${usageParts.join(" · ")}` : "";
319
+ const title = `Subagent session${modelPart}${usagePart}`;
285
320
  lines.push(row(th.bold(title)));
286
321
  lines.push(hrMid);
287
322
 
@@ -426,4 +461,3 @@ export class TranscriptOverlay implements Component {
426
461
  return streaming ? `◍ ${describeActivity(streaming.activeTools, streaming.streamingMessage)}` : "";
427
462
  }
428
463
  }
429
-
@@ -12,6 +12,7 @@ import { getLifetimeTotal } from "../lifecycle/usage";
12
12
  import type { SessionMessage, SubagentType } from "../types";
13
13
  import {
14
14
  describeActivity,
15
+ formatCost,
15
16
  formatMs,
16
17
  formatSessionTokens,
17
18
  formatTurns,
@@ -34,6 +35,7 @@ export interface WidgetAgent {
34
35
  readonly completedAt?: number;
35
36
  readonly error?: string;
36
37
  readonly lifetimeUsage?: Readonly<LifetimeUsage>;
38
+ readonly lifetimeCost?: number;
37
39
  readonly compactionCount: number;
38
40
  // Live activity (folded from the former WidgetActivity — precomputed by AgentWidget)
39
41
  readonly turnCount: number;
@@ -55,6 +57,7 @@ export function renderFinishedLine(agent: WidgetAgent, registry: AgentConfigLook
55
57
  const name = getDisplayName(agent.type, registry);
56
58
  const modeLabel = getPromptModeLabel(agent.type, registry);
57
59
  const duration = formatMs((agent.completedAt ?? Date.now()) - agent.startedAt);
60
+ const lifetimeCost = agent.lifetimeCost ?? 0;
58
61
 
59
62
  let icon: string;
60
63
  let statusText: string;
@@ -85,6 +88,7 @@ export function renderFinishedLine(agent: WidgetAgent, registry: AgentConfigLook
85
88
  }
86
89
  parts.push(formatTurns(agent.turnCount, agent.maxTurns));
87
90
  if (agent.toolUses > 0) parts.push(`${agent.toolUses} tool use${agent.toolUses === 1 ? "" : "s"}`);
91
+ if (lifetimeCost > 0) parts.push(formatCost(lifetimeCost));
88
92
  parts.push(duration);
89
93
 
90
94
  const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
@@ -104,6 +108,7 @@ export function renderRunningLines(
104
108
  const elapsed = formatMs(Date.now() - agent.startedAt);
105
109
 
106
110
  const tokens = getLifetimeTotal(agent.lifetimeUsage);
111
+ const lifetimeCost = agent.lifetimeCost ?? 0;
107
112
  const tokenText = tokens > 0 ? formatSessionTokens(tokens, agent.contextPercent, theme, agent.compactionCount) : "";
108
113
 
109
114
  const parts: string[] = [];
@@ -115,6 +120,7 @@ export function renderRunningLines(
115
120
  parts.push(formatTurns(agent.turnCount, agent.maxTurns));
116
121
  if (agent.toolUses > 0) parts.push(`${agent.toolUses} tool use${agent.toolUses === 1 ? "" : "s"}`);
117
122
  if (tokenText) parts.push(tokenText);
123
+ if (lifetimeCost > 0) parts.push(formatCost(lifetimeCost));
118
124
  parts.push(elapsed);
119
125
  const statsText = parts.join(" · ");
120
126