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
|
@@ -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
|
+
}
|
package/src/usage-api.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { existsSync, unlinkSync } from "node:fs";
|
|
4
|
+
import { resolve } from "node:path";
|
|
5
|
+
import { argv, execPath } from "node:process";
|
|
6
|
+
import { getOAuthToken } from "./credentials";
|
|
7
|
+
import { detectFamily } from "./model";
|
|
8
|
+
import { cachePath, readCache, writeCache } from "./cache";
|
|
9
|
+
import { debug } from "./debug";
|
|
10
|
+
import type { ExtraUsage, Usage, UsageWindow } from "./types";
|
|
11
|
+
|
|
12
|
+
const ENDPOINT = "https://api.anthropic.com/api/oauth/usage";
|
|
13
|
+
const FRESH_TTL_SEC = 60;
|
|
14
|
+
const STALE_TTL_SEC = 24 * 3600;
|
|
15
|
+
const FETCH_TIMEOUT_MS = 8000;
|
|
16
|
+
const LOCK_TTL_SEC = 30;
|
|
17
|
+
|
|
18
|
+
interface ApiWindow {
|
|
19
|
+
utilization?: number;
|
|
20
|
+
resets_at?: string | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
interface ApiExtra {
|
|
24
|
+
is_enabled?: boolean;
|
|
25
|
+
monthly_limit?: number;
|
|
26
|
+
used_credits?: number;
|
|
27
|
+
utilization?: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Newer per-model weekly caps arrive not as named fields but as entries in a
|
|
31
|
+
// `limits[]` array, each tagged with a `scope.model`. We key them by model
|
|
32
|
+
// family (via detectFamily, so "Fable"/"Fable 5" → "fable") for lookup against
|
|
33
|
+
// the active model.
|
|
34
|
+
interface ApiLimit {
|
|
35
|
+
group?: string;
|
|
36
|
+
percent?: number;
|
|
37
|
+
resets_at?: string | null;
|
|
38
|
+
scope?: { model?: { display_name?: string | null } | null } | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface ApiResponse {
|
|
42
|
+
five_hour?: ApiWindow;
|
|
43
|
+
seven_day?: ApiWindow;
|
|
44
|
+
limits?: ApiLimit[] | null;
|
|
45
|
+
extra_usage?: ApiExtra | null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Collect the weekly, model-scoped limits from `limits[]` into a map keyed by
|
|
49
|
+
// model family, so a widget can look up the cap for whatever model is active.
|
|
50
|
+
export function scopedWeekly(limits: ApiLimit[] | null | undefined): Record<string, UsageWindow> {
|
|
51
|
+
const out: Record<string, UsageWindow> = {};
|
|
52
|
+
if (!Array.isArray(limits)) return out;
|
|
53
|
+
for (const l of limits) {
|
|
54
|
+
if (!l || l.group !== "weekly") continue;
|
|
55
|
+
const name = l.scope?.model?.display_name;
|
|
56
|
+
if (typeof name !== "string") continue;
|
|
57
|
+
// percent maps onto ApiWindow.utilization, so reuse the shared window mapper.
|
|
58
|
+
const w = mapWindow({ utilization: l.percent, resets_at: l.resets_at });
|
|
59
|
+
if (w) out[detectFamily(name)] = w;
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function tokenKey(token: string): string {
|
|
65
|
+
return "usage:" + createHash("sha256").update(token).digest("hex").slice(0, 16);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function lockKey(token: string): string {
|
|
69
|
+
return "usage-lock:" + createHash("sha256").update(token).digest("hex").slice(0, 16);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function toEpoch(value: string | null | undefined): number {
|
|
73
|
+
if (!value) return 0;
|
|
74
|
+
const ms = Date.parse(value);
|
|
75
|
+
return Number.isFinite(ms) ? Math.floor(ms / 1000) : 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function mapWindow(w: ApiWindow | undefined | null): UsageWindow | undefined {
|
|
79
|
+
if (!w || w.utilization === undefined) return undefined;
|
|
80
|
+
return { utilization: w.utilization, resets_at: toEpoch(w.resets_at) };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function mapExtra(e: ApiExtra | undefined | null): ExtraUsage | undefined {
|
|
84
|
+
if (!e || e.utilization === undefined) return undefined;
|
|
85
|
+
return {
|
|
86
|
+
is_enabled: e.is_enabled ?? false,
|
|
87
|
+
monthly_limit: e.monthly_limit ?? 0,
|
|
88
|
+
used_credits: e.used_credits ?? 0,
|
|
89
|
+
utilization: e.utilization,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function ageSec(usage: Usage | null): number {
|
|
94
|
+
if (!usage) return Infinity;
|
|
95
|
+
return Math.floor(Date.now() / 1000) - usage.fetched_at;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function isLocked(token: string): boolean {
|
|
99
|
+
return readCache<{ at: number }>(lockKey(token), LOCK_TTL_SEC) !== null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function acquireLock(token: string): void {
|
|
103
|
+
writeCache(lockKey(token), { at: Math.floor(Date.now() / 1000) });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function releaseLock(token: string): void {
|
|
107
|
+
try {
|
|
108
|
+
const path = cachePath(lockKey(token));
|
|
109
|
+
if (existsSync(path)) unlinkSync(path);
|
|
110
|
+
} catch (e) {
|
|
111
|
+
debug("usage-api.lock", e);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function spawnRefresh(): void {
|
|
116
|
+
const scriptArg = argv[1];
|
|
117
|
+
if (!scriptArg) return;
|
|
118
|
+
const scriptPath = resolve(scriptArg);
|
|
119
|
+
try {
|
|
120
|
+
const child = spawn(execPath, [scriptPath, "--refresh-usage"], {
|
|
121
|
+
detached: true,
|
|
122
|
+
stdio: "ignore",
|
|
123
|
+
});
|
|
124
|
+
child.unref();
|
|
125
|
+
} catch (e) {
|
|
126
|
+
debug("usage-api.spawn", e);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function doFetch(token: string): Promise<Usage | null> {
|
|
131
|
+
const controller = new AbortController();
|
|
132
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
133
|
+
try {
|
|
134
|
+
const res = await fetch(ENDPOINT, {
|
|
135
|
+
method: "GET",
|
|
136
|
+
headers: {
|
|
137
|
+
Accept: "application/json",
|
|
138
|
+
Authorization: `Bearer ${token}`,
|
|
139
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
140
|
+
"User-Agent": "glintline/0.1",
|
|
141
|
+
},
|
|
142
|
+
signal: controller.signal,
|
|
143
|
+
});
|
|
144
|
+
if (!res.ok) {
|
|
145
|
+
debug("usage-api.fetch", `HTTP ${res.status}`);
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
const json = (await res.json()) as ApiResponse;
|
|
149
|
+
const usage: Usage = {
|
|
150
|
+
five_hour: mapWindow(json.five_hour),
|
|
151
|
+
seven_day: mapWindow(json.seven_day),
|
|
152
|
+
seven_day_scoped: scopedWeekly(json.limits),
|
|
153
|
+
extra: mapExtra(json.extra_usage),
|
|
154
|
+
fetched_at: Math.floor(Date.now() / 1000),
|
|
155
|
+
source: "api",
|
|
156
|
+
};
|
|
157
|
+
writeCache(tokenKey(token), usage);
|
|
158
|
+
return usage;
|
|
159
|
+
} catch (e) {
|
|
160
|
+
debug("usage-api.fetch", e);
|
|
161
|
+
return null;
|
|
162
|
+
} finally {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export async function refreshUsageOnce(): Promise<void> {
|
|
168
|
+
const token = getOAuthToken();
|
|
169
|
+
if (!token) return;
|
|
170
|
+
if (isLocked(token)) return;
|
|
171
|
+
acquireLock(token);
|
|
172
|
+
try {
|
|
173
|
+
await doFetch(token);
|
|
174
|
+
} finally {
|
|
175
|
+
releaseLock(token);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function getUsageNonBlocking(): Usage | null {
|
|
180
|
+
const token = getOAuthToken();
|
|
181
|
+
if (!token) return null;
|
|
182
|
+
|
|
183
|
+
const cached = readCache<Usage>(tokenKey(token), STALE_TTL_SEC);
|
|
184
|
+
const age = ageSec(cached);
|
|
185
|
+
|
|
186
|
+
if (age >= FRESH_TTL_SEC && !isLocked(token)) spawnRefresh();
|
|
187
|
+
|
|
188
|
+
return cached ? { ...cached, source: "cache" } : null;
|
|
189
|
+
}
|
package/src/usage.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { StatusInput, Usage, UsageWindow, RateLimitWindow } from "./types";
|
|
2
|
+
import type { Config } from "./config";
|
|
3
|
+
import { getUsageNonBlocking } from "./usage-api";
|
|
4
|
+
|
|
5
|
+
function normalizeResetsAt(value: number | string | undefined): number {
|
|
6
|
+
if (value === undefined) return 0;
|
|
7
|
+
if (typeof value === "number") return value;
|
|
8
|
+
const ms = Date.parse(value);
|
|
9
|
+
return Number.isFinite(ms) ? Math.floor(ms / 1000) : 0;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function fromInputWindow(rl: RateLimitWindow | undefined): UsageWindow | undefined {
|
|
13
|
+
if (!rl || rl.used_percentage === undefined) return undefined;
|
|
14
|
+
return {
|
|
15
|
+
utilization: rl.used_percentage,
|
|
16
|
+
resets_at: normalizeResetsAt(rl.resets_at),
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function fromInput(input: StatusInput): Usage | null {
|
|
21
|
+
const rl = input.rate_limits;
|
|
22
|
+
if (!rl) return null;
|
|
23
|
+
const five = fromInputWindow(rl.five_hour);
|
|
24
|
+
const seven = fromInputWindow(rl.seven_day);
|
|
25
|
+
if (!five && !seven) return null;
|
|
26
|
+
return {
|
|
27
|
+
five_hour: five,
|
|
28
|
+
seven_day: seven,
|
|
29
|
+
fetched_at: Math.floor(Date.now() / 1000),
|
|
30
|
+
source: "stdin",
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Once Claude Code reports rate_limits, it decides which windows exist: a
|
|
35
|
+
// window it leaves out is gone (Ultra has no 5-hour limit; an expired window is
|
|
36
|
+
// dropped until the next one starts), so the API must not bring it back. The
|
|
37
|
+
// API still contributes what stdin never carries — per-model caps and extra.
|
|
38
|
+
export function mergeUsage(stdin: Usage | null, api: Usage | null): Usage | null {
|
|
39
|
+
if (!api) return stdin;
|
|
40
|
+
if (!stdin) return api;
|
|
41
|
+
return {
|
|
42
|
+
...api,
|
|
43
|
+
five_hour: stdin.five_hour,
|
|
44
|
+
seven_day: stdin.seven_day,
|
|
45
|
+
source: stdin.source,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function getUsage(input: StatusInput, fetchApi: boolean): Usage | null {
|
|
50
|
+
const stdin = fromInput(input);
|
|
51
|
+
if (!fetchApi) return stdin;
|
|
52
|
+
return mergeUsage(stdin, getUsageNonBlocking());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const API_ONLY_WIDGETS = new Set(["extra"]);
|
|
56
|
+
|
|
57
|
+
export function widgetsNeedApi(config: Config): boolean {
|
|
58
|
+
const anyWidget = (pred: (w: string) => boolean) => config.widgets.some((line) => line.some(pred));
|
|
59
|
+
if (anyWidget((w) => API_ONLY_WIDGETS.has(w))) return true;
|
|
60
|
+
// Per-model weekly caps live only in the API; limit7d needs it when it is set
|
|
61
|
+
// to swap in the active model's scoped window.
|
|
62
|
+
return anyWidget((w) => w === "limit7d") && config.limit7d.perModel;
|
|
63
|
+
}
|