@hasna/statusline 0.0.1 → 0.0.2

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/cli.js ADDED
@@ -0,0 +1,1025 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ function __accessProp(key) {
9
+ return this[key];
10
+ }
11
+ var __toESMCache_node;
12
+ var __toESMCache_esm;
13
+ var __toESM = (mod, isNodeMode, target) => {
14
+ var canCache = mod != null && typeof mod === "object";
15
+ if (canCache) {
16
+ var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
17
+ var cached = cache.get(mod);
18
+ if (cached)
19
+ return cached;
20
+ }
21
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
22
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
23
+ for (let key of __getOwnPropNames(mod))
24
+ if (!__hasOwnProp.call(to, key))
25
+ __defProp(to, key, {
26
+ get: __accessProp.bind(mod, key),
27
+ enumerable: true
28
+ });
29
+ if (canCache)
30
+ cache.set(mod, to);
31
+ return to;
32
+ };
33
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
34
+ var __returnValue = (v) => v;
35
+ function __exportSetter(name, newValue) {
36
+ this[name] = __returnValue.bind(null, newValue);
37
+ }
38
+ var __export = (target, all) => {
39
+ for (var name in all)
40
+ __defProp(target, name, {
41
+ get: all[name],
42
+ enumerable: true,
43
+ configurable: true,
44
+ set: __exportSetter.bind(all, name)
45
+ });
46
+ };
47
+
48
+ // src/config.ts
49
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
50
+ import { homedir } from "os";
51
+ import { dirname, join } from "path";
52
+ function defaultConfig() {
53
+ return {
54
+ separator: " \xB7 ",
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
+ };
84
+ } catch {
85
+ return defaultConfig();
86
+ }
87
+ }
88
+ function saveConfig(cfg, path = configPath()) {
89
+ mkdirSync(dirname(path), { recursive: true });
90
+ writeFileSync(path, JSON.stringify(cfg, null, 2) + `
91
+ `);
92
+ }
93
+
94
+ // src/providers/claude.ts
95
+ function parseClaudeInput(input) {
96
+ const cwd = input?.cwd || input?.workspace?.current_dir || process.cwd();
97
+ return {
98
+ provider: "claude",
99
+ cwd,
100
+ projectDir: input?.workspace?.project_dir || undefined,
101
+ model: input?.model ? { id: input.model.id || undefined, displayName: input.model.display_name || undefined } : undefined,
102
+ cost: input?.cost ? {
103
+ totalCostUsd: numberOr(input.cost.total_cost_usd),
104
+ totalDurationMs: numberOr(input.cost.total_duration_ms),
105
+ totalLinesAdded: numberOr(input.cost.total_lines_added),
106
+ totalLinesRemoved: numberOr(input.cost.total_lines_removed)
107
+ } : undefined,
108
+ transcriptPath: input?.transcript_path || undefined,
109
+ sessionId: input?.session_id || undefined,
110
+ version: input?.version || undefined,
111
+ outputStyle: input?.output_style?.name || undefined
112
+ };
113
+ }
114
+ function numberOr(v) {
115
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
116
+ }
117
+
118
+ // src/segments/index.ts
119
+ import { hostname } from "os";
120
+
121
+ // src/format.ts
122
+ function compactAge(seconds) {
123
+ if (seconds < 60)
124
+ return `${Math.floor(seconds)}s`;
125
+ if (seconds < 3600)
126
+ return `${Math.floor(seconds / 60)}m`;
127
+ if (seconds < 86400)
128
+ return `${Math.floor(seconds / 3600)}h`;
129
+ if (seconds < 604800)
130
+ return `${Math.floor(seconds / 86400)}d`;
131
+ if (seconds < 2592000)
132
+ return `${Math.floor(seconds / 604800)}w`;
133
+ if (seconds < 31536000)
134
+ return `${Math.floor(seconds / 2592000)}mo`;
135
+ return `${Math.floor(seconds / 31536000)}y`;
136
+ }
137
+ function trimmed(value) {
138
+ const fixed = value.toFixed(1);
139
+ return fixed.endsWith(".0") ? fixed.slice(0, -2) : fixed;
140
+ }
141
+ function compactNum(n) {
142
+ if (n >= 1e6)
143
+ return `${trimmed(n / 1e6)}m`;
144
+ if (n >= 1e4)
145
+ return `${Math.floor(n / 1000)}k`;
146
+ if (n >= 1000)
147
+ return `${trimmed(n / 1000)}k`;
148
+ return `${n}`;
149
+ }
150
+ function money(n) {
151
+ return `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
152
+ }
153
+ function compactDuration(ms) {
154
+ const s = Math.floor(ms / 1000);
155
+ if (s < 60)
156
+ return `${s}s`;
157
+ if (s < 3600) {
158
+ const rem2 = s % 60;
159
+ return rem2 ? `${Math.floor(s / 60)}m${rem2}s` : `${Math.floor(s / 60)}m`;
160
+ }
161
+ const rem = Math.floor(s % 3600 / 60);
162
+ return rem ? `${Math.floor(s / 3600)}h${rem}m` : `${Math.floor(s / 3600)}h`;
163
+ }
164
+
165
+ // src/git.ts
166
+ function run(cwd, args) {
167
+ try {
168
+ const proc = Bun.spawnSync(["git", "-c", "gc.auto=0", ...args], {
169
+ cwd,
170
+ stdout: "pipe",
171
+ stderr: "ignore"
172
+ });
173
+ if (proc.exitCode !== 0)
174
+ return null;
175
+ const out = proc.stdout.toString().trim();
176
+ return out.length ? out : null;
177
+ } catch {
178
+ return null;
179
+ }
180
+ }
181
+ function gitRoot(cwd) {
182
+ return run(cwd, ["rev-parse", "--show-toplevel"]);
183
+ }
184
+ function gitBranch(cwd) {
185
+ return run(cwd, ["branch", "--show-current"]);
186
+ }
187
+ function gitProjectName(cwd) {
188
+ const root = gitRoot(cwd);
189
+ if (!root)
190
+ return null;
191
+ const remote = run(root, ["config", "--get", "remote.origin.url"]);
192
+ if (remote)
193
+ return remote.replace(/\.git$/, "").split("/").pop() || null;
194
+ return root.split("/").pop() || null;
195
+ }
196
+ function lastCommitEpoch(cwd) {
197
+ const out = run(cwd, ["log", "-1", "--format=%ct"]);
198
+ if (!out)
199
+ return null;
200
+ const ts = Number(out);
201
+ return Number.isFinite(ts) ? ts : null;
202
+ }
203
+ function trackedLineCount(cwd) {
204
+ const root = gitRoot(cwd);
205
+ if (!root)
206
+ return null;
207
+ try {
208
+ 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" });
209
+ if (proc.exitCode !== 0)
210
+ return null;
211
+ const n = Number(proc.stdout.toString().trim());
212
+ return Number.isFinite(n) && n > 0 ? n : null;
213
+ } catch {
214
+ return null;
215
+ }
216
+ }
217
+
218
+ // src/context-window.ts
219
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
220
+ function contextUsage(ctx) {
221
+ const path = ctx.transcriptPath;
222
+ if (!path || !existsSync2(path))
223
+ return null;
224
+ let lines;
225
+ try {
226
+ lines = readFileSync2(path, "utf8").split(`
227
+ `);
228
+ } catch {
229
+ return null;
230
+ }
231
+ for (let i = lines.length - 1;i >= 0; i--) {
232
+ const line = lines[i];
233
+ if (!line || !line.includes('"usage"'))
234
+ continue;
235
+ try {
236
+ const entry = JSON.parse(line);
237
+ const usage = entry?.message?.usage;
238
+ if (!usage || typeof usage.input_tokens !== "number")
239
+ continue;
240
+ const used = usage.input_tokens + (usage.cache_creation_input_tokens || 0) + (usage.cache_read_input_tokens || 0);
241
+ return {
242
+ used,
243
+ output: usage.output_tokens || 0,
244
+ window: windowSize(ctx)
245
+ };
246
+ } catch {
247
+ continue;
248
+ }
249
+ }
250
+ return null;
251
+ }
252
+ function windowSize(ctx) {
253
+ return ctx.model?.id?.includes("[1m]") ? 1e6 : 200000;
254
+ }
255
+
256
+ // src/segments/index.ts
257
+ function friendlyModel(id) {
258
+ let tag = null;
259
+ let mid = id;
260
+ const tagMatch = mid.match(/\[([^\]]+)\]$/);
261
+ if (tagMatch) {
262
+ tag = `[${tagMatch[1]}]`;
263
+ mid = mid.slice(0, mid.length - tagMatch[0].length);
264
+ }
265
+ mid = mid.replace(/^claude-/, "").replace(/-\d{8}$/, "");
266
+ const tokens = mid.split("-").filter(Boolean);
267
+ const words = tokens.filter((t) => !/^\d+$/.test(t));
268
+ const nums = tokens.filter((t) => /^\d+$/.test(t));
269
+ const name = [words.join(" "), nums.join(".")].filter(Boolean).join(" ");
270
+ return { name: name || mid, tag };
271
+ }
272
+ var dir = (ctx) => ctx.cwd || process.cwd();
273
+ var segments = [
274
+ {
275
+ id: "machine",
276
+ description: "Machine hostname (short)",
277
+ defaultEnabled: true,
278
+ render: () => hostname().split(".")[0] || null
279
+ },
280
+ {
281
+ id: "project",
282
+ description: "Project name with current Git branch",
283
+ defaultEnabled: true,
284
+ render(ctx) {
285
+ const name = gitProjectName(dir(ctx)) || dir(ctx).split("/").pop() || null;
286
+ if (!name)
287
+ return null;
288
+ const branch = gitBranch(dir(ctx));
289
+ return branch ? `${name} (${branch})` : name;
290
+ }
291
+ },
292
+ {
293
+ id: "project-name",
294
+ description: "Project name (omitted when unavailable)",
295
+ defaultEnabled: false,
296
+ render: (ctx) => gitProjectName(dir(ctx)) || dir(ctx).split("/").pop() || null
297
+ },
298
+ {
299
+ id: "git-branch",
300
+ description: "Current Git branch (omitted when unavailable)",
301
+ defaultEnabled: false,
302
+ render: (ctx) => gitBranch(dir(ctx))
303
+ },
304
+ {
305
+ id: "commit-age",
306
+ description: "Time since last commit (compact)",
307
+ defaultEnabled: true,
308
+ render(ctx) {
309
+ const ts = lastCommitEpoch(dir(ctx));
310
+ if (!ts)
311
+ return null;
312
+ return compactAge(Date.now() / 1000 - ts);
313
+ }
314
+ },
315
+ {
316
+ id: "loc",
317
+ description: "Lines of code tracked by Git (compact)",
318
+ defaultEnabled: true,
319
+ render(ctx) {
320
+ const n = trackedLineCount(dir(ctx));
321
+ return n ? compactNum(n) : null;
322
+ }
323
+ },
324
+ {
325
+ id: "current-dir",
326
+ description: "Current working directory (basename)",
327
+ defaultEnabled: false,
328
+ render: (ctx) => dir(ctx).split("/").pop() || null
329
+ },
330
+ {
331
+ id: "model",
332
+ description: "Current model name",
333
+ defaultEnabled: false,
334
+ render(ctx) {
335
+ if (!ctx.model?.id)
336
+ return null;
337
+ return friendlyModel(ctx.model.id).name;
338
+ }
339
+ },
340
+ {
341
+ id: "model-context",
342
+ description: "Model name with context-size tag (e.g. [1m])",
343
+ defaultEnabled: true,
344
+ render(ctx) {
345
+ if (!ctx.model?.id)
346
+ return null;
347
+ const { name, tag } = friendlyModel(ctx.model.id);
348
+ return tag ? `${name} ${tag}` : name;
349
+ }
350
+ },
351
+ {
352
+ id: "context-used",
353
+ description: "Percentage of context window used (omitted when unknown)",
354
+ defaultEnabled: false,
355
+ render(ctx) {
356
+ const u = contextUsage(ctx);
357
+ if (!u)
358
+ return null;
359
+ return `${Math.min(100, Math.round(u.used / u.window * 100))}%`;
360
+ }
361
+ },
362
+ {
363
+ id: "context-remaining",
364
+ description: "Percentage of context window remaining (omitted when unknown)",
365
+ defaultEnabled: true,
366
+ render(ctx) {
367
+ const u = contextUsage(ctx);
368
+ if (!u)
369
+ return null;
370
+ return `${Math.max(0, 100 - Math.round(u.used / u.window * 100))}% left`;
371
+ }
372
+ },
373
+ {
374
+ id: "used-tokens",
375
+ description: "Total tokens in the context window (omitted when unknown)",
376
+ defaultEnabled: false,
377
+ render(ctx) {
378
+ const u = contextUsage(ctx);
379
+ if (!u)
380
+ return null;
381
+ return `${compactNum(u.used + u.output)} tok`;
382
+ }
383
+ },
384
+ {
385
+ id: "cost",
386
+ description: "Session cost in USD (omitted when zero)",
387
+ defaultEnabled: true,
388
+ render(ctx) {
389
+ const c = ctx.cost?.totalCostUsd;
390
+ return c ? money(c) : null;
391
+ }
392
+ },
393
+ {
394
+ id: "duration",
395
+ description: "Session wall-clock duration",
396
+ defaultEnabled: false,
397
+ render(ctx) {
398
+ const ms = ctx.cost?.totalDurationMs;
399
+ return ms ? compactDuration(ms) : null;
400
+ }
401
+ },
402
+ {
403
+ id: "lines-changed",
404
+ description: "Lines added/removed this session (omitted when zero)",
405
+ defaultEnabled: false,
406
+ render(ctx) {
407
+ const a = ctx.cost?.totalLinesAdded || 0;
408
+ const r = ctx.cost?.totalLinesRemoved || 0;
409
+ if (!a && !r)
410
+ return null;
411
+ return `+${a}/-${r}`;
412
+ }
413
+ },
414
+ {
415
+ id: "output-style",
416
+ description: "Active output style (omitted when default)",
417
+ defaultEnabled: false,
418
+ render(ctx) {
419
+ const s = ctx.outputStyle;
420
+ return s && s !== "default" ? s : null;
421
+ }
422
+ },
423
+ {
424
+ id: "agent-version",
425
+ description: "Host agent version (e.g. Claude Code version)",
426
+ defaultEnabled: false,
427
+ render: (ctx) => ctx.version ? `v${ctx.version}` : null
428
+ },
429
+ {
430
+ id: "session-id",
431
+ description: "Session identifier (short)",
432
+ defaultEnabled: false,
433
+ render: (ctx) => ctx.sessionId ? ctx.sessionId.split("-")[0] : null
434
+ }
435
+ ];
436
+ function getSegment(id) {
437
+ return segments.find((s) => s.id === id);
438
+ }
439
+
440
+ // src/render.ts
441
+ async function renderLine(ctx, cfg) {
442
+ const parts = [];
443
+ for (const id of cfg.segments) {
444
+ const segment = getSegment(id);
445
+ if (!segment)
446
+ continue;
447
+ try {
448
+ const out = await segment.render(ctx);
449
+ if (out)
450
+ parts.push(out);
451
+ } catch {}
452
+ }
453
+ return parts.join(cfg.separator);
454
+ }
455
+ // package.json
456
+ var package_default = {
457
+ name: "@hasna/statusline",
458
+ version: "0.0.2",
459
+ description: "Tiny composable statusline CLI for AI coding agents \u2014 pre-built toggleable segments for Claude Code, with a provider model for others",
460
+ license: "Apache-2.0",
461
+ type: "module",
462
+ main: "./dist/index.js",
463
+ types: "./dist/index.d.ts",
464
+ bin: {
465
+ statusline: "./dist/cli.js",
466
+ "statusline-mcp": "./dist/mcp/index.js"
467
+ },
468
+ exports: {
469
+ ".": {
470
+ types: "./dist/index.d.ts",
471
+ import: "./dist/index.js"
472
+ },
473
+ "./cli": {
474
+ types: "./dist/cli.d.ts",
475
+ import: "./dist/cli.js"
476
+ },
477
+ "./mcp": {
478
+ types: "./dist/mcp/index.d.ts",
479
+ import: "./dist/mcp/index.js"
480
+ }
481
+ },
482
+ files: [
483
+ "dist",
484
+ "LICENSE",
485
+ "README.md"
486
+ ],
487
+ scripts: {
488
+ 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",
489
+ typecheck: "tsc --noEmit",
490
+ test: "bun test",
491
+ check: "bun run typecheck && bun test && bun run build",
492
+ prepack: "bun run build",
493
+ prepublishOnly: "bun run typecheck && bun test && bun run build"
494
+ },
495
+ repository: {
496
+ type: "git",
497
+ url: "git+https://github.com/hasna/statusline.git"
498
+ },
499
+ homepage: "https://github.com/hasna/statusline#readme",
500
+ bugs: {
501
+ url: "https://github.com/hasna/statusline/issues"
502
+ },
503
+ keywords: [
504
+ "statusline",
505
+ "status-bar",
506
+ "claude-code",
507
+ "cli",
508
+ "bun"
509
+ ],
510
+ publishConfig: {
511
+ registry: "https://registry.npmjs.org",
512
+ access: "public"
513
+ },
514
+ engines: {
515
+ bun: ">=1.0.0"
516
+ },
517
+ dependencies: {
518
+ "@modelcontextprotocol/sdk": "^1.12.1",
519
+ zod: "^3.25.76"
520
+ },
521
+ devDependencies: {
522
+ "@types/bun": "^1.2.4",
523
+ typescript: "^5.7.3"
524
+ }
525
+ };
526
+ // src/install.ts
527
+ import { copyFileSync, existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
528
+ import { homedir as homedir2 } from "os";
529
+ import { dirname as dirname2, join as join2 } from "path";
530
+ function installClaude(settingsPath = join2(homedir2(), ".claude", "settings.json")) {
531
+ const binary = Bun.which("statusline") || "statusline";
532
+ let settings = {};
533
+ if (existsSync3(settingsPath)) {
534
+ settings = JSON.parse(readFileSync3(settingsPath, "utf8"));
535
+ copyFileSync(settingsPath, `${settingsPath}.bak-statusline`);
536
+ }
537
+ settings.statusLine = { type: "command", command: `${binary} render` };
538
+ mkdirSync2(dirname2(settingsPath), { recursive: true });
539
+ writeFileSync2(settingsPath, JSON.stringify(settings, null, 2) + `
540
+ `);
541
+ return settingsPath;
542
+ }
543
+
544
+ // src/index.ts
545
+ var statuslineVersion = package_default.version;
546
+ function listSegments(config = loadConfig()) {
547
+ const enabled = new Set(config.segments);
548
+ return segments.map((segment) => ({
549
+ id: segment.id,
550
+ description: segment.description,
551
+ defaultEnabled: segment.defaultEnabled,
552
+ enabled: enabled.has(segment.id)
553
+ }));
554
+ }
555
+ function requireKnownSegments(ids) {
556
+ const unknown = ids.filter((id) => !getSegment(id));
557
+ if (unknown.length) {
558
+ throw new Error(`unknown segment(s): ${unknown.join(", ")}`);
559
+ }
560
+ return ids;
561
+ }
562
+ function enableSegments(ids, config = loadConfig()) {
563
+ requireKnownSegments(ids);
564
+ const next = { ...config, segments: [...config.segments] };
565
+ const changed = [];
566
+ for (const id of ids) {
567
+ if (!next.segments.includes(id)) {
568
+ next.segments.push(id);
569
+ changed.push(id);
570
+ }
571
+ }
572
+ return { config: next, changed };
573
+ }
574
+ function disableSegments(ids, config = loadConfig()) {
575
+ requireKnownSegments(ids);
576
+ const nextSegments = config.segments.filter((id) => !ids.includes(id));
577
+ return {
578
+ config: { ...config, segments: nextSegments },
579
+ changed: config.segments.filter((id) => ids.includes(id))
580
+ };
581
+ }
582
+ function orderSegments(ids, config = loadConfig()) {
583
+ requireKnownSegments(ids);
584
+ if (ids.length === 0)
585
+ throw new Error("at least one segment id is required");
586
+ return { config: { ...config, segments: [...ids] }, changed: [...ids] };
587
+ }
588
+ function setSeparator(separator, config = loadConfig()) {
589
+ if (!separator)
590
+ throw new Error("separator must be a non-empty string");
591
+ return { config: { ...config, separator }, changed: ["separator"] };
592
+ }
593
+ function resetStatuslineConfig() {
594
+ return defaultConfig();
595
+ }
596
+ async function renderStatusline(input = {}, config = loadConfig()) {
597
+ return renderLine(parseClaudeInput(input), config);
598
+ }
599
+ function sampleClaudeInput(cwd = process.cwd()) {
600
+ return {
601
+ cwd,
602
+ model: { id: "claude-fable-5[1m]", display_name: "Fable" },
603
+ cost: { total_cost_usd: 12.34, total_duration_ms: 5400000, total_lines_added: 42, total_lines_removed: 7 },
604
+ version: statuslineVersion,
605
+ session_id: "preview0-0000-0000-0000-000000000000"
606
+ };
607
+ }
608
+ async function previewStatusline(config = loadConfig(), cwd = process.cwd()) {
609
+ return renderStatusline(sampleClaudeInput(cwd), config);
610
+ }
611
+ function saveUpdatedConfig(result, path = configPath()) {
612
+ saveConfig(result.config, path);
613
+ return result.config;
614
+ }
615
+
616
+ // src/cli.ts
617
+ var DEFAULT_LIST_LIMIT = 12;
618
+ async function readStdinJson() {
619
+ try {
620
+ const text = await Bun.stdin.text();
621
+ return text.trim() ? JSON.parse(text) : {};
622
+ } catch {
623
+ return {};
624
+ }
625
+ }
626
+ function printError(error) {
627
+ console.error(error instanceof Error ? error.message : String(error));
628
+ process.exitCode = 1;
629
+ }
630
+ function printSegmentError(error) {
631
+ const message = error instanceof Error ? error.message : String(error);
632
+ if (message.startsWith("unknown segment")) {
633
+ console.error(`${message}
634
+ run \`statusline list\` to see available segments`);
635
+ } else {
636
+ console.error(message);
637
+ }
638
+ process.exitCode = 1;
639
+ }
640
+ function help() {
641
+ return `statusline ${statuslineVersion} \u2014 composable statusline for AI coding agents
642
+
643
+ usage:
644
+ statusline render read agent JSON on stdin, print the statusline (default)
645
+ statusline list compact segment list (default limit: ${DEFAULT_LIST_LIMIT})
646
+ statusline list --verbose include descriptions
647
+ statusline list --all show all rows
648
+ statusline list --json machine-readable segment list
649
+ statusline list --limit N cap rows explicitly
650
+ statusline list --enabled show only enabled segments
651
+ statusline list --disabled show only disabled segments
652
+ statusline list --search text filter by id or description
653
+ statusline search <text> alias for list --search
654
+ statusline show <id> show one segment in detail
655
+ statusline show <id> --json machine-readable segment detail
656
+ statusline inspect <id> alias for show
657
+ statusline enable <id...> enable segments (appended to the end)
658
+ statusline disable <id...> disable segments
659
+ statusline order <id...> set the exact segment order (also defines enabled set)
660
+ statusline separator <str> set the separator (default " \xB7 ")
661
+ statusline preview render with a sample payload from the current directory
662
+ statusline reset restore default config
663
+ statusline install [claude] wire into Claude Code (~/.claude/settings.json)
664
+ statusline version print version
665
+
666
+ config: ${configPath()}`;
667
+ }
668
+ function fail(message) {
669
+ console.error(message);
670
+ process.exit(1);
671
+ }
672
+ function printListHelp() {
673
+ console.log(`usage: statusline list [options] [search text]
674
+
675
+ options:
676
+ --all show all matching rows
677
+ --enabled show only enabled segments
678
+ --disabled show only disabled segments
679
+ --json, -j output structured JSON
680
+ --limit <n> cap rows
681
+ --search, -s <q> filter by id or description
682
+ --verbose include descriptions
683
+ --help, -h show this help`);
684
+ process.exit(0);
685
+ }
686
+ function printSearchHelp() {
687
+ console.log(`usage: statusline search <text> [options]
688
+
689
+ options:
690
+ --all show all matching rows
691
+ --enabled show only enabled segments
692
+ --disabled show only disabled segments
693
+ --json, -j output structured JSON
694
+ --limit <n> cap rows
695
+ --verbose include descriptions
696
+ --help, -h show this help`);
697
+ process.exit(0);
698
+ }
699
+ function printShowHelp() {
700
+ console.log(`usage: statusline show <segment> [options]
701
+
702
+ options:
703
+ --json, -j output structured JSON
704
+ --help, -h show this help`);
705
+ process.exit(0);
706
+ }
707
+ function readFlagValue(raw, index, flag) {
708
+ const value = raw[index + 1];
709
+ if (!value || value.startsWith("-"))
710
+ fail(`missing value for ${flag}`);
711
+ return value;
712
+ }
713
+ function parsePositiveInt(value, flag) {
714
+ if (!value)
715
+ fail(`missing value for ${flag}`);
716
+ const n = Number(value);
717
+ if (!Number.isInteger(n) || n < 1)
718
+ fail(`${flag} must be a positive integer`);
719
+ return n;
720
+ }
721
+ function parseListArgs(raw) {
722
+ const opts = {
723
+ all: false,
724
+ disabledOnly: false,
725
+ enabledOnly: false,
726
+ json: false,
727
+ limit: null,
728
+ query: null,
729
+ verbose: false
730
+ };
731
+ const queryParts = [];
732
+ for (let i = 0;i < raw.length; i++) {
733
+ const arg = raw[i];
734
+ switch (arg) {
735
+ case "--all":
736
+ opts.all = true;
737
+ break;
738
+ case "--disabled":
739
+ opts.disabledOnly = true;
740
+ break;
741
+ case "--enabled":
742
+ opts.enabledOnly = true;
743
+ break;
744
+ case "--json":
745
+ case "-j":
746
+ opts.json = true;
747
+ break;
748
+ case "--limit":
749
+ opts.limit = parsePositiveInt(readFlagValue(raw, i, "--limit"), "--limit");
750
+ i++;
751
+ break;
752
+ case "--search":
753
+ case "-s":
754
+ queryParts.push(readFlagValue(raw, i, arg));
755
+ i++;
756
+ break;
757
+ case "--verbose":
758
+ opts.verbose = true;
759
+ break;
760
+ case "--help":
761
+ case "-h":
762
+ printListHelp();
763
+ default:
764
+ if (arg.startsWith("-"))
765
+ fail(`unknown option for list: ${arg}`);
766
+ queryParts.push(arg);
767
+ }
768
+ }
769
+ if (opts.enabledOnly && opts.disabledOnly)
770
+ fail("use only one of --enabled or --disabled");
771
+ if (opts.all && opts.limit !== null)
772
+ fail("use only one of --all or --limit");
773
+ opts.query = queryParts.length ? queryParts.join(" ").toLowerCase() : null;
774
+ return opts;
775
+ }
776
+ function parseShowArgs(raw) {
777
+ let id = null;
778
+ let json = false;
779
+ for (const arg of raw) {
780
+ if (arg === "--json" || arg === "-j") {
781
+ json = true;
782
+ } else if (arg === "--help" || arg === "-h") {
783
+ printShowHelp();
784
+ } else if (arg.startsWith("-")) {
785
+ fail(`unknown option for show: ${arg}`);
786
+ } else if (!id) {
787
+ id = arg;
788
+ } else {
789
+ fail("usage: statusline show <segment> [--json]");
790
+ }
791
+ }
792
+ return { id, json };
793
+ }
794
+ function searchArgsForList(raw) {
795
+ const queryParts = [];
796
+ const forwarded = [];
797
+ for (let i = 0;i < raw.length; i++) {
798
+ const arg = raw[i];
799
+ switch (arg) {
800
+ case "--all":
801
+ case "--disabled":
802
+ case "--enabled":
803
+ case "--json":
804
+ case "-j":
805
+ case "--verbose":
806
+ forwarded.push(arg);
807
+ break;
808
+ case "--help":
809
+ case "-h":
810
+ printSearchHelp();
811
+ case "--limit":
812
+ forwarded.push(arg, readFlagValue(raw, i, "--limit"));
813
+ i++;
814
+ break;
815
+ default:
816
+ if (arg.startsWith("-"))
817
+ fail(`unknown option for search: ${arg}`);
818
+ queryParts.push(arg);
819
+ }
820
+ }
821
+ if (!queryParts.length)
822
+ fail("usage: statusline search <text> [--json] [--verbose] [--limit N]");
823
+ return ["--search", queryParts.join(" "), ...forwarded];
824
+ }
825
+ function filteredSegments(all, opts) {
826
+ return all.filter((s) => {
827
+ if (opts.enabledOnly && !s.enabled)
828
+ return false;
829
+ if (opts.disabledOnly && s.enabled)
830
+ return false;
831
+ if (!opts.query)
832
+ return true;
833
+ return `${s.id} ${s.description}`.toLowerCase().includes(opts.query);
834
+ });
835
+ }
836
+ function prioritizeEnabled(rows) {
837
+ return rows.map((segment, index) => ({ segment, index })).sort((a, b) => Number(b.segment.enabled) - Number(a.segment.enabled) || a.index - b.index).map((entry) => entry.segment);
838
+ }
839
+ function truncate(value, width) {
840
+ return value.length > width ? `${value.slice(0, width - 1)}...` : value;
841
+ }
842
+ function printList(raw) {
843
+ const opts = parseListArgs(raw);
844
+ const all = listSegments(loadConfig());
845
+ const allRows = filteredSegments(all, opts);
846
+ const displayRows = opts.json ? allRows : prioritizeEnabled(allRows);
847
+ const showAll = opts.all || opts.limit === null && opts.json;
848
+ const limit = opts.limit ?? (showAll ? allRows.length : DEFAULT_LIST_LIMIT);
849
+ const rows = displayRows.slice(0, limit);
850
+ const enabledCount = all.filter((s) => s.enabled).length;
851
+ const total = all.length;
852
+ const limited = rows.length < allRows.length;
853
+ if (opts.json) {
854
+ console.log(JSON.stringify({
855
+ total,
856
+ matching: allRows.length,
857
+ showing: rows.length,
858
+ limited,
859
+ segments: rows,
860
+ next: limited ? { all: true, limit: allRows.length } : null
861
+ }, null, 2));
862
+ return;
863
+ }
864
+ const filterLabel = opts.query ? `, query "${opts.query}"` : "";
865
+ console.log(`Segments: ${enabledCount} enabled / ${total} total (showing ${rows.length} of ${allRows.length}${filterLabel})`);
866
+ if (!rows.length) {
867
+ console.log("No matching segments.");
868
+ console.log("Try `statusline list --all` or `statusline list --search <text>`.");
869
+ return;
870
+ }
871
+ const idWidth = Math.max(2, ...rows.map((s) => s.id.length));
872
+ if (opts.verbose) {
873
+ console.log(`state default ${"id".padEnd(idWidth)} description`);
874
+ for (const s of rows) {
875
+ const state = s.enabled ? "on " : "off";
876
+ const def = s.defaultEnabled ? "yes" : "no ";
877
+ console.log(`${state.padEnd(5)} ${def.padEnd(7)} ${s.id.padEnd(idWidth)} ${truncate(s.description, 72)}`);
878
+ }
879
+ } else {
880
+ console.log(`state default ${"id".padEnd(idWidth)}`);
881
+ for (const s of rows) {
882
+ const state = s.enabled ? "on " : "off";
883
+ const def = s.defaultEnabled ? "yes" : "no ";
884
+ console.log(`${state.padEnd(5)} ${def.padEnd(7)} ${s.id.padEnd(idWidth)}`);
885
+ }
886
+ }
887
+ const hints = ["`statusline show <id>` for details", "`--verbose` for descriptions", "`--json` for machines"];
888
+ if (limited)
889
+ hints.unshift("`--all` for all matching rows");
890
+ console.log(`Hint: use ${hints.join(", ")}.`);
891
+ }
892
+ function printShow(raw) {
893
+ const { id, json } = parseShowArgs(raw);
894
+ if (!id)
895
+ fail("usage: statusline show <segment> [--json]");
896
+ const info = listSegments(loadConfig()).find((s) => s.id === id);
897
+ if (!info) {
898
+ console.error(`unknown segment: ${id}`);
899
+ console.error("run `statusline list --all` to see available segments");
900
+ process.exit(1);
901
+ }
902
+ if (json) {
903
+ console.log(JSON.stringify(info, null, 2));
904
+ return;
905
+ }
906
+ console.log(`Segment: ${info.id}`);
907
+ console.log(`State: ${info.enabled ? "enabled" : "disabled"}`);
908
+ console.log(`Default: ${info.defaultEnabled ? "enabled" : "disabled"}`);
909
+ console.log(`Description: ${info.description}`);
910
+ console.log(`Commands: statusline ${info.enabled ? "disable" : "enable"} ${info.id} | statusline list --search ${info.id}`);
911
+ }
912
+ async function runCli(argv = process.argv.slice(2)) {
913
+ const [command = "render", ...args] = argv;
914
+ try {
915
+ switch (command) {
916
+ case "render": {
917
+ console.log(await renderStatusline(await readStdinJson(), loadConfig()));
918
+ return;
919
+ }
920
+ case "list": {
921
+ printList(args);
922
+ return;
923
+ }
924
+ case "search": {
925
+ printList(searchArgsForList(args));
926
+ return;
927
+ }
928
+ case "show":
929
+ case "inspect": {
930
+ printShow(args);
931
+ return;
932
+ }
933
+ case "enable": {
934
+ let result;
935
+ try {
936
+ result = enableSegments(args, loadConfig());
937
+ } catch (error) {
938
+ printSegmentError(error);
939
+ return;
940
+ }
941
+ saveConfig(result.config);
942
+ console.log(`enabled: ${args.join(", ")}
943
+ order: ${result.config.segments.join(", ")}`);
944
+ return;
945
+ }
946
+ case "disable": {
947
+ let result;
948
+ try {
949
+ result = disableSegments(args, loadConfig());
950
+ } catch (error) {
951
+ printSegmentError(error);
952
+ return;
953
+ }
954
+ saveConfig(result.config);
955
+ console.log(`disabled: ${args.join(", ")}
956
+ order: ${result.config.segments.join(", ") || "(none)"}`);
957
+ return;
958
+ }
959
+ case "order": {
960
+ if (!args.length)
961
+ throw new Error("usage: statusline order <segment> [segment...]");
962
+ let result;
963
+ try {
964
+ result = orderSegments(args, loadConfig());
965
+ } catch (error) {
966
+ printSegmentError(error);
967
+ return;
968
+ }
969
+ saveConfig(result.config);
970
+ console.log(`order: ${result.config.segments.join(", ")}`);
971
+ return;
972
+ }
973
+ case "separator": {
974
+ if (!args.length)
975
+ throw new Error('usage: statusline separator " \xB7 "');
976
+ const result = setSeparator(args.join(" "), loadConfig());
977
+ saveConfig(result.config);
978
+ console.log(`separator: "${result.config.separator}"`);
979
+ return;
980
+ }
981
+ case "reset": {
982
+ saveConfig(defaultConfig());
983
+ console.log(`reset to defaults (${configPath()})`);
984
+ return;
985
+ }
986
+ case "preview": {
987
+ console.log(await previewStatusline(loadConfig(), process.cwd()));
988
+ return;
989
+ }
990
+ case "install": {
991
+ const target = args[0] || "claude";
992
+ if (target !== "claude") {
993
+ throw new Error(`unsupported target "${target}" \u2014 only "claude" is supported today (OpenCode has no statusline hook yet)`);
994
+ }
995
+ const path = installClaude();
996
+ console.log(`installed into ${path} \u2014 Claude Code picks it up on the next status refresh`);
997
+ return;
998
+ }
999
+ case "--version":
1000
+ case "-v":
1001
+ case "version": {
1002
+ console.log(statuslineVersion);
1003
+ return;
1004
+ }
1005
+ case "help":
1006
+ case "--help":
1007
+ case "-h": {
1008
+ console.log(help());
1009
+ return;
1010
+ }
1011
+ default: {
1012
+ console.log(help());
1013
+ process.exitCode = 1;
1014
+ }
1015
+ }
1016
+ } catch (error) {
1017
+ printError(error);
1018
+ }
1019
+ }
1020
+ if (import.meta.main) {
1021
+ await runCli();
1022
+ }
1023
+ export {
1024
+ runCli
1025
+ };