glintline 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +278 -0
- package/INSTALL.md +214 -0
- package/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/glintline.js +7 -0
- package/glintline.example.json +38 -0
- package/package.json +54 -4
- package/src/ansi.ts +35 -0
- package/src/cache.ts +42 -0
- package/src/config.ts +209 -0
- package/src/context.ts +64 -0
- package/src/credentials.ts +46 -0
- package/src/debug.ts +9 -0
- package/src/format.ts +109 -0
- package/src/git.ts +68 -0
- package/src/index.ts +100 -0
- package/src/model.ts +120 -0
- package/src/render.ts +176 -0
- package/src/transcript.ts +240 -0
- package/src/types.ts +115 -0
- package/src/usage-api.ts +189 -0
- package/src/usage.ts +63 -0
- package/src/widgets.ts +419 -0
package/src/format.ts
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { c, wrap } from "./ansi";
|
|
2
|
+
|
|
3
|
+
export function formatNumber(n: number): string {
|
|
4
|
+
if (n >= 1_000_000) {
|
|
5
|
+
const m = n / 1_000_000;
|
|
6
|
+
return `${m >= 10 ? m.toFixed(0) : trimZero(m.toFixed(1))}M`;
|
|
7
|
+
}
|
|
8
|
+
if (n >= 1_000) {
|
|
9
|
+
const k = n / 1_000;
|
|
10
|
+
return `${k >= 100 ? k.toFixed(0) : trimZero(k.toFixed(1))}K`;
|
|
11
|
+
}
|
|
12
|
+
return String(n);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function trimZero(s: string): string {
|
|
16
|
+
return s.replace(/\.0$/, "");
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function formatTokens(n: number): string {
|
|
20
|
+
if (n >= 1_000_000) {
|
|
21
|
+
const v = n / 1_000_000;
|
|
22
|
+
return `${v >= 10 ? v.toFixed(0) : trimZero(v.toFixed(1))}M`;
|
|
23
|
+
}
|
|
24
|
+
if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
|
|
25
|
+
return String(n);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function formatDuration(seconds: number): string {
|
|
29
|
+
if (seconds <= 0) return "0m";
|
|
30
|
+
const minutes = seconds / 60;
|
|
31
|
+
if (minutes < 60) return `${Math.round(minutes)}m`;
|
|
32
|
+
const hours = minutes / 60;
|
|
33
|
+
if (hours < 24) {
|
|
34
|
+
return `${hours >= 10 ? Math.round(hours) : trimZero(hours.toFixed(1))}h`;
|
|
35
|
+
}
|
|
36
|
+
const days = hours / 24;
|
|
37
|
+
return `${days >= 10 ? Math.round(days) : trimZero(days.toFixed(1))}d`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Local wall-clock time as HH:MM. Used where a relative countdown would go stale:
|
|
41
|
+
// Claude Code does not redraw the status line while the session sits idle.
|
|
42
|
+
export function formatClock(epochSec: number): string {
|
|
43
|
+
const d = new Date(epochSec * 1000);
|
|
44
|
+
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function colorByPercent(pct: number, calm: boolean = false): string {
|
|
48
|
+
if (pct >= 90) return calm ? c.mutedRed : c.red;
|
|
49
|
+
if (pct >= 75) return calm ? c.mutedYellow : c.yellow;
|
|
50
|
+
return calm ? c.mutedGreen : c.green;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function cacheHitColor(pct: number): string {
|
|
54
|
+
if (pct >= 80) return c.green;
|
|
55
|
+
if (pct >= 50) return c.yellow;
|
|
56
|
+
return c.gray;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function cacheHitRate(cacheRead: number, cacheCreation: number, input: number): number | null {
|
|
60
|
+
const total = cacheRead + cacheCreation + input;
|
|
61
|
+
return total > 0 ? (cacheRead / total) * 100 : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const BAR_PRESETS: Record<string, { full: string; empty: string }> = {
|
|
65
|
+
square: { full: "■", empty: "□" },
|
|
66
|
+
circle: { full: "●", empty: "○" },
|
|
67
|
+
bar: { full: "█", empty: "░" },
|
|
68
|
+
ascii: { full: "#", empty: "-" },
|
|
69
|
+
dots: { full: "⬢", empty: "⬡" },
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export interface ProgressBarOpts {
|
|
73
|
+
full: string;
|
|
74
|
+
empty: string;
|
|
75
|
+
threshold?: number;
|
|
76
|
+
fillEmpty?: boolean;
|
|
77
|
+
calm?: boolean;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function progressBar(
|
|
81
|
+
used: number,
|
|
82
|
+
total: number,
|
|
83
|
+
width: number,
|
|
84
|
+
opts: ProgressBarOpts,
|
|
85
|
+
): string {
|
|
86
|
+
if (total <= 0) return "";
|
|
87
|
+
const { full, empty, threshold, fillEmpty = false, calm = false } = opts;
|
|
88
|
+
const usedRatio = Math.min(1, Math.max(0, used / total));
|
|
89
|
+
const usedCells = Math.round(usedRatio * width);
|
|
90
|
+
const emptyChar = fillEmpty ? full : empty;
|
|
91
|
+
const emptyColor = fillEmpty ? c.darkestGray : c.darkGray;
|
|
92
|
+
|
|
93
|
+
if (threshold !== undefined && threshold > 0 && threshold < total) {
|
|
94
|
+
const pctForColor = (used / threshold) * 100;
|
|
95
|
+
const color = colorByPercent(pctForColor, calm);
|
|
96
|
+
const thresholdCells = Math.round((threshold / total) * width);
|
|
97
|
+
const middleCells = Math.max(0, thresholdCells - usedCells);
|
|
98
|
+
const bufferCells = Math.max(0, width - usedCells - middleCells);
|
|
99
|
+
return (
|
|
100
|
+
wrap(color, full.repeat(usedCells)) +
|
|
101
|
+
wrap(emptyColor, emptyChar.repeat(middleCells)) +
|
|
102
|
+
wrap(c.gray, full.repeat(bufferCells))
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const emptyCount = Math.max(0, width - usedCells);
|
|
107
|
+
const color = colorByPercent(usedRatio * 100, calm);
|
|
108
|
+
return wrap(color, full.repeat(usedCells)) + wrap(emptyColor, emptyChar.repeat(emptyCount));
|
|
109
|
+
}
|
package/src/git.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { debug } from "./debug";
|
|
3
|
+
|
|
4
|
+
const GIT_TIMEOUT_MS = 1500;
|
|
5
|
+
|
|
6
|
+
export interface GitInfo {
|
|
7
|
+
branch: string;
|
|
8
|
+
added: number;
|
|
9
|
+
removed: number;
|
|
10
|
+
dirty: boolean;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function run(args: string[], cwd: string): string {
|
|
14
|
+
return execFileSync("git", args, {
|
|
15
|
+
cwd,
|
|
16
|
+
encoding: "utf8",
|
|
17
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
18
|
+
timeout: GIT_TIMEOUT_MS,
|
|
19
|
+
}).trim();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function gitInfo(cwd: string): GitInfo | null {
|
|
23
|
+
let branch = "";
|
|
24
|
+
try {
|
|
25
|
+
branch = run(["symbolic-ref", "--short", "HEAD"], cwd);
|
|
26
|
+
} catch {
|
|
27
|
+
try {
|
|
28
|
+
branch = run(["rev-parse", "--short", "HEAD"], cwd);
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let added = 0;
|
|
35
|
+
let removed = 0;
|
|
36
|
+
let dirty = false;
|
|
37
|
+
const addNumstat = (out: string) => {
|
|
38
|
+
if (!out) return;
|
|
39
|
+
dirty = true;
|
|
40
|
+
for (const line of out.split("\n")) {
|
|
41
|
+
const [a, r] = line.split("\t");
|
|
42
|
+
const ai = parseInt(a ?? "", 10);
|
|
43
|
+
const ri = parseInt(r ?? "", 10);
|
|
44
|
+
if (Number.isFinite(ai)) added += ai;
|
|
45
|
+
if (Number.isFinite(ri)) removed += ri;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
// Unstaged and staged diffs are run separately so one failing doesn't suppress
|
|
49
|
+
// the others, and so a repo with no commits (unborn HEAD, where `diff HEAD`
|
|
50
|
+
// errors) still reports staged changes via `--cached` against the empty tree.
|
|
51
|
+
try {
|
|
52
|
+
addNumstat(run(["diff", "--numstat"], cwd));
|
|
53
|
+
} catch (e) {
|
|
54
|
+
debug("git.diff", e);
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
addNumstat(run(["diff", "--cached", "--numstat"], cwd));
|
|
58
|
+
} catch (e) {
|
|
59
|
+
debug("git.diffCached", e);
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
if (run(["ls-files", "--others", "--exclude-standard"], cwd)) dirty = true;
|
|
63
|
+
} catch (e) {
|
|
64
|
+
debug("git.untracked", e);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return { branch, added, removed, dirty };
|
|
68
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { writeFileSync } from "node:fs";
|
|
3
|
+
import type { StatusInput } from "./types";
|
|
4
|
+
import { getModelInfo } from "./model";
|
|
5
|
+
import { getContextFromInput, withAutoCompact } from "./context";
|
|
6
|
+
import { scanTranscript } from "./transcript";
|
|
7
|
+
import { getUsage, widgetsNeedApi } from "./usage";
|
|
8
|
+
import { gitInfo } from "./git";
|
|
9
|
+
import { render, terminalColumns, visibleWidth } from "./render";
|
|
10
|
+
import { loadConfig } from "./config";
|
|
11
|
+
import { debug } from "./debug";
|
|
12
|
+
|
|
13
|
+
async function readStdin(): Promise<string> {
|
|
14
|
+
if (process.stdin.isTTY) return "";
|
|
15
|
+
const chunks: Buffer[] = [];
|
|
16
|
+
for await (const chunk of process.stdin) {
|
|
17
|
+
chunks.push(chunk as Buffer);
|
|
18
|
+
}
|
|
19
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function parseInput(raw: string): StatusInput {
|
|
23
|
+
if (!raw.trim()) return {};
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(raw) as StatusInput;
|
|
26
|
+
} catch {
|
|
27
|
+
return {};
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function main(): Promise<void> {
|
|
32
|
+
if (process.argv.includes("--refresh-usage")) {
|
|
33
|
+
const { refreshUsageOnce } = await import("./usage-api");
|
|
34
|
+
await refreshUsageOnce();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const raw = await readStdin();
|
|
39
|
+
const dumpPath = process.env.GLINTLINE_DUMP_STDIN;
|
|
40
|
+
if (dumpPath) {
|
|
41
|
+
try {
|
|
42
|
+
writeFileSync(dumpPath, raw);
|
|
43
|
+
} catch (e) {
|
|
44
|
+
debug("stdin.dump", e);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// Diagnostics for the narrow-terminal logic: records the width Claude Code
|
|
48
|
+
// actually hands us (COLUMNS/LINES) alongside the line it produced.
|
|
49
|
+
const envDump = process.env.GLINTLINE_DUMP_ENV;
|
|
50
|
+
|
|
51
|
+
const input = parseInput(raw);
|
|
52
|
+
|
|
53
|
+
const cwd = input.workspace?.current_dir ?? input.cwd ?? process.cwd();
|
|
54
|
+
const config = loadConfig();
|
|
55
|
+
const transcript = scanTranscript(input.transcript_path);
|
|
56
|
+
|
|
57
|
+
const usage = getUsage(input, widgetsNeedApi(config));
|
|
58
|
+
const context =
|
|
59
|
+
getContextFromInput(input, config.context.showCompactBuffer) ??
|
|
60
|
+
withAutoCompact(transcript.context, config.context.showCompactBuffer);
|
|
61
|
+
|
|
62
|
+
const line = render({
|
|
63
|
+
input,
|
|
64
|
+
model: getModelInfo({ input, sessionEffort: transcript.effort, fast: transcript.fast }),
|
|
65
|
+
context,
|
|
66
|
+
usage,
|
|
67
|
+
git: gitInfo(cwd),
|
|
68
|
+
totals: transcript.totals,
|
|
69
|
+
cacheLast: transcript.last,
|
|
70
|
+
config,
|
|
71
|
+
columns: terminalColumns(),
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
if (envDump) {
|
|
75
|
+
try {
|
|
76
|
+
writeFileSync(
|
|
77
|
+
envDump,
|
|
78
|
+
JSON.stringify(
|
|
79
|
+
{
|
|
80
|
+
COLUMNS: process.env.COLUMNS ?? null,
|
|
81
|
+
LINES: process.env.LINES ?? null,
|
|
82
|
+
parsedColumns: terminalColumns(),
|
|
83
|
+
lines: line.split("\n").map((l) => ({ width: visibleWidth(l), text: l.replace(/\x1b\[[0-9;]*m/g, "") })),
|
|
84
|
+
},
|
|
85
|
+
null,
|
|
86
|
+
2,
|
|
87
|
+
),
|
|
88
|
+
);
|
|
89
|
+
} catch (e) {
|
|
90
|
+
debug("env.dump", e);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
process.stdout.write(line);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
main().catch((err) => {
|
|
98
|
+
debug("main", err);
|
|
99
|
+
process.exit(0);
|
|
100
|
+
});
|
package/src/model.ts
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import type { StatusInput } from "./types";
|
|
5
|
+
|
|
6
|
+
export interface ModelInfo {
|
|
7
|
+
family: string;
|
|
8
|
+
version?: string;
|
|
9
|
+
context?: string;
|
|
10
|
+
effort?: string;
|
|
11
|
+
effortSessionOnly?: boolean;
|
|
12
|
+
fast: boolean;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const FAMILY_PATTERNS: Array<[RegExp, string]> = [
|
|
16
|
+
[/opus/i, "opus"],
|
|
17
|
+
[/sonnet/i, "sonnet"],
|
|
18
|
+
[/haiku/i, "haiku"],
|
|
19
|
+
[/fable/i, "fable"],
|
|
20
|
+
];
|
|
21
|
+
|
|
22
|
+
const ONE_MILLION_RE = /(?:\b|\[)1m\b|1[\s_-]?million/i;
|
|
23
|
+
|
|
24
|
+
export function isOneMillionContext(s: string | undefined | null): boolean {
|
|
25
|
+
return !!s && ONE_MILLION_RE.test(s);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function detectFamily(s: string | undefined): string {
|
|
29
|
+
if (!s) return "claude";
|
|
30
|
+
for (const [re, name] of FAMILY_PATTERNS) if (re.test(s)) return name;
|
|
31
|
+
// Unknown family: take the leading word only, so a trailing version number
|
|
32
|
+
// ("Fable 5") isn't duplicated once detectVersion appends it.
|
|
33
|
+
return s.toLowerCase().match(/[a-z]+/)?.[0] ?? s.toLowerCase();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function detectVersion(s: string | undefined): string | undefined {
|
|
37
|
+
if (!s) return undefined;
|
|
38
|
+
// Major.minor written with either a dot ("Opus 4.8") or a dash in model ids
|
|
39
|
+
// ("claude-opus-4-8"); collapse both to "4.8" so version comparisons work.
|
|
40
|
+
const pair = s.match(/(\d+)[.-](\d+)/);
|
|
41
|
+
if (pair) return `${pair[1]}.${pair[2]}`;
|
|
42
|
+
return s.match(/(\d+)/)?.[1];
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function detectContext(id: string | undefined, displayName: string | undefined): string | undefined {
|
|
46
|
+
const haystack = `${id ?? ""} ${displayName ?? ""}`;
|
|
47
|
+
return isOneMillionContext(haystack) ? "1M" : undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readEffortFromSettings(): string | null {
|
|
51
|
+
const candidates = [
|
|
52
|
+
join(homedir(), ".claude", "settings.local.json"),
|
|
53
|
+
join(homedir(), ".claude", "settings.json"),
|
|
54
|
+
];
|
|
55
|
+
for (const path of candidates) {
|
|
56
|
+
try {
|
|
57
|
+
const raw = readFileSync(path, "utf8");
|
|
58
|
+
const parsed = JSON.parse(raw) as { effortLevel?: string };
|
|
59
|
+
if (typeof parsed.effortLevel === "string" && parsed.effortLevel.length > 0) {
|
|
60
|
+
return parsed.effortLevel;
|
|
61
|
+
}
|
|
62
|
+
} catch {}
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface ModelInputs {
|
|
68
|
+
input: StatusInput;
|
|
69
|
+
sessionEffort: { level: string; sessionOnly: boolean } | null;
|
|
70
|
+
// Fast mode as last toggled in the transcript — used only when stdin lacks
|
|
71
|
+
// `fast_mode` (older Claude Code).
|
|
72
|
+
fast: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function getModelInfo(args: ModelInputs): ModelInfo {
|
|
76
|
+
const { input, sessionEffort, fast } = args;
|
|
77
|
+
const id = input.model?.id;
|
|
78
|
+
const display = input.model?.display_name;
|
|
79
|
+
const source = display ?? id;
|
|
80
|
+
const family = detectFamily(source);
|
|
81
|
+
const version = detectVersion(source);
|
|
82
|
+
const context = detectContext(id, display);
|
|
83
|
+
|
|
84
|
+
const effort = resolveEffort(input, sessionEffort, version);
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
family,
|
|
88
|
+
version,
|
|
89
|
+
context,
|
|
90
|
+
effort,
|
|
91
|
+
effortSessionOnly: sessionEffort?.sessionOnly,
|
|
92
|
+
fast: typeof input.fast_mode === "boolean" ? input.fast_mode : fast,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function resolveEffort(
|
|
97
|
+
input: StatusInput,
|
|
98
|
+
sessionEffort: ModelInputs["sessionEffort"],
|
|
99
|
+
version: string | undefined,
|
|
100
|
+
): string | undefined {
|
|
101
|
+
// Claude Code reports the active effort in the statusline stdin (present only
|
|
102
|
+
// when the model supports it). It already reflects the CLAUDE_CODE_EFFORT_LEVEL
|
|
103
|
+
// env var, the effortLevel setting, the model default and per-model capping —
|
|
104
|
+
// so trust it verbatim when present.
|
|
105
|
+
const fromInput = input.effort;
|
|
106
|
+
if (fromInput && "level" in fromInput) {
|
|
107
|
+
return typeof fromInput.level === "string" ? fromInput.level.toLowerCase() : undefined;
|
|
108
|
+
}
|
|
109
|
+
// Fallback for Claude Code versions that don't send the field: an in-session
|
|
110
|
+
// toggle from the transcript, else the persisted setting — capped by model
|
|
111
|
+
// capability since xhigh only exists on 4.7+.
|
|
112
|
+
const raw = sessionEffort?.level ?? readEffortFromSettings() ?? undefined;
|
|
113
|
+
return clampEffort(raw, version);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function clampEffort(effort: string | undefined, version: string | undefined): string | undefined {
|
|
117
|
+
if (effort !== "xhigh") return effort;
|
|
118
|
+
const major = version ? parseFloat(version) : 0;
|
|
119
|
+
return major >= 4.7 ? effort : "high";
|
|
120
|
+
}
|
package/src/render.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type { StatusInput, Usage } from "./types";
|
|
2
|
+
import { c, wrap } from "./ansi";
|
|
3
|
+
import type { ContextUsage } from "./context";
|
|
4
|
+
import type { ModelInfo } from "./model";
|
|
5
|
+
import type { GitInfo } from "./git";
|
|
6
|
+
import type { Config } from "./config";
|
|
7
|
+
import type { SessionTotals, CacheUsage } from "./transcript";
|
|
8
|
+
import { renderWidget, SEP_NAMES, type WidgetCtx } from "./widgets";
|
|
9
|
+
|
|
10
|
+
export interface RenderArgs {
|
|
11
|
+
input: StatusInput;
|
|
12
|
+
model: ModelInfo;
|
|
13
|
+
context: ContextUsage | null;
|
|
14
|
+
usage: Usage | null;
|
|
15
|
+
git: GitInfo | null;
|
|
16
|
+
totals: SessionTotals;
|
|
17
|
+
cacheLast: CacheUsage | null;
|
|
18
|
+
config: Config;
|
|
19
|
+
columns: number | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Claude Code exports the terminal size before running the status line command
|
|
23
|
+
// (v2.1.153+); the script's own stdout is a pipe, so this env var is the only
|
|
24
|
+
// way to learn the width. null means "unknown" — callers must not hide anything.
|
|
25
|
+
export function terminalColumns(env: NodeJS.ProcessEnv = process.env): number | null {
|
|
26
|
+
const n = Number.parseInt(env.COLUMNS ?? "", 10);
|
|
27
|
+
return Number.isFinite(n) && n > 0 ? n : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Code points that render in two terminal columns: CJK, Hangul, fullwidth
|
|
31
|
+
// forms and the emoji blocks. Anything East-Asian "Ambiguous" (■ ∼ ↓ Σ …) is
|
|
32
|
+
// counted as one, matching the default of most non-CJK terminal setups — its
|
|
33
|
+
// real width depends on a terminal setting we cannot read from here.
|
|
34
|
+
const WIDE_RANGES: Array<[number, number]> = [
|
|
35
|
+
[0x1100, 0x115f], [0x2e80, 0x303e], [0x3041, 0x33ff], [0x3400, 0x4dbf],
|
|
36
|
+
[0x4e00, 0x9fff], [0xa000, 0xa4cf], [0xac00, 0xd7a3], [0xf900, 0xfaff],
|
|
37
|
+
[0xfe30, 0xfe6f], [0xff00, 0xff60], [0xffe0, 0xffe6],
|
|
38
|
+
[0x1f300, 0x1f64f], [0x1f680, 0x1f6ff], [0x1f900, 0x1f9ff],
|
|
39
|
+
[0x20000, 0x3fffd],
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
// Zero-width: combining marks, variation selectors (⏱︎ = U+23F1 U+FE0E),
|
|
43
|
+
// zero-width space/joiners and the BOM.
|
|
44
|
+
function isZeroWidth(cp: number): boolean {
|
|
45
|
+
return (
|
|
46
|
+
(cp >= 0x0300 && cp <= 0x036f) ||
|
|
47
|
+
(cp >= 0xfe00 && cp <= 0xfe0f) ||
|
|
48
|
+
(cp >= 0x200b && cp <= 0x200d) ||
|
|
49
|
+
cp === 0xfeff
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function charWidth(cp: number): number {
|
|
54
|
+
if (isZeroWidth(cp)) return 0;
|
|
55
|
+
for (const [lo, hi] of WIDE_RANGES) if (cp >= lo && cp <= hi) return 2;
|
|
56
|
+
return 1;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Printable width of a rendered line in terminal columns: SGR sequences take no
|
|
60
|
+
// space, combining marks and variation selectors none, wide glyphs two.
|
|
61
|
+
export function visibleWidth(s: string): number {
|
|
62
|
+
let w = 0;
|
|
63
|
+
for (const ch of s.replace(/\x1b\[[0-9;]*m/g, "")) w += charWidth(ch.codePointAt(0)!);
|
|
64
|
+
return w;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
interface Item {
|
|
68
|
+
name: string;
|
|
69
|
+
out: string | null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function namespaceOf(name: string): string {
|
|
73
|
+
const dot = name.indexOf(".");
|
|
74
|
+
return dot >= 0 ? name.slice(0, dot) : name;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function withAutoSep(items: Item[], separator: string): Item[] {
|
|
78
|
+
const sepOut = wrap(c.darkGray, separator);
|
|
79
|
+
const out: Item[] = [];
|
|
80
|
+
let prevName: string | null = null;
|
|
81
|
+
for (let i = 0; i < items.length; i++) {
|
|
82
|
+
const cur = items[i]!;
|
|
83
|
+
if (!cur.out) continue;
|
|
84
|
+
if (prevName !== null) {
|
|
85
|
+
const sameNs = namespaceOf(prevName) === namespaceOf(cur.name) && prevName !== cur.name;
|
|
86
|
+
out.push(sameNs ? { name: "space", out: " " } : { name: "sep", out: sepOut });
|
|
87
|
+
}
|
|
88
|
+
out.push(cur);
|
|
89
|
+
prevName = cur.name;
|
|
90
|
+
}
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function trimSeps(items: Item[]): string[] {
|
|
95
|
+
const result: Item[] = [];
|
|
96
|
+
for (let i = 0; i < items.length; i++) {
|
|
97
|
+
const cur = items[i]!;
|
|
98
|
+
if (cur.out === null || cur.out === "") continue;
|
|
99
|
+
const isSep = SEP_NAMES.has(cur.name);
|
|
100
|
+
if (isSep) {
|
|
101
|
+
const prev = result[result.length - 1];
|
|
102
|
+
if (!prev) continue;
|
|
103
|
+
const hasNextContent = items
|
|
104
|
+
.slice(i + 1)
|
|
105
|
+
.some((it) => it.out && !SEP_NAMES.has(it.name));
|
|
106
|
+
if (!hasNextContent) continue;
|
|
107
|
+
if (SEP_NAMES.has(prev.name)) {
|
|
108
|
+
result[result.length - 1] = cur;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
result.push(cur);
|
|
113
|
+
}
|
|
114
|
+
return result.map((it) => it.out!);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function renderLine(names: string[], ctx: WidgetCtx, separator: string): string {
|
|
118
|
+
const items: Item[] = names.map((name) => ({ name, out: renderWidget(name, ctx) }));
|
|
119
|
+
const hasExplicitSep = names.some((n) => SEP_NAMES.has(n));
|
|
120
|
+
const finalItems = hasExplicitSep ? items : withAutoSep(items, separator);
|
|
121
|
+
return trimSeps(finalItems).join("");
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Partial steps for `dropWhenNarrow`: "widget:part" trims one piece of a widget
|
|
125
|
+
// instead of removing it whole, so a line can narrow gradually.
|
|
126
|
+
const NARROW_STEPS: Record<string, (cfg: Config) => Config> = {
|
|
127
|
+
"cache:session": (cfg) => cfg.cache.window === "both" ? { ...cfg, cache: { ...cfg.cache, window: "last" } } : cfg,
|
|
128
|
+
"cache:percent": (cfg) => ({ ...cfg, cache: { ...cfg.cache, showPercent: false } }),
|
|
129
|
+
"context:buffer": (cfg) => ({ ...cfg, context: { ...cfg.context, showBufferTokens: false } }),
|
|
130
|
+
"context:numbers": (cfg) => ({ ...cfg, context: { ...cfg.context, showNumbers: false } }),
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
// Render a line, shedding `dropWhenNarrow` widgets (in the order given, least
|
|
134
|
+
// important first) for as long as the result overflows the terminal. Dropping a
|
|
135
|
+
// widget also collapses its separator, so the line stays well-formed; once it
|
|
136
|
+
// fits, the remaining widgets are kept even if later ones are droppable.
|
|
137
|
+
function renderLineFitted(
|
|
138
|
+
names: string[],
|
|
139
|
+
ctx: WidgetCtx,
|
|
140
|
+
separator: string,
|
|
141
|
+
columns: number | null,
|
|
142
|
+
): string {
|
|
143
|
+
let out = renderLine(names, ctx, separator);
|
|
144
|
+
if (columns === null) return out;
|
|
145
|
+
let kept = names;
|
|
146
|
+
let cur = ctx;
|
|
147
|
+
for (const drop of ctx.config.dropWhenNarrow) {
|
|
148
|
+
if (visibleWidth(out) <= columns) break;
|
|
149
|
+
const step = NARROW_STEPS[drop];
|
|
150
|
+
if (step) {
|
|
151
|
+
if (!kept.includes(drop.slice(0, drop.indexOf(":")))) continue;
|
|
152
|
+
cur = { ...cur, config: step(cur.config) };
|
|
153
|
+
} else {
|
|
154
|
+
if (!kept.includes(drop)) continue;
|
|
155
|
+
kept = kept.filter((n) => n !== drop);
|
|
156
|
+
}
|
|
157
|
+
out = renderLine(kept, cur, separator);
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// Claude Code indents the status line by two columns plus `padding` and keeps
|
|
163
|
+
// the same margin on the right, truncating with "…" past that — so a line fits
|
|
164
|
+
// in COLUMNS − 2·(2 + padding), not in COLUMNS (measured on v2.1.273).
|
|
165
|
+
export function lineBudget(columns: number | null, padding: number): number | null {
|
|
166
|
+
return columns === null ? null : columns - 2 * (2 + Math.max(0, padding));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function render(args: RenderArgs): string {
|
|
170
|
+
const ctx: WidgetCtx = { ...args, nowSec: Math.floor(Date.now() / 1000) };
|
|
171
|
+
const budget = lineBudget(args.columns, args.config.statusLinePadding);
|
|
172
|
+
return args.config.widgets
|
|
173
|
+
.map((line) => renderLineFitted(line, ctx, args.config.separator, budget))
|
|
174
|
+
.filter((s) => s.length > 0)
|
|
175
|
+
.join("\n");
|
|
176
|
+
}
|