@aeondave/pi-theme-1337 0.5.1 → 0.6.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/format.ts CHANGED
@@ -1,464 +1,464 @@
1
- /** Small, pure formatters shared by the frame and its status row. */
2
-
3
- const INLINE_LIMIT = 512;
4
- const ART_LINE_LIMIT = 2048;
5
- const INLINE_SEGMENTER = new Intl.Segmenter(undefined, { granularity: "grapheme" });
6
-
7
- function isBidiControl(codePoint: number): boolean {
8
- return (
9
- codePoint === 0x061c ||
10
- codePoint === 0x200e ||
11
- codePoint === 0x200f ||
12
- (codePoint >= 0x202a && codePoint <= 0x202e) ||
13
- (codePoint >= 0x2066 && codePoint <= 0x2069)
14
- );
15
- }
16
-
17
- /**
18
- * The one list of code points that must never be written raw: C0, DEL, C1, and
19
- * bidi controls. Callers decide whether to drop, map or spell them; whitespace
20
- * among them (tab, CR, NEL) is each caller's policy and must be checked first.
21
- */
22
- export function isUnsafeCodePoint(codePoint: number): boolean {
23
- return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f) || isBidiControl(codePoint);
24
- }
25
-
26
- /** LS / PS: some hosts break the row on them, so the measured line is not the painted one. */
27
- export function isLineSeparator(codePoint: number): boolean {
28
- return codePoint === 0x2028 || codePoint === 0x2029;
29
- }
30
-
31
- /**
32
- * The code point at `index`, pairing surrogates by hand: a surrogate that is not
33
- * half of a well-formed pair comes back as itself. `String.prototype.codePointAt`
34
- * is not used on purpose — V8's Maglev tier (Node 26.3) has returned the full
35
- * astral code point for a sliced string ending on a high surrogate whose low
36
- * half lies just past the slice, which let an unpaired surrogate through.
37
- */
38
- export function codePointAtIndex(text: string, index: number): number {
39
- const high = text.charCodeAt(index);
40
- if (high >= 0xd800 && high <= 0xdbff && index + 1 < text.length) {
41
- const low = text.charCodeAt(index + 1);
42
- if (low >= 0xdc00 && low <= 0xdfff) return (high - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000;
43
- }
44
- return high;
45
- }
46
-
47
- /** A surrogate code unit returned by `codePointAtIndex` is unpaired: measured as 0 columns, painted as 1. */
48
- export function isLoneSurrogate(codePoint: number): boolean {
49
- return codePoint >= 0xd800 && codePoint <= 0xdfff;
50
- }
51
-
52
- /**
53
- * The terminal escape grammar, shared by every sanitizer: returns the index after
54
- * the control sequence that starts at `index`, or `index` itself when none does.
55
- * CSI (ESC [ / 0x9b) runs to its final byte; OSC/DCS/APC/PM/SOS (ESC ] P _ ^ X or
56
- * their C1 forms) run to BEL, ST or ESC \; anything unterminated owns the rest of
57
- * the text. Any other ESC drops the whole following code point, never half a
58
- * surrogate pair. Linear, allocation-free.
59
- */
60
- export function skipTerminalSequence(text: string, index: number): number {
61
- const code = text.charCodeAt(index);
62
- if (code === 0x1b) {
63
- const kind = text.charCodeAt(index + 1);
64
- if (kind === 0x5b) return skipCsi(text, index + 2);
65
- if (kind === 0x5d || kind === 0x50 || kind === 0x5f || kind === 0x5e || kind === 0x58) {
66
- return skipControlString(text, index + 2);
67
- }
68
- if (index + 1 >= text.length) return index + 1;
69
- // two-char escape; dropping both is safer than exposing its final
70
- return index + 1 + (codePointAtIndex(text, index + 1) > 0xffff ? 2 : 1);
71
- }
72
- if (code === 0x9b) return skipCsi(text, index + 1);
73
- if (code === 0x90 || code === 0x98 || code === 0x9d || code === 0x9e || code === 0x9f) {
74
- return skipControlString(text, index + 1);
75
- }
76
- return index;
77
- }
78
-
79
- function skipControlString(text: string, start: number): number {
80
- let i = start;
81
- while (i < text.length) {
82
- const code = text.charCodeAt(i);
83
- if (code === 0x07 || code === 0x9c) return i + 1; // BEL / C1 ST
84
- if (code === 0x1b && text.charCodeAt(i + 1) === 0x5c) return i + 2; // ESC \\
85
- i++;
86
- }
87
- return text.length; // an unterminated control string owns the remaining bytes
88
- }
89
-
90
- function skipCsi(text: string, start: number): number {
91
- let i = start;
92
- while (i < text.length) {
93
- const code = text.charCodeAt(i++);
94
- if (code >= 0x40 && code <= 0x7e) break; // final byte
95
- }
96
- return i;
97
- }
98
-
99
- /**
100
- * Make foreign text safe for one terminal row. This is a bounded, linear scan:
101
- * terminal control sequences (including unterminated OSC/APC/DCS), C0/C1
102
- * controls, and bidi overrides are removed; whitespace is folded to one space.
103
- * It deliberately preserves emoji selectors/joiners for `stableEmojiWidth` to
104
- * resolve at grapheme level afterwards.
105
- */
106
- function sanitizeTerminalText(value: string, limit: number, preserveSpaces: boolean): string {
107
- let output = "";
108
- let emitted = 0;
109
- let pendingSpace = false;
110
- let i = 0;
111
- while (i < value.length && emitted < limit) {
112
- const next = skipTerminalSequence(value, i);
113
- if (next !== i) {
114
- i = next;
115
- continue;
116
- }
117
- const codePoint = codePointAtIndex(value, i);
118
- const size = codePoint > 0xffff ? 2 : 1;
119
-
120
- // An unpaired surrogate measures zero columns yet is written to the terminal
121
- // as U+FFFD, one cell: make it that glyph here so the measured row is the painted one.
122
- const char = isLoneSurrogate(codePoint) ? "\ufffd" : value.slice(i, i + size);
123
- i += size;
124
- if (/\p{White_Space}/v.test(char)) {
125
- if (preserveSpaces) {
126
- // Keep intentional ASCII-art padding exactly; fold a CRLF, tab, or
127
- // other row-breaking whitespace run to one ordinary terminal cell.
128
- if (char === " " || !output.endsWith(" ")) {
129
- output += " ";
130
- emitted++;
131
- }
132
- } else {
133
- pendingSpace = output.length > 0;
134
- }
135
- continue;
136
- }
137
- if (isUnsafeCodePoint(codePoint)) continue;
138
- if (pendingSpace && emitted < limit) {
139
- output += " ";
140
- emitted++;
141
- pendingSpace = false;
142
- }
143
- if (emitted < limit) {
144
- output += char;
145
- emitted++;
146
- }
147
- }
148
- return preserveSpaces ? output : output.trim();
149
- }
150
-
151
- export function sanitizeInlineText(value: string): string {
152
- return sanitizeTerminalText(value, INLINE_LIMIT, false);
153
- }
154
-
155
- /** Preserve intentional ASCII-art padding while removing terminal controls. */
156
- export function sanitizeArtLine(value: string): string {
157
- return sanitizeTerminalText(value, ART_LINE_LIMIT, true);
158
- }
159
-
160
- /**
161
- * Shorten a path to `~/…/<last two segments>`, normalizing Windows slashes; the
162
- * ellipsis appears only when it stands for omitted segments.
163
- *
164
- * The home prefix is matched on normalized segments, not raw text: a `HOME` with
165
- * a trailing separator used to eat the one after `~` (`~Desktop/ctf`), and a
166
- * Windows shell that reports `C:\users\me\…` while `USERPROFILE` says
167
- * `C:\Users\me` missed the match entirely and showed the bare `…/desktop/ctf`.
168
- * Matching is case-insensitive on Windows only, where the filesystem is, and
169
- * requires a segment boundary so `/home/mario2` is not read as inside `/home/mario`.
170
- */
171
- export function shortCwd(cwd: string): string {
172
- const toUnix = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, "");
173
- const unixCwd = sanitizeInlineText(cwd).replace(/\\/g, "/");
174
- const home = toUnix(process.env.HOME || process.env.USERPROFILE || "");
175
- const fold = (p: string) => (process.platform === "win32" ? p.toLowerCase() : p);
176
- const body = toUnix(unixCwd);
177
- const inHome = home !== "" && (fold(body) === fold(home) || fold(body).startsWith(`${fold(home)}/`));
178
- const unix = inHome ? `~${body.slice(home.length)}` : unixCwd;
179
- // `~` is an anchor, not a segment: `~/src/project` omits nothing, and an
180
- // ellipsis there would only make the label longer.
181
- const segments = (inHome ? unix.slice(1) : unix).split("/").filter(Boolean);
182
- if (segments.length <= 2) return unix;
183
- const lead = unix.startsWith("~") ? "~/" : unix.startsWith("/") ? "/" : "";
184
- return `${lead}…/${segments.slice(-2).join("/")}`;
185
- }
186
-
187
- /** Trim the recognizable model id for a calmer label (`claude-opus-4-8` → `opus-4-8`). */
188
- export function cleanModel(id: string | undefined): string {
189
- if (!id) return "no model";
190
- return sanitizeInlineText(id).replace(/^claude-/, "");
191
- }
192
-
193
- /** Shape of Pi's `ctx.getContextUsage()` (kept local so this module stays pure). */
194
- export interface ContextUsageLike {
195
- tokens: number | null;
196
- contextWindow: number;
197
- percent: number | null;
198
- }
199
-
200
- /** Compact token count: 500 → "500", 12345 → "12.3k", 1_500_000 → "1.5M". */
201
- export function formatTokens(n: number): string {
202
- if (n < 1000) return `${n}`;
203
- if (n < 1_000_000) return `${(n / 1000).toFixed(1)}k`;
204
- return `${(n / 1_000_000).toFixed(1)}M`;
205
- }
206
-
207
- /**
208
- * Elapsed time the way people read it: "850ms", "4.2s", "42s", "1m 05s", "1h 02m".
209
- * Non-finite or negative input yields "".
210
- */
211
- export function formatDuration(ms: number): string {
212
- if (!Number.isFinite(ms) || ms < 0) return "";
213
- if (ms < 1000) return `${Math.round(ms)}ms`;
214
- if (ms < 9950) return `${(ms / 1000).toFixed(1)}s`;
215
- // A finished duration rounds to the nearest second; formatElapsed only floors.
216
- return formatElapsed(Math.round(ms / 1000) * 1000);
217
- }
218
-
219
- /**
220
- * A live counter in whole seconds: "7s", "42s", "1m 05s", "1h 02m". Floored, so
221
- * it never reads ahead of the clock. Non-finite or negative input yields "".
222
- */
223
- export function formatElapsed(ms: number): string {
224
- if (!Number.isFinite(ms) || ms < 0) return "";
225
- const seconds = Math.floor(ms / 1000);
226
- if (seconds < 60) return `${seconds}s`;
227
- const minutes = Math.floor(seconds / 60);
228
- if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
229
- return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
230
- }
231
-
232
- /** "1 file" / "3 files" — `many` defaults to `one` + "s". */
233
- export function plural(count: number, one: string, many = `${one}s`): string {
234
- return `${count} ${count === 1 ? one : many}`;
235
- }
236
-
237
- /** Foreign values (tool arguments, results) read as text: non-strings become "". */
238
- export function textOf(value: unknown): string {
239
- return typeof value === "string" ? value : "";
240
- }
241
-
242
- /** Foreign values read as a record: anything that is not a non-null object becomes `{}`. */
243
- export function recordOf(value: unknown): Record<string, unknown> {
244
- return value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
245
- }
246
-
247
- /**
248
- * The git-branch suffix for the status row's workspace segment: " · main", or
249
- * "" when there's no branch to show (outside a repo, or footer data not yet
250
- * captured). Pi reports detached HEAD as the literal branch "detached".
251
- */
252
- export function branchLabel(branch: string | null | undefined): string {
253
- const safe = branch ? sanitizeInlineText(branch) : "";
254
- return safe ? ` · ${safe}` : "";
255
- }
256
-
257
- /**
258
- * What submitting the buffer would do with a shell command: nothing ("none"),
259
- * run it and hand its output to the model ("context", a leading `!`), or run
260
- * it and keep the output out of the model's context ("excluded", a leading
261
- * `!!`).
262
- */
263
- export type BashInputMode = "none" | "context" | "excluded";
264
-
265
- /**
266
- * Pi's own bash-mode test, so the prompt sigil reacts as the host will: the
267
- * host ignores leading whitespace and looks at the first one or two characters
268
- * (`!!!x` runs `!x` excluded; a bare `!` is bash mode with nothing to run yet).
269
- */
270
- export function bashInputMode(text: string): BashInputMode {
271
- const input = text.trimStart();
272
- if (!input.startsWith("!")) return "none";
273
- return input.startsWith("!!") ? "excluded" : "context";
274
- }
275
-
276
- export type UsageLevel = "normal" | "warn" | "critical";
277
-
278
- /**
279
- * Escalation level for the context-usage label, matching Pi's footer
280
- * thresholds: warn above 70%, critical above 90% (auto-compact territory).
281
- */
282
- export function usageLevel(percent: number | null | undefined): UsageLevel {
283
- if (percent == null) return "normal";
284
- // Judge the number the row prints (a whole percent), so the color and the
285
- // digits never disagree: a warning-colored "70%" would read as a mistake.
286
- const shown = Math.round(percent);
287
- if (shown > 90) return "critical";
288
- if (shown > 70) return "warn";
289
- return "normal";
290
- }
291
-
292
- /** Structural slice of a session entry — enough to sum costs without Pi imports. */
293
- export interface SessionEntryLike {
294
- type: string;
295
- provider?: string;
296
- model?: string;
297
- message?: { role?: string; usage?: { cost?: { total?: unknown } } };
298
- usage?: { cost?: { total?: unknown } };
299
- }
300
-
301
- /**
302
- * Cumulative API-equivalent estimate from assistant/tool-result messages,
303
- * compaction, branch-summary, and Pi usage entries (the same usage sources Pi's
304
- * footer sums), plus pending persona usage. It is not an invoice: session history
305
- * does not establish actual billing across providers, subscriptions, or model
306
- * changes. Malformed, negative and non-finite values count as zero.
307
- */
308
- export function costTotal(entries: Iterable<SessionEntryLike>, extraCost = 0): number {
309
- let total = 0;
310
- for (const entry of entries) {
311
- const messageUsage =
312
- entry.type === "message" && (entry.message?.role === "assistant" || entry.message?.role === "toolResult")
313
- ? entry.message.usage
314
- : undefined;
315
- const summaryUsage =
316
- entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "usage" ? entry.usage : undefined;
317
- const value = (messageUsage ?? summaryUsage)?.cost?.total;
318
- if (typeof value === "number" && Number.isFinite(value) && value > 0) total += value;
319
- }
320
- if (typeof extraCost === "number" && Number.isFinite(extraCost) && extraCost > 0) total += extraCost;
321
- return Number.isFinite(total) && total > 0 ? total : 0;
322
- }
323
-
324
- /**
325
- * The estimate's label: "~$0.423" below a dollar, "~$48.89" from one. The
326
- * decimals follow the ROUNDED value, so 0.9996 reads "~$1.00", not "~$1.000";
327
- * a positive total too small to print reads "~<$0.001" rather than a false
328
- * zero. Zero, negative and non-finite totals show nothing. Always marked `~`:
329
- * these are list-price estimates, never an assertion of actual billing.
330
- */
331
- export function formatCost(total: number): string {
332
- if (!Number.isFinite(total) || total <= 0) return "";
333
- const mills = Math.round(total * 1000);
334
- if (mills === 0) return "~<$0.001";
335
- if (mills < 1000) return `~$${(mills / 1000).toFixed(3)}`;
336
- return `~$${(Math.round(total * 100) / 100).toFixed(2)}`;
337
- }
338
-
339
- /**
340
- * Spend since the current run began: "+$1.24", or "" until it prints at least
341
- * one cent (and for anything non-finite or negative).
342
- */
343
- export function formatRunDelta(delta: number): string {
344
- if (!Number.isFinite(delta)) return "";
345
- const cents = Math.round(delta * 100);
346
- return cents >= 1 ? `+$${(cents / 100).toFixed(2)}` : "";
347
- }
348
-
349
- /**
350
- * Compact context window for the usage denominator, three significant digits
351
- * with trailing zeros dropped: 128000 → "128k", 1000000 → "1M", 1048576 →
352
- * "1.05M". Unknown, zero, negative or non-finite windows yield "".
353
- */
354
- export function formatContextWindow(window: number | null | undefined): string {
355
- if (typeof window !== "number" || !Number.isFinite(window) || window <= 0) return "";
356
- if (window < 1000) return `${Math.round(window)}`;
357
- const k = Number((window / 1000).toPrecision(3));
358
- if (k < 1000) return `${k}k`;
359
- return `${Number((window / 1_000_000).toPrecision(3))}M`;
360
- }
361
-
362
- /**
363
- * Parse pi-persona's `persona-cost` status (leftover background-leg spend not yet
364
- * on a tool result). Accepts "~$0.923", "$0.923" or "0.923"; anything else is 0.
365
- */
366
- export function parsePersonaCost(text: string | undefined): number {
367
- if (!text) return 0;
368
- const match = text.trim().match(/^~?\$?(\d+(?:\.\d+)?)/);
369
- if (!match) return 0;
370
- const value = Number(match[1]);
371
- return Number.isFinite(value) && value > 0 ? value : 0;
372
- }
373
-
374
- /** pi-persona's background work, by kind, in the order its status publishes them. */
375
- export const BACKGROUND_KINDS = ["agents", "monitors", "timers", "scripts"] as const;
376
- export type BackgroundKind = (typeof BACKGROUND_KINDS)[number];
377
- /** How much is still running in the background, per kind; at least one count is positive. */
378
- export type BackgroundWork = Readonly<Record<BackgroundKind, number>>;
379
- /** No session runs more of one kind than this; a larger number is not a count we print. */
380
- export const MAX_BACKGROUND_COUNT = 9999;
381
- /** The longest well-formed status is 50 characters; nothing longer is scanned at all. */
382
- const BACKGROUND_STATUS_LIMIT = 64;
383
- const BACKGROUND_PAIR = /^(agents|monitors|timers|scripts)=([1-9]\d{0,3})$/;
384
- const BACKGROUND_NOUN: Record<BackgroundKind, string> = { agents: "agent", monitors: "monitor", timers: "timer", scripts: "script" };
385
-
386
- /**
387
- * Parse pi-persona's `persona-background` status: `kind=count` pairs separated
388
- * by one space, in the fixed order agents, monitors, timers, scripts, zero
389
- * counts omitted ("agents=3 monitors=1", "timers=1"). Strict on purpose: an
390
- * unknown or repeated key, a pair out of order, a zero, a sign, a leading zero,
391
- * a count past MAX_BACKGROUND_COUNT or any stray character means no background
392
- * work at all, so nothing that did not parse can reach the UI. Only the numbers
393
- * leave this function; the text itself is never displayed.
394
- */
395
- export function parseBackgroundStatus(text: unknown): BackgroundWork | undefined {
396
- if (typeof text !== "string" || text.length === 0 || text.length > BACKGROUND_STATUS_LIMIT) return undefined;
397
- const work = { agents: 0, monitors: 0, timers: 0, scripts: 0 };
398
- let next = 0;
399
- for (const pair of text.split(" ")) {
400
- const match = BACKGROUND_PAIR.exec(pair);
401
- if (!match) return undefined;
402
- const kind = match[1] as BackgroundKind;
403
- const index = BACKGROUND_KINDS.indexOf(kind);
404
- if (index < next) return undefined; // repeated, or out of the published order
405
- next = index + 1;
406
- work[kind] = Number(match[2]);
407
- }
408
- return work;
409
- }
410
-
411
- /**
412
- * The same counts read back from stored JSON (the run summary's snapshot): all
413
- * four kinds as whole numbers within the bound, at least one positive. Anything
414
- * else is undefined, so a damaged entry renders as if it carried none.
415
- */
416
- export function backgroundWorkOf(value: unknown): BackgroundWork | undefined {
417
- if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
418
- const record = value as Record<string, unknown>;
419
- const work = { agents: 0, monitors: 0, timers: 0, scripts: 0 };
420
- let total = 0;
421
- for (const kind of BACKGROUND_KINDS) {
422
- const count = Object.hasOwn(record, kind) ? record[kind] : undefined;
423
- if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > MAX_BACKGROUND_COUNT) return undefined;
424
- work[kind] = count;
425
- total += count;
426
- }
427
- return total > 0 ? work : undefined;
428
- }
429
-
430
- /** Every kind that is running, in order: "3 agents, 1 monitor, 1 timer, 1 script". */
431
- export function backgroundDetail(work: BackgroundWork): string {
432
- return BACKGROUND_KINDS.filter(kind => work[kind] > 0).map(kind => plural(work[kind], BACKGROUND_NOUN[kind])).join(", ");
433
- }
434
-
435
- /** One kind is named ("3 agents", "1 timer"); several are counted together ("5 background tasks"). */
436
- export function backgroundSummary(work: BackgroundWork): string {
437
- const running = BACKGROUND_KINDS.filter(kind => work[kind] > 0);
438
- if (running.length === 1) return plural(work[running[0]!], BACKGROUND_NOUN[running[0]!]);
439
- return plural(running.reduce((sum, kind) => sum + work[kind], 0), "background task");
440
- }
441
-
442
- /**
443
- * Neutralize width-ambiguous VS16 emoji in a status label so a fixed-width box's
444
- * right rail always lands on the corner. A grapheme of the form
445
- * <text-default symbol> + U+FE0F (⚖️, 🗺️, …) requests emoji presentation of a
446
- * symbol whose default is text; terminals disagree on its column count (1, 2, or 2
447
- * plus a tofu cell), so our width model — which mirrors pi-tui at 2 — and the glyph
448
- * the terminal actually paints drift apart, and the persona segment then pushes or
449
- * pulls the right rail off the border. Dropping the lone VS16 forces deterministic
450
- * text presentation: width 1 in our model AND in every terminal, so the two agree
451
- * regardless of how the terminal would have sized the emoji form. Emoji that need
452
- * no selector (🎯, Emoji_Presentation=Yes), keycaps, and complete grapheme clusters
453
- * containing a ZWJ (flags/professions, even when VS16 is not adjacent) stay intact.
454
- */
455
- export function stableEmojiWidth(label: string): string {
456
- const safe = sanitizeInlineText(label);
457
- let output = "";
458
- for (const { segment } of INLINE_SEGMENTER.segment(safe)) {
459
- // Keep selectors that belong to a joined emoji or a keycap. For a lone
460
- // text-default symbol, remove VS16 to force deterministic one-cell text.
461
- output += segment.includes("\u200d") || segment.includes("\u20e3") ? segment : segment.replaceAll("\uFE0F", "");
462
- }
463
- return output;
464
- }
1
+ /** Small, pure formatters shared by the frame and its status row. */
2
+
3
+ const INLINE_LIMIT = 512;
4
+ const ART_LINE_LIMIT = 2048;
5
+ const INLINE_SEGMENTER = new Intl.Segmenter(undefined, { granularity: "grapheme" });
6
+
7
+ function isBidiControl(codePoint: number): boolean {
8
+ return (
9
+ codePoint === 0x061c ||
10
+ codePoint === 0x200e ||
11
+ codePoint === 0x200f ||
12
+ (codePoint >= 0x202a && codePoint <= 0x202e) ||
13
+ (codePoint >= 0x2066 && codePoint <= 0x2069)
14
+ );
15
+ }
16
+
17
+ /**
18
+ * The one list of code points that must never be written raw: C0, DEL, C1, and
19
+ * bidi controls. Callers decide whether to drop, map or spell them; whitespace
20
+ * among them (tab, CR, NEL) is each caller's policy and must be checked first.
21
+ */
22
+ export function isUnsafeCodePoint(codePoint: number): boolean {
23
+ return codePoint < 0x20 || (codePoint >= 0x7f && codePoint <= 0x9f) || isBidiControl(codePoint);
24
+ }
25
+
26
+ /** LS / PS: some hosts break the row on them, so the measured line is not the painted one. */
27
+ export function isLineSeparator(codePoint: number): boolean {
28
+ return codePoint === 0x2028 || codePoint === 0x2029;
29
+ }
30
+
31
+ /**
32
+ * The code point at `index`, pairing surrogates by hand: a surrogate that is not
33
+ * half of a well-formed pair comes back as itself. `String.prototype.codePointAt`
34
+ * is not used on purpose — V8's Maglev tier (Node 26.3) has returned the full
35
+ * astral code point for a sliced string ending on a high surrogate whose low
36
+ * half lies just past the slice, which let an unpaired surrogate through.
37
+ */
38
+ export function codePointAtIndex(text: string, index: number): number {
39
+ const high = text.charCodeAt(index);
40
+ if (high >= 0xd800 && high <= 0xdbff && index + 1 < text.length) {
41
+ const low = text.charCodeAt(index + 1);
42
+ if (low >= 0xdc00 && low <= 0xdfff) return (high - 0xd800) * 0x400 + (low - 0xdc00) + 0x10000;
43
+ }
44
+ return high;
45
+ }
46
+
47
+ /** A surrogate code unit returned by `codePointAtIndex` is unpaired: measured as 0 columns, painted as 1. */
48
+ export function isLoneSurrogate(codePoint: number): boolean {
49
+ return codePoint >= 0xd800 && codePoint <= 0xdfff;
50
+ }
51
+
52
+ /**
53
+ * The terminal escape grammar, shared by every sanitizer: returns the index after
54
+ * the control sequence that starts at `index`, or `index` itself when none does.
55
+ * CSI (ESC [ / 0x9b) runs to its final byte; OSC/DCS/APC/PM/SOS (ESC ] P _ ^ X or
56
+ * their C1 forms) run to BEL, ST or ESC \; anything unterminated owns the rest of
57
+ * the text. Any other ESC drops the whole following code point, never half a
58
+ * surrogate pair. Linear, allocation-free.
59
+ */
60
+ export function skipTerminalSequence(text: string, index: number): number {
61
+ const code = text.charCodeAt(index);
62
+ if (code === 0x1b) {
63
+ const kind = text.charCodeAt(index + 1);
64
+ if (kind === 0x5b) return skipCsi(text, index + 2);
65
+ if (kind === 0x5d || kind === 0x50 || kind === 0x5f || kind === 0x5e || kind === 0x58) {
66
+ return skipControlString(text, index + 2);
67
+ }
68
+ if (index + 1 >= text.length) return index + 1;
69
+ // two-char escape; dropping both is safer than exposing its final
70
+ return index + 1 + (codePointAtIndex(text, index + 1) > 0xffff ? 2 : 1);
71
+ }
72
+ if (code === 0x9b) return skipCsi(text, index + 1);
73
+ if (code === 0x90 || code === 0x98 || code === 0x9d || code === 0x9e || code === 0x9f) {
74
+ return skipControlString(text, index + 1);
75
+ }
76
+ return index;
77
+ }
78
+
79
+ function skipControlString(text: string, start: number): number {
80
+ let i = start;
81
+ while (i < text.length) {
82
+ const code = text.charCodeAt(i);
83
+ if (code === 0x07 || code === 0x9c) return i + 1; // BEL / C1 ST
84
+ if (code === 0x1b && text.charCodeAt(i + 1) === 0x5c) return i + 2; // ESC \\
85
+ i++;
86
+ }
87
+ return text.length; // an unterminated control string owns the remaining bytes
88
+ }
89
+
90
+ function skipCsi(text: string, start: number): number {
91
+ let i = start;
92
+ while (i < text.length) {
93
+ const code = text.charCodeAt(i++);
94
+ if (code >= 0x40 && code <= 0x7e) break; // final byte
95
+ }
96
+ return i;
97
+ }
98
+
99
+ /**
100
+ * Make foreign text safe for one terminal row. This is a bounded, linear scan:
101
+ * terminal control sequences (including unterminated OSC/APC/DCS), C0/C1
102
+ * controls, and bidi overrides are removed; whitespace is folded to one space.
103
+ * It deliberately preserves emoji selectors/joiners for `stableEmojiWidth` to
104
+ * resolve at grapheme level afterwards.
105
+ */
106
+ function sanitizeTerminalText(value: string, limit: number, preserveSpaces: boolean): string {
107
+ let output = "";
108
+ let emitted = 0;
109
+ let pendingSpace = false;
110
+ let i = 0;
111
+ while (i < value.length && emitted < limit) {
112
+ const next = skipTerminalSequence(value, i);
113
+ if (next !== i) {
114
+ i = next;
115
+ continue;
116
+ }
117
+ const codePoint = codePointAtIndex(value, i);
118
+ const size = codePoint > 0xffff ? 2 : 1;
119
+
120
+ // An unpaired surrogate measures zero columns yet is written to the terminal
121
+ // as U+FFFD, one cell: make it that glyph here so the measured row is the painted one.
122
+ const char = isLoneSurrogate(codePoint) ? "\ufffd" : value.slice(i, i + size);
123
+ i += size;
124
+ if (/\p{White_Space}/v.test(char)) {
125
+ if (preserveSpaces) {
126
+ // Keep intentional ASCII-art padding exactly; fold a CRLF, tab, or
127
+ // other row-breaking whitespace run to one ordinary terminal cell.
128
+ if (char === " " || !output.endsWith(" ")) {
129
+ output += " ";
130
+ emitted++;
131
+ }
132
+ } else {
133
+ pendingSpace = output.length > 0;
134
+ }
135
+ continue;
136
+ }
137
+ if (isUnsafeCodePoint(codePoint)) continue;
138
+ if (pendingSpace && emitted < limit) {
139
+ output += " ";
140
+ emitted++;
141
+ pendingSpace = false;
142
+ }
143
+ if (emitted < limit) {
144
+ output += char;
145
+ emitted++;
146
+ }
147
+ }
148
+ return preserveSpaces ? output : output.trim();
149
+ }
150
+
151
+ export function sanitizeInlineText(value: string): string {
152
+ return sanitizeTerminalText(value, INLINE_LIMIT, false);
153
+ }
154
+
155
+ /** Preserve intentional ASCII-art padding while removing terminal controls. */
156
+ export function sanitizeArtLine(value: string): string {
157
+ return sanitizeTerminalText(value, ART_LINE_LIMIT, true);
158
+ }
159
+
160
+ /**
161
+ * Shorten a path to `~/…/<last two segments>`, normalizing Windows slashes; the
162
+ * ellipsis appears only when it stands for omitted segments.
163
+ *
164
+ * The home prefix is matched on normalized segments, not raw text: a `HOME` with
165
+ * a trailing separator used to eat the one after `~` (`~Desktop/ctf`), and a
166
+ * Windows shell that reports `C:\users\me\…` while `USERPROFILE` says
167
+ * `C:\Users\me` missed the match entirely and showed the bare `…/desktop/ctf`.
168
+ * Matching is case-insensitive on Windows only, where the filesystem is, and
169
+ * requires a segment boundary so `/home/mario2` is not read as inside `/home/mario`.
170
+ */
171
+ export function shortCwd(cwd: string): string {
172
+ const toUnix = (p: string) => p.replace(/\\/g, "/").replace(/\/+$/, "");
173
+ const unixCwd = sanitizeInlineText(cwd).replace(/\\/g, "/");
174
+ const home = toUnix(process.env.HOME || process.env.USERPROFILE || "");
175
+ const fold = (p: string) => (process.platform === "win32" ? p.toLowerCase() : p);
176
+ const body = toUnix(unixCwd);
177
+ const inHome = home !== "" && (fold(body) === fold(home) || fold(body).startsWith(`${fold(home)}/`));
178
+ const unix = inHome ? `~${body.slice(home.length)}` : unixCwd;
179
+ // `~` is an anchor, not a segment: `~/src/project` omits nothing, and an
180
+ // ellipsis there would only make the label longer.
181
+ const segments = (inHome ? unix.slice(1) : unix).split("/").filter(Boolean);
182
+ if (segments.length <= 2) return unix;
183
+ const lead = unix.startsWith("~") ? "~/" : unix.startsWith("/") ? "/" : "";
184
+ return `${lead}…/${segments.slice(-2).join("/")}`;
185
+ }
186
+
187
+ /** Trim the recognizable model id for a calmer label (`claude-opus-4-8` → `opus-4-8`). */
188
+ export function cleanModel(id: string | undefined): string {
189
+ if (!id) return "no model";
190
+ return sanitizeInlineText(id).replace(/^claude-/, "");
191
+ }
192
+
193
+ /** Shape of Pi's `ctx.getContextUsage()` (kept local so this module stays pure). */
194
+ export interface ContextUsageLike {
195
+ tokens: number | null;
196
+ contextWindow: number;
197
+ percent: number | null;
198
+ }
199
+
200
+ /** Compact token count: 500 → "500", 12345 → "12.3k", 1_500_000 → "1.5M". */
201
+ export function formatTokens(n: number): string {
202
+ if (n < 1000) return `${n}`;
203
+ if (n < 1_000_000) return `${(n / 1000).toFixed(1)}k`;
204
+ return `${(n / 1_000_000).toFixed(1)}M`;
205
+ }
206
+
207
+ /**
208
+ * Elapsed time the way people read it: "850ms", "4.2s", "42s", "1m 05s", "1h 02m".
209
+ * Non-finite or negative input yields "".
210
+ */
211
+ export function formatDuration(ms: number): string {
212
+ if (!Number.isFinite(ms) || ms < 0) return "";
213
+ if (ms < 1000) return `${Math.round(ms)}ms`;
214
+ if (ms < 9950) return `${(ms / 1000).toFixed(1)}s`;
215
+ // A finished duration rounds to the nearest second; formatElapsed only floors.
216
+ return formatElapsed(Math.round(ms / 1000) * 1000);
217
+ }
218
+
219
+ /**
220
+ * A live counter in whole seconds: "7s", "42s", "1m 05s", "1h 02m". Floored, so
221
+ * it never reads ahead of the clock. Non-finite or negative input yields "".
222
+ */
223
+ export function formatElapsed(ms: number): string {
224
+ if (!Number.isFinite(ms) || ms < 0) return "";
225
+ const seconds = Math.floor(ms / 1000);
226
+ if (seconds < 60) return `${seconds}s`;
227
+ const minutes = Math.floor(seconds / 60);
228
+ if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
229
+ return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`;
230
+ }
231
+
232
+ /** "1 file" / "3 files" — `many` defaults to `one` + "s". */
233
+ export function plural(count: number, one: string, many = `${one}s`): string {
234
+ return `${count} ${count === 1 ? one : many}`;
235
+ }
236
+
237
+ /** Foreign values (tool arguments, results) read as text: non-strings become "". */
238
+ export function textOf(value: unknown): string {
239
+ return typeof value === "string" ? value : "";
240
+ }
241
+
242
+ /** Foreign values read as a record: anything that is not a non-null object becomes `{}`. */
243
+ export function recordOf(value: unknown): Record<string, unknown> {
244
+ return value !== null && typeof value === "object" ? value as Record<string, unknown> : {};
245
+ }
246
+
247
+ /**
248
+ * The git-branch suffix for the status row's workspace segment: " · main", or
249
+ * "" when there's no branch to show (outside a repo, or footer data not yet
250
+ * captured). Pi reports detached HEAD as the literal branch "detached".
251
+ */
252
+ export function branchLabel(branch: string | null | undefined): string {
253
+ const safe = branch ? sanitizeInlineText(branch) : "";
254
+ return safe ? ` · ${safe}` : "";
255
+ }
256
+
257
+ /**
258
+ * What submitting the buffer would do with a shell command: nothing ("none"),
259
+ * run it and hand its output to the model ("context", a leading `!`), or run
260
+ * it and keep the output out of the model's context ("excluded", a leading
261
+ * `!!`).
262
+ */
263
+ export type BashInputMode = "none" | "context" | "excluded";
264
+
265
+ /**
266
+ * Pi's own bash-mode test, so the prompt sigil reacts as the host will: the
267
+ * host ignores leading whitespace and looks at the first one or two characters
268
+ * (`!!!x` runs `!x` excluded; a bare `!` is bash mode with nothing to run yet).
269
+ */
270
+ export function bashInputMode(text: string): BashInputMode {
271
+ const input = text.trimStart();
272
+ if (!input.startsWith("!")) return "none";
273
+ return input.startsWith("!!") ? "excluded" : "context";
274
+ }
275
+
276
+ export type UsageLevel = "normal" | "warn" | "critical";
277
+
278
+ /**
279
+ * Escalation level for the context-usage label, matching Pi's footer
280
+ * thresholds: warn above 70%, critical above 90% (auto-compact territory).
281
+ */
282
+ export function usageLevel(percent: number | null | undefined): UsageLevel {
283
+ if (percent == null) return "normal";
284
+ // Judge the number the row prints (a whole percent), so the color and the
285
+ // digits never disagree: a warning-colored "70%" would read as a mistake.
286
+ const shown = Math.round(percent);
287
+ if (shown > 90) return "critical";
288
+ if (shown > 70) return "warn";
289
+ return "normal";
290
+ }
291
+
292
+ /** Structural slice of a session entry — enough to sum costs without Pi imports. */
293
+ export interface SessionEntryLike {
294
+ type: string;
295
+ provider?: string;
296
+ model?: string;
297
+ message?: { role?: string; usage?: { cost?: { total?: unknown } } };
298
+ usage?: { cost?: { total?: unknown } };
299
+ }
300
+
301
+ /**
302
+ * Cumulative API-equivalent estimate from assistant/tool-result messages,
303
+ * compaction, branch-summary, and Pi usage entries (the same usage sources Pi's
304
+ * footer sums), plus pending persona usage. It is not an invoice: session history
305
+ * does not establish actual billing across providers, subscriptions, or model
306
+ * changes. Malformed, negative and non-finite values count as zero.
307
+ */
308
+ export function costTotal(entries: Iterable<SessionEntryLike>, extraCost = 0): number {
309
+ let total = 0;
310
+ for (const entry of entries) {
311
+ const messageUsage =
312
+ entry.type === "message" && (entry.message?.role === "assistant" || entry.message?.role === "toolResult")
313
+ ? entry.message.usage
314
+ : undefined;
315
+ const summaryUsage =
316
+ entry.type === "compaction" || entry.type === "branch_summary" || entry.type === "usage" ? entry.usage : undefined;
317
+ const value = (messageUsage ?? summaryUsage)?.cost?.total;
318
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) total += value;
319
+ }
320
+ if (typeof extraCost === "number" && Number.isFinite(extraCost) && extraCost > 0) total += extraCost;
321
+ return Number.isFinite(total) && total > 0 ? total : 0;
322
+ }
323
+
324
+ /**
325
+ * The estimate's label: "~$0.423" below a dollar, "~$48.89" from one. The
326
+ * decimals follow the ROUNDED value, so 0.9996 reads "~$1.00", not "~$1.000";
327
+ * a positive total too small to print reads "~<$0.001" rather than a false
328
+ * zero. Zero, negative and non-finite totals show nothing. Always marked `~`:
329
+ * these are list-price estimates, never an assertion of actual billing.
330
+ */
331
+ export function formatCost(total: number): string {
332
+ if (!Number.isFinite(total) || total <= 0) return "";
333
+ const mills = Math.round(total * 1000);
334
+ if (mills === 0) return "~<$0.001";
335
+ if (mills < 1000) return `~$${(mills / 1000).toFixed(3)}`;
336
+ return `~$${(Math.round(total * 100) / 100).toFixed(2)}`;
337
+ }
338
+
339
+ /**
340
+ * Spend since the current run began: "+$1.24", or "" until it prints at least
341
+ * one cent (and for anything non-finite or negative).
342
+ */
343
+ export function formatRunDelta(delta: number): string {
344
+ if (!Number.isFinite(delta)) return "";
345
+ const cents = Math.round(delta * 100);
346
+ return cents >= 1 ? `+$${(cents / 100).toFixed(2)}` : "";
347
+ }
348
+
349
+ /**
350
+ * Compact context window for the usage denominator, three significant digits
351
+ * with trailing zeros dropped: 128000 → "128k", 1000000 → "1M", 1048576 →
352
+ * "1.05M". Unknown, zero, negative or non-finite windows yield "".
353
+ */
354
+ export function formatContextWindow(window: number | null | undefined): string {
355
+ if (typeof window !== "number" || !Number.isFinite(window) || window <= 0) return "";
356
+ if (window < 1000) return `${Math.round(window)}`;
357
+ const k = Number((window / 1000).toPrecision(3));
358
+ if (k < 1000) return `${k}k`;
359
+ return `${Number((window / 1_000_000).toPrecision(3))}M`;
360
+ }
361
+
362
+ /**
363
+ * Parse pi-persona's `persona-cost` status (leftover background-leg spend not yet
364
+ * on a tool result). Accepts "~$0.923", "$0.923" or "0.923"; anything else is 0.
365
+ */
366
+ export function parsePersonaCost(text: string | undefined): number {
367
+ if (!text) return 0;
368
+ const match = text.trim().match(/^~?\$?(\d+(?:\.\d+)?)/);
369
+ if (!match) return 0;
370
+ const value = Number(match[1]);
371
+ return Number.isFinite(value) && value > 0 ? value : 0;
372
+ }
373
+
374
+ /** pi-persona's background work, by kind, in the order its status publishes them. */
375
+ export const BACKGROUND_KINDS = ["agents", "monitors", "timers", "scripts"] as const;
376
+ export type BackgroundKind = (typeof BACKGROUND_KINDS)[number];
377
+ /** How much is still running in the background, per kind; at least one count is positive. */
378
+ export type BackgroundWork = Readonly<Record<BackgroundKind, number>>;
379
+ /** No session runs more of one kind than this; a larger number is not a count we print. */
380
+ export const MAX_BACKGROUND_COUNT = 9999;
381
+ /** The longest well-formed status is 50 characters; nothing longer is scanned at all. */
382
+ const BACKGROUND_STATUS_LIMIT = 64;
383
+ const BACKGROUND_PAIR = /^(agents|monitors|timers|scripts)=([1-9]\d{0,3})$/;
384
+ const BACKGROUND_NOUN: Record<BackgroundKind, string> = { agents: "agent", monitors: "monitor", timers: "timer", scripts: "script" };
385
+
386
+ /**
387
+ * Parse pi-persona's `persona-background` status: `kind=count` pairs separated
388
+ * by one space, in the fixed order agents, monitors, timers, scripts, zero
389
+ * counts omitted ("agents=3 monitors=1", "timers=1"). Strict on purpose: an
390
+ * unknown or repeated key, a pair out of order, a zero, a sign, a leading zero,
391
+ * a count past MAX_BACKGROUND_COUNT or any stray character means no background
392
+ * work at all, so nothing that did not parse can reach the UI. Only the numbers
393
+ * leave this function; the text itself is never displayed.
394
+ */
395
+ export function parseBackgroundStatus(text: unknown): BackgroundWork | undefined {
396
+ if (typeof text !== "string" || text.length === 0 || text.length > BACKGROUND_STATUS_LIMIT) return undefined;
397
+ const work = { agents: 0, monitors: 0, timers: 0, scripts: 0 };
398
+ let next = 0;
399
+ for (const pair of text.split(" ")) {
400
+ const match = BACKGROUND_PAIR.exec(pair);
401
+ if (!match) return undefined;
402
+ const kind = match[1] as BackgroundKind;
403
+ const index = BACKGROUND_KINDS.indexOf(kind);
404
+ if (index < next) return undefined; // repeated, or out of the published order
405
+ next = index + 1;
406
+ work[kind] = Number(match[2]);
407
+ }
408
+ return work;
409
+ }
410
+
411
+ /**
412
+ * The same counts read back from stored JSON (the run summary's snapshot): all
413
+ * four kinds as whole numbers within the bound, at least one positive. Anything
414
+ * else is undefined, so a damaged entry renders as if it carried none.
415
+ */
416
+ export function backgroundWorkOf(value: unknown): BackgroundWork | undefined {
417
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
418
+ const record = value as Record<string, unknown>;
419
+ const work = { agents: 0, monitors: 0, timers: 0, scripts: 0 };
420
+ let total = 0;
421
+ for (const kind of BACKGROUND_KINDS) {
422
+ const count = Object.hasOwn(record, kind) ? record[kind] : undefined;
423
+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0 || count > MAX_BACKGROUND_COUNT) return undefined;
424
+ work[kind] = count;
425
+ total += count;
426
+ }
427
+ return total > 0 ? work : undefined;
428
+ }
429
+
430
+ /** Every kind that is running, in order: "3 agents, 1 monitor, 1 timer, 1 script". */
431
+ export function backgroundDetail(work: BackgroundWork): string {
432
+ return BACKGROUND_KINDS.filter(kind => work[kind] > 0).map(kind => plural(work[kind], BACKGROUND_NOUN[kind])).join(", ");
433
+ }
434
+
435
+ /** One kind is named ("3 agents", "1 timer"); several are counted together ("5 background tasks"). */
436
+ export function backgroundSummary(work: BackgroundWork): string {
437
+ const running = BACKGROUND_KINDS.filter(kind => work[kind] > 0);
438
+ if (running.length === 1) return plural(work[running[0]!], BACKGROUND_NOUN[running[0]!]);
439
+ return plural(running.reduce((sum, kind) => sum + work[kind], 0), "background task");
440
+ }
441
+
442
+ /**
443
+ * Neutralize width-ambiguous VS16 emoji in a status label so a fixed-width box's
444
+ * right rail always lands on the corner. A grapheme of the form
445
+ * <text-default symbol> + U+FE0F (⚖️, 🗺️, …) requests emoji presentation of a
446
+ * symbol whose default is text; terminals disagree on its column count (1, 2, or 2
447
+ * plus a tofu cell), so our width model — which mirrors pi-tui at 2 — and the glyph
448
+ * the terminal actually paints drift apart, and the persona segment then pushes or
449
+ * pulls the right rail off the border. Dropping the lone VS16 forces deterministic
450
+ * text presentation: width 1 in our model AND in every terminal, so the two agree
451
+ * regardless of how the terminal would have sized the emoji form. Emoji that need
452
+ * no selector (🎯, Emoji_Presentation=Yes), keycaps, and complete grapheme clusters
453
+ * containing a ZWJ (flags/professions, even when VS16 is not adjacent) stay intact.
454
+ */
455
+ export function stableEmojiWidth(label: string): string {
456
+ const safe = sanitizeInlineText(label);
457
+ let output = "";
458
+ for (const { segment } of INLINE_SEGMENTER.segment(safe)) {
459
+ // Keep selectors that belong to a joined emoji or a keycap. For a lone
460
+ // text-default symbol, remove VS16 to force deterministic one-cell text.
461
+ output += segment.includes("\u200d") || segment.includes("\u20e3") ? segment : segment.replaceAll("\uFE0F", "");
462
+ }
463
+ return output;
464
+ }