glintline 0.0.0-stage → 0.3.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,189 @@
1
+ import { createHash } from "node:crypto";
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, unlinkSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { argv, execPath } from "node:process";
6
+ import { getOAuthToken } from "./credentials";
7
+ import { detectFamily } from "./model";
8
+ import { cachePath, readCache, writeCache } from "./cache";
9
+ import { debug } from "./debug";
10
+ import type { ExtraUsage, Usage, UsageWindow } from "./types";
11
+
12
+ const ENDPOINT = "https://api.anthropic.com/api/oauth/usage";
13
+ const FRESH_TTL_SEC = 60;
14
+ const STALE_TTL_SEC = 24 * 3600;
15
+ const FETCH_TIMEOUT_MS = 8000;
16
+ const LOCK_TTL_SEC = 30;
17
+
18
+ interface ApiWindow {
19
+ utilization?: number;
20
+ resets_at?: string | null;
21
+ }
22
+
23
+ interface ApiExtra {
24
+ is_enabled?: boolean;
25
+ monthly_limit?: number;
26
+ used_credits?: number;
27
+ utilization?: number;
28
+ }
29
+
30
+ // Newer per-model weekly caps arrive not as named fields but as entries in a
31
+ // `limits[]` array, each tagged with a `scope.model`. We key them by model
32
+ // family (via detectFamily, so "Fable"/"Fable 5" → "fable") for lookup against
33
+ // the active model.
34
+ interface ApiLimit {
35
+ group?: string;
36
+ percent?: number;
37
+ resets_at?: string | null;
38
+ scope?: { model?: { display_name?: string | null } | null } | null;
39
+ }
40
+
41
+ interface ApiResponse {
42
+ five_hour?: ApiWindow;
43
+ seven_day?: ApiWindow;
44
+ limits?: ApiLimit[] | null;
45
+ extra_usage?: ApiExtra | null;
46
+ }
47
+
48
+ // Collect the weekly, model-scoped limits from `limits[]` into a map keyed by
49
+ // model family, so a widget can look up the cap for whatever model is active.
50
+ export function scopedWeekly(limits: ApiLimit[] | null | undefined): Record<string, UsageWindow> {
51
+ const out: Record<string, UsageWindow> = {};
52
+ if (!Array.isArray(limits)) return out;
53
+ for (const l of limits) {
54
+ if (!l || l.group !== "weekly") continue;
55
+ const name = l.scope?.model?.display_name;
56
+ if (typeof name !== "string") continue;
57
+ // percent maps onto ApiWindow.utilization, so reuse the shared window mapper.
58
+ const w = mapWindow({ utilization: l.percent, resets_at: l.resets_at });
59
+ if (w) out[detectFamily(name)] = w;
60
+ }
61
+ return out;
62
+ }
63
+
64
+ function tokenKey(token: string): string {
65
+ return "usage:" + createHash("sha256").update(token).digest("hex").slice(0, 16);
66
+ }
67
+
68
+ function lockKey(token: string): string {
69
+ return "usage-lock:" + createHash("sha256").update(token).digest("hex").slice(0, 16);
70
+ }
71
+
72
+ function toEpoch(value: string | null | undefined): number {
73
+ if (!value) return 0;
74
+ const ms = Date.parse(value);
75
+ return Number.isFinite(ms) ? Math.floor(ms / 1000) : 0;
76
+ }
77
+
78
+ function mapWindow(w: ApiWindow | undefined | null): UsageWindow | undefined {
79
+ if (!w || w.utilization === undefined) return undefined;
80
+ return { utilization: w.utilization, resets_at: toEpoch(w.resets_at) };
81
+ }
82
+
83
+ function mapExtra(e: ApiExtra | undefined | null): ExtraUsage | undefined {
84
+ if (!e || e.utilization === undefined) return undefined;
85
+ return {
86
+ is_enabled: e.is_enabled ?? false,
87
+ monthly_limit: e.monthly_limit ?? 0,
88
+ used_credits: e.used_credits ?? 0,
89
+ utilization: e.utilization,
90
+ };
91
+ }
92
+
93
+ function ageSec(usage: Usage | null): number {
94
+ if (!usage) return Infinity;
95
+ return Math.floor(Date.now() / 1000) - usage.fetched_at;
96
+ }
97
+
98
+ function isLocked(token: string): boolean {
99
+ return readCache<{ at: number }>(lockKey(token), LOCK_TTL_SEC) !== null;
100
+ }
101
+
102
+ function acquireLock(token: string): void {
103
+ writeCache(lockKey(token), { at: Math.floor(Date.now() / 1000) });
104
+ }
105
+
106
+ function releaseLock(token: string): void {
107
+ try {
108
+ const path = cachePath(lockKey(token));
109
+ if (existsSync(path)) unlinkSync(path);
110
+ } catch (e) {
111
+ debug("usage-api.lock", e);
112
+ }
113
+ }
114
+
115
+ function spawnRefresh(): void {
116
+ const scriptArg = argv[1];
117
+ if (!scriptArg) return;
118
+ const scriptPath = resolve(scriptArg);
119
+ try {
120
+ const child = spawn(execPath, [scriptPath, "--refresh-usage"], {
121
+ detached: true,
122
+ stdio: "ignore",
123
+ });
124
+ child.unref();
125
+ } catch (e) {
126
+ debug("usage-api.spawn", e);
127
+ }
128
+ }
129
+
130
+ async function doFetch(token: string): Promise<Usage | null> {
131
+ const controller = new AbortController();
132
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
133
+ try {
134
+ const res = await fetch(ENDPOINT, {
135
+ method: "GET",
136
+ headers: {
137
+ Accept: "application/json",
138
+ Authorization: `Bearer ${token}`,
139
+ "anthropic-beta": "oauth-2025-04-20",
140
+ "User-Agent": "glintline/0.1",
141
+ },
142
+ signal: controller.signal,
143
+ });
144
+ if (!res.ok) {
145
+ debug("usage-api.fetch", `HTTP ${res.status}`);
146
+ return null;
147
+ }
148
+ const json = (await res.json()) as ApiResponse;
149
+ const usage: Usage = {
150
+ five_hour: mapWindow(json.five_hour),
151
+ seven_day: mapWindow(json.seven_day),
152
+ seven_day_scoped: scopedWeekly(json.limits),
153
+ extra: mapExtra(json.extra_usage),
154
+ fetched_at: Math.floor(Date.now() / 1000),
155
+ source: "api",
156
+ };
157
+ writeCache(tokenKey(token), usage);
158
+ return usage;
159
+ } catch (e) {
160
+ debug("usage-api.fetch", e);
161
+ return null;
162
+ } finally {
163
+ clearTimeout(timer);
164
+ }
165
+ }
166
+
167
+ export async function refreshUsageOnce(): Promise<void> {
168
+ const token = getOAuthToken();
169
+ if (!token) return;
170
+ if (isLocked(token)) return;
171
+ acquireLock(token);
172
+ try {
173
+ await doFetch(token);
174
+ } finally {
175
+ releaseLock(token);
176
+ }
177
+ }
178
+
179
+ export function getUsageNonBlocking(): Usage | null {
180
+ const token = getOAuthToken();
181
+ if (!token) return null;
182
+
183
+ const cached = readCache<Usage>(tokenKey(token), STALE_TTL_SEC);
184
+ const age = ageSec(cached);
185
+
186
+ if (age >= FRESH_TTL_SEC && !isLocked(token)) spawnRefresh();
187
+
188
+ return cached ? { ...cached, source: "cache" } : null;
189
+ }
package/src/usage.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { StatusInput, Usage, UsageWindow, RateLimitWindow } from "./types";
2
+ import type { Config } from "./config";
3
+ import { getUsageNonBlocking } from "./usage-api";
4
+
5
+ function normalizeResetsAt(value: number | string | undefined): number {
6
+ if (value === undefined) return 0;
7
+ if (typeof value === "number") return value;
8
+ const ms = Date.parse(value);
9
+ return Number.isFinite(ms) ? Math.floor(ms / 1000) : 0;
10
+ }
11
+
12
+ function fromInputWindow(rl: RateLimitWindow | undefined): UsageWindow | undefined {
13
+ if (!rl || rl.used_percentage === undefined) return undefined;
14
+ return {
15
+ utilization: rl.used_percentage,
16
+ resets_at: normalizeResetsAt(rl.resets_at),
17
+ };
18
+ }
19
+
20
+ function fromInput(input: StatusInput): Usage | null {
21
+ const rl = input.rate_limits;
22
+ if (!rl) return null;
23
+ const five = fromInputWindow(rl.five_hour);
24
+ const seven = fromInputWindow(rl.seven_day);
25
+ if (!five && !seven) return null;
26
+ return {
27
+ five_hour: five,
28
+ seven_day: seven,
29
+ fetched_at: Math.floor(Date.now() / 1000),
30
+ source: "stdin",
31
+ };
32
+ }
33
+
34
+ // Once Claude Code reports rate_limits, it decides which windows exist: a
35
+ // window it leaves out is gone (Ultra has no 5-hour limit; an expired window is
36
+ // dropped until the next one starts), so the API must not bring it back. The
37
+ // API still contributes what stdin never carries — per-model caps and extra.
38
+ export function mergeUsage(stdin: Usage | null, api: Usage | null): Usage | null {
39
+ if (!api) return stdin;
40
+ if (!stdin) return api;
41
+ return {
42
+ ...api,
43
+ five_hour: stdin.five_hour,
44
+ seven_day: stdin.seven_day,
45
+ source: stdin.source,
46
+ };
47
+ }
48
+
49
+ export function getUsage(input: StatusInput, fetchApi: boolean): Usage | null {
50
+ const stdin = fromInput(input);
51
+ if (!fetchApi) return stdin;
52
+ return mergeUsage(stdin, getUsageNonBlocking());
53
+ }
54
+
55
+ const API_ONLY_WIDGETS = new Set(["extra"]);
56
+
57
+ export function widgetsNeedApi(config: Config): boolean {
58
+ const anyWidget = (pred: (w: string) => boolean) => config.widgets.some((line) => line.some(pred));
59
+ if (anyWidget((w) => API_ONLY_WIDGETS.has(w))) return true;
60
+ // Per-model weekly caps live only in the API; limit7d needs it when it is set
61
+ // to swap in the active model's scoped window.
62
+ return anyWidget((w) => w === "limit7d") && config.limit7d.perModel;
63
+ }
package/src/widgets.ts ADDED
@@ -0,0 +1,419 @@
1
+ import type { StatusInput, Usage, UsageWindow } from "./types";
2
+ import type { Config, LimitOpts } from "./config";
3
+ import type { ContextUsage } from "./context";
4
+ import type { ModelInfo } from "./model";
5
+ import type { GitInfo } from "./git";
6
+ import type { SessionTotals, CacheUsage } from "./transcript";
7
+ import { c, wrap } from "./ansi";
8
+ import {
9
+ BAR_PRESETS,
10
+ cacheHitColor,
11
+ cacheHitRate,
12
+ colorByPercent,
13
+ formatClock,
14
+ formatDuration,
15
+ formatTokens,
16
+ progressBar,
17
+ } from "./format";
18
+
19
+ export interface WidgetCtx {
20
+ input: StatusInput;
21
+ config: Config;
22
+ model: ModelInfo;
23
+ context: ContextUsage | null;
24
+ usage: Usage | null;
25
+ git: GitInfo | null;
26
+ totals: SessionTotals;
27
+ cacheLast: CacheUsage | null;
28
+ nowSec: number;
29
+ }
30
+
31
+ const FAMILY_COLOR: Record<string, string> = {
32
+ opus: c.purple,
33
+ sonnet: c.cyan,
34
+ haiku: c.silver,
35
+ fable: c.coral,
36
+ };
37
+
38
+ // Per-generation accents, so a new major reads differently from its
39
+ // predecessors within the same family. [family, minimum major, color] —
40
+ // the first matching entry wins, else the family color.
41
+ const GENERATION_COLOR: Array<[string, number, string]> = [
42
+ ["opus", 5, c.lime],
43
+ ];
44
+
45
+ export function modelColor(family: string, version: string | undefined): string {
46
+ const major = version ? parseFloat(version) : 0;
47
+ for (const [fam, min, color] of GENERATION_COLOR) {
48
+ if (family === fam && major >= min) return color;
49
+ }
50
+ return FAMILY_COLOR[family] ?? c.white;
51
+ }
52
+
53
+ function renderModel(ctx: WidgetCtx): string | null {
54
+ const { model: m } = ctx;
55
+ const opts = ctx.config.model;
56
+ const familyColor = modelColor(m.family, m.version);
57
+
58
+ const parts: string[] = [];
59
+ if (opts.showFamily) parts.push(wrap(c.bold + familyColor, m.family));
60
+
61
+ const versionParts: string[] = [];
62
+ if (opts.showVersion && m.version) versionParts.push(m.version);
63
+ if (opts.showContext && m.context) versionParts.push(m.context);
64
+ if (versionParts.length > 0) parts.push(wrap(familyColor, versionParts.join(" ")));
65
+
66
+ if (opts.showEffortIcon && m.effort) {
67
+ const icon = ctx.config.effort.icons[m.effort];
68
+ if (icon) {
69
+ parts.push(wrap(effortColor(m.effort), icon));
70
+ }
71
+ }
72
+
73
+ if (parts.length === 0) return null;
74
+ const body = parts.join(" ");
75
+ return opts.label ? wrap(c.lightGray, opts.label) + " " + body : body;
76
+ }
77
+
78
+ function effortColor(level: string): string {
79
+ if (level === "max") return c.pink;
80
+ if (level === "xhigh") return c.orange;
81
+ return c.yellow;
82
+ }
83
+
84
+ function renderEffort(ctx: WidgetCtx): string | null {
85
+ const e = ctx.model.effort;
86
+ if (!e) return null;
87
+ let s = wrap(effortColor(e), e);
88
+ if (ctx.model.fast) s += " " + wrap(c.orange, "fast");
89
+ const label = ctx.config.effort.label;
90
+ return label ? wrap(c.lightGray, label) + " " + s : s;
91
+ }
92
+
93
+ function renderContext(ctx: WidgetCtx): string | null {
94
+ if (!ctx.context) return null;
95
+ const { context: cu } = ctx;
96
+ const opts = ctx.config.context;
97
+ const calm = ctx.config.calmColors;
98
+ const denom = cu.compactThreshold ?? cu.total;
99
+ const pctVal = denom > 0 ? (cu.used / denom) * 100 : 0;
100
+ const parts: string[] = [];
101
+ if (opts.showBar) {
102
+ const preset = BAR_PRESETS[opts.barStyle] ?? BAR_PRESETS.square!;
103
+ const chars = opts.barChars ?? preset;
104
+ parts.push(progressBar(cu.used, cu.total, opts.barWidth, {
105
+ full: chars.full,
106
+ empty: chars.empty,
107
+ threshold: cu.compactThreshold,
108
+ fillEmpty: opts.fillEmpty,
109
+ calm,
110
+ }));
111
+ }
112
+ if (opts.showNumbers) {
113
+ const color = colorByPercent(pctVal, calm);
114
+ let s: string;
115
+ if (cu.compactThreshold !== undefined && cu.compactThreshold < cu.total) {
116
+ const buffer = cu.total - cu.compactThreshold;
117
+ s = wrap(color, formatTokens(cu.used)) +
118
+ wrap(c.gray, "/") + wrap(c.lightGray, formatTokens(cu.compactThreshold));
119
+ if (opts.showBufferTokens) s += wrap(c.gray, "/") + wrap(c.gray, formatTokens(buffer));
120
+ } else {
121
+ s = wrap(color, `${formatTokens(cu.used)}/${formatTokens(cu.total)}`);
122
+ }
123
+ if (opts.showPercent) {
124
+ s += " " + wrap(c.gray, "(") + wrap(color, `${Math.round(pctVal)}%`) + wrap(c.gray, ")");
125
+ }
126
+ parts.push(s);
127
+ }
128
+ if (parts.length === 0) return null;
129
+ const body = parts.join(opts.gap);
130
+ return opts.label ? wrap(c.lightGray, opts.label) + " " + body : body;
131
+ }
132
+
133
+ const WINDOW_DURATION_SEC: Record<string, number> = {
134
+ "5h": 5 * 3600,
135
+ "7d": 7 * 24 * 3600,
136
+ };
137
+
138
+ export function burnRate(w: UsageWindow, nowSec: number, windowSec: number, mono: boolean): { icon: string; color: string } | null {
139
+ if (w.resets_at <= 0) return null;
140
+ const progress = (nowSec - (w.resets_at - windowSec)) / windowSec;
141
+ if (progress >= 1) return null;
142
+ const flat = mono ? c.lightGray : null;
143
+ if (progress < 0.1) return { icon: "~", color: flat ?? c.gray };
144
+ const u = w.utilization;
145
+ const proj = u / progress; // projected utilization at reset if the pace holds
146
+ if (proj <= 100) {
147
+ // under pace — won't reach the cap; grade the headroom by where you'd land
148
+ if (proj < 50) return { icon: "↓↓", color: flat ?? c.mutedGreen };
149
+ if (proj < 80) return { icon: "↓", color: flat ?? c.mutedGreen };
150
+ return { icon: "~", color: flat ?? c.gray };
151
+ }
152
+ // Over pace — you'll hit the cap before reset. Grade by the share of the
153
+ // time left you'd spend locked at the cap. This stays meaningful for the
154
+ // whole window: a plain pace ratio caps at 1/progress, so ↑↑ (and even ↑)
155
+ // become unreachable past the window's midpoint exactly when risk is highest.
156
+ const remaining = 1 - progress;
157
+ const timeToCap = ((100 - u) / u) * progress;
158
+ const locked = 1 - timeToCap / remaining;
159
+ if (locked > 0.5) return { icon: "↑↑", color: flat ?? c.mutedRed };
160
+ if (locked > 0.15) return { icon: "↑", color: flat ?? c.mutedYellow };
161
+ return { icon: "~", color: flat ?? c.gray };
162
+ }
163
+
164
+ function renderWindow(w: UsageWindow | undefined, opts: LimitOpts, nowSec: number, calm: boolean, windowSec: number, aside?: UsageWindow): string | null {
165
+ if (!w) return null;
166
+ const pct = Math.round(w.utilization);
167
+ const color = opts.mono ? c.lightGray : colorByPercent(pct, calm);
168
+ let s = wrap(c.lightGray, opts.label) + wrap(c.gray, opts.separator) + wrap(color, `${pct}%`);
169
+ if (opts.showBurnRate) {
170
+ const burn = burnRate(w, nowSec, windowSec, opts.mono);
171
+ if (burn) s += " " + wrap(burn.color, burn.icon);
172
+ }
173
+ // Optional secondary window, in parens after the burn hint. Its percentage
174
+ // stays dimmed (it is the secondary number), but its own burn hint keeps the
175
+ // regular colors — pace on the general cap is a signal worth seeing even when
176
+ // the per-model cap is the headline.
177
+ if (aside) {
178
+ let inner = wrap(c.darkGray, `${Math.round(aside.utilization)}%`);
179
+ if (opts.showBurnRate) {
180
+ const burn = burnRate(aside, nowSec, windowSec, opts.mono);
181
+ if (burn) inner += " " + wrap(burn.color, burn.icon);
182
+ }
183
+ s += " " + wrap(c.darkGray, "(") + inner + wrap(c.darkGray, ")");
184
+ }
185
+ if (opts.showCountdown && w.resets_at > 0) {
186
+ const remain = w.resets_at - nowSec;
187
+ if (remain > 0) s += wrap(c.gray, ` ⟳ ${formatDuration(remain)}`);
188
+ }
189
+ return s;
190
+ }
191
+
192
+ function renderLimit5h(ctx: WidgetCtx): string | null {
193
+ return renderWindow(ctx.usage?.five_hour, ctx.config.limit5h, ctx.nowSec, ctx.config.calmColors, WINDOW_DURATION_SEC["5h"]!);
194
+ }
195
+
196
+ function renderLimit7d(ctx: WidgetCtx): string | null {
197
+ const opts = ctx.config.limit7d;
198
+ const general = ctx.usage?.seven_day;
199
+ const week = WINDOW_DURATION_SEC["7d"]!;
200
+ // With perModel, show the active model's own weekly cap (e.g. Fable) as the
201
+ // primary value, tagging the label, and trail the general weekly cap dimmed
202
+ // in parens. Models without a per-model cap fall back to the general window.
203
+ const scoped = opts.perModel ? ctx.usage?.seven_day_scoped?.[ctx.model.family] : undefined;
204
+ if (scoped) {
205
+ const label = `${opts.label}-${ctx.model.family}`;
206
+ return renderWindow(scoped, { ...opts, label }, ctx.nowSec, ctx.config.calmColors, week, general);
207
+ }
208
+ return renderWindow(general, opts, ctx.nowSec, ctx.config.calmColors, week);
209
+ }
210
+
211
+ function renderExtra(ctx: WidgetCtx): string | null {
212
+ const e = ctx.usage?.extra;
213
+ if (!e || !e.is_enabled) return null;
214
+
215
+ if (ctx.config.extra.onlyWhenActive) {
216
+ const fast = ctx.model.fast;
217
+ const fiveExhausted = (ctx.usage?.five_hour?.utilization ?? 0) >= 100;
218
+ const sevenExhausted = (ctx.usage?.seven_day?.utilization ?? 0) >= 100;
219
+ if (!fast && !fiveExhausted && !sevenExhausted) return null;
220
+ }
221
+
222
+ const pct = Math.round(e.utilization);
223
+ const color = ctx.config.extra.mono ? c.lightGray : colorByPercent(pct, ctx.config.calmColors);
224
+ const used = (e.used_credits / 100).toFixed(2);
225
+ const limit = (e.monthly_limit / 100).toFixed(0);
226
+ return wrap(c.lightGray, ctx.config.extra.label) + wrap(c.gray, ": ") +
227
+ wrap(color, `$${used}`) + wrap(c.gray, `/$${limit}`) +
228
+ " " + wrap(c.gray, "(") + wrap(color, `${pct}%`) + wrap(c.gray, ")");
229
+ }
230
+
231
+ // Name of the linked worktree the session sits in. stdin `workspace.git_worktree`
232
+ // covers any `git worktree add` checkout; `worktree.name` is the Claude Code
233
+ // worktree session, kept as a fallback. Both are absent in the main checkout.
234
+ function renderGitWorktree(ctx: WidgetCtx): string | null {
235
+ const name = ctx.input.workspace?.git_worktree ?? ctx.input.worktree?.name;
236
+ if (!name) return null;
237
+ const label = ctx.config.git.worktreeLabel;
238
+ return wrap(c.cyan, label ? `${label} ${name}` : name);
239
+ }
240
+
241
+ function renderGitBranch(ctx: WidgetCtx): string | null {
242
+ if (!ctx.git || !ctx.git.branch) return null;
243
+ return wrap(c.magenta, "⎇ ") + wrap(c.bold + c.magenta, ctx.git.branch);
244
+ }
245
+
246
+ function renderGitDiff(ctx: WidgetCtx): string | null {
247
+ if (!ctx.git) return null;
248
+ const g = ctx.git;
249
+ if (g.added > 0 || g.removed > 0) {
250
+ return wrap(c.gray, "(") +
251
+ wrap(c.green, `+${g.added}`) + wrap(c.gray, ",") +
252
+ wrap(c.red, `-${g.removed}`) + wrap(c.gray, ")");
253
+ }
254
+ if (g.dirty) return wrap(c.yellow, "*");
255
+ return null;
256
+ }
257
+
258
+ function renderSep(ctx: WidgetCtx): string | null {
259
+ return wrap(c.darkGray, ctx.config.separator);
260
+ }
261
+
262
+ function renderSpace(): string | null {
263
+ return " ";
264
+ }
265
+
266
+ function cachePct(u: CacheUsage | SessionTotals | null): number | null {
267
+ if (!u) return null;
268
+ const rate = cacheHitRate(u.cacheRead, u.cacheCreation, u.input);
269
+ return rate === null ? null : Math.round(rate);
270
+ }
271
+
272
+ function cacheExpiry(ctx: WidgetCtx): string | null {
273
+ const opts = ctx.config.cache;
274
+ const pc = ctx.input.prompt_cache;
275
+ if (!opts.showExpiry || !pc?.caching_observed) return null;
276
+ const expiresAt = pc.expires_at ?? 0;
277
+ // `warm` is only as fresh as the payload, so an expires_at already in the
278
+ // past reads as cold too.
279
+ if (pc.warm && expiresAt > ctx.nowSec) {
280
+ const time = formatClock(expiresAt);
281
+ return wrap(c.gray, opts.expiryLabel ? `${opts.expiryLabel} ${time}` : time);
282
+ }
283
+ const parts: string[] = [];
284
+ if (opts.coldLabel) parts.push(wrap(opts.mono ? c.lightGray : c.mutedBlue, opts.coldLabel));
285
+ const recache = pc.recache_tokens_if_cold;
286
+ if (recache) parts.push(wrap(opts.mono ? c.lightGray : c.yellow, `↑${formatTokens(recache)}`));
287
+ return parts.length > 0 ? parts.join(" ") : null;
288
+ }
289
+
290
+ function renderCache(ctx: WidgetCtx): string | null {
291
+ const opts = ctx.config.cache;
292
+ const parts: string[] = [];
293
+
294
+ if (opts.window === "both") {
295
+ const last = cachePct(ctx.cacheLast);
296
+ const session = cachePct(ctx.totals);
297
+ // Last turn is the primary signal (is the cache warm right now?), colored
298
+ // by its own health; the session lifetime trails it, marked `Σ` and dimmed
299
+ // so it reads as secondary context rather than a competing number.
300
+ if (last !== null) parts.push(wrap(opts.mono ? c.lightGray : cacheHitColor(last), `${last}%`));
301
+ if (session !== null) parts.push(wrap(c.darkGray, `Σ${session}%`));
302
+ } else {
303
+ const pct = cachePct(opts.window === "last" ? ctx.cacheLast : ctx.totals);
304
+ if (pct !== null) parts.push(wrap(opts.mono ? c.lightGray : cacheHitColor(pct), `${pct}%`));
305
+ }
306
+ if (parts.length === 0) return null;
307
+ if (!opts.showPercent) parts.length = 0;
308
+
309
+ const expiry = cacheExpiry(ctx);
310
+ if (expiry) parts.push(expiry);
311
+ if (parts.length === 0) return null;
312
+ const prefix = opts.label ? wrap(c.lightGray, opts.label) + " " : "";
313
+ return prefix + parts.join(" ");
314
+ }
315
+
316
+ function renderCacheTokens(ctx: WidgetCtx): string | null {
317
+ const t = ctx.totals;
318
+ if (t.cacheRead === 0 && t.cacheCreation === 0) return null;
319
+ return wrap(c.green, `↓${formatTokens(t.cacheRead)}`) +
320
+ " " +
321
+ wrap(c.yellow, `↑${formatTokens(t.cacheCreation)}`);
322
+ }
323
+
324
+ function renderCost(ctx: WidgetCtx): string | null {
325
+ if (ctx.config.cost.onlyWhenFast && !ctx.model.fast) return null;
326
+ const cost = ctx.input.cost?.total_cost_usd;
327
+ if (cost === undefined) return null;
328
+ return wrap(c.green, `$${cost.toFixed(ctx.config.cost.precision)}`);
329
+ }
330
+
331
+ function renderLines(ctx: WidgetCtx): string | null {
332
+ const a = ctx.input.cost?.total_lines_added;
333
+ const r = ctx.input.cost?.total_lines_removed;
334
+ if (a === undefined && r === undefined) return null;
335
+ return wrap(c.green, `+${a ?? 0}`) + wrap(c.gray, "/") + wrap(c.red, `-${r ?? 0}`);
336
+ }
337
+
338
+ function renderSession(ctx: WidgetCtx): string | null {
339
+ const ms = ctx.input.cost?.total_duration_ms;
340
+ if (!ms) return null;
341
+ const opts = ctx.config.session;
342
+ const color = opts.mono ? c.lightGray : c.cyan;
343
+ const prefix = opts.label ? wrap(c.gray, opts.label) + " " : "";
344
+ return prefix + wrap(color, formatDuration(ms / 1000));
345
+ }
346
+
347
+ function renderVersion(ctx: WidgetCtx): string | null {
348
+ const v = ctx.input.version;
349
+ return v ? wrap(c.darkGray, `v${v}`) : null;
350
+ }
351
+
352
+ function renderCwd(ctx: WidgetCtx): string | null {
353
+ const cwd = ctx.input.workspace?.current_dir ?? ctx.input.cwd;
354
+ if (!cwd) return null;
355
+ const opts = ctx.config.cwd;
356
+ const path = wrap(c.mutedBlue, formatCwdPath(cwd, opts.format, opts.maxLength));
357
+ return opts.label ? wrap(c.lightGray, opts.label) + " " + path : path;
358
+ }
359
+
360
+ function formatCwdPath(cwd: string, format: string, maxLength: number): string {
361
+ const home = process.env.HOME ?? "";
362
+ const homeRel = home && cwd.startsWith(home) ? "~" + cwd.slice(home.length) : cwd;
363
+ if (format === "full") return cwd;
364
+ if (format === "home") return homeRel;
365
+ if (format === "short") return homeRel.split("/").slice(-2).join("/");
366
+ if (homeRel.length <= maxLength) return homeRel;
367
+ const parts = homeRel.split("/");
368
+ if (parts.length <= 2) return homeRel;
369
+ const first = parts[0]!;
370
+ const tail = parts.slice(-2).join("/");
371
+ const candidate = `${first}/…/${tail}`;
372
+ if (candidate.length <= maxLength) return candidate;
373
+ const last = parts[parts.length - 1]!;
374
+ return `${first}/…/${last}`;
375
+ }
376
+
377
+ function renderSessionId(ctx: WidgetCtx): string | null {
378
+ const id = ctx.input.session_id;
379
+ if (!id) return null;
380
+ const opts = ctx.config.session;
381
+ const len = opts.idLength > 0 ? opts.idLength : id.length;
382
+ const short = id.slice(0, len);
383
+ const color = opts.mono ? c.lightGray : c.gray;
384
+ const prefix = opts.idLabel ? wrap(c.lightGray, opts.idLabel) + " " : "";
385
+ return prefix + wrap(color, short);
386
+ }
387
+
388
+ const REGISTRY: Record<string, (ctx: WidgetCtx) => string | null> = {
389
+ model: renderModel,
390
+ effort: renderEffort,
391
+ context: renderContext,
392
+ limit5h: renderLimit5h,
393
+ limit7d: renderLimit7d,
394
+ extra: renderExtra,
395
+ "git.worktree": renderGitWorktree,
396
+ "git.branch": renderGitBranch,
397
+ "git.diff": renderGitDiff,
398
+ cache: renderCache,
399
+ "cache.tokens": renderCacheTokens,
400
+ cost: renderCost,
401
+ lines: renderLines,
402
+ session: renderSession,
403
+ "session.id": renderSessionId,
404
+ version: renderVersion,
405
+ cwd: renderCwd,
406
+ sep: renderSep,
407
+ space: renderSpace,
408
+ };
409
+
410
+ export const SEP_NAMES = new Set(["sep", "space"]);
411
+
412
+ export function availableWidgets(): string[] {
413
+ return Object.keys(REGISTRY);
414
+ }
415
+
416
+ export function renderWidget(name: string, ctx: WidgetCtx): string | null {
417
+ const fn = REGISTRY[name];
418
+ return fn ? fn(ctx) : null;
419
+ }