@xzzpig/pi-starline 0.1.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 (45) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +223 -0
  3. package/extensions/starline/config.ts +1317 -0
  4. package/extensions/starline/editor-cursor.ts +55 -0
  5. package/extensions/starline/editor-factory-marker.ts +49 -0
  6. package/extensions/starline/editor-metadata-format.ts +259 -0
  7. package/extensions/starline/extension-status.ts +88 -0
  8. package/extensions/starline/footer-format.ts +279 -0
  9. package/extensions/starline/footer.ts +744 -0
  10. package/extensions/starline/format.ts +473 -0
  11. package/extensions/starline/git.ts +467 -0
  12. package/extensions/starline/icons.ts +294 -0
  13. package/extensions/starline/index.ts +651 -0
  14. package/extensions/starline/live-context.ts +75 -0
  15. package/extensions/starline/mouse/capabilities.ts +207 -0
  16. package/extensions/starline/mouse/component-tree.ts +230 -0
  17. package/extensions/starline/mouse/editor-caret.ts +498 -0
  18. package/extensions/starline/mouse/editor-hit-test.ts +133 -0
  19. package/extensions/starline/mouse/editor-mouse.ts +142 -0
  20. package/extensions/starline/mouse/editor-scroll.ts +119 -0
  21. package/extensions/starline/mouse/editor-text-cursor.ts +209 -0
  22. package/extensions/starline/mouse/editor-text-edit.ts +90 -0
  23. package/extensions/starline/mouse/hint.ts +14 -0
  24. package/extensions/starline/mouse/hit-test.ts +144 -0
  25. package/extensions/starline/mouse/index.ts +1119 -0
  26. package/extensions/starline/mouse/selection-state.ts +68 -0
  27. package/extensions/starline/mouse/tool-box.ts +290 -0
  28. package/extensions/starline/mouse/transcript-copy.ts +166 -0
  29. package/extensions/starline/mouse/word-select.ts +145 -0
  30. package/extensions/starline/package-version.ts +650 -0
  31. package/extensions/starline/paste-collapse.ts +312 -0
  32. package/extensions/starline/pill-config.ts +122 -0
  33. package/extensions/starline/pill.ts +295 -0
  34. package/extensions/starline/project-refresh.ts +104 -0
  35. package/extensions/starline/project-state.ts +66 -0
  36. package/extensions/starline/prototype-patch-registry.ts +136 -0
  37. package/extensions/starline/runtime.ts +841 -0
  38. package/extensions/starline/selector-border.ts +77 -0
  39. package/extensions/starline/session-lifecycle.ts +60 -0
  40. package/extensions/starline/settings-command.ts +925 -0
  41. package/extensions/starline/state.ts +65 -0
  42. package/extensions/starline/style.ts +528 -0
  43. package/extensions/starline/ui.ts +611 -0
  44. package/extensions/starline/user-message.ts +267 -0
  45. package/package.json +60 -0
@@ -0,0 +1,473 @@
1
+ import { homedir, hostname, userInfo } from "node:os";
2
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
3
+ import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
4
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
+ import type {
6
+ ColorSource,
7
+ ColorSpec,
8
+ ContextFormat,
9
+ ContextStyle,
10
+ ContextThresholds,
11
+ GitBranchMaxLength,
12
+ PathDisplayMode,
13
+ TokensCacheFormat,
14
+ } from "./config";
15
+ import type { GitCommitInfo, GitMetricsInfo } from "./git";
16
+ import type { IconMode } from "./icons";
17
+ import { resolveOsIcon, resolvePackageIcon, resolveRuntimeSymbol } from "./icons";
18
+ import type { PackageVersionResult } from "./package-version";
19
+ import type { RuntimeInfo } from "./runtime";
20
+ import { renderStyleForSource } from "./style";
21
+
22
+ /**
23
+ * Starship `git_commit` style — render a short hash, optionally with an
24
+ * exact-match tag. See https://starship.rs/config/#git-commit
25
+ *
26
+ * Visibility is decided by the caller; this helper only formats the data.
27
+ * `hashLength` is clamped to [4, 40] upstream.
28
+ */
29
+ export function formatGitCommitSegment(
30
+ theme: Pick<Theme, "fg">,
31
+ commit: GitCommitInfo | undefined,
32
+ config: { hashLength: number; onlyDetached: boolean; showTag: boolean },
33
+ colorSource: ColorSource,
34
+ style: ColorSpec,
35
+ ): string {
36
+ if (!commit?.oid) return "";
37
+ // Starship's only_detached hides the whole module when attached.
38
+ if (config.onlyDetached && !commit.detached) return "";
39
+ const hash = commit.oid.slice(0, config.hashLength);
40
+ const tag = config.showTag && commit.tag ? commit.tag : "";
41
+ if (!hash && !tag) return "";
42
+ const label = [hash, tag].filter(Boolean).join(" ");
43
+ return renderStyleForSource(theme, colorSource, style, label);
44
+ }
45
+
46
+ /**
47
+ * Starship `git_metrics` style — render `+added −deleted` line counts.
48
+ * See https://starship.rs/config/#git-metrics
49
+ *
50
+ * When `onlyNonzero` is true, each zero component is omitted independently
51
+ * and the whole segment hides at 0/0.
52
+ */
53
+ export function formatGitMetricsSegment(
54
+ theme: Pick<Theme, "fg">,
55
+ metrics: GitMetricsInfo | null | undefined,
56
+ config: { onlyNonzero: boolean },
57
+ colorSource: ColorSource,
58
+ addedStyle: ColorSpec,
59
+ deletedStyle: ColorSpec,
60
+ ): string {
61
+ if (!metrics) return "";
62
+ const showAdded = !config.onlyNonzero || metrics.added > 0;
63
+ const showDeleted = !config.onlyNonzero || metrics.deleted > 0;
64
+ if (!showAdded && !showDeleted) return "";
65
+ const parts: string[] = [];
66
+ if (showAdded) {
67
+ parts.push(renderStyleForSource(theme, colorSource, addedStyle, `+${metrics.added}`));
68
+ }
69
+ if (showDeleted) {
70
+ parts.push(renderStyleForSource(theme, colorSource, deletedStyle, `−${metrics.deleted}`));
71
+ }
72
+ return parts.join(" ");
73
+ }
74
+
75
+ export type UsageTotals = {
76
+ input: number;
77
+ output: number;
78
+ cacheRead: number;
79
+ cacheWrite: number;
80
+ latestCacheHitRate?: number;
81
+ cost: number;
82
+ };
83
+
84
+ export type ContextColorTier = "normal" | "warning" | "error";
85
+
86
+ type SessionEntry = {
87
+ type?: string;
88
+ id?: string | number;
89
+ timestamp?: string | number;
90
+ message?: {
91
+ role?: string;
92
+ usage?: AssistantMessage["usage"];
93
+ };
94
+ };
95
+
96
+ type UsageCacheEntry = {
97
+ key: string;
98
+ totals: UsageTotals;
99
+ };
100
+
101
+ let usageTotalsCache: UsageCacheEntry | undefined;
102
+ let usageTotalsComputeCount = 0;
103
+
104
+ export function formatCount(value: number): string {
105
+ if (value < 1000) return value.toString();
106
+ if (value < 10_000) return `${(value / 1000).toFixed(1)}k`;
107
+ if (value < 1_000_000) return `${Math.round(value / 1000)}k`;
108
+ if (value < 10_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
109
+ return `${Math.round(value / 1_000_000)}M`;
110
+ }
111
+
112
+ export function formatProviderLabel(provider: string | undefined): string {
113
+ if (!provider) return "Unknown";
114
+
115
+ const known: Record<string, string> = {
116
+ anthropic: "Anthropic",
117
+ gemini: "Google",
118
+ google: "Google",
119
+ ollama: "Ollama",
120
+ openai: "OpenAI",
121
+ "openai-codex": "OpenAI",
122
+ };
123
+
124
+ return (
125
+ known[provider] ?? provider.replace(/[-_]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase())
126
+ );
127
+ }
128
+
129
+ function calculateCacheHitRate(
130
+ input: number,
131
+ cacheRead: number,
132
+ cacheWrite: number,
133
+ ): number | undefined {
134
+ const promptTokens = input + cacheRead + cacheWrite;
135
+ return promptTokens > 0 ? (cacheRead / promptTokens) * 100 : undefined;
136
+ }
137
+
138
+ function entryIdentity(entry: SessionEntry | undefined): string {
139
+ if (!entry) return "";
140
+ const usage = entry.message?.usage;
141
+ const usageKey = usage
142
+ ? `${usage.input ?? 0}:${usage.output ?? 0}:${usage.cacheRead ?? 0}:${usage.cacheWrite ?? 0}:${usage.cost?.total ?? 0}`
143
+ : "";
144
+ return `${entry.id ?? ""}|${entry.timestamp ?? ""}|${entry.type ?? ""}|${entry.message?.role ?? ""}|${usageKey}`;
145
+ }
146
+
147
+ function buildUsageFingerprint(entries: readonly SessionEntry[]): string {
148
+ const first = entries[0];
149
+ const last = entries[entries.length - 1];
150
+ return `${entries.length}\0${entryIdentity(first)}\0${entryIdentity(last)}`;
151
+ }
152
+
153
+ function computeUsageTotals(entries: readonly SessionEntry[]): UsageTotals {
154
+ usageTotalsComputeCount += 1;
155
+ let input = 0;
156
+ let output = 0;
157
+ let cacheRead = 0;
158
+ let cacheWrite = 0;
159
+ let latestCacheHitRate: number | undefined;
160
+ let cost = 0;
161
+
162
+ for (const entry of entries) {
163
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
164
+ const usage = entry.message.usage;
165
+ const entryInput = usage?.input ?? 0;
166
+ const entryCacheRead = usage?.cacheRead ?? 0;
167
+ const entryCacheWrite = usage?.cacheWrite ?? 0;
168
+
169
+ input += entryInput;
170
+ output += usage?.output ?? 0;
171
+ cacheRead += entryCacheRead;
172
+ cacheWrite += entryCacheWrite;
173
+ cost += usage?.cost?.total ?? 0;
174
+ latestCacheHitRate = calculateCacheHitRate(entryInput, entryCacheRead, entryCacheWrite);
175
+ }
176
+
177
+ return Object.freeze({ input, output, cacheRead, cacheWrite, latestCacheHitRate, cost });
178
+ }
179
+
180
+ export function invalidateUsageTotalsCache(): void {
181
+ usageTotalsCache = undefined;
182
+ }
183
+
184
+ /** Test helper: number of full usage scans performed since process start / last reset. */
185
+ export function __usageTotalsComputeCount(): number {
186
+ return usageTotalsComputeCount;
187
+ }
188
+
189
+ /** Test helper: reset memoization counters/cache. */
190
+ export function __resetUsageTotalsCacheForTests(): void {
191
+ usageTotalsCache = undefined;
192
+ usageTotalsComputeCount = 0;
193
+ }
194
+
195
+ export function getUsageTotals(ctx: ExtensionContext): UsageTotals {
196
+ const sessionManager = ctx.sessionManager as {
197
+ getEntries?: () => SessionEntry[];
198
+ getBranch: () => SessionEntry[];
199
+ };
200
+ const entries = sessionManager.getEntries?.() ?? sessionManager.getBranch();
201
+ const key = buildUsageFingerprint(entries);
202
+ if (usageTotalsCache?.key === key) return usageTotalsCache.totals;
203
+
204
+ const totals = computeUsageTotals(entries);
205
+ usageTotalsCache = { key, totals };
206
+ return totals;
207
+ }
208
+
209
+ export function buildTokenLabel(
210
+ totals: UsageTotals,
211
+ cacheHitIcon = "󰆼",
212
+ cache: TokensCacheFormat = "percent",
213
+ ): string {
214
+ const parts: string[] = [];
215
+ if (totals.input) parts.push(`↑${formatCount(totals.input)}`);
216
+ if (totals.output) parts.push(`↓${formatCount(totals.output)}`);
217
+
218
+ const hasCacheTokens = totals.cacheRead > 0 || totals.cacheWrite > 0;
219
+ if (hasCacheTokens && cache !== "off") {
220
+ // "percent" is starline's long-standing display; "tokens" shows the raw
221
+ // cache-read count instead, which is what the powerline footer showed.
222
+ const cacheText =
223
+ cache === "tokens"
224
+ ? formatCount(totals.cacheRead)
225
+ : totals.latestCacheHitRate !== undefined
226
+ ? `${totals.latestCacheHitRate.toFixed(1)}%`
227
+ : undefined;
228
+ if (cacheText !== undefined) {
229
+ parts.push(cacheHitIcon ? `${cacheHitIcon} ${cacheText}` : cacheText);
230
+ }
231
+ }
232
+ return parts.length > 0 ? parts.join(" ") : "↑0 ↓0";
233
+ }
234
+
235
+ /**
236
+ * Cache hit rate on its own, for the `cacheHit` segment. Empty when there was no
237
+ * cache activity or no rate for the latest turn, so the segment disappears
238
+ * rather than showing a meaningless zero.
239
+ */
240
+ export function buildCacheHitLabel(totals: UsageTotals, icon = ""): string {
241
+ const hasCacheTokens = totals.cacheRead > 0 || totals.cacheWrite > 0;
242
+ if (!hasCacheTokens || totals.latestCacheHitRate === undefined) return "";
243
+ const rate = `${totals.latestCacheHitRate.toFixed(1)}%`;
244
+ return icon ? `${icon} ${rate}` : rate;
245
+ }
246
+
247
+ export function buildCostLabel(totals: UsageTotals): string {
248
+ return `$${totals.cost.toFixed(3)}`;
249
+ }
250
+
251
+ export function buildSessionDurationLabel(startEpoch: number): string {
252
+ const totalSeconds = Math.max(0, Math.floor((Date.now() - startEpoch) / 1000));
253
+ const hours = Math.floor(totalSeconds / 3600);
254
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
255
+ const seconds = totalSeconds % 60;
256
+ if (hours > 0) return `${hours}h ${minutes}m`;
257
+ if (minutes > 0) return `${minutes}m ${seconds}s`;
258
+ return `${seconds}s`;
259
+ }
260
+
261
+ export function contextColorTier(
262
+ percent: number | null | undefined,
263
+ thresholds: ContextThresholds = { warning: 70, error: 90 },
264
+ ): ContextColorTier {
265
+ if (percent === null || percent === undefined || !Number.isFinite(percent)) return "normal";
266
+ if (percent >= thresholds.error) return "error";
267
+ if (percent >= thresholds.warning) return "warning";
268
+ return "normal";
269
+ }
270
+
271
+ export function buildContextGauge(percent: number, width = 10, ascii = false): string {
272
+ const clamped = Math.max(0, Math.min(100, percent));
273
+ const filled = Math.round((clamped / 100) * width);
274
+ const on = ascii ? "#" : "█";
275
+ const off = ascii ? "-" : "░";
276
+ return `${on.repeat(filled)}${off.repeat(Math.max(0, width - filled))}`;
277
+ }
278
+
279
+ export function formatContextPercentLabel(
280
+ percent: number | null | undefined,
281
+ contextWindow: number | undefined,
282
+ ): string {
283
+ if (!contextWindow || contextWindow <= 0) return "--";
284
+ const percentLabel =
285
+ percent === null || percent === undefined
286
+ ? "?"
287
+ : `${Math.max(0, Math.min(999, Math.round(percent)))}%`;
288
+ return `${percentLabel}/${formatCount(contextWindow)}`;
289
+ }
290
+
291
+ /** Just the rounded percentage, for `segmentOptions.context.format: "percent"`. */
292
+ export function formatBareContextPercent(percent: number | null | undefined): string {
293
+ if (percent === null || percent === undefined || !Number.isFinite(percent)) return "?";
294
+ return `${Math.max(0, Math.min(999, Math.round(percent)))}%`;
295
+ }
296
+
297
+ export function buildContextDisplayLabel(options: {
298
+ percent: number | null | undefined;
299
+ contextWindow: number | undefined;
300
+ style?: ContextStyle;
301
+ asciiGauge?: boolean;
302
+ format?: ContextFormat;
303
+ }): string {
304
+ const { percent, contextWindow, style = "text", asciiGauge = false, format = "full" } = options;
305
+ if (!contextWindow || contextWindow <= 0) return "--";
306
+
307
+ // "percent" drops the context window, leaving a bare threshold-coloured
308
+ // figure for minimal layouts. It composes with contextStyle unchanged.
309
+ const text =
310
+ format === "percent"
311
+ ? formatBareContextPercent(percent)
312
+ : formatContextPercentLabel(percent, contextWindow);
313
+ const numericPercent =
314
+ percent === null || percent === undefined || !Number.isFinite(percent)
315
+ ? 0
316
+ : Math.max(0, Math.min(100, percent));
317
+ const gauge = buildContextGauge(numericPercent, 10, asciiGauge);
318
+
319
+ if (style === "gauge") return `[${gauge}]`;
320
+ if (style === "text+gauge") return `[${gauge}] ${text}`;
321
+ return text;
322
+ }
323
+
324
+ export function buildContextLabel(ctx: ExtensionContext): string {
325
+ const usage = ctx.getContextUsage();
326
+ const contextWindow = ctx.model?.contextWindow ?? usage?.contextWindow;
327
+ return formatContextPercentLabel(usage?.percent, contextWindow);
328
+ }
329
+
330
+ export function formatRuntimeSegment(
331
+ theme: Pick<Theme, "fg">,
332
+ runtime: RuntimeInfo | undefined,
333
+ prefixStyle: ColorSpec,
334
+ colorSource: ColorSource,
335
+ mode: IconMode = "auto",
336
+ ): string {
337
+ if (!runtime) return "";
338
+ const symbol = resolveRuntimeSymbol(runtime.name, runtime.symbol, mode);
339
+ const label = runtime.version ? `${symbol} ${runtime.version}` : symbol;
340
+ return `${renderStyleForSource(theme, colorSource, prefixStyle, "via")} ${renderStyleForSource(theme, colorSource, runtime.style, label)}`;
341
+ }
342
+
343
+ /**
344
+ * Render the package-version segment in Starship `is <glyph> <version>` shape.
345
+ *
346
+ * Distinct from the runtime segment: this surfaces the project's own
347
+ * manifest version (e.g. `package.json#version`), not the installed
348
+ * toolchain version. Glyph comes from the Starship Nerd Font preset
349
+ * (https://starship.rs/presets/nerd-font); default color `208` matches
350
+ * the Starship `package` module default
351
+ * (https://starship.rs/config/#package-version).
352
+ */
353
+ export function formatPackageVersionSegment(
354
+ theme: Pick<Theme, "fg">,
355
+ pkg: PackageVersionResult | undefined,
356
+ colorSource: ColorSource,
357
+ mode: IconMode = "auto",
358
+ configuredIcon: string = "",
359
+ versionStyle: ColorSpec = "208",
360
+ ): string {
361
+ if (!pkg) return "";
362
+ const icon = resolvePackageIcon(configuredIcon, mode);
363
+ const label = `${icon} ${pkg.version}`;
364
+ return `${renderStyleForSource(theme, colorSource, "", "is")} ${renderStyleForSource(theme, colorSource, versionStyle, label)}`;
365
+ }
366
+
367
+ export type FormatCwdOptions = {
368
+ mode?: PathDisplayMode;
369
+ /** Trailing directory components to keep in full mode. 0 = unlimited. */
370
+ depth?: number;
371
+ home?: string;
372
+ };
373
+
374
+ function normalizeDisplayPath(cwd: string): string {
375
+ const withSlashes = cwd.replace(/\\/g, "/");
376
+ if (withSlashes === "/" || /^\/+$/.test(withSlashes)) return "/";
377
+ const stripped = withSlashes.replace(/\/+$/, "");
378
+ return stripped === "" ? withSlashes : stripped;
379
+ }
380
+
381
+ function toHomePath(path: string, home: string): string {
382
+ if (!home) return path;
383
+ const homeNorm = home.replace(/\\/g, "/").replace(/\/+$/, "");
384
+ if (!homeNorm) return path;
385
+ if (path === homeNorm) return "~";
386
+ if (path.startsWith(`${homeNorm}/`)) return `~${path.slice(homeNorm.length)}`;
387
+ return path;
388
+ }
389
+
390
+ /** Starship-style: keep last `depth` components; prefix with `…/` when parents were dropped. */
391
+ function applyPathDepth(path: string, depth: number): string {
392
+ if (!Number.isFinite(depth) || depth <= 0) return path;
393
+ const limit = Math.floor(depth);
394
+ if (path === "~" || path === "/") return path;
395
+
396
+ let components: string[];
397
+ if (path.startsWith("~/")) {
398
+ components = path.slice(2).split("/").filter(Boolean);
399
+ } else if (/^[A-Za-z]:\//.test(path)) {
400
+ components = path.slice(3).split("/").filter(Boolean);
401
+ } else if (path.startsWith("/")) {
402
+ components = path.slice(1).split("/").filter(Boolean);
403
+ } else {
404
+ components = path.split("/").filter(Boolean);
405
+ }
406
+
407
+ if (components.length <= limit) return path;
408
+ return `…/${components.slice(-limit).join("/")}`;
409
+ }
410
+
411
+ export function formatCwdLabel(cwd: string, cwdIcon: string, options?: FormatCwdOptions): string {
412
+ const mode = options?.mode ?? "basename";
413
+ const normalized = normalizeDisplayPath(cwd);
414
+ let pathText: string;
415
+ if (mode === "full") {
416
+ const home =
417
+ options?.home ??
418
+ (() => {
419
+ try {
420
+ return homedir();
421
+ } catch {
422
+ return "";
423
+ }
424
+ })();
425
+ pathText = applyPathDepth(toHomePath(normalized, home), options?.depth ?? 0);
426
+ } else if (normalized === "/") {
427
+ pathText = "/";
428
+ } else {
429
+ const parts = normalized.split("/").filter(Boolean);
430
+ pathText = parts[parts.length - 1] ?? cwd;
431
+ }
432
+ return cwdIcon ? `${cwdIcon} ${pathText}` : pathText;
433
+ }
434
+
435
+ function stripAnsi(text: string): string {
436
+ return text.replace(/\u001B\[[0-9;]*m/g, "");
437
+ }
438
+
439
+ export function formatGitBranchText(
440
+ branch: string,
441
+ maxLength: GitBranchMaxLength = "full",
442
+ ): string {
443
+ if (maxLength === "full" || visibleWidth(branch) <= maxLength) return branch;
444
+ return stripAnsi(truncateToWidth(branch, maxLength, "…"));
445
+ }
446
+
447
+ export function formatUsernameHostLabel(icon: string): string {
448
+ try {
449
+ const user = userInfo().username;
450
+ const host = hostname();
451
+ if (!user || !host) return "";
452
+ const label = `${user}@${host}`;
453
+ return icon ? `${icon} ${label}` : label;
454
+ } catch {
455
+ return "";
456
+ }
457
+ }
458
+
459
+ export function formatTimeLabel(icon: string): string {
460
+ const now = new Date();
461
+ const hours = String(now.getHours()).padStart(2, "0");
462
+ const minutes = String(now.getMinutes()).padStart(2, "0");
463
+ const label = `${hours}:${minutes}`;
464
+ return icon ? `${icon} ${label}` : label;
465
+ }
466
+
467
+ export function formatOsLabel(
468
+ configuredIcon: string,
469
+ mode: IconMode = "auto",
470
+ platform: string = process.platform,
471
+ ): string {
472
+ return resolveOsIcon(configuredIcon, mode, platform);
473
+ }