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
@@ -1,8 +1,9 @@
1
1
  // OS-specific inspection stays here; the Radar history and decoder share one model.
2
2
  import { execFile } from 'node:child_process';
3
- import { readdir, readFile, readlink } from 'node:fs/promises';
3
+ import { open, readdir, readlink } from 'node:fs/promises';
4
4
  import { existsSync } from 'node:fs';
5
5
  import { win32 } from 'node:path';
6
+ import { environVariables } from './traffic-radar-config.mjs';
6
7
 
7
8
  export function systemCommand(file, args) {
8
9
  return new Promise(resolve => execFile(file, args, { timeout: 8000, maxBuffer: 262144, encoding: 'utf8', windowsHide: true }, (error, stdout, stderr) => {
@@ -16,32 +17,98 @@ export function windowsSockets(pids) {
16
17
  return `$ids=@(${pids.join(',')}); Get-NetTCPConnection -ErrorAction Stop | Where-Object { $_.State -eq 'Established' -and $_.OwningProcess -in $ids } | ForEach-Object { $peer=$_.RemoteAddress; if($peer.Contains(':')){$peer='['+$peer+']'}; 'p'+$_.OwningProcess; 'nlocal->'+$peer+':'+$_.RemotePort }`;
17
18
  }
18
19
 
19
- // /proc avoids an ss/lsof dependency and reads socket ownership only for selected Claude PIDs.
20
- export async function linuxSockets(pids, { read = readFile, list = readdir, link = readlink } = {}) {
21
- const sockets = [], cwd = [];
22
- let unavailable = false;
20
+ // The native installer runs ~/.local/share/claude/versions/<version>. Started by
21
+ // that path rather than the `claude` link, a process's comm is its version, so
22
+ // only those candidates have their executable read: no full /proc scan, no argv.
23
+ export async function linuxVersionedClaude(text, { link = readlink } = {}) {
24
+ const candidates = [];
25
+ for (const line of String(text ?? '').split('\n')) {
26
+ const match = /^\s*(\d+)\s+\d+\.\d+\.\d+\s*$/.exec(line);
27
+ if (match) candidates.push(Number(match[1]));
28
+ }
29
+ const confirmed = await Promise.all(candidates.slice(0, 256).map(async pid =>
30
+ /\/claude\/versions\/\d+\.\d+\.\d+(?: \(deleted\))?$/.test(await link(`/proc/${pid}/exe`).catch(() => '')) ? pid : null));
31
+ return confirmed.filter(pid => pid !== null);
32
+ }
33
+
34
+ // /proc files report size 0 and answer a page per read. Node 18's
35
+ // fs.promises.readFile stops after that first page, which cut a busy machine's
36
+ // socket table to its first ~27 rows, so /proc is read to EOF within a bound.
37
+ export async function readProc(path, max, openFile = open) {
38
+ const file = await openFile(path, 'r');
39
+ try {
40
+ const chunks = [];
41
+ const chunk = Buffer.alloc(65_536);
42
+ let size = 0;
43
+ for (;;) {
44
+ const { bytesRead } = await file.read(chunk, 0, chunk.length, null);
45
+ if (!bytesRead) return Buffer.concat(chunks, size);
46
+ size += bytesRead;
47
+ if (size > max) return null;
48
+ chunks.push(Buffer.from(chunk.subarray(0, bytesRead)));
49
+ }
50
+ } finally { await file.close(); }
51
+ }
52
+ export const readEnviron = path => readProc(path, 262_144);
53
+ async function readTable(path) {
54
+ const table = await readProc(path, 67_108_864);
55
+ if (!table) throw Object.assign(new Error('Socket table too large.'), { code: 'EFBIG' });
56
+ return table.toString('utf8');
57
+ }
58
+
59
+ // /proc avoids an ss/lsof dependency and reads socket ownership, cwd and the
60
+ // launch environment only for selected Claude PIDs. Established sockets and
61
+ // attempts still awaiting a reply (SYN-SENT, as lsof's TST field) are kept. A
62
+ // process this user may not inspect, such as another user's Claude, is counted
63
+ // instead of hiding every other process; with none readable the sample is unavailable.
64
+ export async function linuxSockets(pids, { read = readTable, list = readdir, link = readlink, readEnv = readEnviron } = {}) {
65
+ const sockets = [], cwd = [], launch = [];
66
+ let unavailable = false, inspected = 0, denied = 0;
67
+ // A namespace's table lists every socket on the machine (thousands of rows on
68
+ // a busy desktop) and Claude processes usually share one, so each table is
69
+ // parsed once per sample into peers by socket inode. A failed shared read is
70
+ // retried through the next process rather than reused.
71
+ const tables = new Map();
72
+ const peers = async (pid, family, ns) => {
73
+ const key = ns && `${ns}|${family}`;
74
+ if (key && tables.has(key)) { try { return await tables.get(key); } catch {} }
75
+ const parsed = read(`/proc/${pid}/net/${family}`, 'utf8').then(table => {
76
+ const byInode = new Map();
77
+ for (const row of table.trim().split('\n').slice(1)) {
78
+ const fields = row.trim().split(/\s+/);
79
+ if (!['01', '02'].includes(fields[3])) continue;
80
+ const [hex, port] = fields[2].split(':');
81
+ const bytes = Buffer.from(hex, 'hex');
82
+ for (let i = 0; i < bytes.length; i += 4) bytes.subarray(i, i + 4).reverse();
83
+ const address = family === 'tcp' ? [...bytes].join('.') : '[' + Array.from({ length: 8 }, (_, i) => bytes.readUInt16BE(i * 2).toString(16)).join(':') + ']';
84
+ byInode.set(fields[9], `${address}:${parseInt(port, 16)}${fields[3] === '02' ? '\nTST=SYN_SENT' : ''}`);
85
+ }
86
+ return byInode;
87
+ });
88
+ if (key) tables.set(key, parsed);
89
+ return parsed;
90
+ };
23
91
  await Promise.all(pids.map(async pid => {
24
92
  try {
25
93
  const descriptors = await list(`/proc/${pid}/fd`);
26
94
  const owned = new Set((await Promise.all(descriptors.map(fd => link(`/proc/${pid}/fd/${fd}`).catch(() => ''))))
27
95
  .map(value => /^socket:\[(\d+)\]$/.exec(value)?.[1]).filter(Boolean));
96
+ const ns = await link(`/proc/${pid}/ns/net`).then(value => /^net:\[\d+\]$/.test(value) ? value : null, () => null);
28
97
  for (const family of ['tcp', 'tcp6']) {
29
- const table = await read(`/proc/${pid}/net/${family}`, 'utf8');
30
- for (const row of table.trim().split('\n').slice(1)) {
31
- const fields = row.trim().split(/\s+/);
32
- if (fields[3] !== '01' || !owned.has(fields[9])) continue;
33
- const [hex, port] = fields[2].split(':');
34
- const bytes = Buffer.from(hex, 'hex');
35
- for (let i = 0; i < bytes.length; i += 4) bytes.subarray(i, i + 4).reverse();
36
- const address = family === 'tcp' ? [...bytes].join('.') : '[' + Array.from({ length: 8 }, (_, i) => bytes.readUInt16BE(i * 2).toString(16)).join(':') + ']';
37
- sockets.push(`p${pid}\nnlocal->${address}:${parseInt(port, 16)}`);
38
- }
98
+ const byInode = await peers(pid, family, ns);
99
+ for (const inode of owned) if (byInode.has(inode)) sockets.push(`p${pid}\nnlocal->${byInode.get(inode)}`);
39
100
  }
40
101
  const path = await link(`/proc/${pid}/cwd`).catch(() => null);
41
102
  if (path) cwd.push(`p${pid}\nn${path}`);
42
- } catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ESRCH') unavailable = true; }
103
+ const environ = await readEnv(`/proc/${pid}/environ`).catch(() => null);
104
+ if (environ) launch.push({ pid, variables: environVariables(environ) });
105
+ inspected++;
106
+ } catch (error) {
107
+ if (error.code === 'EACCES' || error.code === 'EPERM') denied++;
108
+ else if (error.code !== 'ENOENT' && error.code !== 'ESRCH') unavailable = true;
109
+ }
43
110
  }));
44
- return { sockets: unavailable ? null : sockets.join('\n'), cwd: cwd.join('\n') };
111
+ return { sockets: unavailable || (denied && !inspected) ? null : sockets.join('\n'), cwd: cwd.join('\n'), denied, launch };
45
112
  }
46
113
  export function captureInterfaceValid(name, platform) {
47
114
  return typeof name === 'string' && (platform === 'win32'
@@ -70,10 +137,16 @@ export function dumpcapPath(env = process.env, exists = existsSync) {
70
137
  return 'dumpcap.exe'; // Custom installs may expose it on PATH.
71
138
  }
72
139
  export class CaptureSetupError extends Error {}
140
+ // Linux keeps tcpdump in /usr/sbin on some distributions (openSUSE, Fedora
141
+ // before 42), which a user's PATH, or a desktop app's, may leave out.
142
+ const LINUX_TCPDUMP = ['tcpdump', '/usr/sbin/tcpdump', '/usr/bin/tcpdump', '/sbin/tcpdump'];
73
143
  export async function captureTool(platform, run = systemCommand) {
74
- const file = platform === 'win32' ? dumpcapPath() : platform === 'darwin' ? '/usr/sbin/tcpdump' : 'tcpdump';
75
- if (await run(file, [platform === 'win32' ? '-v' : '--version']) === null)
76
- throw new CaptureSetupError(platform === 'win32' ? 'Install Wireshark with Npcap to capture traffic, then retry. Configuration and file inspection work without it.' : 'Install tcpdump to capture traffic, then retry. Configuration and file inspection work without it.');
144
+ const version = platform === 'win32' ? '-v' : '--version';
145
+ const tried = platform === 'win32' ? [dumpcapPath()] : platform === 'darwin' ? ['/usr/sbin/tcpdump'] : LINUX_TCPDUMP;
146
+ let file = null;
147
+ for (const candidate of tried) if (await run(candidate, [version]) !== null) { file = candidate; break; }
148
+ if (file === null)
149
+ throw new CaptureSetupError(platform === 'win32' ? 'Install Wireshark with Npcap to capture traffic. Configuration and file inspection work without it.' : 'Install tcpdump to capture traffic. Configuration and file inspection work without it.');
77
150
  if (platform === 'win32' && await run(file, ['-D']) === null)
78
151
  throw new CaptureSetupError('Npcap interfaces are unavailable. Check that Npcap is installed and its capture permissions allow this user.');
79
152
  return file;
@@ -1,5 +1,6 @@
1
1
  import { trafficCapture } from "./traffic-radar-capture.mjs";
2
2
  import { CaptureSetupError } from './traffic-radar-platform.mjs';
3
+ import { askCapturePermission } from './traffic-radar-permission.mjs';
3
4
  import { updateRadarFlag } from './traffic-radar-config.mjs';
4
5
  import { trafficRadar } from './traffic-radar.mjs';
5
6
  const BASE = '/api/system/traffic-radar';
@@ -17,7 +18,7 @@ async function body(req, max) {
17
18
  for await (const chunk of req) { size += chunk.length; if (size > max) throw new Error('Request too large.'); chunks.push(chunk); }
18
19
  return Buffer.concat(chunks);
19
20
  }
20
- export async function handleTrafficCapture(req, res, url, capture = trafficCapture) {
21
+ export async function handleTrafficCapture(req, res, url, capture = trafficCapture, permission = askCapturePermission) {
21
22
  if (!loopback(req)) return reply(res, 403, { error: 'Telemetry contents are available on this machine only.' });
22
23
  const action = url.pathname.slice(BASE.length);
23
24
  try {
@@ -32,19 +33,6 @@ export async function handleTrafficCapture(req, res, url, capture = trafficCaptu
32
33
  }
33
34
  catch (error) { return reply(res, 400, { error: error.message }); }
34
35
  }
35
- // Settings › Radar: `enabled` is automatic monitoring, off unless switched on.
36
- if (req.method === 'GET' && action === '/settings') return reply(res, 200, await capture.settings());
37
- if (req.method === 'POST' && action === '/settings') {
38
- let data;
39
- try { data = JSON.parse((await body(req, 4096)).toString()); } catch { return reply(res, 400, { error: 'Invalid Radar settings.' }); }
40
- // One field, a boolean, and nothing else: a body that names anything more
41
- // is not this switch's and is refused whole, not half-applied.
42
- if (!data || typeof data !== 'object' || Array.isArray(data) || Object.keys(data).join() !== 'enabled')
43
- return reply(res, 400, { error: 'Invalid Radar settings.' });
44
- if (typeof data.enabled !== 'boolean') return reply(res, 400, { error: 'Radar enabled must be a boolean.' });
45
- try { return reply(res, 200, await capture.setEnabled(data.enabled)); }
46
- catch { return reply(res, 500, { error: 'Could not save Radar settings. Try again.' }); }
47
- }
48
36
  if (req.method === 'GET' && action === '/capture') return reply(res, 200, capture.read());
49
37
  if (req.method === 'GET' && action === '/capture/event') {
50
38
  const detail = capture.detail(Number(url.searchParams.get('id')));
@@ -56,11 +44,13 @@ export async function handleTrafficCapture(req, res, url, capture = trafficCaptu
56
44
  const data = await body(req, 262_144);
57
45
  return reply(res, capture.ingest(token, data, Number(req.headers['x-radar-source'] ?? 0)) ? 200 : 409, { ok: capture.read().state === 'capturing' });
58
46
  }
59
- if (req.method === 'POST' && action === '/capture/prepare') {
60
- const data = JSON.parse((await body(req, 4096)).toString());
61
- return reply(res, 200, await capture.prepare(data.destination, req.socket.localPort));
47
+ // Allow capture: the system's own password prompt, once. Granted, capture
48
+ // starts again now rather than at its next retry.
49
+ if (req.method === 'POST' && action === '/capture/permission') {
50
+ const result = await permission();
51
+ if (result.outcome === 'granted') await capture.retry?.();
52
+ return reply(res, 200, { ok: true, ...result });
62
53
  }
63
- if (req.method === 'POST' && action === '/capture/stop') { await capture.stop(); return reply(res, 200, { ok: true }); }
64
54
  if (req.method === 'POST' && action === '/capture/clear') { capture.clear(); return reply(res, 200, { ok: true }); }
65
55
  return reply(res, 404, { error: 'Unknown capture action.' });
66
56
  } catch (error) { return reply(res, 400, { error: error instanceof CaptureSetupError ? error.message : 'Could not complete capture setup. Use a valid IPv4 destination and check its network route.' }); }
@@ -1,133 +1,120 @@
1
1
  import { CaptureSetupError } from './traffic-radar-platform.mjs';
2
2
  import { isIP } from 'node:net';
3
+ import { lookup } from 'node:dns/promises';
3
4
 
4
5
  export function radarTargets(snapshot) {
5
- const configured = (snapshot?.config?.variables ?? []).filter(v => v.key.endsWith('ENDPOINT')).flatMap(({ value }) => {
6
- try {
7
- const url = new URL(value);
8
- return ['http:', 'https:'].includes(url.protocol) && isIP(url.hostname) === 4
9
- ? [`${url.hostname}:${url.port || (url.protocol === 'https:' ? 443 : 80)}`] : [];
10
- } catch { return []; }
11
- });
12
- // An arbitrary Claude HTTPS connection is not evidence of a collector.
13
- const observed = (snapshot?.connections ?? []).filter(c => c.active === true && /:4317$/.test(c.destination) && isIP(c.destination.slice(0, c.destination.lastIndexOf(':'))) === 4).map(c => c.destination);
14
- return { configured: [...new Set(configured)], observed: [...new Set(observed)] };
6
+ // A running Claude's launch environment names a collector as settings do.
7
+ const variables = [...(snapshot?.config?.variables ?? []), ...(snapshot?.environment ?? [])];
8
+ const configured = [], named = [];
9
+ for (const { key, value } of variables) {
10
+ if (!key.endsWith('ENDPOINT')) continue;
11
+ let url;
12
+ try { url = new URL(value); } catch { continue; }
13
+ if (!['http:', 'https:'].includes(url.protocol)) continue;
14
+ const port = url.port || (url.protocol === 'https:' ? 443 : 80);
15
+ if (isIP(url.hostname) === 4) configured.push(`${url.hostname}:${port}`);
16
+ // A name is looked up before capture (resolveCollector); an IPv6 literal,
17
+ // which URL keeps in brackets, is neither.
18
+ else if (url.hostname && !url.hostname.startsWith('[')) named.push(`${url.hostname}:${port}`);
19
+ }
20
+ // An arbitrary Claude HTTPS connection is not evidence of a collector, nor an
21
+ // attempt nothing has answered.
22
+ const observed = (snapshot?.connections ?? []).filter(c => c.active === true && !c.connecting && /:4317$/.test(c.destination) && isIP(c.destination.slice(0, c.destination.lastIndexOf(':'))) === 4).map(c => c.destination);
23
+ return { configured: [...new Set(configured)], named: [...new Set(named)], observed: [...new Set(observed)] };
24
+ }
25
+
26
+ /** A collector named by host, such as otel.example.com:4317, as the IPv4
27
+ * address Claude reaches it at. Capture filters on an address, and with no
28
+ * destination picker any more a name is the only way such a collector is
29
+ * found. A lookup that fails or hangs past `ms` names nothing. */
30
+ export async function resolveCollector(target, find = lookup, ms = 2000) {
31
+ const at = target.lastIndexOf(':');
32
+ let timer;
33
+ const late = new Promise(resolve => { timer = setTimeout(resolve, ms, null); timer.unref?.(); });
34
+ try {
35
+ const found = await Promise.race([find(target.slice(0, at), { family: 4 }).catch(() => null), late]);
36
+ return found && isIP(found.address) === 4 ? `${found.address}:${target.slice(at + 1)}` : null;
37
+ } finally { clearTimeout(timer); }
15
38
  }
16
39
 
17
40
  const savedDestinations = value => Array.isArray(value)
18
41
  ? value.filter(v => typeof v === 'string' && /^\d+\.\d+\.\d+\.\d+:\d+$/.test(v)).slice(0, 8) : [];
19
42
 
20
- /** Own the automatic-monitoring preference independently of whether capture is ready yet.
43
+ /** Radar monitors by itself, always: there is no switch and no Start (the
44
+ * owner, 2026-10-23, reversing v3.44.0's opt-in). The service finds Claude
45
+ * Code's collector — configured endpoints first, named ones looked up, then the
46
+ * collectors it remembers and active OTLP/gRPC connections on port 4317 — and
47
+ * keeps capture on it, retrying while none is found or capture is not ready.
21
48
  *
22
- * AUTOMATIC MONITORING IS OPT-IN. `enabled` here is Settings › Radar's switch,
23
- * kept in its own file (`preferences`, radar-settings-<port>.json) and on only
24
- * where that file says `automatic: true`. A fresh deck, and a deck upgraded
25
- * from a release that never wrote the file, has it off: nothing is discovered,
26
- * nothing is retried, and the capture behaves exactly as it did before, with
27
- * the person choosing a destination and starting it in Radar's Monitor view
28
- * (`capture.prepare`/`capture.stop`, which keep their own radar-monitor-<port>
29
- * .json opt-in and resume a monitor the person started, as they always did).
30
- * Only while the switch is on does the service find the collector itself and
31
- * retry every `pollMs`. */
32
- export function createRadarService({ capture, preferences, discover, pollMs = 5000 }) {
33
- let enabled = false, port = null, remembered = [], revision = 0, timer = null, disposed = false;
34
- let ready = Promise.resolve(), syncing = null, setupError = null;
35
- const settings = () => ({ ok: true, enabled, setupError });
36
- const save = () => preferences.write(port, { automatic: enabled, destinations: remembered });
37
- const stopLoop = () => { clearInterval(timer); timer = null; };
38
- const startLoop = () => {
39
- stopLoop();
40
- if (enabled && !disposed) { timer = setInterval(() => void sync(), pollMs); timer.unref?.(); }
41
- };
49
+ * Discovery samples Claude's processes (ps and lsof, /proc, or PowerShell), so
50
+ * every deck pays for it: it runs every `pollMs` only while Radar is open,
51
+ * which the page shows by reading the capture, and every `idleMs` otherwise.
52
+ * `radar-settings-<port>.json` keeps the collectors found, so a restart goes
53
+ * back to them; a monitor started by hand in an earlier release resumes too,
54
+ * and is where discovery looks first when no setting names a collector. */
55
+ export function createRadarService({ capture, preferences, discover, resolve = resolveCollector, pollMs = 5000, idleMs = 60000, openMs = 15000, now = Date.now }) {
56
+ let port = null, remembered = [], timer = null, disposed = false;
57
+ let syncing = null, setupError = null, syncedAt = -Infinity, readAt = -Infinity;
58
+ const save = () => preferences.write(port, { destinations: remembered });
42
59
  async function sync() {
43
- if (!enabled || disposed || !port) return;
60
+ if (disposed || !port) return;
44
61
  if (syncing) return syncing;
45
- const operation = revision;
62
+ syncedAt = now();
46
63
  syncing = (async () => {
47
64
  try {
48
- const { configured, observed } = radarTargets(await discover());
49
- if (operation !== revision || !enabled || disposed) return;
50
- const targets = [...new Set(configured.length ? configured : [...remembered, ...observed])].sort().slice(0, 8);
65
+ const { configured, named, observed } = radarTargets(await discover());
66
+ const looked = (await Promise.all(named.map(target => resolve(target)))).filter(Boolean);
67
+ if (disposed) return;
68
+ const settings = [...configured, ...looked];
69
+ const targets = [...new Set(settings.length ? settings : [...remembered, ...observed])].sort().slice(0, 8);
51
70
  if (!targets.length) { setupError = null; return; }
52
71
  const current = capture.read();
53
72
  const existing = (current.sources ?? []).map(s => s.destination).sort();
54
73
  if (current.enabled && JSON.stringify(existing) === JSON.stringify(targets)) { setupError = null; return; }
55
74
  await capture.prepare(targets, port);
56
- // Stopped with its opt-in saved off: a setup that lands after the switch
57
- // went off must not leave a monitor that resumes after a restart.
58
- if (operation !== revision || !enabled || disposed) { await capture.stop('stopped', !disposed); return; }
75
+ // A setup that lands after the deck shut the service down must not
76
+ // leave a monitor running, or one that resumes after a restart.
77
+ if (disposed) { await capture.stop('stopped', false); return; }
59
78
  remembered = targets;
60
79
  setupError = null;
61
80
  await save();
62
81
  } catch (error) {
63
- if (operation === revision && enabled && !disposed) setupError = error instanceof CaptureSetupError ? error.message : 'Monitoring setup failed. Retrying automatically.';
82
+ if (!disposed) setupError = error instanceof CaptureSetupError ? error.message : 'Monitoring setup failed. Retrying automatically.';
64
83
  }
65
84
  })().finally(() => { syncing = null; });
66
85
  return syncing;
67
86
  }
87
+ const tick = () => { if (now() - readAt < openMs || now() - syncedAt >= idleMs) void sync(); };
68
88
  return {
69
89
  ...capture,
70
- resume(requestedPort) {
90
+ async resume(requestedPort) {
71
91
  port = requestedPort;
72
- const operation = ++revision;
73
- ready = (async () => {
74
- const saved = await preferences.read(port);
75
- if (operation !== revision || disposed) return;
76
- enabled = saved?.automatic === true;
77
- remembered = savedDestinations(saved?.destinations);
78
- if (enabled) startLoop();
79
- // Off: the capture's own opt-in, as before — a monitor resumes only
80
- // where the person started one and did not stop it.
81
- else await capture.resume(port);
82
- })();
83
- return ready.then(sync);
84
- },
85
- async settings() { await ready; return settings(); },
86
- async setEnabled(next) {
87
- if (typeof next !== 'boolean') throw new Error('Radar enabled must be a boolean.');
88
- await ready;
89
- if (!port || disposed) throw new Error('Radar is not ready.');
90
- const previous = enabled, operation = ++revision;
91
- enabled = next;
92
- stopLoop();
93
- if (next) {
94
- // A monitor the person started by hand is where automatic monitoring
95
- // looks first when Claude's settings name no collector.
96
- const running = (capture.read().sources ?? []).map(s => s.destination);
97
- if (running.length) remembered = savedDestinations(running);
98
- } else { setupError = null; await capture.stop(); }
99
- try { await save(); }
100
- catch (error) {
101
- if (operation === revision) { enabled = previous; startLoop(); if (enabled) void sync(); }
102
- throw error;
103
- }
104
- if (operation === revision && enabled) {
105
- startLoop();
106
- // A slow older setup must finish/cancel before starting a new one.
107
- if (syncing) void syncing.then(sync); else void sync();
108
- }
109
- return settings();
92
+ const saved = await preferences.read(port);
93
+ if (disposed) return;
94
+ remembered = savedDestinations(saved?.destinations);
95
+ await capture.resume(port);
96
+ if (disposed) return;
97
+ if (!remembered.length) remembered = savedDestinations((capture.read().sources ?? []).map(s => s.destination));
98
+ clearInterval(timer);
99
+ timer = setInterval(tick, pollMs); timer.unref?.();
100
+ return sync();
110
101
  },
111
- async prepare(destination, requestedPort) {
112
- await ready;
113
- // Off: the Monitor view's own Start, unchanged.
114
- if (!enabled) return capture.prepare(destination, requestedPort);
115
- const operation = ++revision;
116
- const result = await capture.prepare(destination, requestedPort);
117
- if (operation !== revision || !enabled || disposed) { await capture.stop('stopped', !disposed); throw new Error('Radar setup was cancelled.'); }
118
- remembered = Array.isArray(destination) ? destination : [destination];
119
- await save();
120
- return result;
102
+ /** Start capture again now: permission was just granted (traffic-radar-permission.mjs). */
103
+ async retry() {
104
+ setupError = null;
105
+ const running = (capture.read().sources ?? []).map(s => s.destination);
106
+ if (!running.length || disposed || !port) return sync();
107
+ try { await capture.prepare(running, port); }
108
+ catch (error) { setupError = error instanceof CaptureSetupError ? error.message : 'Monitoring setup failed. Retrying automatically.'; }
121
109
  },
122
- // Off, Stop monitoring is the Monitor view's, as before; on, stopping is
123
- // turning automatic monitoring off.
124
- stop(...args) { return enabled ? this.setEnabled(false) : capture.stop(...args); },
125
110
  read() {
111
+ // Radar is open: look now rather than waiting out the idle interval.
112
+ readAt = now();
113
+ if (now() - syncedAt >= pollMs) void sync();
126
114
  const value = capture.read();
127
- if (!enabled) return { ...value, automatic: false };
128
115
  return { ...value, automatic: true, featureEnabled: true, setupError,
129
116
  state: setupError && !value.enabled ? 'error' : value.state };
130
117
  },
131
- dispose() { disposed = true; revision++; stopLoop(); capture.dispose(); },
118
+ dispose() { disposed = true; clearInterval(timer); timer = null; capture.dispose(); },
132
119
  };
133
120
  }
@@ -1,7 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { homedir } from "node:os";
3
- import { systemCommand, powershell, WINDOWS_PROCESSES, windowsSockets, linuxSockets } from './traffic-radar-platform.mjs';
4
- import { readRadarConfig } from "./traffic-radar-config.mjs";
3
+ import { systemCommand, powershell, WINDOWS_PROCESSES, windowsSockets, linuxSockets, linuxVersionedClaude } from './traffic-radar-platform.mjs';
4
+ import { launchVariables, readRadarConfig } from "./traffic-radar-config.mjs";
5
5
 
6
6
  export function claudePids(text) {
7
7
  const pids = [];
@@ -15,14 +15,20 @@ export function claudePids(text) {
15
15
  return [...new Set(pids)];
16
16
  }
17
17
 
18
+ // A TST=SYN_SENT line (only Linux /proc rows carry one) marks the socket before
19
+ // it as an attempt still awaiting a reply. A destination is connecting only
20
+ // while every socket to it is such an attempt.
18
21
  export function parseRadarSockets(text, pids) {
19
22
  const allowed = new Set(pids);
20
23
  const sockets = new Map();
21
24
  let pid = null;
25
+ let last = null;
22
26
  for (const rawLine of String(text ?? "").split("\n")) {
23
27
  const line = rawLine.trimEnd();
24
- if (/^p\d+$/.test(line)) pid = Number(line.slice(1));
28
+ if (/^p\d+$/.test(line)) { pid = Number(line.slice(1)); last = null; }
29
+ if (line === "TST=SYN_SENT" && last) { last.attempts++; continue; }
25
30
  if (!allowed.has(pid) || !line.startsWith("n")) continue;
31
+ last = null;
26
32
  const peer = line.slice(1).split("->")[1];
27
33
  if (!peer) continue;
28
34
  const match = /^(\[[0-9a-fA-F:.%]+\]|[0-9.]+):(\d+)$/.exec(peer);
@@ -30,9 +36,12 @@ export function parseRadarSockets(text, pids) {
30
36
  const port = Number(match[2]);
31
37
  if (port < 1 || port > 65535) continue;
32
38
  const destination = `${match[1]}:${port}`;
33
- sockets.set(`${pid}|${destination}`, { pid, destination });
39
+ const key = `${pid}|${destination}`;
40
+ last = sockets.get(key) ?? { pid, destination, count: 0, attempts: 0 };
41
+ last.count++;
42
+ sockets.set(key, last);
34
43
  }
35
- return [...sockets.values()];
44
+ return [...sockets.values()].map(({ pid, destination, count, attempts }) => attempts === count ? { pid, destination, connecting: true } : { pid, destination });
36
45
  }
37
46
 
38
47
  export function parseRadarWorkspaces(text, pids, home = homedir()) {
@@ -50,7 +59,7 @@ export function parseRadarWorkspaces(text, pids, home = homedir()) {
50
59
  return workspaces;
51
60
  }
52
61
 
53
- export function createTrafficRadar({ platform = process.platform, now = Date.now, run = systemCommand, config = readRadarConfig, readLinuxSockets = linuxSockets } = {}) {
62
+ export function createTrafficRadar({ platform = process.platform, now = Date.now, run = systemCommand, config = readRadarConfig, readLinuxSockets = linuxSockets, findLinuxClaude = linuxVersionedClaude } = {}) {
54
63
  let pending = null;
55
64
  let cached = null;
56
65
  let previousAt = null;
@@ -84,11 +93,15 @@ export function createTrafficRadar({ platform = process.platform, now = Date.now
84
93
  if (/^OTEL_LOG_/.test(variable) && value.startsWith("Enabled")) addAlert("Content capture configuration changed to enabled. Review settings below.", sampledAt);
85
94
  }
86
95
  }
87
- const pids = claudePids(processes);
96
+ const pids = platform === "linux" && processes !== null
97
+ ? [...new Set([...claudePids(processes), ...await findLinuxClaude(processes)])].sort((a, b) => a - b)
98
+ : claudePids(processes);
88
99
  const selected = pids.slice(0, 64);
89
100
  let sockets = "";
90
101
  let cwd = "";
91
- if (selected.length && platform === "linux") ({ sockets, cwd } = await readLinuxSockets(selected));
102
+ let denied = 0;
103
+ let launch = [];
104
+ if (selected.length && platform === "linux") ({ sockets, cwd, denied = 0, launch = [] } = await readLinuxSockets(selected));
92
105
  else if (selected.length && platform === "win32") sockets = await run("powershell.exe", powershell(windowsSockets(selected)));
93
106
  else if (selected.length) [sockets, cwd] = await Promise.all([
94
107
  run("/usr/sbin/lsof", ["-nP", "-a", "-p", selected.join(","), "-iTCP", "-sTCP:ESTABLISHED", "-Fpn"]),
@@ -106,13 +119,23 @@ export function createTrafficRadar({ platform = process.platform, now = Date.now
106
119
  if (previousAt !== null && previousConfig && !destinations.has(connection.destination)) addAlert(`New Claude connection destination: ${connection.destination}`, sampledAt);
107
120
  destinations.add(connection.destination);
108
121
  seen.set(key, { ...connection, workspace: workspaces.get(connection.pid) ?? null, firstSeenAt: sampledAt, lastSeenAt: sampledAt });
109
- } else seen.get(key).lastSeenAt = sampledAt;
122
+ } else {
123
+ const entry = seen.get(key);
124
+ entry.lastSeenAt = sampledAt;
125
+ if (connection.connecting) entry.connecting = true;
126
+ else delete entry.connecting;
127
+ }
110
128
  }
111
129
  for (const [key, connection] of seen) if (sampledAt - connection.lastSeenAt > 300_000) seen.delete(key);
112
130
  while (seen.size > 100) seen.delete(seen.keys().next().value);
113
131
  previousAt = sampledAt;
114
132
  previousConfig = nextConfig;
133
+ // Launch values sit beside the settings, not in them: processes starting
134
+ // and stopping are not configuration changes, and a saved switch replaces
135
+ // only the settings.
136
+ const environment = launchVariables(launch);
115
137
  return { ...base, status, config: configuration, processCount: pids.length, limited: pids.length > selected.length,
138
+ ...(denied ? { uninspected: denied } : {}), ...(environment.length ? { environment } : {}),
116
139
  connections: [...seen.entries()].map(([key, value]) => ({ ...value, active: status === "observing" ? active.has(key) : null }))
117
140
  .sort((a, b) => b.lastSeenAt - a.lastSeenAt), alerts };
118
141
  }
@@ -13,6 +13,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
13
13
  import { deckProviders } from "./deck-scope.mjs";
14
14
  import { send } from "./http-io.mjs";
15
15
  import { quotaHistoryReport } from "./quota-history.mjs";
16
+ import { quotaClosesReport } from "./quota-closes.mjs";
16
17
  import { validSessionLookup } from "./ccusage-session.mjs";
17
18
 
18
19
  // Resolved the way pinned-build.mjs resolves it, from a file in the same
@@ -28,13 +29,13 @@ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
28
29
  * carries on behind it and publishes for the next poll.
29
30
  */
30
31
  export async function handleQuota(req, res) {
31
- const { fetchClaudeQuota, QUOTA_DEADLINE_MS } = await import(
32
+ const { fetchClaudeQuota, withClaudePlan, QUOTA_DEADLINE_MS } = await import(
32
33
  pathToFileURL(join(PKG_ROOT, "src/server/quota.mjs")).href
33
34
  );
34
35
  const url = new URL(req.url, "http://localhost");
35
36
  const force = url.searchParams.get("refresh") === "1";
36
37
  const quota = await fetchClaudeQuota({ force, deadlineMs: QUOTA_DEADLINE_MS });
37
- send(res, 200, quota);
38
+ send(res, 200, await withClaudePlan(quota));
38
39
  }
39
40
 
40
41
  export async function handleCodexUsage(req, res) {
@@ -131,3 +132,14 @@ export async function handleQuotaHistory(req, res) {
131
132
  }
132
133
  send(res, 200, await quotaHistoryReport(provider, account));
133
134
  }
135
+
136
+ /** How full each of an account's windows was at its reset; never fetches. */
137
+ export async function handleQuotaCloses(req, res) {
138
+ const url = new URL(req.url, "http://localhost");
139
+ const provider = url.searchParams.get("provider");
140
+ const account = url.searchParams.get("account");
141
+ if (!["claude", "codex"].includes(provider) || !/^[a-f0-9]{64}$/.test(account ?? "")) {
142
+ return send(res, 400, { ok: false, reason: "bad_closes_scope" });
143
+ }
144
+ send(res, 200, await quotaClosesReport(provider, account));
145
+ }