@narumitw/pi-starship 0.55.2 → 0.56.1

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.
@@ -0,0 +1,118 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, open, rename, rm } from "node:fs/promises";
3
+ import { dirname, join } from "node:path";
4
+ import { formatDisplayValue, formatError } from "./script-support.mjs";
5
+
6
+ const PRIVATE_DIRECTORY_MODE = 0o700;
7
+ const PRIVATE_FILE_MODE = 0o600;
8
+ const MAX_EMBEDDED_ERROR_LENGTH = 240;
9
+ const MAX_NESTED_DIRECTORY_ERROR_LENGTH = 80;
10
+
11
+ export async function backupExpectedDocument(destinationPath, expected, options = {}) {
12
+ const backupDirectory = join(dirname(destinationPath), "pi-starship");
13
+ const backupPath = join(backupDirectory, `pi-starship-${localTimestamp(options.now ?? new Date())}.toml`);
14
+ const temporaryPath = join(backupDirectory, `.pi-starship-${randomUUID()}.tmp`);
15
+ const inspectPath = options.inspectPath ?? lstat;
16
+ const makeDirectory = options.makeDirectory ?? mkdir;
17
+ const openFile = options.openFile ?? open;
18
+ const removeFile = options.removeFile ?? rm;
19
+ const renameFile = options.renameFile ?? rename;
20
+ const syncDirectory = options.syncDirectory ?? syncDirectoryEntry;
21
+
22
+ await makeDirectory(backupDirectory, { recursive: true, mode: PRIVATE_DIRECTORY_MODE });
23
+
24
+ let handle;
25
+ let ownsTemporaryPath = false;
26
+ let backupPublished = false;
27
+ try {
28
+ handle = await openFile(temporaryPath, "wx", PRIVATE_FILE_MODE);
29
+ ownsTemporaryPath = true;
30
+ await handle.writeFile(expected);
31
+ await handle.sync();
32
+ await handle.close();
33
+ handle = undefined;
34
+ await assertBackupMissing(backupPath, inspectPath);
35
+ await renameFile(temporaryPath, backupPath);
36
+ ownsTemporaryPath = false;
37
+ backupPublished = true;
38
+ await syncDirectory(backupDirectory);
39
+ await syncDirectory(dirname(backupDirectory));
40
+ return backupPath;
41
+ } catch (error) {
42
+ const cleanupErrors = [];
43
+ if (handle) {
44
+ try {
45
+ await handle.close();
46
+ } catch (closeError) {
47
+ cleanupErrors.push({ operation: "closing the temporary backup", error: closeError });
48
+ }
49
+ }
50
+ if (ownsTemporaryPath) {
51
+ try {
52
+ await removeFile(temporaryPath, { force: true });
53
+ } catch (removeError) {
54
+ cleanupErrors.push({ operation: "removing the temporary backup", error: removeError });
55
+ }
56
+ }
57
+ if (cleanupErrors.length > 0) {
58
+ const diagnostics = cleanupErrors
59
+ .map(({ operation, error: cleanupError }) => `${operation}: ${formatEmbeddedError(cleanupError)}`)
60
+ .join("; ");
61
+ throw new Error(
62
+ `Backup creation failed: ${formatEmbeddedError(error)}. Cleanup also failed (${diagnostics}). The active file was preserved.`,
63
+ );
64
+ }
65
+ if (backupPublished) {
66
+ throw new Error(
67
+ `Backup was retained at ${formatDisplayValue(backupPath)}, but its directory durability check failed: ${formatEmbeddedError(error)}. The active file was preserved.`,
68
+ );
69
+ }
70
+ throw error;
71
+ }
72
+ }
73
+
74
+ async function syncDirectoryEntry(directoryPath) {
75
+ if (process.platform === "win32") return;
76
+
77
+ const handle = await open(directoryPath, "r");
78
+ let syncError;
79
+ try {
80
+ await handle.sync();
81
+ } catch (error) {
82
+ syncError = error;
83
+ }
84
+
85
+ try {
86
+ await handle.close();
87
+ } catch (closeError) {
88
+ if (syncError) {
89
+ throw new Error(
90
+ `Directory sync failed: ${formatEmbeddedError(syncError, MAX_NESTED_DIRECTORY_ERROR_LENGTH)}. Closing the directory also failed: ${formatEmbeddedError(closeError, MAX_NESTED_DIRECTORY_ERROR_LENGTH)}.`,
91
+ );
92
+ }
93
+ throw closeError;
94
+ }
95
+
96
+ if (syncError) throw syncError;
97
+ }
98
+
99
+ async function assertBackupMissing(backupPath, inspectPath) {
100
+ try {
101
+ await inspectPath(backupPath);
102
+ } catch (error) {
103
+ if (error && typeof error === "object" && error.code === "ENOENT") return;
104
+ throw error;
105
+ }
106
+ throw new Error(`Backup already exists at ${formatDisplayValue(backupPath)}; the active file was preserved.`);
107
+ }
108
+
109
+ function formatEmbeddedError(error, maximumLength = MAX_EMBEDDED_ERROR_LENGTH) {
110
+ const diagnostic = formatError(error);
111
+ return diagnostic.length > maximumLength ? `${diagnostic.slice(0, maximumLength - 1)}…` : diagnostic;
112
+ }
113
+
114
+ function localTimestamp(date) {
115
+ return [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
116
+ .map((value, index) => String(value).padStart(index === 0 ? 4 : 2, "0"))
117
+ .join("");
118
+ }
package/src/commands.ts CHANGED
@@ -197,6 +197,8 @@ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipComma
197
197
  `Reason: ${module.reason}`,
198
198
  `Variables: ${module.variables.join(", ") || "none"}`,
199
199
  `Style fields: ${module.styleFields.join(", ") || "none"}`,
200
+ `Style-rule selectors: ${module.styleRuleSelectors.join(", ") || "none"}`,
201
+ `Style rules: ${module.styleRuleCount} configured`,
200
202
  `Display rules: ${module.displayRules.join(" · ") || "none"}`,
201
203
  ],
202
204
  })),
package/src/config.ts CHANGED
@@ -1,12 +1,11 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
- import { createRequire } from "node:module";
4
3
  import { dirname, join } from "node:path";
5
- import type { TomlTable } from "smol-toml";
4
+ import { parse as parseToml, type TomlTable } from "smol-toml";
6
5
  import { type FormatNode, formatVariables, parseFormat, styleVariables } from "./format/formatter.js";
7
6
  import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
8
7
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
9
- import type { ModuleDisplayConfig, ModuleOptionSchema, ModuleOptionValue } from "./modules/types.js";
8
+ import type { ModuleDisplayConfig, ModuleOptionSchema, ModuleOptionValue, ModuleStyleRule } from "./modules/types.js";
10
9
 
11
10
  export const CONFIG_FILE_NAME = "pi-starship.toml";
12
11
  export { MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
@@ -21,6 +20,7 @@ export interface ModuleConfig {
21
20
  symbol: string;
22
21
  style: string;
23
22
  styles: Record<string, string>;
23
+ styleRules: ModuleStyleRule[];
24
24
  display: ModuleDisplayConfig[];
25
25
  disabled: boolean;
26
26
  options: Record<string, ModuleOptionValue>;
@@ -76,6 +76,7 @@ const BUILT_IN_MODULES = Object.fromEntries(
76
76
  ...defaults,
77
77
  formatAst: parseFormat(defaults.format),
78
78
  styles: { ...styleDefaults },
79
+ styleRules: [] as ModuleStyleRule[],
79
80
  display: structuredClone(displayDefaults ?? []),
80
81
  options: Object.fromEntries(
81
82
  Object.entries(options ?? {}).map(([key, schema]) => [key, cloneOptionValue(schema.default)]),
@@ -95,14 +96,6 @@ export const BUILT_IN_CONFIG: StarshipConfig = {
95
96
 
96
97
  export const BUILT_IN_EXAMPLE = `# Native Pi modules with Starship-compatible format and style syntax.\n${BUILT_IN_FORMAT_DOCUMENT}\n`;
97
98
 
98
- const require = createRequire(import.meta.url);
99
- let parseTomlImplementation: typeof import("smol-toml")["parse"] | undefined;
100
-
101
- function parseToml(document: string): TomlTable {
102
- parseTomlImplementation ??= (require("smol-toml") as typeof import("smol-toml")).parse;
103
- return parseTomlImplementation(document);
104
- }
105
-
106
99
  export function settingsFilePath(agentDir: string): string {
107
100
  return join(agentDir, CONFIG_FILE_NAME);
108
101
  }
@@ -273,6 +266,7 @@ function normalizeModule(
273
266
  for (const field of Object.keys(definition.styleDefaults)) known.add(field);
274
267
  } else if (!definition.displayDefaults) known.add("style");
275
268
  if (definition.displayDefaults) known.add("display");
269
+ if (definition.styleRuleSelectors) known.add("style_rules");
276
270
  if (name === "extension_status") {
277
271
  known.add("separator");
278
272
  known.add("max_statuses");
@@ -326,6 +320,15 @@ function normalizeModule(
326
320
  diagnostics,
327
321
  );
328
322
  }
323
+ if (definition.styleRuleSelectors && value.style_rules !== undefined) {
324
+ module.styleRules = normalizeStyleRules(
325
+ name,
326
+ value.style_rules,
327
+ new Set(Object.keys(definition.styleRuleSelectors)),
328
+ activePalette(config),
329
+ diagnostics,
330
+ );
331
+ }
329
332
  if (value.disabled !== undefined) {
330
333
  if (typeof value.disabled !== "boolean") {
331
334
  diagnostics.push(typeDiagnostic(`${name}.disabled`, "boolean"));
@@ -487,6 +490,7 @@ function cloneBuiltInConfig(): StarshipConfig {
487
490
  ...BUILT_IN_CONFIG.modules[name],
488
491
  formatAst: structuredClone(BUILT_IN_CONFIG.modules[name].formatAst),
489
492
  styles: { ...BUILT_IN_CONFIG.modules[name].styles },
493
+ styleRules: structuredClone(BUILT_IN_CONFIG.modules[name].styleRules),
490
494
  display: structuredClone(BUILT_IN_CONFIG.modules[name].display),
491
495
  options: structuredClone(BUILT_IN_CONFIG.modules[name].options),
492
496
  },
@@ -546,6 +550,48 @@ function validateModuleStyleField(
546
550
  }
547
551
  }
548
552
 
553
+ function normalizeStyleRules(
554
+ name: ModuleName,
555
+ value: unknown,
556
+ allowedSelectors: ReadonlySet<string>,
557
+ palette: ColorPalette,
558
+ diagnostics: ConfigDiagnostic[],
559
+ ): ModuleStyleRule[] {
560
+ if (!Array.isArray(value)) {
561
+ diagnostics.push(typeDiagnostic(`${name}.style_rules`, "array of tables"));
562
+ return [];
563
+ }
564
+ const result: ModuleStyleRule[] = [];
565
+ for (const [index, entry] of value.entries()) {
566
+ const path = `${name}.style_rules.${index}`;
567
+ if (!isRecord(entry)) {
568
+ diagnostics.push(diagnostic("warning", path, "Expected a table; rule ignored"));
569
+ continue;
570
+ }
571
+ let valid = true;
572
+ for (const field of Object.keys(entry)) {
573
+ if (field !== "style" && !allowedSelectors.has(field)) {
574
+ diagnostics.push(diagnostic("warning", `${path}.${field}`, "Unknown style-rule field; rule ignored"));
575
+ valid = false;
576
+ }
577
+ }
578
+ if (typeof entry.style !== "string" || !isValidStyle(entry.style, palette)) {
579
+ diagnostics.push(diagnostic("warning", `${path}.style`, "Expected a valid Starship style string; rule ignored"));
580
+ valid = false;
581
+ }
582
+ const selectors: Record<string, string> = {};
583
+ for (const selector of allowedSelectors) {
584
+ if (entry[selector] === undefined) continue;
585
+ if (typeof entry[selector] !== "string") {
586
+ diagnostics.push(diagnostic("warning", `${path}.${selector}`, "Expected string; rule ignored"));
587
+ valid = false;
588
+ } else setOwn(selectors, selector, entry[selector]);
589
+ }
590
+ if (valid) result.push({ style: entry.style as string, selectors });
591
+ }
592
+ return result;
593
+ }
594
+
549
595
  function normalizeDisplay(
550
596
  name: ModuleName,
551
597
  value: unknown,
@@ -28,6 +28,9 @@ export function projectEffectiveConfig(config: StarshipConfig): TomlTable {
28
28
  if (definition.displayDefaults) {
29
29
  table.display = module.display.map((entry) => ({ ...entry }));
30
30
  }
31
+ if (definition.styleRuleSelectors && module.styleRules.length > 0) {
32
+ table.style_rules = module.styleRules.map((rule) => ({ ...rule.selectors, style: rule.style }));
33
+ }
31
34
  table.disabled = module.disabled;
32
35
  for (const key of Object.keys(definition.options ?? {})) {
33
36
  table[key] = cloneOptionValue(module.options[key]);
@@ -14,6 +14,8 @@ export interface ModuleInspection {
14
14
  preview: string;
15
15
  variables: readonly string[];
16
16
  styleFields: readonly string[];
17
+ styleRuleSelectors: readonly string[];
18
+ styleRuleCount: number;
17
19
  displayRules: readonly string[];
18
20
  rootReferenced: boolean;
19
21
  reachable: boolean;
@@ -98,6 +100,8 @@ function moduleInspection(
98
100
  preview,
99
101
  variables: [...definition.variables],
100
102
  styleFields: ["style", ...Object.keys(module.styles)],
103
+ styleRuleSelectors: Object.keys(definition.styleRuleSelectors ?? {}),
104
+ styleRuleCount: module.styleRules.length,
101
105
  displayRules: module.display.map(
102
106
  (rule) => `${rule.threshold}: ${rule.hidden ? "hidden" : rule.style || "unstyled"}`,
103
107
  ),
@@ -14,6 +14,10 @@ export const modelModule = defineModule({
14
14
  style: "bold blue",
15
15
  disabled: false,
16
16
  },
17
+ styleRuleSelectors: {
18
+ provider: ({ runtime }) => runtime.model?.provider,
19
+ model: ({ runtime }) => runtime.model?.id,
20
+ },
17
21
  options: {
18
22
  truncation_length: { kind: "integer", default: 0, minimum: 0, maximum: 1000 },
19
23
  truncation_symbol: { kind: "string", default: "…" },
@@ -12,6 +12,9 @@ export const providerModule = defineModule({
12
12
  style: "bold blue",
13
13
  disabled: false,
14
14
  },
15
+ styleRuleSelectors: {
16
+ provider: ({ runtime }) => runtime.model?.provider,
17
+ },
15
18
  options: {
16
19
  [PROVIDER_ALIASES_KEY]: { kind: "string-map", default: {} },
17
20
  },
@@ -3,7 +3,8 @@ import { activePalette, type ModuleConfig, type StarshipConfig } from "../config
3
3
  import { type FormatValue, formatVariables, renderFormat } from "../format/formatter.js";
4
4
  import { isFillChunk, type LayoutChunk, renderChunksToAnsi, type StyledChunk } from "../format/style.js";
5
5
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./catalog.js";
6
- import type { ModuleValueContext, RenderedStatusline, StarshipRuntimeSnapshot } from "./types.js";
6
+ import { resolveStyleRule } from "./style-rules.js";
7
+ import type { ModuleStyleContext, ModuleValueContext, RenderedStatusline, StarshipRuntimeSnapshot } from "./types.js";
7
8
 
8
9
  export function renderStatusline(
9
10
  config: StarshipConfig,
@@ -23,16 +24,21 @@ export function renderStatusline(
23
24
  const module = config.modules[name];
24
25
  const values = definition.values(valueContext(config, name, runtime));
25
26
  if (!values) continue;
26
- const styleVariables = definition.resolveStyleVariables
27
- ? definition.resolveStyleVariables({
28
- runtime,
29
- values,
30
- style: module.style,
31
- styles: module.styles,
32
- display: module.display,
33
- })
27
+ const styleContext: ModuleStyleContext = {
28
+ runtime,
29
+ values,
30
+ style: module.style,
31
+ styles: module.styles,
32
+ display: module.display,
33
+ };
34
+ const baseStyleVariables = definition.resolveStyleVariables
35
+ ? definition.resolveStyleVariables(styleContext)
34
36
  : { style: module.style };
35
- if (!styleVariables) continue;
37
+ if (!baseStyleVariables) continue;
38
+ const ruleStyle = definition.styleRuleSelectors
39
+ ? resolveStyleRule(module.styleRules, definition.styleRuleSelectors, styleContext)
40
+ : undefined;
41
+ const styleVariables = ruleStyle === undefined ? baseStyleVariables : { ...baseStyleVariables, style: ruleStyle };
36
42
  const contentValues = Object.fromEntries(
37
43
  definition.variables.flatMap((variable) =>
38
44
  variable !== "symbol" && Object.hasOwn(values, variable) ? [[variable, values[variable]]] : [],
@@ -0,0 +1,21 @@
1
+ import type { ModuleStyleContext, ModuleStyleRule, ModuleStyleSelector } from "./types.js";
2
+
3
+ export function resolveStyleRule(
4
+ rules: readonly ModuleStyleRule[],
5
+ selectors: Readonly<Record<string, ModuleStyleSelector>>,
6
+ context: ModuleStyleContext,
7
+ ): string | undefined {
8
+ for (const rule of rules) {
9
+ let matches = true;
10
+ for (const name in rule.selectors) {
11
+ if (!Object.hasOwn(rule.selectors, name)) continue;
12
+ const selector = Object.hasOwn(selectors, name) ? selectors[name] : undefined;
13
+ if (!selector || selector(context) !== rule.selectors[name]) {
14
+ matches = false;
15
+ break;
16
+ }
17
+ }
18
+ if (matches) return rule.style;
19
+ }
20
+ return undefined;
21
+ }
@@ -30,6 +30,10 @@ export const thinkingModule = defineModule({
30
30
  >,
31
31
  fallbackStyle: true,
32
32
  styleVariables: ["style"],
33
+ styleRuleSelectors: {
34
+ provider: ({ runtime }) => runtime.model?.provider,
35
+ level: ({ runtime }) => runtime.thinkingLevel,
36
+ },
33
37
  resolveStyleVariables: ({ runtime, styles, style }) => {
34
38
  const level = thinkingLevelOf(runtime.thinkingLevel);
35
39
  return { style: (level && styles[`style_${level}`]) || style };
@@ -145,6 +145,11 @@ export interface ModuleDisplayConfig {
145
145
  hidden: boolean;
146
146
  }
147
147
 
148
+ export interface ModuleStyleRule {
149
+ style: string;
150
+ selectors: Readonly<Record<string, string>>;
151
+ }
152
+
148
153
  export interface ModuleDefaults {
149
154
  format: string;
150
155
  symbol: string;
@@ -160,6 +165,8 @@ export interface ModuleStyleContext {
160
165
  display: readonly ModuleDisplayConfig[];
161
166
  }
162
167
 
168
+ export type ModuleStyleSelector = (context: ModuleStyleContext) => string | undefined;
169
+
163
170
  export interface ModuleDefinition<Name extends string> {
164
171
  name: Name;
165
172
  variables: readonly string[];
@@ -168,6 +175,7 @@ export interface ModuleDefinition<Name extends string> {
168
175
  fallbackStyle?: boolean;
169
176
  displayDefaults?: readonly ModuleDisplayConfig[];
170
177
  styleVariables?: readonly string[];
178
+ styleRuleSelectors?: Readonly<Record<string, ModuleStyleSelector>>;
171
179
  resolveStyleVariables?(context: ModuleStyleContext): Readonly<Record<string, string>> | undefined;
172
180
  options?: Readonly<Record<string, ModuleOptionSchema>>;
173
181
  layout?: "fill";