@narumitw/pi-starship 0.49.3 → 0.50.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.
Files changed (100) hide show
  1. package/NOTICES.md +4 -2
  2. package/README.md +62 -16
  3. package/package.json +10 -11
  4. package/src/command-contract.ts +13 -0
  5. package/src/command-inspector.ts +198 -0
  6. package/src/command-preset-picker.ts +203 -0
  7. package/src/command-preview.ts +206 -0
  8. package/src/commands.ts +784 -0
  9. package/src/config.ts +794 -0
  10. package/src/format/formatter.ts +275 -0
  11. package/src/format/style.ts +278 -0
  12. package/src/index.ts +1 -1
  13. package/src/modules/activity.ts +38 -0
  14. package/src/modules/brand.ts +13 -0
  15. package/src/modules/cache.ts +23 -0
  16. package/src/modules/catalog.ts +124 -0
  17. package/src/modules/cloud.ts +74 -0
  18. package/src/modules/context.ts +33 -0
  19. package/src/modules/cost.ts +31 -0
  20. package/src/modules/deployment.ts +61 -0
  21. package/src/modules/development.ts +112 -0
  22. package/src/modules/directory.ts +151 -0
  23. package/src/modules/display.ts +14 -0
  24. package/src/modules/execution.ts +84 -0
  25. package/src/modules/extension-status.ts +93 -0
  26. package/src/modules/fill.ts +14 -0
  27. package/src/modules/git/branch.ts +31 -0
  28. package/src/modules/git/commit.ts +29 -0
  29. package/src/modules/git/metrics.ts +26 -0
  30. package/src/modules/git/runtime.ts +415 -0
  31. package/src/modules/git/state.ts +21 -0
  32. package/src/modules/git/status.ts +87 -0
  33. package/src/modules/git/worktree.ts +16 -0
  34. package/src/modules/github-pr.ts +24 -0
  35. package/src/modules/helpers.ts +5 -0
  36. package/src/modules/index.ts +31 -0
  37. package/src/modules/inspection.ts +138 -0
  38. package/src/modules/languages.ts +87 -0
  39. package/src/modules/model.ts +85 -0
  40. package/src/modules/package.ts +17 -0
  41. package/src/modules/provider.ts +13 -0
  42. package/src/modules/render.ts +166 -0
  43. package/src/modules/terminal.ts +60 -0
  44. package/src/modules/thinking.ts +13 -0
  45. package/src/modules/time.ts +20 -0
  46. package/src/modules/tokens.ts +18 -0
  47. package/src/modules/truncation.ts +37 -0
  48. package/src/modules/turn.ts +13 -0
  49. package/src/modules/types.ts +189 -0
  50. package/src/modules/workspace-helpers.ts +10 -0
  51. package/src/pi-starship.ts +619 -0
  52. package/src/presets/bracketed-segments.ts +45 -0
  53. package/src/presets/catalog.ts +138 -0
  54. package/src/presets/catppuccin-powerline.ts +90 -0
  55. package/src/presets/gruvbox-rainbow.ts +66 -0
  56. package/src/presets/jetpack.ts +51 -0
  57. package/src/presets/minimal.ts +23 -0
  58. package/src/presets/nerd-font-symbols.ts +27 -0
  59. package/src/presets/no-empty-icons.ts +47 -0
  60. package/src/presets/no-nerd-font.ts +51 -0
  61. package/src/presets/no-runtime-versions.ts +52 -0
  62. package/src/presets/pastel-powerline.ts +53 -0
  63. package/src/presets/plain-text-symbols.ts +52 -0
  64. package/src/presets/pure-preset.ts +55 -0
  65. package/src/presets/tokyo-night.ts +53 -0
  66. package/src/runtime/cloud.ts +166 -0
  67. package/src/runtime/command.ts +123 -0
  68. package/src/runtime/deployment.ts +201 -0
  69. package/src/runtime/development.ts +153 -0
  70. package/src/runtime/execution.ts +151 -0
  71. package/src/runtime/github-pr.ts +332 -0
  72. package/src/runtime/helpers.ts +274 -0
  73. package/src/runtime/languages.ts +205 -0
  74. package/src/runtime/package.ts +112 -0
  75. package/src/runtime/refresh-controller.ts +107 -0
  76. package/src/runtime/types.ts +63 -0
  77. package/src/runtime/workspace.ts +147 -0
  78. package/src/usage.ts +53 -0
  79. package/dist/chunks/chunk-CKNSOLSW.ts +0 -10
  80. package/dist/chunks/chunk-CKNSOLSW.ts.map +0 -7
  81. package/dist/chunks/chunk-G2GG2V6Q.ts +0 -218
  82. package/dist/chunks/chunk-G2GG2V6Q.ts.map +0 -7
  83. package/dist/chunks/chunk-Q6DLIM7H.ts +0 -2492
  84. package/dist/chunks/chunk-Q6DLIM7H.ts.map +0 -7
  85. package/dist/chunks/cloud-JBSZWTB6.ts +0 -142
  86. package/dist/chunks/cloud-JBSZWTB6.ts.map +0 -7
  87. package/dist/chunks/commands-BSQZ2R4M.ts +0 -757
  88. package/dist/chunks/commands-BSQZ2R4M.ts.map +0 -7
  89. package/dist/chunks/deployment-ZNYM4B6W.ts +0 -172
  90. package/dist/chunks/deployment-ZNYM4B6W.ts.map +0 -7
  91. package/dist/chunks/development-TNWZ5SRC.ts +0 -132
  92. package/dist/chunks/development-TNWZ5SRC.ts.map +0 -7
  93. package/dist/chunks/execution-QHAP4U33.ts +0 -132
  94. package/dist/chunks/execution-QHAP4U33.ts.map +0 -7
  95. package/dist/chunks/languages-DPWDCH6Q.ts +0 -184
  96. package/dist/chunks/languages-DPWDCH6Q.ts.map +0 -7
  97. package/dist/chunks/package-MXN2YFLX.ts +0 -104
  98. package/dist/chunks/package-MXN2YFLX.ts.map +0 -7
  99. package/dist/pi-starship.ts +0 -1350
  100. package/dist/pi-starship.ts.map +0 -7
@@ -0,0 +1,784 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
+ import { completeStarshipArguments, STARSHIP_SUBCOMMANDS } from "./command-contract.js";
4
+ import { showFooterExplanation } from "./command-inspector.js";
5
+ import { showPresetPicker } from "./command-preset-picker.js";
6
+ import { type PreviewMenuResult, showPreviewActionMenu } from "./command-preview.js";
7
+ import {
8
+ atomicRestoreConfigDocument,
9
+ atomicSaveConfigDocument,
10
+ BUILT_IN_EXAMPLE,
11
+ type LoadedStarshipConfig,
12
+ removeConfigDocumentIfMatches,
13
+ validateConfigDocument,
14
+ } from "./config.js";
15
+ import { inspectUnavailableModules, type StatuslineInspection } from "./modules/inspection.js";
16
+ import {
17
+ getStarshipPreset,
18
+ presetForDocument,
19
+ STARSHIP_PRESETS,
20
+ type StarshipPreset,
21
+ } from "./presets/catalog.js";
22
+
23
+ const MAIN_ACTIONS = {
24
+ customize: "customize",
25
+ presets: "presets",
26
+ explain: "explain",
27
+ modules: "modules",
28
+ configuration: "configuration",
29
+ help: "help",
30
+ restore: "restore",
31
+ } as const;
32
+
33
+ const PREVIEW_ACTIONS = {
34
+ continue: "continue",
35
+ edit: "edit",
36
+ cancel: "cancel",
37
+ } as const;
38
+
39
+ export interface StarshipCommandOptions {
40
+ getLoaded(): LoadedStarshipConfig;
41
+ getInspection?(): StatuslineInspection | undefined;
42
+ apply(loaded: LoadedStarshipConfig, ctx: ExtensionCommandContext): void;
43
+ preview?(loaded: LoadedStarshipConfig | undefined, ctx: ExtensionCommandContext): void;
44
+ settingsPath: string;
45
+ renderPreview?(
46
+ loaded: LoadedStarshipConfig,
47
+ width: number,
48
+ ctx: ExtensionCommandContext,
49
+ ): string[];
50
+ save?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
51
+ restore?: (settingsPath: string, rawDocument: string) => void;
52
+ validate?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
53
+ getMenuOwner?(): { signal: AbortSignal; isCurrent(): boolean };
54
+ }
55
+
56
+ interface WorkflowOwner {
57
+ signal: AbortSignal;
58
+ isCurrent(): boolean;
59
+ }
60
+
61
+ type ReviewIntent =
62
+ | { kind: "customize" }
63
+ | { kind: "restore" }
64
+ | { kind: "preset"; preset: StarshipPreset };
65
+
66
+ export function registerStarshipCommand(pi: ExtensionAPI, options: StarshipCommandOptions) {
67
+ pi.registerCommand("starship", {
68
+ description: "Customize or inspect the native Starship-style footer",
69
+ getArgumentCompletions: completeStarshipArguments,
70
+ handler: (args, ctx) => handleStarshipCommand(args, ctx, options),
71
+ });
72
+ }
73
+
74
+ export async function handleStarshipCommand(
75
+ args: string,
76
+ ctx: ExtensionCommandContext,
77
+ options: StarshipCommandOptions,
78
+ ) {
79
+ const normalized = args.trim();
80
+ if (!normalized) {
81
+ if (ctx.mode === "tui") await showMainMenu(ctx, options);
82
+ else showHelp(ctx, options.settingsPath);
83
+ return;
84
+ }
85
+
86
+ const [subcommand = "", ...trailing] = normalized.split(/\s+/u);
87
+ const route = subcommand.toLowerCase();
88
+ if (trailing.length > 0 || !STARSHIP_SUBCOMMANDS.some((item) => item.value === route)) {
89
+ if (canNotify(ctx)) {
90
+ const reason =
91
+ trailing.length > 0
92
+ ? `Unexpected arguments for /starship ${safeText(route)}.`
93
+ : `Unknown /starship subcommand: ${safeText(route)}.`;
94
+ ctx.ui.notify(`${reason} Usage: /starship [settings|status|help]`, "warning");
95
+ }
96
+ return;
97
+ }
98
+ switch (route) {
99
+ case "settings":
100
+ await editSettings(ctx, options);
101
+ return;
102
+ case "status":
103
+ showStatus(ctx, options);
104
+ return;
105
+ case "help":
106
+ showHelp(ctx, options.settingsPath);
107
+ return;
108
+ }
109
+ }
110
+
111
+ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipCommandOptions) {
112
+ const fallbackController = new AbortController();
113
+ const owner = options.getMenuOwner?.() ?? {
114
+ signal: fallbackController.signal,
115
+ isCurrent: () => !fallbackController.signal.aborted,
116
+ };
117
+ type Screen = "main" | "modules" | "configuration" | "help";
118
+ type Action = "customize" | "presets" | "explain" | "restore";
119
+ const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
120
+ start: "main",
121
+ screens: {
122
+ main: () => {
123
+ const loaded = options.getLoaded();
124
+ const presentation = configurationPresentation(loaded);
125
+ return {
126
+ kind: "actions",
127
+ title: "pi-starship",
128
+ lines: [`${presentation.state} · ${presentation.health}`],
129
+ items: [
130
+ {
131
+ id: MAIN_ACTIONS.customize,
132
+ label: "Customize footer",
133
+ description: `${presentation.state} · preview before applying`,
134
+ action: "customize",
135
+ },
136
+ {
137
+ id: MAIN_ACTIONS.presets,
138
+ label: "Presets",
139
+ description: "Browse and live-preview bundled footer starting points",
140
+ action: "presets",
141
+ },
142
+ {
143
+ id: MAIN_ACTIONS.explain,
144
+ label: "Explain footer",
145
+ description: "Why each visible module appears",
146
+ action: "explain",
147
+ },
148
+ {
149
+ id: MAIN_ACTIONS.modules,
150
+ label: "Modules",
151
+ description: "Browse supported modules and current states",
152
+ to: "modules",
153
+ },
154
+ {
155
+ id: MAIN_ACTIONS.configuration,
156
+ label: "Configuration",
157
+ description: presentation.health,
158
+ to: "configuration",
159
+ },
160
+ {
161
+ id: MAIN_ACTIONS.help,
162
+ label: "Help",
163
+ description: "Formats, modules, and commands",
164
+ to: "help",
165
+ },
166
+ {
167
+ id: MAIN_ACTIONS.restore,
168
+ label: "Restore built-in…",
169
+ description: presentation.restoreDescription,
170
+ disabled: presentation.restoreDisabled,
171
+ action: "restore",
172
+ },
173
+ ],
174
+ hint: "close",
175
+ };
176
+ },
177
+ modules: () => {
178
+ const inspection =
179
+ options.getInspection?.() ?? inspectUnavailableModules(options.getLoaded().config);
180
+ return {
181
+ kind: "browse",
182
+ title: "Modules",
183
+ items: inspection.modules.map((module) => ({
184
+ id: module.name,
185
+ label: module.name,
186
+ statusText: module.state,
187
+ description: module.description,
188
+ searchText: [...module.variables, ...module.styleFields, ...module.displayRules].join(
189
+ " ",
190
+ ),
191
+ details: [
192
+ `Root: ${module.rootReferenced ? "Referenced" : "Not referenced"}`,
193
+ `Reachable: ${module.reachable ? "Yes" : "No"}`,
194
+ ...modulePreviewDetails(module.preview),
195
+ `Reason: ${module.reason}`,
196
+ `Variables: ${module.variables.join(", ") || "none"}`,
197
+ `Style fields: ${module.styleFields.join(", ") || "none"}`,
198
+ `Display rules: ${module.displayRules.join(" · ") || "none"}`,
199
+ ],
200
+ })),
201
+ viewportSize: "adaptive",
202
+ hint: "back",
203
+ };
204
+ },
205
+ configuration: () => {
206
+ const loaded = options.getLoaded();
207
+ const presentation = configurationPresentation(loaded);
208
+ return {
209
+ kind: "detail",
210
+ title: "Configuration",
211
+ lines: [
212
+ `State: ${presentation.state}`,
213
+ `Source: ${presentation.source}`,
214
+ `Path: ${safeText(options.settingsPath)}`,
215
+ ...diagnosticLines(loaded, true),
216
+ ],
217
+ hint: "back",
218
+ };
219
+ },
220
+ help: () => ({
221
+ kind: "detail",
222
+ title: "pi-starship help",
223
+ lines: [
224
+ "Customize footer opens the TOML editor, then previews and confirms before saving.",
225
+ "Presets live-previews the cursor in the footer; Enter confirms apply and e customizes first.",
226
+ "Explain footer breaks down the modules currently showing from the existing snapshot.",
227
+ "Modules searches every supported module and explains its current read-only state.",
228
+ "Configuration explains state, source, path, and warnings without changing the footer.",
229
+ `Settings: ${safeText(options.settingsPath)}`,
230
+ "Docs: https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-starship",
231
+ ],
232
+ hint: "back",
233
+ }),
234
+ },
235
+ actions: {
236
+ customize: async () => {
237
+ const result = await editSettings(ctx, options);
238
+ return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
239
+ },
240
+ explain: async () => {
241
+ const result = await showFooterExplanation(ctx, options.getInspection?.(), owner.signal);
242
+ if (!isCurrentOwner(owner)) return { kind: "stay" };
243
+ return result?.kind === "back" ? { kind: "stay" } : { kind: "close" };
244
+ },
245
+ presets: async () => {
246
+ const result = await choosePreset(ctx, options, owner);
247
+ return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
248
+ },
249
+ restore: async () => {
250
+ const presentation = configurationPresentation(options.getLoaded());
251
+ if (presentation.restoreDisabled) {
252
+ ctx.ui.notify(presentation.restoreDescription, "info");
253
+ return { kind: "stay" };
254
+ }
255
+ const result = await restoreBuiltIn(ctx, options);
256
+ return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
257
+ },
258
+ },
259
+ });
260
+ try {
261
+ await runMenu(ctx, menu, {
262
+ getState: () => undefined,
263
+ signal: owner.signal,
264
+ isCurrent: owner.isCurrent,
265
+ });
266
+ } finally {
267
+ fallbackController.abort(new DOMException("Starship menu closed", "AbortError"));
268
+ }
269
+ }
270
+
271
+ async function editSettings(
272
+ ctx: ExtensionCommandContext,
273
+ options: StarshipCommandOptions,
274
+ ): Promise<"applied" | "cancel" | "close"> {
275
+ const owner = workflowOwner(options);
276
+ if (!isCurrentOwner(owner)) return "cancel";
277
+ if (ctx.mode !== "tui") {
278
+ if (ctx.hasUI) ctx.ui.notify(`Edit settings manually: ${options.settingsPath}`, "info");
279
+ return "cancel";
280
+ }
281
+ let draft = options.getLoaded().rawDocument ?? BUILT_IN_EXAMPLE;
282
+ while (true) {
283
+ const edited = await ctx.ui.editor("Customize footer — close to preview", draft);
284
+ if (!isCurrentOwner(owner) || edited === undefined) return "cancel";
285
+ draft = edited;
286
+ let validated: LoadedStarshipConfig;
287
+ try {
288
+ validated = (options.validate ?? validateConfigDocument)(options.settingsPath, draft);
289
+ } catch (error) {
290
+ ctx.ui.notify(`Footer draft is invalid: ${safeText(formatError(error))}`, "error");
291
+ const action = await showPreviewActionMenu(
292
+ ctx,
293
+ "Configuration needs attention",
294
+ () => [safeText(formatError(error)), "The current footer has not changed."],
295
+ [
296
+ { value: PREVIEW_ACTIONS.edit, label: "Continue editing" },
297
+ { value: PREVIEW_ACTIONS.cancel, label: "Discard draft" },
298
+ ],
299
+ owner.signal,
300
+ );
301
+ if (!isCurrentOwner(owner)) return "cancel";
302
+ if (action?.kind === "closed") return "close";
303
+ if (selectedPreviewAction(action) === PREVIEW_ACTIONS.edit) continue;
304
+ return "cancel";
305
+ }
306
+
307
+ const result = await reviewAndApply(ctx, options, validated, { kind: "customize" }, owner);
308
+ if (result === "edit") continue;
309
+ return result;
310
+ }
311
+ }
312
+
313
+ async function choosePreset(
314
+ ctx: ExtensionCommandContext,
315
+ options: StarshipCommandOptions,
316
+ owner: WorkflowOwner,
317
+ ): Promise<"applied" | "cancel" | "close"> {
318
+ const activePreset = presetForDocument(options.getLoaded().rawDocument);
319
+ const selection = await showPresetPicker(ctx, {
320
+ presets: STARSHIP_PRESETS,
321
+ activePresetId: activePreset?.id,
322
+ initialPresetId: activePreset?.id ?? STARSHIP_PRESETS[0]?.id,
323
+ signal: owner.signal,
324
+ isCurrent: owner.isCurrent,
325
+ preview(preset) {
326
+ const loaded = (options.validate ?? validateConfigDocument)(
327
+ options.settingsPath,
328
+ preset.rawDocument,
329
+ );
330
+ options.preview?.(loaded, ctx);
331
+ },
332
+ });
333
+ if (!isCurrentOwner(owner)) {
334
+ options.preview?.(undefined, ctx);
335
+ return "cancel";
336
+ }
337
+ if (selection.kind === "back" || selection.kind === "close") {
338
+ options.preview?.(undefined, ctx);
339
+ return selection.kind === "close" ? "close" : "cancel";
340
+ }
341
+
342
+ const preset = getStarshipPreset(selection.presetId);
343
+ try {
344
+ return await applyPreset(
345
+ ctx,
346
+ options,
347
+ preset,
348
+ selection.kind === "customize" ? "customize" : "confirm",
349
+ );
350
+ } finally {
351
+ options.preview?.(undefined, ctx);
352
+ }
353
+ }
354
+
355
+ async function applyPreset(
356
+ ctx: ExtensionCommandContext,
357
+ options: StarshipCommandOptions,
358
+ preset: StarshipPreset,
359
+ start: "review" | "confirm" | "customize" = "review",
360
+ ): Promise<"applied" | "cancel" | "close"> {
361
+ const owner = workflowOwner(options);
362
+ if (!isCurrentOwner(owner)) return "cancel";
363
+ let draft = preset.rawDocument;
364
+ if (start === "customize") {
365
+ const edited = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
366
+ if (!isCurrentOwner(owner) || edited === undefined) return "cancel";
367
+ draft = edited;
368
+ }
369
+ while (true) {
370
+ let validated: LoadedStarshipConfig;
371
+ try {
372
+ validated = (options.validate ?? validateConfigDocument)(options.settingsPath, draft);
373
+ } catch (error) {
374
+ ctx.ui.notify(`Preset draft is invalid: ${safeText(formatError(error))}`, "error");
375
+ const action = await showPreviewActionMenu(
376
+ ctx,
377
+ "Preset needs attention",
378
+ () => [safeText(formatError(error)), "The current footer has not changed."],
379
+ [
380
+ { value: PREVIEW_ACTIONS.edit, label: "Continue editing" },
381
+ { value: PREVIEW_ACTIONS.cancel, label: "Choose another preset" },
382
+ ],
383
+ owner.signal,
384
+ );
385
+ if (!isCurrentOwner(owner)) return "cancel";
386
+ if (action?.kind === "closed") return "close";
387
+ if (selectedPreviewAction(action) !== PREVIEW_ACTIONS.edit) return "cancel";
388
+ const edited = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
389
+ if (!isCurrentOwner(owner) || edited === undefined) return "cancel";
390
+ draft = edited;
391
+ continue;
392
+ }
393
+
394
+ const result = await reviewAndApply(
395
+ ctx,
396
+ options,
397
+ validated,
398
+ { kind: "preset", preset },
399
+ owner,
400
+ start === "confirm",
401
+ );
402
+ if (result !== "edit") return result;
403
+ const edited = await ctx.ui.editor(`Customize ${preset.label} preset`, draft);
404
+ if (!isCurrentOwner(owner) || edited === undefined) return "cancel";
405
+ draft = edited;
406
+ }
407
+ }
408
+
409
+ async function restoreBuiltIn(
410
+ ctx: ExtensionCommandContext,
411
+ options: StarshipCommandOptions,
412
+ ): Promise<"applied" | "cancel" | "close"> {
413
+ const owner = workflowOwner(options);
414
+ if (!isCurrentOwner(owner)) return "cancel";
415
+ const validated = (options.validate ?? validateConfigDocument)(
416
+ options.settingsPath,
417
+ BUILT_IN_EXAMPLE,
418
+ );
419
+ const result = await reviewAndApply(ctx, options, validated, { kind: "restore" }, owner);
420
+ return result === "edit" ? "cancel" : result;
421
+ }
422
+
423
+ async function reviewAndApply(
424
+ ctx: ExtensionCommandContext,
425
+ options: StarshipCommandOptions,
426
+ validated: LoadedStarshipConfig,
427
+ intent: ReviewIntent,
428
+ owner: WorkflowOwner,
429
+ skipReview = false,
430
+ ): Promise<"applied" | "edit" | "cancel" | "close"> {
431
+ let reviewRequired = !skipReview;
432
+ while (true) {
433
+ const directAttempt = !reviewRequired;
434
+ if (reviewRequired) {
435
+ const selection = await showPreviewActionMenu(
436
+ ctx,
437
+ reviewTitle(intent),
438
+ (width) => reviewPreviewBody(ctx, options, validated, width, intent),
439
+ [
440
+ { value: PREVIEW_ACTIONS.continue, label: continueLabel(intent) },
441
+ ...(intent.kind === "restore"
442
+ ? []
443
+ : [
444
+ {
445
+ value: PREVIEW_ACTIONS.edit,
446
+ label:
447
+ intent.kind === "preset" ? "Customize before applying" : "Continue editing",
448
+ },
449
+ ]),
450
+ {
451
+ value: PREVIEW_ACTIONS.cancel,
452
+ label:
453
+ intent.kind === "restore"
454
+ ? "Cancel"
455
+ : intent.kind === "preset"
456
+ ? "Choose another preset"
457
+ : "Discard draft",
458
+ },
459
+ ],
460
+ owner.signal,
461
+ );
462
+ if (!isCurrentOwner(owner)) return "cancel";
463
+ if (selection?.kind === "closed") return "close";
464
+ const selected = selectedPreviewAction(selection);
465
+ if (selected === PREVIEW_ACTIONS.edit) return "edit";
466
+ if (selected !== PREVIEW_ACTIONS.continue) return "cancel";
467
+ }
468
+ reviewRequired = true;
469
+
470
+ const confirmed = await ctx.ui.confirm(
471
+ confirmationTitle(intent),
472
+ confirmationMessage(options.settingsPath, intent),
473
+ );
474
+ if (!isCurrentOwner(owner)) return "cancel";
475
+ if (!confirmed) {
476
+ if (directAttempt) return "cancel";
477
+ continue;
478
+ }
479
+
480
+ const save = options.save ?? atomicSaveConfigDocument;
481
+ const previous = options.getLoaded();
482
+ let saved: LoadedStarshipConfig;
483
+ try {
484
+ saved = save(options.settingsPath, validated.rawDocument ?? BUILT_IN_EXAMPLE);
485
+ } catch (error) {
486
+ ctx.ui.notify(
487
+ `Footer settings were not saved: ${safeText(formatError(error))}. The previous footer remains active.`,
488
+ "error",
489
+ );
490
+ if (directAttempt) return "cancel";
491
+ continue;
492
+ }
493
+
494
+ try {
495
+ options.apply(saved, ctx);
496
+ } catch (error) {
497
+ const rollbackError = restorePreviousConfiguration(ctx, options, previous, saved);
498
+ ctx.ui.notify(
499
+ rollbackError
500
+ ? `Footer settings could not be applied: ${safeText(formatError(error))}. Restoring the previous configuration also failed: ${safeText(formatError(rollbackError))}.`
501
+ : `Footer settings could not be applied: ${safeText(formatError(error))}. The previous configuration was restored.`,
502
+ "error",
503
+ );
504
+ if (directAttempt) return "cancel";
505
+ continue;
506
+ }
507
+
508
+ const warningSuffix =
509
+ saved.diagnostics.length > 0
510
+ ? ` (${saved.diagnostics.length} warning${saved.diagnostics.length === 1 ? "" : "s"})`
511
+ : "";
512
+ ctx.ui.notify(`${successMessage(intent)}${warningSuffix}.`, "info");
513
+ return "applied";
514
+ }
515
+ }
516
+
517
+ function reviewTitle(intent: ReviewIntent): string {
518
+ switch (intent.kind) {
519
+ case "customize":
520
+ return "Footer preview";
521
+ case "restore":
522
+ return "Restore preview";
523
+ case "preset":
524
+ return `${intent.preset.label} preset preview`;
525
+ }
526
+ }
527
+
528
+ function continueLabel(intent: ReviewIntent): string {
529
+ switch (intent.kind) {
530
+ case "customize":
531
+ return "Apply changes…";
532
+ case "restore":
533
+ return "Replace with built-in…";
534
+ case "preset":
535
+ return `Apply ${intent.preset.label} preset…`;
536
+ }
537
+ }
538
+
539
+ function confirmationTitle(intent: ReviewIntent): string {
540
+ switch (intent.kind) {
541
+ case "customize":
542
+ return "Apply footer changes?";
543
+ case "restore":
544
+ return "Restore built-in footer?";
545
+ case "preset":
546
+ return `Apply ${intent.preset.label} preset?`;
547
+ }
548
+ }
549
+
550
+ function confirmationMessage(settingsPath: string, intent: ReviewIntent): string {
551
+ if (intent.kind === "customize") return "Save this configuration and apply it immediately?";
552
+ const replacement =
553
+ intent.kind === "restore" ? "the built-in configuration" : `the ${intent.preset.label} preset`;
554
+ return `Replace ${safeText(settingsPath)} entirely with ${replacement}? All custom settings, unknown fields, and comments will be removed. No backup is kept after success.`;
555
+ }
556
+
557
+ function successMessage(intent: ReviewIntent): string {
558
+ switch (intent.kind) {
559
+ case "customize":
560
+ return "Footer settings saved and applied";
561
+ case "restore":
562
+ return "Built-in footer restored and applied";
563
+ case "preset":
564
+ return `${intent.preset.label} preset saved and applied`;
565
+ }
566
+ }
567
+
568
+ function modulePreviewDetails(preview: string): string[] {
569
+ const lines = preview ? preview.split("\n") : ["(no current preview)"];
570
+ return lines.map((line, index) => `${index === 0 ? "Preview: " : " "}${line}`);
571
+ }
572
+
573
+ function workflowOwner(options: StarshipCommandOptions): WorkflowOwner {
574
+ if (options.getMenuOwner) return options.getMenuOwner();
575
+ const controller = new AbortController();
576
+ return { signal: controller.signal, isCurrent: () => true };
577
+ }
578
+
579
+ function isCurrentOwner(owner: WorkflowOwner): boolean {
580
+ return !owner.signal.aborted && owner.isCurrent();
581
+ }
582
+
583
+ function restorePreviousConfiguration(
584
+ ctx: ExtensionCommandContext,
585
+ options: StarshipCommandOptions,
586
+ previous: LoadedStarshipConfig,
587
+ saved: LoadedStarshipConfig,
588
+ ): unknown {
589
+ try {
590
+ if (saved.rawDocument === undefined || saved.fileIdentity === undefined) {
591
+ throw new Error("The saved settings document identity is unavailable");
592
+ }
593
+ removeConfigDocumentIfMatches(options.settingsPath, saved.rawDocument, saved.fileIdentity);
594
+ if (previous.rawDocument !== undefined) {
595
+ (options.restore ?? atomicRestoreConfigDocument)(options.settingsPath, previous.rawDocument);
596
+ }
597
+ options.apply(previous, ctx);
598
+ return undefined;
599
+ } catch (error) {
600
+ return error;
601
+ }
602
+ }
603
+
604
+ function reviewPreviewBody(
605
+ ctx: ExtensionCommandContext,
606
+ options: StarshipCommandOptions,
607
+ loaded: LoadedStarshipConfig,
608
+ width: number,
609
+ intent: ReviewIntent,
610
+ ): string[] {
611
+ if (intent.kind === "restore") return restorePreviewBody(ctx, options, loaded, width);
612
+ if (intent.kind === "customize") return previewBody(ctx, options, loaded, width);
613
+ const current = configurationPresentation(options.getLoaded());
614
+ return [
615
+ `Preset: ${intent.preset.label}`,
616
+ `Requirement: ${intent.preset.requiresNerdFont ? "Nerd Font" : "No special font"}`,
617
+ `Current: ${current.state}`,
618
+ `Path: ${safeText(options.settingsPath)}`,
619
+ "Applying replaces the entire settings document, including custom settings, unknown fields, and comments.",
620
+ "No backup is kept after a successful apply.",
621
+ "",
622
+ ...previewBody(ctx, options, loaded, width),
623
+ ];
624
+ }
625
+
626
+ function restorePreviewBody(
627
+ ctx: ExtensionCommandContext,
628
+ options: StarshipCommandOptions,
629
+ loaded: LoadedStarshipConfig,
630
+ width: number,
631
+ ): string[] {
632
+ const current = configurationPresentation(options.getLoaded());
633
+ return [
634
+ `Current: ${current.state}`,
635
+ `Path: ${safeText(options.settingsPath)}`,
636
+ "The entire settings document will be replaced, including custom settings, unknown fields, and comments.",
637
+ "No backup is kept after a successful restore.",
638
+ "",
639
+ ...previewBody(ctx, options, loaded, width),
640
+ ];
641
+ }
642
+
643
+ function previewBody(
644
+ ctx: ExtensionCommandContext,
645
+ options: StarshipCommandOptions,
646
+ loaded: LoadedStarshipConfig,
647
+ width: number,
648
+ ): string[] {
649
+ let lines: string[];
650
+ try {
651
+ lines = options.renderPreview?.(loaded, width, ctx) ?? [
652
+ "Live preview is unavailable until the footer is ready.",
653
+ "The draft is valid and can still be applied.",
654
+ ];
655
+ } catch (error) {
656
+ lines = [`Preview unavailable: ${safeText(formatError(error))}`];
657
+ }
658
+ const warning =
659
+ loaded.diagnostics.length === 0
660
+ ? "Draft validation: Healthy"
661
+ : `Draft validation: ${loaded.diagnostics.length} warning${loaded.diagnostics.length === 1 ? "" : "s"}`;
662
+ return [...lines, "", warning];
663
+ }
664
+
665
+ function selectedPreviewAction<Value extends string>(
666
+ result: PreviewMenuResult<Value> | undefined,
667
+ ): Value | null {
668
+ return result?.kind === "selected" ? result.value : null;
669
+ }
670
+
671
+ function diagnosticLines(loaded: LoadedStarshipConfig, includeSummary: boolean): string[] {
672
+ const diagnostics = loaded.diagnostics
673
+ .slice(0, 8)
674
+ .map((item) => `${safeText(item.path || "root")}: ${safeText(item.message)}`);
675
+ const remaining = loaded.diagnostics.length - diagnostics.length;
676
+ return [
677
+ ...(includeSummary ? [`Health: ${configurationHealth(loaded)}`] : []),
678
+ ...(diagnostics.length > 0 ? diagnostics : ["No configuration warnings."]),
679
+ ...(remaining > 0 ? [`${remaining} additional warnings not shown.`] : []),
680
+ ];
681
+ }
682
+
683
+ interface ConfigurationPresentation {
684
+ state: string;
685
+ source: string;
686
+ health: string;
687
+ restoreDisabled: boolean;
688
+ restoreDescription: string;
689
+ }
690
+
691
+ function configurationPresentation(loaded: LoadedStarshipConfig): ConfigurationPresentation {
692
+ const healthyMissing =
693
+ loaded.source === "built-in" &&
694
+ loaded.rawDocument === undefined &&
695
+ loaded.diagnostics.length === 0;
696
+ const savedBuiltIn = loaded.source === "user" && loaded.rawDocument === BUILT_IN_EXAMPLE;
697
+ const activePreset = presetForDocument(loaded.rawDocument);
698
+ const fallback = loaded.source === "built-in" && loaded.diagnostics.length > 0;
699
+ return {
700
+ state: healthyMissing
701
+ ? "Built-in defaults"
702
+ : savedBuiltIn
703
+ ? "Saved built-in configuration"
704
+ : activePreset
705
+ ? `${activePreset.label} preset`
706
+ : fallback
707
+ ? "Built-in fallback"
708
+ : "Custom configuration",
709
+ source: healthyMissing
710
+ ? "No settings file"
711
+ : activePreset
712
+ ? "Bundled preset"
713
+ : loaded.source === "user"
714
+ ? "User file"
715
+ : "Built-in fallback",
716
+ health: configurationHealth(loaded),
717
+ restoreDisabled: healthyMissing || savedBuiltIn,
718
+ restoreDescription: healthyMissing
719
+ ? "Already using defaults · no file to replace"
720
+ : savedBuiltIn
721
+ ? "Built-in configuration already saved"
722
+ : fallback
723
+ ? "Preview before replacing invalid settings"
724
+ : "Preview before replacing the document",
725
+ };
726
+ }
727
+
728
+ function configurationHealth(loaded: LoadedStarshipConfig): string {
729
+ const errors = loaded.diagnostics.filter((item) => item.severity === "error").length;
730
+ if (errors > 0) return `${errors} error${errors === 1 ? "" : "s"}`;
731
+ const warnings = loaded.diagnostics.length;
732
+ return warnings === 0 ? "Healthy" : `${warnings} warning${warnings === 1 ? "" : "s"}`;
733
+ }
734
+
735
+ function showStatus(ctx: ExtensionCommandContext, options: StarshipCommandOptions) {
736
+ if (!canNotify(ctx)) return;
737
+ const loaded = options.getLoaded();
738
+ const diagnostics = loaded.diagnostics
739
+ .slice(0, 5)
740
+ .map((item) => `${safeText(item.path || "root")}: ${safeText(item.message)}`)
741
+ .join("; ");
742
+ ctx.ui.notify(
743
+ [
744
+ `pi-starship source: ${loaded.source}`,
745
+ `path: ${options.settingsPath}`,
746
+ diagnostics ? `warnings: ${diagnostics}` : "warnings: none",
747
+ ].join("\n"),
748
+ loaded.diagnostics.length > 0 ? "warning" : "info",
749
+ );
750
+ }
751
+
752
+ function showHelp(ctx: ExtensionCommandContext, settingsPath: string) {
753
+ if (!canNotify(ctx)) return;
754
+ ctx.ui.notify(
755
+ [
756
+ "/starship — customize, live-preview presets, explain, or inspect the footer in TUI mode",
757
+ "/starship settings — customize, preview, and apply TOML",
758
+ "/starship status — show source, path, and warnings",
759
+ "/starship help — show this help",
760
+ `Settings: ${settingsPath}`,
761
+ "Format/module docs: https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-starship",
762
+ ].join("\n"),
763
+ "info",
764
+ );
765
+ }
766
+
767
+ function canNotify(ctx: ExtensionCommandContext): boolean {
768
+ return ctx.mode === "tui" || ctx.hasUI;
769
+ }
770
+
771
+ function safeText(value: string): string {
772
+ return Array.from(value, (character) => {
773
+ const codePoint = character.codePointAt(0) ?? 0;
774
+ const unsafe =
775
+ codePoint <= 0x08 ||
776
+ (codePoint >= 0x0b && codePoint <= 0x1f) ||
777
+ (codePoint >= 0x7f && codePoint <= 0x9f);
778
+ return unsafe ? `\\u${codePoint.toString(16).padStart(4, "0")}` : character;
779
+ }).join("");
780
+ }
781
+
782
+ function formatError(error: unknown): string {
783
+ return error instanceof Error ? error.message : String(error);
784
+ }