@narumitw/pi-starship 0.59.2 → 0.60.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/src/config.ts CHANGED
@@ -1,5 +1,17 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import {
3
+ closeSync,
4
+ existsSync,
5
+ fsyncSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ openSync,
9
+ readFileSync,
10
+ renameSync,
11
+ rmSync,
12
+ type Stats,
13
+ writeFileSync,
14
+ } from "node:fs";
3
15
  import { dirname, join } from "node:path";
4
16
  import { parse as parseToml, type TomlTable } from "smol-toml";
5
17
  import { type FormatNode, formatVariables, parseFormat, styleVariables } from "./format/formatter.js";
@@ -53,6 +65,7 @@ export interface LoadedStarshipConfig {
53
65
  source: "built-in" | "user";
54
66
  settingsPath: string;
55
67
  rawDocument?: string;
68
+ rawBytes?: Buffer;
56
69
  fileIdentity?: { dev: number; ino: number };
57
70
  diagnostics: ConfigDiagnostic[];
58
71
  }
@@ -103,8 +116,12 @@ export function settingsFilePath(agentDir: string): string {
103
116
 
104
117
  export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
105
118
  let rawDocument: string;
119
+ let snapshot: ConfigDocumentSnapshot;
106
120
  try {
107
- rawDocument = readFileSync(settingsPath, "utf8");
121
+ const rawBytes = readFileSync(settingsPath);
122
+ snapshot = readConfigDocumentSnapshot(settingsPath);
123
+ if (!snapshot.rawBytes?.equals(rawBytes)) throw new Error("Settings changed while being read; retry the operation");
124
+ rawDocument = rawBytes.toString("utf8");
108
125
  } catch (error) {
109
126
  if ((error as NodeJS.ErrnoException).code === "ENOENT" && !existsSync(settingsPath)) {
110
127
  return {
@@ -124,6 +141,8 @@ export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
124
141
 
125
142
  let parsed: TomlTable;
126
143
  try {
144
+ if (!Buffer.from(rawDocument, "utf8").equals(snapshot.rawBytes ?? Buffer.alloc(0)))
145
+ throw new Error("Settings are not valid UTF-8");
127
146
  parsed = parseToml(rawDocument);
128
147
  } catch (error) {
129
148
  return {
@@ -131,6 +150,7 @@ export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
131
150
  source: "built-in",
132
151
  settingsPath,
133
152
  rawDocument,
153
+ ...snapshot,
134
154
  diagnostics: [diagnostic("error", "", `Unable to parse TOML: ${formatError(error)}`)],
135
155
  };
136
156
  }
@@ -140,9 +160,44 @@ export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
140
160
  source: "user",
141
161
  settingsPath,
142
162
  rawDocument,
163
+ ...snapshot,
143
164
  };
144
165
  }
145
166
 
167
+ export interface ConfigDocumentSnapshot {
168
+ rawBytes?: Buffer;
169
+ fileIdentity?: { dev: number; ino: number };
170
+ }
171
+
172
+ export function readConfigDocumentSnapshot(settingsPath: string): ConfigDocumentSnapshot {
173
+ let info: Stats;
174
+ try {
175
+ info = lstatSync(settingsPath);
176
+ } catch (error) {
177
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
178
+ throw error;
179
+ }
180
+ if (!info.isFile() || info.isSymbolicLink()) throw new Error("Settings must be a regular file, not a symbolic link");
181
+ const rawBytes = readFileSync(settingsPath);
182
+ const after = lstatSync(settingsPath);
183
+ if (after.dev !== info.dev || after.ino !== info.ino || !after.isFile()) {
184
+ throw new Error("Settings changed while being read; retry the operation");
185
+ }
186
+ return { rawBytes, fileIdentity: { dev: info.dev, ino: info.ino } };
187
+ }
188
+
189
+ export function assertConfigDocumentUnchanged(settingsPath: string, expected: ConfigDocumentSnapshot): void {
190
+ const current = readConfigDocumentSnapshot(settingsPath);
191
+ if (current.rawBytes === undefined && expected.rawBytes === undefined) return;
192
+ if (
193
+ current.rawBytes?.equals(expected.rawBytes ?? Buffer.alloc(0)) &&
194
+ current.fileIdentity?.dev === expected.fileIdentity?.dev &&
195
+ current.fileIdentity?.ino === expected.fileIdentity?.ino
196
+ )
197
+ return;
198
+ throw new Error("Starship settings changed concurrently; the newer file was preserved. Reopen settings and retry.");
199
+ }
200
+
146
201
  export function normalizeConfig(value: unknown): {
147
202
  config: StarshipConfig;
148
203
  diagnostics: ConfigDiagnostic[];
@@ -185,12 +240,12 @@ export function normalizeConfig(value: unknown): {
185
240
  }
186
241
  const palette: Record<string, string> = {};
187
242
  for (const [name, color] of Object.entries(paletteValue)) {
188
- if (typeof color !== "string" || !parseColor(color.toLowerCase())) {
243
+ if (typeof color !== "string" || !parseColor(color)) {
189
244
  diagnostics.push(
190
245
  diagnostic(
191
246
  "warning",
192
247
  `palettes.${paletteName}.${name}`,
193
- "Palette colors must be named, ANSI 0-255, or #RRGGBB",
248
+ "Palette colors must be named, ANSI 0-255, #RRGGBB, or pi:<role>",
194
249
  ),
195
250
  );
196
251
  continue;
@@ -393,9 +448,14 @@ interface AtomicFileSystem {
393
448
  writeFileSync: typeof writeFileSync;
394
449
  renameSync: typeof renameSync;
395
450
  rmSync: typeof rmSync;
451
+ openSync: typeof openSync;
452
+ closeSync: typeof closeSync;
453
+ fsyncSync: typeof fsyncSync;
396
454
  }
397
455
 
398
456
  export function validateConfigDocument(settingsPath: string, rawDocument: string): LoadedStarshipConfig {
457
+ if (Buffer.from(rawDocument, "utf8").toString("utf8") !== rawDocument)
458
+ throw new Error("Settings must be lossless UTF-8 text");
399
459
  let parsed: TomlTable;
400
460
  try {
401
461
  parsed = parseToml(rawDocument);
@@ -418,20 +478,32 @@ export function atomicSaveConfigDocument(
418
478
  settingsPath: string,
419
479
  rawDocument: string,
420
480
  overrides: Partial<AtomicFileSystem> = {},
481
+ expected?: ConfigDocumentSnapshot,
421
482
  ): LoadedStarshipConfig {
422
483
  const validated = validateConfigDocument(settingsPath, rawDocument);
423
484
  return {
424
485
  ...validated,
425
- fileIdentity: atomicWriteConfigDocument(settingsPath, rawDocument, overrides),
486
+ rawBytes: Buffer.from(rawDocument),
487
+ fileIdentity: atomicWriteConfigDocument(settingsPath, rawDocument, overrides, expected),
426
488
  };
427
489
  }
428
490
 
429
491
  export function atomicRestoreConfigDocument(
430
492
  settingsPath: string,
431
- rawDocument: string,
493
+ rawDocument: string | Buffer,
432
494
  overrides: Partial<AtomicFileSystem> = {},
495
+ expected?: ConfigDocumentSnapshot,
433
496
  ) {
434
- atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
497
+ atomicWriteConfigDocument(settingsPath, rawDocument, overrides, expected);
498
+ }
499
+
500
+ export class ConfigPublicationError extends Error {
501
+ constructor(
502
+ message: string,
503
+ readonly fileIdentity: { dev: number; ino: number },
504
+ ) {
505
+ super(message);
506
+ }
435
507
  }
436
508
 
437
509
  export function removeConfigDocumentIfMatches(
@@ -454,6 +526,14 @@ export function removeConfigDocumentIfMatches(
454
526
  quarantined.ino === expectedIdentity.ino;
455
527
  if (quarantinedSavedFile && readFileSync(quarantinePath, "utf8") === expectedRawDocument) {
456
528
  (overrides.rmSync ?? rmSync)(quarantinePath);
529
+ if (process.platform !== "win32") {
530
+ const directory = openSync(dirname(settingsPath), "r");
531
+ try {
532
+ fsyncSync(directory);
533
+ } finally {
534
+ closeSync(directory);
535
+ }
536
+ }
457
537
  return;
458
538
  }
459
539
  if (quarantinedSavedFile && !pathEntryExists(settingsPath)) {
@@ -463,26 +543,44 @@ export function removeConfigDocumentIfMatches(
463
543
  // Keep the quarantine for recovery when its atomic restoration fails.
464
544
  }
465
545
  }
466
- throw new Error("Starship settings changed concurrently; the newer file was preserved");
546
+ throw new Error(
547
+ `Starship settings changed concurrently; the newer file was preserved. Recovery path: ${quarantinePath}`,
548
+ );
467
549
  }
468
550
 
469
551
  function atomicWriteConfigDocument(
470
552
  settingsPath: string,
471
- rawDocument: string,
553
+ rawDocument: string | Buffer,
472
554
  overrides: Partial<AtomicFileSystem>,
555
+ captured?: ConfigDocumentSnapshot,
473
556
  ): { dev: number; ino: number } {
474
- const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
475
- const replaceExisting = pathEntryExists(settingsPath);
476
- fs.mkdirSync(dirname(settingsPath), { recursive: true });
557
+ const fs = { mkdirSync, writeFileSync, renameSync, rmSync, openSync, closeSync, fsyncSync, ...overrides };
558
+ const expected = captured ?? readConfigDocumentSnapshot(settingsPath);
559
+ const replaceExisting = expected.rawBytes !== undefined;
560
+ fs.mkdirSync(dirname(settingsPath), { recursive: true, mode: 0o700 });
477
561
  const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
562
+ let publishedIdentity: { dev: number; ino: number } | undefined;
478
563
  try {
479
- fs.writeFileSync(tempPath, rawDocument, { encoding: "utf8", flag: "wx" });
564
+ fs.writeFileSync(tempPath, rawDocument, { encoding: "utf8", flag: "wx", mode: 0o600, flush: true });
480
565
  const info = lstatSync(tempPath);
481
566
  if (!replaceExisting && pathEntryExists(settingsPath)) {
482
567
  throw new Error(`${CONFIG_FILE_NAME} was created concurrently; reopen settings and retry.`);
483
568
  }
569
+ assertConfigDocumentUnchanged(settingsPath, expected);
484
570
  fs.renameSync(tempPath, settingsPath);
485
- return { dev: info.dev, ino: info.ino };
571
+ publishedIdentity = { dev: info.dev, ino: info.ino };
572
+ if (process.platform !== "win32") {
573
+ const directory = fs.openSync(dirname(settingsPath), "r");
574
+ try {
575
+ fs.fsyncSync(directory);
576
+ } finally {
577
+ fs.closeSync(directory);
578
+ }
579
+ }
580
+ return publishedIdentity;
581
+ } catch (error) {
582
+ if (publishedIdentity) throw new ConfigPublicationError(formatError(error), publishedIdentity);
583
+ throw error;
486
584
  } finally {
487
585
  try {
488
586
  fs.rmSync(tempPath, { force: true });
@@ -1,4 +1,5 @@
1
1
  import { type ColorPalette, isFillChunk, type LayoutChunk, parseStyle, type TextStyle } from "./style.js";
2
+ import { sanitizeFormatText } from "./terminal-safety.js";
2
3
 
3
4
  export type FormatNode =
4
5
  | { type: "text"; value: string }
@@ -201,7 +202,7 @@ function renderNodes(
201
202
  for (const node of nodes) {
202
203
  switch (node.type) {
203
204
  case "text":
204
- chunks.push({ text: node.value, style: inheritedStyle });
205
+ chunks.push({ text: sanitizeFormatText(node.value), style: inheritedStyle });
205
206
  break;
206
207
  case "variable":
207
208
  chunks.push(...chunksForValue(ownValue(options.variables, node.name), inheritedStyle));
@@ -232,17 +233,18 @@ function ownValue<T>(record: Readonly<Record<string, T>> | undefined, key: strin
232
233
 
233
234
  function chunksForValue(value: FormatValue, inheritedStyle: TextStyle | undefined): LayoutChunk[] {
234
235
  if (value === undefined) return [];
235
- if (typeof value === "string") return [{ text: value, style: inheritedStyle }];
236
+ if (typeof value === "string") return [{ text: sanitizeFormatText(value), style: inheritedStyle }];
236
237
  return value.map((chunk) =>
237
238
  isFillChunk(chunk)
238
239
  ? {
239
240
  type: "fill" as const,
240
241
  pattern: chunk.pattern.map((part) => ({
241
242
  ...part,
243
+ text: sanitizeFormatText(part.text),
242
244
  style: part.style ?? inheritedStyle,
243
245
  })),
244
246
  }
245
- : { ...chunk, style: chunk.style ?? inheritedStyle },
247
+ : { ...chunk, text: sanitizeFormatText(chunk.text), style: chunk.style ?? inheritedStyle },
246
248
  );
247
249
  }
248
250
 
@@ -250,7 +252,9 @@ function conditionalVisible(nodes: readonly FormatNode[], variables: Readonly<Re
250
252
  for (const variable of formatVariables(nodes)) {
251
253
  const value = ownValue(variables, variable);
252
254
  if (
253
- typeof value === "string" ? value.length > 0 : value?.some((chunk) => isFillChunk(chunk) || chunk.text.length > 0)
255
+ typeof value === "string"
256
+ ? sanitizeFormatText(value).length > 0
257
+ : value?.some((chunk) => isFillChunk(chunk) || sanitizeFormatText(chunk.text).length > 0)
254
258
  ) {
255
259
  return true;
256
260
  }
@@ -1,3 +1,8 @@
1
+ import type { ThemeToken } from "@earendil-works/pi-coding-agent";
2
+ import { backgroundAnsi, foregroundAnsi } from "@earendil-works/pi-tui";
3
+ import { sanitizeFormatText } from "./terminal-safety.js";
4
+ import { isThemeRole, type ThemeColors } from "./theme-colors.js";
5
+
1
6
  export type NamedColor =
2
7
  | "black"
3
8
  | "red"
@@ -19,7 +24,8 @@ export type NamedColor =
19
24
  export type ColorSpec =
20
25
  | { kind: "named"; name: NamedColor }
21
26
  | { kind: "fixed"; value: number }
22
- | { kind: "rgb"; red: number; green: number; blue: number };
27
+ | { kind: "rgb"; red: number; green: number; blue: number }
28
+ | { kind: "theme"; role: ThemeToken };
23
29
 
24
30
  export type PreviousColorSource = "foreground" | "background";
25
31
 
@@ -116,7 +122,7 @@ export function parseStyleResult(styleString: string, palette: ColorPalette = {}
116
122
  continue;
117
123
  }
118
124
  const color = parseColor(token, palette);
119
- if (!foreground && !color) {
125
+ if (!foreground && !color && !token.toLowerCase().startsWith("pi:")) {
120
126
  delete style.background;
121
127
  continue;
122
128
  }
@@ -132,15 +138,17 @@ export function parseStyle(styleString: string, palette: ColorPalette = {}): Tex
132
138
  }
133
139
 
134
140
  function normalizeStyleToken(rawToken: string): { token: string; foreground: boolean } {
135
- let token = rawToken.toLowerCase();
136
- if (token.startsWith("fg:")) {
137
- return { token: token.replace(/^(?:fg:)+/u, ""), foreground: true };
141
+ if (/^fg:/iu.test(rawToken)) {
142
+ return { token: normalizeColorToken(rawToken.replace(/^(?:fg:)+/iu, "")), foreground: true };
138
143
  }
139
- if (token.startsWith("bg:")) {
140
- token = token.replace(/^(?:bg:)+/u, "");
141
- return { token, foreground: false };
144
+ if (/^bg:/iu.test(rawToken)) {
145
+ return { token: normalizeColorToken(rawToken.replace(/^(?:bg:)+/iu, "")), foreground: false };
142
146
  }
143
- return { token, foreground: true };
147
+ return { token: normalizeColorToken(rawToken), foreground: true };
148
+ }
149
+
150
+ function normalizeColorToken(token: string): string {
151
+ return /^pi:/iu.test(token) ? `pi:${token.slice(3)}` : token.toLowerCase();
144
152
  }
145
153
 
146
154
  function applyModifier(style: TextStyle, token: string): boolean {
@@ -175,8 +183,16 @@ function applyModifier(style: TextStyle, token: string): boolean {
175
183
  }
176
184
 
177
185
  export function parseColor(token: string, palette: ColorPalette = {}): ColorSpec | undefined {
178
- const paletteValue = Object.hasOwn(palette, token) ? palette[token] : undefined;
179
- if (paletteValue !== undefined) return parseColor(paletteValue.toLowerCase(), {});
186
+ // Legacy style lookups lowercase palette names, including names that now look
187
+ // like Pi references. Palette values remain direct colors, never aliases.
188
+ const paletteKey = token.toLowerCase();
189
+ const paletteValue = Object.hasOwn(palette, paletteKey) ? palette[paletteKey] : undefined;
190
+ if (paletteValue !== undefined) return parseColor(normalizeColorToken(paletteValue), {});
191
+ token = normalizeColorToken(token);
192
+ if (token.startsWith("pi:")) {
193
+ const role = token.slice(3);
194
+ return isThemeRole(role) ? { kind: "theme", role } : undefined;
195
+ }
180
196
  if (NAMED_COLORS.has(token as NamedColor)) {
181
197
  return { kind: "named", name: token as NamedColor };
182
198
  }
@@ -200,21 +216,30 @@ interface ResolvedStyle
200
216
  background?: ColorSpec;
201
217
  }
202
218
 
203
- export function renderChunksToAnsi(chunks: readonly LayoutChunk[], trueColor = true): string {
219
+ export function renderChunksToAnsi(
220
+ chunks: readonly LayoutChunk[],
221
+ trueColor = true,
222
+ themeColors?: ThemeColors,
223
+ ): string {
204
224
  const runs: Array<{ text: string; style: ResolvedStyle }> = [];
205
225
  let previous: ResolvedStyle | undefined;
206
226
  for (const chunk of chunks) {
207
227
  if (isFillChunk(chunk)) continue;
208
228
  const style = resolveStyle(chunk.style, previous);
229
+ const text = sanitizeFormatText(chunk.text);
209
230
  const last = runs.at(-1);
210
- if (chunk.text && last && stylesEqual(last.style, style)) last.text += chunk.text;
211
- else if (chunk.text) runs.push({ text: chunk.text, style });
231
+ if (text && last && stylesEqual(last.style, style)) last.text += text;
232
+ else if (text) runs.push({ text, style });
212
233
  previous = style;
213
234
  }
214
235
  return runs
215
236
  .map(({ text, style }) => {
216
237
  const codes = ansiCodes(style, trueColor);
217
- return codes.length > 0 ? `\u001b[${codes.join(";")}m${text}\u001b[0m` : text;
238
+ const prefix =
239
+ themeColorAnsi(style.foreground, false, trueColor, themeColors) +
240
+ themeColorAnsi(style.background, true, trueColor, themeColors) +
241
+ (codes.length > 0 ? `\u001b[${codes.join(";")}m` : "");
242
+ return prefix ? `${prefix}${text}\u001b[0m` : text;
218
243
  })
219
244
  .join("");
220
245
  }
@@ -257,7 +282,21 @@ function ansiCodes(style: ResolvedStyle, trueColor: boolean): string[] {
257
282
  return codes;
258
283
  }
259
284
 
285
+ function themeColorAnsi(
286
+ color: ColorSpec | undefined,
287
+ background: boolean,
288
+ trueColor: boolean,
289
+ themeColors: ThemeColors | undefined,
290
+ ): string {
291
+ // Non-UI callers (for example, plain module inspection and width measurement)
292
+ // need no active theme. Keep the renderer pure and omit unresolved colors.
293
+ if (color?.kind !== "theme" || !themeColors) return "";
294
+ const mode = trueColor ? "truecolor" : "256color";
295
+ return (background ? backgroundAnsi : foregroundAnsi)(themeColors[color.role], mode);
296
+ }
297
+
260
298
  function colorCodes(color: ColorSpec, background: boolean, trueColor: boolean): string[] {
299
+ if (color.kind === "theme") return [];
261
300
  if (color.kind === "named") {
262
301
  const foreground = FOREGROUND_CODES[color.name];
263
302
  return [`${background ? foreground + 10 : foreground}`];
@@ -0,0 +1,80 @@
1
+ import { sanitizeTerminalDocument } from "@narumitw/pi-tui-kit/terminal-document";
2
+
3
+ const PREFIX = "\u001b]8;;";
4
+ const BEL = "\u0007";
5
+ const ST = "\u001b\\";
6
+
7
+ /** Preserve layout and supported HTTP(S) links, never arbitrary terminal controls. */
8
+ export function sanitizeFormatText(value: string): string {
9
+ let output = "";
10
+ let offset = 0;
11
+ let cursor = 0;
12
+ while (cursor < value.length) {
13
+ const start = value.indexOf(PREFIX, cursor);
14
+ if (start < 0) break;
15
+ const opening = findTerminator(value, start + PREFIX.length);
16
+ if (!opening) break;
17
+ const closing = findLinkEnd(value, opening.end);
18
+ if (!closing) break;
19
+ cursor = closing.end;
20
+ const url = safeHyperlinkUrl(value.slice(start + PREFIX.length, opening.start));
21
+ if (!url) continue;
22
+ output += sanitizePlainText(value.slice(offset, start));
23
+ const label = sanitizePlainText(value.slice(opening.end, closing.start));
24
+ if (label) {
25
+ const openTerminator = value.slice(opening.start, opening.end);
26
+ const closeTerminator = value.slice(closing.start + PREFIX.length, closing.end);
27
+ output += `${PREFIX}${url}${openTerminator}${label}${PREFIX}${closeTerminator}`;
28
+ }
29
+ offset = closing.end;
30
+ }
31
+ return output + sanitizePlainText(value.slice(offset));
32
+ }
33
+
34
+ function sanitizePlainText(value: string): string {
35
+ return sanitizeTerminalDocument(value).replace(/\t/gu, " ");
36
+ }
37
+
38
+ function terminatorEnd(value: string, start: number): number | undefined {
39
+ if (value.startsWith(BEL, start)) return start + BEL.length;
40
+ if (value.startsWith(ST, start)) return start + ST.length;
41
+ return undefined;
42
+ }
43
+
44
+ function findTerminator(value: string, start: number): { start: number; end: number } | undefined {
45
+ for (let index = start; index < value.length; index += 1) {
46
+ const end = terminatorEnd(value, index);
47
+ if (end !== undefined) return { start: index, end };
48
+ }
49
+ return undefined;
50
+ }
51
+
52
+ function findLinkEnd(value: string, start: number): { start: number; end: number } | undefined {
53
+ let index = value.indexOf(PREFIX, start);
54
+ while (index >= 0) {
55
+ const end = terminatorEnd(value, index + PREFIX.length);
56
+ if (end !== undefined) return { start: index, end };
57
+ index = value.indexOf(PREFIX, index + PREFIX.length);
58
+ }
59
+ return undefined;
60
+ }
61
+
62
+ /** Match the URL policy used by the GitHub collector before generating OSC 8. */
63
+ function safeHyperlinkUrl(value: string): string | undefined {
64
+ if (
65
+ value.length > 4_096 ||
66
+ Array.from(value).some((character) => {
67
+ const code = character.codePointAt(0) ?? 0;
68
+ return code <= 0x1f || (code >= 0x7f && code <= 0x9f) || (code >= 0xd800 && code <= 0xdfff);
69
+ })
70
+ )
71
+ return undefined;
72
+ try {
73
+ const url = new URL(value);
74
+ if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) return undefined;
75
+ const normalized = url.toString();
76
+ return normalized.length <= 4_096 ? normalized : undefined;
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ }
@@ -0,0 +1,69 @@
1
+ import type { Theme, ThemeToken } from "@earendil-works/pi-coding-agent";
2
+
3
+ export type ThemeColors = Theme["colors"];
4
+
5
+ // Pi exports ThemeToken as a type, but has no public runtime token registry.
6
+ // Exhaustiveness keeps validation aligned with the installed public API without
7
+ // reading the active theme before Pi initializes it.
8
+ const THEME_ROLES = {
9
+ accent: true,
10
+ border: true,
11
+ borderAccent: true,
12
+ borderMuted: true,
13
+ success: true,
14
+ error: true,
15
+ warning: true,
16
+ muted: true,
17
+ dim: true,
18
+ text: true,
19
+ thinkingText: true,
20
+ scrollbarTrack: true,
21
+ scrollbarThumb: true,
22
+ selectedBg: true,
23
+ searchMatchBg: true,
24
+ searchMatchText: true,
25
+ userMessageBg: true,
26
+ userMessageText: true,
27
+ customMessageBg: true,
28
+ customMessageText: true,
29
+ customMessageLabel: true,
30
+ toolPendingBg: true,
31
+ toolSuccessBg: true,
32
+ toolErrorBg: true,
33
+ toolTitle: true,
34
+ toolOutput: true,
35
+ mdHeading: true,
36
+ mdLink: true,
37
+ mdLinkUrl: true,
38
+ mdCode: true,
39
+ mdCodeBlock: true,
40
+ mdCodeBlockBorder: true,
41
+ mdQuote: true,
42
+ mdQuoteBorder: true,
43
+ mdHr: true,
44
+ mdListBullet: true,
45
+ toolDiffAdded: true,
46
+ toolDiffRemoved: true,
47
+ toolDiffContext: true,
48
+ syntaxComment: true,
49
+ syntaxKeyword: true,
50
+ syntaxFunction: true,
51
+ syntaxVariable: true,
52
+ syntaxString: true,
53
+ syntaxNumber: true,
54
+ syntaxType: true,
55
+ syntaxOperator: true,
56
+ syntaxPunctuation: true,
57
+ thinkingOff: true,
58
+ thinkingMinimal: true,
59
+ thinkingLow: true,
60
+ thinkingMedium: true,
61
+ thinkingHigh: true,
62
+ thinkingXhigh: true,
63
+ thinkingMax: true,
64
+ bashMode: true,
65
+ } satisfies Record<ThemeToken, true>;
66
+
67
+ export function isThemeRole(role: string): role is ThemeToken {
68
+ return Object.hasOwn(THEME_ROLES, role);
69
+ }
@@ -73,7 +73,7 @@ function isTruncationDirection(value: unknown): value is TruncationDirection {
73
73
  }
74
74
 
75
75
  export function shortenModel(model: string): string {
76
- return model
76
+ return sanitizeTerminalText(model)
77
77
  .replace(/^claude-/u, "")
78
78
  .replace(/-20\d{6}$/u, "")
79
79
  .replace(/-latest$/u, "");
@@ -1,4 +1,5 @@
1
1
  import { visibleWidth } from "@earendil-works/pi-tui";
2
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
2
3
  import { activePalette, type ModuleConfig, type StarshipConfig } from "../config.js";
3
4
  import { type FormatValue, formatVariables, renderFormat } from "../format/formatter.js";
4
5
  import {
@@ -8,6 +9,8 @@ import {
8
9
  renderChunksToAnsi,
9
10
  type StyledChunk,
10
11
  } from "../format/style.js";
12
+ import { sanitizeFormatText } from "../format/terminal-safety.js";
13
+ import type { ThemeColors } from "../format/theme-colors.js";
11
14
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./catalog.js";
12
15
  import { resolveStyleRule } from "./style-rules.js";
13
16
  import type { ModuleStyleContext, ModuleValueContext, RenderedStatusline, StarshipRuntimeSnapshot } from "./types.js";
@@ -17,6 +20,7 @@ export function renderStatusline(
17
20
  runtime: StarshipRuntimeSnapshot,
18
21
  width = 80,
19
22
  trueColor = true,
23
+ themeColors?: ThemeColors,
20
24
  ): RenderedStatusline<ModuleName> {
21
25
  const palette = activePalette(config);
22
26
  const modules = {} as Record<ModuleName, StyledChunk[]>;
@@ -64,7 +68,7 @@ export function renderStatusline(
64
68
  const layout = renderFormat(config.formatAst, { variables: rootVariables, palette });
65
69
  const chunks = resolveFillLayout(layout, width);
66
70
  return {
67
- ansi: renderChunksToAnsi(chunks, trueColor),
71
+ ansi: renderChunksToAnsi(chunks, trueColor, themeColors),
68
72
  chunks,
69
73
  modules,
70
74
  };
@@ -77,14 +81,80 @@ function valueContext(
77
81
  palette: ColorPalette,
78
82
  ): ModuleValueContext {
79
83
  return {
80
- runtime,
84
+ runtime: runtimeForDisplay(name, runtime),
81
85
  palette,
82
- symbol: config.modules[name].symbol,
83
- options: config.modules[name].options,
84
- extensionStatus: config.extensionStatus,
86
+ symbol: sanitizeFormatText(config.modules[name].symbol),
87
+ options: Object.fromEntries(
88
+ Object.entries(config.modules[name].options).map(([key, value]) => [
89
+ key,
90
+ typeof value === "string"
91
+ ? sanitizeTerminalText(value)
92
+ : Array.isArray(value)
93
+ ? value.map(sanitizeTerminalText)
94
+ : value && typeof value === "object"
95
+ ? sanitizeFields(value)
96
+ : value,
97
+ ]),
98
+ ),
99
+ extensionStatus: {
100
+ ...config.extensionStatus,
101
+ separator: sanitizeFormatText(config.extensionStatus.separator),
102
+ icons: Object.fromEntries(
103
+ Object.entries(config.extensionStatus.icons).map(([key, value]) => [key, sanitizeFormatText(value)]),
104
+ ),
105
+ },
85
106
  };
86
107
  }
87
108
 
109
+ // Shallow presentation copies retain keys used for aliases and status policies.
110
+ function sanitizeFields<T extends object>(value: T): T {
111
+ return Object.fromEntries(
112
+ Object.entries(value).map(([key, item]) => [key, typeof item === "string" ? sanitizeTerminalText(item) : item]),
113
+ ) as T;
114
+ }
115
+
116
+ function runtimeForDisplay(name: ModuleName, runtime: StarshipRuntimeSnapshot): StarshipRuntimeSnapshot {
117
+ // Only modules that transform text need sanitized inputs before their value
118
+ // function runs. Pass-through values are sanitized by the formatter, avoiding
119
+ // a full snapshot copy and preserving raw model/provider alias identities.
120
+ switch (name) {
121
+ case "directory":
122
+ return {
123
+ ...runtime,
124
+ ...sanitizeFields({ cwd: runtime.cwd, homeDir: runtime.homeDir, gitRoot: runtime.gitRoot }),
125
+ };
126
+ case "git_branch":
127
+ return {
128
+ ...runtime,
129
+ gitBranch: runtime.gitBranch === null ? null : sanitizeTerminalText(runtime.gitBranch),
130
+ gitBranchDetails: runtime.gitBranchDetails ? sanitizeFields(runtime.gitBranchDetails) : undefined,
131
+ };
132
+ case "git_commit":
133
+ return { ...runtime, gitCommit: runtime.gitCommit ? sanitizeFields(runtime.gitCommit) : undefined };
134
+ case "conda": {
135
+ const values = runtime.workspace?.modules.conda;
136
+ return values && runtime.workspace
137
+ ? {
138
+ ...runtime,
139
+ workspace: {
140
+ ...runtime.workspace,
141
+ modules: { ...runtime.workspace.modules, conda: sanitizeFields(values) },
142
+ },
143
+ }
144
+ : runtime;
145
+ }
146
+ case "extension_status":
147
+ return {
148
+ ...runtime,
149
+ extensionStatuses: new Map(
150
+ [...runtime.extensionStatuses].map(([key, value]) => [key, sanitizeTerminalText(value)]),
151
+ ),
152
+ };
153
+ default:
154
+ return runtime;
155
+ }
156
+ }
157
+
88
158
  function renderModule(
89
159
  module: ModuleConfig,
90
160
  values: Readonly<Record<string, FormatValue>>,