@cad0p/pi-usage 0.11.5 → 0.11.6
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 +22 -0
- package/README.md +81 -39
- package/bin/piquota.js +12 -2
- package/extensions/quota-panel.ts +532 -184
- package/package.json +1 -1
- package/src/cache.js +128 -31
- package/src/cli/commands/omarchy.js +21 -3
- package/src/engine.js +98 -7
- package/src/local/pi-sessions.js +28 -1
- package/src/local/stats-worker.js +27 -0
- package/src/local/worker.js +157 -0
- package/src/model.js +39 -5
- package/src/omarchy/publish.js +9 -8
- package/src/overlay-keys.js +257 -0
- package/src/providers/antigravity-oauth.js +43 -3
- package/src/providers/antigravity.js +44 -5
- package/src/refresh.js +4 -1
|
@@ -26,14 +26,26 @@
|
|
|
26
26
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
27
27
|
import { existsSync, readFileSync } from "node:fs";
|
|
28
28
|
import { homedir } from "node:os";
|
|
29
|
-
import {
|
|
29
|
+
import { join } from "node:path";
|
|
30
30
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
32
|
+
import { extractChatGptAccountId, extractExpiresAtMs } from "../src/auth/jwt.js";
|
|
33
|
+
import { mergeReportIntoCache, writeCache } from "../src/cache.js";
|
|
34
|
+
import { normalizeClaudeSourceMode, collectFamily, enabledFamilies, FAMILIES } from "../src/engine.js";
|
|
35
|
+
import { historyJson } from "../src/cli/commands/stats.js";
|
|
36
|
+
import { resolveHistoryDir } from "../src/local/history.js";
|
|
37
|
+
import { startLocalStatsWorker } from "../src/local/worker.js";
|
|
38
|
+
import { publishRecords } from "../src/omarchy/publish.js";
|
|
39
|
+
import { buildRecords } from "../src/omarchy/record.js";
|
|
40
|
+
import { skippedFamilies } from "../src/cli/commands/omarchy.js";
|
|
41
|
+
import { isKeyRelease, matchesKey, matchesPrintable } from "../src/overlay-keys.js";
|
|
42
|
+
import { mergeLastGood } from "../src/sticky.js";
|
|
43
|
+
import { readRefreshState, resolveFamilyTtls, staleFamilies, writeRefreshState } from "../src/refresh.js";
|
|
44
|
+
|
|
45
|
+
// The in-process collector does not pass through the CLI's sticky layer, so this
|
|
46
|
+
// extension applies the same last-good merge as the CLI before painting or publishing.
|
|
47
|
+
// The classifier below mirrors src/providers/error-kind.js so the extension can
|
|
48
|
+
// render category-specific glyphs without depending on the repo.
|
|
37
49
|
|
|
38
50
|
const STATUS_KEY = "00-quota";
|
|
39
51
|
const WIDGET_KEY = "quota-line";
|
|
@@ -42,7 +54,12 @@ const RAIL_KEY = "quota";
|
|
|
42
54
|
const SIDEBAR_STATE_KEY = Symbol.for("gentle-pi.experimental-sidebar.state");
|
|
43
55
|
const REFRESH_MS = Number(process.env.PI_QUOTA_REFRESH_MS) || 300_000;
|
|
44
56
|
const AGENT_END_DEBOUNCE_MS = 1_500;
|
|
45
|
-
|
|
57
|
+
/** The report cache is keyed by the Claude source its numbers came from. */
|
|
58
|
+
const CLAUDE_SOURCE_CACHE_PREFIX = "claude-source:";
|
|
59
|
+
|
|
60
|
+
function cacheKeyFor(source: string): string {
|
|
61
|
+
return `${CLAUDE_SOURCE_CACHE_PREFIX}${normalizeClaudeSourceMode(source)}`;
|
|
62
|
+
}
|
|
46
63
|
|
|
47
64
|
type QuotaWindow = {
|
|
48
65
|
id: string;
|
|
@@ -124,9 +141,32 @@ type Theme = {
|
|
|
124
141
|
bg?: (key: string, text: string) => string;
|
|
125
142
|
};
|
|
126
143
|
|
|
144
|
+
/**
|
|
145
|
+
* One running local token scan. It is a handle, not a promise, because the scan
|
|
146
|
+
* can outlive the session that started it: a shutdown has to be able to end it
|
|
147
|
+
* and have its lock and cache left clean.
|
|
148
|
+
*/
|
|
149
|
+
type LocalStatsScan = {
|
|
150
|
+
result: Promise<{ byFamily: Record<string, LocalFamilyStats>; warnings: string[]; scan: { partial?: boolean } | null }>;
|
|
151
|
+
stop: () => Promise<void>;
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
type ExtensionDependencies = {
|
|
155
|
+
collectFamily?: typeof collectFamily;
|
|
156
|
+
startLocalStats?: () => LocalStatsScan;
|
|
157
|
+
getProviderAuth?: (ctx: UiContext, provider: string) => Promise<{ auth?: { apiKey?: string }; accountId?: string; source?: string } | undefined>;
|
|
158
|
+
loadHistory?: (month: string | null) => Promise<HistoryPayload> | HistoryPayload;
|
|
159
|
+
publishOmarchy?: (report: QuotaReport, prune: boolean) => void;
|
|
160
|
+
railPatcherPath?: string;
|
|
161
|
+
};
|
|
162
|
+
|
|
127
163
|
/** Only the UI surface this extension uses. */
|
|
128
164
|
type UiContext = {
|
|
129
165
|
hasUI: boolean;
|
|
166
|
+
/** Pi resolves/renews its OAuth credentials under its own auth-store lock. */
|
|
167
|
+
modelRegistry?: {
|
|
168
|
+
getProviderAuth?: (provider: string) => Promise<{ auth?: { apiKey?: string }; source?: string } | undefined>;
|
|
169
|
+
};
|
|
130
170
|
/** Pi's run mode; `custom` components only exist in the TUI. */
|
|
131
171
|
mode?: string;
|
|
132
172
|
ui: {
|
|
@@ -193,23 +233,7 @@ function usedOf(window: QuotaWindow | null): number | null {
|
|
|
193
233
|
return null;
|
|
194
234
|
}
|
|
195
235
|
|
|
196
|
-
|
|
197
|
-
const override = process.env.PI_QUOTA_BIN;
|
|
198
|
-
if (override && existsSync(override)) return override;
|
|
199
|
-
try {
|
|
200
|
-
const sibling = fileURLToPath(new URL("../bin/piquota.js", import.meta.url));
|
|
201
|
-
if (existsSync(sibling)) return sibling;
|
|
202
|
-
} catch {}
|
|
203
|
-
for (const candidate of [
|
|
204
|
-
join(homedir(), ".local", "share", "pi-quota", "bin", "piquota.js"),
|
|
205
|
-
join(homedir(), ".local", "bin", "piquota"),
|
|
206
|
-
join(homedir(), ".pi", "agent", "npm", "node_modules", "@cad0p", "pi-usage", "bin", "piquota.js"),
|
|
207
|
-
join(homedir(), ".pi", "agent", "npm", "node_modules", "@j3pf", "piquota", "bin", "piquota.js"),
|
|
208
|
-
]) {
|
|
209
|
-
if (existsSync(candidate)) return candidate;
|
|
210
|
-
}
|
|
211
|
-
return null;
|
|
212
|
-
}
|
|
236
|
+
|
|
213
237
|
|
|
214
238
|
/**
|
|
215
239
|
* Rank by how soon a window constrains you: 5h/session first, then daily,
|
|
@@ -940,27 +964,6 @@ function renderPanel(report: QuotaReport, theme: Theme): string[] {
|
|
|
940
964
|
return [...sections.flatMap((section) => [section.header, ...section.body]), ...tail];
|
|
941
965
|
}
|
|
942
966
|
|
|
943
|
-
/**
|
|
944
|
-
* Raw input sequences for the keys the overlay turns into actions. The
|
|
945
|
-
* extension ships as one file with no runtime dependencies, so this mirrors
|
|
946
|
-
* the subset of pi-tui's matchesKey() the overlay needs: arrows, paging and
|
|
947
|
-
* home/end in the encodings terminals and tmux actually send.
|
|
948
|
-
*/
|
|
949
|
-
const KEY_SEQUENCES: Record<string, string[]> = {
|
|
950
|
-
up: ["\u001b[A", "\u001bOA"],
|
|
951
|
-
down: ["\u001b[B", "\u001bOB"],
|
|
952
|
-
left: ["\u001b[D", "\u001bOD"],
|
|
953
|
-
right: ["\u001b[C", "\u001bOC"],
|
|
954
|
-
pageUp: ["\u001b[5~", "\u001b[[5~"],
|
|
955
|
-
pageDown: ["\u001b[6~", "\u001b[[6~"],
|
|
956
|
-
home: ["\u001b[H", "\u001bOH", "\u001b[1~", "\u001b[7~"],
|
|
957
|
-
end: ["\u001b[F", "\u001bOF", "\u001b[4~", "\u001b[8~"],
|
|
958
|
-
};
|
|
959
|
-
|
|
960
|
-
function isKey(data: string, name: string): boolean {
|
|
961
|
-
return (KEY_SEQUENCES[name] ?? []).includes(data);
|
|
962
|
-
}
|
|
963
|
-
|
|
964
967
|
/** Pi reports the terminal height as a number; fall back to a usable frame. */
|
|
965
968
|
function terminalRows(value: number | undefined): number {
|
|
966
969
|
return Number.isFinite(value) ? Math.max(1, Math.floor(value as number)) : 24;
|
|
@@ -1036,9 +1039,33 @@ type HistoryFamily = {
|
|
|
1036
1039
|
models: Map<string, number>;
|
|
1037
1040
|
accounts: Map<string, { tokens: number; prompts: number; models: Map<string, number> }>;
|
|
1038
1041
|
allTime: number;
|
|
1039
|
-
|
|
1042
|
+
allTimePrompts: number;
|
|
1043
|
+
allTimeAccounts: Map<string, { tokens: number; prompts: number }>;
|
|
1044
|
+
/** The live day's delta, added to both the month and the all-time figures. */
|
|
1045
|
+
liveTokens: number;
|
|
1046
|
+
livePrompts: number;
|
|
1047
|
+
liveAccounts: Map<string, { tokens: number; prompts: number }>;
|
|
1040
1048
|
};
|
|
1041
1049
|
|
|
1050
|
+
/** An all-time figure, and whether the rollup behind it lags the month on screen. */
|
|
1051
|
+
type AllTimeFigure = { value: number; lags: boolean };
|
|
1052
|
+
|
|
1053
|
+
/**
|
|
1054
|
+
* The all-time figure for one scope. All time contains every frozen day, so it
|
|
1055
|
+
* can never be smaller than a month of it: a smaller rollup means totals.json is
|
|
1056
|
+
* behind the month file — a freeze whose totals write failed, a month restored
|
|
1057
|
+
* behind the rollup. That is printed, dimmed and with a note, never hidden: the
|
|
1058
|
+
* figure is the only answer to "how much has this burned ever", and dropping it
|
|
1059
|
+
* silently is a worse lie than a number with a caveat.
|
|
1060
|
+
*/
|
|
1061
|
+
function allTimeFigure(month: number, allTime: number): AllTimeFigure {
|
|
1062
|
+
if (allTime <= 0) return { value: 0, lags: false };
|
|
1063
|
+
return { value: allTime, lags: allTime < month };
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/** The note printed with an all-time figure that cannot cover the month on screen. */
|
|
1067
|
+
const ALL_TIME_LAGS_NOTE = "all-time lags this month; run piquota stats --rebuild-totals";
|
|
1068
|
+
|
|
1042
1069
|
/**
|
|
1043
1070
|
* What outlives one overlay instance. Every bare `/usage` builds a fresh view,
|
|
1044
1071
|
* so the folds and the page it was closed on live in the extension — for the pi
|
|
@@ -1080,15 +1107,19 @@ type UsageOverlayOptions = {
|
|
|
1080
1107
|
getRows: () => number;
|
|
1081
1108
|
/** The newest report the extension holds, or null before the first one. */
|
|
1082
1109
|
getReport: () => QuotaReport | null;
|
|
1083
|
-
/**
|
|
1084
|
-
|
|
1110
|
+
/**
|
|
1111
|
+
* Every family's refresh failure, one line each, in family order. A failure
|
|
1112
|
+
* is not cleared by another family's success: the families finish out of
|
|
1113
|
+
* order, and a single shared slot made the last arrival erase the others.
|
|
1114
|
+
*/
|
|
1115
|
+
getErrors: () => string[];
|
|
1085
1116
|
isRefreshing: () => boolean;
|
|
1086
1117
|
/** Run the same forced refresh `/usage` always ran, in the background. */
|
|
1087
1118
|
refresh: () => void;
|
|
1088
1119
|
/**
|
|
1089
|
-
* Ask the extension to
|
|
1090
|
-
*
|
|
1091
|
-
*
|
|
1120
|
+
* Ask the extension to read one month in-process (null: current month). The
|
|
1121
|
+
* request id comes back with the answer, so a slow read cannot apply a month
|
|
1122
|
+
* the last keypress did not ask for.
|
|
1092
1123
|
*/
|
|
1093
1124
|
loadHistory: (month: string | null, request: number) => void;
|
|
1094
1125
|
};
|
|
@@ -1132,18 +1163,20 @@ const HISTORY_HINTS: ReadonlyArray<readonly [string, string]> = [
|
|
|
1132
1163
|
["esc/q", "close"],
|
|
1133
1164
|
];
|
|
1134
1165
|
|
|
1135
|
-
/** The report cache the CLI
|
|
1166
|
+
/** The report cache the CLI and in-process extension share. */
|
|
1136
1167
|
function reportCachePath(): string {
|
|
1137
1168
|
const cacheHome = process.env.XDG_CACHE_HOME || join(homedir(), ".cache");
|
|
1138
1169
|
return join(cacheHome, "pi-quota", "usage.json");
|
|
1139
1170
|
}
|
|
1140
1171
|
|
|
1141
1172
|
/**
|
|
1142
|
-
* The last report
|
|
1143
|
-
*
|
|
1144
|
-
*
|
|
1173
|
+
* The last report on disk, read synchronously so the overlay paints on the same
|
|
1174
|
+
* keystroke as /usage: read-only, age is irrelevant for a first frame, and a
|
|
1175
|
+
* missing or malformed cache is simply "no cached report". The key travels back
|
|
1176
|
+
* with it because it names the Claude source those numbers came from, and a
|
|
1177
|
+
* later partial write has to keep describing the same data.
|
|
1145
1178
|
*/
|
|
1146
|
-
function readCachedReport(): QuotaReport | null {
|
|
1179
|
+
function readCachedReport(): { report: QuotaReport; key: string | null } | null {
|
|
1147
1180
|
try {
|
|
1148
1181
|
const parsed = JSON.parse(readFileSync(reportCachePath(), "utf-8"));
|
|
1149
1182
|
const report = parsed?.report;
|
|
@@ -1157,7 +1190,10 @@ function readCachedReport(): QuotaReport | null {
|
|
|
1157
1190
|
if (!Number.isNaN(resetsAtMs)) window.resetsInSec = Math.max(0, Math.round((resetsAtMs - now) / 1000));
|
|
1158
1191
|
}
|
|
1159
1192
|
}
|
|
1160
|
-
return
|
|
1193
|
+
return {
|
|
1194
|
+
report: report as QuotaReport,
|
|
1195
|
+
key: typeof parsed?.key === "string" ? parsed.key : null,
|
|
1196
|
+
};
|
|
1161
1197
|
} catch {
|
|
1162
1198
|
return null;
|
|
1163
1199
|
}
|
|
@@ -1188,32 +1224,23 @@ function redactCause(value: string): string {
|
|
|
1188
1224
|
.replace(/\b((?:__Host-console_session|auth)=)[^;\s]+/gi, "$1<redacted>");
|
|
1189
1225
|
}
|
|
1190
1226
|
|
|
1191
|
-
/**
|
|
1192
|
-
* One short, redacted line for a failed `stats --json` run: the CLI's own first
|
|
1193
|
-
* stderr line when it printed one, otherwise its exit status. The raw parse
|
|
1194
|
-
* error ("Unexpected end of JSON input") says nothing about why the read failed.
|
|
1195
|
-
*/
|
|
1196
|
-
function cliFailureLine(result: { stdout?: string; stderr?: string; code?: number; killed?: boolean } | null | undefined): string {
|
|
1197
|
-
const first = String(result?.stderr ?? "")
|
|
1198
|
-
.split("\n")
|
|
1199
|
-
.map((line) => line.trim())
|
|
1200
|
-
.find((line) => line !== "");
|
|
1201
|
-
const code = Number(result?.code);
|
|
1202
|
-
const cause = first
|
|
1203
|
-
? redactCause(first)
|
|
1204
|
-
: result?.killed
|
|
1205
|
-
? "piquota stats was stopped (timeout)"
|
|
1206
|
-
: Number.isFinite(code) && code !== 0
|
|
1207
|
-
? `piquota stats exited ${code}`
|
|
1208
|
-
: "piquota stats --json printed no history payload";
|
|
1209
|
-
return capCause(cause);
|
|
1210
|
-
}
|
|
1211
|
-
|
|
1212
1227
|
/** A stderr line or a thrown message can quote a whole path list; the frame gets one line. */
|
|
1213
1228
|
function capCause(cause: string): string {
|
|
1214
1229
|
return cause.length > 160 ? `${cause.slice(0, 157)}…` : cause;
|
|
1215
1230
|
}
|
|
1216
1231
|
|
|
1232
|
+
/** Append warnings that are not already there: a repeated scan repeats its notes. */
|
|
1233
|
+
function mergeWarnings(existing: string[], added: string[] | undefined): string[] {
|
|
1234
|
+
const seen = new Set(existing);
|
|
1235
|
+
const merged = [...existing];
|
|
1236
|
+
for (const warning of added ?? []) {
|
|
1237
|
+
if (typeof warning !== "string" || warning === "" || seen.has(warning)) continue;
|
|
1238
|
+
seen.add(warning);
|
|
1239
|
+
merged.push(warning);
|
|
1240
|
+
}
|
|
1241
|
+
return merged;
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1217
1244
|
/** Local YYYY-MM-DD, the history's day key. */
|
|
1218
1245
|
function localDayKey(now = new Date()): string {
|
|
1219
1246
|
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-${String(now.getDate()).padStart(2, "0")}`;
|
|
@@ -1443,7 +1470,7 @@ export class UsageOverlay {
|
|
|
1443
1470
|
}
|
|
1444
1471
|
|
|
1445
1472
|
/**
|
|
1446
|
-
* A month (or the first payload, with the month list) arrived from the
|
|
1473
|
+
* A month (or the first payload, with the month list) arrived from the in-process reader.
|
|
1447
1474
|
* Every answer is cached — a later ← must not refetch what already arrived —
|
|
1448
1475
|
* but only the answer to the newest request may move the page: ←/→ overlap,
|
|
1449
1476
|
* and a late answer for a month the last keypress did not ask for used to snap
|
|
@@ -1481,21 +1508,32 @@ export class UsageOverlay {
|
|
|
1481
1508
|
this.options.requestRender();
|
|
1482
1509
|
}
|
|
1483
1510
|
|
|
1484
|
-
/**
|
|
1511
|
+
/**
|
|
1512
|
+
* Handle one raw key: switch view, fold, move, month, refresh, close.
|
|
1513
|
+
*
|
|
1514
|
+
* Keys arrive in the terminal's own encoding — legacy escape sequences or
|
|
1515
|
+
* kitty CSI sequences with an event type — so every test goes through
|
|
1516
|
+
* src/overlay-keys.js. A kitty release is the second half of a press the
|
|
1517
|
+
* terminal already reported: acting on it would move twice per keystroke.
|
|
1518
|
+
* Repeats stay presses, so a held arrow keeps moving as it does in tmux.
|
|
1519
|
+
*/
|
|
1485
1520
|
public handleInput(data: string): void {
|
|
1486
1521
|
if (this.disposed) return;
|
|
1487
|
-
if (data
|
|
1522
|
+
if (isKeyRelease(data)) return;
|
|
1523
|
+
if (matchesKey(data, "escape") || matchesPrintable(data, "q")) {
|
|
1488
1524
|
this.dispose();
|
|
1489
1525
|
this.options.done();
|
|
1490
1526
|
return;
|
|
1491
1527
|
}
|
|
1492
|
-
|
|
1493
|
-
|
|
1528
|
+
const nowKey = matchesPrintable(data, "1");
|
|
1529
|
+
const historyKey = matchesPrintable(data, "2");
|
|
1530
|
+
if (matchesKey(data, "tab") || nowKey || historyKey) {
|
|
1531
|
+
const target = nowKey ? "now" : historyKey ? "history" : this.view === "now" ? "history" : "now";
|
|
1494
1532
|
this.switchView(target);
|
|
1495
1533
|
this.invalidate();
|
|
1496
1534
|
return;
|
|
1497
1535
|
}
|
|
1498
|
-
if (data
|
|
1536
|
+
if (matchesPrintable(data, "r")) {
|
|
1499
1537
|
// History's today row comes from the live report, so a refresh there
|
|
1500
1538
|
// reloads the month and the report together; one key, one meaning.
|
|
1501
1539
|
if (this.view === "history") this.reloadMonth();
|
|
@@ -1503,17 +1541,17 @@ export class UsageOverlay {
|
|
|
1503
1541
|
this.invalidate();
|
|
1504
1542
|
return;
|
|
1505
1543
|
}
|
|
1506
|
-
if (
|
|
1507
|
-
else if (
|
|
1508
|
-
else if (data
|
|
1509
|
-
else if (
|
|
1510
|
-
else if (
|
|
1511
|
-
else if (
|
|
1512
|
-
else if (
|
|
1513
|
-
else if (this.view === "history" && (
|
|
1514
|
-
else if (this.view === "history" && (
|
|
1515
|
-
else if (
|
|
1516
|
-
else if (
|
|
1544
|
+
if (matchesKey(data, "up") || matchesPrintable(data, "k")) this.moveCursor(-1);
|
|
1545
|
+
else if (matchesKey(data, "down") || matchesPrintable(data, "j")) this.moveCursor(1);
|
|
1546
|
+
else if (matchesKey(data, "enter") || matchesKey(data, "space")) this.toggleSection();
|
|
1547
|
+
else if (matchesKey(data, "pageUp")) this.page(-1);
|
|
1548
|
+
else if (matchesKey(data, "pageDown")) this.page(1);
|
|
1549
|
+
else if (matchesKey(data, "home") || matchesPrintable(data, "g")) this.jumpTo(0);
|
|
1550
|
+
else if (matchesKey(data, "end") || matchesPrintable(data, "G")) this.jumpTo(-1);
|
|
1551
|
+
else if (this.view === "history" && (matchesKey(data, "left") || matchesPrintable(data, "["))) this.moveMonth(-1);
|
|
1552
|
+
else if (this.view === "history" && (matchesKey(data, "right") || matchesPrintable(data, "]"))) this.moveMonth(1);
|
|
1553
|
+
else if (matchesKey(data, "left") || matchesPrintable(data, "h")) this.setExpanded(false);
|
|
1554
|
+
else if (matchesKey(data, "right") || matchesPrintable(data, "l")) this.setExpanded(true);
|
|
1517
1555
|
else return;
|
|
1518
1556
|
// The TUI renders the component again after every key, so the cached frame
|
|
1519
1557
|
// and the cached row map must be dropped here, not only on report changes.
|
|
@@ -1620,8 +1658,9 @@ export class UsageOverlay {
|
|
|
1620
1658
|
this.pushRow(rows, ` ${this.theme.fg("error", `! ${failure}`)}${hint}`, -1, false);
|
|
1621
1659
|
}
|
|
1622
1660
|
} else {
|
|
1623
|
-
const error
|
|
1624
|
-
|
|
1661
|
+
for (const error of this.options.getErrors()) {
|
|
1662
|
+
rows.push({ text: ` ${this.theme.fg("error", `! ${error}`)}`, section: -1, header: false });
|
|
1663
|
+
}
|
|
1625
1664
|
}
|
|
1626
1665
|
if (!layout) {
|
|
1627
1666
|
// Distinct states, distinct lines: a failed fetch used to say "loading
|
|
@@ -1819,7 +1858,19 @@ export class UsageOverlay {
|
|
|
1819
1858
|
const ensure = (family: string): HistoryFamily => {
|
|
1820
1859
|
let entry = families.get(family);
|
|
1821
1860
|
if (!entry) {
|
|
1822
|
-
entry = {
|
|
1861
|
+
entry = {
|
|
1862
|
+
tokens: 0,
|
|
1863
|
+
prompts: 0,
|
|
1864
|
+
days: new Map(),
|
|
1865
|
+
models: new Map(),
|
|
1866
|
+
accounts: new Map(),
|
|
1867
|
+
allTime: 0,
|
|
1868
|
+
allTimePrompts: 0,
|
|
1869
|
+
allTimeAccounts: new Map(),
|
|
1870
|
+
liveTokens: 0,
|
|
1871
|
+
livePrompts: 0,
|
|
1872
|
+
liveAccounts: new Map(),
|
|
1873
|
+
};
|
|
1823
1874
|
families.set(family, entry);
|
|
1824
1875
|
}
|
|
1825
1876
|
return entry;
|
|
@@ -1884,6 +1935,10 @@ export class UsageOverlay {
|
|
|
1884
1935
|
const entry = ensure(family);
|
|
1885
1936
|
entry.tokens += tokens;
|
|
1886
1937
|
entry.prompts += prompts;
|
|
1938
|
+
// Kept apart from the frozen month: the all-time figures add this same
|
|
1939
|
+
// delta below, and a live day may only ever be counted once in each.
|
|
1940
|
+
entry.liveTokens += tokens;
|
|
1941
|
+
entry.livePrompts += prompts;
|
|
1887
1942
|
entry.days.set(today, (entry.days.get(today) ?? 0) + tokens);
|
|
1888
1943
|
for (const [model, modelTokens] of Object.entries(familyStats.todayTokensByModel ?? {})) {
|
|
1889
1944
|
entry.models.set(model, (entry.models.get(model) ?? 0) + Math.max(0, Math.round(Number(modelTokens) || 0)));
|
|
@@ -1891,8 +1946,12 @@ export class UsageOverlay {
|
|
|
1891
1946
|
for (const [rawLabel, account] of Object.entries(familyStats.byAccount ?? {})) {
|
|
1892
1947
|
const label = rawLabel === "#1" ? "" : rawLabel;
|
|
1893
1948
|
const target = entry.accounts.get(label) ?? { tokens: 0, prompts: 0, models: new Map<string, number>() };
|
|
1894
|
-
|
|
1895
|
-
|
|
1949
|
+
const accountTokens = Math.max(0, Math.round(Number(account?.todayTokens) || 0));
|
|
1950
|
+
const accountPrompts = Math.max(0, Math.round(Number(account?.todayPrompts) || 0));
|
|
1951
|
+
target.tokens += accountTokens;
|
|
1952
|
+
target.prompts += accountPrompts;
|
|
1953
|
+
const liveAccount = entry.liveAccounts.get(label) ?? { tokens: 0, prompts: 0 };
|
|
1954
|
+
entry.liveAccounts.set(label, { tokens: liveAccount.tokens + accountTokens, prompts: liveAccount.prompts + accountPrompts });
|
|
1896
1955
|
// The account's own models for today: without them the merged row
|
|
1897
1956
|
// shows a month total and no model, which reads as "no usage".
|
|
1898
1957
|
for (const [model, modelTokens] of Object.entries(account?.todayTokensByModel ?? {})) {
|
|
@@ -1906,10 +1965,33 @@ export class UsageOverlay {
|
|
|
1906
1965
|
for (const [family, totals] of Object.entries(payload.totals?.families ?? {})) {
|
|
1907
1966
|
const entry = ensure(family);
|
|
1908
1967
|
entry.allTime = Object.values(totals?.modelUsage ?? {}).reduce((sum, bucket) => sum + totalsModelTokens(bucket), 0);
|
|
1968
|
+
entry.allTimePrompts = Math.max(0, Math.round(Number(totals?.totalPrompts) || 0));
|
|
1909
1969
|
for (const [rawLabel, account] of Object.entries(totals?.accounts ?? {})) {
|
|
1910
1970
|
const label = rawLabel === "#1" ? "" : rawLabel;
|
|
1911
1971
|
const tokens = Object.values(account?.modelUsage ?? {}).reduce((sum, bucket) => sum + totalsModelTokens(bucket), 0);
|
|
1912
|
-
|
|
1972
|
+
const prompts = Math.max(0, Math.round(Number(account?.totalPrompts) || 0));
|
|
1973
|
+
const seen = entry.allTimeAccounts.get(label) ?? { tokens: 0, prompts: 0 };
|
|
1974
|
+
entry.allTimeAccounts.set(label, { tokens: seen.tokens + tokens, prompts: seen.prompts + prompts });
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
// Today's live day is part of all time, not only of this month: it is the
|
|
1979
|
+
// same usage the month row and the day row above already show, so it is
|
|
1980
|
+
// added here exactly once — the single place the live delta is folded into
|
|
1981
|
+
// a rollup, and only under the merge guard above (the day frozen, or a
|
|
1982
|
+
// report from another day, never produces a delta at all).
|
|
1983
|
+
//
|
|
1984
|
+
// A family with no rollup in totals.json gets nothing: there is no all-time
|
|
1985
|
+
// figure to extend, and calling today's tokens "all-time" would hide every
|
|
1986
|
+
// frozen day before it. The page already carries the CLI's note for that.
|
|
1987
|
+
for (const [family, entry] of families) {
|
|
1988
|
+
if (!payload.totals?.families?.[family]) continue;
|
|
1989
|
+
if (entry.liveTokens === 0 && entry.livePrompts === 0) continue;
|
|
1990
|
+
entry.allTime += entry.liveTokens;
|
|
1991
|
+
entry.allTimePrompts += entry.livePrompts;
|
|
1992
|
+
for (const [label, delta] of entry.liveAccounts) {
|
|
1993
|
+
const seen = entry.allTimeAccounts.get(label) ?? { tokens: 0, prompts: 0 };
|
|
1994
|
+
entry.allTimeAccounts.set(label, { tokens: seen.tokens + delta.tokens, prompts: seen.prompts + delta.prompts });
|
|
1913
1995
|
}
|
|
1914
1996
|
}
|
|
1915
1997
|
|
|
@@ -1936,10 +2018,29 @@ export class UsageOverlay {
|
|
|
1936
2018
|
// Multi-account families use the same short name as the Now panel header.
|
|
1937
2019
|
const display = accountLabels.length > 1 ? SHORT_NAME[family] ?? FAMILY_LABEL[family] ?? family : FAMILY_LABEL[family] ?? family;
|
|
1938
2020
|
const name = paint(BRAND[family] ?? "#8B949E", display);
|
|
2021
|
+
// The month first, then the all-time rollup with today's live day folded
|
|
2022
|
+
// in: every figure here counts a live day once. Prompts are scope-labelled
|
|
2023
|
+
// in their own row below, because an unlabelled count reads as the wrong
|
|
2024
|
+
// one of the two.
|
|
2025
|
+
//
|
|
2026
|
+
// Every all-time figure is computed before the first line is built: the
|
|
2027
|
+
// note a lagging rollup earns belongs at the top of the section, where it
|
|
2028
|
+
// explains the header, the prompts row and the account rows at once.
|
|
1939
2029
|
const meta = [`${formatTokens(entry.tokens)} in ${month}`];
|
|
1940
|
-
|
|
1941
|
-
if (
|
|
2030
|
+
const familyAllTime = allTimeFigure(entry.tokens, entry.allTime);
|
|
2031
|
+
if (familyAllTime.value > 0) meta.push(`${formatTokens(familyAllTime.value)} all-time`);
|
|
2032
|
+
const promptsAllTime = allTimeFigure(entry.prompts, entry.allTimePrompts);
|
|
2033
|
+
const accountAllTime = new Map<string, AllTimeFigure>();
|
|
2034
|
+
for (const accountLabel of accountLabels) {
|
|
2035
|
+
accountAllTime.set(
|
|
2036
|
+
accountLabel,
|
|
2037
|
+
allTimeFigure(entry.accounts.get(accountLabel)?.tokens ?? 0, entry.allTimeAccounts.get(accountLabel)?.tokens ?? 0),
|
|
2038
|
+
);
|
|
2039
|
+
}
|
|
2040
|
+
const lagsMonth =
|
|
2041
|
+
familyAllTime.lags || promptsAllTime.lags || Array.from(accountAllTime.values()).some((figure) => figure.lags);
|
|
1942
2042
|
const body: string[] = [];
|
|
2043
|
+
if (lagsMonth) body.push(` ${this.theme.fg("warning", `~ ${ALL_TIME_LAGS_NOTE}`)}`);
|
|
1943
2044
|
const label = (text: string) => ` ${this.theme.fg("dim", text.padEnd(6))} `;
|
|
1944
2045
|
const rest = ` ${" ".repeat(8)}`;
|
|
1945
2046
|
const dayCells = Array.from(entry.days.entries())
|
|
@@ -1951,6 +2052,22 @@ export class UsageOverlay {
|
|
|
1951
2052
|
rest,
|
|
1952
2053
|
bodyWidth,
|
|
1953
2054
|
));
|
|
2055
|
+
// Both scopes, always: the live day is merged into each of them once, so
|
|
2056
|
+
// the month count and the all-time count may never disagree about it.
|
|
2057
|
+
const promptCells: string[] = [];
|
|
2058
|
+
if (entry.prompts > 0) promptCells.push(`${entry.prompts} in ${month}`);
|
|
2059
|
+
if (promptsAllTime.value > 0) {
|
|
2060
|
+
// A figure that lags the month is still a figure: it is printed, dimmed
|
|
2061
|
+
// whole, and the note above the rows says why it is small.
|
|
2062
|
+
promptCells.push(
|
|
2063
|
+
promptsAllTime.lags
|
|
2064
|
+
? this.theme.fg("dim", `${promptsAllTime.value} all-time`)
|
|
2065
|
+
: `${promptsAllTime.value} ${this.theme.fg("dim", "all-time")}`,
|
|
2066
|
+
);
|
|
2067
|
+
}
|
|
2068
|
+
if (promptCells.length > 0) {
|
|
2069
|
+
body.push(...wrapCells(promptCells, label("prompts"), rest, bodyWidth));
|
|
2070
|
+
}
|
|
1954
2071
|
if (entry.models.size > 0) {
|
|
1955
2072
|
const top = Array.from(entry.models.entries()).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
|
|
1956
2073
|
const shown = top.slice(0, 5).map(([model, tokens]) => `${shortModelName(model)} ${formatTokens(tokens)}`);
|
|
@@ -1962,8 +2079,14 @@ export class UsageOverlay {
|
|
|
1962
2079
|
for (const accountLabel of accountLabels) {
|
|
1963
2080
|
const account = entry.accounts.get(accountLabel) ?? { tokens: 0, prompts: 0, models: new Map<string, number>() };
|
|
1964
2081
|
const parts = [`${this.theme.fg("dim", "month")} ${formatTokens(account.tokens)}`];
|
|
1965
|
-
const
|
|
1966
|
-
if (
|
|
2082
|
+
const accountFigure = accountAllTime.get(accountLabel) ?? { value: 0, lags: false };
|
|
2083
|
+
if (accountFigure.value > 0) {
|
|
2084
|
+
parts.push(
|
|
2085
|
+
accountFigure.lags
|
|
2086
|
+
? this.theme.fg("dim", `all-time ${formatTokens(accountFigure.value)}`)
|
|
2087
|
+
: `${this.theme.fg("dim", "all-time")} ${formatTokens(accountFigure.value)}`,
|
|
2088
|
+
);
|
|
2089
|
+
}
|
|
1967
2090
|
const best = Array.from(account.models.entries()).sort((a, b) => b[1] - a[1])[0];
|
|
1968
2091
|
if (best) parts.push(this.theme.fg("dim", shortModelName(best[0])));
|
|
1969
2092
|
body.push(` ${this.theme.fg("dim", accountLabel.padEnd(labelWidth))} ${parts.join(this.theme.fg("dim", " · "))}`);
|
|
@@ -2008,7 +2131,7 @@ export class UsageOverlay {
|
|
|
2008
2131
|
} else {
|
|
2009
2132
|
const report = this.options.getReport();
|
|
2010
2133
|
if (report) parts.push(this.theme.fg("dim", updatedAtLabel(report)));
|
|
2011
|
-
if (this.options.
|
|
2134
|
+
if (this.options.getErrors().length > 0) parts.push(this.theme.fg("error", "refresh failed"));
|
|
2012
2135
|
}
|
|
2013
2136
|
if (this.view === "history") {
|
|
2014
2137
|
const status = this.historyStatus;
|
|
@@ -2055,9 +2178,34 @@ export class UsageOverlay {
|
|
|
2055
2178
|
}
|
|
2056
2179
|
}
|
|
2057
2180
|
|
|
2058
|
-
export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
2181
|
+
export default function quotaPanelExtension(pi: ExtensionAPI, dependencies: ExtensionDependencies = {}): void {
|
|
2182
|
+
const loadFamily = dependencies.collectFamily ?? collectFamily;
|
|
2183
|
+
const startScan = dependencies.startLocalStats ?? (() => startLocalStatsWorker() as LocalStatsScan);
|
|
2184
|
+
const getProviderAuth = dependencies.getProviderAuth ?? (async (ctx, provider) => ctx.modelRegistry?.getProviderAuth?.(provider));
|
|
2185
|
+
const readHistory = (month: string | null) => dependencies.loadHistory
|
|
2186
|
+
? dependencies.loadHistory(month)
|
|
2187
|
+
: (historyJson({ historyDir: resolveHistoryDir(), month }) as HistoryPayload);
|
|
2188
|
+
const publishOmarchy = dependencies.publishOmarchy ?? ((value, prune) => {
|
|
2189
|
+
const skip = skippedFamilies(process.env);
|
|
2190
|
+
const reportToPublish = skip.size > 0
|
|
2191
|
+
? { ...value, providers: value.providers.filter((provider) => !skip.has(provider.family)) }
|
|
2192
|
+
: value;
|
|
2193
|
+
publishRecords(buildRecords(reportToPublish as any), { prune });
|
|
2194
|
+
});
|
|
2059
2195
|
let report: QuotaReport | null = null;
|
|
2060
|
-
|
|
2196
|
+
const inFlight = new Map<string, Promise<boolean>>();
|
|
2197
|
+
let resultGeneration = 0;
|
|
2198
|
+
let prunedGeneration = 0;
|
|
2199
|
+
let localStatsInFlight: Promise<void> | null = null;
|
|
2200
|
+
let localStatsScan: LocalStatsScan | null = null;
|
|
2201
|
+
let localStatsResult: Awaited<LocalStatsScan["result"]> | null = null;
|
|
2202
|
+
/**
|
|
2203
|
+
* The notes the scan produced (its own warnings, or the one line a failure
|
|
2204
|
+
* becomes). They live here, not only in the report, because the scan can
|
|
2205
|
+
* finish before the first family does: it is the report that is late then,
|
|
2206
|
+
* not the warning.
|
|
2207
|
+
*/
|
|
2208
|
+
let localStatsWarnings: string[] = [];
|
|
2061
2209
|
let timer: ReturnType<typeof setInterval> | null = null;
|
|
2062
2210
|
let agentEndTimer: ReturnType<typeof setTimeout> | null = null;
|
|
2063
2211
|
let panelVisible = false;
|
|
@@ -2080,22 +2228,30 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2080
2228
|
let explicitBox = false;
|
|
2081
2229
|
/** gentle-pi owns the footer and truncates it from the end, so start off. */
|
|
2082
2230
|
let statusVisible = false;
|
|
2083
|
-
|
|
2231
|
+
/** One failure per family: an out-of-order success must not hide another's. */
|
|
2232
|
+
const familyErrors = new Map<string, string>();
|
|
2233
|
+
/**
|
|
2234
|
+
* The Claude source the report in memory actually came from. The extension
|
|
2235
|
+
* forces Pi's own OAuth when Pi resolves a token, and that is a different
|
|
2236
|
+
* fact from what PI_QUOTA_CLAUDE_SOURCE says: keying the cache by the setting
|
|
2237
|
+
* alone stored Pi-sourced numbers under the CLI's auto/claude-code key, where
|
|
2238
|
+
* the next reader asked the other question and was served them anyway.
|
|
2239
|
+
*/
|
|
2240
|
+
let claudeSourceUsed: string | null = null;
|
|
2084
2241
|
let disposed = false;
|
|
2085
2242
|
/** True once the installed gentle-pi is known to paint a rail slot for this card. */
|
|
2086
2243
|
let railMode = false;
|
|
2087
2244
|
|
|
2088
2245
|
/**
|
|
2089
|
-
* Load the rail inspector from
|
|
2090
|
-
* native-layout detection; the runtime chaining
|
|
2246
|
+
* Load the rail inspector from this package, not from a quota CLI subprocess.
|
|
2247
|
+
* A missing patcher disables native-layout detection; the runtime chaining
|
|
2248
|
+
* hook remains available.
|
|
2091
2249
|
*/
|
|
2092
2250
|
async function loadRailPatcher(): Promise<{
|
|
2093
2251
|
resolveGentlePiLayout: (options?: { dir?: string }) => { layoutPath: string; present: boolean };
|
|
2094
2252
|
inspectRailPatch: (options: { layoutPath: string }) => { state: string };
|
|
2095
2253
|
} | null> {
|
|
2096
|
-
const
|
|
2097
|
-
if (!cli) return null;
|
|
2098
|
-
const modulePath = join(dirname(cli), "..", "src", "gentle-pi", "rail-patch.js");
|
|
2254
|
+
const modulePath = dependencies.railPatcherPath ?? fileURLToPath(new URL("../src/gentle-pi/rail-patch.js", import.meta.url));
|
|
2099
2255
|
if (!existsSync(modulePath)) return null;
|
|
2100
2256
|
try {
|
|
2101
2257
|
return await import(pathToFileURL(modulePath).href);
|
|
@@ -2115,35 +2271,211 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2115
2271
|
railMode = inspection.state === "patched";
|
|
2116
2272
|
}
|
|
2117
2273
|
|
|
2274
|
+
/** Whether a family refresh is in flight; the header shows it while one is. */
|
|
2275
|
+
function isRefreshing(): boolean {
|
|
2276
|
+
return inFlight.size > 0;
|
|
2277
|
+
}
|
|
2278
|
+
|
|
2279
|
+
/** Resolve Pi's own auth for the two rotating OAuth providers. Tokens stay local to this call. */
|
|
2280
|
+
async function authOverridesFor(ctx: UiContext, family: string): Promise<Record<string, { access: string; expiresAtMs: number | null; accountId?: string }> | undefined> {
|
|
2281
|
+
const provider = family === "claude" ? "anthropic" : family === "codex" ? "openai-codex" : null;
|
|
2282
|
+
if (!provider) return undefined;
|
|
2283
|
+
try {
|
|
2284
|
+
const resolved = await getProviderAuth(ctx, provider);
|
|
2285
|
+
// Pi can resolve api_key credentials through the same method. Quota
|
|
2286
|
+
// endpoints here require the subscription OAuth access token, not an API
|
|
2287
|
+
// key; only Pi's OAuth result is eligible for the in-memory override.
|
|
2288
|
+
if (resolved?.source !== "OAuth") return undefined;
|
|
2289
|
+
const token = resolved.auth?.apiKey;
|
|
2290
|
+
if (typeof token !== "string" || token.length === 0) return undefined;
|
|
2291
|
+
const accountId = (typeof resolved?.accountId === "string" && resolved.accountId) || extractChatGptAccountId(token) || undefined;
|
|
2292
|
+
return {
|
|
2293
|
+
[provider]: {
|
|
2294
|
+
access: token,
|
|
2295
|
+
expiresAtMs: extractExpiresAtMs(token),
|
|
2296
|
+
...(family === "codex" && accountId ? { accountId } : {}),
|
|
2297
|
+
},
|
|
2298
|
+
};
|
|
2299
|
+
} catch {
|
|
2300
|
+
// Never put arbitrary auth errors in a TUI frame; the engine will report its read-only credential state.
|
|
2301
|
+
return undefined;
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
|
|
2305
|
+
function mergeFamilyReport(fragment: QuotaReport): void {
|
|
2306
|
+
const prior = report;
|
|
2307
|
+
const merged = mergeReportIntoCache(prior, fragment as any) as QuotaReport;
|
|
2308
|
+
merged.localStats = localStatsResult?.byFamily ?? prior?.localStats ?? fragment.localStats ?? {};
|
|
2309
|
+
merged.localStatsMeta = localStatsResult?.scan ?? prior?.localStatsMeta ?? fragment.localStatsMeta ?? null;
|
|
2310
|
+
merged.warnings = mergeWarnings(merged.warnings ?? [], localStatsWarnings);
|
|
2311
|
+
const families = enabledFamilies({ env: process.env, requested: FAMILIES });
|
|
2312
|
+
const ordering = [...families, ...Object.keys(merged.byFamily).filter((family) => !families.includes(family))];
|
|
2313
|
+
merged.providers = ordering.flatMap((family) => merged.providers.filter((provider) => provider.family === family));
|
|
2314
|
+
merged.byFamily = Object.fromEntries(
|
|
2315
|
+
ordering
|
|
2316
|
+
.map((family) => [family, merged.providers.filter((provider) => provider.family === family)] as const)
|
|
2317
|
+
.filter(([, providers]) => providers.length > 0),
|
|
2318
|
+
);
|
|
2319
|
+
report = merged;
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2118
2322
|
/**
|
|
2119
|
-
*
|
|
2120
|
-
*
|
|
2323
|
+
* The report in memory, or the one on disk. Reading the cache also adopts the
|
|
2324
|
+
* Claude source its key names, so a codex-only write keeps describing the
|
|
2325
|
+
* Claude numbers the file already holds.
|
|
2121
2326
|
*/
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
const
|
|
2125
|
-
if (!
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2327
|
+
function ensureReport(): QuotaReport | null {
|
|
2328
|
+
if (report) return report;
|
|
2329
|
+
const cached = readCachedReport();
|
|
2330
|
+
if (!cached) return null;
|
|
2331
|
+
const stored = cached.key?.startsWith(CLAUDE_SOURCE_CACHE_PREFIX)
|
|
2332
|
+
? cached.key.slice(CLAUDE_SOURCE_CACHE_PREFIX.length)
|
|
2333
|
+
: null;
|
|
2334
|
+
if (stored) claudeSourceUsed = normalizeClaudeSourceMode(stored);
|
|
2335
|
+
report = cached.report;
|
|
2336
|
+
return report;
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
/** The key this report belongs under: the source it used, not the setting. */
|
|
2340
|
+
function cacheKey(): string {
|
|
2341
|
+
return cacheKeyFor(claudeSourceUsed ?? process.env.PI_QUOTA_CLAUDE_SOURCE ?? "");
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
function persistReport(freshFamilies: string[] = []): void {
|
|
2345
|
+
if (!report) return;
|
|
2346
|
+
// Every family keeps the clock it was fetched on: this report is written one
|
|
2347
|
+
// family at a time, and stamping the whole file with "now" made Claude's
|
|
2348
|
+
// five-minute-old numbers look as fresh as the Codex ones saved beside them.
|
|
2349
|
+
// Only the family that just resolved is "now"; a family without a clock in
|
|
2350
|
+
// refresh-state keeps the cache's, or its own results' age.
|
|
2351
|
+
writeCache(report as any, { key: cacheKey(), fetchedAtMs: readRefreshState().fetchedAtMs, freshFamilies });
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
function updateFamilyClock(family: string): void {
|
|
2355
|
+
const state = readRefreshState();
|
|
2356
|
+
writeRefreshState({ fetchedAtMs: { ...state.fetchedAtMs, [family]: Date.now() } });
|
|
2357
|
+
}
|
|
2358
|
+
|
|
2359
|
+
function startLocalStats(ctx: UiContext): void {
|
|
2360
|
+
if (process.env.PI_QUOTA_LOCAL_STATS === "0" || localStatsInFlight) return;
|
|
2361
|
+
const scan = startScan();
|
|
2362
|
+
localStatsScan = scan;
|
|
2363
|
+
const task = scan.result
|
|
2364
|
+
.then((result) => {
|
|
2365
|
+
if (disposed) return;
|
|
2366
|
+
localStatsResult = result;
|
|
2367
|
+
// The scan's own notes (a corrupt cache, an unreadable file) are part of
|
|
2368
|
+
// the report the CLI already publishes; dropping them here made the same
|
|
2369
|
+
// scan quieter inside Pi than in the terminal.
|
|
2370
|
+
localStatsWarnings = result.warnings ?? [];
|
|
2371
|
+
if (report) {
|
|
2372
|
+
report = {
|
|
2373
|
+
...report,
|
|
2374
|
+
localStats: result.byFamily,
|
|
2375
|
+
localStatsMeta: result.scan,
|
|
2376
|
+
warnings: mergeWarnings(report.warnings, localStatsWarnings),
|
|
2377
|
+
};
|
|
2378
|
+
persistReport();
|
|
2379
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2380
|
+
try {
|
|
2381
|
+
publishOmarchy(report, false);
|
|
2382
|
+
} catch {
|
|
2383
|
+
// The quota view is independent of the optional Omarchy record writer.
|
|
2384
|
+
}
|
|
2385
|
+
overlayView?.redraw();
|
|
2386
|
+
}
|
|
2387
|
+
})
|
|
2388
|
+
.catch((error: { name?: string; message?: string }) => {
|
|
2389
|
+
// The scan is optional, so a failure never delays or erases quotas — but
|
|
2390
|
+
// it is not the same as a scan that found nothing. The CLI reports a
|
|
2391
|
+
// failed scan as one warning line; a swallowed worker error meant a
|
|
2392
|
+
// crash in the scanner looked exactly like an empty token history.
|
|
2393
|
+
if (disposed || error?.name === "AbortError") return;
|
|
2394
|
+
const cause = capCause(redactCause(error?.message ?? String(error)).split("\n")[0]);
|
|
2395
|
+
localStatsWarnings = mergeWarnings(localStatsWarnings, [`local token stats: ${cause}`]);
|
|
2396
|
+
if (!report) return;
|
|
2397
|
+
report = { ...report, warnings: mergeWarnings(report.warnings, localStatsWarnings) };
|
|
2398
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2399
|
+
overlayView?.redraw();
|
|
2400
|
+
})
|
|
2401
|
+
.finally(() => {
|
|
2402
|
+
if (localStatsScan === scan) localStatsScan = null;
|
|
2403
|
+
if (localStatsInFlight === task) localStatsInFlight = null;
|
|
2404
|
+
});
|
|
2405
|
+
localStatsInFlight = task;
|
|
2406
|
+
}
|
|
2407
|
+
|
|
2408
|
+
/**
|
|
2409
|
+
* End the local scan this session started. Nothing it began may outlive the
|
|
2410
|
+
* session: a /quit or /reload one second into a cold scan would otherwise
|
|
2411
|
+
* keep reading the session store and hold the token-history lock until the
|
|
2412
|
+
* 120 s stale timeout, making the next scan read-only.
|
|
2413
|
+
*/
|
|
2414
|
+
async function stopLocalStats(): Promise<void> {
|
|
2415
|
+
const scan = localStatsScan;
|
|
2416
|
+
localStatsScan = null;
|
|
2417
|
+
if (!scan) return;
|
|
2418
|
+
await scan.stop();
|
|
2419
|
+
}
|
|
2420
|
+
|
|
2421
|
+
async function refreshFamily(ctx: UiContext, family: string, force: boolean): Promise<boolean> {
|
|
2422
|
+
const running = inFlight.get(family);
|
|
2423
|
+
if (running) return running;
|
|
2424
|
+
let task: Promise<boolean>;
|
|
2425
|
+
task = (async () => {
|
|
2426
|
+
try {
|
|
2427
|
+
// Explicit delay seam used by the live progressive-refresh proof; absent in normal runs.
|
|
2428
|
+
if (process.env.PI_QUOTA_DEBUG_DELAY_FAMILY === family) {
|
|
2429
|
+
const delay = Math.max(0, Math.min(30_000, Number(process.env.PI_QUOTA_DEBUG_DELAY_MS) || 2_000));
|
|
2430
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2431
|
+
}
|
|
2432
|
+
const authOverrides = await authOverridesFor(ctx, family);
|
|
2433
|
+
const env = family === "claude" && authOverrides
|
|
2434
|
+
? { ...process.env, PI_QUOTA_CLAUDE_SOURCE: "pi" }
|
|
2435
|
+
: process.env;
|
|
2436
|
+
const fragment = await loadFamily(family, { force, authOverrides, env, localStats: false } as any);
|
|
2437
|
+
if (disposed) return false;
|
|
2438
|
+
if (family === "claude") claudeSourceUsed = normalizeClaudeSourceMode(env.PI_QUOTA_CLAUDE_SOURCE);
|
|
2439
|
+
const stickyFragment = mergeLastGood(fragment as any, {}).report as QuotaReport;
|
|
2440
|
+
mergeFamilyReport(stickyFragment);
|
|
2441
|
+
updateFamilyClock(family);
|
|
2442
|
+
persistReport([family]);
|
|
2443
|
+
resultGeneration += 1;
|
|
2444
|
+
familyErrors.delete(family);
|
|
2445
|
+
try {
|
|
2446
|
+
const familyReport = { ...stickyFragment, localStats: report?.localStats ?? stickyFragment.localStats ?? {} };
|
|
2447
|
+
publishOmarchy(familyReport, false);
|
|
2448
|
+
} catch {
|
|
2449
|
+
// A bar-record failure must not turn a quota refresh into an error.
|
|
2450
|
+
}
|
|
2451
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2452
|
+
return true;
|
|
2453
|
+
} catch (error) {
|
|
2454
|
+
const message = (error as { message?: string })?.message ?? String(error);
|
|
2455
|
+
familyErrors.set(family, capCause(redactCause(message).split("\n")[0]));
|
|
2456
|
+
return false;
|
|
2457
|
+
} finally {
|
|
2458
|
+
if (inFlight.get(family) === task) inFlight.delete(family);
|
|
2459
|
+
if (surfaceActive()) paintUi(ctx);
|
|
2460
|
+
overlayView?.redraw();
|
|
2140
2461
|
}
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2462
|
+
})();
|
|
2463
|
+
inFlight.set(family, task);
|
|
2464
|
+
return task;
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
/**
|
|
2468
|
+
* One line per failing family, in family order so the list does not reshuffle
|
|
2469
|
+
* as families land. The name is short for the same reason: this is a row in a
|
|
2470
|
+
* dense panel, not a log.
|
|
2471
|
+
*/
|
|
2472
|
+
function errorLines(): string[] {
|
|
2473
|
+
const order = [...enabledFamilies({ env: process.env, requested: FAMILIES })];
|
|
2474
|
+
for (const family of familyErrors.keys()) if (!order.includes(family)) order.push(family);
|
|
2475
|
+
return order.flatMap((family) => {
|
|
2476
|
+
const message = familyErrors.get(family);
|
|
2477
|
+
return message ? [`${SHORT_NAME[family] ?? family}: ${message}`] : [];
|
|
2478
|
+
});
|
|
2147
2479
|
}
|
|
2148
2480
|
|
|
2149
2481
|
function paintUi(ctx: UiContext): void {
|
|
@@ -2294,21 +2626,42 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2294
2626
|
}
|
|
2295
2627
|
|
|
2296
2628
|
async function refresh(ctx: UiContext, force: boolean): Promise<void> {
|
|
2297
|
-
if (
|
|
2298
|
-
|
|
2299
|
-
|
|
2300
|
-
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2629
|
+
if (disposed) return;
|
|
2630
|
+
report = ensureReport();
|
|
2631
|
+
const families = enabledFamilies({ env: process.env, requested: FAMILIES });
|
|
2632
|
+
const now = Date.now();
|
|
2633
|
+
const fetchedAtMs = { ...readRefreshState().fetchedAtMs };
|
|
2634
|
+
// Upgrade path: an older CLI cache has no per-family clock file, but each
|
|
2635
|
+
// provider already carries its own updatedAt. Do not refetch fresh cached data
|
|
2636
|
+
// merely because this extension version has not written clocks yet.
|
|
2637
|
+
for (const family of families) {
|
|
2638
|
+
if (typeof fetchedAtMs[family] === "number") continue;
|
|
2639
|
+
const providerTimes = (report?.providers ?? [])
|
|
2640
|
+
.filter((provider) => provider.family === family)
|
|
2641
|
+
.map((provider) => Date.parse(provider.updatedAt))
|
|
2642
|
+
.filter((time) => Number.isFinite(time));
|
|
2643
|
+
const generatedAt = report?.generatedAt ? Date.parse(report.generatedAt) : NaN;
|
|
2644
|
+
const fallback = providerTimes.length > 0 ? Math.max(...providerTimes) : generatedAt;
|
|
2645
|
+
if (Number.isFinite(fallback)) fetchedAtMs[family] = fallback;
|
|
2646
|
+
}
|
|
2647
|
+
const staleByClock = new Set(staleFamilies({
|
|
2648
|
+
fetchedAtMs,
|
|
2649
|
+
ttls: resolveFamilyTtls({ families }),
|
|
2650
|
+
families,
|
|
2651
|
+
now,
|
|
2652
|
+
}));
|
|
2653
|
+
const cachedFamilies = new Set(report?.providers.map((provider) => provider.family) ?? []);
|
|
2654
|
+
const selected = force ? families : families.filter((family) => !cachedFamilies.has(family) || staleByClock.has(family));
|
|
2655
|
+
if (selected.length === 0) return;
|
|
2656
|
+
startLocalStats(ctx);
|
|
2657
|
+
const outcomes = await Promise.all(selected.map((family) => refreshFamily(ctx, family, force)));
|
|
2658
|
+
if (outcomes.every(Boolean) && inFlight.size === 0 && report && resultGeneration !== prunedGeneration) {
|
|
2659
|
+
try {
|
|
2660
|
+
publishOmarchy(report, true);
|
|
2661
|
+
prunedGeneration = resultGeneration;
|
|
2662
|
+
} catch {
|
|
2663
|
+
// Keep fresh quota data even if the optional final stale-record prune fails.
|
|
2308
2664
|
}
|
|
2309
|
-
} finally {
|
|
2310
|
-
refreshing = false;
|
|
2311
|
-
overlayView?.redraw();
|
|
2312
2665
|
}
|
|
2313
2666
|
}
|
|
2314
2667
|
|
|
@@ -2368,36 +2721,23 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2368
2721
|
ui.ui.setStatus(STATUS_KEY, undefined);
|
|
2369
2722
|
ui.ui.setWidget(WIDGET_KEY, undefined);
|
|
2370
2723
|
}
|
|
2724
|
+
// Pi awaits session_shutdown (reason "reload" included), so the scan is gone
|
|
2725
|
+
// and its lock released before the next session or the process starts.
|
|
2726
|
+
await stopLocalStats();
|
|
2371
2727
|
});
|
|
2372
2728
|
|
|
2373
2729
|
/**
|
|
2374
|
-
*
|
|
2375
|
-
*
|
|
2730
|
+
* Read one month (null: the current local month) in-process and hand the
|
|
2731
|
+
* aggregate-only payload to the overlay. Read-only, no lock: historyJson only reads.
|
|
2376
2732
|
*
|
|
2377
|
-
* A failure is
|
|
2378
|
-
* stderr line or its exit status, redacted and on one line. The JSON parser's
|
|
2733
|
+
* A reader failure is redacted and limited to one line. The JSON parser's
|
|
2379
2734
|
* "Unexpected end of JSON input" says nothing about the cause.
|
|
2380
2735
|
*/
|
|
2381
2736
|
async function loadHistory(month: string | null, request: number): Promise<void> {
|
|
2382
|
-
const cli = resolveCliPath();
|
|
2383
|
-
if (!cli) {
|
|
2384
|
-
overlayView?.setHistoryError("piquota not installed: run install.sh from the pi-quota repo", request);
|
|
2385
|
-
return;
|
|
2386
|
-
}
|
|
2387
2737
|
try {
|
|
2388
|
-
const
|
|
2389
|
-
const argv = [cli, "stats", "--json", ...(month ? ["--month", month] : [])];
|
|
2390
|
-
const result = await pi.exec(runner, argv, { timeout: EXEC_TIMEOUT_MS });
|
|
2391
|
-
const stdout = typeof result?.stdout === "string" ? result.stdout : "";
|
|
2392
|
-
let parsed: HistoryPayload | null = null;
|
|
2393
|
-
try {
|
|
2394
|
-
parsed = stdout.trim() === "" ? null : (JSON.parse(stdout) as HistoryPayload);
|
|
2395
|
-
} catch {
|
|
2396
|
-
// A truncated or non-JSON stdout: report the run, not the parser.
|
|
2397
|
-
parsed = null;
|
|
2398
|
-
}
|
|
2738
|
+
const parsed = await readHistory(month);
|
|
2399
2739
|
if (!parsed || !Array.isArray(parsed.months)) {
|
|
2400
|
-
overlayView?.setHistoryError(
|
|
2740
|
+
overlayView?.setHistoryError("piquota stats returned no history payload", request);
|
|
2401
2741
|
return;
|
|
2402
2742
|
}
|
|
2403
2743
|
overlayView?.setHistory(parsed, request);
|
|
@@ -2414,9 +2754,9 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2414
2754
|
*/
|
|
2415
2755
|
async function showOverlay(ctx: UiContext): Promise<void> {
|
|
2416
2756
|
// Paint on the same keystroke: the report already in memory, otherwise the
|
|
2417
|
-
//
|
|
2418
|
-
//
|
|
2419
|
-
|
|
2757
|
+
// on-disk cache. Only stale families refresh behind the overlay; the first
|
|
2758
|
+
// frame never waits for the network.
|
|
2759
|
+
report = ensureReport();
|
|
2420
2760
|
const custom = ctx.ui.custom;
|
|
2421
2761
|
if (typeof custom !== "function" || (ctx.mode !== undefined && ctx.mode !== "tui")) {
|
|
2422
2762
|
// A host without custom components still gets the panel that /usage panel pins.
|
|
@@ -2424,7 +2764,8 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2424
2764
|
lineVisible = false;
|
|
2425
2765
|
boxVisible = false;
|
|
2426
2766
|
explicitBox = false;
|
|
2427
|
-
|
|
2767
|
+
report = ensureReport();
|
|
2768
|
+
void refresh(ctx, false);
|
|
2428
2769
|
ensurePolling(ctx);
|
|
2429
2770
|
paintUi(ctx);
|
|
2430
2771
|
ctx.ui.notify("This host has no fullscreen overlay; the quota panel is pinned above the editor", "info");
|
|
@@ -2437,8 +2778,8 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2437
2778
|
requestRender: () => tui?.requestRender?.(),
|
|
2438
2779
|
getRows: () => tui?.terminal?.rows ?? process.stdout.rows ?? 24,
|
|
2439
2780
|
getReport: () => report,
|
|
2440
|
-
|
|
2441
|
-
isRefreshing: () =>
|
|
2781
|
+
getErrors: () => errorLines(),
|
|
2782
|
+
isRefreshing: () => isRefreshing(),
|
|
2442
2783
|
refresh: () => {
|
|
2443
2784
|
void refresh(ctx, true);
|
|
2444
2785
|
},
|
|
@@ -2474,10 +2815,11 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2474
2815
|
switch (action) {
|
|
2475
2816
|
case "refresh":
|
|
2476
2817
|
await refresh(ctx, true);
|
|
2818
|
+
const failures = errorLines();
|
|
2477
2819
|
ctx.ui.notify(
|
|
2478
2820
|
report
|
|
2479
2821
|
? `Quota refreshed (${report.providers.filter((provider) => provider.ok).length}/${report.providers.length} providers)`
|
|
2480
|
-
: `Quota refresh failed: ${
|
|
2822
|
+
: `Quota refresh failed: ${failures.length > 1 ? `${failures[0]} (+${failures.length - 1} more)` : failures[0] ?? "unknown error"}`,
|
|
2481
2823
|
report ? "info" : "error",
|
|
2482
2824
|
);
|
|
2483
2825
|
return;
|
|
@@ -2487,7 +2829,9 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2487
2829
|
boxVisible = false;
|
|
2488
2830
|
explicitBox = false;
|
|
2489
2831
|
panelVisible = false;
|
|
2832
|
+
report = ensureReport();
|
|
2490
2833
|
if (!report) await refresh(ctx, false);
|
|
2834
|
+
else void refresh(ctx, false);
|
|
2491
2835
|
ensurePolling(ctx);
|
|
2492
2836
|
paintUi(ctx);
|
|
2493
2837
|
ctx.ui.notify("Quota line pinned above the editor", "info");
|
|
@@ -2497,7 +2841,9 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2497
2841
|
lineVisible = false;
|
|
2498
2842
|
boxVisible = false;
|
|
2499
2843
|
explicitBox = false;
|
|
2844
|
+
report = ensureReport();
|
|
2500
2845
|
if (!report) await refresh(ctx, false);
|
|
2846
|
+
else void refresh(ctx, false);
|
|
2501
2847
|
ensurePolling(ctx);
|
|
2502
2848
|
paintUi(ctx);
|
|
2503
2849
|
ctx.ui.notify("Quota panel shown above the editor", "info");
|
|
@@ -2507,7 +2853,9 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2507
2853
|
boxVisible = true;
|
|
2508
2854
|
explicitBox = true;
|
|
2509
2855
|
panelVisible = false;
|
|
2856
|
+
report = ensureReport();
|
|
2510
2857
|
if (!report) await refresh(ctx, false);
|
|
2858
|
+
else void refresh(ctx, false);
|
|
2511
2859
|
ensurePolling(ctx);
|
|
2512
2860
|
paintUi(ctx);
|
|
2513
2861
|
ctx.ui.notify("Quota box pinned above the editor", "info");
|
|
@@ -2534,7 +2882,7 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2534
2882
|
paintUi(ctx);
|
|
2535
2883
|
return;
|
|
2536
2884
|
case "json":
|
|
2537
|
-
ctx.ui.notify(
|
|
2885
|
+
ctx.ui.notify(`Report cache: ${reportCachePath()}`, "info");
|
|
2538
2886
|
return;
|
|
2539
2887
|
default:
|
|
2540
2888
|
break;
|
|
@@ -2543,7 +2891,7 @@ export default function quotaPanelExtension(pi: ExtensionAPI): void {
|
|
|
2543
2891
|
// Bare /usage (or an unknown argument): open the overlay with whatever the
|
|
2544
2892
|
// extension already has, and refresh in the background behind it.
|
|
2545
2893
|
const opening = showOverlay(ctx);
|
|
2546
|
-
void refresh(ctx,
|
|
2894
|
+
void refresh(ctx, false);
|
|
2547
2895
|
await opening;
|
|
2548
2896
|
};
|
|
2549
2897
|
|