ccdeck 3.46.0 → 3.48.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 +99 -46
- package/bin/cli/commands.js +17 -9
- package/bin/cli/help.js +9 -4
- package/bin/cli/second-start.js +4 -2
- package/bin/cli/startup.js +26 -2
- package/bin/cli/tui.js +544 -0
- package/bin/deck.js +32 -1
- package/dist/web/assets/{BrowserWatchModal-CoX9FIUE.js → BrowserWatchModal-DuopT2Oa.js} +1 -1
- package/dist/web/assets/IntegrationModal-CszT-tts.js +7 -0
- package/dist/web/assets/{RadioPanel-biw_BbZq.js → RadioPanel-Cn3WvPUG.js} +1 -1
- package/dist/web/assets/TrafficRadar-DZA8XSi7.js +8 -0
- package/dist/web/assets/UsageHistoryModal-MgZJLXbF.js +1 -0
- package/dist/web/assets/app-DjlHxWHg.css +1 -0
- package/dist/web/assets/app-F1xryJpn.js +321 -0
- package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
- package/dist/web/assets/{index-DmENqVdt.js → index-BK9avF1k.js} +1 -1
- package/dist/web/index.html +3 -3
- package/package.json +1 -1
- package/release-notes.json +58 -2
- package/src/server/args.mjs +1 -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/cli-lines.mjs +46 -0
- package/src/server/gpu-metrics.mjs +78 -0
- package/src/server/index.mjs +18 -2
- package/src/server/integrations/jira-move.mjs +239 -0
- package/src/server/integrations/jira.mjs +30 -8
- package/src/server/integrations/proxy.mjs +14 -6
- package/src/server/integrations/routes.mjs +25 -9
- 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/system-metrics.mjs +4 -0
- package/src/server/term.mjs +14 -5
- 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/tui-screen.mjs +110 -0
- package/src/server/tui-view.mjs +1072 -0
- package/src/server/usage-routes.mjs +14 -2
- package/src/server/way-back.mjs +27 -0
- package/dist/web/assets/IntegrationModal-B1ypkK-E.js +0 -5
- package/dist/web/assets/TrafficRadar-nhtFoYVv.js +0 -8
- package/dist/web/assets/UsageHistoryModal-Bd-JRAa4.js +0 -1
- package/dist/web/assets/app-BlRY6EME.css +0 -1
- package/dist/web/assets/app-DhGvSH7o.js +0 -319
|
@@ -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
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
// readout the loudest producer in the application. So this is a plain poll
|
|
19
19
|
// endpoint, exactly like /api/quota and /api/codex-usage already are.
|
|
20
20
|
import os from "node:os";
|
|
21
|
+
import { startGpuMetrics, stopGpuMetrics, gpuSnapshot } from "./gpu-metrics.mjs";
|
|
21
22
|
import { loadReading } from "./load-average.mjs";
|
|
22
23
|
import { BUCKET_MS, labelsUnder, oldestBucketMs, pointsOf, record, resetHistory } from "./metrics-history.mjs";
|
|
23
24
|
import { readAvailable, readSwap } from "./memory-metrics.mjs";
|
|
@@ -374,6 +375,7 @@ export function startSystemMetrics({ probe = false } = {}) {
|
|
|
374
375
|
cpuTimer = setInterval(sampleCpu, CPU_INTERVAL_MS);
|
|
375
376
|
memTimer = setInterval(sampleMemory, MEM_INTERVAL_MS);
|
|
376
377
|
startThermalTimer();
|
|
378
|
+
startGpuMetrics();
|
|
377
379
|
startNetworkTimers(probe);
|
|
378
380
|
cpuTimer.unref?.();
|
|
379
381
|
memTimer.unref?.();
|
|
@@ -401,6 +403,7 @@ export function stopSystemMetrics() {
|
|
|
401
403
|
if (memTimer) clearInterval(memTimer);
|
|
402
404
|
cpuTimer = memTimer = null;
|
|
403
405
|
stopThermal();
|
|
406
|
+
stopGpuMetrics();
|
|
404
407
|
stopNetwork();
|
|
405
408
|
resetHistory();
|
|
406
409
|
historySince = 0;
|
|
@@ -436,6 +439,7 @@ export function systemSnapshot() {
|
|
|
436
439
|
// Null on a machine that publishes nothing, and the panel draws no section
|
|
437
440
|
// at all for it rather than an empty one.
|
|
438
441
|
thermal: thermalSnapshot(),
|
|
442
|
+
gpus: gpuSnapshot(),
|
|
439
443
|
uptimeSec: Math.round(os.uptime()),
|
|
440
444
|
platform: process.platform,
|
|
441
445
|
// The rule the `load:1m` record in sampleCpu asks too — see loadReading.
|
package/src/server/term.mjs
CHANGED
|
@@ -83,12 +83,15 @@ export function colorProfile({ env = process.env, isTTY = false, platform = proc
|
|
|
83
83
|
// ── colours ──────────────────────────────────────────────────────────────────
|
|
84
84
|
|
|
85
85
|
/** rgb → the nearest xterm-256 index: the 6×6×6 cube, or the 24-step grey ramp
|
|
86
|
-
* for anything neutral, which is where the muted tones land.
|
|
86
|
+
* for anything neutral, which is where the muted tones land. Neutral is near
|
|
87
|
+
* grey, not exactly grey: the muted tone is a cool grey, and the cube's
|
|
88
|
+
* nearest to it is a teal — every border and every quiet word, under tmux. */
|
|
87
89
|
function to256(r, g, b) {
|
|
88
|
-
if (r
|
|
89
|
-
|
|
90
|
-
if (
|
|
91
|
-
|
|
90
|
+
if (Math.max(r, g, b) - Math.min(r, g, b) < 16) {
|
|
91
|
+
const v = Math.round((r + g + b) / 3);
|
|
92
|
+
if (v < 8) return 16;
|
|
93
|
+
if (v > 248) return 231;
|
|
94
|
+
return Math.round(((v - 8) / 247) * 24) + 232;
|
|
92
95
|
}
|
|
93
96
|
return 16 + 36 * Math.round((r / 255) * 5) + 6 * Math.round((g / 255) * 5) + Math.round((b / 255) * 5);
|
|
94
97
|
}
|
|
@@ -189,6 +192,12 @@ const ASCII_GLYPHS = {
|
|
|
189
192
|
arrow: "->", ellipsis: "...", dash: "-", bullet: "-",
|
|
190
193
|
};
|
|
191
194
|
|
|
195
|
+
/** Whether this shell came in over SSH: sshd sets one of these in every
|
|
196
|
+
* session it starts, interactive or not. */
|
|
197
|
+
export function overSsh(env = process.env) {
|
|
198
|
+
return set(env.SSH_CONNECTION) || set(env.SSH_CLIENT) || set(env.SSH_TTY);
|
|
199
|
+
}
|
|
200
|
+
|
|
192
201
|
/**
|
|
193
202
|
* Whether this terminal can be trusted with the box-drawing and arrow glyphs.
|
|
194
203
|
*
|
|
@@ -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
|
}
|