@narumitw/pi-starship 0.35.0 → 0.38.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
@@ -10,7 +10,7 @@ A native Pi footer configured with Starship-style TOML. It parses and renders fo
10
10
 
11
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.
@@ -52,12 +52,14 @@ Open the interactive menu in TUI mode:
52
52
 
53
53
  Choose **Customize footer** to edit the TOML. Closing the editor validates the draft and opens a width-aware preview; saving happens only after a separate confirmation. Confirmed changes are atomically saved and applied immediately. Editor cancellation, preview cancellation, invalid drafts, write failures, and runtime application failures preserve the previous file and effective footer.
54
54
 
55
- The **Advanced** menu is one level deep and contains configuration details plus **Restore built-in**. Restore shows the concrete built-in preview and requires explicit overwrite confirmation.
55
+ The standard **Advanced** menu is one level deep and contains configuration details plus **Restore
56
+ built-in**. Standard diagnostics, details, and help are Back-navigable detail screens. Restore still
57
+ shows the specialized width-aware preview and requires explicit overwrite confirmation.
56
58
 
57
59
  ### 📝 Example
58
60
 
59
61
  ```toml
60
- format = "$brand$provider$model$thinking\n$directory$git_branch$git_status\n$activity$context$tokens$cost$time$turn\n$extension_status"
62
+ format = "$brand$provider$model$thinking\n$directory$git_branch$git_status\n$activity$context$tokens$cache$cost$time$turn\n$extension_status"
61
63
  palette = "tokyo-night"
62
64
 
63
65
  [palettes.tokyo-night]
@@ -70,11 +72,24 @@ format = "[ $symbol$model ]($style)"
70
72
  symbol = "◆ "
71
73
  style = "bold fg:header_fg bg:header"
72
74
  disabled = false
75
+ truncation_length = 36
76
+ truncation_symbol = "…"
77
+ truncation_direction = "middle"
73
78
 
74
79
  [activity]
75
80
  format = "([ $text ]($style))"
76
81
  style = "fg:custom"
77
82
 
83
+ [context]
84
+ format = "[$symbol $percentage/$window ]($style)"
85
+
86
+ [cache]
87
+ format = "[$symbol (R$read )(W$write )(CH$rate )]($style)"
88
+ disabled = false
89
+
90
+ [cost]
91
+ format = "[ $symbol \\$$cost( $subscription) ]($style)"
92
+
78
93
  [git_branch]
79
94
  format = "[ $symbol$branch$pr ]($style)"
80
95
 
@@ -155,7 +170,8 @@ An invalid root format falls back to the built-in root format. An invalid module
155
170
  | `activity` | `$symbol`, `$state`, `$tool`, `$count`, `$text` | Active tools, streaming, completion, or idle |
156
171
  | `context` | `$symbol`, `$percentage`, `$tokens`, `$window` | Context-window use |
157
172
  | `tokens` | `$symbol`, `$input`, `$output`, `$total` | Token totals |
158
- | `cost` | `$symbol`, `$cost` | Session cost |
173
+ | `cache` | `$symbol`, `$rate`, `$read`, `$write` | Prompt-cache reads, writes, and latest hit rate; disabled by default |
174
+ | `cost` | `$symbol`, `$cost`, `$subscription` | Session cost and optional `(sub)` marker |
159
175
  | `time` | `$symbol`, `$time` | Current local time |
160
176
  | `turn` | `$symbol`, `$count` | User turn count |
161
177
  | `package` | `$symbol`, `$version`, `$source` | Direct project manifest version |
@@ -184,6 +200,50 @@ An invalid root format falls back to the built-in root format. An invalid module
184
200
  | `fill` | `$symbol` | Flexible width-aware root-layout marker |
185
201
  | `extension_status` | `$symbol`, `$statuses`, `$count` | Pi extension statuses |
186
202
 
203
+ ### Usage semantics
204
+
205
+ - `tokens`, `cache`, and `cost` total every usage-bearing session entry, matching Pi's native footer:
206
+ assistant messages, nested-LLM tool results, compactions, and branch summaries, including abandoned
207
+ branches retained in the session.
208
+ - Cache `$read` and `$write` are cumulative. `$rate` uses only the latest assistant prompt:
209
+ `cacheRead / (input + cacheRead + cacheWrite) * 100`. The module is empty when Pi has reported no
210
+ cache reads or writes.
211
+ - `cache` is disabled by default, but the built-in root format already contains `$cache`; users who
212
+ inherit that format can enable it with only `[cache] disabled = false`. A custom root format must
213
+ reference `$cache` or `$all` normally.
214
+ - Context `$percentage` uses native one-decimal precision. For a native-style display, use
215
+ `format = "[$symbol $percentage/$window ]($style)"` under `[context]`; the module name remains
216
+ `context`, not `context_usage`.
217
+ - Subscription-backed OAuth models and `kimi-coding` set cost `$subscription` to `(sub)`. The dollar
218
+ value is usage cost, not proof of an amount billed under a subscription.
219
+ - Pi's public extension API does not expose the current auto-compaction toggle, so pi-starship cannot
220
+ reliably provide the native `(auto)` marker.
221
+
222
+ ### Model truncation
223
+
224
+ The model module accepts Starship-style `truncation_length` and `truncation_symbol` options plus the
225
+ Pi-specific `truncation_direction` option:
226
+
227
+ ```toml
228
+ [model]
229
+ truncation_length = 36
230
+ truncation_symbol = "…"
231
+ truncation_direction = "middle"
232
+ ```
233
+
234
+ `truncation_length` counts model grapheme clusters retained before the symbol; `0` disables
235
+ truncation and is the default. The direction names the removed portion: `start` retains the suffix,
236
+ `end` retains the prefix and is the default, and `middle` retains both ends. Truncation runs after the
237
+ built-in Claude/GPT shortening rules and changes display only—the provider model ID is untouched.
238
+ Terminal control sequences in model IDs and truncation symbols are removed at render time. An empty
239
+ symbol truncates without a marker. For example, `middle` can retain both a Hugging Face model
240
+ family and its variant, while `start` is useful when a llama.cpp server reports an absolute model path.
241
+ pi-starship treats model IDs as opaque strings and does not parse paths, repositories, GGUF suffixes,
242
+ or quantization names.
243
+
244
+ `truncation_direction` is a pi-starship adaptation; upstream Starship has no model module or generic
245
+ truncation-direction setting.
246
+
187
247
  `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
248
 
189
249
  `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.
@@ -309,7 +369,10 @@ at eight parents.
309
369
  | `/starship status` | Show config source/path and diagnostics |
310
370
  | `/starship help` | Show command and configuration help |
311
371
 
312
- The main menu keeps frequent goals visible: **Customize footer**, **Check configuration**, and **Help**. It shows whether the footer uses the built-in or custom document and displays the current warning count. **Advanced** contains uncommon details and the confirmed restore action, with an explicit **Back** path.
372
+ The standard main menu keeps frequent goals visible: **Customize footer**, **Check configuration**,
373
+ and **Help**. It shows whether the footer uses the built-in or custom document and displays the
374
+ current warning count. **Advanced** contains uncommon details and the confirmed restore action, with
375
+ an explicit **Back** path. The TOML editor and live footer previews remain specialized extension UI.
313
376
 
314
377
  Status and help remain safe in TUI, RPC, JSON, and print modes. RPC receives notifications but never opens custom terminal UI; print and JSON modes produce no ad hoc output. Footer/timer/Git lifecycle work starts only in TUI mode.
315
378
 
@@ -322,7 +385,7 @@ shell modules, or expose unrestricted `env_var` behavior. JVM/.NET, other long-t
322
385
  alternative VCS, system-monitor, and additional DevOps modules remain demand-gated; the first-wave
323
386
  review found no issue/discussion evidence for a coherent follow-up batch, so no second wave is added.
324
387
 
325
- Pi-native model, context, cost, Git metrics, and activity remain owned by the existing modules. The
388
+ Pi-native model, context, cache, cost, Git metrics, and activity remain owned by the existing modules. The
326
389
  lifecycle design rejects provider-specific duplicates and ambiguous `turn_duration`/`last_result`
327
390
  modules until separately approved semantics exist.
328
391
 
@@ -336,6 +399,7 @@ Keep `extension_status` last in the catalog so earlier modules can consume exten
336
399
 
337
400
  - `src/index.ts` — Pi package entrypoint.
338
401
  - `src/pi-starship.ts` — extension lifecycle, cached refresh binding, live preview, and footer.
402
+ - `src/usage.ts` — native-aligned session usage and cache aggregation.
339
403
  - `src/commands.ts` — goal-oriented menu, preview/confirmation, diagnostics, and compatibility routes.
340
404
  - `src/config.ts` — TOML loading, draft validation, defaults, atomic persistence, and rollback.
341
405
  - `src/format/` — native format/style parser and renderer.
@@ -345,7 +409,8 @@ Keep `extension_status` last in the catalog so earlier modules can consume exten
345
409
 
346
410
  ## 🔎 Keywords
347
411
 
348
- Pi Coding Agent, Starship statusline, Starship TOML, terminal footer, native statusline, Pi extension
412
+ Pi Coding Agent, Starship statusline, Starship TOML, terminal footer, native statusline, prompt cache,
413
+ cache hit rate, Pi extension
349
414
 
350
415
  ## 📄 License
351
416
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-starship",
3
- "version": "0.35.0",
3
+ "version": "0.38.0",
4
4
  "description": "Native Starship-style TOML statusline for the Pi coding agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,6 +31,7 @@
31
31
  "typecheck": "tsc --noEmit"
32
32
  },
33
33
  "dependencies": {
34
+ "@narumitw/pi-tui-kit": "<1",
34
35
  "smol-toml": "^1.7.0",
35
36
  "yaml": "^2.9.0"
36
37
  },
package/src/commands.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  truncateToWidth,
7
7
  wrapTextWithAnsi,
8
8
  } from "@earendil-works/pi-tui";
9
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
9
10
  import {
10
11
  atomicRestoreConfigDocument,
11
12
  atomicSaveConfigDocument,
@@ -52,6 +53,7 @@ export interface StarshipCommandOptions {
52
53
  save?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
53
54
  restore?: (settingsPath: string, rawDocument: string) => void;
54
55
  validate?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
56
+ getMenuOwner?(): { signal: AbortSignal; isCurrent(): boolean };
55
57
  }
56
58
 
57
59
  interface MenuItem extends SelectItem {
@@ -95,80 +97,138 @@ export function registerStarshipCommand(pi: ExtensionAPI, options: StarshipComma
95
97
  }
96
98
 
97
99
  async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipCommandOptions) {
98
- while (true) {
99
- const loaded = options.getLoaded();
100
- const state = configurationState(loaded);
101
- const health = configurationHealth(loaded);
102
- const selection = await showActionMenu(ctx, "pi-starship", () => [`${state} · ${health}`], [
103
- {
104
- value: MAIN_ACTIONS.customize,
105
- label: "Customize footer",
106
- description: `${state} · preview before applying`,
107
- },
108
- {
109
- value: MAIN_ACTIONS.diagnostics,
110
- label: "Check configuration",
111
- description: health,
100
+ const fallbackController = new AbortController();
101
+ const owner = options.getMenuOwner?.() ?? {
102
+ signal: fallbackController.signal,
103
+ isCurrent: () => !fallbackController.signal.aborted,
104
+ };
105
+ type Screen = "main" | "advanced" | "diagnostics" | "details" | "help";
106
+ type Action = "customize" | "restore" | "back";
107
+ const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
108
+ start: "main",
109
+ screens: {
110
+ main: () => {
111
+ const loaded = options.getLoaded();
112
+ const state = configurationState(loaded);
113
+ const health = configurationHealth(loaded);
114
+ return {
115
+ kind: "actions",
116
+ title: "pi-starship",
117
+ lines: [`${state} · ${health}`],
118
+ items: [
119
+ {
120
+ id: MAIN_ACTIONS.customize,
121
+ label: "Customize footer",
122
+ description: `${state} · preview before applying`,
123
+ action: "customize",
124
+ },
125
+ {
126
+ id: MAIN_ACTIONS.diagnostics,
127
+ label: "Check configuration",
128
+ description: health,
129
+ to: "diagnostics",
130
+ },
131
+ {
132
+ id: MAIN_ACTIONS.help,
133
+ label: "Help",
134
+ description: "Formats, modules, and commands",
135
+ to: "help",
136
+ },
137
+ {
138
+ id: MAIN_ACTIONS.advanced,
139
+ label: "Advanced",
140
+ description: "Details and restore controls",
141
+ to: "advanced",
142
+ },
143
+ ],
144
+ hint: "close",
145
+ };
112
146
  },
113
- { value: MAIN_ACTIONS.help, label: "Help", description: "Formats, modules, and commands" },
114
- {
115
- value: MAIN_ACTIONS.advanced,
116
- label: "Advanced",
117
- description: "Details and restore controls",
147
+ advanced: () => {
148
+ const loaded = options.getLoaded();
149
+ const alreadyBuiltIn = loaded.rawDocument === BUILT_IN_EXAMPLE;
150
+ return {
151
+ kind: "actions",
152
+ title: "Advanced",
153
+ lines: [configurationState(loaded)],
154
+ items: [
155
+ {
156
+ id: ADVANCED_ACTIONS.details,
157
+ label: "Configuration details",
158
+ description: `${configurationSource(loaded)} · ${fileName(options.settingsPath)}`,
159
+ to: "details",
160
+ },
161
+ {
162
+ id: ADVANCED_ACTIONS.restore,
163
+ label: "Restore built-in",
164
+ description: alreadyBuiltIn
165
+ ? "Already active"
166
+ : "Preview before replacing the document",
167
+ action: "restore",
168
+ },
169
+ {
170
+ id: ADVANCED_ACTIONS.back,
171
+ label: "Back",
172
+ description: "Return to pi-starship",
173
+ action: "back",
174
+ },
175
+ ],
176
+ hint: "back",
177
+ };
118
178
  },
119
- ]);
120
- switch (selection) {
121
- case MAIN_ACTIONS.customize:
122
- if (await editSettings(ctx, options)) return;
123
- break;
124
- case MAIN_ACTIONS.diagnostics:
125
- await showDiagnosticsScreen(ctx, loaded);
126
- break;
127
- case MAIN_ACTIONS.help:
128
- await showHelpScreen(ctx, options.settingsPath);
129
- break;
130
- case MAIN_ACTIONS.advanced:
131
- if (!(await showAdvancedMenu(ctx, options))) return;
132
- break;
133
- default:
134
- return;
135
- }
136
- }
137
- }
138
-
139
- async function showAdvancedMenu(
140
- ctx: ExtensionCommandContext,
141
- options: StarshipCommandOptions,
142
- ): Promise<boolean> {
143
- while (true) {
144
- const loaded = options.getLoaded();
145
- const alreadyBuiltIn = loaded.rawDocument === BUILT_IN_EXAMPLE;
146
- const selection = await showActionMenu(ctx, "Advanced", () => [configurationState(loaded)], [
147
- {
148
- value: ADVANCED_ACTIONS.details,
149
- label: "Configuration details",
150
- description: `${configurationSource(loaded)} · ${fileName(options.settingsPath)}`,
179
+ diagnostics: () => ({
180
+ kind: "detail",
181
+ title: "Configuration health",
182
+ lines: diagnosticLines(options.getLoaded(), false),
183
+ hint: "back",
184
+ }),
185
+ details: () => {
186
+ const loaded = options.getLoaded();
187
+ return {
188
+ kind: "detail",
189
+ title: "Configuration details",
190
+ lines: [
191
+ `State: ${configurationState(loaded)}`,
192
+ `Source: ${configurationSource(loaded)}`,
193
+ `Path: ${safeText(options.settingsPath)}`,
194
+ ...diagnosticLines(loaded, true),
195
+ ],
196
+ hint: "back",
197
+ };
151
198
  },
152
- {
153
- value: ADVANCED_ACTIONS.restore,
154
- label: "Restore built-in",
155
- description: alreadyBuiltIn ? "Already active" : "Preview before replacing the document",
199
+ help: () => ({
200
+ kind: "detail",
201
+ title: "pi-starship help",
202
+ lines: [
203
+ "Customize footer opens the TOML editor, then previews and confirms before saving.",
204
+ "Check configuration explains warnings without changing the footer.",
205
+ `Settings: ${safeText(options.settingsPath)}`,
206
+ "Docs: https://github.com/narumiruna/pi-extensions/tree/main/extensions/pi-starship",
207
+ ],
208
+ hint: "back",
209
+ }),
210
+ },
211
+ actions: {
212
+ customize: async () =>
213
+ (await editSettings(ctx, options)) ? { kind: "close" } : { kind: "stay" },
214
+ restore: async () => {
215
+ if (options.getLoaded().rawDocument === BUILT_IN_EXAMPLE) {
216
+ ctx.ui.notify("The built-in footer configuration is already active.", "info");
217
+ return { kind: "stay" };
218
+ }
219
+ return (await restoreBuiltIn(ctx, options)) ? { kind: "close" } : { kind: "stay" };
156
220
  },
157
- { value: ADVANCED_ACTIONS.back, label: "Back", description: "Return to pi-starship" },
158
- ]);
159
- if (selection === ADVANCED_ACTIONS.details) {
160
- await showConfigurationDetails(ctx, loaded, options.settingsPath);
161
- continue;
162
- }
163
- if (selection === ADVANCED_ACTIONS.restore) {
164
- if (alreadyBuiltIn) {
165
- ctx.ui.notify("The built-in footer configuration is already active.", "info");
166
- continue;
167
- }
168
- if (await restoreBuiltIn(ctx, options)) return false;
169
- continue;
170
- }
171
- return selection === ADVANCED_ACTIONS.back;
221
+ back: async () => ({ kind: "back" }),
222
+ },
223
+ });
224
+ try {
225
+ await runMenu(ctx, menu, {
226
+ getState: () => undefined,
227
+ signal: owner.signal,
228
+ isCurrent: owner.isCurrent,
229
+ });
230
+ } finally {
231
+ fallbackController.abort(new DOMException("Starship menu closed", "AbortError"));
172
232
  }
173
233
  }
174
234
 
@@ -190,7 +250,7 @@ async function editSettings(
190
250
  validated = (options.validate ?? validateConfigDocument)(options.settingsPath, draft);
191
251
  } catch (error) {
192
252
  ctx.ui.notify(`Footer draft is invalid: ${safeText(formatError(error))}`, "error");
193
- const action = await showActionMenu(
253
+ const action = await showPreviewActionMenu(
194
254
  ctx,
195
255
  "Configuration needs attention",
196
256
  () => [safeText(formatError(error)), "The current footer has not changed."],
@@ -228,7 +288,7 @@ async function reviewAndApply(
228
288
  restore: boolean,
229
289
  ): Promise<"applied" | "edit" | "cancel"> {
230
290
  while (true) {
231
- const selection = await showActionMenu(
291
+ const selection = await showPreviewActionMenu(
232
292
  ctx,
233
293
  title,
234
294
  (width) => previewBody(ctx, options, validated, width),
@@ -332,45 +392,7 @@ function previewBody(
332
392
  return [...lines, "", warning];
333
393
  }
334
394
 
335
- async function showDiagnosticsScreen(ctx: ExtensionCommandContext, loaded: LoadedStarshipConfig) {
336
- await showActionMenu(ctx, "Configuration health", () => diagnosticLines(loaded, false), [
337
- { value: ADVANCED_ACTIONS.back, label: "Back" },
338
- ]);
339
- }
340
-
341
- async function showConfigurationDetails(
342
- ctx: ExtensionCommandContext,
343
- loaded: LoadedStarshipConfig,
344
- settingsPath: string,
345
- ) {
346
- await showActionMenu(
347
- ctx,
348
- "Configuration details",
349
- () => [
350
- `State: ${configurationState(loaded)}`,
351
- `Source: ${configurationSource(loaded)}`,
352
- `Path: ${safeText(settingsPath)}`,
353
- ...diagnosticLines(loaded, true),
354
- ],
355
- [{ value: ADVANCED_ACTIONS.back, label: "Back" }],
356
- );
357
- }
358
-
359
- async function showHelpScreen(ctx: ExtensionCommandContext, settingsPath: string) {
360
- await showActionMenu(
361
- ctx,
362
- "pi-starship help",
363
- () => [
364
- "Customize footer opens the TOML editor, then previews and confirms before saving.",
365
- "Check configuration explains warnings without changing the footer.",
366
- `Settings: ${safeText(settingsPath)}`,
367
- "Docs: https://github.com/narumiruna/pi-extensions/tree/main/extensions/pi-starship",
368
- ],
369
- [{ value: ADVANCED_ACTIONS.back, label: "Back" }],
370
- );
371
- }
372
-
373
- async function showActionMenu(
395
+ async function showPreviewActionMenu(
374
396
  ctx: ExtensionCommandContext,
375
397
  title: string,
376
398
  body: (width: number) => readonly string[],
package/src/config.ts CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  } from "./format/formatter.js";
19
19
  import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
20
20
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
21
- import type { ModuleOptionSchema } from "./modules/types.js";
21
+ import type { ModuleOptionSchema, ModuleOptionValue } from "./modules/types.js";
22
22
 
23
23
  export const CONFIG_FILE_NAME = "pi-starship.toml";
24
24
  export { MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
@@ -27,13 +27,6 @@ const MODULE_CONTENT_VARIABLES = Object.fromEntries(
27
27
  MODULE_DEFINITIONS.map((definition) => [definition.name, definition.variables]),
28
28
  ) as Record<ModuleName, readonly string[]>;
29
29
 
30
- export type ModuleOptionValue =
31
- | string
32
- | boolean
33
- | number
34
- | readonly string[]
35
- | Readonly<Record<string, string>>;
36
-
37
30
  export interface ModuleConfig {
38
31
  format: string;
39
32
  formatAst: FormatNode[];
@@ -89,6 +82,7 @@ $git_status\
89
82
  $activity\
90
83
  $context\
91
84
  $tokens\
85
+ $cache\
92
86
  [](fg:runtime bg:meter)\
93
87
  $cost\
94
88
  $time\
@@ -575,6 +569,13 @@ function normalizeModuleOption(
575
569
  return typeof value === "string" && (schema.allowEmpty !== false || value.length > 0)
576
570
  ? { ok: true, value }
577
571
  : { ok: false, message: "Expected a non-empty string; using the default value" };
572
+ case "string-enum":
573
+ return typeof value === "string" && schema.values.includes(value)
574
+ ? { ok: true, value }
575
+ : {
576
+ ok: false,
577
+ message: `Expected one of: ${schema.values.join(", ")}; using the default value`,
578
+ };
578
579
  case "boolean":
579
580
  return typeof value === "boolean"
580
581
  ? { ok: true, value }
@@ -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 {
@@ -1,5 +1,9 @@
1
1
  import { defineModule } from "./types.js";
2
2
 
3
+ const TRUNCATION_DIRECTIONS = ["start", "middle", "end"] as const;
4
+ type TruncationDirection = (typeof TRUNCATION_DIRECTIONS)[number];
5
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
6
+
3
7
  export const modelModule = defineModule({
4
8
  name: "model",
5
9
  variables: ["symbol", "model"],
@@ -9,9 +13,119 @@ export const modelModule = defineModule({
9
13
  style: "fg:header_fg bg:header",
10
14
  disabled: false,
11
15
  },
12
- values: ({ runtime }) => (runtime.model ? { model: shortenModel(runtime.model.id) } : undefined),
16
+ options: {
17
+ truncation_length: { kind: "integer", default: 0, minimum: 0, maximum: 1000 },
18
+ truncation_symbol: { kind: "string", default: "…" },
19
+ truncation_direction: {
20
+ kind: "string-enum",
21
+ default: "end",
22
+ values: TRUNCATION_DIRECTIONS,
23
+ },
24
+ },
25
+ values: ({ runtime, options }) => {
26
+ if (!runtime.model) return undefined;
27
+ const length = typeof options.truncation_length === "number" ? options.truncation_length : 0;
28
+ const symbol = typeof options.truncation_symbol === "string" ? options.truncation_symbol : "…";
29
+ const direction = isTruncationDirection(options.truncation_direction)
30
+ ? options.truncation_direction
31
+ : "end";
32
+ return {
33
+ model: truncateModel(shortenModel(runtime.model.id), length, symbol, direction),
34
+ };
35
+ },
13
36
  });
14
37
 
38
+ export function truncateModel(
39
+ model: string,
40
+ length: number,
41
+ symbol: string,
42
+ direction: TruncationDirection,
43
+ ): string {
44
+ const safeModel = sanitizeModelDisplay(model);
45
+ if (length === 0) return safeModel;
46
+ const graphemes = [...graphemeSegmenter.segment(safeModel)].map(({ segment }) => segment);
47
+ if (graphemes.length <= length) return safeModel;
48
+ const safeSymbol = sanitizeModelDisplay(symbol);
49
+
50
+ switch (direction) {
51
+ case "start":
52
+ return `${safeSymbol}${graphemes.slice(-length).join("")}`;
53
+ case "middle": {
54
+ const headLength = Math.ceil(length / 2);
55
+ const tailLength = Math.floor(length / 2);
56
+ const tail = tailLength > 0 ? graphemes.slice(-tailLength).join("") : "";
57
+ return `${graphemes.slice(0, headLength).join("")}${safeSymbol}${tail}`;
58
+ }
59
+ case "end":
60
+ return `${graphemes.slice(0, length).join("")}${safeSymbol}`;
61
+ }
62
+ }
63
+
64
+ function sanitizeModelDisplay(value: string): string {
65
+ let result = "";
66
+ for (let index = 0; index < value.length; ) {
67
+ const codePoint = value.codePointAt(index) ?? 0;
68
+ const character = String.fromCodePoint(codePoint);
69
+ if (codePoint === 0x1b || codePoint === 0x9b || codePoint === 0x9d) {
70
+ index = skipTerminalEscape(value, index, codePoint);
71
+ continue;
72
+ }
73
+ if (
74
+ codePoint <= 0x1f ||
75
+ (codePoint >= 0x7f && codePoint <= 0x9f) ||
76
+ codePoint === 0x2028 ||
77
+ codePoint === 0x2029
78
+ ) {
79
+ if (
80
+ codePoint === 0x09 ||
81
+ codePoint === 0x0a ||
82
+ codePoint === 0x0d ||
83
+ codePoint === 0x85 ||
84
+ codePoint === 0x2028 ||
85
+ codePoint === 0x2029
86
+ ) {
87
+ result += " ";
88
+ }
89
+ index += character.length;
90
+ continue;
91
+ }
92
+ result += character;
93
+ index += character.length;
94
+ }
95
+ return result;
96
+ }
97
+
98
+ function skipTerminalEscape(value: string, start: number, codePoint: number): number {
99
+ let index = start + 1;
100
+ const next = value.charCodeAt(index);
101
+ const isOsc = codePoint === 0x9d || (codePoint === 0x1b && next === 0x5d);
102
+ if (isOsc) {
103
+ if (codePoint === 0x1b) index += 1;
104
+ while (index < value.length) {
105
+ const current = value.charCodeAt(index);
106
+ if (current === 0x07 || current === 0x9c) return index + 1;
107
+ if (current === 0x1b && value.charCodeAt(index + 1) === 0x5c) return index + 2;
108
+ index += 1;
109
+ }
110
+ return index;
111
+ }
112
+ const isCsi = codePoint === 0x9b || (codePoint === 0x1b && next === 0x5b);
113
+ if (isCsi) {
114
+ if (codePoint === 0x1b) index += 1;
115
+ while (index < value.length) {
116
+ const current = value.charCodeAt(index);
117
+ index += 1;
118
+ if (current >= 0x40 && current <= 0x7e) break;
119
+ }
120
+ return index;
121
+ }
122
+ return Math.min(value.length, start + (codePoint === 0x1b ? 2 : 1));
123
+ }
124
+
125
+ function isTruncationDirection(value: unknown): value is TruncationDirection {
126
+ return TRUNCATION_DIRECTIONS.includes(value as TruncationDirection);
127
+ }
128
+
15
129
  export function shortenModel(model: string): string {
16
130
  return model
17
131
  .replace(/^claude-/u, "")
@@ -71,6 +71,7 @@ function valueContext(
71
71
  return {
72
72
  runtime,
73
73
  symbol: config.modules[name].symbol,
74
+ options: config.modules[name].options,
74
75
  extensionStatus: config.extensionStatus,
75
76
  hiddenExtensionStatusKeys,
76
77
  };
@@ -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;
@@ -98,15 +106,24 @@ export interface ExtensionStatusPresentation {
98
106
  icons: Readonly<Record<string, string>>;
99
107
  }
100
108
 
109
+ export type ModuleOptionValue =
110
+ | string
111
+ | boolean
112
+ | number
113
+ | readonly string[]
114
+ | Readonly<Record<string, string>>;
115
+
101
116
  export interface ModuleValueContext {
102
117
  runtime: StarshipRuntimeSnapshot;
103
118
  symbol: string;
119
+ options: Readonly<Record<string, ModuleOptionValue>>;
104
120
  extensionStatus: ExtensionStatusPresentation;
105
121
  hiddenExtensionStatusKeys: ReadonlySet<string>;
106
122
  }
107
123
 
108
124
  export type ModuleOptionSchema =
109
125
  | { kind: "string"; default: string; allowEmpty?: boolean }
126
+ | { kind: "string-enum"; default: string; values: readonly string[] }
110
127
  | { kind: "boolean"; default: boolean }
111
128
  | { kind: "integer"; default: number; minimum: number; maximum: number }
112
129
  | { kind: "string-array"; default: readonly string[]; allowNegative?: boolean }
@@ -30,6 +30,7 @@ import {
30
30
  type WorkspaceRefreshInput,
31
31
  workspaceSnapshotEqual,
32
32
  } from "./runtime/workspace.js";
33
+ import { summarizeFooterUsage } from "./usage.js";
33
34
 
34
35
  const REFRESH_INTERVAL_MS = 30_000;
35
36
  const EVENT_DEBOUNCE_MS = 250;
@@ -67,6 +68,7 @@ export default function piStarship(pi: ExtensionAPI) {
67
68
  };
68
69
  let conflictWarningShown = false;
69
70
  let sessionGeneration = 0;
71
+ let menuController = new AbortController();
70
72
  let activeTarget: RefreshTarget | undefined;
71
73
  let eventDebounceTimer: ReturnType<typeof setTimeout> | undefined;
72
74
 
@@ -138,6 +140,8 @@ export default function piStarship(pi: ExtensionAPI) {
138
140
 
139
141
  const installFooter = (ctx: ExtensionContext) => {
140
142
  const generation = ++sessionGeneration;
143
+ menuController.abort(new DOMException("Starship session context replaced", "AbortError"));
144
+ menuController = new AbortController();
141
145
  const target = { cwd: ctx.cwd, generation };
142
146
  clearDebounce();
143
147
  gitController.stop();
@@ -220,6 +224,13 @@ export default function piStarship(pi: ExtensionAPI) {
220
224
  registerStarshipCommand(pi, {
221
225
  settingsPath: configPath,
222
226
  getLoaded: () => loaded ?? loadStarshipConfig(configPath),
227
+ getMenuOwner: () => {
228
+ const generation = sessionGeneration;
229
+ return {
230
+ signal: menuController.signal,
231
+ isCurrent: () => generation === sessionGeneration && !menuController.signal.aborted,
232
+ };
233
+ },
223
234
  apply(next) {
224
235
  loaded = next;
225
236
  const target = activeTarget;
@@ -251,6 +262,7 @@ export default function piStarship(pi: ExtensionAPI) {
251
262
 
252
263
  pi.on("session_shutdown", (_event, ctx) => {
253
264
  sessionGeneration += 1;
265
+ menuController.abort(new DOMException("Starship session shut down", "AbortError"));
254
266
  activeTarget = undefined;
255
267
  clearDebounce();
256
268
  gitController.stop();
@@ -394,7 +406,8 @@ function runtimeSnapshot(
394
406
  isStreaming: runtime.isStreaming,
395
407
  lastCompletedTool: runtime.lastCompletedTool,
396
408
  contextUsage: ctx.getContextUsage() ?? undefined,
397
- tokenTotals: tokenTotals(ctx),
409
+ tokenTotals: summarizeFooterUsage(ctx.sessionManager.getEntries()),
410
+ usingSubscription: isSubscriptionBacked(ctx),
398
411
  gitBranch: runtime.git?.branch?.name ?? footerData.getGitBranch(),
399
412
  gitBranchDetails: runtime.git?.branch,
400
413
  gitCommit: runtime.git?.commit,
@@ -415,16 +428,12 @@ function userTurnCount(ctx: ExtensionContext): number {
415
428
  .filter((entry) => entry.type === "message" && entry.message.role === "user").length;
416
429
  }
417
430
 
418
- function tokenTotals(ctx: ExtensionContext): { input: number; output: number; cost: number } {
419
- const totals = { input: 0, output: 0, cost: 0 };
420
- for (const entry of ctx.sessionManager.getBranch()) {
421
- if (entry.type !== "message" || entry.message.role !== "assistant") continue;
422
- const usage = entry.message.usage;
423
- totals.input += usage.input ?? 0;
424
- totals.output += usage.output ?? 0;
425
- totals.cost += usage.cost?.total ?? 0;
426
- }
427
- return totals;
431
+ function isSubscriptionBacked(ctx: ExtensionContext): boolean {
432
+ const model = ctx.model;
433
+ return (
434
+ model !== undefined &&
435
+ (model.provider === "kimi-coding" || ctx.modelRegistry.isUsingOAuth(model))
436
+ );
428
437
  }
429
438
 
430
439
  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
+ }