pi-path-bar 0.4.1 → 0.5.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.
@@ -0,0 +1,712 @@
1
+ import { stripTerminalSequences, truncateToWidth } from "@earendil-works/pi-tui";
2
+
3
+ /** Footer segment ids: a plugin shows up by calling setStatus("path-bar:<id>", text). */
4
+ export const SEGMENT_KEY = /^path-bar:([a-z0-9][a-z0-9._-]{0,31})$/;
5
+ export const SEGMENT_ID = /^[a-z0-9][a-z0-9._-]{0,31}$/;
6
+ export const CLOCK = "clock";
7
+
8
+ /** Keep every segment on one line; control separators would break the footer layout. */
9
+ export const segmentText = (text: string) => text.replace(/[\r\n\t]/g, " ");
10
+
11
+ export type SlotSource = "segment" | "adapted";
12
+ export interface SlotEntry { id: string; text: string; source: SlotSource }
13
+ export interface ExtensionAdapter {
14
+ readonly key: string;
15
+ readonly id: string;
16
+ format(text: string): string | undefined;
17
+ }
18
+ export interface ClassifiedStatuses {
19
+ /** Type 1 (adapted) and Type 2 (path-bar:*) slots before hidden filtering. */
20
+ slots: Map<string, SlotEntry>;
21
+ /** Type 3 (unknown extensions), sorted alphabetically by status key. */
22
+ unknown: Array<[string, string]>;
23
+ }
24
+
25
+ const LEADING_RESET_OR_WS = /^(?:\s|\x1b\[(?:0|22|39|22;39|39;22)?m)+/;
26
+ const LEADING_SGR = /^((?:\x1b\[[0-9;]*m)+)/;
27
+ const ANSI_TOKEN = /\x1b\[[0-9;]*m/g;
28
+ const RESET_SGR = /^\x1b\[(?:0|22|39|22;39|39;22)?m$/;
29
+
30
+ function extractColorPrefix(segment: string): string | undefined {
31
+ const match = LEADING_SGR.exec(segment.replace(LEADING_RESET_OR_WS, ""));
32
+ if (!match) return undefined;
33
+ // Track active SGR codes sequentially so reset codes (`\x1b[0m`, `\x1b[39m`, `\x1b[22;39m`, etc.) clear prior styles.
34
+ const codes = match[1].match(ANSI_TOKEN) ?? [];
35
+ const active: string[] = [];
36
+ for (const code of codes) {
37
+ if (RESET_SGR.test(code)) active.length = 0;
38
+ else active.push(code);
39
+ }
40
+ return active.length ? active.join("") : undefined;
41
+ }
42
+
43
+ function wrapColor(color: string | undefined, compact: string): string {
44
+ return color ? `${color}${compact}\x1b[0m` : compact;
45
+ }
46
+
47
+ function preserveColor(original: string, compact: string): string {
48
+ return wrapColor(extractColorPrefix(original), compact);
49
+ }
50
+
51
+ interface UrgentItem {
52
+ index: number;
53
+ limited: boolean;
54
+ remainingScore: number;
55
+ rendered: string;
56
+ }
57
+
58
+ function selectUrgent<T extends UrgentItem>(items: readonly T[], limit = 2): T[] {
59
+ if (items.length <= limit) return [...items];
60
+ return [...items]
61
+ .sort((a, b) => Number(b.limited) - Number(a.limited) || a.remainingScore - b.remainingScore || a.index - b.index)
62
+ .slice(0, limit)
63
+ .sort((a, b) => a.index - b.index);
64
+ }
65
+
66
+ const PI_USAGE_SHORT_LABELS: Record<string, string> = {
67
+ "7d-son": "7s",
68
+ "7d-opus": "7o",
69
+ "daily": "1d",
70
+ "weekly": "7d",
71
+ "week": "7d",
72
+ "wk": "7d",
73
+ "monthly": "mo",
74
+ "month": "mo",
75
+ "premium": "pm",
76
+ "chat": "ch",
77
+ "comp": "cp",
78
+ "cap": "cap",
79
+ "credits": "cr",
80
+ "extra": "ex",
81
+ "budget": "bg",
82
+ "search": "sr",
83
+ "tools": "tl",
84
+ };
85
+
86
+ function shortResetUnit(rawReset: string): string {
87
+ const trimmed = rawReset.trim().replace(/^in\s+/i, "");
88
+ if (/^now$/i.test(trimmed)) return "now";
89
+ const ltMatch = /^<\s*(\d+)([dhms])$/i.exec(trimmed);
90
+ if (ltMatch) return `${Number(ltMatch[1])}${ltMatch[2].toLowerCase()}`;
91
+ const units = [...trimmed.matchAll(/(\d+)([dhms])/gi)];
92
+ if (units.length) {
93
+ const nonZero = units.find((match) => Number(match[1]) > 0);
94
+ if (!nonZero) return "now";
95
+ return `${Number(nonZero[1])}${nonZero[2].toLowerCase()}`;
96
+ }
97
+ return trimmed;
98
+ }
99
+
100
+ function compactCurrency(raw: string, symbolOverride?: string): string {
101
+ const trimmed = raw.trim();
102
+ const symbol = symbolOverride ?? (/^(?:CNY|CN¥|RMB|¥)/i.test(trimmed) ? "¥" : "$");
103
+ const numeric = trimmed.replace(/^(?:USD|US\$|CNY|CN¥|RMB|\$|¥)\s*/i, "").replace(/,/g, "");
104
+ const value = Number(numeric);
105
+ if (!Number.isFinite(value)) return trimmed;
106
+ if (value === 0) return `${symbol}0`;
107
+ if (Math.abs(value) >= 10) return `${symbol}${Math.round(value)}`;
108
+ if (Math.abs(value) >= 0.1) return `${symbol}${value.toFixed(1).replace(/\.0$/, "")}`;
109
+ return `${symbol}${numeric}`;
110
+ }
111
+
112
+ function formatCreditsFallback(plain: string): string | undefined {
113
+ if (/^no credits$/i.test(plain)) return "cr:0!";
114
+ if (/^(?:credits unlimited|unlimited credits)$/i.test(plain)) return "cr:∞";
115
+ if (/^credits available$/i.test(plain)) return "cr:ok";
116
+ const count = /^(\d+(?:\.\d+)?)\s+credits$/i.exec(plain);
117
+ if (count) return `cr:${count[1]}`;
118
+ return undefined;
119
+ }
120
+
121
+ function formatPiUsageStatus(text: string): string | undefined {
122
+ const plainAll = stripTerminalSequences(text).trim();
123
+ if (!plainAll) return undefined;
124
+ if (/^usage unavailable$/i.test(plainAll)) return preserveColor(text, "u?");
125
+
126
+ // Split into per-window chunks starting at `<optional-ansi><label>:` so each window keeps its own color.
127
+ const windowHeader = /(?:^|\s)((?:\x1b\[[0-9;]*m)*[^\s\x1b:]+(?:\x1b\[[0-9;]*m)*:)/g;
128
+ const starts: number[] = [];
129
+ for (const match of text.matchAll(windowHeader)) {
130
+ const start = (match.index ?? 0) + (match[0].length - match[1].length);
131
+ starts.push(start);
132
+ }
133
+ if (!starts.length) return preserveColor(text, truncateToWidth(plainAll, 14, "…"));
134
+
135
+ const parsed: UrgentItem[] = [];
136
+ for (let i = 0; i < starts.length; i++) {
137
+ const chunk = text.slice(starts[i], starts[i + 1] ?? text.length).trim();
138
+ const colon = chunk.indexOf(":");
139
+ if (colon === -1) continue;
140
+ const rawLabel = chunk.slice(0, colon);
141
+ const rawRest = chunk.slice(colon + 1);
142
+
143
+ const label = stripTerminalSequences(rawLabel).trim();
144
+ const shortLabel = PI_USAGE_SHORT_LABELS[label.toLowerCase()] ?? label;
145
+ const color = extractColorPrefix(rawRest) ?? extractColorPrefix(rawLabel);
146
+
147
+ let restPlain = stripTerminalSequences(rawRest).trim();
148
+ const resetMatch = /\(↺(?:in\s+)?([^)]+)\)/.exec(restPlain);
149
+ const resetUnit = resetMatch ? shortResetUnit(resetMatch[1]) : undefined;
150
+ if (resetMatch) restPlain = restPlain.replace(resetMatch[0], "").trim();
151
+
152
+ const hasBang = /(?:^|\s)!(?:\s|$)/.test(restPlain);
153
+ if (hasBang) restPlain = restPlain.replace(/(?:^|\s)!(?:\s|$)/g, " ").trim();
154
+
155
+ let value = restPlain
156
+ .replace(/\s+left$/i, "")
157
+ .replace(/\s+used$/i, "")
158
+ .replace(/\$(\d+)\.00\b/g, "$$$1")
159
+ .trim();
160
+
161
+ const reached = /^REACHED$/i.test(value);
162
+ if (reached) value = "MAX";
163
+
164
+ const pctMatch = /^(\d+(?:\.\d+)?)%$/.exec(value);
165
+ const countMatch = /^(\d+)\/(\d+)$/.exec(value);
166
+ let remainingScore = 100;
167
+ if (pctMatch) remainingScore = Number(pctMatch[1]);
168
+ else if (countMatch && Number(countMatch[2]) > 0) remainingScore = (Number(countMatch[1]) / Number(countMatch[2])) * 100;
169
+ else if (reached) remainingScore = 0;
170
+
171
+ const limited = hasBang || reached || remainingScore <= 0;
172
+ const compact = `${shortLabel}:${value}${limited ? "!" : ""}${limited && resetUnit ? `↺${resetUnit}` : ""}`;
173
+ parsed.push({ index: i, limited, remainingScore, rendered: wrapColor(color, compact) });
174
+ }
175
+
176
+ if (!parsed.length) return preserveColor(text, truncateToWidth(plainAll, 14, "…"));
177
+ return selectUrgent(parsed).map((item) => item.rendered).join(" ");
178
+ }
179
+
180
+ function formatPiUsageTokenStatus(text: string): string | undefined {
181
+ const plainAll = stripTerminalSequences(text).trim();
182
+ if (!plainAll) return undefined;
183
+ if (/^token tracking unavailable$/i.test(plainAll)) return preserveColor(text, "tok?");
184
+
185
+ const segments = text.split(/\s*·\s*/);
186
+ const formatted: string[] = [];
187
+ for (const part of segments) {
188
+ const plain = stripTerminalSequences(part).trim();
189
+ const dollar = /\$[\d.,]+/.exec(plain)?.[0];
190
+ if (!dollar) continue;
191
+ const compact = compactCurrency(dollar, "$");
192
+ formatted.push(wrapColor(extractColorPrefix(part), compact));
193
+ }
194
+ if (!formatted.length) return preserveColor(text, truncateToWidth(plainAll, 14, "…"));
195
+ return formatted.join("/");
196
+ }
197
+
198
+ const NARUMI_UNAVAILABLE =
199
+ /^(?:auth unavailable|selection required|usage err:.*|usage unavailable|chatgpt usage: web only|.+ (?:usage|API|balance|credits) unavailable)$/i;
200
+
201
+ const NARUMI_PROVIDERS =
202
+ /^(codex|chatgpt(?:\s+plan)?|minimax(?:\s+(?:cn|global|intl))?|cmd|kimi|zai|zen|copilot|anthropic|openrouter|vercel|baseten|deepseek|fireworks|moonshot)\s+/i;
203
+
204
+ const NARUMI_SHORT_LABELS: Record<string, string> = {
205
+ ...PI_USAGE_SHORT_LABELS,
206
+ "w": "7d",
207
+ "m": "mo",
208
+ "r": "5h",
209
+ };
210
+
211
+ const NARUMI_COPILOT_LABELS: Record<string, string> = {
212
+ "premium": "pm",
213
+ "chat": "ch",
214
+ "credits": "cr",
215
+ };
216
+
217
+ const CURRENCY_AMOUNT = /(?:CN¥|CNY|RMB|USD|US\$|\$|¥)\s*[\d.,]+/gi;
218
+
219
+ function inferCountdownLabel(index: number, rawReset: string): string {
220
+ const days = /(\d+)d/i.exec(rawReset);
221
+ if (index === 0 && days) return Number(days[1]) > 7 ? "mo" : "7d";
222
+ if (index === 1 && days && Number(days[1]) > 7) return "mo";
223
+ return (["5h", "7d", "mo"] as const)[index] ?? `w${index + 1}`;
224
+ }
225
+
226
+ function formatNarumiCopilot(body: string): string | undefined {
227
+ const subMatch = /^(premium|chat|credits)\b\s*/i.exec(body);
228
+ const shortLabel = NARUMI_COPILOT_LABELS[(subMatch?.[1] ?? "premium").toLowerCase()] ?? "pm";
229
+ const rest = subMatch ? body.slice(subMatch[0].length).trim() : body.trim();
230
+ if (/^unlimited\b/i.test(rest)) return `${shortLabel}:∞`;
231
+
232
+ const pctMatch = /(\d+(?:\.\d+)?)%/.exec(rest);
233
+ if (!pctMatch) return undefined;
234
+ const pct = Number(pctMatch[1]);
235
+ const hasOver = /\+\s*\d+(?:\.\d+)?\s*over\b/i.test(rest);
236
+ const resetMatch = /[↻↺⟳]\s*(.+)$/.exec(rest);
237
+ const resetUnit = resetMatch ? shortResetUnit(resetMatch[1]) : undefined;
238
+ const limited = pct <= 0 || hasOver;
239
+ return `${shortLabel}:${pctMatch[1]}%${limited ? "!" : ""}${limited && resetUnit ? `↺${resetUnit}` : ""}`;
240
+ }
241
+
242
+ function formatUsageStatus(text: string): string | undefined {
243
+ const plainAll = stripTerminalSequences(text).trim();
244
+ if (!plainAll) return undefined;
245
+ if (NARUMI_UNAVAILABLE.test(plainAll)) return preserveColor(text, "u?");
246
+
247
+ const providerMatch = NARUMI_PROVIDERS.exec(plainAll);
248
+ if (!providerMatch && !plainAll.includes("·") && /^[^\s:]+:/.test(plainAll)) {
249
+ return formatPiUsageStatus(text);
250
+ }
251
+
252
+ const provider = providerMatch ? providerMatch[1].toLowerCase().split(/\s+/)[0] : undefined;
253
+ let body = providerMatch ? plainAll.slice(providerMatch[0].length).trim() : plainAll;
254
+ if (provider === "codex") {
255
+ // Strip optional Codex variant suffixes such as `(Fast unknown)` or `fast` without eating `no credits`.
256
+ body = body
257
+ .replace(/^\([^)]+\)\s+/, "")
258
+ .replace(/^(?!(?:no\s+credits|credits\b))[a-z][a-z0-9_-]*\s+(?=(?:\d+(?:\.\d+)?%|\S+:|\d+(?:\.\d+)?\s+credits\b|no\s+credits\b|credits\b))/i, "")
259
+ .trim();
260
+ }
261
+
262
+ if (provider === "copilot") {
263
+ const copilot = formatNarumiCopilot(body);
264
+ if (copilot) return preserveColor(text, copilot);
265
+ }
266
+
267
+ const credits = formatCreditsFallback(body);
268
+ if (credits) return preserveColor(text, credits);
269
+
270
+ if (/^no (?:Model APIs|rated) usage$/i.test(body)) return preserveColor(text, "$0");
271
+
272
+ const isUsed = provider === "zen";
273
+ const parsed: UrgentItem[] = [];
274
+ const pushWindow = (label: string, valueText: string, pct: number | undefined, rawReset: string | undefined, index: number) => {
275
+ const shortLabel = NARUMI_SHORT_LABELS[label.toLowerCase()] ?? label;
276
+ const isUnlimited = /^unlimited$/i.test(valueText);
277
+ const displayValue = isUnlimited ? "∞" : valueText;
278
+ const remainingScore = isUnlimited
279
+ ? 101
280
+ : pct === undefined
281
+ ? 100
282
+ : isUsed
283
+ ? 100 - pct
284
+ : pct;
285
+ const limited = pct !== undefined && (isUsed ? pct >= 100 : pct <= 0);
286
+ const resetUnit = rawReset ? shortResetUnit(rawReset) : undefined;
287
+ const rendered = `${shortLabel}:${displayValue}${limited ? "!" : ""}${limited && resetUnit ? `↺${resetUnit}` : ""}`;
288
+ parsed.push({ index, limited, remainingScore, rendered });
289
+ };
290
+
291
+ if (body.includes("·")) {
292
+ const parts = body.split(/\s*·\s*/).filter(Boolean);
293
+ for (let i = 0; i < parts.length; i++) {
294
+ const part = parts[i].trim();
295
+ const labeled = /^([^\s:]+):\s*(unlimited|\d+(?:\.\d+)?%)(?:\s*[↻↺⟳]\s*(.+))?$/i.exec(part);
296
+ if (labeled) {
297
+ const val = labeled[2];
298
+ const pct = val.endsWith("%") ? Number(val.slice(0, -1)) : undefined;
299
+ pushWindow(labeled[1], val, pct, labeled[3], i);
300
+ continue;
301
+ }
302
+ const countdown = /^(\d+(?:\.\d+)?)%\s*[↻↺⟳]\s*(.+)$/.exec(part);
303
+ if (countdown) {
304
+ pushWindow(inferCountdownLabel(i, countdown[2]), `${countdown[1]}%`, Number(countdown[1]), countdown[2], i);
305
+ }
306
+ }
307
+ } else {
308
+ const labeled = /^([^\s:]+):\s*(unlimited|\d+(?:\.\d+)?%)(?:\s*[↻↺⟳]\s*(.+))?$/i.exec(body);
309
+ if (labeled) {
310
+ const val = labeled[2];
311
+ const pct = val.endsWith("%") ? Number(val.slice(0, -1)) : undefined;
312
+ pushWindow(labeled[1], val, pct, labeled[3], 0);
313
+ } else {
314
+ const countdowns = [...body.matchAll(/(\d+(?:\.\d+)?)%\s*[↻↺⟳]\s*(<\s*\d+[dhms]|now|[^\s·]+)/gi)];
315
+ if (countdowns.length) {
316
+ for (let i = 0; i < countdowns.length; i++) {
317
+ const match = countdowns[i];
318
+ pushWindow(inferCountdownLabel(i, match[2]), `${match[1]}%`, Number(match[1]), match[2], i);
319
+ }
320
+ } else {
321
+ const valueLabels = [...body.matchAll(/(\d+(?:\.\d+)?)%\s+([a-z0-9_-]+)/gi)];
322
+ for (let i = 0; i < valueLabels.length; i++) {
323
+ const match = valueLabels[i];
324
+ pushWindow(match[2], `${match[1]}%`, Number(match[1]), undefined, i);
325
+ }
326
+ }
327
+ }
328
+ }
329
+
330
+ if (parsed.length) {
331
+ return preserveColor(text, selectUrgent(parsed).map((item) => item.rendered).join(" "));
332
+ }
333
+
334
+ const currencies = [...body.matchAll(CURRENCY_AMOUNT)].map((match) => compactCurrency(match[0]));
335
+ if (currencies.length) {
336
+ return preserveColor(text, currencies.join("/"));
337
+ }
338
+
339
+ const fallback = plainAll.replace(/\bleft\b/gi, "").replace(/\s+/g, " ").trim();
340
+ return fallback ? preserveColor(text, truncateToWidth(fallback, 14, "…")) : undefined;
341
+ }
342
+
343
+ const USAGE_BARS_SHORT_LABELS: Record<string, string> = {
344
+ "5h": "5h",
345
+ "S": "s",
346
+ "I": "i",
347
+ "L": "L",
348
+ "W": "7d",
349
+ };
350
+
351
+ const USAGE_BAR_LANE =
352
+ /(?:^|\s|\x1b\[[0-9;]*m)(5h|[SILW])(?:\x1b\[[0-9;]*m|\s)+[█░](?:[█░]|\x1b\[[0-9;]*m)*\s+((?:\x1b\[[0-9;]*m)*(?:<1|\d+(?:\.\d+)?)%)/g;
353
+
354
+ const ANSI_OR_CURRENCY = /\x1b\[[0-9;]*m|(?:CN¥|CNY|RMB|USD|US\$|\$|¥)\s*[\d.,]+/gi;
355
+
356
+ function formatUsageBarsStatus(text: string): string | undefined {
357
+ const plainAll = stripTerminalSequences(text).trim();
358
+ if (!plainAll) return undefined;
359
+ if (/\busage:\s*loading/i.test(plainAll)) return preserveColor(text, "u…");
360
+ if (/\busage unavailable\b/i.test(plainAll)) return preserveColor(text, "u?");
361
+
362
+ if (/[█░]/.test(plainAll)) {
363
+ const matches = [...text.matchAll(USAGE_BAR_LANE)];
364
+ const parsed: UrgentItem[] = [];
365
+ for (let i = 0; i < matches.length; i++) {
366
+ const match = matches[i];
367
+ const rawPrefix = match[1];
368
+ const rawPct = match[2];
369
+ const shortLabel = USAGE_BARS_SHORT_LABELS[rawPrefix] ?? rawPrefix;
370
+ const pctPlain = stripTerminalSequences(rawPct).trim();
371
+ const pctNum = pctPlain === "<1%" ? 0.5 : Number(pctPlain.slice(0, -1));
372
+ const color = extractColorPrefix(rawPct);
373
+
374
+ const tailStart = (match.index ?? 0) + match[0].length;
375
+ const tailEnd = matches[i + 1]?.index ?? text.length;
376
+ const tailPlain = stripTerminalSequences(text.slice(tailStart, tailEnd));
377
+ const resetMatch = /[⟳↻↺]\s*(<\s*\d+[dhms]|now|(?:\d+[dhms]\s*)+)/i.exec(tailPlain);
378
+ const resetUnit = resetMatch ? shortResetUnit(resetMatch[1]) : undefined;
379
+
380
+ const limited = pctNum >= 100;
381
+ const compact = `${shortLabel}:${pctPlain}${limited ? "!" : ""}${limited && resetUnit ? `↺${resetUnit}` : ""}`;
382
+ parsed.push({ index: i, limited, remainingScore: 100 - pctNum, rendered: wrapColor(color, compact) });
383
+ }
384
+ if (parsed.length) {
385
+ let rendered = selectUrgent(parsed).map((item) => item.rendered).join(" ");
386
+ const staleMatch = /((?:\x1b\[[0-9;]*m)*)\s*((?:\x1b\[[0-9;]*m)*)\bstale\b(?:\x1b\[[0-9;]*m)*\s*$/i.exec(text);
387
+ if (staleMatch) {
388
+ const staleColor = extractColorPrefix(`${staleMatch[1]}${staleMatch[2]}`);
389
+ rendered += wrapColor(staleColor, "~");
390
+ }
391
+ return rendered;
392
+ }
393
+ }
394
+
395
+ // Finance-only mode: extract currency amounts while tracking active ANSI color spans.
396
+ const activeSgr: string[] = [];
397
+ const amounts: Array<{ compact: string; color: string | undefined }> = [];
398
+ for (const match of text.matchAll(ANSI_OR_CURRENCY)) {
399
+ const token = match[0];
400
+ if (token.startsWith("\x1b[")) {
401
+ if (RESET_SGR.test(token)) activeSgr.length = 0;
402
+ else activeSgr.push(token);
403
+ continue;
404
+ }
405
+ amounts.push({
406
+ compact: compactCurrency(token),
407
+ color: activeSgr.length ? activeSgr.join("") : undefined,
408
+ });
409
+ }
410
+ if (!amounts.length) return preserveColor(text, "u?");
411
+ const firstColor = amounts[0].color;
412
+ if (amounts.every((item) => item.color === firstColor)) {
413
+ return wrapColor(firstColor, amounts.map((item) => item.compact).join("/"));
414
+ }
415
+ return amounts.map((item) => wrapColor(item.color, item.compact)).join("/");
416
+ }
417
+
418
+ function shortModelWindowLabel(model: string | undefined, rawLabel: string): string {
419
+ const normalized = PI_USAGE_SHORT_LABELS[rawLabel.toLowerCase()] ?? rawLabel.toLowerCase();
420
+ if (model && normalized === "7d") {
421
+ const m = model.toLowerCase();
422
+ if (m === "sonnet") return "7s";
423
+ if (m === "opus") return "7o";
424
+ if (m === "haiku") return "7h";
425
+ }
426
+ return normalized;
427
+ }
428
+
429
+ function formatProviderUsageStatus(text: string): string | undefined {
430
+ const rawPlain = stripTerminalSequences(text).trim();
431
+ if (!rawPlain) return undefined;
432
+ const plain = rawPlain.replace(/\s*\([^)]*\bold\)$/i, "").trim();
433
+ if (!plain) return undefined;
434
+
435
+ if (/^checking$/i.test(plain)) return preserveColor(text, "u…");
436
+ const rateLimited = /^usage rate-limited\s*\(([^)]+)\)$/i.exec(plain);
437
+ if (rateLimited) return preserveColor(text, `u!↺${shortResetUnit(rateLimited[1])}`);
438
+ if (/^usage (?:unavailable|error)$/i.test(plain)) return preserveColor(text, "u?");
439
+
440
+ const withoutProvider = plain.replace(/^(?:codex|claude|anthropic|openai)\b\s*/i, "").trim();
441
+ const credits = formatCreditsFallback(withoutProvider);
442
+ if (credits) return preserveColor(text, credits);
443
+
444
+ // Anthropic enterprise / extra spend budgets: `<pct>% $used/$limit [extra]`.
445
+ const budgetMatches = [...plain.matchAll(/(\d+(?:\.\d+)?)%\s+(\$[\d.,]+)\/(\$[\d.,]+)(?:\s+(extra))?/gi)];
446
+ if (budgetMatches.length === 1) {
447
+ const [, pct, used, limit] = budgetMatches[0];
448
+ const limited = Number(pct) >= 100;
449
+ return preserveColor(text, `${compactCurrency(used, "$")}/${compactCurrency(limit, "$")}${limited ? "!" : ""}`);
450
+ }
451
+ if (budgetMatches.length >= 2) {
452
+ const parsed: UrgentItem[] = budgetMatches.map((match, index) => {
453
+ const pctNum = Number(match[1]);
454
+ const limited = pctNum >= 100;
455
+ const label = match[4] ? "ex" : index === 0 ? "bg" : "ex";
456
+ return {
457
+ index,
458
+ limited,
459
+ remainingScore: 100 - pctNum,
460
+ rendered: `${label}:${match[1]}%${limited ? "!" : ""}`,
461
+ };
462
+ });
463
+ return preserveColor(text, selectUrgent(parsed).map((item) => item.rendered).join(" "));
464
+ }
465
+
466
+ // OpenRouter / spend pair without percentage (e.g. `OpenRouter · $12.34/$50`).
467
+ const spendPair = /(\$[\d.,]+)\/(\$[\d.,]+)/.exec(plain);
468
+ if (spendPair && !plain.includes("%")) {
469
+ return preserveColor(text, `${compactCurrency(spendPair[1], "$")}/${compactCurrency(spendPair[2], "$")}`);
470
+ }
471
+
472
+ const parsed: UrgentItem[] = [];
473
+ if (plain.includes("·")) {
474
+ const parts = plain.split(/\s*·\s*/).filter(Boolean);
475
+ for (let i = 0; i < parts.length; i++) {
476
+ const match = /^(?:(sonnet|opus|haiku)\s+)?([a-z0-9_-]+)\s+(\d+(?:\.\d+)?)%(?:\s*[↻↺⟳]\s*(.+))?$/i.exec(parts[i].trim());
477
+ if (!match) continue;
478
+ const label = shortModelWindowLabel(match[1], match[2]);
479
+ const pctNum = Number(match[3]);
480
+ const limited = pctNum >= 100;
481
+ const resetUnit = match[4] ? shortResetUnit(match[4]) : undefined;
482
+ parsed.push({
483
+ index: parsed.length,
484
+ limited,
485
+ remainingScore: 100 - pctNum,
486
+ rendered: `${label}:${match[3]}%${limited ? "!" : ""}${limited && resetUnit ? `↺${resetUnit}` : ""}`,
487
+ });
488
+ }
489
+ } else {
490
+ for (const match of plain.matchAll(/(\d+(?:\.\d+)?)%\s+([a-z0-9_-]+)/gi)) {
491
+ const pctNum = Number(match[1]);
492
+ const limited = pctNum >= 100;
493
+ const label = PI_USAGE_SHORT_LABELS[match[2].toLowerCase()] ?? match[2].toLowerCase();
494
+ parsed.push({
495
+ index: parsed.length,
496
+ limited,
497
+ remainingScore: 100 - pctNum,
498
+ rendered: `${label}:${match[1]}%${limited ? "!" : ""}`,
499
+ });
500
+ }
501
+ }
502
+
503
+ if (parsed.length) {
504
+ return preserveColor(text, selectUrgent(parsed).map((item) => item.rendered).join(" "));
505
+ }
506
+
507
+ return preserveColor(text, truncateToWidth(plain, 14, "…"));
508
+ }
509
+
510
+ const QUOTA_SHORT_LABELS: Record<string, string> = {
511
+ "claude": "Cl",
512
+ "codex": "Cx",
513
+ "agy": "Ag",
514
+ "agy c/g": "AgC",
515
+ "op-go": "OG",
516
+ "gh": "GH",
517
+ };
518
+
519
+ function formatQuotaStatus(text: string): string | undefined {
520
+ const plainAll = stripTerminalSequences(text).trim();
521
+ if (!plainAll) return undefined;
522
+ if (/^quota\s*(?:…|\.\.\.)$/i.test(plainAll)) return preserveColor(text, "u…");
523
+ if (/^quota:\s*no providers/i.test(plainAll)) return preserveColor(text, "u?");
524
+
525
+ const chunks = text.trim().split(/ {2,}/);
526
+ const parsed: UrgentItem[] = [];
527
+ for (let i = 0; i < chunks.length; i++) {
528
+ const chunk = chunks[i];
529
+ const colon = chunk.indexOf(":");
530
+ if (colon === -1) continue;
531
+ const rawLabel = chunk.slice(0, colon);
532
+ const rawRest = chunk.slice(colon + 1);
533
+ const label = stripTerminalSequences(rawLabel).trim();
534
+ if (!label) continue;
535
+ const shortLabel = QUOTA_SHORT_LABELS[label.toLowerCase()] ?? label.slice(0, 3);
536
+ const color = extractColorPrefix(rawRest);
537
+ const valuePlain = stripTerminalSequences(rawRest).trim().replace(/^[○◔◕●]\s*/, "").trim();
538
+
539
+ const pctMatch = /^(\d+(?:\.\d+)?)%$/.exec(valuePlain);
540
+ if (pctMatch) {
541
+ const pctNum = Number(pctMatch[1]);
542
+ const limited = pctNum >= 100;
543
+ const compact = `${shortLabel}:${pctMatch[1]}%${limited ? "!" : ""}`;
544
+ parsed.push({ index: i, limited, remainingScore: 100 - pctNum, rendered: wrapColor(color, compact) });
545
+ continue;
546
+ }
547
+ if (/^[!…]$/.test(valuePlain)) {
548
+ parsed.push({ index: i, limited: true, remainingScore: 0, rendered: wrapColor(color, `${shortLabel}:${valuePlain}`) });
549
+ continue;
550
+ }
551
+ if (/^[~?·]$/.test(valuePlain)) {
552
+ parsed.push({ index: i, limited: false, remainingScore: 50, rendered: wrapColor(color, `${shortLabel}:${valuePlain}`) });
553
+ }
554
+ }
555
+
556
+ if (!parsed.length) return preserveColor(text, truncateToWidth(plainAll, 14, "…"));
557
+ return selectUrgent(parsed).map((item) => item.rendered).join(" ");
558
+ }
559
+
560
+ /** Built-in Type 1 adapters that compress known third-party statuses for the top border. */
561
+ export const ADAPTED_EXTENSIONS: readonly ExtensionAdapter[] = [
562
+ {
563
+ key: "pi-usage",
564
+ id: "pi-usage",
565
+ format: formatPiUsageStatus,
566
+ },
567
+ {
568
+ key: "pi-usage-token-status",
569
+ id: "pi-usage-token-status",
570
+ format: formatPiUsageTokenStatus,
571
+ },
572
+ {
573
+ key: "usage",
574
+ id: "usage",
575
+ format: formatUsageStatus,
576
+ },
577
+ {
578
+ key: "@hk_net/pi-usage-bars",
579
+ id: "pi-usage-bars",
580
+ format: formatUsageBarsStatus,
581
+ },
582
+ {
583
+ key: "provider-usage",
584
+ id: "provider-usage",
585
+ format: formatProviderUsageStatus,
586
+ },
587
+ {
588
+ key: "00-quota",
589
+ id: "quota",
590
+ format: formatQuotaStatus,
591
+ },
592
+ {
593
+ key: "ssh",
594
+ id: "ssh",
595
+ format(text) {
596
+ const plain = stripTerminalSequences(text).trim();
597
+ if (!plain) return undefined;
598
+ const body = plain.replace(/^ssh:\s*/i, "");
599
+ const remote = body.split(":")[0] ?? body;
600
+ const host = remote.includes("@") ? remote.slice(remote.indexOf("@") + 1) : remote;
601
+ const label = host.trim() || plain;
602
+ return preserveColor(text, truncateToWidth(`ssh:${label}`, 14, "…"));
603
+ },
604
+ },
605
+ {
606
+ key: "preset",
607
+ id: "preset",
608
+ format(text) {
609
+ const plain = stripTerminalSequences(text).trim();
610
+ if (!plain) return undefined;
611
+ const name = plain.replace(/^preset:\s*/i, "").trim();
612
+ return preserveColor(text, truncateToWidth(`P:${name || plain}`, 12, "…"));
613
+ },
614
+ },
615
+ {
616
+ key: "debug-provider",
617
+ id: "debug-provider",
618
+ format(text) {
619
+ const plain = stripTerminalSequences(text).trim();
620
+ return plain ? preserveColor(text, "dbg") : undefined;
621
+ },
622
+ },
623
+ {
624
+ key: "provider-debug",
625
+ id: "debug-provider",
626
+ format(text) {
627
+ const plain = stripTerminalSequences(text).trim();
628
+ return plain ? preserveColor(text, "dbg") : undefined;
629
+ },
630
+ },
631
+ {
632
+ key: "ponytail",
633
+ id: "ponytail",
634
+ format(text) {
635
+ const plain = stripTerminalSequences(text).trim();
636
+ if (!plain) return undefined;
637
+ const modeMatch = /\b(ULTRA|FULL|LITE|OFF)\b/i.exec(plain);
638
+ const modeWord = modeMatch?.[1]?.toUpperCase();
639
+ if (modeWord === "OFF") return preserveColor(text, "♘-");
640
+ const level = modeWord
641
+ ? modeWord[0]
642
+ : (/([A-Za-z]+)\s*$/.exec(plain)?.[1]?.[0]?.toUpperCase() ?? "");
643
+ if (!level) return undefined;
644
+ const inactive = /[○◯◌]/.test(plain);
645
+ const active = /[●◉◆✓✔]/.test(plain);
646
+ const horse = active ? "♞" : inactive ? "♘" : "♞";
647
+ return preserveColor(text, `${horse}${level}`);
648
+ },
649
+ },
650
+ ];
651
+
652
+ export function segmentEntries(statuses: ReadonlyMap<string, string>): Map<string, string> {
653
+ const entries = new Map<string, string>();
654
+ for (const [key, text] of statuses) {
655
+ const id = SEGMENT_KEY.exec(key)?.[1];
656
+ if (id) entries.set(id, segmentText(text));
657
+ }
658
+ return entries;
659
+ }
660
+
661
+ /**
662
+ * Split extension statuses into three tiers for Minimal mode:
663
+ * - Type 2: explicit `path-bar:<id>` segments (highest priority; suppresses matching Type 1 key)
664
+ * - Type 1: known third-party statuses compressed by built-in adapters
665
+ * - Type 3: unknown extensions rendered on the auto-hiding line below the bottom border
666
+ */
667
+ export function classifyStatuses(
668
+ statuses: ReadonlyMap<string, string>,
669
+ adapters: readonly ExtensionAdapter[] = ADAPTED_EXTENSIONS,
670
+ ): ClassifiedStatuses {
671
+ const slots = new Map<string, SlotEntry>();
672
+ const remaining: Array<[string, string]> = [];
673
+ for (const [key, raw] of statuses) {
674
+ const text = segmentText(raw);
675
+ const id = SEGMENT_KEY.exec(key)?.[1];
676
+ if (id) {
677
+ slots.set(id, { id, text, source: "segment" });
678
+ } else {
679
+ remaining.push([key, text]);
680
+ }
681
+ }
682
+ const byKey = new Map(adapters.map((adapter) => [adapter.key, adapter]));
683
+ const unknown: Array<[string, string]> = [];
684
+ for (const [key, text] of remaining) {
685
+ const adapter = byKey.get(key);
686
+ if (adapter) {
687
+ // Explicit Type 2 registration wins and suppresses the legacy key so it does not duplicate below.
688
+ if (slots.has(adapter.id)) continue;
689
+ const formatted = adapter.format(text);
690
+ if (formatted) {
691
+ slots.set(adapter.id, { id: adapter.id, text: segmentText(formatted), source: "adapted" });
692
+ continue;
693
+ }
694
+ }
695
+ unknown.push([key, text]);
696
+ }
697
+ unknown.sort(([a], [b]) => a.localeCompare(b));
698
+ return { slots, unknown };
699
+ }
700
+
701
+ /**
702
+ * Left-to-right order of the segments right of the path. The configured order wins; ids that
703
+ * are registered but not configured go left of the clock, sorted by id.
704
+ */
705
+ export function resolveOrder(segments: string[], registered: Iterable<string>): string[] {
706
+ const known = new Set([CLOCK, ...registered]);
707
+ const listed = [...new Set(segments)].filter((id) => known.has(id));
708
+ if (!listed.includes(CLOCK)) listed.push(CLOCK);
709
+ const at = listed.indexOf(CLOCK);
710
+ const unknown = [...known].filter((id) => !listed.includes(id)).sort((a, b) => a.localeCompare(b));
711
+ return [...listed.slice(0, at), ...unknown, ...listed.slice(at)];
712
+ }