@narumitw/pi-starship 0.45.0 → 0.46.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
@@ -339,22 +339,74 @@ There is no hidden compatibility overlay or automatic migration.
339
339
  - Pi's public extension API does not expose the current auto-compaction toggle, so pi-starship cannot
340
340
  reliably provide the native `(auto)` marker.
341
341
 
342
- ### Model truncation
342
+ ### Directory, Git, and environment contraction
343
343
 
344
- The model module accepts Starship-style `truncation_length` and `truncation_symbol` options plus the
345
- Pi-specific `truncation_direction` option:
344
+ The analogous modules keep their display policy local and use Starship defaults:
345
+
346
+ ```toml
347
+ [directory]
348
+ truncation_length = 3
349
+ truncate_to_repo = true
350
+ fish_style_pwd_dir_length = 0
351
+ truncation_symbol = ""
352
+ home_symbol = "~"
353
+ use_os_path_sep = true
354
+ substitutions = { "/Volumes/network/path" = "/net" }
355
+
356
+ [git_branch]
357
+ truncation_length = 0 # pi-starship's bounded no-truncation sentinel
358
+ truncation_symbol = "…"
359
+
360
+ [git_commit]
361
+ commit_hash_length = 7
362
+
363
+ [conda]
364
+ ignore_base = true
365
+ truncation_length = 1
366
+
367
+ [hostname]
368
+ trim_at = "." # set to "" to keep the complete hostname
369
+ ```
370
+
371
+ Directory `$path` contracts the home directory and, by default, the current Git repository root
372
+ before retaining the last three path components. `$full_path` remains the unmodified absolute cwd.
373
+ A positive `fish_style_pwd_dir_length` abbreviates otherwise omitted parent components when no
374
+ substitution is configured. `substitutions` is an ordered TOML string table of literal replacements.
375
+ Pi exposes one cwd rather than separate logical and physical paths, and pi-starship does not implement
376
+ Starship's regex substitution array or repo-root-specific split style/format fields. Directory
377
+ rendering reads only immutable home and repository-root snapshot data and performs no filesystem or
378
+ Git work.
379
+
380
+ Git branch truncation retains the first `N` grapheme clusters and appends the first grapheme of
381
+ `truncation_symbol` only when truncation occurs. The same rule applies independently to `$branch`,
382
+ `$remote_name`, and `$remote_branch`. Upstream Starship represents its unlimited default as
383
+ `2^63 - 1`; pi-starship uses `0` for the same behavior because its settings integers are deliberately
384
+ bounded. `commit_hash_length` accepts 0 through 64.
385
+
386
+ Conda retains the last path component by default; `0` keeps the complete environment path. Hostname
387
+ trimming runs before exact alias lookup, matching Starship. These are display transformations only:
388
+ collectors retain bounded, control-sanitized source metadata.
389
+
390
+ ### Model aliases and truncation
391
+
392
+ The model module accepts exact `model_aliases`, Starship-style `truncation_length` and
393
+ `truncation_symbol` options, plus the Pi-specific `truncation_direction` option:
346
394
 
347
395
  ```toml
348
396
  [model]
397
+ model_aliases = { "/models/Qwen3.6-35B-Q4.gguf" = "Qwen 35B Q4" }
349
398
  truncation_length = 36
350
399
  truncation_symbol = "…"
351
400
  truncation_direction = "middle"
352
401
  ```
353
402
 
354
- `truncation_length` counts model grapheme clusters retained before the symbol; `0` disables
403
+ An exact alias is selected before the built-in Claude/GPT shortening rules, then the resulting label
404
+ is subject to the configured truncation. `truncation_length` counts model grapheme clusters retained
405
+ before the symbol; `0` disables
355
406
  truncation and is the default. The direction names the removed portion: `start` retains the suffix,
356
- `end` retains the prefix and is the default, and `middle` retains both ends. Truncation runs after the
357
- built-in Claude/GPT shortening rules and changes display only—the provider model ID is untouched.
407
+ `end` retains the prefix and is the default, and `middle` retains both ends. When no alias matches,
408
+ truncation runs after the built-in Claude/GPT shortening rules. It always changes display only—the
409
+ provider model ID is untouched.
358
410
  Terminal control sequences in model IDs and truncation symbols are removed at render time. An empty
359
411
  symbol truncates without a marker. For example, `middle` can retain both a Hugging Face model
360
412
  family and its variant, while `start` is useful when a llama.cpp server reports an absolute model path.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-starship",
3
- "version": "0.45.0",
3
+ "version": "0.46.0",
4
4
  "description": "Native Starship-style TOML statusline for the Pi coding agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -31,7 +31,7 @@
31
31
  "typecheck": "tsc --noEmit"
32
32
  },
33
33
  "dependencies": {
34
- "@narumitw/pi-tui-kit": "^0.43.0",
34
+ "@narumitw/pi-tui-kit": "^0.45.0",
35
35
  "smol-toml": "^1.7.1",
36
36
  "yaml": "^2.9.0"
37
37
  },
@@ -1,22 +1,12 @@
1
1
  import { stripVTControlCharacters } from "node:util";
2
2
  import type { ExtensionCommandContext, KeybindingsManager } from "@earendil-works/pi-coding-agent";
3
- import {
4
- type Component,
5
- type Focusable,
6
- Input,
7
- Key,
8
- matchesKey,
9
- truncateToWidth,
10
- wrapTextWithAnsi,
11
- } from "@earendil-works/pi-tui";
12
- import type { ModuleInspection, StatuslineInspection } from "./modules/inspection.js";
3
+ import { Key, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
4
+ import type { StatuslineInspection } from "./modules/inspection.js";
13
5
 
14
6
  const RESERVED_HOST_ROWS = 3;
15
7
 
16
8
  export type InspectorResult = { kind: "back" } | { kind: "close" };
17
9
 
18
- type DisposableComponent = Component & Focusable & { dispose(): void };
19
-
20
10
  export function showFooterExplanation(
21
11
  ctx: ExtensionCommandContext,
22
12
  inspection: StatuslineInspection | undefined,
@@ -87,181 +77,6 @@ export function showFooterExplanation(
87
77
  });
88
78
  }
89
79
 
90
- export function showModuleBrowser(
91
- ctx: ExtensionCommandContext,
92
- inspection: StatuslineInspection,
93
- signal?: AbortSignal,
94
- ): Promise<InspectorResult | undefined> {
95
- if (signal?.aborted) return Promise.resolve({ kind: "close" });
96
- return ctx.ui.custom<InspectorResult | undefined>((tui, theme, keybindings, done) => {
97
- const input = new Input();
98
- let filtered = [...inspection.modules];
99
- let selectedIndex = 0;
100
- let listOffset = 0;
101
- let detailScrollOffset = 0;
102
- let lastListRows = 1;
103
- let searchInputVisible = true;
104
- let lastDetailRows = 1;
105
- let lastDetailMaximumScroll = 0;
106
- let view: "list" | "detail" = "list";
107
- let focused = false;
108
- let disposed = false;
109
- let settled = false;
110
- let deferredAbort: ReturnType<typeof setImmediate> | undefined;
111
- const finish = (result: InspectorResult) => {
112
- if (disposed || settled) return;
113
- settled = true;
114
- done(result);
115
- };
116
- const closeForAbort = () => finish({ kind: "close" });
117
- signal?.addEventListener("abort", closeForAbort, { once: true });
118
- if (signal?.aborted) deferredAbort = setImmediate(closeForAbort);
119
- const selected = () => filtered[selectedIndex];
120
- const syncFocus = () => {
121
- input.focused = focused && view === "list";
122
- };
123
- const select = (index: number) => {
124
- if (filtered.length === 0) return;
125
- selectedIndex = (index + filtered.length) % filtered.length;
126
- };
127
- const applySearch = () => {
128
- const sanitized = safeSearchText(input.getValue());
129
- if (sanitized !== input.getValue()) input.setValue(sanitized);
130
- filtered = filterModules(inspection.modules, sanitized);
131
- selectedIndex = 0;
132
- listOffset = 0;
133
- };
134
-
135
- const component: DisposableComponent = {
136
- get focused() {
137
- return focused;
138
- },
139
- set focused(value: boolean) {
140
- focused = value;
141
- syncFocus();
142
- },
143
- render(width: number): string[] {
144
- const safeWidth = Math.max(1, width);
145
- const availableRows = componentRows(tui.terminal.rows);
146
- if (view === "detail") {
147
- const module = selected();
148
- const content = moduleDetailLines(module, safeWidth);
149
- const layout = detailLayout(availableRows, content.length);
150
- lastDetailRows = layout.contentRows;
151
- lastDetailMaximumScroll = Math.max(0, content.length - layout.contentRows);
152
- detailScrollOffset = clamp(detailScrollOffset, 0, lastDetailMaximumScroll);
153
- const lines = [
154
- ...(layout.titleRows ? [theme.fg("accent", theme.bold(module?.name ?? "Module"))] : []),
155
- ...content.slice(detailScrollOffset, detailScrollOffset + layout.contentRows),
156
- ...(layout.positionRows
157
- ? [
158
- theme.fg(
159
- "dim",
160
- positionText(detailScrollOffset, layout.contentRows, content.length),
161
- ),
162
- ]
163
- : []),
164
- ...(layout.hintRows ? [theme.fg("dim", detailHint(keybindings, "back"))] : []),
165
- ];
166
- return boundedLines(lines, safeWidth, availableRows);
167
- }
168
-
169
- const layout = listLayout(availableRows, filtered.length);
170
- lastListRows = layout.itemRows;
171
- searchInputVisible = layout.inputRows > 0;
172
- listOffset = listWindowStart(selectedIndex, filtered.length, layout.itemRows);
173
- const rows =
174
- filtered.length === 0
175
- ? [theme.fg("dim", " No matching modules")]
176
- : filtered.slice(listOffset, listOffset + layout.itemRows).map((module, index) => {
177
- const absoluteIndex = listOffset + index;
178
- const prefix = absoluteIndex === selectedIndex ? "→ " : " ";
179
- const text = `${prefix}${module.name} [${module.state}]`;
180
- return theme.fg(absoluteIndex === selectedIndex ? "accent" : "text", text);
181
- });
182
- const description = selected()?.description;
183
- const lines = [
184
- ...(layout.titleRows ? [theme.fg("accent", theme.bold("Modules · type to search"))] : []),
185
- ...(layout.inputRows ? input.render(safeWidth) : []),
186
- ...rows,
187
- ...(layout.positionRows
188
- ? [theme.fg("dim", positionText(listOffset, layout.itemRows, filtered.length))]
189
- : []),
190
- ...(layout.descriptionRows && description
191
- ? [theme.fg("muted", safeDisplayText(description))]
192
- : []),
193
- ...(layout.hintRows ? [theme.fg("dim", browserHint(keybindings))] : []),
194
- ];
195
- return boundedLines(lines, safeWidth, availableRows);
196
- },
197
- invalidate() {
198
- input.invalidate();
199
- },
200
- handleInput(data: string) {
201
- if (disposed || settled) return;
202
- if (matchesKey(data, Key.ctrl("c"))) {
203
- finish({ kind: "close" });
204
- } else if (keybindings.matches(data, "tui.select.cancel")) {
205
- if (view === "detail") {
206
- view = "list";
207
- detailScrollOffset = 0;
208
- syncFocus();
209
- } else finish({ kind: "back" });
210
- } else if (view === "detail") {
211
- if (keybindings.matches(data, "tui.select.up")) {
212
- detailScrollOffset = clamp(detailScrollOffset - 1, 0, lastDetailMaximumScroll);
213
- } else if (keybindings.matches(data, "tui.select.down")) {
214
- detailScrollOffset = clamp(detailScrollOffset + 1, 0, lastDetailMaximumScroll);
215
- } else if (keybindings.matches(data, "tui.select.pageUp")) {
216
- detailScrollOffset = clamp(
217
- detailScrollOffset - lastDetailRows,
218
- 0,
219
- lastDetailMaximumScroll,
220
- );
221
- } else if (keybindings.matches(data, "tui.select.pageDown")) {
222
- detailScrollOffset = clamp(
223
- detailScrollOffset + lastDetailRows,
224
- 0,
225
- lastDetailMaximumScroll,
226
- );
227
- } else if (matchesKey(data, Key.home)) detailScrollOffset = 0;
228
- else if (matchesKey(data, Key.end)) {
229
- detailScrollOffset = lastDetailMaximumScroll;
230
- }
231
- } else if (keybindings.matches(data, "tui.select.up")) {
232
- select(selectedIndex - 1);
233
- } else if (keybindings.matches(data, "tui.select.down")) {
234
- select(selectedIndex + 1);
235
- } else if (keybindings.matches(data, "tui.select.pageUp")) {
236
- select(selectedIndex - lastListRows);
237
- } else if (keybindings.matches(data, "tui.select.pageDown")) {
238
- select(selectedIndex + lastListRows);
239
- } else if (matchesKey(data, Key.home)) selectedIndex = 0;
240
- else if (matchesKey(data, Key.end)) selectedIndex = Math.max(0, filtered.length - 1);
241
- else if (keybindings.matches(data, "tui.select.confirm")) {
242
- if (selected()) {
243
- view = "detail";
244
- detailScrollOffset = 0;
245
- syncFocus();
246
- }
247
- } else if (searchInputVisible) {
248
- input.handleInput(data);
249
- applySearch();
250
- }
251
- tui.requestRender();
252
- },
253
- dispose() {
254
- if (disposed) return;
255
- disposed = true;
256
- if (deferredAbort) clearImmediate(deferredAbort);
257
- deferredAbort = undefined;
258
- signal?.removeEventListener("abort", closeForAbort);
259
- },
260
- };
261
- return component;
262
- });
263
- }
264
-
265
80
  function explanationLines(inspection: StatuslineInspection | undefined, width: number): string[] {
266
81
  if (!inspection) {
267
82
  return wrapLines(
@@ -290,34 +105,11 @@ function explanationLines(inspection: StatuslineInspection | undefined, width: n
290
105
  return wrapLines(lines, width);
291
106
  }
292
107
 
293
- function moduleDetailLines(module: ModuleInspection | undefined, width: number): string[] {
294
- if (!module) return ["No matching module."];
295
- return wrapLines(
296
- [
297
- `State: ${module.state}`,
298
- module.description,
299
- `Root: ${module.rootReferenced ? "Referenced" : "Not referenced"}`,
300
- `Reachable: ${module.reachable ? "Yes" : "No"}`,
301
- ...detailPreviewLines(module.preview),
302
- `Reason: ${module.reason}`,
303
- `Variables: ${module.variables.join(", ") || "none"}`,
304
- `Style fields: ${module.styleFields.join(", ") || "none"}`,
305
- `Display rules: ${module.displayRules.join(" · ") || "none"}`,
306
- ],
307
- width,
308
- );
309
- }
310
-
311
108
  function previewLines(preview: string): string[] {
312
109
  const lines = preview ? preview.split("\n") : ["(no text)"];
313
110
  return lines.map((line, index) => `${index === 0 ? "Value: " : " "}${line}`);
314
111
  }
315
112
 
316
- function detailPreviewLines(preview: string): string[] {
317
- const lines = preview ? preview.split("\n") : ["(no current preview)"];
318
- return lines.map((line, index) => `${index === 0 ? "Preview: " : " "}${line}`);
319
- }
320
-
321
113
  function wrapLines(lines: readonly string[], width: number): string[] {
322
114
  return lines.flatMap((line) => {
323
115
  const safe = safeDisplayText(line);
@@ -325,15 +117,6 @@ function wrapLines(lines: readonly string[], width: number): string[] {
325
117
  });
326
118
  }
327
119
 
328
- function filterModules(modules: readonly ModuleInspection[], query: string): ModuleInspection[] {
329
- const terms = query.toLowerCase().trim().split(/\s+/u).filter(Boolean);
330
- if (terms.length === 0) return [...modules];
331
- return modules.filter((module) => {
332
- const candidate = `${module.name} ${module.description} ${module.state}`.toLowerCase();
333
- return terms.every((term) => candidate.includes(term));
334
- });
335
- }
336
-
337
120
  interface DetailLayout {
338
121
  titleRows: number;
339
122
  contentRows: number;
@@ -353,46 +136,11 @@ function detailLayout(availableRows: number, contentLength: number): DetailLayou
353
136
  return { titleRows, contentRows, positionRows, hintRows };
354
137
  }
355
138
 
356
- interface ListLayout {
357
- titleRows: number;
358
- inputRows: number;
359
- itemRows: number;
360
- positionRows: number;
361
- descriptionRows: number;
362
- hintRows: number;
363
- }
364
-
365
- function listLayout(availableRows: number, itemCount: number): ListLayout {
366
- if (availableRows === 1) {
367
- return {
368
- titleRows: 0,
369
- inputRows: 0,
370
- itemRows: 1,
371
- positionRows: 0,
372
- descriptionRows: 0,
373
- hintRows: 0,
374
- };
375
- }
376
- const titleRows = availableRows >= 4 ? 1 : 0;
377
- const inputRows = availableRows >= 3 ? 1 : 0;
378
- const hintRows = availableRows >= 3 ? 1 : 0;
379
- const descriptionRows = availableRows >= 7 ? 1 : 0;
380
- let itemRows = Math.max(1, availableRows - titleRows - inputRows - hintRows - descriptionRows);
381
- const positionRows = itemCount > itemRows && itemRows >= 2 ? 1 : 0;
382
- itemRows -= positionRows;
383
- return { titleRows, inputRows, itemRows, positionRows, descriptionRows, hintRows };
384
- }
385
-
386
139
  function componentRows(rows: number): number {
387
140
  const terminalRows = Number.isFinite(rows) ? Math.floor(rows) : 24;
388
141
  return Math.max(1, terminalRows - RESERVED_HOST_ROWS);
389
142
  }
390
143
 
391
- function listWindowStart(selectedIndex: number, itemCount: number, viewportSize: number): number {
392
- if (itemCount <= viewportSize) return 0;
393
- return Math.max(0, Math.min(selectedIndex, itemCount - viewportSize));
394
- }
395
-
396
144
  function positionText(offset: number, viewportSize: number, itemCount: number): string {
397
145
  if (itemCount === 0) return "0/0";
398
146
  return `${offset + 1}-${Math.min(itemCount, offset + viewportSize)}/${itemCount}`;
@@ -402,19 +150,6 @@ function boundedLines(lines: readonly string[], width: number, rows: number): st
402
150
  return lines.slice(0, rows).map((line) => truncateToWidth(line, width, ""));
403
151
  }
404
152
 
405
- function browserHint(keybindings: Pick<KeybindingsManager, "getKeys">): string {
406
- const up = bindingText(keybindings, "tui.select.up");
407
- const down = bindingText(keybindings, "tui.select.down");
408
- const confirm = bindingText(keybindings, "tui.select.confirm");
409
- const cancel = bindingText(keybindings, "tui.select.cancel", "ctrl+c");
410
- return [
411
- ...(up || down ? [`${[up, down].filter(Boolean).join("/")} navigate`] : []),
412
- ...(confirm ? [`${confirm} details`] : []),
413
- ...(cancel ? [`${cancel} back`] : []),
414
- "ctrl+c close",
415
- ].join(" • ");
416
- }
417
-
418
153
  function detailHint(
419
154
  keybindings: Pick<KeybindingsManager, "getKeys">,
420
155
  destination: "back" | "close",
@@ -451,13 +186,6 @@ function bindingText(
451
186
  .join("/");
452
187
  }
453
188
 
454
- function safeSearchText(value: string): string {
455
- return Array.from(stripVTControlCharacters(value), (character) => {
456
- const codePoint = character.codePointAt(0) ?? 0;
457
- return codePoint <= 0x1f || (codePoint >= 0x7f && codePoint <= 0x9f) ? "" : character;
458
- }).join("");
459
- }
460
-
461
189
  function safeDisplayText(value: string): string {
462
190
  return Array.from(stripVTControlCharacters(value), (character) => {
463
191
  const codePoint = character.codePointAt(0) ?? 0;
package/src/commands.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { AutocompleteItem } from "@earendil-works/pi-tui";
3
3
  import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
4
- import { showFooterExplanation, showModuleBrowser } from "./command-inspector.js";
4
+ import { showFooterExplanation } from "./command-inspector.js";
5
5
  import { type PreviewMenuResult, showPreviewActionMenu } from "./command-preview.js";
6
6
  import {
7
7
  atomicRestoreConfigDocument,
@@ -104,8 +104,8 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
104
104
  signal: fallbackController.signal,
105
105
  isCurrent: () => !fallbackController.signal.aborted,
106
106
  };
107
- type Screen = "main" | "configuration" | "help";
108
- type Action = "customize" | "explain" | "modules" | "restore";
107
+ type Screen = "main" | "modules" | "configuration" | "help";
108
+ type Action = "customize" | "explain" | "restore";
109
109
  const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
110
110
  start: "main",
111
111
  screens: {
@@ -133,7 +133,7 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
133
133
  id: MAIN_ACTIONS.modules,
134
134
  label: "Modules",
135
135
  description: "Browse supported modules and current states",
136
- action: "modules",
136
+ to: "modules",
137
137
  },
138
138
  {
139
139
  id: MAIN_ACTIONS.configuration,
@@ -158,6 +158,34 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
158
158
  hint: "close",
159
159
  };
160
160
  },
161
+ modules: () => {
162
+ const inspection =
163
+ options.getInspection?.() ?? inspectUnavailableModules(options.getLoaded().config);
164
+ return {
165
+ kind: "browse",
166
+ title: "Modules",
167
+ items: inspection.modules.map((module) => ({
168
+ id: module.name,
169
+ label: module.name,
170
+ statusText: module.state,
171
+ description: module.description,
172
+ searchText: [...module.variables, ...module.styleFields, ...module.displayRules].join(
173
+ " ",
174
+ ),
175
+ details: [
176
+ `Root: ${module.rootReferenced ? "Referenced" : "Not referenced"}`,
177
+ `Reachable: ${module.reachable ? "Yes" : "No"}`,
178
+ ...modulePreviewDetails(module.preview),
179
+ `Reason: ${module.reason}`,
180
+ `Variables: ${module.variables.join(", ") || "none"}`,
181
+ `Style fields: ${module.styleFields.join(", ") || "none"}`,
182
+ `Display rules: ${module.displayRules.join(" · ") || "none"}`,
183
+ ],
184
+ })),
185
+ viewportSize: "adaptive",
186
+ hint: "back",
187
+ };
188
+ },
161
189
  configuration: () => {
162
190
  const loaded = options.getLoaded();
163
191
  const presentation = configurationPresentation(loaded);
@@ -197,13 +225,6 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
197
225
  if (!isCurrentOwner(owner)) return { kind: "stay" };
198
226
  return result?.kind === "back" ? { kind: "stay" } : { kind: "close" };
199
227
  },
200
- modules: async () => {
201
- const inspection =
202
- options.getInspection?.() ?? inspectUnavailableModules(options.getLoaded().config);
203
- const result = await showModuleBrowser(ctx, inspection, owner.signal);
204
- if (!isCurrentOwner(owner)) return { kind: "stay" };
205
- return result?.kind === "back" ? { kind: "stay" } : { kind: "close" };
206
- },
207
228
  restore: async () => {
208
229
  const presentation = configurationPresentation(options.getLoaded());
209
230
  if (presentation.restoreDisabled) {
@@ -366,6 +387,11 @@ async function reviewAndApply(
366
387
  }
367
388
  }
368
389
 
390
+ function modulePreviewDetails(preview: string): string[] {
391
+ const lines = preview ? preview.split("\n") : ["(no current preview)"];
392
+ return lines.map((line, index) => `${index === 0 ? "Preview: " : " "}${line}`);
393
+ }
394
+
369
395
  function workflowOwner(options: StarshipCommandOptions): WorkflowOwner {
370
396
  if (options.getMenuOwner) return options.getMenuOwner();
371
397
  const controller = new AbortController();
@@ -1,3 +1,4 @@
1
+ import { truncatePathComponents } from "./truncation.js";
1
2
  import { defineModule, type ModuleDefinition, type ModuleOptionSchema } from "./types.js";
2
3
  import { workspaceModuleValues } from "./workspace-helpers.js";
3
4
 
@@ -47,13 +48,29 @@ export const direnvModule = developmentModule({
47
48
  options: directDetection,
48
49
  });
49
50
 
50
- export const condaModule = developmentModule({
51
+ export const condaModule = defineModule({
51
52
  name: "conda",
52
- variables: ["environment"],
53
- format: "via [$symbol$environment]($style) ",
54
- symbol: "🅒 ",
55
- style: "green bold",
56
- options: { ignore_base: { kind: "boolean", default: true } },
53
+ variables: ["symbol", "environment"],
54
+ defaults: {
55
+ format: "via [$symbol$environment]($style) ",
56
+ symbol: "🅒 ",
57
+ style: "green bold",
58
+ disabled: false,
59
+ },
60
+ options: {
61
+ ignore_base: { kind: "boolean", default: true },
62
+ truncation_length: { kind: "integer", default: 1, minimum: 0, maximum: 1_000_000 },
63
+ },
64
+ values: (context) => {
65
+ const values = workspaceModuleValues("conda", context);
66
+ const environment = values?.environment;
67
+ if (!environment) return undefined;
68
+ const length =
69
+ typeof context.options.truncation_length === "number" ? context.options.truncation_length : 1;
70
+ return {
71
+ environment: truncatePathComponents(environment, length).value,
72
+ };
73
+ },
57
74
  });
58
75
 
59
76
  export const pixiModule = developmentModule({
@@ -1,5 +1,12 @@
1
- import { basename } from "node:path";
2
- import { defineModule } from "./types.js";
1
+ import { basename, isAbsolute, relative, sep } from "node:path";
2
+ import { sanitizeTerminalText } from "./terminal.js";
3
+ import {
4
+ graphemes,
5
+ toSlashPath,
6
+ truncatePathComponents,
7
+ useNativePathSeparator,
8
+ } from "./truncation.js";
9
+ import { defineModule, type ModuleOptionValue } from "./types.js";
3
10
 
4
11
  export const directoryModule = defineModule({
5
12
  name: "directory",
@@ -10,8 +17,135 @@ export const directoryModule = defineModule({
10
17
  style: "cyan bold",
11
18
  disabled: false,
12
19
  },
13
- values: ({ runtime }) => ({
14
- path: basename(runtime.cwd) || runtime.cwd,
15
- full_path: runtime.cwd,
16
- }),
20
+ options: {
21
+ truncation_length: { kind: "integer", default: 3, minimum: 0, maximum: 1_000_000 },
22
+ truncate_to_repo: { kind: "boolean", default: true },
23
+ fish_style_pwd_dir_length: { kind: "integer", default: 0, minimum: 0, maximum: 1_000 },
24
+ truncation_symbol: { kind: "string", default: "" },
25
+ home_symbol: { kind: "string", default: "~" },
26
+ use_os_path_sep: { kind: "boolean", default: true },
27
+ substitutions: { kind: "string-map", default: {} },
28
+ },
29
+ values: ({ runtime, options }) => {
30
+ const fullPath = runtime.cwd;
31
+ const home = runtime.homeDir;
32
+ const repoRoot = runtime.gitRoot;
33
+ const homeSymbol = stringOption(options, "home_symbol", "~");
34
+ const truncateToRepo = booleanOption(options, "truncate_to_repo", true);
35
+ const substitutions = mapOption(options, "substitutions");
36
+ const homeContracted = contractPath(fullPath, home, homeSymbol);
37
+ const repoContracted =
38
+ truncateToRepo && repoRoot && (!home || !samePath(repoRoot, home))
39
+ ? contractRepositoryPath(fullPath, repoRoot)
40
+ : undefined;
41
+ let path = sanitizeTerminalText(repoContracted ?? homeContracted);
42
+ let truncated = repoContracted !== undefined;
43
+
44
+ for (const [from, to] of Object.entries(substitutions)) {
45
+ if (from) path = path.replaceAll(from, to);
46
+ }
47
+
48
+ const componentResult = truncatePathComponents(
49
+ path,
50
+ numberOption(options, "truncation_length", 3),
51
+ );
52
+ path = componentResult.value;
53
+ truncated ||= componentResult.truncated;
54
+
55
+ if (truncated) {
56
+ const fishLength = numberOption(options, "fish_style_pwd_dir_length", 0);
57
+ if (fishLength > 0 && Object.keys(substitutions).length === 0) {
58
+ path = `${fishPrefix(homeContracted, path, fishLength)}${path}`;
59
+ } else {
60
+ path = `${stringOption(options, "truncation_symbol", "")}${path}`;
61
+ }
62
+ }
63
+
64
+ if (booleanOption(options, "use_os_path_sep", true)) path = useNativePathSeparator(path);
65
+ const fallback = basename(fullPath) || fullPath;
66
+ return {
67
+ path: sanitizeTerminalText(path || fallback),
68
+ full_path: sanitizeTerminalText(fullPath),
69
+ };
70
+ },
17
71
  });
72
+
73
+ function contractPath(path: string, root: string | undefined, replacement: string): string {
74
+ if (!root) return toSlashPath(path);
75
+ const child = relativeWithin(path, root);
76
+ if (child === undefined) return toSlashPath(path);
77
+ return child ? `${replacement}/${child}` : replacement;
78
+ }
79
+
80
+ function contractRepositoryPath(path: string, root: string): string | undefined {
81
+ const child = relativeWithin(path, root);
82
+ if (child === undefined) return undefined;
83
+ const name = basename(root) || toSlashPath(root);
84
+ return child ? `${name}/${child}` : name;
85
+ }
86
+
87
+ function relativeWithin(path: string, root: string): string | undefined {
88
+ const child = relative(root, path);
89
+ if (child === "") return "";
90
+ if (child === ".." || child.startsWith(`..${sep}`) || isAbsolute(child)) return undefined;
91
+ return toSlashPath(child);
92
+ }
93
+
94
+ function samePath(left: string, right: string): boolean {
95
+ return relative(left, right) === "";
96
+ }
97
+
98
+ function fishPrefix(source: string, displayed: string, length: number): string {
99
+ const prefix = source.endsWith(displayed) ? source.slice(0, -displayed.length) : "";
100
+ if (!prefix) return "";
101
+ return prefix
102
+ .split("/")
103
+ .map((component) => abbreviateComponent(component, length))
104
+ .join("/");
105
+ }
106
+
107
+ function abbreviateComponent(component: string, length: number): string {
108
+ if (!component) return "";
109
+ const parts = graphemes(component);
110
+ if (parts.length <= length) return component;
111
+ return component.startsWith(".")
112
+ ? parts.slice(0, length + 1).join("")
113
+ : parts.slice(0, length).join("");
114
+ }
115
+
116
+ function numberOption(
117
+ options: Readonly<Record<string, ModuleOptionValue>>,
118
+ name: string,
119
+ fallback: number,
120
+ ): number {
121
+ const value = options[name];
122
+ return typeof value === "number" ? value : fallback;
123
+ }
124
+
125
+ function stringOption(
126
+ options: Readonly<Record<string, ModuleOptionValue>>,
127
+ name: string,
128
+ fallback: string,
129
+ ): string {
130
+ const value = options[name];
131
+ return typeof value === "string" ? value : fallback;
132
+ }
133
+
134
+ function booleanOption(
135
+ options: Readonly<Record<string, ModuleOptionValue>>,
136
+ name: string,
137
+ fallback: boolean,
138
+ ): boolean {
139
+ const value = options[name];
140
+ return typeof value === "boolean" ? value : fallback;
141
+ }
142
+
143
+ function mapOption(
144
+ options: Readonly<Record<string, ModuleOptionValue>>,
145
+ name: string,
146
+ ): Readonly<Record<string, string>> {
147
+ const value = options[name];
148
+ return value && typeof value === "object" && !Array.isArray(value)
149
+ ? (value as Readonly<Record<string, string>>)
150
+ : {};
151
+ }
@@ -42,7 +42,7 @@ export const hostnameModule = defineModule({
42
42
  },
43
43
  options: {
44
44
  ssh_only: { kind: "boolean", default: true },
45
- trim_at: { kind: "string", default: ".", allowEmpty: false },
45
+ trim_at: { kind: "string", default: "." },
46
46
  aliases: { kind: "string-map", default: {} },
47
47
  },
48
48
  values: (context) => workspaceModuleValues("hostname", context),
@@ -1,3 +1,4 @@
1
+ import { truncateLeadingGraphemes } from "../truncation.js";
1
2
  import { defineModule } from "../types.js";
2
3
 
3
4
  export const gitBranchModule = defineModule({
@@ -9,14 +10,22 @@ export const gitBranchModule = defineModule({
9
10
  style: "bold purple",
10
11
  disabled: false,
11
12
  },
12
- values: ({ runtime }) => {
13
+ options: {
14
+ // Starship uses i64::MAX as its effective no-truncation default. Zero is the
15
+ // equivalent stable TOML representation in pi-starship's bounded integer schema.
16
+ truncation_length: { kind: "integer", default: 0, minimum: 0, maximum: 1_000_000 },
17
+ truncation_symbol: { kind: "string", default: "…" },
18
+ },
19
+ values: ({ runtime, options }) => {
13
20
  const branch = runtime.gitBranchDetails;
14
21
  const name = branch?.name ?? runtime.gitBranch;
15
22
  if (!name) return undefined;
23
+ const length = typeof options.truncation_length === "number" ? options.truncation_length : 0;
24
+ const symbol = typeof options.truncation_symbol === "string" ? options.truncation_symbol : "…";
16
25
  return {
17
- branch: name,
18
- remote_name: branch?.remoteName ?? "",
19
- remote_branch: branch?.remoteBranch ?? "",
26
+ branch: truncateLeadingGraphemes(name, length, symbol),
27
+ remote_name: truncateLeadingGraphemes(branch?.remoteName ?? "", length, symbol),
28
+ remote_branch: truncateLeadingGraphemes(branch?.remoteBranch ?? "", length, symbol),
20
29
  };
21
30
  },
22
31
  });
@@ -11,11 +11,18 @@ export const gitCommitModule = defineModule({
11
11
  style: "green bold",
12
12
  disabled: false,
13
13
  },
14
- values: ({ runtime }) => {
14
+ options: {
15
+ commit_hash_length: { kind: "integer", default: DEFAULT_HASH_LENGTH, minimum: 0, maximum: 64 },
16
+ },
17
+ values: ({ runtime, options }) => {
15
18
  const commit = runtime.gitCommit;
16
19
  if (!commit) return undefined;
20
+ const hashLength =
21
+ typeof options.commit_hash_length === "number"
22
+ ? options.commit_hash_length
23
+ : DEFAULT_HASH_LENGTH;
17
24
  return {
18
- hash: commit.hash.slice(0, DEFAULT_HASH_LENGTH),
25
+ hash: commit.hash.slice(0, hashLength),
19
26
  tag: commit.tag ? ` 🏷 ${commit.tag}` : "",
20
27
  };
21
28
  },
@@ -77,6 +77,7 @@ export async function readGitSnapshot(
77
77
 
78
78
  return {
79
79
  ...parsed,
80
+ root: metadata?.root,
80
81
  commit,
81
82
  state: metadata ? parseGitState(metadata.gitDirectory) : undefined,
82
83
  metrics,
@@ -250,6 +251,7 @@ export function parseGitState(gitDirectory: string): GitStateSnapshot | undefine
250
251
  }
251
252
 
252
253
  interface GitRepositoryMetadata {
254
+ root: string;
253
255
  gitDirectory: string;
254
256
  worktree?: GitWorktreeSnapshot;
255
257
  }
@@ -261,6 +263,7 @@ function parseGitRepositoryMetadata(output: string): GitRepositoryMetadata | und
261
263
  if (!path || !commonDir || !gitDirectory) return undefined;
262
264
  if (![path, commonDir, gitDirectory].every(isAbsolute)) return undefined;
263
265
  return {
266
+ root: path,
264
267
  gitDirectory,
265
268
  worktree: samePath(commonDir, gitDirectory)
266
269
  ? undefined
@@ -1,3 +1,4 @@
1
+ import { sanitizeTerminalText } from "./terminal.js";
1
2
  import { defineModule } from "./types.js";
2
3
 
3
4
  const TRUNCATION_DIRECTIONS = ["start", "middle", "end"] as const;
@@ -21,6 +22,7 @@ export const modelModule = defineModule({
21
22
  default: "end",
22
23
  values: TRUNCATION_DIRECTIONS,
23
24
  },
25
+ model_aliases: { kind: "string-map", default: {} },
24
26
  },
25
27
  values: ({ runtime, options }) => {
26
28
  if (!runtime.model) return undefined;
@@ -29,8 +31,17 @@ export const modelModule = defineModule({
29
31
  const direction = isTruncationDirection(options.truncation_direction)
30
32
  ? options.truncation_direction
31
33
  : "end";
34
+ const aliases = options.model_aliases;
35
+ const aliasMap =
36
+ aliases && typeof aliases === "object" && !Array.isArray(aliases)
37
+ ? (aliases as Readonly<Record<string, string>>)
38
+ : undefined;
39
+ const alias =
40
+ aliasMap && Object.hasOwn(aliasMap, runtime.model.id)
41
+ ? aliasMap[runtime.model.id]
42
+ : undefined;
32
43
  return {
33
- model: truncateModel(shortenModel(runtime.model.id), length, symbol, direction),
44
+ model: truncateModel(alias ?? shortenModel(runtime.model.id), length, symbol, direction),
34
45
  };
35
46
  },
36
47
  });
@@ -41,11 +52,11 @@ export function truncateModel(
41
52
  symbol: string,
42
53
  direction: TruncationDirection,
43
54
  ): string {
44
- const safeModel = sanitizeModelDisplay(model);
55
+ const safeModel = sanitizeTerminalText(model);
45
56
  if (length === 0) return safeModel;
46
57
  const graphemes = [...graphemeSegmenter.segment(safeModel)].map(({ segment }) => segment);
47
58
  if (graphemes.length <= length) return safeModel;
48
- const safeSymbol = sanitizeModelDisplay(symbol);
59
+ const safeSymbol = sanitizeTerminalText(symbol);
49
60
 
50
61
  switch (direction) {
51
62
  case "start":
@@ -61,67 +72,6 @@ export function truncateModel(
61
72
  }
62
73
  }
63
74
 
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
75
  function isTruncationDirection(value: unknown): value is TruncationDirection {
126
76
  return TRUNCATION_DIRECTIONS.includes(value as TruncationDirection);
127
77
  }
@@ -0,0 +1,60 @@
1
+ export function sanitizeTerminalText(value: string): string {
2
+ let result = "";
3
+ for (let index = 0; index < value.length; ) {
4
+ const codePoint = value.codePointAt(index) ?? 0;
5
+ const character = String.fromCodePoint(codePoint);
6
+ if (codePoint === 0x1b || codePoint === 0x9b || codePoint === 0x9d) {
7
+ index = skipTerminalEscape(value, index, codePoint);
8
+ continue;
9
+ }
10
+ if (
11
+ codePoint <= 0x1f ||
12
+ (codePoint >= 0x7f && codePoint <= 0x9f) ||
13
+ codePoint === 0x2028 ||
14
+ codePoint === 0x2029
15
+ ) {
16
+ if (
17
+ codePoint === 0x09 ||
18
+ codePoint === 0x0a ||
19
+ codePoint === 0x0d ||
20
+ codePoint === 0x85 ||
21
+ codePoint === 0x2028 ||
22
+ codePoint === 0x2029
23
+ ) {
24
+ result += " ";
25
+ }
26
+ index += character.length;
27
+ continue;
28
+ }
29
+ result += character;
30
+ index += character.length;
31
+ }
32
+ return result;
33
+ }
34
+
35
+ function skipTerminalEscape(value: string, start: number, codePoint: number): number {
36
+ let index = start + 1;
37
+ const next = value.charCodeAt(index);
38
+ const isOsc = codePoint === 0x9d || (codePoint === 0x1b && next === 0x5d);
39
+ if (isOsc) {
40
+ if (codePoint === 0x1b) index += 1;
41
+ while (index < value.length) {
42
+ const current = value.charCodeAt(index);
43
+ if (current === 0x07 || current === 0x9c) return index + 1;
44
+ if (current === 0x1b && value.charCodeAt(index + 1) === 0x5c) return index + 2;
45
+ index += 1;
46
+ }
47
+ return index;
48
+ }
49
+ const isCsi = codePoint === 0x9b || (codePoint === 0x1b && next === 0x5b);
50
+ if (isCsi) {
51
+ if (codePoint === 0x1b) index += 1;
52
+ while (index < value.length) {
53
+ const current = value.charCodeAt(index);
54
+ index += 1;
55
+ if (current >= 0x40 && current <= 0x7e) break;
56
+ }
57
+ return index;
58
+ }
59
+ return Math.min(value.length, start + (codePoint === 0x1b ? 2 : 1));
60
+ }
@@ -0,0 +1,37 @@
1
+ import { sep } from "node:path";
2
+
3
+ const graphemeSegmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
4
+
5
+ export function graphemes(value: string): string[] {
6
+ return [...graphemeSegmenter.segment(value)].map(({ segment }) => segment);
7
+ }
8
+
9
+ export function firstGrapheme(value: string): string {
10
+ return graphemes(value)[0] ?? "";
11
+ }
12
+
13
+ export function truncateLeadingGraphemes(value: string, length: number, symbol: string): string {
14
+ if (length <= 0) return value;
15
+ const parts = graphemes(value);
16
+ if (parts.length <= length) return value;
17
+ return `${parts.slice(0, length).join("")}${firstGrapheme(symbol)}`;
18
+ }
19
+
20
+ export function toSlashPath(value: string): string {
21
+ return sep === "\\" ? value.replaceAll("\\", "/") : value;
22
+ }
23
+
24
+ export function truncatePathComponents(
25
+ value: string,
26
+ length: number,
27
+ ): { value: string; truncated: boolean } {
28
+ if (length <= 0) return { value, truncated: false };
29
+ const normalized = toSlashPath(value);
30
+ const components = normalized.split("/").filter((component) => component.length > 0);
31
+ if (components.length <= length) return { value: normalized, truncated: false };
32
+ return { value: components.slice(-length).join("/"), truncated: true };
33
+ }
34
+
35
+ export function useNativePathSeparator(value: string): string {
36
+ return sep === "/" ? value : value.replaceAll("/", sep);
37
+ }
@@ -63,6 +63,7 @@ export interface GithubPrSnapshot {
63
63
  }
64
64
 
65
65
  export interface GitSnapshot {
66
+ root?: string;
66
67
  branch?: GitBranchSnapshot;
67
68
  commit?: GitCommitSnapshot;
68
69
  state?: GitStateSnapshot;
@@ -78,6 +79,8 @@ export interface WorkspaceSnapshot {
78
79
 
79
80
  export interface StarshipRuntimeSnapshot {
80
81
  cwd: string;
82
+ homeDir?: string;
83
+ gitRoot?: string;
81
84
  model?: { provider: string; id: string };
82
85
  thinkingLevel: string;
83
86
  turnCount: number;
@@ -90,7 +90,10 @@ export default function piStarship(pi: ExtensionAPI, options: PiStarshipOptions
90
90
  const gitController = new AsyncRefreshController<GitRefreshInput, GitSnapshot | undefined>({
91
91
  async read(input, signal) {
92
92
  const requirements = reachableModuleRequirements(input.config);
93
- const gitReachable = [...requirements.keys()].some((name) => name.startsWith("git_"));
93
+ const gitReachable =
94
+ [...requirements.keys()].some((name) => name.startsWith("git_")) ||
95
+ (requirements.has("directory") &&
96
+ input.config.modules.directory.options.truncate_to_repo === true);
94
97
  if (!gitReachable) return undefined;
95
98
  try {
96
99
  return await readGitSnapshot(pi, input.cwd, {
@@ -521,6 +524,8 @@ function runtimeSnapshot(
521
524
  ): StarshipRuntimeSnapshot {
522
525
  return {
523
526
  cwd: ctx.cwd,
527
+ homeDir: homedir(),
528
+ gitRoot: runtime.git?.root,
524
529
  model: ctx.model ? { provider: ctx.model.provider, id: ctx.model.id } : undefined,
525
530
  thinkingLevel: runtime.thinkingLevel,
526
531
  turnCount: userTurnCount(ctx),
@@ -8,7 +8,6 @@ import {
8
8
  optionBoolean,
9
9
  optionString,
10
10
  optionStrings,
11
- pathName,
12
11
  runBounded,
13
12
  safeMetadata,
14
13
  setString,
@@ -51,7 +50,7 @@ export async function collectDevelopment(
51
50
  conda &&
52
51
  !(optionBoolean(context, "conda", "ignore_base") && conda === "base")
53
52
  ) {
54
- result.conda = { environment: pathName(conda) };
53
+ result.conda = { environment: conda };
55
54
  }
56
55
 
57
56
  if (context.needs("pixi") && detected(context, entries, "pixi", ["pixi.toml", "pixi.lock"])) {
@@ -98,12 +98,10 @@ function hostnameValues(context: CollectorContext): Record<string, string> | und
98
98
  const raw = safeMetadata(context.input.hostname);
99
99
  if (!raw) return undefined;
100
100
  const aliases = optionMap(context, "hostname", "aliases");
101
- let hostname = exactAlias(raw, aliases) ?? raw;
102
- if (hostname === raw) {
103
- const trimAt = optionString(context, "hostname", "trim_at");
104
- const index = trimAt ? hostname.indexOf(trimAt) : -1;
105
- if (index > 0) hostname = hostname.slice(0, index);
106
- }
101
+ const trimAt = optionString(context, "hostname", "trim_at");
102
+ const index = trimAt ? raw.indexOf(trimAt) : -1;
103
+ const trimmed = index >= 0 ? raw.slice(0, index) : raw;
104
+ const hostname = exactAlias(trimmed, aliases) ?? trimmed;
107
105
  return { hostname, ssh_symbol: ssh ? "🌐 " : "" };
108
106
  }
109
107