@narumitw/pi-starship 0.34.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,9 +8,9 @@ A native Pi footer configured with Starship-style TOML. It parses and renders fo
8
8
 
9
9
  ## ✨ Features
10
10
 
11
- - Automatically creates a readable Tokyo Night configuration on first session start.
11
+ - Uses a readable built-in Tokyo Night configuration until the user explicitly saves settings.
12
12
  - Starship-style root/module formats, conditional groups, `$all`, styles, and palettes.
13
- - Pi modules for model, thinking, activity, context, tokens, cost, turn, and extension statuses.
13
+ - Pi modules for model, thinking, activity, context, tokens, prompt cache, cost, turn, and extension statuses.
14
14
  - Cached Git branch, commit, operation state, line metrics, detailed status, and linked-worktree identity.
15
15
  - Opt-in package, language, development-shell, deployment, cloud, and execution-context modules.
16
16
  - Width-aware `$fill` alignment for native multiline left/right layouts.
@@ -40,7 +40,7 @@ The only configuration source is:
40
40
  <getAgentDir()>/pi-starship.toml
41
41
  ```
42
42
 
43
- On the first session start, the extension atomically creates this file from its readable Tokyo Night default. It never overwrites an existing document, including a malformed one. If initialization fails, the built-in configuration remains active and the failure is reported as a warning.
43
+ When this file is absent, the extension uses its readable Tokyo Night default without creating the file or parent directory. The first successful settings save creates it atomically. Existing malformed documents are never overwritten.
44
44
 
45
45
  The extension does **not** read project overrides, `pi-statusline.json`, `PI_STATUSLINE_PRESET`, or `~/.config/starship.toml`, and does not migrate statusline settings.
46
46
 
@@ -57,7 +57,7 @@ The **Advanced** menu is one level deep and contains configuration details plus
57
57
  ### 📝 Example
58
58
 
59
59
  ```toml
60
- format = "$brand$provider$model$thinking\n$directory$git_branch$git_status\n$activity$context$tokens$cost$time$turn\n$extension_status"
60
+ format = "$brand$provider$model$thinking\n$directory$git_branch$git_status\n$activity$context$tokens$cache$cost$time$turn\n$extension_status"
61
61
  palette = "tokyo-night"
62
62
 
63
63
  [palettes.tokyo-night]
@@ -75,6 +75,16 @@ disabled = false
75
75
  format = "([ $text ]($style))"
76
76
  style = "fg:custom"
77
77
 
78
+ [context]
79
+ format = "[$symbol $percentage/$window ]($style)"
80
+
81
+ [cache]
82
+ format = "[$symbol (R$read )(W$write )(CH$rate )]($style)"
83
+ disabled = false
84
+
85
+ [cost]
86
+ format = "[ $symbol \\$$cost( $subscription) ]($style)"
87
+
78
88
  [git_branch]
79
89
  format = "[ $symbol$branch$pr ]($style)"
80
90
 
@@ -155,7 +165,8 @@ An invalid root format falls back to the built-in root format. An invalid module
155
165
  | `activity` | `$symbol`, `$state`, `$tool`, `$count`, `$text` | Active tools, streaming, completion, or idle |
156
166
  | `context` | `$symbol`, `$percentage`, `$tokens`, `$window` | Context-window use |
157
167
  | `tokens` | `$symbol`, `$input`, `$output`, `$total` | Token totals |
158
- | `cost` | `$symbol`, `$cost` | Session cost |
168
+ | `cache` | `$symbol`, `$rate`, `$read`, `$write` | Prompt-cache reads, writes, and latest hit rate; disabled by default |
169
+ | `cost` | `$symbol`, `$cost`, `$subscription` | Session cost and optional `(sub)` marker |
159
170
  | `time` | `$symbol`, `$time` | Current local time |
160
171
  | `turn` | `$symbol`, `$count` | User turn count |
161
172
  | `package` | `$symbol`, `$version`, `$source` | Direct project manifest version |
@@ -184,6 +195,25 @@ An invalid root format falls back to the built-in root format. An invalid module
184
195
  | `fill` | `$symbol` | Flexible width-aware root-layout marker |
185
196
  | `extension_status` | `$symbol`, `$statuses`, `$count` | Pi extension statuses |
186
197
 
198
+ ### Usage semantics
199
+
200
+ - `tokens`, `cache`, and `cost` total every usage-bearing session entry, matching Pi's native footer:
201
+ assistant messages, nested-LLM tool results, compactions, and branch summaries, including abandoned
202
+ branches retained in the session.
203
+ - Cache `$read` and `$write` are cumulative. `$rate` uses only the latest assistant prompt:
204
+ `cacheRead / (input + cacheRead + cacheWrite) * 100`. The module is empty when Pi has reported no
205
+ cache reads or writes.
206
+ - `cache` is disabled by default, but the built-in root format already contains `$cache`; users who
207
+ inherit that format can enable it with only `[cache] disabled = false`. A custom root format must
208
+ reference `$cache` or `$all` normally.
209
+ - Context `$percentage` uses native one-decimal precision. For a native-style display, use
210
+ `format = "[$symbol $percentage/$window ]($style)"` under `[context]`; the module name remains
211
+ `context`, not `context_usage`.
212
+ - Subscription-backed OAuth models and `kimi-coding` set cost `$subscription` to `(sub)`. The dollar
213
+ value is usage cost, not proof of an amount billed under a subscription.
214
+ - Pi's public extension API does not expose the current auto-compaction toggle, so pi-starship cannot
215
+ reliably provide the native `(auto)` marker.
216
+
187
217
  `git_worktree` is empty in the primary worktree. In a linked worktree it defaults to the top-level directory name; use `$path` when the full absolute path is needed.
188
218
 
189
219
  `git_commit`, `git_state`, and `git_metrics` are intentionally not present in the built-in root format. Add their variables to `format` to opt in; also set `[git_metrics].disabled = false`, matching Starship's opt-in metrics default. `$tag` resolves only an exact tag on HEAD and is queried only when the configured `git_commit` format references it.
@@ -322,7 +352,7 @@ shell modules, or expose unrestricted `env_var` behavior. JVM/.NET, other long-t
322
352
  alternative VCS, system-monitor, and additional DevOps modules remain demand-gated; the first-wave
323
353
  review found no issue/discussion evidence for a coherent follow-up batch, so no second wave is added.
324
354
 
325
- Pi-native model, context, cost, Git metrics, and activity remain owned by the existing modules. The
355
+ Pi-native model, context, cache, cost, Git metrics, and activity remain owned by the existing modules. The
326
356
  lifecycle design rejects provider-specific duplicates and ambiguous `turn_duration`/`last_result`
327
357
  modules until separately approved semantics exist.
328
358
 
@@ -336,6 +366,7 @@ Keep `extension_status` last in the catalog so earlier modules can consume exten
336
366
 
337
367
  - `src/index.ts` — Pi package entrypoint.
338
368
  - `src/pi-starship.ts` — extension lifecycle, cached refresh binding, live preview, and footer.
369
+ - `src/usage.ts` — native-aligned session usage and cache aggregation.
339
370
  - `src/commands.ts` — goal-oriented menu, preview/confirmation, diagnostics, and compatibility routes.
340
371
  - `src/config.ts` — TOML loading, draft validation, defaults, atomic persistence, and rollback.
341
372
  - `src/format/` — native format/style parser and renderer.
@@ -345,7 +376,8 @@ Keep `extension_status` last in the catalog so earlier modules can consume exten
345
376
 
346
377
  ## 🔎 Keywords
347
378
 
348
- Pi Coding Agent, Starship statusline, Starship TOML, terminal footer, native statusline, Pi extension
379
+ Pi Coding Agent, Starship statusline, Starship TOML, terminal footer, native statusline, prompt cache,
380
+ cache hit rate, Pi extension
349
381
 
350
382
  ## 📄 License
351
383
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-starship",
3
- "version": "0.34.0",
3
+ "version": "0.37.0",
4
4
  "description": "Native Starship-style TOML statusline for the Pi coding agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/commands.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  atomicSaveConfigDocument,
12
12
  BUILT_IN_EXAMPLE,
13
13
  type LoadedStarshipConfig,
14
+ removeConfigDocumentIfMatches,
14
15
  validateConfigDocument,
15
16
  } from "./config.js";
16
17
 
@@ -264,7 +265,7 @@ async function reviewAndApply(
264
265
  try {
265
266
  options.apply(saved, ctx);
266
267
  } catch (error) {
267
- const rollbackError = restorePreviousConfiguration(ctx, options, previous);
268
+ const rollbackError = restorePreviousConfiguration(ctx, options, previous, saved);
268
269
  ctx.ui.notify(
269
270
  rollbackError
270
271
  ? `Footer settings could not be applied: ${safeText(formatError(error))}. Restoring the previous configuration also failed: ${safeText(formatError(rollbackError))}.`
@@ -292,12 +293,16 @@ function restorePreviousConfiguration(
292
293
  ctx: ExtensionCommandContext,
293
294
  options: StarshipCommandOptions,
294
295
  previous: LoadedStarshipConfig,
296
+ saved: LoadedStarshipConfig,
295
297
  ): unknown {
296
298
  try {
297
- if (previous.rawDocument === undefined) {
298
- throw new Error("The previous settings document is unavailable");
299
+ if (saved.rawDocument === undefined || saved.fileIdentity === undefined) {
300
+ throw new Error("The saved settings document identity is unavailable");
301
+ }
302
+ removeConfigDocumentIfMatches(options.settingsPath, saved.rawDocument, saved.fileIdentity);
303
+ if (previous.rawDocument !== undefined) {
304
+ (options.restore ?? atomicRestoreConfigDocument)(options.settingsPath, previous.rawDocument);
299
305
  }
300
- (options.restore ?? atomicRestoreConfigDocument)(options.settingsPath, previous.rawDocument);
301
306
  options.apply(previous, ctx);
302
307
  return undefined;
303
308
  } catch (error) {
package/src/config.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import {
3
3
  existsSync,
4
- linkSync,
4
+ lstatSync,
5
5
  mkdirSync,
6
6
  readFileSync,
7
7
  renameSync,
@@ -69,6 +69,7 @@ export interface LoadedStarshipConfig {
69
69
  source: "built-in" | "user";
70
70
  settingsPath: string;
71
71
  rawDocument?: string;
72
+ fileIdentity?: { dev: number; ino: number };
72
73
  diagnostics: ConfigDiagnostic[];
73
74
  }
74
75
 
@@ -88,6 +89,7 @@ $git_status\
88
89
  $activity\
89
90
  $context\
90
91
  $tokens\
92
+ $cache\
91
93
  [](fg:runtime bg:meter)\
92
94
  $cost\
93
95
  $time\
@@ -157,7 +159,7 @@ export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
157
159
  try {
158
160
  rawDocument = readFileSync(settingsPath, "utf8");
159
161
  } catch (error) {
160
- if (!existsSync(settingsPath)) {
162
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && !existsSync(settingsPath)) {
161
163
  return {
162
164
  config: cloneBuiltInConfig(),
163
165
  source: "built-in",
@@ -194,48 +196,6 @@ export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
194
196
  };
195
197
  }
196
198
 
197
- interface InitialFileSystem {
198
- mkdirSync: typeof mkdirSync;
199
- writeFileSync: typeof writeFileSync;
200
- linkSync: typeof linkSync;
201
- rmSync: typeof rmSync;
202
- }
203
-
204
- export function loadOrCreateStarshipConfig(
205
- settingsPath: string,
206
- overrides: Partial<InitialFileSystem> = {},
207
- ): LoadedStarshipConfig {
208
- const loaded = loadStarshipConfig(settingsPath);
209
- if (loaded.source === "user" || loaded.diagnostics.length > 0) return loaded;
210
-
211
- const fs = { mkdirSync, writeFileSync, linkSync, rmSync, ...overrides };
212
- const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
213
- try {
214
- fs.mkdirSync(dirname(settingsPath), { recursive: true });
215
- fs.writeFileSync(tempPath, BUILT_IN_EXAMPLE, { encoding: "utf8", flag: "wx" });
216
- try {
217
- fs.linkSync(tempPath, settingsPath);
218
- } catch (error) {
219
- if (isAlreadyExistsError(error)) return loadStarshipConfig(settingsPath);
220
- throw error;
221
- }
222
- return loadStarshipConfig(settingsPath);
223
- } catch (error) {
224
- return {
225
- ...loaded,
226
- diagnostics: [
227
- diagnostic("warning", "", `Unable to create default settings: ${formatError(error)}`),
228
- ],
229
- };
230
- } finally {
231
- try {
232
- fs.rmSync(tempPath, { force: true });
233
- } catch {
234
- // Best-effort cleanup must not replace the initialization result.
235
- }
236
- }
237
- }
238
-
239
199
  export function normalizeConfig(value: unknown): {
240
200
  config: StarshipConfig;
241
201
  diagnostics: ConfigDiagnostic[];
@@ -472,8 +432,10 @@ export function atomicSaveConfigDocument(
472
432
  overrides: Partial<AtomicFileSystem> = {},
473
433
  ): LoadedStarshipConfig {
474
434
  const validated = validateConfigDocument(settingsPath, rawDocument);
475
- atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
476
- return validated;
435
+ return {
436
+ ...validated,
437
+ fileIdentity: atomicWriteConfigDocument(settingsPath, rawDocument, overrides),
438
+ };
477
439
  }
478
440
 
479
441
  export function atomicRestoreConfigDocument(
@@ -484,17 +446,58 @@ export function atomicRestoreConfigDocument(
484
446
  atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
485
447
  }
486
448
 
449
+ export function removeConfigDocumentIfMatches(
450
+ settingsPath: string,
451
+ expectedRawDocument: string,
452
+ expectedIdentity: { dev: number; ino: number },
453
+ overrides: Pick<Partial<AtomicFileSystem>, "rmSync"> = {},
454
+ ) {
455
+ const quarantinePath = join(
456
+ dirname(settingsPath),
457
+ `.${CONFIG_FILE_NAME}.${randomUUID()}.rollback`,
458
+ );
459
+ const before = lstatSync(settingsPath);
460
+ if (before.dev !== expectedIdentity.dev || before.ino !== expectedIdentity.ino) {
461
+ throw new Error("Starship settings changed concurrently; the newer file was preserved");
462
+ }
463
+ renameSync(settingsPath, quarantinePath);
464
+ const quarantined = lstatSync(quarantinePath);
465
+ const quarantinedSavedFile =
466
+ quarantined.isFile() &&
467
+ !quarantined.isSymbolicLink() &&
468
+ quarantined.dev === expectedIdentity.dev &&
469
+ quarantined.ino === expectedIdentity.ino;
470
+ if (quarantinedSavedFile && readFileSync(quarantinePath, "utf8") === expectedRawDocument) {
471
+ (overrides.rmSync ?? rmSync)(quarantinePath);
472
+ return;
473
+ }
474
+ if (quarantinedSavedFile && !pathEntryExists(settingsPath)) {
475
+ try {
476
+ renameSync(quarantinePath, settingsPath);
477
+ } catch {
478
+ // Keep the quarantine for recovery when its atomic restoration fails.
479
+ }
480
+ }
481
+ throw new Error("Starship settings changed concurrently; the newer file was preserved");
482
+ }
483
+
487
484
  function atomicWriteConfigDocument(
488
485
  settingsPath: string,
489
486
  rawDocument: string,
490
487
  overrides: Partial<AtomicFileSystem>,
491
- ) {
488
+ ): { dev: number; ino: number } {
492
489
  const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
490
+ const replaceExisting = pathEntryExists(settingsPath);
493
491
  fs.mkdirSync(dirname(settingsPath), { recursive: true });
494
492
  const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
495
493
  try {
496
494
  fs.writeFileSync(tempPath, rawDocument, { encoding: "utf8", flag: "wx" });
495
+ const info = lstatSync(tempPath);
496
+ if (!replaceExisting && pathEntryExists(settingsPath)) {
497
+ throw new Error(`${CONFIG_FILE_NAME} was created concurrently; reopen settings and retry.`);
498
+ }
497
499
  fs.renameSync(tempPath, settingsPath);
500
+ return { dev: info.dev, ino: info.ino };
498
501
  } finally {
499
502
  try {
500
503
  fs.rmSync(tempPath, { force: true });
@@ -648,8 +651,14 @@ function diagnostic(
648
651
  return { severity, path, message };
649
652
  }
650
653
 
651
- function isAlreadyExistsError(error: unknown): boolean {
652
- return error instanceof Error && "code" in error && error.code === "EEXIST";
654
+ function pathEntryExists(path: string): boolean {
655
+ try {
656
+ lstatSync(path);
657
+ return true;
658
+ } catch (error) {
659
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
660
+ throw error;
661
+ }
653
662
  }
654
663
 
655
664
  function formatError(error: unknown): string {
@@ -0,0 +1,23 @@
1
+ import { formatCount } from "./helpers.js";
2
+ import { defineModule } from "./types.js";
3
+
4
+ export const cacheModule = defineModule({
5
+ name: "cache",
6
+ variables: ["symbol", "rate", "read", "write"],
7
+ defaults: {
8
+ format: "[$symbol (CH$rate )]($style)",
9
+ symbol: "📦",
10
+ style: "fg:runtime_fg bg:runtime",
11
+ disabled: true,
12
+ },
13
+ values: ({ runtime }) => {
14
+ const { cacheRead, cacheWrite, latestCacheHitRate } = runtime.tokenTotals;
15
+ if (cacheRead === 0 && cacheWrite === 0) return undefined;
16
+ const rate = latestCacheHitRate === undefined ? "" : `${latestCacheHitRate.toFixed(1)}%`;
17
+ return {
18
+ rate,
19
+ read: cacheRead > 0 ? formatCount(cacheRead) : "",
20
+ write: cacheWrite > 0 ? formatCount(cacheWrite) : "",
21
+ };
22
+ },
23
+ });
@@ -1,5 +1,6 @@
1
1
  import { activityModule } from "./activity.js";
2
2
  import { brandModule } from "./brand.js";
3
+ import { cacheModule } from "./cache.js";
3
4
  import { cloudModules } from "./cloud.js";
4
5
  import { contextModule } from "./context.js";
5
6
  import { costModule } from "./cost.js";
@@ -46,6 +47,7 @@ export const MODULE_DEFINITIONS = [
46
47
  activityModule,
47
48
  contextModule,
48
49
  tokensModule,
50
+ cacheModule,
49
51
  costModule,
50
52
  timeModule,
51
53
  turnModule,
@@ -13,7 +13,7 @@ export const contextModule = defineModule({
13
13
  values: ({ runtime }) => {
14
14
  const percent = runtime.contextUsage?.percent;
15
15
  return {
16
- percentage: percent === null || percent === undefined ? "?" : `${percent.toFixed(0)}%`,
16
+ percentage: percent === null || percent === undefined ? "?" : `${percent.toFixed(1)}%`,
17
17
  tokens: formatCount(runtime.contextUsage?.tokens ?? 0),
18
18
  window: formatCount(runtime.contextUsage?.contextWindow ?? 0),
19
19
  };
@@ -2,14 +2,17 @@ import { defineModule } from "./types.js";
2
2
 
3
3
  export const costModule = defineModule({
4
4
  name: "cost",
5
- variables: ["symbol", "cost"],
5
+ variables: ["symbol", "cost", "subscription"],
6
6
  defaults: {
7
- format: "[ $symbol \\$$cost ]($style)",
7
+ format: "[ $symbol \\$$cost( $subscription) ]($style)",
8
8
  symbol: "💸",
9
9
  style: "fg:meter_fg bg:meter",
10
10
  disabled: false,
11
11
  },
12
- values: ({ runtime }) => ({ cost: formatCost(runtime.tokenTotals.cost) }),
12
+ values: ({ runtime }) => ({
13
+ cost: formatCost(runtime.tokenTotals.cost),
14
+ subscription: runtime.usingSubscription ? "(sub)" : "",
15
+ }),
13
16
  });
14
17
 
15
18
  function formatCost(value: number): string {
@@ -78,7 +78,15 @@ export interface StarshipRuntimeSnapshot {
78
78
  tokens?: number | null;
79
79
  contextWindow?: number | null;
80
80
  };
81
- tokenTotals: { input: number; output: number; cost: number };
81
+ tokenTotals: {
82
+ input: number;
83
+ output: number;
84
+ cacheRead: number;
85
+ cacheWrite: number;
86
+ cost: number;
87
+ latestCacheHitRate?: number;
88
+ };
89
+ usingSubscription: boolean;
82
90
  gitBranch: string | null;
83
91
  gitBranchDetails?: GitBranchSnapshot;
84
92
  gitCommit?: GitCommitSnapshot;
@@ -9,7 +9,6 @@ import { wrapTextWithAnsi } from "@earendil-works/pi-tui";
9
9
  import { registerStarshipCommand } from "./commands.js";
10
10
  import {
11
11
  type LoadedStarshipConfig,
12
- loadOrCreateStarshipConfig,
13
12
  loadStarshipConfig,
14
13
  type StarshipConfig,
15
14
  settingsFilePath,
@@ -31,6 +30,7 @@ import {
31
30
  type WorkspaceRefreshInput,
32
31
  workspaceSnapshotEqual,
33
32
  } from "./runtime/workspace.js";
33
+ import { summarizeFooterUsage } from "./usage.js";
34
34
 
35
35
  const REFRESH_INTERVAL_MS = 30_000;
36
36
  const EVENT_DEBOUNCE_MS = 250;
@@ -237,7 +237,7 @@ export default function piStarship(pi: ExtensionAPI) {
237
237
  });
238
238
 
239
239
  pi.on("session_start", (_event, ctx) => {
240
- loaded = loadOrCreateStarshipConfig(configPath);
240
+ loaded = loadStarshipConfig(configPath);
241
241
  if (loaded.diagnostics.length > 0 && (ctx.mode === "tui" || ctx.hasUI)) {
242
242
  ctx.ui.notify(formatDiagnostics(loaded), "warning");
243
243
  }
@@ -395,7 +395,8 @@ function runtimeSnapshot(
395
395
  isStreaming: runtime.isStreaming,
396
396
  lastCompletedTool: runtime.lastCompletedTool,
397
397
  contextUsage: ctx.getContextUsage() ?? undefined,
398
- tokenTotals: tokenTotals(ctx),
398
+ tokenTotals: summarizeFooterUsage(ctx.sessionManager.getEntries()),
399
+ usingSubscription: isSubscriptionBacked(ctx),
399
400
  gitBranch: runtime.git?.branch?.name ?? footerData.getGitBranch(),
400
401
  gitBranchDetails: runtime.git?.branch,
401
402
  gitCommit: runtime.git?.commit,
@@ -416,16 +417,12 @@ function userTurnCount(ctx: ExtensionContext): number {
416
417
  .filter((entry) => entry.type === "message" && entry.message.role === "user").length;
417
418
  }
418
419
 
419
- function tokenTotals(ctx: ExtensionContext): { input: number; output: number; cost: number } {
420
- const totals = { input: 0, output: 0, cost: 0 };
421
- for (const entry of ctx.sessionManager.getBranch()) {
422
- if (entry.type !== "message" || entry.message.role !== "assistant") continue;
423
- const usage = entry.message.usage;
424
- totals.input += usage.input ?? 0;
425
- totals.output += usage.output ?? 0;
426
- totals.cost += usage.cost?.total ?? 0;
427
- }
428
- return totals;
420
+ function isSubscriptionBacked(ctx: ExtensionContext): boolean {
421
+ const model = ctx.model;
422
+ return (
423
+ model !== undefined &&
424
+ (model.provider === "kimi-coding" || ctx.modelRegistry.isUsingOAuth(model))
425
+ );
429
426
  }
430
427
 
431
428
  function formatDiagnostics(loaded: LoadedStarshipConfig): string {
package/src/usage.ts ADDED
@@ -0,0 +1,53 @@
1
+ import type { SessionEntry } from "@earendil-works/pi-coding-agent";
2
+
3
+ interface UsageLike {
4
+ input?: number;
5
+ output?: number;
6
+ cacheRead?: number;
7
+ cacheWrite?: number;
8
+ cost?: { total?: number };
9
+ }
10
+
11
+ export interface FooterUsageSummary {
12
+ input: number;
13
+ output: number;
14
+ cacheRead: number;
15
+ cacheWrite: number;
16
+ cost: number;
17
+ latestCacheHitRate?: number;
18
+ }
19
+
20
+ export function summarizeFooterUsage(entries: readonly SessionEntry[]): FooterUsageSummary {
21
+ const totals: FooterUsageSummary = {
22
+ input: 0,
23
+ output: 0,
24
+ cacheRead: 0,
25
+ cacheWrite: 0,
26
+ cost: 0,
27
+ };
28
+
29
+ for (const entry of entries) {
30
+ let usage: UsageLike | undefined;
31
+ if (entry.type === "message" && entry.message.role === "assistant") {
32
+ usage = entry.message.usage;
33
+ const input = usage.input ?? 0;
34
+ const cacheRead = usage.cacheRead ?? 0;
35
+ const cacheWrite = usage.cacheWrite ?? 0;
36
+ const promptTokens = input + cacheRead + cacheWrite;
37
+ totals.latestCacheHitRate = promptTokens > 0 ? (cacheRead / promptTokens) * 100 : undefined;
38
+ } else if (entry.type === "message" && entry.message.role === "toolResult") {
39
+ usage = entry.message.usage;
40
+ } else if (entry.type === "compaction" || entry.type === "branch_summary") {
41
+ usage = entry.usage;
42
+ }
43
+ if (!usage) continue;
44
+
45
+ totals.input += usage.input ?? 0;
46
+ totals.output += usage.output ?? 0;
47
+ totals.cacheRead += usage.cacheRead ?? 0;
48
+ totals.cacheWrite += usage.cacheWrite ?? 0;
49
+ totals.cost += usage.cost?.total ?? 0;
50
+ }
51
+
52
+ return totals;
53
+ }