glintline 0.0.0-stage → 0.3.0
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 +266 -0
- package/INSTALL.md +214 -0
- package/LICENSE +21 -0
- package/README.md +405 -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 +199 -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/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
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { openSync, readSync, closeSync, statSync } from "node:fs";
|
|
2
|
+
import { readCache, writeCache } from "./cache";
|
|
3
|
+
import { isOneMillionContext } from "./model";
|
|
4
|
+
import { debug } from "./debug";
|
|
5
|
+
|
|
6
|
+
const CACHE_VERSION = 4;
|
|
7
|
+
const CACHE_TTL_SEC = 7 * 24 * 3600;
|
|
8
|
+
|
|
9
|
+
export interface SessionTotals {
|
|
10
|
+
input: number;
|
|
11
|
+
output: number;
|
|
12
|
+
cacheRead: number;
|
|
13
|
+
cacheCreation: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// The token breakdown of a single assistant turn, enough for a hit-rate.
|
|
17
|
+
export interface CacheUsage {
|
|
18
|
+
input: number;
|
|
19
|
+
cacheRead: number;
|
|
20
|
+
cacheCreation: number;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface TranscriptState {
|
|
24
|
+
v: number;
|
|
25
|
+
scannedUpTo: number;
|
|
26
|
+
ppid: number;
|
|
27
|
+
effort: { level: string; sessionOnly: boolean } | null;
|
|
28
|
+
context: { used: number; total: number } | null;
|
|
29
|
+
fast: boolean;
|
|
30
|
+
totals: SessionTotals;
|
|
31
|
+
last: CacheUsage | null;
|
|
32
|
+
// Response behind `last`. Claude Code writes one line per content block, each
|
|
33
|
+
// repeating the response's usage, so a repeat of this id replaces the figures
|
|
34
|
+
// already counted instead of adding them again.
|
|
35
|
+
lastId: string | null;
|
|
36
|
+
lastOutput: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function emptyState(): TranscriptState {
|
|
40
|
+
return {
|
|
41
|
+
v: CACHE_VERSION,
|
|
42
|
+
scannedUpTo: 0,
|
|
43
|
+
ppid: 0,
|
|
44
|
+
effort: null,
|
|
45
|
+
context: null,
|
|
46
|
+
fast: false,
|
|
47
|
+
totals: { input: 0, output: 0, cacheRead: 0, cacheCreation: 0 },
|
|
48
|
+
last: null,
|
|
49
|
+
lastId: null,
|
|
50
|
+
lastOutput: 0,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
interface TranscriptUsage {
|
|
55
|
+
input_tokens?: number;
|
|
56
|
+
output_tokens?: number;
|
|
57
|
+
cache_creation_input_tokens?: number;
|
|
58
|
+
cache_read_input_tokens?: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
interface JsonlLine {
|
|
62
|
+
type?: string;
|
|
63
|
+
isSidechain?: boolean;
|
|
64
|
+
message?: {
|
|
65
|
+
role?: string;
|
|
66
|
+
content?: unknown;
|
|
67
|
+
id?: string;
|
|
68
|
+
usage?: TranscriptUsage;
|
|
69
|
+
model?: string;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const SET_EFFORT_RE = /Set effort level to ([a-z0-9-]+)(?:\s*\(([^)]*)\))?/i;
|
|
74
|
+
const ANSI_RE = /\x1b\[[0-9;]*m/g;
|
|
75
|
+
const MODEL_EFFORT_RE = /Set model to .*?with ([a-z0-9-]+) effort/i;
|
|
76
|
+
const FAST_RE = /Fast mode (ON|OFF)/i;
|
|
77
|
+
const DEFAULT_CONTEXT = 200_000;
|
|
78
|
+
|
|
79
|
+
function readRange(path: string, offset: number, length: number): string {
|
|
80
|
+
if (length <= 0) return "";
|
|
81
|
+
const fd = openSync(path, "r");
|
|
82
|
+
try {
|
|
83
|
+
const buf = Buffer.alloc(length);
|
|
84
|
+
const bytesRead = readSync(fd, buf, 0, length, offset);
|
|
85
|
+
return buf.subarray(0, bytesRead).toString("utf8");
|
|
86
|
+
} finally {
|
|
87
|
+
closeSync(fd);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function extractStdout(content: unknown): string | null {
|
|
92
|
+
let text: string;
|
|
93
|
+
if (typeof content === "string") {
|
|
94
|
+
text = content;
|
|
95
|
+
} else if (Array.isArray(content)) {
|
|
96
|
+
text = content
|
|
97
|
+
.map((p) =>
|
|
98
|
+
typeof p === "object" && p && "text" in p
|
|
99
|
+
? String((p as { text: unknown }).text)
|
|
100
|
+
: "",
|
|
101
|
+
)
|
|
102
|
+
.join("");
|
|
103
|
+
} else {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
const m = text.match(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/);
|
|
107
|
+
return m?.[1] ?? null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function detectContextSize(model: string | undefined): number {
|
|
111
|
+
return isOneMillionContext(model) ? 1_000_000 : DEFAULT_CONTEXT;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function applyLine(line: string, state: TranscriptState): void {
|
|
115
|
+
if (!line || line[0] !== "{") return;
|
|
116
|
+
let parsed: JsonlLine;
|
|
117
|
+
try {
|
|
118
|
+
parsed = JSON.parse(line) as JsonlLine;
|
|
119
|
+
} catch {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (parsed.type === "user" && parsed.message?.role === "user") {
|
|
124
|
+
const rawStdout = extractStdout(parsed.message.content);
|
|
125
|
+
const stdout = rawStdout?.replace(ANSI_RE, "");
|
|
126
|
+
if (stdout) {
|
|
127
|
+
const setMatch = stdout.match(SET_EFFORT_RE);
|
|
128
|
+
if (setMatch) {
|
|
129
|
+
const level = (setMatch[1] ?? "").toLowerCase();
|
|
130
|
+
const note = (setMatch[2] ?? "").toLowerCase();
|
|
131
|
+
state.effort = {
|
|
132
|
+
level,
|
|
133
|
+
sessionOnly:
|
|
134
|
+
note.includes("this session only") || note.includes("session only"),
|
|
135
|
+
};
|
|
136
|
+
} else {
|
|
137
|
+
const modelMatch = stdout.match(MODEL_EFFORT_RE);
|
|
138
|
+
if (modelMatch) {
|
|
139
|
+
state.effort = { level: (modelMatch[1] ?? "").toLowerCase(), sessionOnly: false };
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const fastMatch = stdout.match(FAST_RE);
|
|
143
|
+
if (fastMatch) {
|
|
144
|
+
state.fast = fastMatch[1]!.toUpperCase() === "ON";
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
if (
|
|
150
|
+
parsed.type === "assistant" &&
|
|
151
|
+
parsed.message?.usage &&
|
|
152
|
+
!parsed.isSidechain
|
|
153
|
+
) {
|
|
154
|
+
const u = parsed.message.usage;
|
|
155
|
+
const input = u.input_tokens ?? 0;
|
|
156
|
+
const output = u.output_tokens ?? 0;
|
|
157
|
+
const cacheCreation = u.cache_creation_input_tokens ?? 0;
|
|
158
|
+
const cacheRead = u.cache_read_input_tokens ?? 0;
|
|
159
|
+
const id = parsed.message.id ?? null;
|
|
160
|
+
if (id !== null && id === state.lastId && state.last) {
|
|
161
|
+
state.totals.input -= state.last.input;
|
|
162
|
+
state.totals.output -= state.lastOutput;
|
|
163
|
+
state.totals.cacheRead -= state.last.cacheRead;
|
|
164
|
+
state.totals.cacheCreation -= state.last.cacheCreation;
|
|
165
|
+
}
|
|
166
|
+
state.totals.input += input;
|
|
167
|
+
state.totals.output += output;
|
|
168
|
+
state.totals.cacheRead += cacheRead;
|
|
169
|
+
state.totals.cacheCreation += cacheCreation;
|
|
170
|
+
state.last = { input, cacheRead, cacheCreation };
|
|
171
|
+
state.lastId = id;
|
|
172
|
+
state.lastOutput = output;
|
|
173
|
+
const used = input + cacheCreation + cacheRead;
|
|
174
|
+
if (used > 0) {
|
|
175
|
+
state.context = { used, total: detectContextSize(parsed.message.model) };
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function cacheKey(path: string): string {
|
|
181
|
+
return "transcript:" + path;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function scanTranscript(path: string | undefined): TranscriptState {
|
|
185
|
+
if (!path) return emptyState();
|
|
186
|
+
|
|
187
|
+
let size: number;
|
|
188
|
+
try {
|
|
189
|
+
size = statSync(path).size;
|
|
190
|
+
} catch (e) {
|
|
191
|
+
debug("transcript.stat", e);
|
|
192
|
+
return emptyState();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const cached = readCache<TranscriptState>(cacheKey(path), CACHE_TTL_SEC);
|
|
196
|
+
let state: TranscriptState =
|
|
197
|
+
cached && cached.v === CACHE_VERSION ? cached : emptyState();
|
|
198
|
+
|
|
199
|
+
if (state.scannedUpTo > size) {
|
|
200
|
+
state = emptyState();
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const ppid = process.ppid;
|
|
204
|
+
if (state.ppid !== 0 && state.ppid !== ppid && state.effort?.sessionOnly) {
|
|
205
|
+
state.effort = null;
|
|
206
|
+
}
|
|
207
|
+
state.ppid = ppid;
|
|
208
|
+
|
|
209
|
+
if (state.scannedUpTo === size) {
|
|
210
|
+
writeCache(cacheKey(path), state);
|
|
211
|
+
return state;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const startOffset = state.scannedUpTo;
|
|
215
|
+
const length = size - startOffset;
|
|
216
|
+
let chunk: string;
|
|
217
|
+
try {
|
|
218
|
+
chunk = readRange(path, startOffset, length);
|
|
219
|
+
} catch (e) {
|
|
220
|
+
debug("transcript.read", e);
|
|
221
|
+
return state;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const lines = chunk.split("\n");
|
|
225
|
+
const skipFirst = startOffset > 0;
|
|
226
|
+
const start = skipFirst ? 1 : 0;
|
|
227
|
+
for (let i = start; i < lines.length - 1; i++) {
|
|
228
|
+
applyLine(lines[i] ?? "", state);
|
|
229
|
+
}
|
|
230
|
+
// The last split element is whatever follows the final "\n". If the chunk
|
|
231
|
+
// ended with a newline it is empty (every line was complete and consumed);
|
|
232
|
+
// otherwise it is a partially-written line — leave it unscanned for the next
|
|
233
|
+
// pass rather than guessing completeness from its last character (a partial
|
|
234
|
+
// line often ends in "}" when an inner object closes mid-write).
|
|
235
|
+
const tail = lines[lines.length - 1] ?? "";
|
|
236
|
+
state.scannedUpTo = size - Buffer.byteLength(tail, "utf8");
|
|
237
|
+
|
|
238
|
+
writeCache(cacheKey(path), state);
|
|
239
|
+
return state;
|
|
240
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
export interface StatusInput {
|
|
2
|
+
hook_event_name?: string;
|
|
3
|
+
session_id?: string;
|
|
4
|
+
session_name?: string;
|
|
5
|
+
prompt_id?: string;
|
|
6
|
+
transcript_path?: string;
|
|
7
|
+
scratchpad_dir?: string;
|
|
8
|
+
cwd?: string;
|
|
9
|
+
model?: {
|
|
10
|
+
id?: string;
|
|
11
|
+
display_name?: string;
|
|
12
|
+
};
|
|
13
|
+
workspace?: {
|
|
14
|
+
current_dir?: string;
|
|
15
|
+
project_dir?: string;
|
|
16
|
+
added_dirs?: string[];
|
|
17
|
+
git_worktree?: string;
|
|
18
|
+
repo?: { host?: string; owner?: string; name?: string };
|
|
19
|
+
};
|
|
20
|
+
version?: string;
|
|
21
|
+
output_style?: { name?: string };
|
|
22
|
+
effort?: { level?: string | null };
|
|
23
|
+
cost?: {
|
|
24
|
+
total_cost_usd?: number;
|
|
25
|
+
total_duration_ms?: number;
|
|
26
|
+
total_api_duration_ms?: number;
|
|
27
|
+
total_lines_added?: number;
|
|
28
|
+
total_lines_removed?: number;
|
|
29
|
+
};
|
|
30
|
+
exceeds_200k_tokens?: boolean;
|
|
31
|
+
fast_mode?: boolean;
|
|
32
|
+
thinking?: { enabled?: boolean };
|
|
33
|
+
prompt_cache?: PromptCache;
|
|
34
|
+
context_window?: {
|
|
35
|
+
total_input_tokens?: number;
|
|
36
|
+
total_output_tokens?: number;
|
|
37
|
+
context_window_size?: number;
|
|
38
|
+
used_percentage?: number;
|
|
39
|
+
remaining_percentage?: number;
|
|
40
|
+
current_usage?: {
|
|
41
|
+
input_tokens?: number;
|
|
42
|
+
output_tokens?: number;
|
|
43
|
+
cache_creation_input_tokens?: number;
|
|
44
|
+
cache_read_input_tokens?: number;
|
|
45
|
+
} | null;
|
|
46
|
+
};
|
|
47
|
+
rate_limits?: {
|
|
48
|
+
five_hour?: RateLimitWindow;
|
|
49
|
+
seven_day?: RateLimitWindow;
|
|
50
|
+
spend_limit?: RateLimitWindow;
|
|
51
|
+
};
|
|
52
|
+
vim?: { mode?: string };
|
|
53
|
+
agent?: { name?: string };
|
|
54
|
+
pr?: { number?: number; url?: string; review_state?: string; kind?: string };
|
|
55
|
+
worktree?: {
|
|
56
|
+
name?: string;
|
|
57
|
+
path?: string;
|
|
58
|
+
branch?: string;
|
|
59
|
+
original_cwd?: string;
|
|
60
|
+
original_branch?: string;
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Prompt-cache statistics for the main conversation (Claude Code v2.1.251+).
|
|
65
|
+
// Absent until the first API response of the process — a resumed session starts
|
|
66
|
+
// without it. Timestamps are epoch seconds.
|
|
67
|
+
export interface PromptCache {
|
|
68
|
+
warm?: boolean;
|
|
69
|
+
caching_observed?: boolean;
|
|
70
|
+
ttl?: string;
|
|
71
|
+
expires_at?: number | null;
|
|
72
|
+
requests?: number;
|
|
73
|
+
misses?: number;
|
|
74
|
+
expected_rebuilds?: number;
|
|
75
|
+
hit_ratio?: number | null;
|
|
76
|
+
cache_write_tokens?: number;
|
|
77
|
+
miss_recache_tokens?: number;
|
|
78
|
+
last_miss_at?: number | null;
|
|
79
|
+
last_miss_cause?: {
|
|
80
|
+
causes?: string[];
|
|
81
|
+
tools_added?: number;
|
|
82
|
+
tools_removed?: number;
|
|
83
|
+
system_char_delta?: number;
|
|
84
|
+
} | null;
|
|
85
|
+
miss_causes?: Record<string, number>;
|
|
86
|
+
recache_tokens_if_cold?: number | null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface RateLimitWindow {
|
|
90
|
+
used_percentage?: number;
|
|
91
|
+
resets_at?: number | string;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export interface UsageWindow {
|
|
95
|
+
utilization: number;
|
|
96
|
+
resets_at: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface ExtraUsage {
|
|
100
|
+
is_enabled: boolean;
|
|
101
|
+
monthly_limit: number;
|
|
102
|
+
used_credits: number;
|
|
103
|
+
utilization: number;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface Usage {
|
|
107
|
+
five_hour?: UsageWindow;
|
|
108
|
+
seven_day?: UsageWindow;
|
|
109
|
+
// Per-model weekly caps, keyed by model family (e.g. "fable", "sonnet"),
|
|
110
|
+
// extracted from the API's `limits[]` array. Only present from the API.
|
|
111
|
+
seven_day_scoped?: Record<string, UsageWindow>;
|
|
112
|
+
extra?: ExtraUsage;
|
|
113
|
+
fetched_at: number;
|
|
114
|
+
source: "stdin" | "api" | "cache";
|
|
115
|
+
}
|