@hank-warren/pi-statusline 0.1.3 → 0.2.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/README.md +15 -4
- package/cache-celebration.ts +1 -1
- package/index.ts +39 -10
- package/package.json +2 -1
- package/usage.ts +234 -0
package/README.md
CHANGED
|
@@ -3,28 +3,39 @@
|
|
|
3
3
|
Replaces Pi's default footer with a compact statusline:
|
|
4
4
|
|
|
5
5
|
```text
|
|
6
|
-
gpt-5.6-sol | pi-extensions:main* ⇣1 | 40k/1.0m
|
|
6
|
+
gpt-5.6-sol | pi-extensions:main* ⇣1 | 40k/1.0m | 97·54 80
|
|
7
7
|
⑂ pi-extensions:feature/statusline* ⇣2 #7 | infra:fix/alerts #168
|
|
8
8
|
019fafa7-29c0-7e99-9f82-5794d5721848
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
## What it shows
|
|
12
12
|
|
|
13
|
-
- **Line 1** — active model ID, current directory basename and Git branch,
|
|
13
|
+
- **Line 1** — active model ID, current directory basename and Git branch, current context usage/window, and subscription usage headroom (see below). A yellow `*` marks a dirty checkout and `⇣N` shows how many commits it is behind its locally known upstream ref. Unknown context usage is rendered as `?/<window>` until Pi can provide an estimate. Exceptional prompt-cache hits trigger the celebration described below.
|
|
14
14
|
- **Worktree lines** — when the session works in or sends tool calls into linked worktrees, one line shows the same branch/dirty/behind state for each worktree plus its associated PR number.
|
|
15
15
|
- **Final line** — the full Pi session ID.
|
|
16
16
|
|
|
17
17
|
It uses a fixed true-color palette with context warning thresholds.
|
|
18
18
|
|
|
19
|
+
## Subscription usage meters
|
|
20
|
+
|
|
21
|
+
When Pi's `~/.pi/agent/auth.json` contains OAuth credentials for Anthropic (Claude subscription) and/or OpenAI Codex, line 1 shows **percent remaining** for each rate-limit window after the context meter:
|
|
22
|
+
|
|
23
|
+
- ` 97·54` — Claude 5-hour, then weekly remaining percent (Nerd Font `nf-cod-claude` icon). Subscriptions with a model-scoped weekly limit (e.g. Fable) show it as a third number — ` 97·54·24` — and it is omitted when the account has none.
|
|
24
|
+
- ` 80` — Codex weekly remaining percent (`nf-cod-openai` icon)
|
|
25
|
+
|
|
26
|
+
Numbers are colored by remaining headroom: green above 60, yellow 41–60, orange 16–40, red at 15 and below.
|
|
27
|
+
|
|
28
|
+
Usage is fetched from the providers' own usage endpoints with Pi's stored tokens — read-only; tokens are never refreshed or written. Fetches happen on session start and after each turn, throttled to once per minute, and are strictly best-effort: on any failure the last-known value is kept, and providers without credentials (or before the first successful fetch) are simply omitted, leaving the statusline exactly as before. Requires a Nerd Font new enough to include the codicon brand glyphs (v3.5.0+); older fonts render them as replacement boxes.
|
|
29
|
+
|
|
19
30
|
## Neon cache-wave celebration
|
|
20
31
|
|
|
21
32
|
Whenever one assistant response reaches a prompt-cache hit rate of at least 90%, a temporary module is appended after context usage for about two seconds:
|
|
22
33
|
|
|
23
34
|
```text
|
|
24
|
-
gpt-5.6-sol | pi-extensions:main | 135k/272k | ⚡
|
|
35
|
+
gpt-5.6-sol | pi-extensions:main | 135k/272k | ⚡96%·CACHE·HIT
|
|
25
36
|
```
|
|
26
37
|
|
|
27
|
-
Only the `⚡
|
|
38
|
+
Only the `⚡96%·CACHE·HIT` badge animates: the whole badge flashes between neon magenta and neon cyan every 60 ms. The existing model, repository, context, separators, worktree, and session-ID rendering do not change.
|
|
28
39
|
|
|
29
40
|
The rate is evaluated per provider response as:
|
|
30
41
|
|
package/cache-celebration.ts
CHANGED
package/index.ts
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
triggerCacheCelebrationForMessage,
|
|
8
8
|
} from "./cache-celebration.ts";
|
|
9
9
|
import { FullRedrawScheduler } from "./redraw.ts";
|
|
10
|
+
import { type UsageSnapshot, usageBand, UsageTracker } from "./usage.ts";
|
|
10
11
|
import {
|
|
11
12
|
type GitRepositoryStatus,
|
|
12
13
|
readGitStatus,
|
|
@@ -24,6 +25,7 @@ export interface StatuslineData {
|
|
|
24
25
|
worktrees: SessionWorktree[];
|
|
25
26
|
sessionId: string;
|
|
26
27
|
cacheCelebration?: CacheCelebrationSnapshot;
|
|
28
|
+
usage?: UsageSnapshot;
|
|
27
29
|
}
|
|
28
30
|
|
|
29
31
|
const BLUE = "\x1b[38;2;0;153;255m";
|
|
@@ -35,17 +37,37 @@ const YELLOW = "\x1b[38;2;230;200;0m";
|
|
|
35
37
|
const WHITE = "\x1b[38;2;220;220;220m";
|
|
36
38
|
const MAGENTA = "\x1b[38;2;190;120;255m";
|
|
37
39
|
const NEON_CYAN = "\x1b[38;2;0;255;255m";
|
|
38
|
-
const NEON_BLUE = "\x1b[38;2;0;125;255m";
|
|
39
40
|
const NEON_MAGENTA = "\x1b[38;2;255;0;255m";
|
|
40
41
|
const DIM = "\x1b[2m";
|
|
41
42
|
const BOLD = "\x1b[1m";
|
|
42
43
|
const RESET = "\x1b[0m";
|
|
43
|
-
const NEON_WAVE = [NEON_CYAN, NEON_CYAN, NEON_BLUE, NEON_BLUE, NEON_MAGENTA, NEON_MAGENTA] as const;
|
|
44
44
|
|
|
45
45
|
function styled(style: string, text: string): string {
|
|
46
46
|
return `${style}${text}${RESET}`;
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
const CLAUDE_ICON = "\uec82";
|
|
50
|
+
const OPENAI_ICON = "\uec81";
|
|
51
|
+
const USAGE_BAND_COLORS = { green: GREEN, yellow: YELLOW, orange: ORANGE, red: RED } as const;
|
|
52
|
+
|
|
53
|
+
function remainingPercent(remaining: number): string {
|
|
54
|
+
return styled(USAGE_BAND_COLORS[usageBand(remaining)], `${remaining}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function renderUsageSegment(usage: UsageSnapshot): string | undefined {
|
|
58
|
+
const parts: string[] = [];
|
|
59
|
+
if (usage.claude) {
|
|
60
|
+
const dot = styled(DIM, "\u00b7");
|
|
61
|
+
let claude = `${remainingPercent(usage.claude.fiveHour)}${dot}${remainingPercent(usage.claude.sevenDay)}`;
|
|
62
|
+
if (usage.claude.scopedWeekly !== undefined) claude += `${dot}${remainingPercent(usage.claude.scopedWeekly)}`;
|
|
63
|
+
parts.push(`${styled(WHITE, CLAUDE_ICON)} ${claude}`);
|
|
64
|
+
}
|
|
65
|
+
if (usage.codex) {
|
|
66
|
+
parts.push(`${styled(WHITE, OPENAI_ICON)} ${remainingPercent(usage.codex.weekly)}`);
|
|
67
|
+
}
|
|
68
|
+
return parts.length > 0 ? parts.join(" ") : undefined;
|
|
69
|
+
}
|
|
70
|
+
|
|
49
71
|
function contextColor(contextTokens: number, contextWindow: number): string {
|
|
50
72
|
const percent = contextWindow > 0 ? Math.floor((contextTokens * 100) / contextWindow) : 0;
|
|
51
73
|
if (percent >= 90) return RED;
|
|
@@ -77,13 +99,9 @@ export function renderCacheCelebrationLine(
|
|
|
77
99
|
summary: string,
|
|
78
100
|
celebration: CacheCelebrationSnapshot,
|
|
79
101
|
): string {
|
|
80
|
-
const badge =
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
const color = NEON_WAVE[(index + celebration.frame) % NEON_WAVE.length];
|
|
84
|
-
return `${BOLD}${color}${character}${RESET}`;
|
|
85
|
-
})
|
|
86
|
-
.join("");
|
|
102
|
+
const badge = `⚡${celebration.percent}%·CACHE·HIT`;
|
|
103
|
+
const color = celebration.frame % 2 === 0 ? NEON_MAGENTA : NEON_CYAN;
|
|
104
|
+
const animatedBadge = `${BOLD}${color}${badge}${RESET}`;
|
|
87
105
|
return `${summary}${styled(DIM, " | ")}${animatedBadge}`;
|
|
88
106
|
}
|
|
89
107
|
|
|
@@ -112,7 +130,14 @@ export function renderStatusline(data: StatuslineData, width: number): string[]
|
|
|
112
130
|
: styled(contextColor(data.contextTokens, data.contextWindow), formatTokenCount(data.contextTokens));
|
|
113
131
|
const context = `${used}${styled(DIM, "/")}${styled(WHITE, formatTokenCount(data.contextWindow))}`;
|
|
114
132
|
const cwd = data.cwdGit ? renderRepository(data.cwd, data.cwdGit) : styled(CYAN, data.cwd);
|
|
115
|
-
const
|
|
133
|
+
const usageSegment = data.usage ? renderUsageSegment(data.usage) : undefined;
|
|
134
|
+
const summary =
|
|
135
|
+
styled(BLUE, data.model) +
|
|
136
|
+
separator +
|
|
137
|
+
cwd +
|
|
138
|
+
separator +
|
|
139
|
+
context +
|
|
140
|
+
(usageSegment ? separator + usageSegment : "");
|
|
116
141
|
const firstLine = data.cacheCelebration
|
|
117
142
|
? renderCacheCelebrationLine(summary, data.cacheCelebration)
|
|
118
143
|
: summary;
|
|
@@ -128,6 +153,7 @@ export default function statuslineExtension(pi: ExtensionAPI): void {
|
|
|
128
153
|
const fullRedraw = new FullRedrawScheduler();
|
|
129
154
|
const cacheCelebration = new CacheCelebrationController(() => requestRender?.());
|
|
130
155
|
let tracker: SessionWorktreeTracker | undefined;
|
|
156
|
+
const usageTracker = new UsageTracker({ onChange: () => requestRender?.() });
|
|
131
157
|
let cwdGit: GitRepositoryStatus | null = null;
|
|
132
158
|
let cwdStatusAbort: AbortController | undefined;
|
|
133
159
|
let cwdStatusInFlight: Promise<void> | undefined;
|
|
@@ -180,6 +206,7 @@ export default function statuslineExtension(pi: ExtensionAPI): void {
|
|
|
180
206
|
runInBackground(refreshCwdStatus(ctx));
|
|
181
207
|
runInBackground(next.seedFromEntries(ctx.sessionManager.getBranch()));
|
|
182
208
|
runInBackground(next.includeCurrentWorktree(ctx.cwd));
|
|
209
|
+
runInBackground(usageTracker.refresh());
|
|
183
210
|
};
|
|
184
211
|
|
|
185
212
|
pi.on("session_start", (_event, ctx) => {
|
|
@@ -220,6 +247,7 @@ export default function statuslineExtension(pi: ExtensionAPI): void {
|
|
|
220
247
|
worktrees: tracker?.getWorktrees() ?? [],
|
|
221
248
|
sessionId: ctx.sessionManager.getSessionId(),
|
|
222
249
|
cacheCelebration: cacheCelebration.snapshot(),
|
|
250
|
+
usage: usageTracker.snapshot(),
|
|
223
251
|
},
|
|
224
252
|
width,
|
|
225
253
|
),
|
|
@@ -240,6 +268,7 @@ export default function statuslineExtension(pi: ExtensionAPI): void {
|
|
|
240
268
|
requestRender?.();
|
|
241
269
|
runInBackground(refreshCwdStatus(ctx));
|
|
242
270
|
if (tracker) runInBackground(tracker.refresh());
|
|
271
|
+
runInBackground(usageTracker.refresh());
|
|
243
272
|
});
|
|
244
273
|
pi.on("model_select", () => requestRender?.());
|
|
245
274
|
pi.on("session_tree", (_event, ctx) => resetTracker(ctx));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hank-warren/pi-statusline",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Compact Pi footer statusline with Git/worktree context, token usage, and neon celebrations for exceptional prompt-cache hits.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
|
@@ -34,6 +34,7 @@
|
|
|
34
34
|
"index.ts",
|
|
35
35
|
"cache-celebration.ts",
|
|
36
36
|
"redraw.ts",
|
|
37
|
+
"usage.ts",
|
|
37
38
|
"worktrees.ts",
|
|
38
39
|
"README.md",
|
|
39
40
|
"LICENSE"
|
package/usage.ts
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
|
|
5
|
+
/** Remaining (not used) integer percents per provider window. */
|
|
6
|
+
export interface UsageSnapshot {
|
|
7
|
+
claude?: { fiveHour: number; sevenDay: number; scopedWeekly?: number };
|
|
8
|
+
codex?: { weekly: number };
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
12
|
+
const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
13
|
+
const REFRESH_INTERVAL_MS = 60_000;
|
|
14
|
+
const FETCH_TIMEOUT_MS = 10_000;
|
|
15
|
+
const ONE_DAY_SECONDS = 86_400;
|
|
16
|
+
|
|
17
|
+
function toRemaining(usedPercent: unknown): number | undefined {
|
|
18
|
+
if (typeof usedPercent !== "number" || !Number.isFinite(usedPercent)) return undefined;
|
|
19
|
+
return Math.round(Math.min(100, Math.max(0, 100 - usedPercent)));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface ClaudeLimitEntry {
|
|
23
|
+
kind?: unknown;
|
|
24
|
+
percent?: unknown;
|
|
25
|
+
scope?: { model?: unknown } | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Parse the Anthropic OAuth usage payload into remaining percents. Accounts
|
|
30
|
+
* with a model-scoped weekly limit (e.g. Fable) expose it in the `limits`
|
|
31
|
+
* array as `weekly_scoped`; accounts without one simply omit the entry.
|
|
32
|
+
*/
|
|
33
|
+
export function parseClaudeUsage(json: unknown): UsageSnapshot["claude"] | undefined {
|
|
34
|
+
if (typeof json !== "object" || json === null) return undefined;
|
|
35
|
+
const body = json as {
|
|
36
|
+
five_hour?: { utilization?: unknown };
|
|
37
|
+
seven_day?: { utilization?: unknown };
|
|
38
|
+
limits?: unknown;
|
|
39
|
+
};
|
|
40
|
+
const fiveHour = toRemaining(body.five_hour?.utilization);
|
|
41
|
+
const sevenDay = toRemaining(body.seven_day?.utilization);
|
|
42
|
+
if (fiveHour === undefined || sevenDay === undefined) return undefined;
|
|
43
|
+
const result: UsageSnapshot["claude"] = { fiveHour, sevenDay };
|
|
44
|
+
if (Array.isArray(body.limits)) {
|
|
45
|
+
const scoped = body.limits.find(
|
|
46
|
+
(entry): entry is ClaudeLimitEntry =>
|
|
47
|
+
typeof entry === "object" &&
|
|
48
|
+
entry !== null &&
|
|
49
|
+
(entry as ClaudeLimitEntry).kind === "weekly_scoped" &&
|
|
50
|
+
typeof (entry as ClaudeLimitEntry).percent === "number",
|
|
51
|
+
);
|
|
52
|
+
const scopedWeekly = scoped === undefined ? undefined : toRemaining(scoped.percent);
|
|
53
|
+
if (scopedWeekly !== undefined) result.scopedWeekly = scopedWeekly;
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface CodexWindow {
|
|
59
|
+
used_percent?: unknown;
|
|
60
|
+
limit_window_seconds?: unknown;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Parse the Codex usage payload, selecting the weekly (largest ≥ 1 day) window. */
|
|
64
|
+
export function parseCodexUsage(json: unknown): UsageSnapshot["codex"] | undefined {
|
|
65
|
+
if (typeof json !== "object" || json === null) return undefined;
|
|
66
|
+
const rateLimit = (json as { rate_limit?: unknown }).rate_limit;
|
|
67
|
+
if (typeof rateLimit !== "object" || rateLimit === null) return undefined;
|
|
68
|
+
const { primary_window, secondary_window } = rateLimit as {
|
|
69
|
+
primary_window?: CodexWindow | null;
|
|
70
|
+
secondary_window?: CodexWindow | null;
|
|
71
|
+
};
|
|
72
|
+
const windows = [primary_window, secondary_window].filter(
|
|
73
|
+
(window): window is CodexWindow => typeof window === "object" && window !== null,
|
|
74
|
+
);
|
|
75
|
+
const weekly = windows
|
|
76
|
+
.filter((window) => typeof window.limit_window_seconds === "number" && window.limit_window_seconds >= ONE_DAY_SECONDS)
|
|
77
|
+
.sort((a, b) => (b.limit_window_seconds as number) - (a.limit_window_seconds as number))[0];
|
|
78
|
+
const remaining = toRemaining((weekly ?? windows[0])?.used_percent);
|
|
79
|
+
return remaining === undefined ? undefined : { weekly: remaining };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Color band for a remaining percent: >60 green, >40 yellow, >15 orange, else red. */
|
|
83
|
+
export function usageBand(remaining: number): "green" | "yellow" | "orange" | "red" {
|
|
84
|
+
if (remaining > 60) return "green";
|
|
85
|
+
if (remaining > 40) return "yellow";
|
|
86
|
+
if (remaining > 15) return "orange";
|
|
87
|
+
return "red";
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
type FetchFn = (url: string, init: { headers: Record<string, string>; signal: AbortSignal }) => Promise<{
|
|
91
|
+
ok: boolean;
|
|
92
|
+
json(): Promise<unknown>;
|
|
93
|
+
}>;
|
|
94
|
+
|
|
95
|
+
export interface UsageTrackerOptions {
|
|
96
|
+
authPath?: string;
|
|
97
|
+
fetchFn?: FetchFn;
|
|
98
|
+
onChange?: () => void;
|
|
99
|
+
now?: () => number;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface AuthEntries {
|
|
103
|
+
anthropic?: { access?: unknown };
|
|
104
|
+
"openai-codex"?: { access?: unknown; accountId?: unknown };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function hasClaudeAuth(auth: AuthEntries): boolean {
|
|
108
|
+
const access = auth.anthropic?.access;
|
|
109
|
+
return typeof access === "string" && access.length > 0;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function hasCodexAuth(auth: AuthEntries): boolean {
|
|
113
|
+
const entry = auth["openai-codex"];
|
|
114
|
+
return (
|
|
115
|
+
typeof entry?.access === "string" &&
|
|
116
|
+
entry.access.length > 0 &&
|
|
117
|
+
typeof entry.accountId === "string" &&
|
|
118
|
+
entry.accountId.length > 0
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Best-effort subscription usage poller. Reads Pi's auth.json for tokens (never
|
|
124
|
+
* refreshes them), fetches both usage endpoints, and keeps the last-known good
|
|
125
|
+
* value per provider. Refreshes are throttled and must never throw.
|
|
126
|
+
*/
|
|
127
|
+
export class UsageTracker {
|
|
128
|
+
private readonly authPath: string;
|
|
129
|
+
private readonly fetchFn: FetchFn;
|
|
130
|
+
private readonly onChange?: () => void;
|
|
131
|
+
private readonly now: () => number;
|
|
132
|
+
private current: UsageSnapshot = {};
|
|
133
|
+
private lastAttempt = Number.NEGATIVE_INFINITY;
|
|
134
|
+
private inFlight: Promise<void> | undefined;
|
|
135
|
+
|
|
136
|
+
constructor(options: UsageTrackerOptions = {}) {
|
|
137
|
+
this.authPath = options.authPath ?? join(homedir(), ".pi", "agent", "auth.json");
|
|
138
|
+
this.fetchFn = options.fetchFn ?? ((url, init) => fetch(url, init));
|
|
139
|
+
this.onChange = options.onChange;
|
|
140
|
+
this.now = options.now ?? Date.now;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
snapshot(): UsageSnapshot {
|
|
144
|
+
return this.current;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Throttled refresh; resolves when the current attempt (if any) settles. */
|
|
148
|
+
refresh(): Promise<void> {
|
|
149
|
+
if (this.inFlight) return this.inFlight;
|
|
150
|
+
if (this.now() - this.lastAttempt < REFRESH_INTERVAL_MS) return Promise.resolve();
|
|
151
|
+
this.lastAttempt = this.now();
|
|
152
|
+
const attempt = this.performRefresh()
|
|
153
|
+
.catch(() => {
|
|
154
|
+
// Usage display is best-effort and must never interrupt the agent.
|
|
155
|
+
})
|
|
156
|
+
.finally(() => {
|
|
157
|
+
if (this.inFlight === attempt) this.inFlight = undefined;
|
|
158
|
+
});
|
|
159
|
+
this.inFlight = attempt;
|
|
160
|
+
return attempt;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
private async performRefresh(): Promise<void> {
|
|
164
|
+
const auth = (await this.readAuth()) ?? {};
|
|
165
|
+
const [claude, codex] = await Promise.all([this.fetchClaude(auth), this.fetchCodex(auth)]);
|
|
166
|
+
const next: UsageSnapshot = {};
|
|
167
|
+
// A logged-out provider (missing/invalid auth entry) is dropped immediately;
|
|
168
|
+
// a fetch failure with credentials present keeps the last-known value.
|
|
169
|
+
if (hasClaudeAuth(auth)) {
|
|
170
|
+
const nextClaude = claude ?? this.current.claude;
|
|
171
|
+
if (nextClaude) next.claude = nextClaude;
|
|
172
|
+
}
|
|
173
|
+
if (hasCodexAuth(auth)) {
|
|
174
|
+
const nextCodex = codex ?? this.current.codex;
|
|
175
|
+
if (nextCodex) next.codex = nextCodex;
|
|
176
|
+
}
|
|
177
|
+
if (JSON.stringify(next) === JSON.stringify(this.current)) return;
|
|
178
|
+
this.current = next;
|
|
179
|
+
this.onChange?.();
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
private async readAuth(): Promise<AuthEntries | undefined> {
|
|
183
|
+
try {
|
|
184
|
+
const parsed: unknown = JSON.parse(await readFile(this.authPath, "utf8"));
|
|
185
|
+
if (typeof parsed !== "object" || parsed === null) return undefined;
|
|
186
|
+
return parsed as AuthEntries;
|
|
187
|
+
} catch {
|
|
188
|
+
return undefined;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
private async fetchJson(url: string, headers: Record<string, string>): Promise<unknown> {
|
|
193
|
+
const controller = new AbortController();
|
|
194
|
+
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
195
|
+
try {
|
|
196
|
+
const response = await this.fetchFn(url, { headers, signal: controller.signal });
|
|
197
|
+
if (!response.ok) return undefined;
|
|
198
|
+
return await response.json();
|
|
199
|
+
} finally {
|
|
200
|
+
clearTimeout(timeout);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
private async fetchClaude(auth: AuthEntries): Promise<UsageSnapshot["claude"] | undefined> {
|
|
205
|
+
if (!hasClaudeAuth(auth)) return undefined;
|
|
206
|
+
try {
|
|
207
|
+
return parseClaudeUsage(
|
|
208
|
+
await this.fetchJson(CLAUDE_USAGE_URL, {
|
|
209
|
+
Authorization: `Bearer ${auth.anthropic?.access as string}`,
|
|
210
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
211
|
+
}),
|
|
212
|
+
);
|
|
213
|
+
} catch {
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private async fetchCodex(auth: AuthEntries): Promise<UsageSnapshot["codex"] | undefined> {
|
|
219
|
+
if (!hasCodexAuth(auth)) return undefined;
|
|
220
|
+
const entry = auth["openai-codex"];
|
|
221
|
+
const access = entry?.access as string;
|
|
222
|
+
const accountId = entry?.accountId as string;
|
|
223
|
+
try {
|
|
224
|
+
return parseCodexUsage(
|
|
225
|
+
await this.fetchJson(CODEX_USAGE_URL, {
|
|
226
|
+
Authorization: `Bearer ${access}`,
|
|
227
|
+
"chatgpt-account-id": accountId,
|
|
228
|
+
}),
|
|
229
|
+
);
|
|
230
|
+
} catch {
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|