ccdeck 3.45.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.
Files changed (61) hide show
  1. package/README.md +79 -47
  2. package/bin/cli/startup.js +27 -3
  3. package/bin/deck.js +32 -1
  4. package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +1 -0
  5. package/dist/web/assets/IntegrationModal-8tTi25gA.js +6 -0
  6. package/dist/web/assets/RadioPanel-DbmJJPsz.js +1 -0
  7. package/dist/web/assets/TrafficRadar-CPjAXd5e.js +8 -0
  8. package/dist/web/assets/{UsageHistoryModal-DAhplVju.js → UsageHistoryModal-qfmvXdWJ.js} +1 -1
  9. package/dist/web/assets/app-BFFG6Wz8.js +321 -0
  10. package/dist/web/assets/app-DfcfHvcX.css +1 -0
  11. package/dist/web/assets/claude-settings-index-1Qg1AUda.js +1 -0
  12. package/dist/web/assets/{index-r8Ymr47Q.js → index-Ca87aJP9.js} +1 -1
  13. package/dist/web/index.html +3 -3
  14. package/package.json +1 -1
  15. package/release-notes.json +60 -0
  16. package/src/server/ccusage-install.mjs +58 -1
  17. package/src/server/ccusage-registry.mjs +289 -0
  18. package/src/server/ccusage-runner.mjs +9 -2
  19. package/src/server/claude-accounts.mjs +56 -19
  20. package/src/server/claude-login.mjs +129 -0
  21. package/src/server/claude-settings-catalog.d.mts +37 -0
  22. package/src/server/claude-settings-catalog.mjs +169 -0
  23. package/src/server/claude-settings-docs.mjs +109 -0
  24. package/src/server/claude-settings-index.json +251 -0
  25. package/src/server/claude-settings-routes.mjs +46 -0
  26. package/src/server/claude-settings.mjs +406 -0
  27. package/src/server/cli-arrival.mjs +64 -0
  28. package/src/server/cswap-admin.mjs +12 -3
  29. package/src/server/index.mjs +18 -2
  30. package/src/server/installer.mjs +24 -7
  31. package/src/server/integrations/proxy.mjs +11 -2
  32. package/src/server/integrations/routes.mjs +6 -4
  33. package/src/server/login-service.mjs +2 -2
  34. package/src/server/quota-close-watch.mjs +81 -0
  35. package/src/server/quota-closes.mjs +181 -0
  36. package/src/server/quota-history.mjs +8 -1
  37. package/src/server/quota-shape.mjs +12 -0
  38. package/src/server/quota.mjs +28 -1
  39. package/src/server/request-gates.mjs +3 -1
  40. package/src/server/skill-hook.mjs +28 -22
  41. package/src/server/system-metrics.mjs +4 -0
  42. package/src/server/tool-audit-operations.mjs +30 -10
  43. package/src/server/tool-audit-report.mjs +79 -7
  44. package/src/server/tool-audit-routes.mjs +5 -1
  45. package/src/server/tool-audit-skills.mjs +8 -3
  46. package/src/server/tool-audit.mjs +55 -5
  47. package/src/server/traffic-radar-capture.mjs +3 -3
  48. package/src/server/traffic-radar-config.mjs +43 -3
  49. package/src/server/traffic-radar-monitor.mjs +8 -5
  50. package/src/server/traffic-radar-permission.mjs +162 -0
  51. package/src/server/traffic-radar-platform.mjs +93 -20
  52. package/src/server/traffic-radar-routes.mjs +8 -18
  53. package/src/server/traffic-radar-service.mjs +81 -94
  54. package/src/server/traffic-radar.mjs +32 -9
  55. package/src/server/usage-routes.mjs +14 -2
  56. package/dist/web/assets/BrowserWatchModal-Cbzf3TWa.js +0 -1
  57. package/dist/web/assets/IntegrationModal-BnnBr0a3.js +0 -5
  58. package/dist/web/assets/RadioPanel-BIqrMLQN.js +0 -1
  59. package/dist/web/assets/TrafficRadar-D1gZCIwX.js +0 -8
  60. package/dist/web/assets/app-BW3NYUYB.js +0 -318
  61. package/dist/web/assets/app-C5RY_wZ4.css +0 -1
@@ -215,6 +215,14 @@ export function rasterMatches(type, b) {
215
215
  return false;
216
216
  }
217
217
 
218
+ /** The raster type the bytes are, by how they start, or null. An image is
219
+ * served under this, not its label: Jira Data Center labels an uploaded
220
+ * avatar's PNG image/jpeg. */
221
+ export function rasterTypeOf(b) {
222
+ for (const type of RASTER_TYPES) if (rasterMatches(type, b)) return type;
223
+ return null;
224
+ }
225
+
218
226
  /** An address that names this machine or a private network: loopback,
219
227
  * RFC 1918, link-local, CGNAT, unique-local IPv6, an IPv4-mapped one of
220
228
  * those, or a name with no public suffix (an intranet host). Only a token
@@ -308,7 +316,8 @@ export async function fetchImage(target, {
308
316
  }
309
317
  let bytes;
310
318
  try { bytes = await readCapped(res, maxBytes); } catch { throw integrationError("not-found", "The image is larger than the deck shows."); }
311
- if (!rasterMatches(type, bytes)) throw integrationError("not-found", "That is not an image the deck shows.");
312
- return { contentType: type, bytes };
319
+ const actual = rasterTypeOf(bytes);
320
+ if (!actual) throw integrationError("not-found", "That is not an image the deck shows.");
321
+ return { contentType: actual, bytes };
313
322
  }
314
323
  }
@@ -33,7 +33,7 @@
33
33
  import { createHash } from "node:crypto";
34
34
  import { readBody, send } from "../http-io.mjs";
35
35
  import { errorBody, errorResponse, integrationError, isTypedError } from "./errors.mjs";
36
- import { fetchImage, IMAGE_MAX_BYTES, isSafeTarget, normaliseBaseUrl, originOf, RASTER_TYPES, rasterMatches } from "./proxy.mjs";
36
+ import { fetchImage, IMAGE_MAX_BYTES, isSafeTarget, normaliseBaseUrl, originOf, RASTER_TYPES, rasterTypeOf } from "./proxy.mjs";
37
37
  import { getProvider, isAvailable, providerList } from "./registry.mjs";
38
38
  import { integrationsStore } from "./store.mjs";
39
39
  import "./providers.mjs";
@@ -160,10 +160,12 @@ async function serveAsset(res, conn, client, raw, { signal, method, fetchImpl })
160
160
  const got = typeof client.fetchAsset === "function"
161
161
  ? await client.fetchAsset(target.href, { maxBytes: IMAGE_MAX_BYTES, signal })
162
162
  : await genericAsset(client, target.href, { maxBytes: IMAGE_MAX_BYTES, signal, fetchImpl });
163
- const contentType = String(got?.contentType ?? "").split(";")[0].trim().toLowerCase();
163
+ const declared = String(got?.contentType ?? "").split(";")[0].trim().toLowerCase();
164
164
  const bytes = got?.bytes;
165
- // The route checks again what every client promised.
166
- if (!RASTER_TYPES.has(contentType) || !Buffer.isBuffer(bytes) || bytes.length > IMAGE_MAX_BYTES || !rasterMatches(contentType, bytes)) {
165
+ // The route checks again what every client promised, and serves the
166
+ // image as the type its bytes are, whichever raster type it was labelled.
167
+ const contentType = Buffer.isBuffer(bytes) ? rasterTypeOf(bytes) : null;
168
+ if (!RASTER_TYPES.has(declared) || !contentType || bytes.length > IMAGE_MAX_BYTES) {
167
169
  throw integrationError("not-found", "Not an image the deck shows.");
168
170
  }
169
171
  image = { at: Date.now(), contentType, bytes };
@@ -403,8 +403,8 @@ export const SETTING_VARS = Object.freeze([
403
403
  "AGENTS_DECK_NO_INSTALL", "AGENTS_DECK_NO_DOWNLOAD", "AGENTS_DECK_NO_UPDATE_CHECK", "AGENTS_DECK_NO_STATUS",
404
404
  "AGENTS_DECK_NO_FRESHEN", "AGENTS_DECK_NO_NOTIFY", "AGENTS_DECK_NO_LAN", "AGENTS_DECK_NO_REPORTS",
405
405
  "AGENTS_DECK_CSWAP", "AGENTS_DECK_CLAUDE", "AGENTS_DECK_CCUSAGE", "CLAUDE_SWAP_BACKUP", "AGENTS_DECK_LHM_PORT",
406
- // The opt-in for Skill activity's typed-command hook (skill-hook.mjs). A deck
407
- // started at login without it would take the entry back out.
406
+ // The off switch for Skill activity's typed-command hook (skill-hook.mjs). A
407
+ // deck started at login without it would put the entry back in.
408
408
  "AGENTS_DECK_SKILL_HOOK",
409
409
  ]);
410
410
 
@@ -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) { reading.historyAccount = key; void history.record(provider, key, reading); }
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.
@@ -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
@@ -1,6 +1,9 @@
1
1
  // Whether the deck may add the UserPromptExpansion hook that Skill activity
2
- // counts typed slash commands with (#2181) — and, until somebody asks for it,
3
- // the answer is no.
2
+ // counts typed slash commands with (#2181). It is the only signal for them: a
3
+ // typed skill never calls the Skill tool, and UserPromptSubmit also carries a
4
+ // prompt that only starts like a command (`/etc is full`, an unknown command
5
+ // Claude Code hands to the model), so without this entry the Skills tab counts
6
+ // none of the commands a person types. On by default, behind the version gate.
4
7
  //
5
8
  // WHY THIS ENTRY IS GATED HARDER THAN STOPFAILURE. A hook event name Claude
6
9
  // Code does not know is not skipped by every version. Up to 2.1.100 it made
@@ -23,7 +26,8 @@
23
26
  // it costs the user every setting they have.
24
27
  //
25
28
  // WHAT HAS TO BE TRUE before the entry is written:
26
- // - the deck was started with AGENTS_DECK_SKILL_HOOK=1 — never by default;
29
+ // - the deck was not started with AGENTS_DECK_SKILL_HOOK turned off (any
30
+ // value but 1; unset or empty is on);
27
31
  // - at least one Claude Code was found, the way the deck finds `claude`: the
28
32
  // candidate list (claude-dir.mjs) and AGENTS_DECK_CLAUDE;
29
33
  // - EVERY one found says which version it is, and every one is 2.1.116 or
@@ -31,11 +35,11 @@
31
35
  // one that will not say its version is treated as an old one.
32
36
  // A version is read off disk first (claude-dir.mjs, no child process). Only
33
37
  // for an install whose layout does not name one — a wrapper script, an unusual
34
- // prefix — and only once the user has opted in, is that binary asked
38
+ // prefix — and only while the entry is not turned off, is that binary asked
35
39
  // `--version`, by its full path and as argv, and believed only when it answers
36
40
  // the way Claude Code does: `<x.y.z> (Claude Code)`.
37
41
  //
38
- // Every boot re-decides. A machine that stops passing — the opt-in removed, a
42
+ // Every boot re-decides. A machine that stops passing — the entry turned off, a
39
43
  // Claude Code rolled back, a second, older one installed — has the entry taken
40
44
  // back out by the next start (installer.mjs), and the user's own
41
45
  // UserPromptExpansion hooks are left where they are.
@@ -56,13 +60,15 @@ export const SKILL_HOOK_SINCE = claudeVersionAtLeast(USER_PROMPT_EXPANSION_SINCE
56
60
  ? USER_PROMPT_EXPANSION_SINCE
57
61
  : UNKNOWN_EVENT_TOLERATED_SINCE;
58
62
 
59
- /** Set to "1" to ask for the entry. Anything else, or nothing, is no. */
63
+ /** Set to "0" to leave the entry out. Unset, empty or "1" is on. */
60
64
  export const SKILL_HOOK_ENV = "AGENTS_DECK_SKILL_HOOK";
61
65
 
62
- /** Whether the person starting the deck asked for the entry. Only the exact
63
- * string "1": a typo or a "true" does not turn it on. */
64
- export function skillHookOptedIn(env = process.env) {
65
- return env?.[SKILL_HOOK_ENV] === "1";
66
+ /** Whether the person starting the deck left the entry on. Any value but "1"
67
+ * turns it off, so a "false", an "off" or a typo is honoured as a no rather
68
+ * than read as a yes; only unset or empty is no instruction at all. */
69
+ export function skillHookEnabled(env = process.env) {
70
+ const value = env?.[SKILL_HOOK_ENV];
71
+ return value === undefined || value === "" || value === "1";
66
72
  }
67
73
 
68
74
  /** A `--version` that is not quick is not Claude Code's fast path. */
@@ -92,7 +98,7 @@ async function askVersion(runImpl, bin, timeout) {
92
98
  /**
93
99
  * The decision, and why:
94
100
  *
95
- * { install: false, state: "off", reason: "not-enabled" }
101
+ * { install: false, state: "off", reason: "turned-off" }
96
102
  * { install: false, state: "skipped", reason: "no-claude" | "version-unknown" | "too-old", versions }
97
103
  * { install: true, state: "on", versions }
98
104
  *
@@ -105,15 +111,15 @@ async function askVersion(runImpl, bin, timeout) {
105
111
  */
106
112
  export async function skillHookDecision({
107
113
  env = process.env,
108
- optedIn = skillHookOptedIn(env),
114
+ enabled = skillHookEnabled(env),
109
115
  installs,
110
116
  runImpl = run,
111
117
  timeout = PROBE_TIMEOUT_MS,
112
118
  } = {}) {
113
119
  const since = SKILL_HOOK_SINCE;
114
- // Off is decided before anything is looked at: a deck that was not asked
115
- // spends nothing on the question, and spawns nothing.
116
- if (!optedIn) return { install: false, state: "off", reason: "not-enabled", since, versions: [] };
120
+ // Off is decided before anything is looked at: a deck told to leave the
121
+ // entry out spends nothing on the question, and spawns nothing.
122
+ if (!enabled) return { install: false, state: "off", reason: "turned-off", since, versions: [] };
117
123
  let found;
118
124
  try {
119
125
  found = Array.isArray(installs) ? [...installs] : claudeCodeInstalls();
@@ -140,16 +146,16 @@ export async function skillHookDecision({
140
146
  }
141
147
 
142
148
  /**
143
- * The boot report's row for the entry — `{ ok, detail }` — or null when there
144
- * is nothing to say, which is the default: nobody asked for it, and a deck
145
- * that was not asked prints exactly what it printed before. `dash` is the
146
- * screen's own (bin/cli/screen.js), so the line carries no punctuation a
147
- * legacy console cannot draw.
149
+ * The boot report's row for the entry — `{ ok: false, detail }` — or null when
150
+ * there is nothing to say: installed, which is the default and needs no line,
151
+ * or turned off by the person starting the deck, who knows. Only an entry the
152
+ * gate or the file kept out is said, since then the Skills tab counts no typed
153
+ * command. `dash` is the screen's own (bin/cli/screen.js), so the line carries
154
+ * no punctuation a legacy console cannot draw.
148
155
  */
149
156
  export function skillHookStatus(decision, dash = "-") {
150
- if (!decision || decision.state === "off") return null;
157
+ if (!decision || decision.state === "off" || decision.state === "on") return null;
151
158
  const found = (decision.versions ?? []).map(v => v ?? "unknown").join(", ");
152
- if (decision.state === "on") return { ok: true, detail: `on ${dash} counts typed slash commands (Claude Code ${found})` };
153
159
  const why = {
154
160
  "no-claude": "no Claude Code found",
155
161
  "version-unknown": `a Claude Code here does not say its version (found: ${found})`,
@@ -264,6 +264,10 @@ function loadSeries(at, coreCount) {
264
264
  warnAt: coreCount,
265
265
  critAt: null,
266
266
  restsAtZero: false,
267
+ // What the chart's reading divides by, so a point read after the fact says
268
+ // how many times over the cores it was — the live note's figure, for a
269
+ // minute that is no longer live.
270
+ cores: coreCount,
267
271
  points,
268
272
  }];
269
273
  }
@@ -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
- for (const ch of command.slice(0, 32768)) {
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') { word(); segments.push([]); } else word(); }
15
- else if (';&|'.includes(ch)) { word(); if (segments.at(-1).length) segments.push([]); }
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
- return { segments: segments.filter(s => s.length), uncertain: !!quote || escaped || /\$\(|`|<<|\b(?:if|for|while|case|function)\b/.test(command) };
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 shellOperations(args[at + 1], depth + 1);
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
- export function shellOperations(command, depth = 0) {
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
- return [...new Set(segments.flatMap(words => operation(words, depth)))].slice(0, 16);
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, operations: shellOperations(command), shell: true };
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 };