glintline 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
+ }