ccdeck 3.46.0 → 3.47.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 +72 -43
- package/bin/cli/startup.js +23 -0
- package/bin/deck.js +32 -1
- package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +1 -0
- package/dist/web/assets/IntegrationModal-8tTi25gA.js +6 -0
- package/dist/web/assets/{RadioPanel-biw_BbZq.js → RadioPanel-DbmJJPsz.js} +1 -1
- package/dist/web/assets/TrafficRadar-CPjAXd5e.js +8 -0
- package/dist/web/assets/{UsageHistoryModal-Bd-JRAa4.js → UsageHistoryModal-qfmvXdWJ.js} +1 -1
- package/dist/web/assets/app-BFFG6Wz8.js +321 -0
- package/dist/web/assets/app-DfcfHvcX.css +1 -0
- package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
- package/dist/web/assets/{index-DmENqVdt.js → index-Ca87aJP9.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/release-notes.json +30 -0
- package/src/server/ccusage-install.mjs +58 -1
- package/src/server/ccusage-registry.mjs +289 -0
- package/src/server/ccusage-runner.mjs +9 -2
- package/src/server/claude-accounts.mjs +21 -0
- package/src/server/claude-login.mjs +21 -3
- package/src/server/claude-settings-catalog.d.mts +37 -0
- package/src/server/claude-settings-catalog.mjs +169 -0
- package/src/server/claude-settings-docs.mjs +109 -0
- package/src/server/claude-settings-index.json +251 -0
- package/src/server/claude-settings-routes.mjs +46 -0
- package/src/server/claude-settings.mjs +406 -0
- package/src/server/cli-arrival.mjs +64 -0
- package/src/server/index.mjs +18 -2
- package/src/server/integrations/proxy.mjs +11 -2
- package/src/server/integrations/routes.mjs +6 -4
- package/src/server/quota-close-watch.mjs +81 -0
- package/src/server/quota-closes.mjs +181 -0
- package/src/server/quota-history.mjs +8 -1
- package/src/server/quota-shape.mjs +12 -0
- package/src/server/quota.mjs +28 -1
- package/src/server/request-gates.mjs +3 -1
- package/src/server/tool-audit-operations.mjs +30 -10
- package/src/server/tool-audit-report.mjs +79 -7
- package/src/server/tool-audit-routes.mjs +1 -1
- package/src/server/tool-audit-skills.mjs +8 -3
- package/src/server/tool-audit.mjs +55 -5
- package/src/server/traffic-radar-capture.mjs +3 -3
- package/src/server/traffic-radar-config.mjs +10 -3
- package/src/server/traffic-radar-monitor.mjs +8 -5
- package/src/server/traffic-radar-permission.mjs +162 -0
- package/src/server/traffic-radar-platform.mjs +9 -3
- package/src/server/traffic-radar-routes.mjs +8 -18
- package/src/server/traffic-radar-service.mjs +76 -92
- package/src/server/usage-routes.mjs +14 -2
- package/dist/web/assets/BrowserWatchModal-CoX9FIUE.js +0 -1
- package/dist/web/assets/IntegrationModal-B1ypkK-E.js +0 -5
- package/dist/web/assets/TrafficRadar-nhtFoYVv.js +0 -8
- package/dist/web/assets/app-BlRY6EME.css +0 -1
- package/dist/web/assets/app-DhGvSH7o.js +0 -319
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// What keeps quota-closes.mjs fed while no page is open. Every five minutes it
|
|
2
|
+
// reads claude-swap's store for every account (two small files, no request),
|
|
3
|
+
// notes the plan the signed-in account is on, and closes the windows whose
|
|
4
|
+
// reset has passed. And once per weekly window about to reset that was last
|
|
5
|
+
// read over an hour ago, it asks for one fresh reading: the reading the whole
|
|
6
|
+
// record is about, at a cost of one collection a week per account.
|
|
7
|
+
//
|
|
8
|
+
// The quota modules are reached by `import()`, as account-watch.mjs reaches
|
|
9
|
+
// them, and are pinned with the rest (pinned-build.mjs).
|
|
10
|
+
import { dirname, join, resolve } from "node:path";
|
|
11
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
12
|
+
import { historyAccount } from "./quota-history.mjs";
|
|
13
|
+
import { quotaCloses } from "./quota-closes.mjs";
|
|
14
|
+
import { readLiveLogin } from "./claude-login.mjs";
|
|
15
|
+
|
|
16
|
+
const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
|
|
17
|
+
const lazy = name => import(pathToFileURL(join(PKG_ROOT, "src/server", name)).href);
|
|
18
|
+
export const CLOSE_WATCH_MS = 5 * 60_000;
|
|
19
|
+
|
|
20
|
+
/** One store row's windows, in the shape quota-history.mjs's historyWindows
|
|
21
|
+
* gives the published reading, so both sources land on the same window. */
|
|
22
|
+
export function storedWindows(lastGood) {
|
|
23
|
+
const win = (id, label, w, windowSec) => {
|
|
24
|
+
const resetMs = typeof w?.resets_at === "string" ? Date.parse(w.resets_at) : NaN;
|
|
25
|
+
return Number.isFinite(resetMs) && resetMs > 0 && typeof w?.pct === "number" && Number.isFinite(w.pct)
|
|
26
|
+
? { id, label, pct: Math.min(100, Math.max(0, w.pct)), resetAt: Math.floor(resetMs / 1000), windowSec } : null;
|
|
27
|
+
};
|
|
28
|
+
const five = win("five_hour", "5-hour window", lastGood?.five_hour, 18000);
|
|
29
|
+
const week = win("seven_day", "7-day window", lastGood?.seven_day, 604800);
|
|
30
|
+
// The store's fallback can copy the weekly reading into the session lane.
|
|
31
|
+
return [five && !(week && five.resetAt === week.resetAt && five.pct === week.pct) ? five : null, week].filter(Boolean);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function closingRead(due, liveKey) {
|
|
35
|
+
if (due.provider === "codex") { await (await lazy("codex-quota.mjs")).fetchCodexQuota({ force: true }); return; }
|
|
36
|
+
// claude-swap collects for every account it holds; the signed-in one is also
|
|
37
|
+
// read the way the Usage panel reads it, for a deck without claude-swap.
|
|
38
|
+
await (await lazy("claude-accounts.mjs")).requestCollection();
|
|
39
|
+
if (due.account === liveKey) await (await lazy("quota.mjs")).fetchClaudeQuota({ force: true });
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let _running = null;
|
|
43
|
+
/** One pass, never two at once. Every failure ends here: a record that cannot
|
|
44
|
+
* be kept is not worth a line in anyone's way. `providers` is deck-scope's
|
|
45
|
+
* deckProviders, asked each pass as account-watch.mjs asks it. */
|
|
46
|
+
export function closeWatchOnce({ providers } = {}) {
|
|
47
|
+
if (_running) return _running;
|
|
48
|
+
_running = (async () => {
|
|
49
|
+
const closes = quotaCloses();
|
|
50
|
+
if (!closes) return;
|
|
51
|
+
const { claude = true, codex = true } = providers?.() ?? {};
|
|
52
|
+
const watched = { claude, codex };
|
|
53
|
+
let liveKey = null;
|
|
54
|
+
if (claude) {
|
|
55
|
+
const { storedUsageReadings } = await lazy("claude-accounts.mjs");
|
|
56
|
+
for (const r of await storedUsageReadings()) {
|
|
57
|
+
const key = historyAccount("claude", { email: r.email, organizationUuid: r.organizationUuid });
|
|
58
|
+
if (key) await closes.observe("claude", key, storedWindows(r.lastGood), r.fetchedAt);
|
|
59
|
+
}
|
|
60
|
+
const live = await readLiveLogin();
|
|
61
|
+
liveKey = live ? historyAccount("claude", { email: live.email, organizationUuid: live.orgUuid }) : null;
|
|
62
|
+
if (liveKey && live.plan) await closes.plan("claude", liveKey, live.plan);
|
|
63
|
+
}
|
|
64
|
+
await closes.sweep();
|
|
65
|
+
for (const due of await closes.closingReads()) {
|
|
66
|
+
if (watched[due.provider]) await closingRead(due, liveKey).catch(() => {});
|
|
67
|
+
}
|
|
68
|
+
})().catch(() => {}).finally(() => { _running = null; });
|
|
69
|
+
return _running;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
let _timer = null;
|
|
73
|
+
/** Started from startServer once the port is bound, never at import; unref'd
|
|
74
|
+
* like every other timer the deck keeps. */
|
|
75
|
+
export function startQuotaCloseWatch({ providers } = {}) {
|
|
76
|
+
if (_timer) return;
|
|
77
|
+
_timer = setInterval(() => { void closeWatchOnce({ providers }); }, CLOSE_WATCH_MS);
|
|
78
|
+
_timer.unref?.();
|
|
79
|
+
const first = setTimeout(() => { void closeWatchOnce({ providers }); }, 30_000);
|
|
80
|
+
first.unref?.();
|
|
81
|
+
}
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// How full each quota window was when it reset: the first half of "is my plan
|
|
2
|
+
// the right size?". A window is held open while readings of it arrive and
|
|
3
|
+
// closed, with the last of them, once its reset passes — or earlier, when a
|
|
4
|
+
// reading shows a new window already running (a saved reset spent, a counter
|
|
5
|
+
// flushed). Fed only by readings the deck already has: the signed-in account's
|
|
6
|
+
// published quota and claude-swap's store for every account (quota-close-watch.mjs).
|
|
7
|
+
import { readFile, stat, mkdir } from "node:fs/promises";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { deckDataDir } from "./deck-home.mjs";
|
|
10
|
+
import { writeFileAtomic } from "./atomic-write.mjs";
|
|
11
|
+
|
|
12
|
+
export const CLOSE_LIMITS = Object.freeze({ open: 128, closed: 4000, days: 400, bytes: 2 * 1024 * 1024 });
|
|
13
|
+
const finite = n => typeof n === "number" && Number.isFinite(n);
|
|
14
|
+
const providers = new Set(["claude", "codex"]);
|
|
15
|
+
const accountKey = /^[a-f0-9]{64}$/;
|
|
16
|
+
|
|
17
|
+
/** Two readings of one window may disagree on its reset: `claude /usage` prints
|
|
18
|
+
* it to the hour, the usage endpoint to the second. The next window cannot
|
|
19
|
+
* reset sooner than a whole window later, so a quarter of one (at most six
|
|
20
|
+
* hours) still tells the same window from the next. */
|
|
21
|
+
export const sameReset = (windowSec, a, b) => Math.abs(a - b) <= Math.min(windowSec / 4, 6 * 3600);
|
|
22
|
+
|
|
23
|
+
const validWindow = w => typeof w?.id === "string" && w.id.length <= 100 && finite(w.pct) && w.pct >= 0
|
|
24
|
+
&& finite(w.resetAt) && finite(w.windowSec) && w.windowSec >= 60 && w.windowSec <= 40 * 86400;
|
|
25
|
+
|
|
26
|
+
function entryOf(raw, now) {
|
|
27
|
+
if (!providers.has(raw?.provider) || !accountKey.test(raw.account ?? "") || !validWindow(raw)
|
|
28
|
+
|| typeof raw.label !== "string" || !finite(raw.peak) || !finite(raw.t) || !finite(raw.first)
|
|
29
|
+
|| !Number.isInteger(raw.n) || raw.n < 1 || raw.t > now + 60_000 || raw.first > raw.t) return null;
|
|
30
|
+
return {
|
|
31
|
+
provider: raw.provider, account: raw.account, id: raw.id, label: raw.label.slice(0, 100),
|
|
32
|
+
windowSec: raw.windowSec, resetAt: raw.resetAt, pct: Math.min(100, raw.pct), peak: Math.min(100, Math.max(raw.peak, raw.pct)),
|
|
33
|
+
t: raw.t, first: raw.first, n: raw.n,
|
|
34
|
+
...(typeof raw.plan === "string" && raw.plan && raw.plan.length <= 40 && { plan: raw.plan }),
|
|
35
|
+
...(raw.asked === true && { asked: true }),
|
|
36
|
+
...(raw.ended === "reset" || raw.ended === "early" ? { ended: raw.ended } : {}),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function prune(state, now) {
|
|
41
|
+
const floor = now / 1000 - CLOSE_LIMITS.days * 86400;
|
|
42
|
+
state.closed = state.closed.filter(c => c.resetAt >= floor)
|
|
43
|
+
.sort((a, b) => b.resetAt - a.resetAt).slice(0, CLOSE_LIMITS.closed);
|
|
44
|
+
state.open = state.open.sort((a, b) => b.t - a.t).slice(0, CLOSE_LIMITS.open);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function normalizeCloses(raw, now) {
|
|
48
|
+
const state = { open: [], closed: [] };
|
|
49
|
+
if (raw?.v !== 1) return state;
|
|
50
|
+
for (const e of Array.isArray(raw.open) ? raw.open.slice(0, CLOSE_LIMITS.open) : []) {
|
|
51
|
+
const entry = entryOf(e, now);
|
|
52
|
+
if (entry) { delete entry.ended; state.open.push(entry); }
|
|
53
|
+
}
|
|
54
|
+
for (const e of Array.isArray(raw.closed) ? raw.closed.slice(0, CLOSE_LIMITS.closed) : []) {
|
|
55
|
+
const entry = entryOf(e, now);
|
|
56
|
+
if (entry?.ended) state.closed.push(entry);
|
|
57
|
+
}
|
|
58
|
+
prune(state, now);
|
|
59
|
+
return state;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function createQuotaCloses({ load = async () => null, save = async () => {}, now = Date.now } = {}) {
|
|
63
|
+
let state = { open: [], closed: [] }, loading = null, storageOk = true, dirty = false;
|
|
64
|
+
let queue = Promise.resolve();
|
|
65
|
+
const ready = () => loading ??= (async () => {
|
|
66
|
+
try { state = normalizeCloses(await load(), now()); }
|
|
67
|
+
catch { storageOk = false; }
|
|
68
|
+
})();
|
|
69
|
+
const close = (entry, ended) => {
|
|
70
|
+
state.open = state.open.filter(e => e !== entry);
|
|
71
|
+
delete entry.asked;
|
|
72
|
+
state.closed.push({ ...entry, ended });
|
|
73
|
+
dirty = true;
|
|
74
|
+
};
|
|
75
|
+
const sweep = () => {
|
|
76
|
+
const at = now();
|
|
77
|
+
for (const entry of [...state.open]) if (entry.resetAt * 1000 <= at) close(entry, "reset");
|
|
78
|
+
};
|
|
79
|
+
const flush = async () => {
|
|
80
|
+
prune(state, now());
|
|
81
|
+
if (!dirty) return;
|
|
82
|
+
dirty = false;
|
|
83
|
+
try { await save({ v: 1, open: state.open, closed: state.closed }); storageOk = true; }
|
|
84
|
+
catch { storageOk = false; } // the record cannot fail a quota read
|
|
85
|
+
};
|
|
86
|
+
const run = fn => (queue = queue.then(async () => { await ready(); await fn(); await flush(); }).catch(() => { storageOk = false; }));
|
|
87
|
+
return {
|
|
88
|
+
/** Readings of an account's windows, taken at `fetchedAt` (ms). */
|
|
89
|
+
observe(provider, account, windows, fetchedAt, { plan } = {}) {
|
|
90
|
+
return run(() => {
|
|
91
|
+
if (!providers.has(provider) || !accountKey.test(account ?? "") || !finite(fetchedAt) || fetchedAt > now() + 60_000) return;
|
|
92
|
+
sweep();
|
|
93
|
+
for (const w of Array.isArray(windows) ? windows : []) {
|
|
94
|
+
if (!validWindow(w) || fetchedAt >= w.resetAt * 1000 || fetchedAt < (w.resetAt - w.windowSec) * 1000 - 120_000) continue;
|
|
95
|
+
const pct = Math.min(100, w.pct);
|
|
96
|
+
const same = e => e.provider === provider && e.account === account && e.id === w.id && e.windowSec === w.windowSec;
|
|
97
|
+
// A reading that arrives after its window closed — claude-swap's store
|
|
98
|
+
// is read on a timer — still improves the close if it is the later one.
|
|
99
|
+
const done = state.closed.find(e => same(e) && sameReset(w.windowSec, e.resetAt, w.resetAt));
|
|
100
|
+
if (done) {
|
|
101
|
+
if (fetchedAt > done.t) { done.pct = pct; done.t = fetchedAt; done.n++; done.peak = Math.max(done.peak, pct); dirty = true; }
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
const lane = state.open.filter(same);
|
|
105
|
+
const entry = lane.find(e => sameReset(w.windowSec, e.resetAt, w.resetAt));
|
|
106
|
+
if (!entry && lane.some(e => e.resetAt > w.resetAt)) continue; // a late reading of a window already left
|
|
107
|
+
// A newer window running before the old one's reset ended it early.
|
|
108
|
+
for (const old of lane) if (old !== entry && old.resetAt < w.resetAt && old.t < fetchedAt) close(old, fetchedAt < old.resetAt * 1000 ? "early" : "reset");
|
|
109
|
+
if (!entry) {
|
|
110
|
+
state.open.push({ provider, account, id: w.id, label: String(w.label ?? w.id).slice(0, 100), windowSec: w.windowSec,
|
|
111
|
+
resetAt: w.resetAt, pct, peak: pct, t: fetchedAt, first: fetchedAt, n: 1, ...(plan && { plan }) });
|
|
112
|
+
dirty = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
// Readings reach here from two sources, not always in order: an older
|
|
116
|
+
// one still counts toward the peak and the first sight, never the last.
|
|
117
|
+
entry.peak = Math.max(entry.peak, pct);
|
|
118
|
+
entry.first = Math.min(entry.first, fetchedAt);
|
|
119
|
+
if (fetchedAt > entry.t) { entry.pct = pct; entry.t = fetchedAt; entry.n++; entry.resetAt = w.resetAt; }
|
|
120
|
+
if (plan) entry.plan = plan;
|
|
121
|
+
dirty = true;
|
|
122
|
+
}
|
|
123
|
+
sweep();
|
|
124
|
+
});
|
|
125
|
+
},
|
|
126
|
+
/** The plan an account is on now, written onto its open windows. */
|
|
127
|
+
plan(provider, account, plan) {
|
|
128
|
+
return run(() => {
|
|
129
|
+
if (typeof plan !== "string" || !plan || plan.length > 40) return;
|
|
130
|
+
for (const e of state.open) if (e.provider === provider && e.account === account && e.plan !== plan) { e.plan = plan; dirty = true; }
|
|
131
|
+
});
|
|
132
|
+
},
|
|
133
|
+
/** Closes every window whose reset has passed. */
|
|
134
|
+
sweep() { return run(sweep); },
|
|
135
|
+
/** The open weekly windows that reset within `withinMs` and were last read
|
|
136
|
+
* more than `staleMs` ago — each handed out once, for one fresh reading
|
|
137
|
+
* before its reset. */
|
|
138
|
+
async closingReads({ withinMs = 45 * 60_000, staleMs = 60 * 60_000 } = {}) {
|
|
139
|
+
const due = [];
|
|
140
|
+
await run(() => {
|
|
141
|
+
const at = now();
|
|
142
|
+
for (const e of state.open) {
|
|
143
|
+
if (e.windowSec < 86400 || e.asked || e.resetAt * 1000 <= at || e.resetAt * 1000 - at > withinMs || at - e.t < staleMs) continue;
|
|
144
|
+
e.asked = true; dirty = true;
|
|
145
|
+
due.push({ provider: e.provider, account: e.account, id: e.id, resetAt: e.resetAt });
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
return due;
|
|
149
|
+
},
|
|
150
|
+
async report(provider, account) {
|
|
151
|
+
await run(sweep);
|
|
152
|
+
const strip = ({ provider: _p, account: _a, asked: _asked, ...e }) => e;
|
|
153
|
+
return { ok: true, storageOk, account,
|
|
154
|
+
closed: state.closed.filter(e => e.provider === provider && e.account === account).map(strip),
|
|
155
|
+
open: state.open.filter(e => e.provider === provider && e.account === account).map(strip) };
|
|
156
|
+
},
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
let closes = null;
|
|
161
|
+
export function startQuotaCloses() {
|
|
162
|
+
if (closes) return closes;
|
|
163
|
+
const file = join(deckDataDir(), "quota-closes.json");
|
|
164
|
+
closes = createQuotaCloses({
|
|
165
|
+
load: async () => {
|
|
166
|
+
try {
|
|
167
|
+
if ((await stat(file)).size > CLOSE_LIMITS.bytes) throw new Error("Closes exceed capacity");
|
|
168
|
+
return JSON.parse((await readFile(file, "utf8")).replace(/^/, ""));
|
|
169
|
+
} catch (e) { if (e?.code === "ENOENT") return null; throw e; }
|
|
170
|
+
},
|
|
171
|
+
save: async raw => { await mkdir(dirname(file), { recursive: true }); await writeFileAtomic(file, JSON.stringify(raw)); },
|
|
172
|
+
});
|
|
173
|
+
return closes;
|
|
174
|
+
}
|
|
175
|
+
export const quotaCloses = () => closes;
|
|
176
|
+
export function noteQuotaCloses(provider, account, windows, fetchedAt, extra) {
|
|
177
|
+
if (closes && account) void closes.observe(provider, account, windows, fetchedAt, extra);
|
|
178
|
+
}
|
|
179
|
+
export async function quotaClosesReport(provider, account) {
|
|
180
|
+
return closes ? closes.report(provider, account) : { ok: true, storageOk: true, account, closed: [], open: [] };
|
|
181
|
+
}
|
|
@@ -4,6 +4,7 @@ import { readFile, stat, mkdir } from "node:fs/promises";
|
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { deckDataDir } from "./deck-home.mjs";
|
|
6
6
|
import { writeFileAtomic } from "./atomic-write.mjs";
|
|
7
|
+
import { noteQuotaCloses } from "./quota-closes.mjs";
|
|
7
8
|
|
|
8
9
|
export const HISTORY_LIMITS = Object.freeze({ series: 32, points: 2048, totalPoints: 16384, days: 35, bytes: 2 * 1024 * 1024 });
|
|
9
10
|
const finite = n => typeof n === "number" && Number.isFinite(n);
|
|
@@ -141,7 +142,13 @@ export function startQuotaHistory() {
|
|
|
141
142
|
export function noteQuotaHistory(provider, account, reading) {
|
|
142
143
|
if (!history) return;
|
|
143
144
|
const key = history.activate(provider, account);
|
|
144
|
-
if (key) {
|
|
145
|
+
if (key) {
|
|
146
|
+
reading.historyAccount = key;
|
|
147
|
+
void history.record(provider, key, reading);
|
|
148
|
+
// The same reading, toward how full each window was at its reset.
|
|
149
|
+
noteQuotaCloses(provider, key, historyWindows(provider, reading), reading.fetchedAt,
|
|
150
|
+
{ plan: provider === "codex" && typeof reading.plan === "string" ? reading.plan : undefined });
|
|
151
|
+
}
|
|
145
152
|
}
|
|
146
153
|
export function forgetQuotaHistoryAccount(provider) { history?.activate(provider, null); }
|
|
147
154
|
export async function quotaHistoryReport(provider, account) {
|
|
@@ -22,6 +22,18 @@ import { stripAnsi } from "./term.mjs";
|
|
|
22
22
|
export const WIN_5H_SEC = 18000;
|
|
23
23
|
export const WIN_7D_SEC = 604800;
|
|
24
24
|
|
|
25
|
+
// Anthropic's names for its plans, with the Max tier said: "Max" alone does not
|
|
26
|
+
// tell the user which of the two they are on, as codex-quota.mjs's labels say
|
|
27
|
+
// which Pro. Keyed by depth-facts.mjs's claudePlanToken.
|
|
28
|
+
const CLAUDE_PLAN_LABELS = Object.freeze({
|
|
29
|
+
free: "Free", pro: "Pro", max: "Max", "max-5x": "Max 5x", "max-20x": "Max 20x", team: "Team", enterprise: "Enterprise",
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
/** The plan as the section title prints it, or null for one off the list. */
|
|
33
|
+
export function claudePlanLabel(plan) {
|
|
34
|
+
return typeof plan === "string" && Object.hasOwn(CLAUDE_PLAN_LABELS, plan) ? CLAUDE_PLAN_LABELS[plan] : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
25
37
|
/**
|
|
26
38
|
* A reported utilisation as the whole percentage the panel draws: rounded, and
|
|
27
39
|
* held inside 0–100 whatever the source said.
|
package/src/server/quota.mjs
CHANGED
|
@@ -54,7 +54,8 @@
|
|
|
54
54
|
// reset inventory is quota-store-resets.mjs's.
|
|
55
55
|
import { noteQuotaHistory, forgetQuotaHistoryAccount } from "./quota-history.mjs";
|
|
56
56
|
import { activeAccountUsage, requestCollection } from "./claude-accounts.mjs";
|
|
57
|
-
import { quotaFromStore, readingLapsed, WIN_5H_SEC, WIN_7D_SEC } from "./quota-shape.mjs";
|
|
57
|
+
import { claudePlanLabel, quotaFromStore, readingLapsed, WIN_5H_SEC, WIN_7D_SEC } from "./quota-shape.mjs";
|
|
58
|
+
import { readLiveLogin } from "./claude-login.mjs";
|
|
58
59
|
import {
|
|
59
60
|
SELF_POLL_MS, clearCooldown, coolingDown, cooldownUntil, credentialFingerprint, fetchOAuthUsage,
|
|
60
61
|
hasSubscriptionCredential,
|
|
@@ -325,6 +326,32 @@ export function quotaAccount(reading) {
|
|
|
325
326
|
return (reading && typeof reading === "object" && _accountOfQuota.get(reading)) || null;
|
|
326
327
|
}
|
|
327
328
|
|
|
329
|
+
/**
|
|
330
|
+
* A reading with the plan of the account it is about — `plan` as
|
|
331
|
+
* claudePlanToken names it, `planLabel` as the panel prints it beside the
|
|
332
|
+
* section title, where the Codex section has always shown its own.
|
|
333
|
+
*
|
|
334
|
+
* The plan is the signed-in account's, read off Claude Code's own config
|
|
335
|
+
* (claude-login.mjs), and that is whose numbers every source reads. A reading
|
|
336
|
+
* with no numbers has nothing to label, and one tagged as somebody else's —
|
|
337
|
+
* taken before a switch, answered after it — gets no plan rather than the new
|
|
338
|
+
* account's.
|
|
339
|
+
*
|
|
340
|
+
* Applied by the route, to a copy: account-watch.mjs looks the reading itself
|
|
341
|
+
* up in _accountOfQuota, and a copy is not in it.
|
|
342
|
+
*
|
|
343
|
+
* @param login who is signed in; read from Claude Code's config by default,
|
|
344
|
+
* and a parameter so a test can name its own, as it can `account`.
|
|
345
|
+
*/
|
|
346
|
+
export async function withClaudePlan(reading, { login, account = quotaAccount(reading) } = {}) {
|
|
347
|
+
if (!reading?.ok) return reading;
|
|
348
|
+
const live = login === undefined ? await readLiveLogin() : login;
|
|
349
|
+
const planLabel = claudePlanLabel(live?.plan);
|
|
350
|
+
if (!planLabel) return reading;
|
|
351
|
+
if (account && !sameAccount(account, accountOf(live.email, live.orgUuid))) return reading;
|
|
352
|
+
return { ...reading, plan: live.plan, planLabel };
|
|
353
|
+
}
|
|
354
|
+
|
|
328
355
|
// Which account a store reading is about, for the inventory read it starts.
|
|
329
356
|
// Beside the reading rather than on it: the reading is sent to the browser as
|
|
330
357
|
// it is, and an identity is not something the panel needs. Weak, so a reading
|
|
@@ -433,9 +433,10 @@ export const GUARDED_READS = new Set([
|
|
|
433
433
|
"/api/tool-audit",
|
|
434
434
|
"/api/tool-audit/storage",
|
|
435
435
|
"/api/system/traffic-radar",
|
|
436
|
-
"/api/system/traffic-radar/settings",
|
|
437
436
|
"/api/system/traffic-radar/capture",
|
|
438
437
|
"/api/system/traffic-radar/capture/event",
|
|
438
|
+
// What the user's Claude Code settings.json holds, for Settings › Claude Code.
|
|
439
|
+
"/api/claude-settings",
|
|
439
440
|
"/events",
|
|
440
441
|
"/api/events",
|
|
441
442
|
// The ring folded to one row per session (#2183): each project's path and a
|
|
@@ -454,6 +455,7 @@ export const GUARDED_READS = new Set([
|
|
|
454
455
|
// route above is guarded for.
|
|
455
456
|
"/api/codex-quota",
|
|
456
457
|
"/api/quota/history",
|
|
458
|
+
"/api/quota/closes",
|
|
457
459
|
// And the rest of the usage panel, by the rule /api/account-projects is here
|
|
458
460
|
// under: the active account's quota windows, Claude's spend by day and by
|
|
459
461
|
// session, Codex's token spend, and the auto-switch settings with the last
|
|
@@ -3,20 +3,27 @@ const safe = value => typeof value === 'string' && /^[A-Za-z0-9_./:+-]{1,100}$/.
|
|
|
3
3
|
const basename = value => value.split(/[\\/]/).at(-1).replace(/\.exe$/i, '');
|
|
4
4
|
const takesValue = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env']);
|
|
5
5
|
|
|
6
|
+
// Each command, and whether it reads the one before it through a pipe.
|
|
6
7
|
function shellWords(command) {
|
|
7
|
-
const segments = [[]]; let token = '', quote = '', escaped = false;
|
|
8
|
+
const segments = [[]], piped = [false]; let token = '', quote = '', escaped = false;
|
|
8
9
|
const word = () => { if (token) segments.at(-1).push(token); token = ''; };
|
|
9
|
-
|
|
10
|
+
const next = pipe => { word(); if (segments.at(-1).length) { segments.push([]); piped.push(pipe); } };
|
|
11
|
+
const text = command.slice(0, 32768);
|
|
12
|
+
for (let i = 0; i < text.length; i++) {
|
|
13
|
+
const ch = text[i];
|
|
10
14
|
if (escaped) { token += ch; escaped = false; continue; }
|
|
11
15
|
if (ch === '\\' && quote !== "'") { escaped = true; continue; }
|
|
12
16
|
if (quote) { if (ch === quote) quote = ''; else token += ch; continue; }
|
|
13
17
|
if (ch === '"' || ch === "'") { quote = ch; continue; }
|
|
14
|
-
if (/\s/.test(ch)) { if (ch === '\n')
|
|
15
|
-
|
|
18
|
+
if (/\s/.test(ch)) { if (ch === '\n') next(false); else word(); }
|
|
19
|
+
// The & of 2>&1, >&2 and &>file is a redirection, not the end of a command.
|
|
20
|
+
else if (ch === '&' && (/[<>]$/.test(token) || text[i + 1] === '>')) token += ch;
|
|
21
|
+
else if (';&|'.includes(ch)) next(ch === '|' && text[i - 1] !== '|' && text[i + 1] !== '|');
|
|
16
22
|
else token += ch;
|
|
17
23
|
}
|
|
18
24
|
word();
|
|
19
|
-
|
|
25
|
+
const kept = segments.map((words, i) => ({ words, piped: piped[i] })).filter(s => s.words.length);
|
|
26
|
+
return { segments: kept, uncertain: !!quote || escaped || /\$\(|`|<<|\b(?:if|for|while|case|function)\b/.test(command) };
|
|
20
27
|
}
|
|
21
28
|
function operation(words, depth = 0) {
|
|
22
29
|
let i = 0;
|
|
@@ -28,7 +35,7 @@ function operation(words, depth = 0) {
|
|
|
28
35
|
const program = basename(exe); const args = words.slice(i + 1);
|
|
29
36
|
if (['sh', 'bash', 'zsh', 'pwsh', 'powershell'].includes(program) && depth < 2) {
|
|
30
37
|
const at = args.findIndex(a => /^-(?:[a-z]*c|Command)$/i.test(a));
|
|
31
|
-
if (at >= 0 && args[at + 1]) return
|
|
38
|
+
if (at >= 0 && args[at + 1]) return shellParts(args[at + 1], depth + 1);
|
|
32
39
|
}
|
|
33
40
|
if (program === 'git') {
|
|
34
41
|
let j = 0;
|
|
@@ -45,17 +52,30 @@ function operation(words, depth = 0) {
|
|
|
45
52
|
}
|
|
46
53
|
return safe(program) ?? 'shell (unclassified)';
|
|
47
54
|
}
|
|
48
|
-
|
|
55
|
+
// Builtins that take no time beside the command they set up.
|
|
56
|
+
const instant = new Set(['cd', 'pwd', 'echo', 'printf', 'true', 'false', 'export', 'set', 'unset', 'source', '.']);
|
|
57
|
+
/** A command's operations, and `lead`: the ones its time is theirs. A pipeline runs
|
|
58
|
+
* as long as the command feeding it, not the tail or grep reading its output. */
|
|
59
|
+
function shellParts(command, depth = 0) {
|
|
49
60
|
const { segments, uncertain } = shellWords(command);
|
|
50
|
-
if (uncertain || !segments.length || segments.length > 32) return ['shell (unclassified)'];
|
|
51
|
-
|
|
61
|
+
if (uncertain || !segments.length || segments.length > 32) return { operations: ['shell (unclassified)'], lead: ['shell (unclassified)'] };
|
|
62
|
+
const parts = segments.map(({ words, piped }) => {
|
|
63
|
+
const part = operation(words, depth);
|
|
64
|
+
return typeof part === 'string' ? { operations: [part], lead: piped ? [] : [part] } : { operations: part.operations, lead: piped ? [] : part.lead };
|
|
65
|
+
});
|
|
66
|
+
const operations = [...new Set(parts.flatMap(part => part.operations))].slice(0, 16);
|
|
67
|
+
const fed = [...new Set(parts.flatMap(part => part.lead))].filter(op => operations.includes(op));
|
|
68
|
+
const busy = fed.filter(op => !instant.has(op));
|
|
69
|
+
return { operations, lead: busy.length ? busy : fed.length ? fed : operations };
|
|
52
70
|
}
|
|
71
|
+
export function shellOperations(command, depth = 0) { return shellParts(command, depth).operations; }
|
|
72
|
+
const withLead = ({ operations, lead }) => lead.length < operations.length ? { operations, lead } : { operations };
|
|
53
73
|
export function auditOperations(name, input) {
|
|
54
74
|
const tool = safe(name) ?? 'tool (unclassified)';
|
|
55
75
|
if (['exec', 'functions.exec'].includes(name) && typeof input?.script === 'string') return { tool, operations: scriptOperations(input.script), shell: true, wrapped: true };
|
|
56
76
|
if (/^(?:Bash|Shell|exec_command|run|shell_command|functions\.exec_command|mcp__.*__exec_command)$/i.test(name ?? '')) {
|
|
57
77
|
const command = input?.command ?? input?.cmd;
|
|
58
|
-
if (typeof command === 'string' && command.length <= 32768) return { tool,
|
|
78
|
+
if (typeof command === 'string' && command.length <= 32768) return { tool, ...withLead(shellParts(command)), shell: true };
|
|
59
79
|
return { tool, operations: ['shell (unclassified)'], shell: true };
|
|
60
80
|
}
|
|
61
81
|
return { tool, operations: [tool], shell: false };
|
|
@@ -3,13 +3,19 @@ export async function buildToolAuditReport({ files, query, now, meta }, { create
|
|
|
3
3
|
const DAY = 86400000;
|
|
4
4
|
const finite = n => typeof n === 'number' && Number.isFinite(n);
|
|
5
5
|
const valid = r => /^[a-f0-9]{64}$/.test(r?.id ?? '') && ['claude', 'codex'].includes(r.provider)
|
|
6
|
-
&& ['start', 'end', 'skill'].includes(r.kind) && finite(r.t) && (r.at === null || finite(r.at))
|
|
6
|
+
&& ['start', 'end', 'skill', 'turn', 'turn-end'].includes(r.kind) && finite(r.t) && (r.at === null || finite(r.at))
|
|
7
7
|
&& ['hook', 'rollout'].includes(r.clock)
|
|
8
|
-
// A typed or detected skill is not a tool call; Skill activity reads it.
|
|
8
|
+
// A typed or detected skill is not a tool call; Skill activity reads it. Nor is a
|
|
9
|
+
// turn, which only bounds the calls made for one prompt.
|
|
9
10
|
&& (r.kind === 'skill' ? typeof r.skill === 'string'
|
|
10
|
-
: r.kind === '
|
|
11
|
+
: r.kind === 'turn' ? true
|
|
12
|
+
: r.kind === 'turn-end' ? typeof r.stop === 'string' && r.stop.length <= 40
|
|
13
|
+
: r.kind === 'end' ? typeof r.failed === 'boolean' && (r.ms === undefined || finite(r.ms) && r.ms >= 0) && (r.asked === undefined || typeof r.asked === 'boolean')
|
|
14
|
+
: typeof r.tool === 'string' && r.tool.length <= 100
|
|
11
15
|
&& Array.isArray(r.operations) && r.operations.length > 0 && r.operations.length <= 16
|
|
12
|
-
&& r.operations.every(s => typeof s === 'string' && s.length <= 150)
|
|
16
|
+
&& r.operations.every(s => typeof s === 'string' && s.length <= 150)
|
|
17
|
+
&& (r.lead === undefined || Array.isArray(r.lead) && r.lead.length > 0 && r.lead.every(s => r.operations.includes(s)))
|
|
18
|
+
&& (r.turn === undefined || /^[a-f0-9]{64}$/.test(r.turn)));
|
|
13
19
|
const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(sorted.length * p) - 1)] : null;
|
|
14
20
|
const calls = new Map(); let corrupt = 0, duplicates = 0;
|
|
15
21
|
// Explicit failure rather than a convincing-looking partial report.
|
|
@@ -25,7 +31,8 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
25
31
|
if (!valid(r)) { corrupt++; continue; }
|
|
26
32
|
let call = calls.get(r.id);
|
|
27
33
|
if (!call) { if (calls.size >= 500000) throw new Error('Tool history exceeds report capacity; choose shorter retention in Settings'); call = {}; calls.set(r.id, call); }
|
|
28
|
-
|
|
34
|
+
// A turn a Stop hook sent back to work ends at its last Stop.
|
|
35
|
+
if (call[r.kind]) { duplicates++; if (r.kind === 'turn-end' && finite(r.at) && !(r.at <= call[r.kind].at)) call[r.kind] = r; continue; }
|
|
29
36
|
call[r.kind] = r;
|
|
30
37
|
}
|
|
31
38
|
} finally { lines.close(); stream.destroy(); }
|
|
@@ -62,7 +69,7 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
62
69
|
const providers = { claude: { calls: 0, measured: 0, failed: 0 }, codex: { calls: 0, measured: 0, failed: 0 } };
|
|
63
70
|
for (const [id, call] of calls) {
|
|
64
71
|
const start = call.start, end = call.end;
|
|
65
|
-
if (!start) { if (!call.skill) orphaned++; continue; }
|
|
72
|
+
if (!start) { if (!call.skill && !call.turn && !call['turn-end']) orphaned++; continue; }
|
|
66
73
|
if (start.t < since || start.t > until || query.provider !== 'all' && start.provider !== query.provider) continue;
|
|
67
74
|
total++; providers[start.provider].calls++;
|
|
68
75
|
observedSince = observedSince === null ? start.t : Math.min(observedSince, start.t);
|
|
@@ -89,6 +96,71 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
89
96
|
capturedAt: start.t, durationMs: duration, state: !end ? 'unmatched' : end.failed ? 'failed' : 'success', clock: start.clock, shared });
|
|
90
97
|
}
|
|
91
98
|
}
|
|
99
|
+
// Where the turns' time went: Claude, this machine, or you. Wall-clock time, so the
|
|
100
|
+
// calls that ran together, a subagent's among them, count once; a turn's time is cut
|
|
101
|
+
// into the stretches between its calls' edges, and each stretch goes to one of three:
|
|
102
|
+
// this machine while any call runs or hooks start one, you while one waits for your
|
|
103
|
+
// approval or answer, and Claude while nothing does — the model, the network to it,
|
|
104
|
+
// and Claude Code itself. An Agent call only holds its subagent's calls, which count.
|
|
105
|
+
const holders = new Set(['Agent', 'Task']), questions = new Set(['AskUserQuestion', 'ExitPlanMode']);
|
|
106
|
+
const middle = list => list.length ? list.length % 2 ? list[Math.floor(list.length / 2)] : (list[list.length / 2 - 1] + list[list.length / 2]) / 2 : null;
|
|
107
|
+
let split = null;
|
|
108
|
+
if (query.provider !== 'codex') {
|
|
109
|
+
const byTurn = new Map();
|
|
110
|
+
for (const call of calls.values()) {
|
|
111
|
+
const s = call.start, e = call.end;
|
|
112
|
+
if (!s?.turn || !e || s.provider !== 'claude' || s.clock !== 'hook' || e.clock !== 'hook' || !finite(s.at) || !finite(e.at) || e.at < s.at || holders.has(s.tool)) continue;
|
|
113
|
+
if (!byTurn.has(s.turn)) byTurn.set(s.turn, []);
|
|
114
|
+
byTurn.get(s.turn).push(call);
|
|
115
|
+
}
|
|
116
|
+
const sum = { turns: 0, open: 0, totalMs: 0, claudeMs: 0, machineMs: 0, youMs: 0 }, machine = new Map(), you = new Map(), replies = [], stops = {};
|
|
117
|
+
const add = (map, operation, ms) => map.set(operation, (map.get(operation) ?? 0) + ms);
|
|
118
|
+
for (const [id, call] of calls) {
|
|
119
|
+
const begin = call.turn, end = call['turn-end'];
|
|
120
|
+
if (!begin || begin.t < since || begin.t > until) continue;
|
|
121
|
+
if (!end || !finite(begin.at) || !finite(end.at) || end.at <= begin.at || end.at - begin.at > DAY) { sum.open++; continue; }
|
|
122
|
+
const a = begin.at, b = end.at, spans = [];
|
|
123
|
+
sum.turns++; sum.totalMs += b - a;
|
|
124
|
+
if (end.stop !== 'done') stops[end.stop] = (stops[end.stop] ?? 0) + 1;
|
|
125
|
+
for (const { start: s, end: e } of byTurn.get(id) ?? []) {
|
|
126
|
+
// A command's time is its lead's: npm test's, not the tail reading its output.
|
|
127
|
+
const own = s.lead ?? s.operations;
|
|
128
|
+
if (questions.has(s.tool)) { spans.push([s.at, e.at, you, own]); continue; }
|
|
129
|
+
// Claude Code's own time for the call ends where the call does; what comes
|
|
130
|
+
// before it is the approval, when a prompt came up, or else the hooks.
|
|
131
|
+
const run = finite(e.ms) ? Math.min(e.ms, e.at - s.at) : e.at - s.at, from = e.at - run;
|
|
132
|
+
if (run > 0) spans.push([from, e.at, machine, own]);
|
|
133
|
+
if (from > s.at) spans.push(e.asked ? [s.at, from, you, own] : [s.at, from, machine, ['(starting tools)']]);
|
|
134
|
+
}
|
|
135
|
+
const edges = [];
|
|
136
|
+
for (const span of spans) { const x = Math.max(span[0], a), y = Math.min(span[1], b); if (y > x) edges.push([x, 1, span], [y, -1, span]); }
|
|
137
|
+
edges.sort((p, q) => p[0] - q[0] || p[1] - q[1]);
|
|
138
|
+
const live = new Set(); let at = a, reply = 0, replyFrom = a;
|
|
139
|
+
const spend = to => {
|
|
140
|
+
const ms = to - at; if (ms <= 0) return;
|
|
141
|
+
const running = [...live].filter(span => span[2] === machine), lane = running.length ? running : [...live];
|
|
142
|
+
if (!lane.length) { if (!reply) replyFrom = at; reply += ms; sum.claudeMs += ms; at = to; return; }
|
|
143
|
+
if (reply) { replies.push([replyFrom, reply]); reply = 0; }
|
|
144
|
+
if (running.length) sum.machineMs += ms; else sum.youMs += ms;
|
|
145
|
+
for (const span of lane) for (const operation of span[3]) add(span[2], operation, ms / lane.length / span[3].length);
|
|
146
|
+
at = to;
|
|
147
|
+
};
|
|
148
|
+
for (const [t, step, span] of edges) { spend(t); if (step > 0) live.add(span); else live.delete(span); }
|
|
149
|
+
spend(b);
|
|
150
|
+
if (reply) replies.push([replyFrom, reply]);
|
|
151
|
+
}
|
|
152
|
+
// Claude's replies by the reader's calendar day, so a slow afternoon shows as one.
|
|
153
|
+
const dayOf = new Intl.DateTimeFormat('en-CA', { timeZone: query.timeZone ?? 'UTC', year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
154
|
+
const days = new Map();
|
|
155
|
+
for (let t = since; t <= until; t += DAY / 2) days.set(dayOf.format(new Date(t)), []);
|
|
156
|
+
days.set(dayOf.format(new Date(until)), days.get(dayOf.format(new Date(until))) ?? []);
|
|
157
|
+
for (const [t, ms] of replies) days.get(dayOf.format(new Date(t)))?.push(ms);
|
|
158
|
+
const lengths = replies.map(r => r[1]).sort((x, y) => x - y);
|
|
159
|
+
const top = (map, n) => [...map].map(([operation, ms]) => ({ operation, ms: Math.round(ms) })).sort((p, q) => q.ms - p.ms || p.operation.localeCompare(q.operation)).slice(0, n);
|
|
160
|
+
split = { ...sum, machine: top(machine, 40), you: top(you, 20), stops,
|
|
161
|
+
replies: { count: lengths.length, medianMs: middle(lengths), p90Ms: lengths.length >= 10 ? percentile(lengths, .9) : null, maxMs: lengths.at(-1) ?? null,
|
|
162
|
+
days: [...days].map(([date, list]) => { list.sort((x, y) => x - y); return { date, count: list.length, medianMs: middle(list) }; }) } };
|
|
163
|
+
}
|
|
92
164
|
const rows = [...groups.values()].map(g => {
|
|
93
165
|
const durations = g.durations.sort((a, b) => a - b);
|
|
94
166
|
const n = durations.length;
|
|
@@ -102,7 +174,7 @@ const percentile = (sorted, p) => sorted.length ? sorted[Math.max(0, Math.ceil(s
|
|
|
102
174
|
}).sort((a, b) => b.calls - a.calls || a.operation.localeCompare(b.operation));
|
|
103
175
|
return { ok: true, capturedAt: now, since, until, provider: query.provider, total, measured, failed, unmatched: pending,
|
|
104
176
|
corrupt, duplicates, orphaned, rows, totalMs, completed: total - pending, providers, observedSince, observedUntil,
|
|
105
|
-
retainedSince,
|
|
177
|
+
retainedSince, split,
|
|
106
178
|
details: query.operation ? { operation: query.operation, total: details.length,
|
|
107
179
|
...(query.history ? { capturedAt: now, measurements: rows.find(row => row.operation === query.operation) ?? null, history: { timeZone: query.timeZone ?? 'UTC', days: [...daily.values()].map(bucket => {
|
|
108
180
|
const sorted = bucket.durations.sort((a, b) => a - b), n = sorted.length;
|
|
@@ -17,7 +17,7 @@ export function auditQuery(params) {
|
|
|
17
17
|
if (!['all', 'claude', 'codex'].includes(provider) || ![1, 7, 30, 60, 90].includes(days)
|
|
18
18
|
|| operation && operation.length > 150 || skill !== undefined && !/^[^\s<>]{1,150}$/.test(skill) || !!since !== !!until) return null;
|
|
19
19
|
if (since && (!calendarDate(since) || !calendarDate(until) || since > until || Date.parse(until) - Date.parse(since) >= 90 * 86400000)) return null;
|
|
20
|
-
return { provider, days, ...(view === 'skills' ? { view, skill } : { operation }), ...(history ? { history: true
|
|
20
|
+
return { provider, days, timeZone, ...(view === 'skills' ? { view, skill } : { operation }), ...(history ? { history: true } : {}), ...(since ? { since: Date.parse(since), until: Date.parse(until) + 86400000 - 1 } : {}) };
|
|
21
21
|
}
|
|
22
22
|
export async function handleToolAudit(req, res) {
|
|
23
23
|
const audit = toolAudit();
|
|
@@ -59,8 +59,13 @@ const named = r => text(r.skill, 150) && ['typed', 'agent', 'detected'].includes
|
|
|
59
59
|
const counted = picked.filter(use => !use.repeat).sort((a, b) => b.at - a.at);
|
|
60
60
|
const projects = new Map();
|
|
61
61
|
for (const use of counted) if (use.project) projects.set(use.project, (projects.get(use.project) ?? 0) + 1);
|
|
62
|
+
const ranked = [...projects].map(([name, uses]) => ({ name, uses })).sort((a, b) => b.uses - a.uses || a.name.localeCompare(b.name));
|
|
63
|
+
// What the five named projects leave out, so the list adds up to the uses: the
|
|
64
|
+
// rest of the projects, and uses with no project folder to name.
|
|
65
|
+
const rest = ranked.slice(5);
|
|
62
66
|
details = { name: query.skill, row: rows.find(row => row.name === query.skill) ?? null, total: counted.length,
|
|
63
|
-
projects:
|
|
67
|
+
projects: ranked.slice(0, 5), moreProjects: { projects: rest.length, uses: rest.reduce((sum, item) => sum + item.uses, 0) },
|
|
68
|
+
projectless: counted.filter(use => !use.project).length,
|
|
64
69
|
recent: counted.slice(0, 50).map(({ id, provider, at, origin, session, project, subagent, state }) => ({ id, provider, at, origin, session, project, subagent, state })) };
|
|
65
70
|
if (query.history) {
|
|
66
71
|
const format = new Intl.DateTimeFormat('en-CA', { timeZone: query.timeZone ?? 'UTC', year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
@@ -71,9 +76,9 @@ const named = r => text(r.skill, 150) && ['typed', 'agent', 'detected'].includes
|
|
|
71
76
|
// Calendar labels advance independently of offsets: DST days may be 23 or 25 hours.
|
|
72
77
|
for (let date = first; date <= last; date += DAY) {
|
|
73
78
|
const key = new Date(date).toISOString().slice(0, 10);
|
|
74
|
-
days.set(key, { date: key, uses: 0, providers: { claude: 0, codex: 0 }, status: key < countedDay ? 'outside-history' : 'no-uses' });
|
|
79
|
+
days.set(key, { date: key, uses: 0, providers: { claude: 0, codex: 0 }, agent: 0, typed: 0, detected: 0, status: key < countedDay ? 'outside-history' : 'no-uses' });
|
|
75
80
|
}
|
|
76
|
-
for (const use of counted) { const day = days.get(dayKey(use.at)); if (day) { day.uses++; day.providers[use.provider]++; day.status = 'used'; } }
|
|
81
|
+
for (const use of counted) { const day = days.get(dayKey(use.at)); if (day) { day.uses++; day.providers[use.provider]++; day[use.origin]++; day.status = 'used'; } }
|
|
77
82
|
details.history = { timeZone: query.timeZone ?? 'UTC', days: [...days.values()] };
|
|
78
83
|
}
|
|
79
84
|
}
|