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.
Files changed (54) hide show
  1. package/README.md +72 -43
  2. package/bin/cli/startup.js +23 -0
  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-biw_BbZq.js → RadioPanel-DbmJJPsz.js} +1 -1
  7. package/dist/web/assets/TrafficRadar-CPjAXd5e.js +8 -0
  8. package/dist/web/assets/{UsageHistoryModal-Bd-JRAa4.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-DmENqVdt.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 +30 -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 +21 -0
  20. package/src/server/claude-login.mjs +21 -3
  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/index.mjs +18 -2
  29. package/src/server/integrations/proxy.mjs +11 -2
  30. package/src/server/integrations/routes.mjs +6 -4
  31. package/src/server/quota-close-watch.mjs +81 -0
  32. package/src/server/quota-closes.mjs +181 -0
  33. package/src/server/quota-history.mjs +8 -1
  34. package/src/server/quota-shape.mjs +12 -0
  35. package/src/server/quota.mjs +28 -1
  36. package/src/server/request-gates.mjs +3 -1
  37. package/src/server/tool-audit-operations.mjs +30 -10
  38. package/src/server/tool-audit-report.mjs +79 -7
  39. package/src/server/tool-audit-routes.mjs +1 -1
  40. package/src/server/tool-audit-skills.mjs +8 -3
  41. package/src/server/tool-audit.mjs +55 -5
  42. package/src/server/traffic-radar-capture.mjs +3 -3
  43. package/src/server/traffic-radar-config.mjs +10 -3
  44. package/src/server/traffic-radar-monitor.mjs +8 -5
  45. package/src/server/traffic-radar-permission.mjs +162 -0
  46. package/src/server/traffic-radar-platform.mjs +9 -3
  47. package/src/server/traffic-radar-routes.mjs +8 -18
  48. package/src/server/traffic-radar-service.mjs +76 -92
  49. package/src/server/usage-routes.mjs +14 -2
  50. package/dist/web/assets/BrowserWatchModal-CoX9FIUE.js +0 -1
  51. package/dist/web/assets/IntegrationModal-B1ypkK-E.js +0 -5
  52. package/dist/web/assets/TrafficRadar-nhtFoYVv.js +0 -8
  53. package/dist/web/assets/app-BlRY6EME.css +0 -1
  54. package/dist/web/assets/app-DhGvSH7o.js +0 -319
@@ -0,0 +1,406 @@
1
+ // Settings › Claude Code: what the short list of Claude Code settings
2
+ // (claude-settings-catalog.mjs) reads as on this machine, and the one write
3
+ // that changes one of them in the user's settings.json.
4
+ //
5
+ // THE USER FILE IS THE ONLY ONE WRITTEN. Claude Code reads settings from five
6
+ // places, and the four others are not the deck's to touch: managed settings
7
+ // and the cached organization settings belong to an administrator, and a
8
+ // project's .claude/settings.json and settings.local.json belong to that
9
+ // project. Those two are read anyway, the administrator's ones, so a row they
10
+ // decide says so and offers no control; a project file can still override a
11
+ // row in that project, which the section says once rather than on every row.
12
+ //
13
+ // WHAT IS SENT TO THE PAGE. A value is sent only where the table or the
14
+ // generated index (claude-settings-index.json) says what kind of value the
15
+ // key holds and the value is one of the safe kinds: a Boolean, a number, or a
16
+ // string from the key's own list of choices. Everything else in the file —
17
+ // env blocks, helper commands, URLs, tokens — is reported as present and
18
+ // nothing more, because the deck has no business carrying it into a page.
19
+ //
20
+ // NOTHING IS GUESSED. A row shows what Claude Code will do, or no value at
21
+ // all: a settings.json that cannot be read sends no values, only why; a
22
+ // variable that outranks a key (the table's `overrides`) is said under its
23
+ // row; the old `includeCoAuthoredBy: false`, and a turn-duration choice an
24
+ // older Claude Code kept in ~/.claude.json, are read as Claude Code still
25
+ // reads them; and a row that needs a newer Claude Code is not written while
26
+ // the version here cannot be read.
27
+ import { readFileSync } from "node:fs";
28
+ import { mkdir, readdir, readFile, stat, unlink } from "node:fs/promises";
29
+ import { homedir } from "node:os";
30
+ import { posix, win32 } from "node:path";
31
+ import { createTemp, readSettingsForWrite, renameWithRetry, writeFileAtomic } from "./atomic-write.mjs";
32
+ import { CLAUDE_SETTINGS, claudeSettingById } from "./claude-settings-catalog.mjs";
33
+ import { claudeCodeVersions, claudeConfigDir, claudeVersionAtLeast } from "./claude-dir.mjs";
34
+ import { claudeGlobalConfigPath } from "./claude-login.mjs";
35
+ import { deckDataDir } from "./deck-home.mjs";
36
+ import { managedSettingsPath, readBoundedJson } from "./traffic-radar-config.mjs";
37
+
38
+ /** Before this Claude Code ignored a whole settings.json that held a key it
39
+ * did not know (installer.mjs), so the section changes nothing below it. */
40
+ export const WRITABLE_SINCE = "2.1.101";
41
+
42
+ /** The file the last state before each change is kept in, in the deck's own
43
+ * directory, mode 0600: settings.json can hold API keys in its env block. */
44
+ export const SETTINGS_BACKUP = "claude-settings.before-change.json";
45
+
46
+ let indexCache = null;
47
+ /** The generated list of every key Claude Code documents, read once. */
48
+ export function settingsIndex() {
49
+ if (!indexCache) {
50
+ try { indexCache = JSON.parse(readFileSync(new URL("./claude-settings-index.json", import.meta.url), "utf8")); }
51
+ catch { indexCache = { keys: [] }; }
52
+ }
53
+ return indexCache;
54
+ }
55
+
56
+ const isObject = value => !!value && typeof value === "object" && !Array.isArray(value);
57
+
58
+ /** The oldest Claude Code found on disk, or null when none says its version. */
59
+ export function oldestClaudeVersion(versions) {
60
+ let oldest = null;
61
+ for (const version of versions) if (!oldest || !claudeVersionAtLeast(version, oldest)) oldest = version;
62
+ return oldest;
63
+ }
64
+
65
+ function files({ home, env, platform }) {
66
+ const join = platform === "win32" ? win32.join : posix.join;
67
+ const dir = claudeConfigDir(env, home, platform);
68
+ const managed = managedSettingsPath(platform, env);
69
+ const managedDir = (platform === "win32" ? win32 : posix).dirname(managed);
70
+ return {
71
+ dir,
72
+ user: join(dir, "settings.json"),
73
+ organization: join(dir, "remote-settings.json"),
74
+ managed,
75
+ dropIns: join(managedDir, "managed-settings.d"),
76
+ };
77
+ }
78
+
79
+ /** Every drop-in file an administrator put beside managed-settings.json,
80
+ * which Claude Code merges with it. A directory that exists and cannot be
81
+ * listed is a source the deck cannot vouch for. */
82
+ async function readDropIns(dir, join, readJson, list) {
83
+ let names;
84
+ try { names = await list(dir); }
85
+ catch (error) { return error?.code === "ENOENT" ? [] : [{ status: "unreadable", settings: {} }]; }
86
+ return Promise.all(names.filter(n => n.endsWith(".json")).sort().map(n => readSource(join(dir, n), readJson)));
87
+ }
88
+
89
+ /** A settings file as `read`, `absent`, `invalid` (not a JSON object, which
90
+ * Claude Code skips whole) or `unreadable` (by the deck: no permission, or
91
+ * larger than it reads). */
92
+ async function readSource(path, readJson) {
93
+ try {
94
+ const settings = await readJson(path);
95
+ return isObject(settings) ? { status: "read", settings } : { status: "invalid", settings: {} };
96
+ } catch (error) {
97
+ return { status: error?.code === "ENOENT" ? "absent" : error instanceof SyntaxError ? "invalid" : "unreadable", settings: {} };
98
+ }
99
+ }
100
+
101
+ const unknown = source => source.status === "invalid" || source.status === "unreadable";
102
+
103
+ let legacyCache = null;
104
+ /**
105
+ * The `legacy` rows' values an older Claude Code kept in its state file
106
+ * (~/.claude.json, or the config directory's when it moved), which still
107
+ * apply while no settings file sets the key. That file holds every project's
108
+ * history and can run to megabytes, so it is read again only when it changes.
109
+ */
110
+ export async function readLegacyValues({ home = homedir(), env = process.env, platform = process.platform } = {}) {
111
+ try {
112
+ const path = await claudeGlobalConfigPath({ env, home, platform });
113
+ const st = await stat(path);
114
+ if (legacyCache?.path === path && legacyCache.mtimeMs === st.mtimeMs && legacyCache.size === st.size) return legacyCache.values;
115
+ const state = st.size > 64 * 1024 * 1024 ? null : JSON.parse((await readFile(path, "utf8")).replace(/^/, ""));
116
+ const values = {};
117
+ for (const entry of CLAUDE_SETTINGS) {
118
+ if (entry.legacy && isObject(state) && typeof state[entry.key] === "boolean") values[entry.key] = state[entry.key];
119
+ }
120
+ legacyCache = { path, mtimeMs: st.mtimeMs, size: st.size, values };
121
+ return values;
122
+ } catch {
123
+ return {};
124
+ }
125
+ }
126
+
127
+ const ON = /^(1|true|yes|on)$/i;
128
+ const OFF = /^(0|false|no|off)$/i;
129
+
130
+ /** The variable that outranks this row, where it is set and what it makes of
131
+ * the row, or null. For each variable the first source that sets it
132
+ * decides — a settings file's `env` is applied over the environment a
133
+ * session starts with, the administrator's first. */
134
+ function overrideFor(entry, sources) {
135
+ for (const o of entry.overrides ?? []) {
136
+ const from = sources.find(s => isObject(s.env) && s.env[o.env] !== undefined && s.env[o.env] !== null);
137
+ if (!from) continue;
138
+ const value = String(from.env[o.env]).trim();
139
+ if ((o.when === "on" ? ON : OFF).test(value)) return { env: o.env, value, where: from.where, effect: o.effect };
140
+ }
141
+ return null;
142
+ }
143
+
144
+ /** `path` with the home directory written as ~, for the page to show. */
145
+ function shownPath(path, home, platform) {
146
+ const sep = platform === "win32" ? "\\" : "/";
147
+ return path === home || path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path;
148
+ }
149
+
150
+ const denies = (settings, tool) => {
151
+ const deny = settings?.permissions?.deny;
152
+ return Array.isArray(deny) && deny.includes(tool);
153
+ };
154
+
155
+ /** Whether a file decides this row: names its key, or for a tool row, denies
156
+ * the tool. The deprecated `includeCoAuthoredBy: false` still turns
157
+ * attribution off where `attribution` is not set. */
158
+ function decides(entry, settings) {
159
+ if (entry.kind === "allowTool") return denies(settings, entry.tool);
160
+ if (entry.kind === "attribution" && settings.includeCoAuthoredBy === false) return true;
161
+ return Object.hasOwn(settings, entry.key);
162
+ }
163
+
164
+ /** What the row's control shows for a settings object: a switch's Boolean, a
165
+ * choice's string or null, a day count. `custom` marks a value the row's
166
+ * control cannot express, which it shows but will not overwrite. `legacy`
167
+ * holds the values ~/.claude.json still gives a key no file sets. */
168
+ function rowValue(entry, settings, legacy = {}) {
169
+ const raw = settings[entry.key];
170
+ switch (entry.kind) {
171
+ case "allowTool": return { value: !denies(settings, entry.tool) };
172
+ case "attribution":
173
+ if (raw === undefined) return { value: settings.includeCoAuthoredBy !== false };
174
+ if (raw === false) return { value: false };
175
+ return { value: true, custom: true };
176
+ case "switch":
177
+ if (raw === undefined) return { value: entry.legacy && typeof legacy[entry.key] === "boolean" ? legacy[entry.key] : entry.unset };
178
+ return typeof raw === "boolean" ? { value: raw } : { value: entry.unset, custom: true };
179
+ case "days":
180
+ if (raw === undefined) return { value: entry.unset };
181
+ return Number.isInteger(raw) && raw >= 1 ? { value: raw } : { value: entry.unset, custom: true };
182
+ case "choice": {
183
+ if (raw === undefined) return { value: null };
184
+ const option = entry.options.find(o => o.value === raw || o.also === raw);
185
+ return option ? { value: option.value } : { value: null, custom: true };
186
+ }
187
+ default: return { value: null, custom: true };
188
+ }
189
+ }
190
+
191
+ /** A top-level value of the user file as the page may see it (see the header). */
192
+ export function safeDisplay(key, raw, index = settingsIndex()) {
193
+ if (typeof raw === "boolean") return String(raw);
194
+ if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
195
+ const known = index.keys.find(k => k.key === key);
196
+ if (typeof raw === "string" && known?.options?.includes(raw)) return raw;
197
+ return "set";
198
+ }
199
+
200
+ /**
201
+ * Every row of the table as this machine reads it.
202
+ *
203
+ * `editable` is false, with the reason in words, while a file that could
204
+ * decide the row cannot be read, while an administrator's file decides it,
205
+ * while the Claude Code on this machine is too old to read what it writes, or
206
+ * cannot be asked, or while the user file holds a value the control cannot
207
+ * express. While the user file cannot be read no row has a value at all.
208
+ *
209
+ * `userFile` says which: `read`, `absent` (Claude Code is on its defaults,
210
+ * and the first change makes the file), `invalid` or `unreadable`.
211
+ */
212
+ export async function readClaudeSettings({
213
+ home = homedir(), env = process.env, platform = process.platform,
214
+ readJson = readBoundedJson, list = readdir, versions = () => claudeCodeVersions({ home, env, platform }),
215
+ readLegacy = readLegacyValues,
216
+ } = {}) {
217
+ const paths = files({ home, env, platform });
218
+ const [user, organization, managedFile, dropIns, legacy] = await Promise.all([
219
+ readSource(paths.user, readJson), readSource(paths.organization, readJson), readSource(paths.managed, readJson),
220
+ readDropIns(paths.dropIns, platform === "win32" ? win32.join : posix.join, readJson, list),
221
+ readLegacy({ home, env, platform }),
222
+ ]);
223
+ // The administrator's files as one: the drop-ins merged over the main file,
224
+ // as Claude Code reads them, with every file's deny rules kept.
225
+ const managedParts = [managedFile, ...dropIns];
226
+ const managed = {
227
+ status: managedParts.find(unknown)?.status ?? (managedParts.some(p => p.status === "read") ? "read" : "absent"),
228
+ settings: Object.assign({}, ...managedParts.map(p => p.settings)),
229
+ };
230
+ const deny = managedParts.flatMap(p => Array.isArray(p.settings.permissions?.deny) ? p.settings.permissions.deny : []);
231
+ if (deny.length) managed.settings.permissions = { ...managed.settings.permissions, deny };
232
+ const found = versions();
233
+ const oldest = oldestClaudeVersion(found);
234
+ const tooOld = oldest !== null && !claudeVersionAtLeast(oldest, WRITABLE_SINCE);
235
+ const userUnknown = unknown(user);
236
+ const othersUnknown = unknown(organization) || unknown(managed);
237
+ const rulesManagedOnly = managed.settings.allowManagedPermissionRulesOnly === true;
238
+ const envSources = [
239
+ { where: "managed", env: managed.settings.env }, { where: "organization", env: organization.settings.env },
240
+ { where: "user", env: user.settings.env }, { where: "environment", env },
241
+ ];
242
+
243
+ const settings = CLAUDE_SETTINGS.map(entry => {
244
+ const lockedBy = decides(entry, managed.settings) ? "managed"
245
+ : decides(entry, organization.settings) ? "organization"
246
+ : entry.kind === "allowTool" && rulesManagedOnly ? "managed" : null;
247
+ const shown = lockedBy ? rowValue(entry, lockedBy === "managed" ? managed.settings : organization.settings) : rowValue(entry, user.settings, legacy);
248
+ const behind = entry.since && oldest !== null && !claudeVersionAtLeast(oldest, entry.since);
249
+ const unknownVersion = entry.since && oldest === null;
250
+ const reason = user.status === "invalid" ? "Your settings.json is not valid JSON, so Claude Code skips all of it, hooks included. Fix it in an editor; this section reads it again by itself."
251
+ : user.status === "unreadable" ? "Your settings.json could not be read here, so nothing is shown or changed until it can."
252
+ : othersUnknown ? "Your organization's settings could not be read, so nothing here can be changed until they can."
253
+ : lockedBy ? "Set by your organization. Ask your administrator to change it."
254
+ : tooOld ? `Needs Claude Code ${WRITABLE_SINCE} or newer.`
255
+ : behind ? `Needs Claude Code ${entry.since} or newer.`
256
+ : unknownVersion ? `Needs Claude Code ${entry.since} or newer, and the version installed here could not be read.`
257
+ : shown.custom ? "Your settings.json holds a custom value. Edit it there."
258
+ : null;
259
+ const override = userUnknown ? null : overrideFor(entry, envSources);
260
+ return {
261
+ id: entry.id, value: userUnknown ? null : shown.value, isSet: !lockedBy && decides(entry, user.settings),
262
+ ...(shown.custom && !userUnknown ? { custom: true } : {}), ...(lockedBy ? { lockedBy } : {}),
263
+ editable: reason === null, ...(reason ? { reason } : {}), ...(override ? { override } : {}),
264
+ };
265
+ });
266
+
267
+ let present = null;
268
+ if (user.status === "read" || user.status === "absent") {
269
+ present = {};
270
+ for (const [key, raw] of Object.entries(user.settings)) present[key] = safeDisplay(key, raw);
271
+ }
272
+
273
+ return {
274
+ ok: true,
275
+ claudeVersion: oldest,
276
+ file: paths.user,
277
+ fileShown: shownPath(paths.user, home, platform),
278
+ userFile: user.status,
279
+ sources: [
280
+ { name: "User settings", status: user.status },
281
+ { name: "Cached organization settings", status: organization.status },
282
+ { name: "Managed settings", status: managed.status },
283
+ ],
284
+ settings,
285
+ present,
286
+ };
287
+ }
288
+
289
+ /** Whether `value` is one this row can write, by its kind. */
290
+ function acceptable(entry, value) {
291
+ switch (entry.kind) {
292
+ case "switch": case "allowTool": case "attribution": return typeof value === "boolean";
293
+ case "choice": return entry.options.some(o => o.value === value);
294
+ case "days": return Number.isInteger(value) && value >= 1 && value <= 36_500;
295
+ default: return false;
296
+ }
297
+ }
298
+
299
+ /** The user settings with the row set to `value`, or a reason it cannot be.
300
+ * The value Claude Code uses when the key is absent removes the key — for a
301
+ * `legacy` row, the value ~/.claude.json would then give it. */
302
+ function applied(entry, value, current, legacy = {}) {
303
+ const settings = { ...current };
304
+ if (entry.kind === "allowTool") {
305
+ const permissions = settings.permissions;
306
+ if (permissions !== undefined && !isObject(permissions)) return { error: "Your settings.json has a permissions value that is not an object. No changes were saved." };
307
+ const deny = permissions?.deny;
308
+ if (deny !== undefined && !Array.isArray(deny)) return { error: "Your settings.json has a permissions.deny value that is not a list. No changes were saved." };
309
+ const list = deny ?? [];
310
+ if (value) {
311
+ if (!list.includes(entry.tool)) return { settings };
312
+ const kept = list.filter(rule => rule !== entry.tool);
313
+ const next = { ...permissions };
314
+ if (kept.length) next.deny = kept; else delete next.deny;
315
+ if (Object.keys(next).length) settings.permissions = next; else delete settings.permissions;
316
+ return { settings };
317
+ }
318
+ if (list.includes(entry.tool)) return { settings };
319
+ settings.permissions = { ...permissions, deny: [...list, entry.tool] };
320
+ return { settings };
321
+ }
322
+ if (entry.kind === "attribution") {
323
+ if (current.attribution !== undefined && current.attribution !== false) return { error: "Your settings.json holds a custom attribution. Edit it there." };
324
+ if (value) {
325
+ delete settings.attribution;
326
+ if (settings.includeCoAuthoredBy === false) delete settings.includeCoAuthoredBy;
327
+ } else if (current.attribution === undefined && current.includeCoAuthoredBy === false) {
328
+ // Already off, by the key that came before `attribution`.
329
+ } else {
330
+ settings.attribution = false;
331
+ }
332
+ return { settings };
333
+ }
334
+ if (entry.kind === "switch" || entry.kind === "days") {
335
+ const absent = entry.legacy && typeof legacy[entry.key] === "boolean" ? legacy[entry.key] : entry.unset;
336
+ if (value === absent) delete settings[entry.key]; else settings[entry.key] = value;
337
+ return { settings };
338
+ }
339
+ if (value === null) delete settings[entry.key]; else settings[entry.key] = value;
340
+ return { settings };
341
+ }
342
+
343
+ async function writePrivate(path, text) {
344
+ const { tmp, handle } = await createTemp(path, { mode: 0o600 });
345
+ try {
346
+ try { await handle.writeFile(text, "utf8"); await handle.sync(); }
347
+ finally { await handle.close(); }
348
+ await renameWithRetry(tmp, path);
349
+ } catch (error) {
350
+ await unlink(tmp).catch(() => {});
351
+ throw error;
352
+ }
353
+ }
354
+
355
+ class SettingsRefusal extends Error {}
356
+
357
+ // One write at a time, so two rows changed in quick succession both land.
358
+ let settingsWrite = Promise.resolve();
359
+
360
+ /**
361
+ * Set one row of the table in the user's settings.json.
362
+ *
363
+ * Read, change one key, write, through the same atomic write every settings
364
+ * writer in the deck uses (atomic-write.mjs), and only when the row is
365
+ * editable now — the check is made again here, not trusted from the page. The
366
+ * file as it was is kept in the deck's directory first. When the file changed
367
+ * on disk between the read and the write — Claude Code's own /config writes
368
+ * here too — the whole change is made again from the new file, once, rather
369
+ * than written over it.
370
+ */
371
+ export function updateClaudeSetting(id, value, options = {}) {
372
+ const write = settingsWrite.catch(() => {}).then(async () => {
373
+ const entry = typeof id === "string" ? claudeSettingById(id) : undefined;
374
+ if (!entry || !acceptable(entry, value)) throw new SettingsRefusal("Choose a setting this section offers and one of its values.");
375
+ const state = await readClaudeSettings(options);
376
+ const row = state.settings.find(r => r.id === entry.id);
377
+ if (!row.editable) throw new SettingsRefusal(row.reason);
378
+ const { home = homedir(), env = process.env, platform = process.platform, readLegacy = readLegacyValues } = options;
379
+ const paths = files({ home, env, platform });
380
+ const legacy = await readLegacy({ home, env, platform });
381
+ for (let attempt = 0; attempt < 2; attempt++) {
382
+ let read;
383
+ try { read = await readSettingsForWrite(paths.user); }
384
+ catch { throw new SettingsRefusal("Your settings.json could not be read as JSON. No changes were saved."); }
385
+ const next = applied(entry, value, read.settings, legacy);
386
+ if (next.error) throw new SettingsRefusal(next.error);
387
+ const text = JSON.stringify(next.settings, null, 2) + "\n";
388
+ if (JSON.stringify(next.settings) === JSON.stringify(read.settings)) return readClaudeSettings(options);
389
+ const again = await readSettingsForWrite(paths.user).catch(() => null);
390
+ if (!again || again.raw !== read.raw) continue;
391
+ if (read.raw !== null) {
392
+ const backupDir = deckDataDir(platform, env, home);
393
+ await mkdir(backupDir, { recursive: true });
394
+ await writePrivate((platform === "win32" ? win32.join : posix.join)(backupDir, SETTINGS_BACKUP), read.raw);
395
+ }
396
+ await mkdir(paths.dir, { recursive: true });
397
+ await writeFileAtomic(paths.user, text);
398
+ return readClaudeSettings(options);
399
+ }
400
+ throw new SettingsRefusal("Your settings.json changed while saving. Nothing was written. Try again.");
401
+ });
402
+ settingsWrite = write;
403
+ return write;
404
+ }
405
+
406
+ export { SettingsRefusal };
@@ -0,0 +1,64 @@
1
+ // A CLI installed after the deck started, noticed by the deck.
2
+ //
3
+ // Whether this deck serves Claude Code and Codex is decided once, at boot
4
+ // (wantsCli in bin/deck.js), and everything hangs off that answer: the hooks in
5
+ // Claude Code's settings.json, claude-swap, the ccusage prime, the Codex rollout
6
+ // watcher. A first run is the boot where that answer is most likely to change a
7
+ // few minutes later — the desktop app is installed and opened, and only then
8
+ // does its user install Claude Code. Reproduced on a clean Windows VM: the deck
9
+ // said "Waiting for Claude Code or Codex", no hook was installed, and the
10
+ // sessions the user went on to start never appeared, until the app was quit and
11
+ // opened again, which nothing told them to do.
12
+ //
13
+ // So while a CLI is neither served nor switched off, the boot's own question is
14
+ // asked again on a slow timer, and the first yes restarts the deck through its
15
+ // supervisor. The respawn asks wantsCli afresh and comes back serving the CLI;
16
+ // bin/deck.js runs the Claude setup it then owes (claudeArrived there). The
17
+ // checks are the boot's own, hasClaudeInstalled and hasCodexInstalled: a
18
+ // handful of stats, which is nothing at this cadence.
19
+
20
+ /** How often to look. A user who has just installed Claude Code takes longer
21
+ * than this to open a terminal and start it. */
22
+ export const CLI_POLL_MS = 15_000;
23
+
24
+ /** The interval, as the environment may override it — for tests, which
25
+ * should not wait fifteen real seconds to see a restart. Anything unparseable
26
+ * or below a tenth of a second is the default. */
27
+ export function cliPollMs(env = process.env) {
28
+ const n = Number(env.AGENTS_DECK_CLI_POLL_MS);
29
+ return Number.isFinite(n) && n >= 100 ? n : CLI_POLL_MS;
30
+ }
31
+
32
+ /**
33
+ * Watch for a CLI the boot did not find, and call `onArrive(name)` once, for
34
+ * the first one that appears. Answers a function that stops the watch.
35
+ *
36
+ * `clis` is `{ name, want, off, installed }` per CLI: `want` is the boot's
37
+ * answer, `off` is `--no-claude` / `--no-codex` (the user telling the deck to
38
+ * leave that CLI alone, which still holds for one installed afterwards), and
39
+ * `installed` is the boot's presence check. A CLI already served or switched
40
+ * off is not watched, and with nothing to watch no timer is started at all.
41
+ *
42
+ * The timer is unref'd: it must never be the thing keeping a deck alive.
43
+ * A presence check that throws is a no for this beat, not the end of the watch.
44
+ */
45
+ export function watchForClis({ clis, onArrive, everyMs = cliPollMs(), timers = globalThis }) {
46
+ const awaited = clis.filter(c => !c.want && !c.off);
47
+ if (!awaited.length) return () => {};
48
+ let stopped = false;
49
+ const timer = timers.setInterval(() => {
50
+ if (stopped) return;
51
+ const found = awaited.find(c => {
52
+ try { return Boolean(c.installed()); } catch { return false; }
53
+ });
54
+ if (!found) return;
55
+ stop();
56
+ onArrive(found.name);
57
+ }, everyMs);
58
+ timer?.unref?.();
59
+ function stop() {
60
+ stopped = true;
61
+ timers.clearInterval(timer);
62
+ }
63
+ return stop;
64
+ }
@@ -23,6 +23,7 @@ import { OPEN_MUTATIONS, isAuthorizedDataRead, isAuthorizedMutation, isGuardedRe
23
23
  import { trafficCapture } from "./traffic-radar-capture.mjs";
24
24
  import { trafficRadar } from "./traffic-radar.mjs";
25
25
  import { handleTrafficCapture, isAuthorizedTrafficIngest } from "./traffic-radar-routes.mjs";
26
+ import { CLAUDE_SETTINGS_ROUTE, handleClaudeSettings } from "./claude-settings-routes.mjs";
26
27
  // How much the event ring may hold and what one event is charged against it —
27
28
  // see ring-bounds.mjs. The four it exported from this file, it still exports.
28
29
  export { MAX_BUFFER, MAX_BUFFER_CHARS, MAX_RING_ENTRIES, payloadChars } from "./ring-bounds.mjs";
@@ -172,7 +173,9 @@ import { handleBestOfNostalgia, handleCafeMusicBgm, handleClaudeFm, handleFmStat
172
173
  import { startToolAudit } from "./tool-audit.mjs";
173
174
  import { handleToolAudit } from "./tool-audit-routes.mjs";
174
175
  import { startQuotaHistory } from "./quota-history.mjs";
175
- import { handleCcusage, handleCcusageSession, handleCodexQuota, handleCodexUsage, handleProviderStatus, handleQuota, handleQuotaHistory } from "./usage-routes.mjs";
176
+ import { startQuotaCloses } from "./quota-closes.mjs";
177
+ import { startQuotaCloseWatch } from "./quota-close-watch.mjs";
178
+ import { handleCcusage, handleCcusageSession, handleCodexQuota, handleCodexUsage, handleProviderStatus, handleQuota, handleQuotaCloses, handleQuotaHistory } from "./usage-routes.mjs";
176
179
  // Connected trackers (#2178) and each provider's own reads. See
177
180
  // integrations/routes.mjs; nothing in it is shared with paired decks.
178
181
  import { handleIntegrations } from "./integrations/routes.mjs";
@@ -202,6 +205,7 @@ export function requestUrl(rawUrl) {
202
205
 
203
206
  export async function startServer({ port = 4317, host = "127.0.0.1", persist = null, portRange = [4318, 4400], workspace = "", codex = true, claude = true, onRestart = null, onStop = null, cswapQuiet = null } = {}) {
204
207
  startQuotaHistory();
208
+ startQuotaCloses();
205
209
  await startToolAudit();
206
210
  armLifecycle({ onRestart, onStop, persist, onSelfUpdate: () => reporter.noteSelfUpdate() });
207
211
  // Which tree and which CLIs, normalised once — see setDeckScope.
@@ -331,6 +335,7 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
331
335
  if (req.method === "POST" && url.pathname === "/api/shutdown") return guard(handleStop(req, res), res);
332
336
  if (["GET", "POST"].includes(req.method) && ["/api/tool-audit", "/api/tool-audit/storage"].includes(url.pathname)) return guard(handleToolAudit(req, res), res);
333
337
  if (req.method === "GET" && url.pathname === "/api/quota/history") return guard(handleQuotaHistory(req, res), res);
338
+ if (req.method === "GET" && url.pathname === "/api/quota/closes") return guard(handleQuotaCloses(req, res), res);
334
339
  if (req.method === "GET" && url.pathname === "/api/quota") return guard(handleQuota(req, res), res);
335
340
  if (req.method === "GET" && url.pathname === "/api/codex-usage") return guard(handleCodexUsage(req, res), res);
336
341
  // Machine state, not session state: sampled on the server's own timer and
@@ -353,6 +358,9 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
353
358
  return guard(trafficRadar.read().then(snapshot => send(res, 200, snapshot)), res);
354
359
  }
355
360
  if (url.pathname.startsWith("/api/system/traffic-radar/")) return guard(handleTrafficCapture(req, res, url), res);
361
+ // Settings › Claude Code: the short list of Claude Code settings, and the
362
+ // press that changes one in the user's settings.json. See claude-settings.mjs.
363
+ if (url.pathname === CLAUDE_SETTINGS_ROUTE) return guard(handleClaudeSettings(req, res), res);
356
364
  // On demand only — the process list costs a subprocess on every platform,
357
365
  // so it is fetched while the detail panel is open and never on the timer.
358
366
  if (req.method === "GET" && url.pathname === "/api/system/processes") {
@@ -528,7 +536,12 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
528
536
  // and that will differ on the next boot. Every test in this suite boots
529
537
  // that way. Comparing the candidate would hand those decks a manifest.
530
538
  boundPort = server.address()?.port ?? candidate;
531
- void trafficCapture.resume(boundPort).catch(() => {});
539
+ // Radar monitors by itself, always (traffic-radar-service.mjs), which
540
+ // means looking at the machine's Claude processes and capturing their
541
+ // collector. AGENTS_DECK_NO_RADAR=1 keeps a deck from doing either: the
542
+ // test suite sets it, so a developer's own telemetry is never captured by
543
+ // a test's deck.
544
+ if (process.env.AGENTS_DECK_NO_RADAR !== "1") void trafficCapture.resume(boundPort).catch(() => {});
532
545
  server.once("close", () => trafficCapture.dispose());
533
546
  // Codex has no working hooks on Windows — tail its rollout files instead.
534
547
  if (codex) {
@@ -570,6 +583,9 @@ export async function startServer({ port = 4317, host = "127.0.0.1", persist = n
570
583
  // watches. Idle — a check of two switches every couple of minutes — unless
571
584
  // the threshold or the reset notification is on.
572
585
  startAccountWatch({ providers: deckProviders });
586
+ // How full each quota window was at its reset: claude-swap's store read
587
+ // every few minutes, and one fresh reading before each weekly reset.
588
+ startQuotaCloseWatch({ providers: deckProviders });
573
589
  // The account-projects rollup: fold Claude transcripts into a per-account,
574
590
  // per-project token tally, incrementally. Claude only — it reads Claude
575
591
  // transcripts — best effort, and its timer is unref'd so it never holds
@@ -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 };