@narumitw/pi-starship 0.60.1 → 0.62.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 (114) hide show
  1. package/README.md +63 -6
  2. package/dist/chunks/chunk-43VIENBN.ts +1586 -0
  3. package/dist/chunks/chunk-43VIENBN.ts.map +7 -0
  4. package/dist/chunks/chunk-HPZTMIZS.ts +646 -0
  5. package/dist/chunks/chunk-HPZTMIZS.ts.map +7 -0
  6. package/dist/chunks/chunk-IYDZ3R2T.ts +69 -0
  7. package/dist/chunks/chunk-IYDZ3R2T.ts.map +7 -0
  8. package/dist/chunks/chunk-KP33I6BR.ts +579 -0
  9. package/dist/chunks/chunk-KP33I6BR.ts.map +7 -0
  10. package/dist/chunks/{chunk-KZZKGGFW.ts → chunk-PWTSHSP3.ts} +853 -1001
  11. package/dist/chunks/chunk-PWTSHSP3.ts.map +7 -0
  12. package/dist/chunks/{chunk-PD457PX5.ts → chunk-S2KBLHE2.ts} +75 -10
  13. package/dist/chunks/chunk-S2KBLHE2.ts.map +7 -0
  14. package/dist/chunks/chunk-XQUIQO2G.ts +20 -0
  15. package/dist/chunks/chunk-XQUIQO2G.ts.map +7 -0
  16. package/dist/chunks/{chunk-ADX4CY27.ts → chunk-XTLQ4WUL.ts} +1 -1
  17. package/dist/chunks/chunk-XTLQ4WUL.ts.map +7 -0
  18. package/dist/chunks/{cloud-EPAEV4ZB.ts → cloud-J2ZOE3HE.ts} +6 -2
  19. package/dist/chunks/cloud-J2ZOE3HE.ts.map +7 -0
  20. package/dist/chunks/command-configuration-menu-S2LXCOJG.ts +147 -0
  21. package/dist/chunks/command-configuration-menu-S2LXCOJG.ts.map +7 -0
  22. package/dist/chunks/command-settings-chat-O34BEU4X.ts +1041 -0
  23. package/dist/chunks/command-settings-chat-O34BEU4X.ts.map +7 -0
  24. package/dist/chunks/commands-ZYIJVIEJ.ts +1022 -0
  25. package/dist/chunks/commands-ZYIJVIEJ.ts.map +7 -0
  26. package/dist/chunks/{deployment-7J54EHNR.ts → deployment-NOJ2KCLI.ts} +85 -5
  27. package/dist/chunks/deployment-NOJ2KCLI.ts.map +7 -0
  28. package/dist/chunks/{development-IWJAAAEV.ts → development-T3XXVVDP.ts} +67 -15
  29. package/dist/chunks/development-T3XXVVDP.ts.map +7 -0
  30. package/dist/chunks/directory-OX6BWJZA.ts +31 -0
  31. package/dist/chunks/directory-OX6BWJZA.ts.map +7 -0
  32. package/dist/chunks/{execution-P4WZALW2.ts → execution-R2OHIP2L.ts} +8 -4
  33. package/dist/chunks/execution-R2OHIP2L.ts.map +7 -0
  34. package/dist/chunks/jujutsu-XLDYKSX2.ts +174 -0
  35. package/dist/chunks/jujutsu-XLDYKSX2.ts.map +7 -0
  36. package/dist/chunks/languages-CBQNNYXM.ts +262 -0
  37. package/dist/chunks/languages-CBQNNYXM.ts.map +7 -0
  38. package/dist/chunks/{package-H24VJEX3.ts → package-7KVAK3TC.ts} +6 -2
  39. package/dist/chunks/package-7KVAK3TC.ts.map +7 -0
  40. package/dist/chunks/system-574MHB4R.ts +165 -0
  41. package/dist/chunks/system-574MHB4R.ts.map +7 -0
  42. package/dist/index.ts +558 -150
  43. package/dist/index.ts.map +4 -4
  44. package/package.json +5 -1
  45. package/skills/configure-pi-starship/SKILL.md +14 -0
  46. package/skills/configure-pi-starship/references/configuration.md +109 -24
  47. package/skills/configure-pi-starship/references/module-catalog.md +278 -25
  48. package/skills/configure-pi-starship/references/modules.md +213 -36
  49. package/skills/configure-pi-starship/references/runtime-and-security.md +88 -28
  50. package/src/command-configuration-menu.ts +155 -0
  51. package/src/command-configuration.ts +9 -84
  52. package/src/command-preview.ts +3 -3
  53. package/src/command-settings-chat.ts +210 -0
  54. package/src/commands.ts +54 -98
  55. package/src/config/module-options.ts +112 -0
  56. package/src/config.ts +17 -53
  57. package/src/effective-config.ts +5 -4
  58. package/src/format/bounded-regex.ts +66 -0
  59. package/src/format/version.ts +24 -0
  60. package/src/modules/catalog.ts +10 -0
  61. package/src/modules/cloud.ts +1 -0
  62. package/src/modules/deployment.ts +8 -0
  63. package/src/modules/development.ts +20 -2
  64. package/src/modules/directory.ts +171 -51
  65. package/src/modules/execution.ts +2 -0
  66. package/src/modules/git/branch.ts +19 -4
  67. package/src/modules/git/commit.ts +9 -2
  68. package/src/modules/git/metrics.ts +9 -4
  69. package/src/modules/git/runtime.ts +122 -33
  70. package/src/modules/git/state.ts +23 -2
  71. package/src/modules/git/status-templates.ts +58 -0
  72. package/src/modules/git/status.ts +96 -30
  73. package/src/modules/jujutsu.ts +225 -0
  74. package/src/modules/languages.ts +26 -2
  75. package/src/modules/package.ts +1 -0
  76. package/src/modules/render.ts +42 -16
  77. package/src/modules/system.ts +54 -0
  78. package/src/modules/time-format.ts +188 -0
  79. package/src/modules/time.ts +11 -5
  80. package/src/modules/types.ts +42 -4
  81. package/src/pi-starship.ts +56 -12
  82. package/src/profile-store.ts +5 -0
  83. package/src/runtime/cloud.ts +3 -0
  84. package/src/runtime/command.ts +1 -1
  85. package/src/runtime/deployment.ts +120 -4
  86. package/src/runtime/development.ts +86 -13
  87. package/src/runtime/directory.ts +33 -0
  88. package/src/runtime/execution.ts +12 -2
  89. package/src/runtime/helpers.ts +57 -8
  90. package/src/runtime/jujutsu.ts +225 -0
  91. package/src/runtime/languages.ts +106 -19
  92. package/src/runtime/package.ts +3 -0
  93. package/src/runtime/system.ts +202 -0
  94. package/src/runtime/types.ts +3 -0
  95. package/src/runtime/version-requirements.ts +30 -0
  96. package/src/runtime/workspace.ts +12 -1
  97. package/src/settings-agent.ts +80 -0
  98. package/src/settings-chat-transcript.ts +140 -0
  99. package/src/settings-chat-ui.ts +426 -0
  100. package/src/settings-draft.ts +260 -0
  101. package/src/settings-snapshots.ts +41 -0
  102. package/dist/chunks/chunk-ADX4CY27.ts.map +0 -7
  103. package/dist/chunks/chunk-KZZKGGFW.ts.map +0 -7
  104. package/dist/chunks/chunk-PD457PX5.ts.map +0 -7
  105. package/dist/chunks/cloud-EPAEV4ZB.ts.map +0 -7
  106. package/dist/chunks/commands-C2VJ6ZBN.ts +0 -3374
  107. package/dist/chunks/commands-C2VJ6ZBN.ts.map +0 -7
  108. package/dist/chunks/deployment-7J54EHNR.ts.map +0 -7
  109. package/dist/chunks/development-IWJAAAEV.ts.map +0 -7
  110. package/dist/chunks/execution-P4WZALW2.ts.map +0 -7
  111. package/dist/chunks/languages-JO6R2PHL.ts +0 -168
  112. package/dist/chunks/languages-JO6R2PHL.ts.map +0 -7
  113. package/dist/chunks/package-H24VJEX3.ts.map +0 -7
  114. package/src/command-inspector.ts +0 -41
package/src/commands.ts CHANGED
@@ -10,34 +10,27 @@ import {
10
10
  } from "./command-commit.js";
11
11
  import {
12
12
  type ConfigurationCommandOptions,
13
- configurationMenuScreen,
14
- configurationOverviewScreen,
15
13
  configurationPresentation,
16
- effectiveConfigurationScreen,
17
14
  reloadConfiguration,
18
- settingsDocumentScreen,
19
15
  type WorkflowOwner,
20
16
  } from "./command-configuration.js";
21
17
  import { completeStarshipArguments, STARSHIP_SUBCOMMANDS } from "./command-contract.js";
22
18
  import { importSettingsGist, shareSettingsGist } from "./command-gist.js";
23
- import { formatFooterExplanation } from "./command-inspector.js";
24
19
  import { showPresetPicker } from "./command-preset-picker.js";
25
20
  import { type PreviewMenuResult, showPreviewActionMenu } from "./command-preview.js";
26
21
  import { saveAsProfile, showHistory, showProfiles } from "./command-profiles.js";
27
22
  import { BUILT_IN_EXAMPLE, type LoadedStarshipConfig, validateConfigDocument } from "./config.js";
28
23
  import type { GhApi } from "./gist.js";
29
- import { inspectUnavailableModules, type StatuslineInspection } from "./modules/inspection.js";
24
+ import type { StatuslineInspection } from "./modules/inspection.js";
30
25
  import { getStarshipPreset, presetForDocument, STARSHIP_PRESETS, type StarshipPreset } from "./presets/catalog.js";
31
26
 
32
27
  const MAIN_ACTIONS = {
33
- customize: "customize",
34
28
  presets: "presets",
35
- explain: "explain",
36
- modules: "modules",
37
29
  configuration: "configuration",
38
30
  help: "help",
39
31
  restore: "restore",
40
32
  profiles: "profiles",
33
+ chat: "settings-chat",
41
34
  } as const;
42
35
 
43
36
  const PREVIEW_ACTIONS = {
@@ -55,6 +48,7 @@ export interface StarshipCommandOptions extends ConfigurationCommandOptions, Com
55
48
  validate?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
56
49
  getMenuOwner?(): WorkflowOwner;
57
50
  gistApi?: GhApi;
51
+ registerChatCleanup?(cleanup: () => Promise<void>): () => void;
58
52
  }
59
53
 
60
54
  export type ReviewIntent =
@@ -67,7 +61,7 @@ export type ReviewIntent =
67
61
 
68
62
  export function registerStarshipCommand(pi: ExtensionAPI, options: StarshipCommandOptions) {
69
63
  pi.registerCommand("starship", {
70
- description: "Customize or inspect the native Starship-style footer",
64
+ description: "Configure the footer with agent, presets, profiles, and recovery",
71
65
  getArgumentCompletions: completeStarshipArguments,
72
66
  handler: (args, ctx) => handleStarshipCommand(args, ctx, options),
73
67
  });
@@ -153,24 +147,17 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
153
147
  signal: fallbackController.signal,
154
148
  isCurrent: () => !fallbackController.signal.aborted,
155
149
  };
156
- type Screen =
157
- | "main"
158
- | "explain"
159
- | "modules"
160
- | "configuration"
161
- | "configuration-overview"
162
- | "configuration-effective"
163
- | "configuration-document"
164
- | "help";
150
+ type Screen = "main" | "help";
165
151
  type Action =
166
- | "customize"
152
+ | "configuration"
167
153
  | "presets"
168
154
  | "profiles"
169
155
  | "history"
170
156
  | "configuration-reload"
171
157
  | "restore"
172
158
  | "gist-share"
173
- | "gist-import";
159
+ | "gist-import"
160
+ | "settings-chat";
174
161
  const menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({
175
162
  start: "main",
176
163
  screens: {
@@ -180,13 +167,16 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
180
167
  return {
181
168
  kind: "actions",
182
169
  title: "pi-starship",
183
- lines: [`${presentation.state} · ${presentation.health}`],
170
+ lines: [
171
+ `${presentation.state} · ${presentation.health}`,
172
+ "Configure with agent for edits, module questions, and footer explanations.",
173
+ ],
184
174
  items: [
185
175
  {
186
- id: MAIN_ACTIONS.customize,
187
- label: "Customize footer",
188
- description: `${presentation.state} · preview before applying`,
189
- action: "customize",
176
+ id: MAIN_ACTIONS.chat,
177
+ label: "Configure with agent",
178
+ description: "Separate conversation · draft tools · live preview only until you save",
179
+ action: "settings-chat",
190
180
  },
191
181
  {
192
182
  id: MAIN_ACTIONS.presets,
@@ -195,28 +185,16 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
195
185
  action: "presets",
196
186
  },
197
187
  {
198
- id: MAIN_ACTIONS.explain,
199
- label: "Explain footer",
200
- description: "Why each visible module appears",
201
- to: "explain",
202
- },
203
- {
204
- id: MAIN_ACTIONS.modules,
205
- label: "Modules",
206
- description: "Browse supported modules and current states",
207
- to: "modules",
188
+ id: MAIN_ACTIONS.profiles,
189
+ label: "Profiles",
190
+ description: "Save, edit, manage, and live-preview named TOML documents",
191
+ action: "profiles",
208
192
  },
209
193
  {
210
194
  id: MAIN_ACTIONS.configuration,
211
195
  label: "Configuration",
212
196
  description: presentation.health,
213
- to: "configuration",
214
- },
215
- {
216
- id: MAIN_ACTIONS.help,
217
- label: "Help",
218
- description: "Formats, modules, and commands",
219
- to: "help",
197
+ action: "configuration",
220
198
  },
221
199
  {
222
200
  id: MAIN_ACTIONS.restore,
@@ -226,64 +204,25 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
226
204
  action: "restore",
227
205
  },
228
206
  {
229
- id: MAIN_ACTIONS.profiles,
230
- label: "Profiles",
231
- description: "Save, edit, manage, and live-preview named TOML documents",
232
- action: "profiles",
207
+ id: MAIN_ACTIONS.help,
208
+ label: "Help",
209
+ description: "Settings, modules, and commands",
210
+ to: "help",
233
211
  },
234
212
  ],
235
213
  hint: "close",
236
214
  };
237
215
  },
238
- explain: () => ({
239
- kind: "review",
240
- title: "Explain footer",
241
- content: formatFooterExplanation(options.getInspection?.()),
242
- format: { kind: "text" },
243
- viewportSize: "adaptive",
244
- hint: "back",
245
- }),
246
- modules: () => {
247
- const inspection = options.getInspection?.() ?? inspectUnavailableModules(options.getLoaded().config);
248
- return {
249
- kind: "browse",
250
- title: "Modules",
251
- items: inspection.modules.map((module) => ({
252
- id: module.name,
253
- label: module.name,
254
- statusText: module.state,
255
- description: module.description,
256
- searchText: [...module.variables, ...module.styleFields, ...module.displayRules].join(" "),
257
- details: [
258
- `Root: ${module.rootReferenced ? "Referenced" : "Not referenced"}`,
259
- `Reachable: ${module.reachable ? "Yes" : "No"}`,
260
- ...modulePreviewDetails(module.preview),
261
- `Reason: ${module.reason}`,
262
- `Variables: ${module.variables.join(", ") || "none"}`,
263
- `Style fields: ${module.styleFields.join(", ") || "none"}`,
264
- `Style-rule selectors: ${module.styleRuleSelectors.join(", ") || "none"}`,
265
- `Style rules: ${module.styleRuleCount} configured`,
266
- `Display rules: ${module.displayRules.join(" · ") || "none"}`,
267
- ],
268
- })),
269
- viewportSize: "adaptive",
270
- hint: "back",
271
- };
272
- },
273
- configuration: () => configurationMenuScreen(options.getLoaded()),
274
- "configuration-overview": () => configurationOverviewScreen(options.getLoaded(), options.settingsPath),
275
- "configuration-effective": () => effectiveConfigurationScreen(options.getLoaded()),
276
- "configuration-document": () => settingsDocumentScreen(options.getLoaded(), options.settingsPath),
277
216
  help: () => ({
278
217
  kind: "detail",
279
218
  title: "pi-starship help",
280
219
  lines: [
281
- "Customize footer opens the TOML editor, then previews and confirms before saving.",
220
+ "/starship settings retains the TOML editor with preview and confirmation.",
221
+ "Configure with agent opens a separate skill-backed chat; edits preview only until you explicitly save.",
282
222
  "Presets live-previews the cursor in the footer; Enter confirms apply, e customizes, and s saves a profile when available.",
283
223
  "Profiles manages named TOML copies; selecting a document previews it without saving.",
284
224
  "Configuration History reviews and restores recovery copies; external edits are not fully tracked.",
285
- "Explain footer breaks down the modules currently showing from the existing snapshot.",
286
- "Modules searches every supported module and explains its current read-only state.",
225
+ "Ask Configure with agent about active settings and module states captured when the chat opens.",
287
226
  "Configuration includes disk reload plus unlisted Gist sharing and reviewed Gist import through gh.",
288
227
  `Settings: ${safeText(options.settingsPath)}`,
289
228
  "Docs: https://github.com/narumiruna/pi-extensions/tree/main/packages/pi-starship",
@@ -292,9 +231,31 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
292
231
  }),
293
232
  },
294
233
  actions: {
295
- customize: async () => {
296
- const result = await editSettings(ctx, options);
297
- return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
234
+ "settings-chat": async () => {
235
+ const { showSettingsAgentChat } = await import("./command-settings-chat.js");
236
+ if (!isCurrentOwner(owner)) return { kind: "close" };
237
+ await showSettingsAgentChat(ctx, options, owner);
238
+ return { kind: "close" };
239
+ },
240
+ configuration: async () => {
241
+ const { showConfigurationMenu } = await import("./command-configuration-menu.js");
242
+ if (!isCurrentOwner(owner)) return { kind: "close" };
243
+ let selected: string | undefined;
244
+ while (isCurrentOwner(owner)) {
245
+ const result = await showConfigurationMenu(ctx, options, owner, selected);
246
+ if (!isCurrentOwner(owner) || result.kind !== "completed") return { kind: "close" };
247
+ if (result.value === "back") return { kind: "stay" };
248
+ if (result.value === "close") return { kind: "close" };
249
+ selected = result.value;
250
+ const transition = await menu.actions[result.value]({
251
+ ctx,
252
+ state: undefined,
253
+ signal: owner.signal,
254
+ itemId: result.value,
255
+ });
256
+ if (!isCurrentOwner(owner) || transition?.kind === "close") return { kind: "close" };
257
+ }
258
+ return { kind: "close" };
298
259
  },
299
260
  presets: async () => {
300
261
  const result = await choosePreset(ctx, options, owner);
@@ -732,11 +693,6 @@ function successMessage(intent: ReviewIntent): string {
732
693
  }
733
694
  }
734
695
 
735
- function modulePreviewDetails(preview: string): string[] {
736
- const lines = preview ? preview.split("\n") : ["(no current preview)"];
737
- return lines.map((line, index) => `${index === 0 ? "Preview: " : " "}${line}`);
738
- }
739
-
740
696
  function workflowOwner(options: StarshipCommandOptions): WorkflowOwner {
741
697
  if (options.getMenuOwner) return options.getMenuOwner();
742
698
  const controller = new AbortController();
@@ -853,7 +809,7 @@ function showHelp(ctx: ExtensionCommandContext, settingsPath: string) {
853
809
  if (!canNotify(ctx)) return;
854
810
  ctx.ui.notify(
855
811
  [
856
- "/starship — manage profiles, live-preview presets, recover history, explain, or inspect the footer in TUI mode",
812
+ "/starship — configure with agent, manage profiles, preview presets, or recover settings in TUI mode",
857
813
  "/starship settings — customize, preview, and apply TOML",
858
814
  "/starship status — show source, path, and warnings",
859
815
  "/starship help — show this help",
@@ -0,0 +1,112 @@
1
+ import { validPattern } from "../format/bounded-regex.js";
2
+ import { isValidStyle } from "../format/style.js";
3
+ import { validStatusTemplate } from "../modules/git/status-templates.js";
4
+ import type { ModuleContextRule, ModuleOptionSchema, ModuleOptionValue, ModuleSubstitution } from "../modules/types.js";
5
+
6
+ type Result = { ok: true; value: ModuleOptionValue } | { ok: false; message: string };
7
+ const invalid = (expected: string): Result => ({ ok: false, message: `Expected ${expected}; using the default value` });
8
+ const record = (value: unknown): value is Record<string, unknown> =>
9
+ typeof value === "object" && value !== null && !Array.isArray(value);
10
+ const text = (value: unknown, max = 4_096): value is string => typeof value === "string" && value.length <= max;
11
+
12
+ export function normalizeModuleOption(
13
+ value: unknown,
14
+ schema: ModuleOptionSchema,
15
+ palette: Readonly<Record<string, string>> = {},
16
+ ): Result {
17
+ switch (schema.kind) {
18
+ case "string": {
19
+ if (typeof value !== "string" || (schema.allowEmpty === false && value.length === 0)) return invalid("a string");
20
+ if (schema.templateVariables && !validStatusTemplate(value, schema.templateVariables)) {
21
+ return invalid("a bounded template with only the documented variables");
22
+ }
23
+ return { ok: true, value };
24
+ }
25
+ case "string-enum":
26
+ return typeof value === "string" && schema.values.includes(value)
27
+ ? { ok: true, value }
28
+ : invalid(`one of: ${schema.values.join(", ")}`);
29
+ case "boolean":
30
+ return typeof value === "boolean" ? { ok: true, value } : invalid("boolean");
31
+ case "integer":
32
+ case "number":
33
+ return typeof value === "number" &&
34
+ Number.isFinite(value) &&
35
+ (schema.kind !== "integer" || Number.isInteger(value)) &&
36
+ value >= schema.minimum &&
37
+ value <= schema.maximum
38
+ ? { ok: true, value }
39
+ : invalid(`${schema.kind} from ${schema.minimum} through ${schema.maximum}`);
40
+ case "string-array":
41
+ return Array.isArray(value) &&
42
+ value.every(
43
+ (item) => typeof item === "string" && item.length > 0 && (schema.allowNegative || !item.startsWith("!")),
44
+ )
45
+ ? { ok: true, value: [...value] as string[] }
46
+ : invalid("an array of valid strings");
47
+ case "string-map":
48
+ return stringMap(value);
49
+ case "command-alternatives": {
50
+ if (typeof value === "string") value = [value];
51
+ const argument = (item: unknown): item is string =>
52
+ text(item, 1_024) &&
53
+ item.length > 0 &&
54
+ ![...item].some((character) => {
55
+ const code = character.codePointAt(0) ?? 0;
56
+ return code < 32 || (code >= 127 && code <= 159);
57
+ });
58
+ if (
59
+ !Array.isArray(value) ||
60
+ value.length > 16 ||
61
+ !value.every(
62
+ (item) =>
63
+ argument(item) || (Array.isArray(item) && item.length > 0 && item.length <= 16 && item.every(argument)),
64
+ )
65
+ )
66
+ return invalid("at most 16 command names or argv arrays without terminal controls");
67
+ return { ok: true, value: structuredClone(value) };
68
+ }
69
+ case "context-rules": {
70
+ if (!Array.isArray(value) || value.length > 64) return invalid("at most 64 context rules");
71
+ const keys = new Set(["context_pattern", "user_pattern", "symbol", "style", "context_alias", "user_alias"]);
72
+ for (const rule of value) {
73
+ if (
74
+ !record(rule) ||
75
+ !text(rule.context_pattern, 512) ||
76
+ !validPattern(rule.context_pattern) ||
77
+ Object.entries(rule).some(
78
+ ([key, item]) =>
79
+ !keys.has(key) ||
80
+ !text(item) ||
81
+ ((key === "context_pattern" || key === "user_pattern") && (!text(item, 512) || !validPattern(item))) ||
82
+ (key === "style" && !isValidStyle(item, palette)),
83
+ )
84
+ )
85
+ return invalid("context rules with valid bounded patterns, strings, and styles");
86
+ }
87
+ return { ok: true, value: structuredClone(value) as ModuleContextRule[] };
88
+ }
89
+ case "substitutions": {
90
+ if (!Array.isArray(value)) return stringMap(value);
91
+ if (value.length > 64) return invalid("at most 64 substitutions");
92
+ for (const substitution of value) {
93
+ if (
94
+ !record(substitution) ||
95
+ !text(substitution.from, 512) ||
96
+ !text(substitution.to) ||
97
+ Object.keys(substitution).some((key) => key !== "from" && key !== "to" && key !== "regex") ||
98
+ (substitution.regex !== undefined && typeof substitution.regex !== "boolean") ||
99
+ (substitution.regex === true && !validPattern(substitution.from))
100
+ )
101
+ return invalid("bounded from/to substitutions with an optional regex boolean");
102
+ }
103
+ return { ok: true, value: structuredClone(value) as ModuleSubstitution[] };
104
+ }
105
+ }
106
+ }
107
+
108
+ function stringMap(value: unknown): Result {
109
+ if (!record(value) || Object.values(value).some((item) => typeof item !== "string"))
110
+ return invalid("a table of strings");
111
+ return { ok: true, value: Object.fromEntries(Object.entries(value)) as Record<string, string> };
112
+ }
package/src/config.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  } from "node:fs";
15
15
  import { dirname, join } from "node:path";
16
16
  import { parse as parseToml, type TomlTable } from "smol-toml";
17
+ import { normalizeModuleOption } from "./config/module-options.js";
17
18
  import { type FormatNode, formatVariables, parseFormat, styleVariables } from "./format/formatter.js";
18
19
  import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
19
20
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
@@ -393,7 +394,22 @@ function normalizeModule(
393
394
  }
394
395
  for (const [key, schema] of Object.entries(optionSchemas)) {
395
396
  if (value[key] === undefined) continue;
396
- const normalized = normalizeModuleOption(value[key], schema);
397
+ const normalized = normalizeModuleOption(value[key], schema, activePalette(config));
398
+ if (normalized.ok && name === "directory" && key === "repo_root_format" && typeof normalized.value === "string") {
399
+ try {
400
+ const ast = parseFormat(normalized.value);
401
+ if (
402
+ normalized.value.length > 4_096 ||
403
+ [...formatVariables(ast)].some((variable) => !definition.variables.includes(variable)) ||
404
+ [...styleVariables(ast)].some((variable) => !definition.styleVariables?.includes(variable))
405
+ )
406
+ throw new Error("Unknown format variable");
407
+ validateLiteralStyles(ast, activePalette(config), `${name}.${key}`, diagnostics);
408
+ } catch {
409
+ diagnostics.push(diagnostic("warning", `${name}.${key}`, "Invalid repository-root format; using the default"));
410
+ continue;
411
+ }
412
+ }
397
413
  if (normalized.ok) module.options[key] = normalized.value;
398
414
  else diagnostics.push(diagnostic("warning", `${name}.${key}`, normalized.message));
399
415
  }
@@ -777,58 +793,6 @@ function validateLiteralStyles(
777
793
  }
778
794
  }
779
795
 
780
- function normalizeModuleOption(
781
- value: unknown,
782
- schema: ModuleOptionSchema,
783
- ): { ok: true; value: ModuleOptionValue } | { ok: false; message: string } {
784
- switch (schema.kind) {
785
- case "string":
786
- return typeof value === "string" && (schema.allowEmpty !== false || value.length > 0)
787
- ? { ok: true, value }
788
- : { ok: false, message: "Expected a non-empty string; using the default value" };
789
- case "string-enum":
790
- return typeof value === "string" && schema.values.includes(value)
791
- ? { ok: true, value }
792
- : {
793
- ok: false,
794
- message: `Expected one of: ${schema.values.join(", ")}; using the default value`,
795
- };
796
- case "boolean":
797
- return typeof value === "boolean"
798
- ? { ok: true, value }
799
- : { ok: false, message: "Expected boolean; using the default value" };
800
- case "integer":
801
- return typeof value === "number" && Number.isInteger(value) && value >= schema.minimum && value <= schema.maximum
802
- ? { ok: true, value }
803
- : {
804
- ok: false,
805
- message: `Expected an integer from ${schema.minimum} through ${schema.maximum}; using the default value`,
806
- };
807
- case "string-array": {
808
- if (
809
- !Array.isArray(value) ||
810
- value.some(
811
- (item) => typeof item !== "string" || item.length === 0 || (!schema.allowNegative && item.startsWith("!")),
812
- )
813
- ) {
814
- return {
815
- ok: false,
816
- message: "Expected an array of valid strings; using the default value",
817
- };
818
- }
819
- return { ok: true, value: [...value] as string[] };
820
- }
821
- case "string-map": {
822
- if (!isRecord(value) || Object.values(value).some((item) => typeof item !== "string")) {
823
- return { ok: false, message: "Expected a table of strings; using the default value" };
824
- }
825
- const result: Record<string, string> = {};
826
- for (const [key, item] of Object.entries(value)) setOwn(result, key, item as string);
827
- return { ok: true, value: result };
828
- }
829
- }
830
- }
831
-
832
796
  function cloneOptionValue(value: ModuleOptionValue): ModuleOptionValue {
833
797
  return typeof value === "object" ? structuredClone(value) : value;
834
798
  }
@@ -33,7 +33,7 @@ export function projectEffectiveConfig(config: StarshipConfig): TomlTable {
33
33
  }
34
34
  table.disabled = module.disabled;
35
35
  for (const key of Object.keys(definition.options ?? {})) {
36
- table[key] = cloneOptionValue(module.options[key]);
36
+ table[key] = cloneOptionValue(module.options[key], definition.name === "directory" && key === "substitutions");
37
37
  }
38
38
  if (definition.name === "extension_status") {
39
39
  table.separator = config.extensionStatus.separator;
@@ -50,11 +50,12 @@ export function serializeEffectiveConfig(config: StarshipConfig): string {
50
50
  return stringify(projectEffectiveConfig(config));
51
51
  }
52
52
 
53
- function cloneOptionValue(value: ModuleOptionValue | undefined): TomlValue {
53
+ function cloneOptionValue(value: ModuleOptionValue | undefined, preserveOrder = false): TomlValue {
54
54
  if (value === undefined) throw new Error("Missing normalized module option");
55
- if (Array.isArray(value)) return [...(value as readonly string[])];
55
+ if (Array.isArray(value)) return structuredClone(value) as TomlValue;
56
56
  if (typeof value === "object") {
57
- return sortedRecord(value as Readonly<Record<string, string>>);
57
+ const record = value as Readonly<Record<string, string>>;
58
+ return preserveOrder ? { ...record } : sortedRecord(record);
58
59
  }
59
60
  return value;
60
61
  }
@@ -0,0 +1,66 @@
1
+ import { RE2JS } from "re2js";
2
+
3
+ const MAX_PATTERN = 512;
4
+ const MAX_VALUE = 4_096;
5
+ const MAX_OUTPUT = 8_192;
6
+ const CACHE_SIZE = 64;
7
+ const patterns = new Map<string, RE2JS | null>();
8
+
9
+ // RE2 rejects backreferences and lookaround and matches without backtracking.
10
+ // Bound compilation, input, replacement, output, and retained compiled patterns.
11
+ function compile(pattern: string): RE2JS | undefined {
12
+ const sourceLength = pattern.startsWith("^(?:") && pattern.endsWith(")$") ? pattern.length - 6 : pattern.length;
13
+ if (sourceLength > MAX_PATTERN) return undefined;
14
+ if (patterns.has(pattern)) return patterns.get(pattern) ?? undefined;
15
+ let compiled: RE2JS | null;
16
+ try {
17
+ compiled = RE2JS.compile(pattern);
18
+ } catch {
19
+ compiled = null;
20
+ }
21
+ if (patterns.size >= CACHE_SIZE) {
22
+ const oldest = patterns.keys().next().value;
23
+ if (oldest !== undefined) patterns.delete(oldest);
24
+ }
25
+ patterns.set(pattern, compiled);
26
+ return compiled ?? undefined;
27
+ }
28
+
29
+ export function validPattern(pattern: string): boolean {
30
+ return pattern.length <= MAX_PATTERN && compile(pattern) !== undefined;
31
+ }
32
+
33
+ export function matchPattern(pattern: string, value: string, full = true): boolean {
34
+ if (value.length > MAX_VALUE) return false;
35
+ const compiled = compile(pattern);
36
+ if (!compiled) return false;
37
+ const matcher = compiled.matcher(value);
38
+ return full ? matcher.matches() : matcher.find();
39
+ }
40
+
41
+ /** Rust-style replacement fields: $1, $name, ${name}, and $$ for a literal $. */
42
+ export function replacePattern(pattern: string, value: string, replacement: string, all = false): string | undefined {
43
+ if (value.length > MAX_VALUE || replacement.length > MAX_VALUE) return undefined;
44
+ const compiled = compile(pattern);
45
+ if (!compiled) return undefined;
46
+ const matcher = compiled.matcher(value);
47
+ let result = "";
48
+ let end = 0;
49
+ while (matcher.find()) {
50
+ result += value.slice(end, matcher.start());
51
+ result += replacement.replace(/\$(?:\{([A-Za-z_0-9]+)\}|([A-Za-z_0-9]+)|(\$))/gu, (_, braced, plain, dollar) => {
52
+ if (dollar) return "$";
53
+ const field = braced ?? plain;
54
+ try {
55
+ return matcher.group(/^\d+$/u.test(field) ? Number(field) : field) ?? "";
56
+ } catch {
57
+ return "";
58
+ }
59
+ });
60
+ if (result.length > MAX_OUTPUT) return undefined;
61
+ end = matcher.end();
62
+ if (!all) break;
63
+ }
64
+ result += value.slice(end);
65
+ return result.length <= MAX_OUTPUT ? result : undefined;
66
+ }
@@ -0,0 +1,24 @@
1
+ import { parseFormat, renderFormat } from "./formatter.js";
2
+ import { isFillChunk } from "./style.js";
3
+
4
+ /** Use the package format grammar, without applying ANSI styles to the version value. */
5
+ export function formatVersion(raw: string, format: string | undefined): string {
6
+ // Collectors historically pass versions with a leading v. Keep the existing raw value.
7
+ const version = raw.replace(/^v/u, "");
8
+ const fallback = `v${version}`;
9
+ const template = format ?? "v$raw";
10
+ if (template.length > 4_096) return fallback;
11
+ // Only dotted numeric releases and an optional prerelease/build suffix expose components.
12
+ // Missing components stay absent; malformed releases keep only their raw value.
13
+ const release = /^(\d+(?:\.\d+)*)(?:[-+][0-9A-Za-z.+_-]+|[A-Za-z][0-9A-Za-z.+_-]*)?$/u.exec(version)?.[1];
14
+ const parts = release?.split(".").map((part) => part.replace(/^0+(?=\d)/u, ""));
15
+ try {
16
+ return renderFormat(parseFormat(template), {
17
+ variables: { raw: version, major: parts?.[0], minor: parts?.[1], patch: parts?.[2] },
18
+ })
19
+ .map((chunk) => (isFillChunk(chunk) ? "" : chunk.text))
20
+ .join("");
21
+ } catch {
22
+ return fallback;
23
+ }
24
+ }
@@ -17,10 +17,12 @@ import { gitStateModule } from "./git/state.js";
17
17
  import { gitStatusModule } from "./git/status.js";
18
18
  import { gitWorktreeModule } from "./git/worktree.js";
19
19
  import { githubPrModule } from "./github-pr.js";
20
+ import { jujutsuModules } from "./jujutsu.js";
20
21
  import { languageModules } from "./languages.js";
21
22
  import { modelModule } from "./model.js";
22
23
  import { packageModule } from "./package.js";
23
24
  import { providerModule } from "./provider.js";
25
+ import { systemModules } from "./system.js";
24
26
  import { thinkingModule } from "./thinking.js";
25
27
  import { timeModule } from "./time.js";
26
28
  import { tokensModule } from "./tokens.js";
@@ -40,12 +42,14 @@ const MODULE_IMPLEMENTATIONS = [
40
42
  gitStateModule,
41
43
  gitMetricsModule,
42
44
  gitStatusModule,
45
+ ...jujutsuModules,
43
46
  packageModule,
44
47
  ...languageModules,
45
48
  ...developmentModules,
46
49
  ...deploymentModules,
47
50
  ...cloudModules,
48
51
  ...executionModules,
52
+ ...systemModules,
49
53
  activityModule,
50
54
  contextModule,
51
55
  tokensModule,
@@ -64,6 +68,7 @@ const MODULE_DESCRIPTIONS = {
64
68
  activity: "Current Pi activity, extension UI wait, or most recently completed tool.",
65
69
  aws: "Active AWS profile and region.",
66
70
  azure: "Active Azure subscription and optional username.",
71
+ battery: "Local battery charge and charging state on supported platforms.",
67
72
  brand: "pi-starship brand mark.",
68
73
  bun: "Bun version detected in the current workspace.",
69
74
  cache: "Prompt-cache usage and latest cache hit rate.",
@@ -88,7 +93,12 @@ const MODULE_DESCRIPTIONS = {
88
93
  golang: "Go version detected in the current workspace.",
89
94
  guix_shell: "Current Guix shell state.",
90
95
  hostname: "Current host name, normally shown for remote sessions.",
96
+ jj_bookmark: "Closest ancestor bookmark in the current Jujutsu repository.",
97
+ jj_change: "Current Jujutsu change and commit identity.",
98
+ jj_metrics: "Added and deleted lines in the current Jujutsu change.",
99
+ jj_status: "Current Jujutsu change status.",
91
100
  kubernetes: "Active Kubernetes context, namespace, cluster, and user.",
101
+ memory_usage: "Current system memory and available swap usage.",
92
102
  mise: "Current mise configuration health.",
93
103
  model: "Current Pi model.",
94
104
  nix_shell: "Current Nix shell state, name, and nesting level.",
@@ -44,6 +44,7 @@ export const gcloudModule = cloudModule({
44
44
  options: {
45
45
  project_aliases: { kind: "string-map", default: {} },
46
46
  region_aliases: { kind: "string-map", default: {} },
47
+ detect_env_vars: { kind: "string-array", default: [], allowNegative: true },
47
48
  },
48
49
  });
49
50
 
@@ -32,7 +32,15 @@ export const kubernetesModule = defineModule({
32
32
  style: "cyan bold",
33
33
  disabled: false,
34
34
  },
35
+ resolveStyleVariables: ({ runtime, style }) => ({
36
+ style: runtime.workspace?.styleSelectors?.kubernetes ?? style,
37
+ }),
35
38
  options: {
39
+ detect_files: { kind: "string-array", default: [], allowNegative: true },
40
+ detect_extensions: { kind: "string-array", default: [], allowNegative: true },
41
+ detect_folders: { kind: "string-array", default: [], allowNegative: true },
42
+ detect_env_vars: { kind: "string-array", default: [], allowNegative: true },
43
+ contexts: { kind: "context-rules", default: [] },
36
44
  context_aliases: { kind: "string-map", default: {} },
37
45
  namespace_aliases: { kind: "string-map", default: {} },
38
46
  cluster_aliases: { kind: "string-map", default: {} },