pi-one-ui 0.1.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.
Files changed (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -0
  3. package/extensions/app/config/renderer.ts +452 -0
  4. package/extensions/app/config/shell.ts +2484 -0
  5. package/extensions/app/ownership.ts +18 -0
  6. package/extensions/app/panel.ts +533 -0
  7. package/extensions/app/presets.ts +36 -0
  8. package/extensions/features/agent-summary/core.ts +194 -0
  9. package/extensions/features/agent-summary/index.ts +37 -0
  10. package/extensions/features/compact-thinking.ts +1262 -0
  11. package/extensions/features/context.ts +857 -0
  12. package/extensions/features/reference/index.ts +643 -0
  13. package/extensions/features/reference/session.ts +278 -0
  14. package/extensions/features/reference/subagent.ts +218 -0
  15. package/extensions/features/shell/aliases.ts +28 -0
  16. package/extensions/features/shell/flush-docked-bash.ts +39 -0
  17. package/extensions/features/shell/startup-header.ts +357 -0
  18. package/extensions/features/shell/working-message.ts +226 -0
  19. package/extensions/index.ts +52 -0
  20. package/extensions/shell/accent-rail-editor.ts +112 -0
  21. package/extensions/shell/accent-rail-layout-patch.ts +530 -0
  22. package/extensions/shell/completion-menu.ts +186 -0
  23. package/extensions/shell/editor-metadata-format.ts +287 -0
  24. package/extensions/shell/editor-transfer.ts +73 -0
  25. package/extensions/shell/extension-status.ts +102 -0
  26. package/extensions/shell/footer-format.ts +388 -0
  27. package/extensions/shell/footer-layout.ts +144 -0
  28. package/extensions/shell/footer.ts +1035 -0
  29. package/extensions/shell/format.ts +577 -0
  30. package/extensions/shell/git.ts +434 -0
  31. package/extensions/shell/icons.ts +261 -0
  32. package/extensions/shell/index.ts +1659 -0
  33. package/extensions/shell/interaction-summary.ts +1194 -0
  34. package/extensions/shell/live-context.ts +82 -0
  35. package/extensions/shell/minimalist-editor.ts +548 -0
  36. package/extensions/shell/package-version.ts +675 -0
  37. package/extensions/shell/project-refresh.ts +130 -0
  38. package/extensions/shell/project-state.ts +60 -0
  39. package/extensions/shell/prototype-patch-registry.ts +183 -0
  40. package/extensions/shell/runtime.ts +915 -0
  41. package/extensions/shell/selector-border.ts +109 -0
  42. package/extensions/shell/session-lifecycle.ts +60 -0
  43. package/extensions/shell/settings-command.ts +2144 -0
  44. package/extensions/shell/settings-previews.ts +137 -0
  45. package/extensions/shell/state.ts +83 -0
  46. package/extensions/shell/style.ts +480 -0
  47. package/extensions/shell/telemetry.ts +90 -0
  48. package/extensions/shell/ui.ts +1326 -0
  49. package/extensions/shell/user-message-osc.ts +279 -0
  50. package/extensions/shell/user-message-styles.ts +266 -0
  51. package/extensions/shell/user-message.ts +226 -0
  52. package/extensions/shell/working-line-messages.ts +24 -0
  53. package/extensions/shell/working-line-spinners.ts +54 -0
  54. package/extensions/shell/working-line.ts +1603 -0
  55. package/extensions/tools/ansi-color.ts +44 -0
  56. package/extensions/tools/ansi-text.ts +52 -0
  57. package/extensions/tools/component-tree.ts +37 -0
  58. package/extensions/tools/format.ts +28 -0
  59. package/extensions/tools/fullscreen-detect.ts +11 -0
  60. package/extensions/tools/patch-keys.ts +158 -0
  61. package/extensions/tools/sgr-mouse.ts +59 -0
  62. package/extensions/tools/tool-loading-icon.ts +20 -0
  63. package/extensions/tools/tool-result-sanitize.ts +27 -0
  64. package/extensions/transcript/index.ts +65 -0
  65. package/extensions/transcript/renderer/compact-mode.ts +1443 -0
  66. package/extensions/transcript/renderer/default-mode.ts +735 -0
  67. package/extensions/transcript/renderer/index.ts +286 -0
  68. package/extensions/transcript/renderer/markdown-enhance.ts +325 -0
  69. package/extensions/transcript/renderer/mouse/hover.ts +175 -0
  70. package/extensions/transcript/renderer/mouse/interaction.ts +1016 -0
  71. package/extensions/transcript/renderer/mouse/layout.ts +207 -0
  72. package/extensions/transcript/renderer/mouse/packets.ts +96 -0
  73. package/extensions/transcript/renderer/mouse/scroll.ts +211 -0
  74. package/extensions/transcript/renderer/tool/diff/ATTRIBUTION.md +28 -0
  75. package/extensions/transcript/renderer/tool/diff/ansi-utils.ts +128 -0
  76. package/extensions/transcript/renderer/tool/diff/diff-component.ts +112 -0
  77. package/extensions/transcript/renderer/tool/diff/diff-edit-render.ts +255 -0
  78. package/extensions/transcript/renderer/tool/diff/diff-header.ts +184 -0
  79. package/extensions/transcript/renderer/tool/diff/diff-highlight.ts +131 -0
  80. package/extensions/transcript/renderer/tool/diff/diff-inline.ts +350 -0
  81. package/extensions/transcript/renderer/tool/diff/diff-layout.ts +870 -0
  82. package/extensions/transcript/renderer/tool/diff/diff-limits.ts +189 -0
  83. package/extensions/transcript/renderer/tool/diff/diff-palette.ts +436 -0
  84. package/extensions/transcript/renderer/tool/diff/diff-parse.ts +536 -0
  85. package/extensions/transcript/renderer/tool/diff/diff-presentation.ts +79 -0
  86. package/extensions/transcript/renderer/tool/diff/diff-renderer.ts +29 -0
  87. package/extensions/transcript/renderer/tool/diff/diff-text.ts +57 -0
  88. package/extensions/transcript/renderer/tool/diff/diff-write-render.ts +629 -0
  89. package/extensions/transcript/renderer/tool/diff/index.ts +147 -0
  90. package/extensions/transcript/renderer/tool/diff/line-width-safety.ts +100 -0
  91. package/extensions/transcript/renderer/tool/diff/shiki-highlight.ts +104 -0
  92. package/extensions/transcript/renderer/tool/diff/write-execution.ts +124 -0
  93. package/extensions/transcript/renderer/tool/grouping.ts +619 -0
  94. package/extensions/transcript/renderer/tool/message-display.ts +183 -0
  95. package/extensions/transcript/renderer/tool/names.ts +195 -0
  96. package/extensions/transcript/renderer/tool/result.ts +842 -0
  97. package/extensions/transcript/renderer/tool/show-more-hint.ts +42 -0
  98. package/extensions/transcript/renderer/transcript-refresh.ts +79 -0
  99. package/package.json +58 -0
  100. package/themes/cc-dark.json +91 -0
  101. package/themes/cc-light.json +91 -0
@@ -0,0 +1,577 @@
1
+ import { homedir, hostname, userInfo } from "node:os";
2
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
3
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
+ import type {
5
+ ColorSource,
6
+ ColorSpec,
7
+ ContextStyle,
8
+ ContextThresholds,
9
+ GitBranchMaxLength,
10
+ PathDisplayMode,
11
+ } from "../app/config/shell.ts";
12
+ import type { GitCommitInfo, GitMetricsInfo } from "./git.ts";
13
+ import type { IconMode } from "./icons.ts";
14
+ import {
15
+ resolveOsIcon,
16
+ resolvePackageIcon,
17
+ resolveRuntimeSymbol,
18
+ } from "./icons.ts";
19
+ import type { PackageVersionResult } from "./package-version.ts";
20
+ import type { RuntimeInfo } from "./runtime.ts";
21
+ import { renderStyleForSource } from "./style.ts";
22
+
23
+ /**
24
+ * Starship `git_commit` style — render a short hash, optionally with an
25
+ * exact-match tag. See https://starship.rs/config/#git-commit
26
+ *
27
+ * Visibility is decided by the caller; this helper only formats the data.
28
+ * `hashLength` is clamped to [4, 40] upstream.
29
+ */
30
+ export function formatGitCommitSegment(
31
+ theme: Pick<Theme, "fg">,
32
+ commit: GitCommitInfo | undefined,
33
+ config: { hashLength: number; onlyDetached: boolean; showTag: boolean },
34
+ colorSource: ColorSource,
35
+ style: ColorSpec,
36
+ ): string {
37
+ if (!commit?.oid) return "";
38
+ // Starship's only_detached hides the whole module when attached.
39
+ if (config.onlyDetached && !commit.detached) return "";
40
+ const hash = commit.oid.slice(0, config.hashLength);
41
+ const tag = config.showTag && commit.tag ? commit.tag : "";
42
+ if (!hash && !tag) return "";
43
+ const label = [hash, tag].filter(Boolean).join(" ");
44
+ return renderStyleForSource(theme, colorSource, style, label);
45
+ }
46
+
47
+ /**
48
+ * Starship `git_metrics` style — render `+added −deleted` line counts.
49
+ * See https://starship.rs/config/#git-metrics
50
+ *
51
+ * When `onlyNonzero` is true, each zero component is omitted independently
52
+ * and the whole segment hides at 0/0.
53
+ */
54
+ export function formatGitMetricsSegment(
55
+ theme: Pick<Theme, "fg">,
56
+ metrics: GitMetricsInfo | null | undefined,
57
+ config: { onlyNonzero: boolean },
58
+ colorSource: ColorSource,
59
+ addedStyle: ColorSpec,
60
+ deletedStyle: ColorSpec,
61
+ ): string {
62
+ if (!metrics) return "";
63
+ const showAdded = !config.onlyNonzero || metrics.added > 0;
64
+ const showDeleted = !config.onlyNonzero || metrics.deleted > 0;
65
+ if (!showAdded && !showDeleted) return "";
66
+ const parts: string[] = [];
67
+ if (showAdded) {
68
+ parts.push(
69
+ renderStyleForSource(theme, colorSource, addedStyle, `+${metrics.added}`),
70
+ );
71
+ }
72
+ if (showDeleted) {
73
+ parts.push(
74
+ renderStyleForSource(
75
+ theme,
76
+ colorSource,
77
+ deletedStyle,
78
+ `−${metrics.deleted}`,
79
+ ),
80
+ );
81
+ }
82
+ return parts.join(" ");
83
+ }
84
+
85
+ export type UsageTotals = {
86
+ input: number;
87
+ output: number;
88
+ cacheRead: number;
89
+ cacheWrite: number;
90
+ latestCacheHitRate?: number;
91
+ cost: number;
92
+ };
93
+
94
+ export type ContextColorTier = "normal" | "warning" | "error";
95
+
96
+ type SessionUsage = {
97
+ input?: unknown;
98
+ output?: unknown;
99
+ cacheRead?: unknown;
100
+ cacheWrite?: unknown;
101
+ cost?: unknown;
102
+ };
103
+
104
+ type SessionEntry = {
105
+ type?: string;
106
+ id?: string | number;
107
+ timestamp?: string | number;
108
+ usage?: SessionUsage;
109
+ message?: {
110
+ role?: string;
111
+ usage?: SessionUsage;
112
+ };
113
+ };
114
+
115
+ type SelectedUsage = {
116
+ usage: SessionUsage | undefined;
117
+ location: "message" | "entry";
118
+ isAssistant: boolean;
119
+ };
120
+
121
+ type UsageCacheEntry = {
122
+ key: string;
123
+ totals: UsageTotals;
124
+ };
125
+
126
+ const MAX_USAGE_TOTAL = Number.MAX_VALUE;
127
+
128
+ let usageTotalsCache: UsageCacheEntry | undefined;
129
+ let usageTotalsAggregationPassCount = 0;
130
+
131
+ export function formatCount(value: number): string {
132
+ if (value < 1000) return value.toString();
133
+ if (value < 10_000) return `${(value / 1000).toFixed(1)}k`;
134
+ if (value < 1_000_000) return `${Math.round(value / 1000)}k`;
135
+ if (value < 10_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
136
+ return `${Math.round(value / 1_000_000)}M`;
137
+ }
138
+
139
+ /** Human-readable whole-second duration used by settled and minimalist turn UI. */
140
+ export function formatElapsedDuration(durationMs: number): string {
141
+ const totalSeconds = Math.max(0, Math.floor(durationMs / 1000));
142
+ const hours = Math.floor(totalSeconds / 3600);
143
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
144
+ const seconds = totalSeconds % 60;
145
+ if (hours > 0) return `${hours}h ${minutes}m`;
146
+ if (minutes > 0) return `${minutes}m ${seconds}s`;
147
+ return `${seconds}s`;
148
+ }
149
+
150
+ export function formatProviderLabel(provider: string | undefined): string {
151
+ if (!provider) return "Unknown";
152
+
153
+ const known: Record<string, string> = {
154
+ anthropic: "Anthropic",
155
+ gemini: "Google",
156
+ google: "Google",
157
+ ollama: "Ollama",
158
+ openai: "OpenAI",
159
+ "openai-codex": "OpenAI",
160
+ };
161
+
162
+ return (
163
+ known[provider] ??
164
+ provider
165
+ .replace(/[-_]/g, " ")
166
+ .replace(/\b\w/g, (char) => char.toUpperCase())
167
+ );
168
+ }
169
+
170
+ function calculateCacheHitRate(
171
+ input: number,
172
+ cacheRead: number,
173
+ cacheWrite: number,
174
+ ): number | undefined {
175
+ const promptTokens = input + cacheRead + cacheWrite;
176
+ if (promptTokens === 0) return undefined;
177
+ if (Number.isFinite(promptTokens)) return (cacheRead / promptTokens) * 100;
178
+
179
+ const scale = Math.max(input, cacheRead, cacheWrite);
180
+ const scaledPromptTokens =
181
+ input / scale + cacheRead / scale + cacheWrite / scale;
182
+ return (cacheRead / scale / scaledPromptTokens) * 100;
183
+ }
184
+
185
+ function normalizeUsageNumber(value: unknown): number {
186
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
187
+ ? value
188
+ : 0;
189
+ }
190
+
191
+ function usageCostTotal(usage: SessionUsage | undefined): number {
192
+ if (typeof usage?.cost !== "object" || usage.cost === null) return 0;
193
+ return normalizeUsageNumber((usage.cost as { total?: unknown }).total);
194
+ }
195
+
196
+ function addUsageTotal(total: number, value: number): number {
197
+ const sum = total + value;
198
+ return Number.isFinite(sum) ? sum : MAX_USAGE_TOTAL;
199
+ }
200
+
201
+ function usageForEntry(entry: SessionEntry): SelectedUsage | undefined {
202
+ if (entry.type === "message") {
203
+ const role = entry.message?.role;
204
+ if (role !== "assistant" && role !== "toolResult") return undefined;
205
+ return {
206
+ usage: entry.message?.usage,
207
+ location: "message",
208
+ isAssistant: role === "assistant",
209
+ };
210
+ }
211
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
212
+ return { usage: entry.usage, location: "entry", isAssistant: false };
213
+ }
214
+ return undefined;
215
+ }
216
+
217
+ function normalizedUsage(usage: SessionUsage | undefined) {
218
+ return {
219
+ input: normalizeUsageNumber(usage?.input),
220
+ output: normalizeUsageNumber(usage?.output),
221
+ cacheRead: normalizeUsageNumber(usage?.cacheRead),
222
+ cacheWrite: normalizeUsageNumber(usage?.cacheWrite),
223
+ cost: usageCostTotal(usage),
224
+ };
225
+ }
226
+
227
+ function entryIdentity(entry: SessionEntry): string {
228
+ const selected = usageForEntry(entry);
229
+ if (!selected) return "unsupported";
230
+ const usage = normalizedUsage(selected.usage);
231
+ return JSON.stringify([
232
+ entry.id ?? null,
233
+ entry.timestamp ?? null,
234
+ entry.type ?? null,
235
+ entry.message?.role ?? null,
236
+ selected.location,
237
+ usage.input,
238
+ usage.output,
239
+ usage.cacheRead,
240
+ usage.cacheWrite,
241
+ usage.cost,
242
+ ]);
243
+ }
244
+
245
+ function buildUsageFingerprint(entries: readonly SessionEntry[]): string {
246
+ return entries.map(entryIdentity).join("\0");
247
+ }
248
+
249
+ function computeUsageTotals(entries: readonly SessionEntry[]): UsageTotals {
250
+ usageTotalsAggregationPassCount += 1;
251
+ let input = 0;
252
+ let output = 0;
253
+ let cacheRead = 0;
254
+ let cacheWrite = 0;
255
+ let latestCacheHitRate: number | undefined;
256
+ let cost = 0;
257
+
258
+ for (const entry of entries) {
259
+ const selected = usageForEntry(entry);
260
+ if (!selected) continue;
261
+ const usage = normalizedUsage(selected.usage);
262
+
263
+ input = addUsageTotal(input, usage.input);
264
+ output = addUsageTotal(output, usage.output);
265
+ cacheRead = addUsageTotal(cacheRead, usage.cacheRead);
266
+ cacheWrite = addUsageTotal(cacheWrite, usage.cacheWrite);
267
+ cost = addUsageTotal(cost, usage.cost);
268
+ if (selected.isAssistant) {
269
+ latestCacheHitRate = calculateCacheHitRate(
270
+ usage.input,
271
+ usage.cacheRead,
272
+ usage.cacheWrite,
273
+ );
274
+ }
275
+ }
276
+
277
+ return Object.freeze({
278
+ input,
279
+ output,
280
+ cacheRead,
281
+ cacheWrite,
282
+ latestCacheHitRate,
283
+ cost,
284
+ });
285
+ }
286
+
287
+ export function invalidateUsageTotalsCache(): void {
288
+ usageTotalsCache = undefined;
289
+ }
290
+
291
+ /** Test helper: counts aggregation passes only; every cache lookup still fingerprints all entries. */
292
+ export function __usageTotalsAggregationPassCount(): number {
293
+ return usageTotalsAggregationPassCount;
294
+ }
295
+
296
+ /** Test helper: reset the aggregation-pass counter and cached totals. */
297
+ export function __resetUsageTotalsCacheForTests(): void {
298
+ usageTotalsCache = undefined;
299
+ usageTotalsAggregationPassCount = 0;
300
+ }
301
+
302
+ export function getUsageTotals(ctx: ExtensionContext): UsageTotals {
303
+ const sessionManager = ctx.sessionManager as {
304
+ getEntries?: () => readonly SessionEntry[];
305
+ getBranch: () => readonly SessionEntry[];
306
+ };
307
+ const entries =
308
+ typeof sessionManager.getEntries === "function"
309
+ ? sessionManager.getEntries()
310
+ : sessionManager.getBranch();
311
+ const key = buildUsageFingerprint(entries);
312
+ if (usageTotalsCache?.key === key) return usageTotalsCache.totals;
313
+
314
+ const totals = computeUsageTotals(entries);
315
+ usageTotalsCache = { key, totals };
316
+ return totals;
317
+ }
318
+
319
+ export function buildCacheReadLabel(cacheRead: number): string {
320
+ return cacheRead > 0 ? `R${formatCount(cacheRead)}` : "";
321
+ }
322
+
323
+ export function buildCacheWriteLabel(cacheWrite: number): string {
324
+ return cacheWrite > 0 ? `W${formatCount(cacheWrite)}` : "";
325
+ }
326
+
327
+ export function buildTokenLabel(
328
+ totals: UsageTotals,
329
+ cacheHitIcon = "󰆼",
330
+ ): string {
331
+ const parts: string[] = [];
332
+ if (totals.input) parts.push(`↑${formatCount(totals.input)}`);
333
+ if (totals.output) parts.push(`↓${formatCount(totals.output)}`);
334
+
335
+ const hasCacheTokens = totals.cacheRead > 0 || totals.cacheWrite > 0;
336
+ if (hasCacheTokens && totals.latestCacheHitRate !== undefined) {
337
+ const cacheHitRate = `${totals.latestCacheHitRate.toFixed(1)}%`;
338
+ parts.push(cacheHitIcon ? `${cacheHitIcon} ${cacheHitRate}` : cacheHitRate);
339
+ }
340
+ return parts.length > 0 ? parts.join(" ") : "↑0 ↓0";
341
+ }
342
+
343
+ export function buildCostLabel(totals: UsageTotals): string {
344
+ return `$${totals.cost.toFixed(3)}`;
345
+ }
346
+
347
+ export function buildSessionDurationLabel(startEpoch: number): string {
348
+ const totalSeconds = Math.max(
349
+ 0,
350
+ Math.floor((Date.now() - startEpoch) / 1000),
351
+ );
352
+ const hours = Math.floor(totalSeconds / 3600);
353
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
354
+ const seconds = totalSeconds % 60;
355
+ if (hours > 0) return `${hours}h ${minutes}m`;
356
+ if (minutes > 0) return `${minutes}m ${seconds}s`;
357
+ return `${seconds}s`;
358
+ }
359
+
360
+ export function contextColorTier(
361
+ percent: number | null | undefined,
362
+ thresholds: ContextThresholds = { warning: 70, error: 90 },
363
+ ): ContextColorTier {
364
+ if (percent === null || percent === undefined || !Number.isFinite(percent))
365
+ return "normal";
366
+ if (percent >= thresholds.error) return "error";
367
+ if (percent >= thresholds.warning) return "warning";
368
+ return "normal";
369
+ }
370
+
371
+ export function buildContextGauge(
372
+ percent: number,
373
+ width = 10,
374
+ ascii = false,
375
+ ): string {
376
+ const clamped = Math.max(0, Math.min(100, percent));
377
+ const filled = Math.round((clamped / 100) * width);
378
+ const on = ascii ? "#" : "█";
379
+ const off = ascii ? "-" : "░";
380
+ return `${on.repeat(filled)}${off.repeat(Math.max(0, width - filled))}`;
381
+ }
382
+
383
+ export function formatContextPercentLabel(
384
+ percent: number | null | undefined,
385
+ contextWindow: number | undefined,
386
+ ): string {
387
+ if (!contextWindow || contextWindow <= 0) return "--";
388
+ const percentLabel =
389
+ percent === null || percent === undefined || !Number.isFinite(percent)
390
+ ? "?"
391
+ : `${Math.max(0, Math.min(999, percent)).toFixed(1)}%`;
392
+ return `${percentLabel}/${formatCount(contextWindow)}`;
393
+ }
394
+
395
+ export function buildContextDisplayLabel(options: {
396
+ percent: number | null | undefined;
397
+ contextWindow: number | undefined;
398
+ style?: ContextStyle;
399
+ asciiGauge?: boolean;
400
+ }): string {
401
+ const {
402
+ percent,
403
+ contextWindow,
404
+ style = "text",
405
+ asciiGauge = false,
406
+ } = options;
407
+ if (!contextWindow || contextWindow <= 0) return "--";
408
+
409
+ const text = formatContextPercentLabel(percent, contextWindow);
410
+ const numericPercent =
411
+ percent === null || percent === undefined || !Number.isFinite(percent)
412
+ ? 0
413
+ : Math.max(0, Math.min(100, percent));
414
+ const gauge = buildContextGauge(numericPercent, 10, asciiGauge);
415
+
416
+ if (style === "gauge") return `[${gauge}]`;
417
+ if (style === "text+gauge") return `[${gauge}] ${text}`;
418
+ return text;
419
+ }
420
+
421
+ export function buildContextLabel(ctx: ExtensionContext): string {
422
+ const usage = ctx.getContextUsage();
423
+ const contextWindow = ctx.model?.contextWindow ?? usage?.contextWindow;
424
+ return formatContextPercentLabel(usage?.percent, contextWindow);
425
+ }
426
+
427
+ export function formatRuntimeSegment(
428
+ theme: Pick<Theme, "fg">,
429
+ runtime: RuntimeInfo | undefined,
430
+ prefixStyle: ColorSpec,
431
+ colorSource: ColorSource,
432
+ mode: IconMode = "auto",
433
+ ): string {
434
+ if (!runtime) return "";
435
+ const symbol = resolveRuntimeSymbol(runtime.name, runtime.symbol, mode);
436
+ const label = runtime.version ? `${symbol} ${runtime.version}` : symbol;
437
+ return `${renderStyleForSource(theme, colorSource, prefixStyle, "via")} ${renderStyleForSource(theme, colorSource, runtime.style, label)}`;
438
+ }
439
+
440
+ /**
441
+ * Render the package-version segment in Starship `is <glyph> <version>` shape.
442
+ *
443
+ * Distinct from the runtime segment: this surfaces the project's own
444
+ * manifest version (e.g. `package.json#version`), not the installed
445
+ * toolchain version. Glyph comes from the Starship Nerd Font preset
446
+ * (https://starship.rs/presets/nerd-font); default color `208` matches
447
+ * the Starship `package` module default
448
+ * (https://starship.rs/config/#package-version).
449
+ */
450
+ export function formatPackageVersionSegment(
451
+ theme: Pick<Theme, "fg">,
452
+ pkg: PackageVersionResult | undefined,
453
+ colorSource: ColorSource,
454
+ mode: IconMode = "auto",
455
+ configuredIcon: string = "",
456
+ versionStyle: ColorSpec = "208",
457
+ ): string {
458
+ if (!pkg) return "";
459
+ const icon = resolvePackageIcon(configuredIcon, mode);
460
+ const label = `${icon} ${pkg.version}`;
461
+ return `${renderStyleForSource(theme, colorSource, "", "is")} ${renderStyleForSource(theme, colorSource, versionStyle, label)}`;
462
+ }
463
+
464
+ export type FormatCwdOptions = {
465
+ mode?: PathDisplayMode;
466
+ /** Trailing directory components to keep in full mode. 0 = unlimited. */
467
+ depth?: number;
468
+ home?: string;
469
+ };
470
+
471
+ function normalizeDisplayPath(cwd: string): string {
472
+ const withSlashes = cwd.replace(/\\/g, "/");
473
+ if (withSlashes === "/" || /^\/+$/.test(withSlashes)) return "/";
474
+ const stripped = withSlashes.replace(/\/+$/, "");
475
+ return stripped === "" ? withSlashes : stripped;
476
+ }
477
+
478
+ function toHomePath(path: string, home: string): string {
479
+ if (!home) return path;
480
+ const homeNorm = home.replace(/\\/g, "/").replace(/\/+$/, "");
481
+ if (!homeNorm) return path;
482
+ if (path === homeNorm) return "~";
483
+ if (path.startsWith(`${homeNorm}/`)) return `~${path.slice(homeNorm.length)}`;
484
+ return path;
485
+ }
486
+
487
+ /** Starship-style: keep last `depth` components; prefix with `…/` when parents were dropped. */
488
+ function applyPathDepth(path: string, depth: number): string {
489
+ if (!Number.isFinite(depth) || depth <= 0) return path;
490
+ const limit = Math.floor(depth);
491
+ if (path === "~" || path === "/") return path;
492
+
493
+ let components: string[];
494
+ if (path.startsWith("~/")) {
495
+ components = path.slice(2).split("/").filter(Boolean);
496
+ } else if (/^[A-Za-z]:\//.test(path)) {
497
+ components = path.slice(3).split("/").filter(Boolean);
498
+ } else if (path.startsWith("/")) {
499
+ components = path.slice(1).split("/").filter(Boolean);
500
+ } else {
501
+ components = path.split("/").filter(Boolean);
502
+ }
503
+
504
+ if (components.length <= limit) return path;
505
+ return `…/${components.slice(-limit).join("/")}`;
506
+ }
507
+
508
+ export function formatCwdLabel(
509
+ cwd: string,
510
+ cwdIcon: string,
511
+ options?: FormatCwdOptions,
512
+ ): string {
513
+ const mode = options?.mode ?? "basename";
514
+ const normalized = normalizeDisplayPath(cwd);
515
+ let pathText: string;
516
+ if (mode === "full") {
517
+ const home =
518
+ options?.home ??
519
+ (() => {
520
+ try {
521
+ return homedir();
522
+ } catch {
523
+ return "";
524
+ }
525
+ })();
526
+ pathText = applyPathDepth(
527
+ toHomePath(normalized, home),
528
+ options?.depth ?? 0,
529
+ );
530
+ } else if (normalized === "/") {
531
+ pathText = "/";
532
+ } else {
533
+ const parts = normalized.split("/").filter(Boolean);
534
+ pathText = parts[parts.length - 1] ?? cwd;
535
+ }
536
+ return cwdIcon ? `${cwdIcon} ${pathText}` : pathText;
537
+ }
538
+
539
+ function stripAnsi(text: string): string {
540
+ return text.replace(/\u001B\[[0-9;]*m/g, "");
541
+ }
542
+
543
+ export function formatGitBranchText(
544
+ branch: string,
545
+ maxLength: GitBranchMaxLength = "full",
546
+ ): string {
547
+ if (maxLength === "full" || visibleWidth(branch) <= maxLength) return branch;
548
+ return stripAnsi(truncateToWidth(branch, maxLength, "…"));
549
+ }
550
+
551
+ export function formatUsernameHostLabel(icon: string): string {
552
+ try {
553
+ const user = userInfo().username;
554
+ const host = hostname();
555
+ if (!user || !host) return "";
556
+ const label = `${user}@${host}`;
557
+ return icon ? `${icon} ${label}` : label;
558
+ } catch {
559
+ return "";
560
+ }
561
+ }
562
+
563
+ export function formatTimeLabel(icon: string): string {
564
+ const now = new Date();
565
+ const hours = String(now.getHours()).padStart(2, "0");
566
+ const minutes = String(now.getMinutes()).padStart(2, "0");
567
+ const label = `${hours}:${minutes}`;
568
+ return icon ? `${icon} ${label}` : label;
569
+ }
570
+
571
+ export function formatOsLabel(
572
+ configuredIcon: string,
573
+ mode: IconMode = "auto",
574
+ platform: string = process.platform,
575
+ ): string {
576
+ return resolveOsIcon(configuredIcon, mode, platform);
577
+ }