@ferris1225/pi-subagents 4.3.29 → 4.3.31

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/CHANGELOG.md CHANGED
@@ -3,6 +3,26 @@
3
3
  Release notes for `@ferris1225/pi-subagents`. Only the most recent releases
4
4
  are kept here; every published version is preserved as a GitHub Release.
5
5
 
6
+ ## 4.3.31
7
+
8
+ - Write the config on first start instead of prompting. A missing
9
+ `pi-subagents.json` is created with both roles enabled and no model overrides,
10
+ so scout and artisan follow the main model immediately. Session start announces
11
+ `/subagents-setup` once; the file's presence keeps later sessions silent. The
12
+ first-run confirm dialog is gone.
13
+
14
+ ## 4.3.30
15
+
16
+ - Restore pi's own footer. The extension no longer replaces the built-in
17
+ consumption line with a per-model cost footer, so session spend is shown
18
+ exactly as pi reports it.
19
+ - Ask for configuration on a fresh install. When `pi-subagents.json` does not
20
+ exist, session start announces `/subagents-setup` and offers to open the
21
+ wizard immediately instead of only printing a hint.
22
+ - The full setup asks each enabled role's thinking level right after its model,
23
+ the same model-then-thinking order as _Configure an agent_, instead of leaving
24
+ the role default unexamined.
25
+
6
26
  ## 4.3.29
7
27
 
8
28
  - Remove the leftover `steward` and `sentinel` routing. Those roles are no
package/README.md CHANGED
@@ -13,6 +13,15 @@ is clear, and delegation will actually reduce cost or improve completion quality
13
13
 
14
14
  ## What's new
15
15
 
16
+ **4.3.31** — a first start writes `pi-subagents.json` instead of prompting. Both
17
+ roles are enabled with no model overrides, so scout and artisan follow the main
18
+ model immediately; session start announces `/subagents-setup` once, and later
19
+ sessions stay silent because the file itself is the marker.
20
+
21
+ **4.3.30** — pi's own footer is back: the per-model cost footer is removed, so
22
+ pi's built-in consumption line shows unchanged. The wizard asks each role's model
23
+ and immediately its thinking level.
24
+
16
25
  **4.3.29** — the retired `steward` and `sentinel` roles lose their leftover
17
26
  routing rules: a custom file with either name is now an ordinary custom role.
18
27
 
@@ -148,9 +157,11 @@ Pi's extension list shows `@ferris1225/pi-subagents` without an internal source-
148
157
  Open pi and run `/subagents-setup`. The original menu flow lets you enable or
149
158
  disable roles, configure one role's model and thinking level, or run the full setup
150
159
  again. Each screen uses the usual arrow-key/Enter/Esc navigation, and model lists
151
- remain searchable. Fresh installs select both roles. A newly shipped built-in is
152
- surfaced once without being re-enabled after you deliberately turn it off. Then ask
153
- for work:
160
+ remain searchable. A fresh install writes a default config at session start — both
161
+ roles enabled, both following the main model — and announces the command once; the
162
+ full setup asks each enabled role's model, then its thinking level. A newly shipped
163
+ built-in is surfaced once without being re-enabled after you deliberately turn it
164
+ off. Then ask for work:
154
165
 
155
166
  ```text
156
167
  Map how authentication works, fix the refresh race, and run the tests.
@@ -388,7 +399,7 @@ The TUI widget renders one line per active run in fixed identity columns —
388
399
  status icon, right-aligned `#id`, padded agent name, then the task label — so
389
400
  every label starts at the same column, with the live activity dimmed after
390
401
  `↳` on its own line and the rest of the telemetry flowing inline after ` · `: the
391
- worktree badge, wait state, token flow in the footer vocabulary (`↑` input, `↓`
402
+ worktree badge, wait state, token flow in pi's footer vocabulary (`↑` input, `↓`
392
403
  output, `R`/`W` cache read/write), cost, full `provider/model`, current effective
393
404
  `think:<level>`, and seconds-precision elapsed. A live run renders
394
405
  two lines: what it is — agent, task, usage, model, thinking, elapsed —
@@ -410,30 +421,6 @@ for shared-checkout write serialization, or `starting`. The widget is
410
421
  capped at ten lines: when many runs are live, extra runs collapse into a
411
422
  `… +N more` marker so the editor keeps its space.
412
423
 
413
- ### Per-model cost footer
414
-
415
- In TUI sessions the extension replaces pi's built-in consumption line with a
416
- per-model tally of the main window's own spend, directly under the
417
- current-project line. Models are never merged: each `provider/model` keeps its
418
- own token flow, cost, and — for the current model — context share and
419
- effective thinking level:
420
-
421
- ```text
422
- ~/projs/app (main)
423
- ↑48.1k ↓112.7k R1.9M W302.4k $3.0812 · 41.2%/200.0k zhipu/glm-4.7 • high
424
- anthropic/claude-sonnet-4 ↑12.0k ↓31.2k R410.0k $0.9104
425
- ```
426
-
427
- Settled models rank by spend and cap at three rows (`… +N more models`);
428
- under width pressure a settled row drops its token flow before truncating, so
429
- `model $cost` always survives. Sub-agent spend is deliberately not folded in:
430
- children report their own usage per run when they settle, and pi would
431
- otherwise attribute it to one session total — exactly the cross-model merge
432
- this footer exists to avoid. The ledger reseeds from the session file on
433
- reload or session replacement. The footer is removed at session shutdown and
434
- reinstalled with the new session's live context, so switching or reloading
435
- never reuses a stale context from the previous session.
436
-
437
424
  Completions resume the main agent on their own, with a compact block of at most 40
438
425
  lines by default. Longer output (or lines wider than 200 characters) is not inlined
439
426
  at all: the notice states the true size — `137 lines`, or a 200-character clip when
@@ -453,7 +440,7 @@ A `wait: true` dispatch streams its progress onto the tool card while it waits.
453
440
  Usage is no longer attached to the tool result: pi folds tool-result usage into
454
441
  one session total, which merged every model's spend into the main window's
455
442
  consumption line. Instead, each child reports its usage per run — with its full
456
- `provider/model` ref — when it settles, and a parallel group's footer totals
443
+ `provider/model` ref — when it settles, and a parallel group's totals
457
444
  are grouped per model, never summed across them:
458
445
 
459
446
  ```text
@@ -504,14 +491,17 @@ search snippets, records material dates/versions, and marks uncertainty.
504
491
 
505
492
  `/subagents-setup` opens the original settings menu: enable or disable roles,
506
493
  configure one enabled role's model and thinking level, or walk through a full
507
- re-setup. `Esc` moves back through the menu stack, and model lists support fuzzy
494
+ re-setup. A full re-setup asks each role's model and then its thinking level, in
495
+ that order. `Esc` moves back through the menu stack, and model lists support fuzzy
508
496
  search. The enable menu discovers built-ins and actual custom role files in the configured
509
497
  scope, including roles never configured before. Project files require Pi's project trust.
510
498
  Config-only names are not role definitions and never appear in the enable or configure
511
499
  picker. Saving an enable selection or full setup discards unavailable role names and their
512
500
  model/thinking settings; no retired-name aliases or configuration migration are applied.
513
- To start over, remove `pi-subagents.json` and run `/subagents-setup` again. Other settings live in
514
- `~/.pi/agent/pi-subagents.json` (following `PI_CODING_AGENT_DIR`):
501
+ The file is created on first start, and its presence is what keeps later sessions
502
+ silent. To start over, delete it and run `/subagents-setup`; the next session writes
503
+ the defaults again. Settings live in `~/.pi/agent/pi-subagents.json` (following
504
+ `PI_CODING_AGENT_DIR`):
515
505
 
516
506
  ```json
517
507
  {
package/index.ts CHANGED
@@ -8,8 +8,8 @@
8
8
  * - execution/ — process queue, RPC transport/control, and model handoff
9
9
  * - lifecycle/ — durable threads, restoration, controls, and delivery
10
10
  * - isolation/ — Git worktrees, recovery, and temporary-state hygiene
11
- * - presentation/ — announcements, cost footer/ledger, formatting, monitor,
12
- * and the active-run widget
11
+ * - presentation/ — announcements, formatting, monitor, and the active-run
12
+ * widget
13
13
  *
14
14
  * Also registers the `/subagents-setup` command and a `before_agent_start` hook
15
15
  * that installs the delegation directive as replaceable prompt sections so the
@@ -31,8 +31,6 @@ import { createRuntime } from "./src/lifecycle/runtime.ts";
31
31
  import { bootstrapDurableState } from "./src/lifecycle/thread-restore.ts";
32
32
  import { registerLookupTools } from "./src/lifecycle/tools.ts";
33
33
  import { registerAnnouncements } from "./src/presentation/announcements.ts";
34
- import { registerMainCostTracking } from "./src/presentation/cost-ledger.ts";
35
- import { clearCostFooter } from "./src/presentation/cost-footer.ts";
36
34
  import { matchRunIds } from "./src/presentation/format.ts";
37
35
  import { clearActiveRunsWidget } from "./src/presentation/widget.ts";
38
36
 
@@ -66,13 +64,11 @@ export default function (pi: ExtensionAPI): void {
66
64
 
67
65
  pi.on("session_shutdown", async (_event, ctx) => {
68
66
  clearActiveRunsWidget(ctx);
69
- clearCostFooter(ctx);
70
67
  await runtime.shutdown();
71
68
  });
72
69
 
73
70
  registerSubagentTool(pi, runtime);
74
71
  registerLookupTools(pi, runtime);
75
- registerMainCostTracking(pi);
76
72
 
77
73
  pi.registerCommand("subagents-setup", {
78
74
  description: "Configure pi-subagents: agents, models, and per-role thinking",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "4.3.29",
3
+ "version": "4.3.31",
4
4
  "description": "A managed sub-agent team for pi: lightweight scout research and artisan implementation, one-shot runs, read-only status, and Git worktree isolation.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -126,10 +126,6 @@ export const DEFAULT_CONFIG: SubagentsConfig = {
126
126
  idleTimeoutSec: DEFAULT_IDLE_TIMEOUT_SEC,
127
127
  };
128
128
 
129
- export const FIRST_RUN_SETUP_HINT =
130
- "Run /subagents-setup to choose enabled roles, models, and thinking levels. " +
131
- "Scout does lightweight read-only research. Artisan implements one substantial change.";
132
-
133
129
  export function getConfigPath(agentDir: string = getAgentDir()): string {
134
130
  return join(agentDir, CONFIG_FILE_NAME);
135
131
  }
@@ -8,7 +8,7 @@
8
8
 
9
9
  import { stat } from "node:fs/promises";
10
10
  import type { Api, Model } from "@earendil-works/pi-ai";
11
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
11
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
12
12
  import { discoverAgents } from "../delegation/agents.ts";
13
13
  import {
14
14
  AGENT_PROFILES,
@@ -47,7 +47,7 @@ const THINKING_LEVEL_HINTS: Record<ThinkingLevel, string> = {
47
47
  max: "strongest reasoning",
48
48
  };
49
49
 
50
- function setupAgentNames(ctx: ExtensionCommandContext, config: SubagentsConfig): string[] {
50
+ function setupAgentNames(ctx: ExtensionContext, config: SubagentsConfig): string[] {
51
51
  const { agents } = discoverAgents(ctx.cwd, {
52
52
  scope: config.agentScope,
53
53
  projectTrusted: ctx.isProjectTrusted?.() === true,
@@ -82,7 +82,7 @@ async function configExists(configPath: string): Promise<boolean> {
82
82
  }
83
83
 
84
84
  async function pickEnabledAgents(
85
- ctx: ExtensionCommandContext,
85
+ ctx: ExtensionContext,
86
86
  config: SubagentsConfig,
87
87
  ): Promise<string[] | undefined> {
88
88
  const names = setupAgentNames(ctx, config);
@@ -96,7 +96,7 @@ async function pickEnabledAgents(
96
96
  }
97
97
 
98
98
  async function pickConfiguredModel(
99
- ctx: ExtensionCommandContext,
99
+ ctx: ExtensionContext,
100
100
  title: string,
101
101
  configuredRef: string | undefined,
102
102
  escNote: string,
@@ -117,7 +117,7 @@ async function pickConfiguredModel(
117
117
  }
118
118
 
119
119
  async function pickAgentModel(
120
- ctx: ExtensionCommandContext,
120
+ ctx: ExtensionContext,
121
121
  agentName: string,
122
122
  agentModels: Readonly<Record<string, string>>,
123
123
  escNote = "cancels this setup pass",
@@ -133,7 +133,7 @@ async function pickAgentModel(
133
133
  }
134
134
 
135
135
  function effectiveModelForChoice(
136
- ctx: ExtensionCommandContext,
136
+ ctx: ExtensionContext,
137
137
  agentName: string,
138
138
  choice: string,
139
139
  agentModels: Readonly<Record<string, string>>,
@@ -145,7 +145,7 @@ function effectiveModelForChoice(
145
145
 
146
146
  /** The role default is marked; picking it clears a stored override. */
147
147
  async function pickAgentStrength(
148
- ctx: ExtensionCommandContext,
148
+ ctx: ExtensionContext,
149
149
  agentName: string,
150
150
  model: Model<Api> | undefined,
151
151
  current: ThinkingLevel | undefined,
@@ -177,7 +177,7 @@ async function pickAgentStrength(
177
177
  }
178
178
 
179
179
  async function pickAgentToConfigure(
180
- ctx: ExtensionCommandContext,
180
+ ctx: ExtensionContext,
181
181
  enabledAgents: readonly string[],
182
182
  ): Promise<string | undefined> {
183
183
  if (enabledAgents.length === 0) {
@@ -206,7 +206,7 @@ interface ConfiguredAgentChoice {
206
206
  }
207
207
 
208
208
  async function configureOneAgent(
209
- ctx: ExtensionCommandContext,
209
+ ctx: ExtensionContext,
210
210
  config: SubagentsConfig,
211
211
  ): Promise<ConfiguredAgentChoice | undefined> {
212
212
  // Canonical order (built-ins first), whatever order the config file saved.
@@ -258,42 +258,49 @@ function applyThinkingChoice(
258
258
  return next;
259
259
  }
260
260
 
261
- async function introduceSetup(ctx: ExtensionCommandContext): Promise<boolean> {
261
+ async function introduceSetup(ctx: ExtensionContext): Promise<boolean> {
262
262
  const lines = BUILTIN_AGENT_NAMES.map((name) => {
263
263
  const profile = AGENT_PROFILES[name];
264
264
  return `${name} — ${profile.summary}. ${profile.remark}`;
265
265
  });
266
266
  const defaults = BUILTIN_AGENT_NAMES.map((name) => `${name} ${roleThinkingLevel(name)}`).join(", ");
267
267
  ctx.ui.notify(
268
- `pi-subagents: ${lines.join(" ")} Pick a model for each role next. Thinking defaults per role (${defaults}); change it on a role when you want.`,
268
+ `pi-subagents: ${lines.join(" ")} Pick a model and its thinking level for each role next. Thinking starts at the role default (${defaults}).`,
269
269
  "info",
270
270
  );
271
271
  const choice = await ctx.ui.select("How to configure pi-subagents", [
272
- "Continue — pick a model for each role (thinking has a role default you can change later)",
272
+ "Continue — pick a model, then its thinking level, for each role",
273
273
  ]);
274
274
  return choice !== undefined;
275
275
  }
276
276
 
277
- async function runFullSetup(ctx: ExtensionCommandContext, configPath: string, base: SubagentsConfig): Promise<boolean> {
277
+ async function runFullSetup(ctx: ExtensionContext, configPath: string, base: SubagentsConfig): Promise<boolean> {
278
278
  if (!(await introduceSetup(ctx))) return false;
279
279
 
280
280
  const enabled = await pickEnabledAgents(ctx, base);
281
281
  if (enabled === undefined) return false;
282
282
 
283
283
  let agentModels = keepAgentEntries(base.agentModels, enabled);
284
+ let agentThinkingLevels = keepAgentEntries(base.agentThinkingLevels, enabled);
284
285
  for (const agentName of enabled) {
285
286
  const profile = agentProfile(agentName);
286
287
  if (profile) ctx.ui.notify(`${agentName}: ${profile.remark}`, "info");
287
288
  const choice = await pickAgentModel(ctx, agentName, agentModels);
288
289
  if (choice === undefined) return false;
289
290
  agentModels = applyAgentModelChoice(agentModels, agentName, choice);
291
+ // Thinking follows the model immediately: the supported levels come from
292
+ // the model just picked, so this is the only moment the choice is exact.
293
+ const model = effectiveModelForChoice(ctx, agentName, choice, agentModels);
294
+ const strength = await pickAgentStrength(ctx, agentName, model, agentThinkingLevels[agentName]);
295
+ if (strength === undefined) return false;
296
+ agentThinkingLevels = applyThinkingChoice(agentThinkingLevels, agentName, strength, model);
290
297
  }
291
298
 
292
299
  const next: SubagentsConfig = {
293
300
  enabledAgents: enabled,
294
301
  knownAgents: setupAgentNames(ctx, base),
295
302
  agentModels,
296
- agentThinkingLevels: keepAgentEntries(base.agentThinkingLevels, enabled),
303
+ agentThinkingLevels,
297
304
  maxResultLines: base.maxResultLines,
298
305
  maxConcurrentAgents: base.maxConcurrentAgents,
299
306
  agentScope: base.agentScope,
@@ -301,18 +308,18 @@ async function runFullSetup(ctx: ExtensionCommandContext, configPath: string, ba
301
308
  };
302
309
  await saveConfig(next, configPath);
303
310
  ctx.ui.notify(
304
- `pi-subagents saved to ${configPath}. Role thinking defaults apply; open Configure an agent to change one.`,
311
+ `pi-subagents saved to ${configPath}. Models and thinking levels are set; open Configure an agent to change one.`,
305
312
  "info",
306
313
  );
307
314
  return true;
308
315
  }
309
316
 
310
- async function runMenu(ctx: ExtensionCommandContext, configPath: string, config: SubagentsConfig): Promise<void> {
317
+ async function runMenu(ctx: ExtensionContext, configPath: string, config: SubagentsConfig): Promise<void> {
311
318
  while (true) {
312
319
  const choice = await ctx.ui.select("pi-subagents settings", [
313
320
  "Enable/disable agents — choose which roles are available",
314
321
  "Configure an agent — model and thinking, with its job on the row",
315
- "Full re-setup — walk through the team and pick models again",
322
+ "Full re-setup — pick each role's model and thinking again",
316
323
  ]);
317
324
  if (choice === undefined) return;
318
325
  if (choice.startsWith("Full")) {
@@ -361,7 +368,7 @@ async function runMenu(ctx: ExtensionCommandContext, configPath: string, config:
361
368
  }
362
369
 
363
370
  /** Entry point for the /subagents-setup command. */
364
- export async function runSetup(ctx: ExtensionCommandContext, configPath: string = getConfigPath()): Promise<void> {
371
+ export async function runSetup(ctx: ExtensionContext, configPath: string = getConfigPath()): Promise<void> {
365
372
  if (ctx.mode !== "tui") {
366
373
  ctx.ui.notify("/subagents-setup requires Pi's interactive TUI.", "error");
367
374
  return;
@@ -377,3 +384,21 @@ export async function runSetup(ctx: ExtensionCommandContext, configPath: string
377
384
  ctx.ui.notify(`pi-subagents setup failed: ${errorMessage(error)}`, "error");
378
385
  }
379
386
  }
387
+
388
+ /**
389
+ * First start: write the shipped defaults so both roles work immediately — no
390
+ * model overrides means each child follows the main model — then announce the
391
+ * command that customizes them. The file is the marker: once it exists, later
392
+ * sessions stay silent.
393
+ */
394
+ export async function ensureDefaultConfig(
395
+ ctx: ExtensionContext,
396
+ configPath: string = getConfigPath(),
397
+ ): Promise<void> {
398
+ if (await configExists(configPath)) return;
399
+ await saveConfig(DEFAULT_CONFIG, configPath);
400
+ ctx.ui.notify(
401
+ `pi-subagents: wrote ${configPath} with scout and artisan enabled; both follow the main model. Run /subagents-setup to pick a model and thinking level per role.`,
402
+ "info",
403
+ );
404
+ }
@@ -1,13 +1,11 @@
1
1
  /** Session-start recovery, stale-model cleanup, and progress-surface installation. */
2
2
 
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
- import { existsSync } from "node:fs";
5
- import { FIRST_RUN_SETUP_HINT, loadConfig, saveConfig } from "../configuration/config.ts";
4
+ import { loadConfig, saveConfig } from "../configuration/config.ts";
6
5
  import { availableModelsInScope, filterUnavailableModelOverrides } from "../configuration/models.ts";
6
+ import { ensureDefaultConfig } from "../configuration/setup.ts";
7
7
  import { announceRecoveryRecords, relocateRecoveryManifest } from "../isolation/recovery.ts";
8
8
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
9
- import { seedCostLedgerFromSession } from "./cost-ledger.ts";
10
- import { installCostFooter } from "./cost-footer.ts";
11
9
  import { installActiveRunsWidget } from "./widget.ts";
12
10
 
13
11
  /** Drop unavailable model overrides back to dynamic main-model routing. */
@@ -36,9 +34,7 @@ async function removeUnavailableAgentModels(
36
34
 
37
35
  export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime): void {
38
36
  pi.on("session_start", async (_event, ctx) => {
39
- if (!existsSync(runtime.configPath)) {
40
- ctx.ui.notify(`pi-subagents: ${FIRST_RUN_SETUP_HINT}`, "info");
41
- }
37
+ await ensureDefaultConfig(ctx, runtime.configPath);
42
38
  await relocateRecoveryManifest(runtime.configPath);
43
39
  await announceRecoveryRecords(runtime.configPath, ctx);
44
40
  await removeUnavailableAgentModels(ctx, runtime);
@@ -53,13 +49,9 @@ export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime
53
49
  "info",
54
50
  );
55
51
  }
56
- // The widget and the per-model cost footer are TUI-only. Seeding first
57
- // means the first footer render already carries the reloaded session's
58
- // per-model spend.
52
+ // The active-run widget is TUI-only.
59
53
  if (ctx.mode !== "tui") return;
60
- seedCostLedgerFromSession(ctx);
61
54
  installActiveRunsWidget(ctx);
62
- installCostFooter(ctx);
63
55
  });
64
56
 
65
57
  // Compaction failures are otherwise silent in long orchestration sessions
@@ -1,190 +0,0 @@
1
- /**
2
- * Persistent cost footer: replaces pi's built-in consumption line with a
3
- * per-model tally of the main window's own spend, so models are never summed
4
- * into one number — each `provider/model` keeps its own token flow, cost, and
5
- * context share. The current-project line stays first, exactly where pi put
6
- * it; extension statuses stay last.
7
- *
8
- * Sub-agent spend is intentionally absent: children report per-run usage with
9
- * their model ref when they settle, and injecting it here (or into the parent
10
- * session totals) is what mixed unrelated models' costs before.
11
- */
12
-
13
- import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
14
- import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
15
- import { isAbsolute, relative, resolve, sep } from "node:path";
16
- import { stripVTControlCharacters } from "node:util";
17
- import { costLedger, type ModelSpendRow } from "./cost-ledger.ts";
18
- import { formatTokens, formatUsageTokens } from "./monitor.ts";
19
- import type { UsageStats } from "../execution/rpc-control.ts";
20
-
21
- /** Footer data as injected by pi's `setFooter` factory; only the read-only
22
- * surface exists in types, so keep the structural shape local. */
23
- interface FooterData {
24
- getGitBranch(): string | null;
25
- getExtensionStatuses(): ReadonlyMap<string, string>;
26
- onBranchChange(callback: () => void): () => void;
27
- }
28
-
29
- /** Live context owned by the installed footer's session. */
30
- type RenderContext = Partial<Pick<ExtensionContext, "sessionManager" | "getContextUsage" | "model" | "thinkingLevel">>;
31
-
32
- /** Minimum gap between the stats left side and the right-aligned model. */
33
- const MIN_PADDING = 2;
34
- /** Settled-model rows shown after the current one; anything older collapses
35
- * into one overflow marker so the footer's height stays bounded no matter how
36
- * many models a session switched through. */
37
- const MAX_SETTLED_MODEL_ROWS = 3;
38
-
39
- /** Home-relative project path, matching the built-in footer's `~` form. */
40
- function formatProjectPath(cwd: string, home: string | undefined): string {
41
- if (!home) return cwd;
42
- const resolvedCwd = resolve(cwd);
43
- const resolvedHome = resolve(home);
44
- const relativeToHome = relative(resolvedHome, resolvedCwd);
45
- const isInsideHome = relativeToHome === "" ||
46
- (relativeToHome !== ".." && !relativeToHome.startsWith(`..${sep}`) && !isAbsolute(relativeToHome));
47
- if (!isInsideHome) return cwd;
48
- return relativeToHome === "" ? "~" : `~${sep}${relativeToHome}`;
49
- }
50
-
51
- /** The `12%/200k` context share of the current model; colored by pressure
52
- * like the built-in footer did. */
53
- function contextPart(theme: Theme, usage: { percent?: number | null; contextWindow?: number } | undefined): string {
54
- if (!usage || !usage.contextWindow || usage.contextWindow <= 0) return "";
55
- const percent = usage.percent === null || usage.percent === undefined
56
- ? "?"
57
- : usage.percent.toFixed(1);
58
- const display = `${percent}%/${formatTokens(usage.contextWindow)}`;
59
- if (typeof usage.percent === "number" && usage.percent > 90) return theme.fg("error", display);
60
- if (typeof usage.percent === "number" && usage.percent > 70) return theme.fg("warning", display);
61
- return display;
62
- }
63
-
64
- function spendUsage(spend: ModelSpendRow["spend"]): UsageStats {
65
- return { ...spend, contextTokens: 0, turns: 0 };
66
- }
67
-
68
- /** One `↑in ↓out R r W w $cost` flow for a model row; zero components drop
69
- * out, but a model with no spend at all still shows its bare `$0.0000` so the
70
- * row reads as a tally rather than an empty label. */
71
- function spendPart(spend: ModelSpendRow["spend"]): string {
72
- return [formatUsageTokens(spendUsage(spend)), `$${spend.cost.toFixed(4)}`].filter(Boolean).join(" ");
73
- }
74
-
75
- /** Current-model row: stats left, model identity right-aligned — the built-in
76
- * footer's geometry, applied to the ledger row. */
77
- function currentModelLine(
78
- row: ModelSpendRow,
79
- theme: Theme,
80
- width: number,
81
- ctx: RenderContext,
82
- ): string {
83
- const parts = [spendPart(row.spend)];
84
- const context = contextPart(theme, ctx.getContextUsage?.());
85
- if (context) parts.push(context);
86
- let left = parts.join(" ");
87
- if (visibleWidth(left) > width) left = truncateToWidth(left, width, "…");
88
-
89
- let right = row.model;
90
- if (ctx.model?.reasoning && ctx.thinkingLevel) {
91
- right = ctx.thinkingLevel === "off" ? `${right} • thinking off` : `${right} • ${ctx.thinkingLevel}`;
92
- }
93
- // The provider prefix duplicates the ref's own `provider/` half, so keep it
94
- // only for the bare-id shape a providerless ref produces.
95
- const leftWidth = visibleWidth(left);
96
- if (leftWidth + MIN_PADDING + visibleWidth(right) > width) {
97
- const available = width - leftWidth - MIN_PADDING;
98
- if (available <= 0) return theme.fg("dim", left);
99
- right = truncateToWidth(right, available, "");
100
- }
101
- const padding = " ".repeat(Math.max(MIN_PADDING, width - leftWidth - visibleWidth(right)));
102
- return theme.fg("dim", `${left}${padding}${right}`);
103
- }
104
-
105
- /** Settled-model row: the model ref leads because that is the line's whole
106
- * point — which model, what it cost. Under width pressure the token flow drops
107
- * first (the cost is the headline), then the line truncates. */
108
- function settledModelLine(row: ModelSpendRow, theme: Theme, width: number): string {
109
- const full = `${row.model} ${spendPart(row.spend)}`;
110
- if (visibleWidth(full) <= width) return theme.fg("dim", full);
111
- const bare = `${row.model} $${row.spend.cost.toFixed(4)}`;
112
- if (visibleWidth(bare) <= width) return theme.fg("dim", bare);
113
- return truncateToWidth(theme.fg("dim", full), width, "…");
114
- }
115
-
116
- /** Render the replacement footer: project line first, one line per model the
117
- * main window spent on (current model with context share), extension
118
- * statuses last — the same slots the built-in footer used. Settled models are
119
- * ranked by spend and capped, so a session that switched through many models
120
- * never grows the footer without bound. */
121
- export function renderCostFooter(
122
- width: number,
123
- theme: Theme,
124
- footerData: FooterData | undefined,
125
- ctx: RenderContext,
126
- ): string[] {
127
- const sessionManager = ctx.sessionManager;
128
- const lines: string[] = [];
129
-
130
- let project = formatProjectPath(sessionManager?.getCwd() ?? "", process.env.HOME || process.env.USERPROFILE);
131
- const branch = footerData?.getGitBranch();
132
- if (branch) project = `${project} (${branch})`;
133
- const sessionName = sessionManager?.getSessionName();
134
- if (sessionName) project = `${project} • ${sessionName}`;
135
- lines.push(truncateToWidth(theme.fg("dim", project), width, theme.fg("dim", "…")));
136
-
137
- const rows = costLedger.snapshot();
138
- if (rows.length > 0) {
139
- const current = rows.find((row) => row.current);
140
- if (current) lines.push(currentModelLine(current, theme, width, ctx));
141
- const settled = rows
142
- .filter((row) => !row.current)
143
- .sort((left, right) => right.spend.cost - left.spend.cost);
144
- for (const row of settled.slice(0, MAX_SETTLED_MODEL_ROWS)) {
145
- lines.push(settledModelLine(row, theme, width));
146
- }
147
- const hidden = settled.length - MAX_SETTLED_MODEL_ROWS;
148
- if (hidden > 0) {
149
- lines.push(theme.fg("dim", `… +${hidden} more model${hidden === 1 ? "" : "s"}`));
150
- }
151
- }
152
-
153
- const statuses = footerData?.getExtensionStatuses();
154
- if (statuses && statuses.size > 0) {
155
- const statusLine = [...statuses.entries()]
156
- .sort(([left], [right]) => left.localeCompare(right))
157
- .map(([, text]) => stripVTControlCharacters(text).replace(/[\r\n\t]+/g, " ").replace(/ +/g, " ").trim())
158
- .join(" ");
159
- lines.push(truncateToWidth(statusLine, width, theme.fg("dim", "…")));
160
- }
161
- return lines;
162
- }
163
-
164
- /**
165
- * Replace pi's built-in footer with the per-model cost footer. The factory
166
- * re-renders on ledger updates and git branch changes; context, model, and
167
- * thinking state use Pi's live getters for this session. Shutdown clears the
168
- * footer before Pi invalidates its context.
169
- */
170
- export function installCostFooter(ctx: Pick<ExtensionContext, "mode" | "ui"> & RenderContext): void {
171
- if (ctx.mode !== "tui") return;
172
- ctx.ui.setFooter((tui, theme, footerData) => {
173
- const unsubscribe = [
174
- costLedger.subscribe(() => tui.requestRender()),
175
- footerData.onBranchChange(() => tui.requestRender()),
176
- ];
177
- return {
178
- render: (width: number) => renderCostFooter(width, theme, footerData, ctx),
179
- invalidate() {},
180
- dispose() {
181
- for (const stop of unsubscribe) stop();
182
- },
183
- };
184
- });
185
- }
186
-
187
- /** Restore pi's built-in footer. */
188
- export function clearCostFooter(ctx: Pick<ExtensionContext, "mode" | "ui">): void {
189
- if (ctx.mode === "tui") ctx.ui.setFooter(undefined);
190
- }
@@ -1,185 +0,0 @@
1
- /**
2
- * Per-model spend ledger for the main window's own generation.
3
- *
4
- * Sub-agent runs are deliberately not tracked here: every child reports its
5
- * usage with its model ref when it settles (completion block, widget row,
6
- * per-model completion totals), so mixing its live spend into the parent's
7
- * footer would just re-create the cross-model sum this ledger exists to
8
- * avoid. The ledger covers the main window only — across `/model` switches,
9
- * each model keeps its own tally.
10
- */
11
-
12
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
13
- import { modelRef } from "../configuration/models.ts";
14
-
15
- export interface ModelSpend {
16
- input: number;
17
- output: number;
18
- cacheRead: number;
19
- cacheWrite: number;
20
- cost: number;
21
- }
22
-
23
- export interface ModelSpendRow {
24
- /** Full `provider/model` ref. */
25
- model: string;
26
- /** True while this is the window's current model. */
27
- current: boolean;
28
- spend: ModelSpend;
29
- }
30
-
31
- /** pi Usage shape: numeric token buckets plus a cost that is either already a
32
- * number (child tallies) or the provider object with a `total`. */
33
- interface UsageLike {
34
- input?: unknown;
35
- output?: unknown;
36
- cacheRead?: unknown;
37
- cacheWrite?: unknown;
38
- cost?: unknown;
39
- }
40
-
41
- function emptySpend(): ModelSpend {
42
- return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
43
- }
44
-
45
- /** `provider/model` for a message; falls back to the bare model id when a
46
- * providerless message sneaks through. */
47
- export function messageModelRef(message: { provider?: string; model?: string }): string | undefined {
48
- const model = message.model?.trim();
49
- if (!model) return undefined;
50
- return message.provider?.trim() ? `${message.provider.trim()}/${model}` : model;
51
- }
52
-
53
- function finiteUsage(usage: UsageLike | undefined): ModelSpend {
54
- const num = (value: unknown): number => (typeof value === "number" && Number.isFinite(value) ? value : 0);
55
- const cost = usage?.cost;
56
- return {
57
- input: num(usage?.input),
58
- output: num(usage?.output),
59
- cacheRead: num(usage?.cacheRead),
60
- cacheWrite: num(usage?.cacheWrite),
61
- cost: num(typeof cost === "object" && cost !== null ? (cost as { total?: unknown }).total : cost),
62
- };
63
- }
64
-
65
- export class CostLedger {
66
- private rows = new Map<string, ModelSpend>();
67
- /** First-seen order, so row order is stable between notifications. */
68
- private order: string[] = [];
69
- private currentModel: string | undefined;
70
- private subscribers = new Set<() => void>();
71
-
72
- record(model: string, spend: UsageLike | undefined): void {
73
- const ref = model.trim();
74
- if (!ref) return;
75
- const row = this.rows.get(ref) ?? emptySpend();
76
- const add = finiteUsage(spend);
77
- row.input += add.input;
78
- row.output += add.output;
79
- row.cacheRead += add.cacheRead;
80
- row.cacheWrite += add.cacheWrite;
81
- row.cost += add.cost;
82
- if (!this.rows.has(ref)) this.order.push(ref);
83
- this.rows.set(ref, row);
84
- this.notify();
85
- }
86
-
87
- markCurrentModel(model: string | undefined): void {
88
- const ref = model?.trim() || undefined;
89
- if (ref === this.currentModel) return;
90
- this.currentModel = ref;
91
- this.notify();
92
- }
93
-
94
- getCurrentModel(): string | undefined {
95
- return this.currentModel;
96
- }
97
-
98
- /** Current model first, everything else in first-seen order. A current
99
- * model with no spend yet still gets a zero row so the footer keeps its
100
- * shape from the first render. */
101
- snapshot(): ModelSpendRow[] {
102
- const rows: ModelSpendRow[] = [];
103
- if (this.currentModel) {
104
- rows.push({ model: this.currentModel, current: true, spend: this.rows.get(this.currentModel) ?? emptySpend() });
105
- }
106
- for (const model of this.order) {
107
- if (model === this.currentModel) continue;
108
- rows.push({ model, current: false, spend: this.rows.get(model) ?? emptySpend() });
109
- }
110
- return rows;
111
- }
112
-
113
- reset(): void {
114
- this.rows.clear();
115
- this.order = [];
116
- this.currentModel = undefined;
117
- this.notify();
118
- }
119
-
120
- subscribe(cb: () => void): () => void {
121
- this.subscribers.add(cb);
122
- return () => {
123
- this.subscribers.delete(cb);
124
- };
125
- }
126
-
127
- private notify(): void {
128
- for (const cb of this.subscribers) {
129
- try {
130
- cb();
131
- } catch {
132
- /* subscriber errors must not break accounting */
133
- }
134
- }
135
- }
136
- }
137
-
138
- export const costLedger = new CostLedger();
139
-
140
- /** Wire the main window's own generation into the ledger: assistant messages
141
- * carry the serving model and exact usage, model switches re-key the current
142
- * row, and compaction calls land on the model that made them. */
143
- export function registerMainCostTracking(pi: ExtensionAPI): void {
144
- pi.on("message_end", async (event) => {
145
- const message = (event as { message?: { role?: string; provider?: string; model?: string; usage?: UsageLike } }).message;
146
- if (message?.role !== "assistant") return;
147
- const ref = messageModelRef(message) ?? costLedger.getCurrentModel();
148
- if (!ref) return;
149
- const usage = finiteUsage(message.usage);
150
- costLedger.record(ref, usage);
151
- });
152
-
153
- pi.on("model_select", async (event) => {
154
- costLedger.markCurrentModel(modelRef(event.model));
155
- });
156
-
157
- pi.on("session_compact", async (event, ctx) => {
158
- const usage = (event as { compactionEntry?: { usage?: UsageLike } }).compactionEntry?.usage;
159
- const ref = costLedger.getCurrentModel() ?? (ctx.model ? modelRef(ctx.model) : undefined);
160
- if (usage && ref) costLedger.record(ref, finiteUsage(usage));
161
- });
162
- }
163
-
164
- /** Rebuild the ledger from the persisted session after a reload or session
165
- * switch, then key the current row to the window's model. Compaction and
166
- * branch-summary LLM calls carry no model of their own, so they land on the
167
- * current model — the one that made them. */
168
- export function seedCostLedgerFromSession(ctx: {
169
- sessionManager: { getEntries(): Array<{ type: string; message?: unknown; usage?: UsageLike }> };
170
- model?: { provider: string; id: string } | undefined;
171
- }): void {
172
- costLedger.reset();
173
- costLedger.markCurrentModel(ctx.model ? modelRef(ctx.model) : undefined);
174
- const current = costLedger.getCurrentModel();
175
- for (const entry of ctx.sessionManager.getEntries()) {
176
- if (entry.type === "message") {
177
- const message = entry.message as { role?: string; provider?: string; model?: string; usage?: UsageLike } | undefined;
178
- if (message?.role !== "assistant") continue;
179
- const ref = messageModelRef(message);
180
- if (ref) costLedger.record(ref, finiteUsage(message.usage));
181
- } else if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage && current) {
182
- costLedger.record(current, finiteUsage(entry.usage));
183
- }
184
- }
185
- }