@hasna/statusline 0.0.1 → 0.0.3

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/dist/index.js ADDED
@@ -0,0 +1,920 @@
1
+ // @bun
2
+ var __create = Object.create;
3
+ var __getProtoOf = Object.getPrototypeOf;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ function __accessProp(key) {
8
+ return this[key];
9
+ }
10
+ var __toESMCache_node;
11
+ var __toESMCache_esm;
12
+ var __toESM = (mod, isNodeMode, target) => {
13
+ var canCache = mod != null && typeof mod === "object";
14
+ if (canCache) {
15
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
16
+ var cached = cache.get(mod);
17
+ if (cached)
18
+ return cached;
19
+ }
20
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
21
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
22
+ for (let key of __getOwnPropNames(mod))
23
+ if (!__hasOwnProp.call(to, key))
24
+ __defProp(to, key, {
25
+ get: __accessProp.bind(mod, key),
26
+ enumerable: true
27
+ });
28
+ if (canCache)
29
+ cache.set(mod, to);
30
+ return to;
31
+ };
32
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
33
+ var __returnValue = (v) => v;
34
+ function __exportSetter(name, newValue) {
35
+ this[name] = __returnValue.bind(null, newValue);
36
+ }
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, {
40
+ get: all[name],
41
+ enumerable: true,
42
+ configurable: true,
43
+ set: __exportSetter.bind(all, name)
44
+ });
45
+ };
46
+
47
+ // src/config.ts
48
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
49
+ import { homedir } from "os";
50
+ import { dirname, join } from "path";
51
+ function defaultConfig() {
52
+ return {
53
+ separator: " \xB7 ",
54
+ colors: true,
55
+ segments: [
56
+ "machine",
57
+ "project",
58
+ "commit-age",
59
+ "loc",
60
+ "model-context",
61
+ "context-remaining",
62
+ "cost"
63
+ ]
64
+ };
65
+ }
66
+ function configPath(path) {
67
+ if (path)
68
+ return path;
69
+ if (process.env.STATUSLINE_CONFIG)
70
+ return process.env.STATUSLINE_CONFIG;
71
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
72
+ return join(base, "statusline", "config.json");
73
+ }
74
+ function loadConfig(path = configPath()) {
75
+ if (!existsSync(path))
76
+ return defaultConfig();
77
+ try {
78
+ const raw = JSON.parse(readFileSync(path, "utf8"));
79
+ const fallback = defaultConfig();
80
+ return {
81
+ separator: typeof raw.separator === "string" ? raw.separator : fallback.separator,
82
+ segments: Array.isArray(raw.segments) ? raw.segments.filter((s) => typeof s === "string") : fallback.segments,
83
+ colors: typeof raw.colors === "boolean" ? raw.colors : fallback.colors
84
+ };
85
+ } catch {
86
+ return defaultConfig();
87
+ }
88
+ }
89
+ function saveConfig(cfg, path = configPath()) {
90
+ mkdirSync(dirname(path), { recursive: true });
91
+ writeFileSync(path, JSON.stringify(cfg, null, 2) + `
92
+ `);
93
+ }
94
+
95
+ // src/providers/claude.ts
96
+ function parseClaudeInput(input) {
97
+ const cwd = input?.cwd || input?.workspace?.current_dir || process.cwd();
98
+ return {
99
+ provider: "claude",
100
+ cwd,
101
+ projectDir: input?.workspace?.project_dir || undefined,
102
+ model: input?.model ? { id: input.model.id || undefined, displayName: input.model.display_name || undefined } : undefined,
103
+ cost: input?.cost ? {
104
+ totalCostUsd: numberOr(input.cost.total_cost_usd),
105
+ totalDurationMs: numberOr(input.cost.total_duration_ms),
106
+ totalLinesAdded: numberOr(input.cost.total_lines_added),
107
+ totalLinesRemoved: numberOr(input.cost.total_lines_removed)
108
+ } : undefined,
109
+ transcriptPath: input?.transcript_path || undefined,
110
+ sessionId: input?.session_id || undefined,
111
+ sessionName: input?.session_name || undefined,
112
+ version: input?.version || undefined,
113
+ outputStyle: input?.output_style?.name || undefined,
114
+ effort: input?.effort?.level || undefined,
115
+ thinking: typeof input?.thinking?.enabled === "boolean" ? input.thinking.enabled : undefined,
116
+ rateLimits: input?.rate_limits ? {
117
+ fiveHour: { usedPercentage: numberOr(input.rate_limits.five_hour?.used_percentage) },
118
+ sevenDay: { usedPercentage: numberOr(input.rate_limits.seven_day?.used_percentage) }
119
+ } : undefined
120
+ };
121
+ }
122
+ function numberOr(v) {
123
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
124
+ }
125
+
126
+ // src/segments/index.ts
127
+ import { hostname } from "os";
128
+
129
+ // src/format.ts
130
+ function compactAge(seconds) {
131
+ if (seconds < 60)
132
+ return `${Math.floor(seconds)}s`;
133
+ if (seconds < 3600)
134
+ return `${Math.floor(seconds / 60)}m`;
135
+ if (seconds < 86400)
136
+ return `${Math.floor(seconds / 3600)}h`;
137
+ if (seconds < 604800)
138
+ return `${Math.floor(seconds / 86400)}d`;
139
+ if (seconds < 2592000)
140
+ return `${Math.floor(seconds / 604800)}w`;
141
+ if (seconds < 31536000)
142
+ return `${Math.floor(seconds / 2592000)}mo`;
143
+ return `${Math.floor(seconds / 31536000)}y`;
144
+ }
145
+ function trimmed(value) {
146
+ const fixed = value.toFixed(1);
147
+ return fixed.endsWith(".0") ? fixed.slice(0, -2) : fixed;
148
+ }
149
+ function compactNum(n) {
150
+ if (n >= 1e6)
151
+ return `${trimmed(n / 1e6)}m`;
152
+ if (n >= 1e4)
153
+ return `${Math.floor(n / 1000)}k`;
154
+ if (n >= 1000)
155
+ return `${trimmed(n / 1000)}k`;
156
+ return `${n}`;
157
+ }
158
+ function money(n) {
159
+ return `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
160
+ }
161
+ function compactDuration(ms) {
162
+ const s = Math.floor(ms / 1000);
163
+ if (s < 60)
164
+ return `${s}s`;
165
+ if (s < 3600) {
166
+ const rem2 = s % 60;
167
+ return rem2 ? `${Math.floor(s / 60)}m${rem2}s` : `${Math.floor(s / 60)}m`;
168
+ }
169
+ const rem = Math.floor(s % 3600 / 60);
170
+ return rem ? `${Math.floor(s / 3600)}h${rem}m` : `${Math.floor(s / 3600)}h`;
171
+ }
172
+
173
+ // src/git.ts
174
+ function run(cwd, args) {
175
+ try {
176
+ const proc = Bun.spawnSync(["git", "-c", "gc.auto=0", ...args], {
177
+ cwd,
178
+ stdout: "pipe",
179
+ stderr: "ignore"
180
+ });
181
+ if (proc.exitCode !== 0)
182
+ return null;
183
+ const out = proc.stdout.toString().trim();
184
+ return out.length ? out : null;
185
+ } catch {
186
+ return null;
187
+ }
188
+ }
189
+ function gitRoot(cwd) {
190
+ return run(cwd, ["rev-parse", "--show-toplevel"]);
191
+ }
192
+ function gitBranch(cwd) {
193
+ return run(cwd, ["branch", "--show-current"]);
194
+ }
195
+ function gitProjectName(cwd) {
196
+ const root = gitRoot(cwd);
197
+ if (!root)
198
+ return null;
199
+ const remote = run(root, ["config", "--get", "remote.origin.url"]);
200
+ if (remote)
201
+ return remote.replace(/\.git$/, "").split("/").pop() || null;
202
+ return root.split("/").pop() || null;
203
+ }
204
+ function lastCommitEpoch(cwd) {
205
+ const out = run(cwd, ["log", "-1", "--format=%ct"]);
206
+ if (!out)
207
+ return null;
208
+ const ts = Number(out);
209
+ return Number.isFinite(ts) ? ts : null;
210
+ }
211
+ function trackedLineCount(cwd) {
212
+ const root = gitRoot(cwd);
213
+ if (!root)
214
+ return null;
215
+ try {
216
+ const proc = Bun.spawnSync(["bash", "-c", "git -c gc.auto=0 ls-files -z | xargs -0 wc -l 2>/dev/null | awk 'END {print $1+0}'"], { cwd: root, stdout: "pipe", stderr: "ignore" });
217
+ if (proc.exitCode !== 0)
218
+ return null;
219
+ const n = Number(proc.stdout.toString().trim());
220
+ return Number.isFinite(n) && n > 0 ? n : null;
221
+ } catch {
222
+ return null;
223
+ }
224
+ }
225
+
226
+ // src/context-window.ts
227
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
228
+ function contextUsage(ctx) {
229
+ const path = ctx.transcriptPath;
230
+ if (!path || !existsSync2(path))
231
+ return null;
232
+ let lines;
233
+ try {
234
+ lines = readFileSync2(path, "utf8").split(`
235
+ `);
236
+ } catch {
237
+ return null;
238
+ }
239
+ for (let i = lines.length - 1;i >= 0; i--) {
240
+ const line = lines[i];
241
+ if (!line || !line.includes('"usage"'))
242
+ continue;
243
+ try {
244
+ const entry = JSON.parse(line);
245
+ const usage = entry?.message?.usage;
246
+ if (!usage || typeof usage.input_tokens !== "number")
247
+ continue;
248
+ const used = usage.input_tokens + (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0);
249
+ return {
250
+ used,
251
+ output: usage.output_tokens || 0,
252
+ window: windowSize(ctx)
253
+ };
254
+ } catch {
255
+ continue;
256
+ }
257
+ }
258
+ return null;
259
+ }
260
+ function windowSize(ctx) {
261
+ return ctx.model?.id?.includes("[1m]") ? 1e6 : 200000;
262
+ }
263
+
264
+ // src/accounts.ts
265
+ import { existsSync as existsSync3, readFileSync as readFileSync3, realpathSync } from "fs";
266
+ import { homedir as homedir2 } from "os";
267
+ import { join as join2, resolve, sep } from "path";
268
+ var CONFIG_DIR_ENV = "CLAUDE_CONFIG_DIR";
269
+ var DEFAULT_CONFIG_SUBDIR = ".claude";
270
+ var STORE_PATH_ENV = "ACCOUNTS_STORE_PATH";
271
+ var ACCOUNTS_HOME_ENV = "ACCOUNTS_HOME";
272
+ var DEFAULT_ACCOUNTS_HOME = [".hasna", "accounts"];
273
+ var STORE_FILE = "accounts.json";
274
+ var PROFILES_SUBDIR = "profiles";
275
+ var STATE_FILE_PREFERRED = ".config.json";
276
+ var STATE_FILE_PREFIX = ".claude";
277
+ var STATE_FILE_SUFFIX = ".json";
278
+ var CUSTOM_OAUTH_ENV = "CLAUDE_CODE_CUSTOM_OAUTH_URL";
279
+ var OAUTH_VARIANTS = ["", "-custom-oauth", "-local-oauth", "-staging-oauth"];
280
+ function str(value) {
281
+ return typeof value === "string" && value.trim() ? value.trim() : null;
282
+ }
283
+ function home(env) {
284
+ return str(env.HOME) ?? homedir2();
285
+ }
286
+ function expandHome(path, env) {
287
+ return path === "~" || path.startsWith(`~${sep}`) ? join2(home(env), path.slice(1)) : path;
288
+ }
289
+ function canonical(path, env) {
290
+ const abs = resolve(expandHome(path, env));
291
+ try {
292
+ return realpathSync(abs);
293
+ } catch {
294
+ return abs;
295
+ }
296
+ }
297
+ function readJson(path) {
298
+ try {
299
+ return JSON.parse(readFileSync3(path, "utf8"));
300
+ } catch {
301
+ return null;
302
+ }
303
+ }
304
+ var ACCOUNTS_STORAGE_MODULE = "@hasna/accounts/storage";
305
+ var storagePromise;
306
+ function accountsStorage() {
307
+ storagePromise ??= import(ACCOUNTS_STORAGE_MODULE).then((mod) => typeof mod?.storePath === "function" && typeof mod?.profilesDir === "function" ? mod : null, () => null);
308
+ return storagePromise;
309
+ }
310
+ async function accountsPaths(env) {
311
+ const homeOverride = str(env[ACCOUNTS_HOME_ENV]);
312
+ const storeOverride = str(env[STORE_PATH_ENV]);
313
+ if (!homeOverride && !storeOverride) {
314
+ const storage = await accountsStorage();
315
+ try {
316
+ if (storage)
317
+ return { store: storage.storePath(), profiles: storage.profilesDir() };
318
+ } catch {}
319
+ }
320
+ const base = homeOverride ?? join2(home(env), ...DEFAULT_ACCOUNTS_HOME);
321
+ return {
322
+ store: storeOverride ?? join2(base, STORE_FILE),
323
+ profiles: join2(base, PROFILES_SUBDIR)
324
+ };
325
+ }
326
+ function registryEntry(store, configDir, env, tool) {
327
+ if (!existsSync3(store))
328
+ return null;
329
+ const entries = readJson(store)?.profiles;
330
+ if (!Array.isArray(entries))
331
+ return null;
332
+ let untyped = null;
333
+ let first = null;
334
+ for (const entry of entries) {
335
+ const dir = str(entry?.dir);
336
+ if (!dir || canonical(dir, env) !== configDir)
337
+ continue;
338
+ const entryTool = str(entry?.tool);
339
+ if (tool && entryTool === tool)
340
+ return entry;
341
+ if (!entryTool)
342
+ untyped ??= entry;
343
+ first ??= entry;
344
+ }
345
+ return tool ? untyped : first;
346
+ }
347
+ function layoutProfile(profilesRoot, configDir, env) {
348
+ if (!existsSync3(configDir))
349
+ return null;
350
+ const prefix = canonical(profilesRoot, env) + sep;
351
+ if (!configDir.startsWith(prefix))
352
+ return null;
353
+ const parts = configDir.slice(prefix.length).split(sep);
354
+ if (parts.length !== 2)
355
+ return null;
356
+ const [tool, profile] = parts;
357
+ if (!tool || !profile)
358
+ return null;
359
+ return { configDir, profile, tool, source: "layout" };
360
+ }
361
+ function sessionConfigDir(env = process.env) {
362
+ return canonical(str(env[CONFIG_DIR_ENV]) ?? join2(home(env), DEFAULT_CONFIG_SUBDIR), env);
363
+ }
364
+ function sessionStateFile(env = process.env) {
365
+ const base = canonical(str(env[CONFIG_DIR_ENV]) ?? home(env), env);
366
+ const preferred = join2(base, STATE_FILE_PREFERRED);
367
+ if (existsSync3(preferred))
368
+ return preferred;
369
+ const variants = str(env[CUSTOM_OAUTH_ENV]) ? ["-custom-oauth", ...OAUTH_VARIANTS] : OAUTH_VARIANTS;
370
+ for (const variant of variants) {
371
+ const candidate = join2(base, `${STATE_FILE_PREFIX}${variant}${STATE_FILE_SUFFIX}`);
372
+ if (existsSync3(candidate))
373
+ return candidate;
374
+ }
375
+ return null;
376
+ }
377
+ async function sessionAccount(env = process.env, tool) {
378
+ const configDir = sessionConfigDir(env);
379
+ const unresolved = { configDir, profile: null, tool: null, source: null };
380
+ try {
381
+ const paths = await accountsPaths(env);
382
+ const entry = registryEntry(paths.store, configDir, env, tool);
383
+ const name = str(entry?.name);
384
+ if (name)
385
+ return { configDir, profile: name, tool: str(entry?.tool), source: "registry" };
386
+ return layoutProfile(paths.profiles, configDir, env) ?? unresolved;
387
+ } catch {
388
+ return unresolved;
389
+ }
390
+ }
391
+ async function sessionAccountEmail(env = process.env, tool) {
392
+ try {
393
+ const stateFile = sessionStateFile(env);
394
+ const live = stateFile ? str(readJson(stateFile)?.oauthAccount?.emailAddress) : null;
395
+ if (live)
396
+ return live;
397
+ const paths = await accountsPaths(env);
398
+ return str(registryEntry(paths.store, sessionConfigDir(env), env, tool)?.email);
399
+ } catch {
400
+ return null;
401
+ }
402
+ }
403
+
404
+ // src/segments/index.ts
405
+ function friendlyModel(id) {
406
+ let tag = null;
407
+ let mid = id;
408
+ const tagMatch = mid.match(/\[([^\]]+)\]$/);
409
+ if (tagMatch) {
410
+ tag = `[${tagMatch[1]}]`;
411
+ mid = mid.slice(0, mid.length - tagMatch[0].length);
412
+ }
413
+ mid = mid.replace(/^claude-/, "").replace(/-\d{8}$/, "");
414
+ const tokens = mid.split("-").filter(Boolean);
415
+ const words = tokens.filter((t) => !/^\d+$/.test(t));
416
+ const nums = tokens.filter((t) => /^\d+$/.test(t));
417
+ const name = [words.join(" "), nums.join(".")].filter(Boolean).join(" ");
418
+ return { name: name || mid, tag };
419
+ }
420
+ var dir = (ctx) => ctx.cwd || process.cwd();
421
+ function modelName(ctx) {
422
+ if (ctx.model?.displayName)
423
+ return ctx.model.displayName;
424
+ return ctx.model?.id ? friendlyModel(ctx.model.id).name : null;
425
+ }
426
+ function limitPercent(pct) {
427
+ return typeof pct === "number" ? pct : 0;
428
+ }
429
+ var segments = [
430
+ {
431
+ id: "machine",
432
+ description: "Machine hostname (short)",
433
+ defaultEnabled: true,
434
+ render: () => hostname().split(".")[0] || null
435
+ },
436
+ {
437
+ id: "project",
438
+ description: "Project name with current Git branch",
439
+ defaultEnabled: true,
440
+ render(ctx) {
441
+ const name = gitProjectName(dir(ctx)) || dir(ctx).split("/").pop() || null;
442
+ if (!name)
443
+ return null;
444
+ const branch = gitBranch(dir(ctx));
445
+ return branch ? `${name} (${branch})` : name;
446
+ }
447
+ },
448
+ {
449
+ id: "project-name",
450
+ description: "Project name (omitted when unavailable)",
451
+ defaultEnabled: false,
452
+ render: (ctx) => gitProjectName(dir(ctx)) || dir(ctx).split("/").pop() || null
453
+ },
454
+ {
455
+ id: "git-branch",
456
+ description: "Current Git branch (omitted when unavailable)",
457
+ defaultEnabled: false,
458
+ render: (ctx) => gitBranch(dir(ctx))
459
+ },
460
+ {
461
+ id: "commit-age",
462
+ description: "Time since last commit (compact)",
463
+ defaultEnabled: true,
464
+ render(ctx) {
465
+ const ts = lastCommitEpoch(dir(ctx));
466
+ if (!ts)
467
+ return null;
468
+ return compactAge(Date.now() / 1000 - ts);
469
+ }
470
+ },
471
+ {
472
+ id: "loc",
473
+ description: "Lines of code tracked by Git (compact)",
474
+ defaultEnabled: true,
475
+ render(ctx) {
476
+ const n = trackedLineCount(dir(ctx));
477
+ return n ? compactNum(n) : null;
478
+ }
479
+ },
480
+ {
481
+ id: "current-dir",
482
+ description: "Current working directory (basename)",
483
+ defaultEnabled: false,
484
+ render: (ctx) => dir(ctx).split("/").pop() || null
485
+ },
486
+ {
487
+ id: "model",
488
+ description: "Current model name",
489
+ defaultEnabled: false,
490
+ render(ctx) {
491
+ if (!ctx.model?.id)
492
+ return null;
493
+ return friendlyModel(ctx.model.id).name;
494
+ }
495
+ },
496
+ {
497
+ id: "model-context",
498
+ description: "Model name with context-size tag (e.g. [1m])",
499
+ defaultEnabled: true,
500
+ render(ctx) {
501
+ if (!ctx.model?.id)
502
+ return null;
503
+ const { name, tag } = friendlyModel(ctx.model.id);
504
+ return tag ? `${name} ${tag}` : name;
505
+ }
506
+ },
507
+ {
508
+ id: "model-with-reasoning",
509
+ description: "Model name with its reasoning effort (or thinking, when on)",
510
+ defaultEnabled: false,
511
+ color: "cyan",
512
+ render(ctx) {
513
+ const name = modelName(ctx);
514
+ if (!name)
515
+ return null;
516
+ if (ctx.effort)
517
+ return `${name} (${ctx.effort})`;
518
+ if (ctx.thinking)
519
+ return `${name} (thinking)`;
520
+ return name;
521
+ }
522
+ },
523
+ {
524
+ id: "auth-profile",
525
+ description: "Account profile this session runs as (omitted when unmanaged)",
526
+ defaultEnabled: false,
527
+ color: "magenta",
528
+ async render(ctx) {
529
+ const account = await sessionAccount(process.env, ctx.provider);
530
+ return account.profile ?? await sessionAccountEmail(process.env, ctx.provider);
531
+ }
532
+ },
533
+ {
534
+ id: "auth-email",
535
+ description: "Account email this session is logged in as (omitted when unknown)",
536
+ defaultEnabled: false,
537
+ color: "magenta",
538
+ render: (ctx) => sessionAccountEmail(process.env, ctx.provider)
539
+ },
540
+ {
541
+ id: "five-hour-limit",
542
+ description: "Percentage of the 5-hour rate limit used (omitted when unreported)",
543
+ defaultEnabled: false,
544
+ color: (ctx) => limitPercent(ctx.rateLimits?.fiveHour?.usedPercentage) >= 80 ? "red" : "yellow",
545
+ render(ctx) {
546
+ const pct = ctx.rateLimits?.fiveHour?.usedPercentage;
547
+ return typeof pct === "number" ? `5h:${Math.round(pct)}%` : null;
548
+ }
549
+ },
550
+ {
551
+ id: "seven-day-limit",
552
+ description: "Percentage of the 7-day rate limit used (omitted when unreported)",
553
+ defaultEnabled: false,
554
+ color: (ctx) => limitPercent(ctx.rateLimits?.sevenDay?.usedPercentage) >= 80 ? "red" : "yellow",
555
+ render(ctx) {
556
+ const pct = ctx.rateLimits?.sevenDay?.usedPercentage;
557
+ return typeof pct === "number" ? `7d:${Math.round(pct)}%` : null;
558
+ }
559
+ },
560
+ {
561
+ id: "thread-title",
562
+ description: "Thread title set with /rename (omitted until named)",
563
+ defaultEnabled: false,
564
+ color: "blue",
565
+ render: (ctx) => ctx.sessionName || null
566
+ },
567
+ {
568
+ id: "context-used",
569
+ description: "Percentage of context window used (omitted when unknown)",
570
+ defaultEnabled: false,
571
+ render(ctx) {
572
+ const u = contextUsage(ctx);
573
+ if (!u)
574
+ return null;
575
+ return `${Math.min(100, Math.round(u.used / u.window * 100))}%`;
576
+ }
577
+ },
578
+ {
579
+ id: "context-remaining",
580
+ description: "Percentage of context window remaining (omitted when unknown)",
581
+ defaultEnabled: true,
582
+ render(ctx) {
583
+ const u = contextUsage(ctx);
584
+ if (!u)
585
+ return null;
586
+ return `${Math.max(0, 100 - Math.round(u.used / u.window * 100))}% left`;
587
+ }
588
+ },
589
+ {
590
+ id: "used-tokens",
591
+ description: "Total tokens in the context window (omitted when unknown)",
592
+ defaultEnabled: false,
593
+ render(ctx) {
594
+ const u = contextUsage(ctx);
595
+ if (!u)
596
+ return null;
597
+ return `${compactNum(u.used + u.output)} tok`;
598
+ }
599
+ },
600
+ {
601
+ id: "cost",
602
+ description: "Session cost in USD (omitted when zero)",
603
+ defaultEnabled: true,
604
+ render(ctx) {
605
+ const c = ctx.cost?.totalCostUsd;
606
+ return c ? money(c) : null;
607
+ }
608
+ },
609
+ {
610
+ id: "duration",
611
+ description: "Session wall-clock duration",
612
+ defaultEnabled: false,
613
+ render(ctx) {
614
+ const ms = ctx.cost?.totalDurationMs;
615
+ return ms ? compactDuration(ms) : null;
616
+ }
617
+ },
618
+ {
619
+ id: "lines-changed",
620
+ description: "Lines added/removed this session (omitted when zero)",
621
+ defaultEnabled: false,
622
+ render(ctx) {
623
+ const a = ctx.cost?.totalLinesAdded || 0;
624
+ const r = ctx.cost?.totalLinesRemoved || 0;
625
+ if (!a && !r)
626
+ return null;
627
+ return `+${a}/-${r}`;
628
+ }
629
+ },
630
+ {
631
+ id: "output-style",
632
+ description: "Active output style (omitted when default)",
633
+ defaultEnabled: false,
634
+ render(ctx) {
635
+ const s = ctx.outputStyle;
636
+ return s && s !== "default" ? s : null;
637
+ }
638
+ },
639
+ {
640
+ id: "agent-version",
641
+ description: "Host agent version (e.g. Claude Code version)",
642
+ defaultEnabled: false,
643
+ render: (ctx) => ctx.version ? `v${ctx.version}` : null
644
+ },
645
+ {
646
+ id: "session-id",
647
+ description: "Session identifier (short)",
648
+ defaultEnabled: false,
649
+ render: (ctx) => ctx.sessionId ? ctx.sessionId.split("-")[0] : null
650
+ }
651
+ ];
652
+ function getSegment(id) {
653
+ return segments.find((s) => s.id === id);
654
+ }
655
+
656
+ // src/render.ts
657
+ var ANSI = {
658
+ cyan: "\x1B[36m",
659
+ magenta: "\x1B[35m",
660
+ blue: "\x1B[34m",
661
+ green: "\x1B[32m",
662
+ yellow: "\x1B[33m",
663
+ red: "\x1B[31m",
664
+ bold: "\x1B[1m",
665
+ dim: "\x1B[2m"
666
+ };
667
+ var RESET = "\x1B[0m";
668
+ function colorsEnabled(cfg, env = process.env) {
669
+ if (env.NO_COLOR)
670
+ return false;
671
+ return cfg.colors !== false;
672
+ }
673
+ function paint(segment, text, ctx) {
674
+ const color = typeof segment.color === "function" ? segment.color(ctx) : segment.color;
675
+ const code = color ? ANSI[color] : undefined;
676
+ return code ? `${code}${text}${RESET}` : text;
677
+ }
678
+ async function renderLine(ctx, cfg) {
679
+ const colorize = colorsEnabled(cfg);
680
+ const parts = [];
681
+ for (const id of cfg.segments) {
682
+ const segment = getSegment(id);
683
+ if (!segment)
684
+ continue;
685
+ try {
686
+ const out = await segment.render(ctx);
687
+ if (out)
688
+ parts.push(colorize ? paint(segment, out, ctx) : out);
689
+ } catch {}
690
+ }
691
+ return parts.join(cfg.separator);
692
+ }
693
+ // package.json
694
+ var package_default = {
695
+ name: "@hasna/statusline",
696
+ version: "0.0.3",
697
+ description: "Tiny composable statusline CLI for AI coding agents \u2014 pre-built toggleable segments for Claude Code, with a provider model for others",
698
+ license: "Apache-2.0",
699
+ type: "module",
700
+ main: "./dist/index.js",
701
+ types: "./dist/index.d.ts",
702
+ bin: {
703
+ statusline: "./dist/cli.js",
704
+ "statusline-mcp": "./dist/mcp/index.js"
705
+ },
706
+ exports: {
707
+ ".": {
708
+ types: "./dist/index.d.ts",
709
+ import: "./dist/index.js"
710
+ },
711
+ "./cli": {
712
+ types: "./dist/cli.d.ts",
713
+ import: "./dist/cli.js"
714
+ },
715
+ "./mcp": {
716
+ types: "./dist/mcp/index.d.ts",
717
+ import: "./dist/mcp/index.js"
718
+ }
719
+ },
720
+ files: [
721
+ "dist",
722
+ "LICENSE",
723
+ "README.md"
724
+ ],
725
+ scripts: {
726
+ build: "rm -rf dist && bun build src/index.ts src/cli.ts src/mcp/index.ts --outdir dist --target bun && tsc -p tsconfig.build.json && chmod +x dist/cli.js dist/mcp/index.js",
727
+ typecheck: "tsc --noEmit",
728
+ test: "bun test",
729
+ check: "bun run typecheck && bun test && bun run build",
730
+ prepack: "bun run build",
731
+ prepublishOnly: "bun run typecheck && bun test && bun run build"
732
+ },
733
+ repository: {
734
+ type: "git",
735
+ url: "git+https://github.com/hasna/statusline.git"
736
+ },
737
+ homepage: "https://github.com/hasna/statusline#readme",
738
+ bugs: {
739
+ url: "https://github.com/hasna/statusline/issues"
740
+ },
741
+ keywords: [
742
+ "statusline",
743
+ "status-bar",
744
+ "claude-code",
745
+ "cli",
746
+ "bun"
747
+ ],
748
+ publishConfig: {
749
+ registry: "https://registry.npmjs.org",
750
+ access: "public"
751
+ },
752
+ engines: {
753
+ bun: ">=1.0.0"
754
+ },
755
+ dependencies: {
756
+ "@modelcontextprotocol/sdk": "^1.12.1",
757
+ zod: "^3.25.76"
758
+ },
759
+ devDependencies: {
760
+ "@types/bun": "^1.2.4",
761
+ typescript: "^5.7.3"
762
+ }
763
+ };
764
+ // src/install.ts
765
+ import { copyFileSync, existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
766
+ import { homedir as homedir3 } from "os";
767
+ import { dirname as dirname2, join as join3, resolve as resolve2 } from "path";
768
+ function defaultSettingsPath(env) {
769
+ return join3(env.HOME || homedir3(), ".claude", "settings.json");
770
+ }
771
+ function claudeSettingsPath(env = process.env) {
772
+ const home2 = env.HOME || homedir3();
773
+ const raw = env.CLAUDE_CONFIG_DIR?.trim();
774
+ if (!raw)
775
+ return defaultSettingsPath(env);
776
+ const configDir = raw === "~" || raw.startsWith("~/") ? join3(home2, raw.slice(1)) : raw;
777
+ return join3(configDir, "settings.json");
778
+ }
779
+ function installClaude(settingsPath, env = process.env) {
780
+ const target = settingsPath ?? claudeSettingsPath(env);
781
+ const binary = Bun.which("statusline") || "statusline";
782
+ let settings = {};
783
+ if (existsSync4(target)) {
784
+ try {
785
+ settings = JSON.parse(readFileSync4(target, "utf8"));
786
+ } catch (error) {
787
+ throw new Error(`${target} is not valid JSON \u2014 fix or move it first`);
788
+ }
789
+ copyFileSync(target, `${target}.bak-statusline`);
790
+ }
791
+ settings.statusLine = { ...settings.statusLine, type: "command", command: `${binary} render` };
792
+ const configDir = dirname2(target);
793
+ if (!existsSync4(configDir)) {
794
+ if (resolve2(target) !== resolve2(defaultSettingsPath(env))) {
795
+ throw new Error(`config dir ${configDir} does not exist \u2014 create the profile first`);
796
+ }
797
+ mkdirSync2(configDir, { recursive: true });
798
+ }
799
+ writeFileSync2(target, JSON.stringify(settings, null, 2) + `
800
+ `);
801
+ return target;
802
+ }
803
+
804
+ // src/index.ts
805
+ var statuslineVersion = package_default.version;
806
+ function listSegments(config = loadConfig()) {
807
+ const enabled = new Set(config.segments);
808
+ return segments.map((segment) => ({
809
+ id: segment.id,
810
+ description: segment.description,
811
+ defaultEnabled: segment.defaultEnabled,
812
+ enabled: enabled.has(segment.id)
813
+ }));
814
+ }
815
+ function requireKnownSegments(ids) {
816
+ const unknown = ids.filter((id) => !getSegment(id));
817
+ if (unknown.length) {
818
+ throw new Error(`unknown segment(s): ${unknown.join(", ")}`);
819
+ }
820
+ return ids;
821
+ }
822
+ function enableSegments(ids, config = loadConfig()) {
823
+ requireKnownSegments(ids);
824
+ const next = { ...config, segments: [...config.segments] };
825
+ const changed = [];
826
+ for (const id of ids) {
827
+ if (!next.segments.includes(id)) {
828
+ next.segments.push(id);
829
+ changed.push(id);
830
+ }
831
+ }
832
+ return { config: next, changed };
833
+ }
834
+ function disableSegments(ids, config = loadConfig()) {
835
+ requireKnownSegments(ids);
836
+ const nextSegments = config.segments.filter((id) => !ids.includes(id));
837
+ return {
838
+ config: { ...config, segments: nextSegments },
839
+ changed: config.segments.filter((id) => ids.includes(id))
840
+ };
841
+ }
842
+ function orderSegments(ids, config = loadConfig()) {
843
+ requireKnownSegments(ids);
844
+ if (ids.length === 0)
845
+ throw new Error("at least one segment id is required");
846
+ return { config: { ...config, segments: [...ids] }, changed: [...ids] };
847
+ }
848
+ function setSeparator(separator, config = loadConfig()) {
849
+ if (!separator)
850
+ throw new Error("separator must be a non-empty string");
851
+ return { config: { ...config, separator }, changed: ["separator"] };
852
+ }
853
+ function setColors(colors, config = loadConfig()) {
854
+ return { config: { ...config, colors }, changed: ["colors"] };
855
+ }
856
+ function resetStatuslineConfig() {
857
+ return defaultConfig();
858
+ }
859
+ async function renderStatusline(input = {}, config = loadConfig()) {
860
+ return renderLine(parseClaudeInput(input), config);
861
+ }
862
+ function sampleClaudeInput(cwd = process.cwd()) {
863
+ return {
864
+ cwd,
865
+ model: { id: "claude-fable-5[1m]", display_name: "Fable" },
866
+ cost: { total_cost_usd: 12.34, total_duration_ms: 5400000, total_lines_added: 42, total_lines_removed: 7 },
867
+ version: statuslineVersion,
868
+ session_id: "preview0-0000-0000-0000-000000000000",
869
+ session_name: "preview thread",
870
+ effort: { level: "high" },
871
+ thinking: { enabled: true },
872
+ rate_limits: { five_hour: { used_percentage: 42 } }
873
+ };
874
+ }
875
+ async function previewStatusline(config = loadConfig(), cwd = process.cwd()) {
876
+ return renderStatusline(sampleClaudeInput(cwd), config);
877
+ }
878
+ function saveUpdatedConfig(result, path = configPath()) {
879
+ saveConfig(result.config, path);
880
+ return result.config;
881
+ }
882
+ export {
883
+ trackedLineCount,
884
+ statuslineVersion,
885
+ setSeparator,
886
+ setColors,
887
+ sessionStateFile,
888
+ sessionConfigDir,
889
+ sessionAccountEmail,
890
+ sessionAccount,
891
+ segments,
892
+ saveUpdatedConfig,
893
+ saveConfig,
894
+ sampleClaudeInput,
895
+ resetStatuslineConfig,
896
+ requireKnownSegments,
897
+ renderStatusline,
898
+ renderLine,
899
+ previewStatusline,
900
+ parseClaudeInput,
901
+ orderSegments,
902
+ money,
903
+ loadConfig,
904
+ listSegments,
905
+ lastCommitEpoch,
906
+ installClaude,
907
+ gitRoot,
908
+ gitProjectName,
909
+ gitBranch,
910
+ getSegment,
911
+ enableSegments,
912
+ disableSegments,
913
+ defaultConfig,
914
+ contextUsage,
915
+ configPath,
916
+ compactNum,
917
+ compactDuration,
918
+ compactAge,
919
+ claudeSettingsPath
920
+ };