@hasna/statusline 0.0.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # statusline
2
+
3
+ Tiny, composable statusline CLI for AI coding agents. Pre-built segments you toggle
4
+ on and off — machine name, project + branch, model, context remaining, session cost,
5
+ and more — rendered as a single line for your agent's status bar.
6
+
7
+ ```
8
+ apple03 · statusline (main) · 12h · 1.2k · fable 5 [1m] · 90% left · $0.04
9
+ ```
10
+
11
+ Zero runtime dependencies. Built with [Bun](https://bun.sh) + TypeScript. Apache-2.0.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ bun install -g @hasna/statusline
17
+ statusline install claude # wires it into ~/.claude/settings.json
18
+ ```
19
+
20
+ That's it — Claude Code picks it up on the next status refresh (no restart needed).
21
+
22
+ ## Segments
23
+
24
+ `statusline list` shows everything available:
25
+
26
+ ```
27
+ [x] machine Machine hostname (short)
28
+ [x] project Project name with current Git branch
29
+ [ ] project-name Project name (omitted when unavailable)
30
+ [ ] git-branch Current Git branch (omitted when unavailable)
31
+ [x] commit-age Time since last commit (compact)
32
+ [x] loc Lines of code tracked by Git (compact)
33
+ [ ] current-dir Current working directory (basename)
34
+ [ ] model Current model name
35
+ [x] model-context Model name with context-size tag (e.g. [1m])
36
+ [ ] context-used Percentage of context window used (omitted when unknown)
37
+ [x] context-remaining Percentage of context window remaining (omitted when unknown)
38
+ [ ] used-tokens Total tokens in the context window (omitted when unknown)
39
+ [x] cost Session cost in USD (omitted when zero)
40
+ [ ] duration Session wall-clock duration
41
+ [ ] lines-changed Lines added/removed this session (omitted when zero)
42
+ [ ] output-style Active output style (omitted when default)
43
+ [ ] agent-version Host agent version (e.g. Claude Code version)
44
+ [ ] session-id Session identifier (short)
45
+ ```
46
+
47
+ ## Usage
48
+
49
+ ```bash
50
+ statusline enable used-tokens duration # turn segments on (appended at the end)
51
+ statusline disable loc # turn segments off
52
+ statusline order machine project model-context cost # exact order = enabled set
53
+ statusline separator " | " # change the separator
54
+ statusline preview # render a sample line from the current dir
55
+ statusline reset # back to defaults
56
+ ```
57
+
58
+ Config lives at `~/.config/statusline/config.json` (override with `$STATUSLINE_CONFIG`):
59
+
60
+ ```json
61
+ {
62
+ "separator": " · ",
63
+ "segments": ["machine", "project", "commit-age", "loc", "model-context", "context-remaining", "cost"]
64
+ }
65
+ ```
66
+
67
+ ## How it works
68
+
69
+ Claude Code pipes a JSON payload (cwd, model, session cost, transcript path, …) to the
70
+ configured `statusLine` command on every status refresh. `statusline render` parses it,
71
+ renders each enabled segment, drops anything unavailable, and prints one line. Segments
72
+ that need more than the payload offers (e.g. `context-remaining`) read the session
73
+ transcript to compute it. A segment failure is never fatal — it's simply omitted.
74
+
75
+ ## Providers
76
+
77
+ | Agent | Status |
78
+ |-------|--------|
79
+ | Claude Code | ✅ `statusline install claude` |
80
+ | OpenCode | ⏳ no statusline/footer hook in its config as of v1.3.x — the renderer is provider-agnostic (`src/providers/`), so an adapter slots in the moment one exists |
81
+ | Codex CLI | Codex ships its own built-in segment picker; no external command hook |
82
+
83
+ Adding a provider means one small parser: agent payload → `StatusContext`
84
+ (`src/providers/types.ts`). PRs welcome.
85
+
86
+ ## Development
87
+
88
+ ```bash
89
+ bun install
90
+ bun test
91
+ echo '{"cwd":"'$PWD'","model":{"id":"claude-fable-5[1m]"}}' | bun src/index.ts render
92
+ ```
93
+
94
+ ## License
95
+
96
+ [Apache-2.0](LICENSE)
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@hasna/statusline",
3
+ "version": "0.0.1",
4
+ "description": "Tiny composable statusline CLI for AI coding agents — pre-built toggleable segments for Claude Code, with a provider model for others",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "bin": {
8
+ "statusline": "./src/index.ts"
9
+ },
10
+ "files": [
11
+ "src",
12
+ "LICENSE",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "test": "bun test"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/hasna/statusline.git"
21
+ },
22
+ "homepage": "https://github.com/hasna/statusline#readme",
23
+ "bugs": {
24
+ "url": "https://github.com/hasna/statusline/issues"
25
+ },
26
+ "keywords": [
27
+ "statusline",
28
+ "status-bar",
29
+ "claude-code",
30
+ "cli",
31
+ "bun"
32
+ ],
33
+ "publishConfig": {
34
+ "registry": "https://registry.npmjs.org",
35
+ "access": "public"
36
+ },
37
+ "engines": {
38
+ "bun": ">=1.0.0"
39
+ }
40
+ }
package/src/config.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+
5
+ export interface StatuslineConfig {
6
+ separator: string;
7
+ /** Ordered list of enabled segment ids. */
8
+ segments: string[];
9
+ }
10
+
11
+ export function defaultConfig(): StatuslineConfig {
12
+ return {
13
+ separator: " · ",
14
+ segments: [
15
+ "machine",
16
+ "project",
17
+ "commit-age",
18
+ "loc",
19
+ "model-context",
20
+ "context-remaining",
21
+ "cost",
22
+ ],
23
+ };
24
+ }
25
+
26
+ export function configPath(): string {
27
+ if (process.env.STATUSLINE_CONFIG) return process.env.STATUSLINE_CONFIG;
28
+ const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config");
29
+ return join(base, "statusline", "config.json");
30
+ }
31
+
32
+ export function loadConfig(): StatuslineConfig {
33
+ const path = configPath();
34
+ if (!existsSync(path)) return defaultConfig();
35
+ try {
36
+ const raw = JSON.parse(readFileSync(path, "utf8"));
37
+ const fallback = defaultConfig();
38
+ return {
39
+ separator: typeof raw.separator === "string" ? raw.separator : fallback.separator,
40
+ segments: Array.isArray(raw.segments)
41
+ ? raw.segments.filter((s: unknown) => typeof s === "string")
42
+ : fallback.segments,
43
+ };
44
+ } catch {
45
+ return defaultConfig();
46
+ }
47
+ }
48
+
49
+ export function saveConfig(cfg: StatuslineConfig): void {
50
+ const path = configPath();
51
+ mkdirSync(dirname(path), { recursive: true });
52
+ writeFileSync(path, JSON.stringify(cfg, null, 2) + "\n");
53
+ }
@@ -0,0 +1,51 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import type { StatusContext } from "./providers/types";
3
+
4
+ export interface ContextUsage {
5
+ /** Tokens currently occupying the context window (input side). */
6
+ used: number;
7
+ /** Output tokens of the latest assistant turn. */
8
+ output: number;
9
+ /** Context window size in tokens. */
10
+ window: number;
11
+ }
12
+
13
+ /**
14
+ * Derive context usage from the session transcript (JSONL). The last
15
+ * assistant entry's usage block reflects what the context window holds.
16
+ */
17
+ export function contextUsage(ctx: StatusContext): ContextUsage | null {
18
+ const path = ctx.transcriptPath;
19
+ if (!path || !existsSync(path)) return null;
20
+ let lines: string[];
21
+ try {
22
+ lines = readFileSync(path, "utf8").split("\n");
23
+ } catch {
24
+ return null;
25
+ }
26
+ for (let i = lines.length - 1; i >= 0; i--) {
27
+ const line = lines[i];
28
+ if (!line || !line.includes('"usage"')) continue;
29
+ try {
30
+ const entry = JSON.parse(line);
31
+ const usage = entry?.message?.usage;
32
+ if (!usage || typeof usage.input_tokens !== "number") continue;
33
+ const used =
34
+ usage.input_tokens +
35
+ (usage.cache_creation_input_tokens || 0) +
36
+ (usage.cache_read_input_tokens || 0);
37
+ return {
38
+ used,
39
+ output: usage.output_tokens || 0,
40
+ window: windowSize(ctx),
41
+ };
42
+ } catch {
43
+ continue;
44
+ }
45
+ }
46
+ return null;
47
+ }
48
+
49
+ function windowSize(ctx: StatusContext): number {
50
+ return ctx.model?.id?.includes("[1m]") ? 1_000_000 : 200_000;
51
+ }
package/src/format.ts ADDED
@@ -0,0 +1,36 @@
1
+ export function compactAge(seconds: number): string {
2
+ if (seconds < 60) return `${Math.floor(seconds)}s`;
3
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
4
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
5
+ if (seconds < 604800) return `${Math.floor(seconds / 86400)}d`;
6
+ if (seconds < 2592000) return `${Math.floor(seconds / 604800)}w`;
7
+ if (seconds < 31536000) return `${Math.floor(seconds / 2592000)}mo`;
8
+ return `${Math.floor(seconds / 31536000)}y`;
9
+ }
10
+
11
+ function trimmed(value: number): string {
12
+ const fixed = value.toFixed(1);
13
+ return fixed.endsWith(".0") ? fixed.slice(0, -2) : fixed;
14
+ }
15
+
16
+ export function compactNum(n: number): string {
17
+ if (n >= 1_000_000) return `${trimmed(n / 1_000_000)}m`;
18
+ if (n >= 10_000) return `${Math.floor(n / 1000)}k`;
19
+ if (n >= 1000) return `${trimmed(n / 1000)}k`;
20
+ return `${n}`;
21
+ }
22
+
23
+ export function money(n: number): string {
24
+ return `$${n.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
25
+ }
26
+
27
+ export function compactDuration(ms: number): string {
28
+ const s = Math.floor(ms / 1000);
29
+ if (s < 60) return `${s}s`;
30
+ if (s < 3600) {
31
+ const rem = s % 60;
32
+ return rem ? `${Math.floor(s / 60)}m${rem}s` : `${Math.floor(s / 60)}m`;
33
+ }
34
+ const rem = Math.floor((s % 3600) / 60);
35
+ return rem ? `${Math.floor(s / 3600)}h${rem}m` : `${Math.floor(s / 3600)}h`;
36
+ }
package/src/git.ts ADDED
@@ -0,0 +1,55 @@
1
+ /** Minimal git helpers — every call degrades to null outside a repo. */
2
+
3
+ function run(cwd: string, args: string[]): string | null {
4
+ try {
5
+ const proc = Bun.spawnSync(["git", "-c", "gc.auto=0", ...args], {
6
+ cwd,
7
+ stdout: "pipe",
8
+ stderr: "ignore",
9
+ });
10
+ if (proc.exitCode !== 0) return null;
11
+ const out = proc.stdout.toString().trim();
12
+ return out.length ? out : null;
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+
18
+ export function gitRoot(cwd: string): string | null {
19
+ return run(cwd, ["rev-parse", "--show-toplevel"]);
20
+ }
21
+
22
+ export function gitBranch(cwd: string): string | null {
23
+ return run(cwd, ["branch", "--show-current"]);
24
+ }
25
+
26
+ export function gitProjectName(cwd: string): string | null {
27
+ const root = gitRoot(cwd);
28
+ if (!root) return null;
29
+ const remote = run(root, ["config", "--get", "remote.origin.url"]);
30
+ if (remote) return remote.replace(/\.git$/, "").split("/").pop() || null;
31
+ return root.split("/").pop() || null;
32
+ }
33
+
34
+ export function lastCommitEpoch(cwd: string): number | null {
35
+ const out = run(cwd, ["log", "-1", "--format=%ct"]);
36
+ if (!out) return null;
37
+ const ts = Number(out);
38
+ return Number.isFinite(ts) ? ts : null;
39
+ }
40
+
41
+ export function trackedLineCount(cwd: string): number | null {
42
+ const root = gitRoot(cwd);
43
+ if (!root) return null;
44
+ try {
45
+ const proc = Bun.spawnSync(
46
+ ["bash", "-c", "git -c gc.auto=0 ls-files -z | xargs -0 wc -l 2>/dev/null | awk 'END {print $1+0}'"],
47
+ { cwd: root, stdout: "pipe", stderr: "ignore" },
48
+ );
49
+ if (proc.exitCode !== 0) return null;
50
+ const n = Number(proc.stdout.toString().trim());
51
+ return Number.isFinite(n) && n > 0 ? n : null;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
package/src/index.ts ADDED
@@ -0,0 +1,143 @@
1
+ #!/usr/bin/env bun
2
+ import { defaultConfig, loadConfig, saveConfig, configPath } from "./config";
3
+ import { parseClaudeInput } from "./providers/claude";
4
+ import { renderLine } from "./render";
5
+ import { segments, getSegment } from "./segments";
6
+ import { installClaude } from "./install";
7
+ import pkg from "../package.json";
8
+
9
+ const [, , command = "render", ...args] = process.argv;
10
+
11
+ async function readStdinJson(): Promise<Record<string, any>> {
12
+ try {
13
+ const text = await Bun.stdin.text();
14
+ return text.trim() ? JSON.parse(text) : {};
15
+ } catch {
16
+ return {};
17
+ }
18
+ }
19
+
20
+ function requireKnown(ids: string[]): string[] {
21
+ const unknown = ids.filter((id) => !getSegment(id));
22
+ if (unknown.length) {
23
+ console.error(`unknown segment(s): ${unknown.join(", ")}\nrun \`statusline list\` to see available segments`);
24
+ process.exit(1);
25
+ }
26
+ return ids;
27
+ }
28
+
29
+ switch (command) {
30
+ case "render": {
31
+ const input = await readStdinJson();
32
+ console.log(await renderLine(parseClaudeInput(input), loadConfig()));
33
+ break;
34
+ }
35
+
36
+ case "list": {
37
+ const enabled = new Set(loadConfig().segments);
38
+ const width = Math.max(...segments.map((s) => s.id.length));
39
+ for (const s of segments) {
40
+ const mark = enabled.has(s.id) ? "[x]" : "[ ]";
41
+ console.log(` ${mark} ${s.id.padEnd(width)} ${s.description}`);
42
+ }
43
+ break;
44
+ }
45
+
46
+ case "enable": {
47
+ const ids = requireKnown(args);
48
+ const cfg = loadConfig();
49
+ for (const id of ids) if (!cfg.segments.includes(id)) cfg.segments.push(id);
50
+ saveConfig(cfg);
51
+ console.log(`enabled: ${ids.join(", ")}\norder: ${cfg.segments.join(", ")}`);
52
+ break;
53
+ }
54
+
55
+ case "disable": {
56
+ const ids = requireKnown(args);
57
+ const cfg = loadConfig();
58
+ cfg.segments = cfg.segments.filter((id) => !ids.includes(id));
59
+ saveConfig(cfg);
60
+ console.log(`disabled: ${ids.join(", ")}\norder: ${cfg.segments.join(", ") || "(none)"}`);
61
+ break;
62
+ }
63
+
64
+ case "order": {
65
+ const ids = requireKnown(args);
66
+ if (!ids.length) {
67
+ console.error("usage: statusline order <segment> [segment...]");
68
+ process.exit(1);
69
+ }
70
+ const cfg = loadConfig();
71
+ cfg.segments = ids;
72
+ saveConfig(cfg);
73
+ console.log(`order: ${cfg.segments.join(", ")}`);
74
+ break;
75
+ }
76
+
77
+ case "separator": {
78
+ if (!args.length) {
79
+ console.error('usage: statusline separator " · "');
80
+ process.exit(1);
81
+ }
82
+ const cfg = loadConfig();
83
+ cfg.separator = args.join(" ");
84
+ saveConfig(cfg);
85
+ console.log(`separator: "${cfg.separator}"`);
86
+ break;
87
+ }
88
+
89
+ case "reset": {
90
+ saveConfig(defaultConfig());
91
+ console.log(`reset to defaults (${configPath()})`);
92
+ break;
93
+ }
94
+
95
+ case "preview": {
96
+ const sample = {
97
+ cwd: process.cwd(),
98
+ model: { id: "claude-fable-5[1m]", display_name: "Fable" },
99
+ cost: { total_cost_usd: 12.34, total_duration_ms: 5400000, total_lines_added: 42, total_lines_removed: 7 },
100
+ version: pkg.version,
101
+ session_id: "preview0-0000-0000-0000-000000000000",
102
+ };
103
+ console.log(await renderLine(parseClaudeInput(sample), loadConfig()));
104
+ break;
105
+ }
106
+
107
+ case "install": {
108
+ const target = args[0] || "claude";
109
+ if (target !== "claude") {
110
+ console.error(`unsupported target "${target}" — only "claude" is supported today (OpenCode has no statusline hook yet)`);
111
+ process.exit(1);
112
+ }
113
+ const path = installClaude();
114
+ console.log(`installed into ${path} — Claude Code picks it up on the next status refresh`);
115
+ break;
116
+ }
117
+
118
+ case "--version":
119
+ case "-v":
120
+ case "version": {
121
+ console.log(pkg.version);
122
+ break;
123
+ }
124
+
125
+ default: {
126
+ console.log(`statusline ${pkg.version} — composable statusline for AI coding agents
127
+
128
+ usage:
129
+ statusline render read agent JSON on stdin, print the statusline (default)
130
+ statusline list show all segments and which are enabled
131
+ statusline enable <id...> enable segments (appended to the end)
132
+ statusline disable <id...> disable segments
133
+ statusline order <id...> set the exact segment order (also defines enabled set)
134
+ statusline separator <str> set the separator (default " · ")
135
+ statusline preview render with a sample payload from the current directory
136
+ statusline reset restore default config
137
+ statusline install [claude] wire into Claude Code (~/.claude/settings.json)
138
+ statusline version print version
139
+
140
+ config: ${configPath()}`);
141
+ if (command !== "help" && command !== "--help" && command !== "-h") process.exit(1);
142
+ }
143
+ }
package/src/install.ts ADDED
@@ -0,0 +1,20 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+
5
+ /**
6
+ * Wire the statusline into Claude Code's user settings. Existing settings
7
+ * are preserved; the previous file is backed up alongside it.
8
+ */
9
+ export function installClaude(settingsPath = join(homedir(), ".claude", "settings.json")): string {
10
+ const binary = Bun.which("statusline") || "statusline";
11
+ let settings: Record<string, any> = {};
12
+ if (existsSync(settingsPath)) {
13
+ settings = JSON.parse(readFileSync(settingsPath, "utf8"));
14
+ copyFileSync(settingsPath, `${settingsPath}.bak-statusline`);
15
+ }
16
+ settings.statusLine = { type: "command", command: `${binary} render` };
17
+ mkdirSync(dirname(settingsPath), { recursive: true });
18
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n");
19
+ return settingsPath;
20
+ }
@@ -0,0 +1,35 @@
1
+ import type { StatusContext } from "./types";
2
+
3
+ /**
4
+ * Parse the JSON payload Claude Code pipes to a `statusLine` command.
5
+ * Every field is optional — a partial or empty payload must still
6
+ * produce a usable context.
7
+ */
8
+ export function parseClaudeInput(input: Record<string, any>): StatusContext {
9
+ const cwd: string =
10
+ input?.cwd || input?.workspace?.current_dir || process.cwd();
11
+ return {
12
+ provider: "claude",
13
+ cwd,
14
+ projectDir: input?.workspace?.project_dir || undefined,
15
+ model: input?.model
16
+ ? { id: input.model.id || undefined, displayName: input.model.display_name || undefined }
17
+ : undefined,
18
+ cost: input?.cost
19
+ ? {
20
+ totalCostUsd: numberOr(input.cost.total_cost_usd),
21
+ totalDurationMs: numberOr(input.cost.total_duration_ms),
22
+ totalLinesAdded: numberOr(input.cost.total_lines_added),
23
+ totalLinesRemoved: numberOr(input.cost.total_lines_removed),
24
+ }
25
+ : undefined,
26
+ transcriptPath: input?.transcript_path || undefined,
27
+ sessionId: input?.session_id || undefined,
28
+ version: input?.version || undefined,
29
+ outputStyle: input?.output_style?.name || undefined,
30
+ };
31
+ }
32
+
33
+ function numberOr(v: unknown): number | undefined {
34
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
35
+ }
@@ -0,0 +1,23 @@
1
+ export interface StatusContext {
2
+ provider: "claude";
3
+ cwd: string;
4
+ projectDir?: string;
5
+ model?: { id?: string; displayName?: string };
6
+ cost?: {
7
+ totalCostUsd?: number;
8
+ totalDurationMs?: number;
9
+ totalLinesAdded?: number;
10
+ totalLinesRemoved?: number;
11
+ };
12
+ transcriptPath?: string;
13
+ sessionId?: string;
14
+ version?: string;
15
+ outputStyle?: string;
16
+ }
17
+
18
+ export interface Segment {
19
+ id: string;
20
+ description: string;
21
+ defaultEnabled: boolean;
22
+ render(ctx: StatusContext): Promise<string | null> | string | null;
23
+ }
package/src/render.ts ADDED
@@ -0,0 +1,19 @@
1
+ import type { StatusContext } from "./providers/types";
2
+ import type { StatuslineConfig } from "./config";
3
+ import { getSegment } from "./segments";
4
+
5
+ /** Render the configured segments; a failing segment is dropped, never fatal. */
6
+ export async function renderLine(ctx: StatusContext, cfg: StatuslineConfig): Promise<string> {
7
+ const parts: string[] = [];
8
+ for (const id of cfg.segments) {
9
+ const segment = getSegment(id);
10
+ if (!segment) continue;
11
+ try {
12
+ const out = await segment.render(ctx);
13
+ if (out) parts.push(out);
14
+ } catch {
15
+ // statuslines must never break the host UI
16
+ }
17
+ }
18
+ return parts.join(cfg.separator);
19
+ }
@@ -0,0 +1,187 @@
1
+ import { hostname } from "node:os";
2
+ import type { Segment, StatusContext } from "../providers/types";
3
+ import { compactAge, compactDuration, compactNum, money } from "../format";
4
+ import { gitBranch, gitProjectName, lastCommitEpoch, trackedLineCount } from "../git";
5
+ import { contextUsage } from "../context-window";
6
+
7
+ /**
8
+ * Format a model id like "claude-fable-5[1m]" or "claude-3-5-sonnet-20241022"
9
+ * into a friendly name ("fable 5", "sonnet 3.5") plus an optional context tag.
10
+ */
11
+ function friendlyModel(id: string): { name: string; tag: string | null } {
12
+ let tag: string | null = null;
13
+ let mid = id;
14
+ const tagMatch = mid.match(/\[([^\]]+)\]$/);
15
+ if (tagMatch) {
16
+ tag = `[${tagMatch[1]}]`;
17
+ mid = mid.slice(0, mid.length - tagMatch[0].length);
18
+ }
19
+ mid = mid.replace(/^claude-/, "").replace(/-\d{8}$/, "");
20
+ const tokens = mid.split("-").filter(Boolean);
21
+ const words = tokens.filter((t) => !/^\d+$/.test(t));
22
+ const nums = tokens.filter((t) => /^\d+$/.test(t));
23
+ const name = [words.join(" "), nums.join(".")].filter(Boolean).join(" ");
24
+ return { name: name || mid, tag };
25
+ }
26
+
27
+ const dir = (ctx: StatusContext) => ctx.cwd || process.cwd();
28
+
29
+ export const segments: Segment[] = [
30
+ {
31
+ id: "machine",
32
+ description: "Machine hostname (short)",
33
+ defaultEnabled: true,
34
+ render: () => hostname().split(".")[0] || null,
35
+ },
36
+ {
37
+ id: "project",
38
+ description: "Project name with current Git branch",
39
+ defaultEnabled: true,
40
+ render(ctx) {
41
+ const name = gitProjectName(dir(ctx)) || dir(ctx).split("/").pop() || null;
42
+ if (!name) return null;
43
+ const branch = gitBranch(dir(ctx));
44
+ return branch ? `${name} (${branch})` : name;
45
+ },
46
+ },
47
+ {
48
+ id: "project-name",
49
+ description: "Project name (omitted when unavailable)",
50
+ defaultEnabled: false,
51
+ render: (ctx) => gitProjectName(dir(ctx)) || dir(ctx).split("/").pop() || null,
52
+ },
53
+ {
54
+ id: "git-branch",
55
+ description: "Current Git branch (omitted when unavailable)",
56
+ defaultEnabled: false,
57
+ render: (ctx) => gitBranch(dir(ctx)),
58
+ },
59
+ {
60
+ id: "commit-age",
61
+ description: "Time since last commit (compact)",
62
+ defaultEnabled: true,
63
+ render(ctx) {
64
+ const ts = lastCommitEpoch(dir(ctx));
65
+ if (!ts) return null;
66
+ return compactAge(Date.now() / 1000 - ts);
67
+ },
68
+ },
69
+ {
70
+ id: "loc",
71
+ description: "Lines of code tracked by Git (compact)",
72
+ defaultEnabled: true,
73
+ render(ctx) {
74
+ const n = trackedLineCount(dir(ctx));
75
+ return n ? compactNum(n) : null;
76
+ },
77
+ },
78
+ {
79
+ id: "current-dir",
80
+ description: "Current working directory (basename)",
81
+ defaultEnabled: false,
82
+ render: (ctx) => dir(ctx).split("/").pop() || null,
83
+ },
84
+ {
85
+ id: "model",
86
+ description: "Current model name",
87
+ defaultEnabled: false,
88
+ render(ctx) {
89
+ if (!ctx.model?.id) return null;
90
+ return friendlyModel(ctx.model.id).name;
91
+ },
92
+ },
93
+ {
94
+ id: "model-context",
95
+ description: "Model name with context-size tag (e.g. [1m])",
96
+ defaultEnabled: true,
97
+ render(ctx) {
98
+ if (!ctx.model?.id) return null;
99
+ const { name, tag } = friendlyModel(ctx.model.id);
100
+ return tag ? `${name} ${tag}` : name;
101
+ },
102
+ },
103
+ {
104
+ id: "context-used",
105
+ description: "Percentage of context window used (omitted when unknown)",
106
+ defaultEnabled: false,
107
+ render(ctx) {
108
+ const u = contextUsage(ctx);
109
+ if (!u) return null;
110
+ return `${Math.min(100, Math.round((u.used / u.window) * 100))}%`;
111
+ },
112
+ },
113
+ {
114
+ id: "context-remaining",
115
+ description: "Percentage of context window remaining (omitted when unknown)",
116
+ defaultEnabled: true,
117
+ render(ctx) {
118
+ const u = contextUsage(ctx);
119
+ if (!u) return null;
120
+ return `${Math.max(0, 100 - Math.round((u.used / u.window) * 100))}% left`;
121
+ },
122
+ },
123
+ {
124
+ id: "used-tokens",
125
+ description: "Total tokens in the context window (omitted when unknown)",
126
+ defaultEnabled: false,
127
+ render(ctx) {
128
+ const u = contextUsage(ctx);
129
+ if (!u) return null;
130
+ return `${compactNum(u.used + u.output)} tok`;
131
+ },
132
+ },
133
+ {
134
+ id: "cost",
135
+ description: "Session cost in USD (omitted when zero)",
136
+ defaultEnabled: true,
137
+ render(ctx) {
138
+ const c = ctx.cost?.totalCostUsd;
139
+ return c ? money(c) : null;
140
+ },
141
+ },
142
+ {
143
+ id: "duration",
144
+ description: "Session wall-clock duration",
145
+ defaultEnabled: false,
146
+ render(ctx) {
147
+ const ms = ctx.cost?.totalDurationMs;
148
+ return ms ? compactDuration(ms) : null;
149
+ },
150
+ },
151
+ {
152
+ id: "lines-changed",
153
+ description: "Lines added/removed this session (omitted when zero)",
154
+ defaultEnabled: false,
155
+ render(ctx) {
156
+ const a = ctx.cost?.totalLinesAdded || 0;
157
+ const r = ctx.cost?.totalLinesRemoved || 0;
158
+ if (!a && !r) return null;
159
+ return `+${a}/-${r}`;
160
+ },
161
+ },
162
+ {
163
+ id: "output-style",
164
+ description: "Active output style (omitted when default)",
165
+ defaultEnabled: false,
166
+ render(ctx) {
167
+ const s = ctx.outputStyle;
168
+ return s && s !== "default" ? s : null;
169
+ },
170
+ },
171
+ {
172
+ id: "agent-version",
173
+ description: "Host agent version (e.g. Claude Code version)",
174
+ defaultEnabled: false,
175
+ render: (ctx) => (ctx.version ? `v${ctx.version}` : null),
176
+ },
177
+ {
178
+ id: "session-id",
179
+ description: "Session identifier (short)",
180
+ defaultEnabled: false,
181
+ render: (ctx) => (ctx.sessionId ? ctx.sessionId.split("-")[0] : null),
182
+ },
183
+ ];
184
+
185
+ export function getSegment(id: string): Segment | undefined {
186
+ return segments.find((s) => s.id === id);
187
+ }