ccdeck 3.82.3 → 4.0.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 (146) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/login-item.js +5 -0
  5. package/bin/cli/tui.js +58 -4
  6. package/bin/deck.js +27 -1
  7. package/dist/web/assets/AccountBridge-OQHT5qmS.js +1 -0
  8. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  9. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  10. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  11. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  12. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  13. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  14. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  15. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  16. package/dist/web/assets/UsageHistoryModal-ckawZGoe.js +1 -0
  17. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  18. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  19. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  20. package/dist/web/assets/app-40gNTTfq.js +361 -0
  21. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  22. package/dist/web/assets/{index-B4c5MZCc.js → index-XIY3yFiN.js} +1 -1
  23. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  24. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  25. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  26. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  27. package/dist/web/assets/use-account-BUmI-A8e.js +1 -0
  28. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  29. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  30. package/dist/web/index.html +16 -6
  31. package/package.json +13 -1
  32. package/release-notes.json +79 -0
  33. package/src/server/account-client.mjs +196 -0
  34. package/src/server/account-connect.mjs +238 -0
  35. package/src/server/account-flag.mjs +106 -0
  36. package/src/server/account-projects.mjs +1 -1
  37. package/src/server/account-service.mjs +532 -0
  38. package/src/server/account-status.mjs +293 -0
  39. package/src/server/account-store.mjs +137 -0
  40. package/src/server/account-sync.mjs +473 -0
  41. package/src/server/account-token-store.mjs +216 -0
  42. package/src/server/account-ui-fields.mjs +126 -0
  43. package/src/server/account-watch.mjs +1 -1
  44. package/src/server/browser-watch-log.mjs +1 -1
  45. package/src/server/browser-watch-store.mjs +1 -1
  46. package/src/server/ccdeck-account-routes.mjs +252 -0
  47. package/src/server/ccusage-install.mjs +2 -2
  48. package/src/server/ccusage-registry.mjs +4 -4
  49. package/src/server/ccusage-session.mjs +11 -0
  50. package/src/server/claude-accounts.mjs +1 -1
  51. package/src/server/claude-recovery.mjs +9 -4
  52. package/src/server/claude-settings-catalog.mjs +6 -6
  53. package/src/server/claude-settings.mjs +1 -1
  54. package/src/server/codex-auto.mjs +1 -1
  55. package/src/server/codex-cost-usage.mjs +7 -2
  56. package/src/server/codex-live-checkpoint.mjs +24 -9
  57. package/src/server/codex-live-engine.mjs +14 -4
  58. package/src/server/codex-live-handoff.mjs +53 -9
  59. package/src/server/codex-names.mjs +49 -0
  60. package/src/server/codex-translate.mjs +1 -1
  61. package/src/server/codex-ultrafast.d.mts +3 -0
  62. package/src/server/codex-ultrafast.mjs +5 -0
  63. package/src/server/codex-watch.mjs +25 -0
  64. package/src/server/command-panel-engine.mjs +300 -0
  65. package/src/server/command-panel-platform.mjs +99 -0
  66. package/src/server/cswap-auto-choice.mjs +1 -1
  67. package/src/server/cswap-auto-loop.mjs +1 -1
  68. package/src/server/cswap-install.mjs +21 -40
  69. package/src/server/deck-home.mjs +6 -0
  70. package/src/server/deck-prefs.mjs +53 -1
  71. package/src/server/detach.mjs +1 -1
  72. package/src/server/engine-download.mjs +277 -0
  73. package/src/server/engine-install.mjs +378 -0
  74. package/src/server/engine-package.mjs +267 -0
  75. package/src/server/event-log.mjs +7 -1
  76. package/src/server/event-pipeline.mjs +29 -1
  77. package/src/server/ghostty-handoff.mjs +81 -0
  78. package/src/server/index.mjs +143 -5
  79. package/src/server/installer.mjs +4 -1
  80. package/src/server/integrations/jira-write-guard.mjs +14 -208
  81. package/src/server/integrations/store.mjs +37 -19
  82. package/src/server/integrations/write-guard.mjs +223 -0
  83. package/src/server/intel-cpu-temperature.mjs +26 -0
  84. package/src/server/lifecycle.mjs +69 -6
  85. package/src/server/log-replay.mjs +4 -0
  86. package/src/server/login-service.mjs +116 -14
  87. package/src/server/macmon.mjs +1 -1
  88. package/src/server/npm-latest.mjs +1 -1
  89. package/src/server/org-telemetry.mjs +1 -1
  90. package/src/server/output-watch.mjs +4 -1
  91. package/src/server/panel-provenance.mjs +390 -0
  92. package/src/server/pinned-build.mjs +14 -0
  93. package/src/server/prefs-refusal.mjs +8 -1
  94. package/src/server/prefs-routes.mjs +60 -11
  95. package/src/server/pro-engine-client.mjs +339 -0
  96. package/src/server/pro-engine-install.mjs +294 -0
  97. package/src/server/pro-engine-terminal.mjs +308 -0
  98. package/src/server/project-discovery.mjs +139 -0
  99. package/src/server/provider-session-name.mjs +58 -0
  100. package/src/server/quota-closes.mjs +1 -1
  101. package/src/server/quota-history.mjs +1 -1
  102. package/src/server/reports.mjs +86 -21
  103. package/src/server/request-gates.mjs +34 -5
  104. package/src/server/restart-note.mjs +1 -1
  105. package/src/server/seed-boundary.mjs +489 -0
  106. package/src/server/session-counts.mjs +244 -0
  107. package/src/server/session-deck-names.mjs +143 -0
  108. package/src/server/session-enrichment.mjs +43 -6
  109. package/src/server/session-name-route.mjs +73 -0
  110. package/src/server/session-summary.mjs +12 -1
  111. package/src/server/session-transcript-routes.mjs +167 -0
  112. package/src/server/swap-log.mjs +1 -1
  113. package/src/server/system-metrics.mjs +57 -0
  114. package/src/server/terminal-bridge.mjs +485 -0
  115. package/src/server/terminal-folder.mjs +61 -0
  116. package/src/server/terminal-js-routes.mjs +752 -0
  117. package/src/server/terminal-routes.mjs +553 -0
  118. package/src/server/terminal-sessions.mjs +759 -0
  119. package/src/server/terminal-socket.mjs +403 -0
  120. package/src/server/terminal-target.mjs +928 -0
  121. package/src/server/thermal-metrics.mjs +13 -9
  122. package/src/server/tmux-control.mjs +1319 -0
  123. package/src/server/tmux-download.mjs +220 -0
  124. package/src/server/tmux.mjs +542 -0
  125. package/src/server/token-redact.mjs +42 -3
  126. package/src/server/tool-audit-report.mjs +44 -6
  127. package/src/server/tool-audit-routes.mjs +12 -1
  128. package/src/server/tool-audit.mjs +42 -8
  129. package/src/server/traffic-radar-monitor.mjs +1 -1
  130. package/src/server/traffic-radar-permission.mjs +1 -1
  131. package/src/server/transcript-gate.mjs +1 -1
  132. package/src/server/transcript-scan.mjs +15 -7
  133. package/src/server/transcript-turns.mjs +154 -0
  134. package/src/server/tui-network.mjs +1 -0
  135. package/src/server/tui-view.mjs +28 -0
  136. package/src/server/utf8-carry.mjs +159 -0
  137. package/src/server/uv-bootstrap.mjs +2 -2
  138. package/src/server/windows-acl.mjs +158 -0
  139. package/src/server/ws-frames.mjs +690 -0
  140. package/dist/web/assets/BrowserWatchModal-BmRTh_xT.js +0 -1
  141. package/dist/web/assets/IntegrationModal-C_f526aV.js +0 -7
  142. package/dist/web/assets/RadioPanel-D2rkf9cg.js +0 -1
  143. package/dist/web/assets/TrafficRadar-BOgVBLIN.js +0 -8
  144. package/dist/web/assets/UsageHistoryModal-BJPTFwM9.js +0 -1
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
  146. package/dist/web/assets/app-DZdZoqJ6.js +0 -358
@@ -0,0 +1,223 @@
1
+ // Durable per-scope reservations, shared by every provider. Only the small
2
+ // allowlisted record the provider's scope builds is stored.
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { chmod, link, mkdir, open, readFile, readdir, unlink } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { createConnection, createServer } from 'node:net';
7
+ import { setTimeout as delay } from 'node:timers/promises';
8
+ import { createRequire } from 'node:module';
9
+ import { dirname } from 'node:path';
10
+ import { integrationError } from './errors.mjs';
11
+ import { createTemp, renameWithRetry } from '../atomic-write.mjs';
12
+
13
+ const require = createRequire(import.meta.url);
14
+ let binding;
15
+ function nativeLock() {
16
+ if (!binding) {
17
+ // The exact dependency version pins this N-API layout and ABI. Loading the
18
+ // shipped binding directly avoids its resolver's Node 20-only Array.with.
19
+ // Keep this lazy so unsupported targets can still run the read-only deck.
20
+ const root = dirname(require.resolve('fs-native-extensions/package.json'));
21
+ binding = require(join(root, 'prebuilds', `${process.platform}-${process.arch}`, 'fs-native-extensions.node'));
22
+ }
23
+ return binding;
24
+ }
25
+ const nativeLocks = {
26
+ tryLock(fd) {
27
+ try { nativeLock().tryLock(fd, 0, 0, true); return true; }
28
+ catch (err) { if (err.code === 'EAGAIN') return false; throw err; }
29
+ },
30
+ unlock(fd) { nativeLock().unlock(fd, 0, 0); },
31
+ };
32
+ const active = new Set();
33
+ const listeners = new Map();
34
+ const uuidPattern = /^[0-9a-f-]{36}$/;
35
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code !== 'ESRCH'; } };
36
+
37
+ // Ephemeral sockets identify live writers without trusting reusable PIDs.
38
+ // Scope synchronization uses OS file locks below, never a fixed TCP port.
39
+ function listen(port, handler = socket => socket.destroy()) {
40
+ return new Promise((resolve, reject) => {
41
+ const server = createServer(handler);
42
+ server.once('error', reject);
43
+ server.listen({ port, host: '127.0.0.1', exclusive: true }, () => {
44
+ server.removeListener('error', reject);
45
+ resolve(server);
46
+ });
47
+ });
48
+ }
49
+ const close = server => new Promise((resolve, reject) => server.close(err => err ? reject(err) : resolve()));
50
+ async function startMarker(op) {
51
+ const token = randomUUID();
52
+ let server;
53
+ do {
54
+ server = await listen(0, socket => {
55
+ socket.setTimeout(1000, () => socket.destroy());
56
+ socket.end(token);
57
+ });
58
+ } while (!server);
59
+ server.unref();
60
+ listeners.set(op.operationId, server);
61
+ return { port: server.address().port, token };
62
+ }
63
+ async function stopMarker(op) {
64
+ const server = listeners.get(op.operationId);
65
+ if (server) { listeners.delete(op.operationId); await close(server); }
66
+ }
67
+ function markerAlive(marker) {
68
+ return new Promise(resolve => {
69
+ let data = '';
70
+ let settled = false;
71
+ const socket = createConnection({ host: '127.0.0.1', port: marker.port });
72
+ const done = value => { if (!settled) { settled = true; socket.destroy(); resolve(value); } };
73
+ // Ambiguous failures are treated as live; never acknowledge on a timeout.
74
+ socket.setTimeout(1000, () => done(true));
75
+ socket.on('data', chunk => { data += chunk.toString(); if (data.length >= marker.token.length) done(data === marker.token); });
76
+ socket.on('end', () => done(data === marker.token));
77
+ socket.on('error', err => done(err.code !== 'ECONNREFUSED'));
78
+ });
79
+ }
80
+
81
+ // The four outcomes a write can report. Failed is what a route says when the
82
+ // provider refused for certain; it never comes from a reservation.
83
+ export const WRITE_OUTCOMES = Object.freeze({ saving: 'saving', saved: 'saved', failed: 'failed', uncertain: 'uncertain' });
84
+ const outcomeOfRead = Object.freeze({ pending: WRITE_OUTCOMES.saving, confirmed: WRITE_OUTCOMES.saved, uncertain: WRITE_OUTCOMES.uncertain });
85
+ export const writeOutcome = record => outcomeOfRead[record?.state] ?? null;
86
+
87
+ // provider.record(input) validates the input and returns the stored record, or
88
+ // throws; provider.key(record) returns the string the scope hash is made from.
89
+ // list() and acknowledge() filter on connectionId, so every record must carry a
90
+ // top-level non-empty string connectionId.
91
+ export function createWriteGuard({ name, dir, locks = nativeLocks, scope: provider }) {
92
+ const scope = record => createHash('sha256').update(provider.key(record)).digest('hex');
93
+ async function prepare() {
94
+ const root = dir();
95
+ await mkdir(root, { recursive: true, mode: 0o700 });
96
+ if (process.platform !== 'win32') await chmod(root, 0o700);
97
+ return root;
98
+ }
99
+ async function syncDir(root) {
100
+ // Windows does not support opening directories for fsync.
101
+ if (process.platform === 'win32') return;
102
+ const h = await open(root, 'r'); try { await h.sync(); } finally { await h.close(); }
103
+ }
104
+ async function read(path) {
105
+ try { return JSON.parse(await readFile(path, 'utf8')); }
106
+ catch (e) { if (e.code === 'ENOENT') return null; throw e; }
107
+ }
108
+ async function running(root, op) {
109
+ if (active.has(op.operationId)) return true;
110
+ const names = await readdir(root);
111
+ const prefix = `running-${op.operationId}-`;
112
+ for (const name of names.filter(name => name.startsWith(prefix))) {
113
+ const marker = await read(join(root, name)).catch(err => {
114
+ // Older releases used empty PID-only marker files. Preserve their
115
+ // conservative behaviour while those processes may still be running.
116
+ if (err instanceof SyntaxError) return null;
117
+ throw err;
118
+ });
119
+ if (marker && Number.isInteger(marker.port) && marker.port > 0 && marker.port <= 65535 && typeof marker.token === 'string' && uuidPattern.test(marker.token)) {
120
+ if (await markerAlive(marker)) return true;
121
+ } else if (alive(Number(name.slice(prefix.length)))) return true;
122
+ }
123
+ return false;
124
+ }
125
+ async function state(root, op) { return { ...op, state: await running(root, op) ? 'pending' : op.state === 'confirmed' ? 'confirmed' : 'uncertain' }; }
126
+ async function lock(root, op, fn) {
127
+ // Keep the inode forever: unlinking/replacing a locked file would allow
128
+ // two processes to lock different inodes for the same scope. The kernel
129
+ // releases ownership on descriptor close or process death, not file age.
130
+ const handle = await open(join(root, `lock-${scope(op)}`), 'a+', 0o600);
131
+ let acquired = false;
132
+ try {
133
+ while (!(acquired = locks.tryLock(handle.fd))) await delay(10);
134
+ return await fn();
135
+ } finally {
136
+ try { if (acquired) locks.unlock(handle.fd); }
137
+ finally { await handle.close(); }
138
+ }
139
+ }
140
+ return {
141
+ async begin(input) {
142
+ const op = { ...provider.record(input), operationId: randomUUID(), state: 'pending' };
143
+ if (typeof op.connectionId !== 'string' || !op.connectionId) throw new Error('Invalid guard scope');
144
+ const root = await prepare();
145
+ // Check the actual filesystem and native support before any write.
146
+ try { await lock(root, op, async () => {}); }
147
+ catch { throw integrationError('unavailable', `${name} writes are unavailable because this system cannot safely coordinate them.`); }
148
+ const path = join(root, `${scope(op)}.json`);
149
+ const marker = join(root, `running-${op.operationId}-${process.pid}`);
150
+ const temp = join(root, `tmp-${op.operationId}`);
151
+ let returned = false;
152
+ active.add(op.operationId);
153
+ try {
154
+ const identity = await startMarker(op);
155
+ const markerHandle = await open(marker, 'wx', 0o600);
156
+ try { await markerHandle.writeFile(JSON.stringify(identity)); } finally { await markerHandle.close(); }
157
+ const h = await open(temp, 'wx', 0o600);
158
+ try { await h.writeFile(JSON.stringify(op)); await h.sync(); } finally { await h.close(); }
159
+ try { await link(temp, path); }
160
+ catch (e) {
161
+ if (e.code !== 'EEXIST') throw e;
162
+ const existing = await read(path);
163
+ if (!existing) return await this.begin(input);
164
+ return { conflict: await state(root, existing) };
165
+ }
166
+ await syncDir(root);
167
+ returned = true;
168
+ return { operation: { ...op, state: 'pending' } };
169
+ } finally {
170
+ await unlink(temp).catch(() => {});
171
+ if (!returned) { active.delete(op.operationId); await stopMarker(op); await unlink(marker).catch(() => {}); }
172
+ }
173
+ },
174
+ async finish(op, outcome) {
175
+ const root = await prepare();
176
+ try {
177
+ if (outcome === true || outcome === 'confirmed') {
178
+ const result = await lock(root, op, async () => {
179
+ const path = join(root, `${scope(op)}.json`);
180
+ const current = await read(path);
181
+ if (current?.operationId !== op.operationId) return { ok: false };
182
+ if (outcome === true) await unlink(path);
183
+ else {
184
+ const { tmp, handle } = await createTemp(path, { mode: 0o600 });
185
+ try {
186
+ try { await handle.writeFile(JSON.stringify({ ...current, state: 'confirmed' })); await handle.sync(); }
187
+ finally { await handle.close(); }
188
+ await renameWithRetry(tmp, path);
189
+ } finally { await unlink(tmp).catch(() => {}); }
190
+ }
191
+ await syncDir(root);
192
+ return { ok: true };
193
+ });
194
+ if (!result.ok) throw new Error(`${name} write guard could not finalize the operation`);
195
+ }
196
+ } finally {
197
+ active.delete(op.operationId);
198
+ await stopMarker(op);
199
+ await unlink(join(root, `running-${op.operationId}-${process.pid}`)).catch(() => {});
200
+ }
201
+ },
202
+ async list(connectionId) {
203
+ const root = await prepare();
204
+ const names = (await readdir(root)).filter(n => /^[a-f0-9]{64}\.json$/.test(n));
205
+ const records = await Promise.all(names.map(n => read(join(root, n))));
206
+ return Promise.all(records.filter(x => x?.connectionId === connectionId).map(x => state(root, x)));
207
+ },
208
+ async acknowledge(connectionId, operationId) {
209
+ if (typeof operationId !== 'string' || !uuidPattern.test(operationId)) return { ok: false };
210
+ const root = await prepare();
211
+ const op = (await this.list(connectionId)).find(x => x.operationId === operationId);
212
+ if (!op) return { ok: false };
213
+ return lock(root, op, async () => {
214
+ const path = join(root, `${scope(op)}.json`);
215
+ const current = await read(path);
216
+ if (!current || current.operationId !== operationId) return { ok: false };
217
+ if (await running(root, current)) return { conflict: await state(root, current) };
218
+ await unlink(path); await syncDir(root);
219
+ return { ok: true };
220
+ });
221
+ },
222
+ };
223
+ }
@@ -0,0 +1,26 @@
1
+ // Optional Intel SMC reader. macOS's built-in powermetrics needs root; this
2
+ // installed command reads the CPU proximity sensor without elevation.
3
+ // The executable is separate software, not bundled or downloaded by ccdeck.
4
+ import { existsSync } from "node:fs";
5
+ import { run } from "./exec.mjs";
6
+
7
+ export const INTEL_CPU_TEMP_CANDIDATES = [
8
+ "/usr/local/bin/osx-cpu-temp",
9
+ "/opt/homebrew/bin/osx-cpu-temp",
10
+ ];
11
+
12
+ export function cpuFromIntelSmc(text) {
13
+ const match = /^\s*(\d+(?:\.\d+)?)\s*°C\s*$/.exec(String(text ?? ""));
14
+ if (!match) return null;
15
+ const c = Number(match[1]);
16
+ return Number.isFinite(c) && c > 0 && c < 130 ? Math.round(c) : null;
17
+ }
18
+
19
+ export async function readIntelCpuTemp(deps = {}) {
20
+ if ((deps.platform ?? process.platform) !== "darwin" || (deps.arch ?? process.arch) !== "x64") return null;
21
+ const exists = deps.exists ?? existsSync;
22
+ const binary = INTEL_CPU_TEMP_CANDIDATES.find(p => exists(p));
23
+ if (!binary) return null;
24
+ const result = await (deps.run ?? run)(binary, ["-c"], { timeout: 2000, maxBuffer: 1024 });
25
+ return result.ok ? cpuFromIntelSmc(result.stdout) : null;
26
+ }
@@ -30,6 +30,8 @@ import { presentsDeckToken } from "./request-gates.mjs";
30
30
  // engine's card and /api/version give one answer — see running-version.mjs.
31
31
  import { RUNNING_VERSION } from "./running-version.mjs";
32
32
  import { terminalCliState, updateTerminalCli } from "./terminal-cli-update.mjs";
33
+ // How many terminal panels have a socket open on this deck — see deckPresence.
34
+ import { openTerminalCount } from "./terminal-socket.mjs";
33
35
 
34
36
  // Resolved the way pinned-build.mjs resolves it, from a file in the same
35
37
  // directory, so every lazy import below is the URL the pin has already evaluated.
@@ -359,14 +361,46 @@ async function handleStop(req, res) {
359
361
  send(res, 200, { ok: true, pid: process.pid });
360
362
  }
361
363
 
364
+ /**
365
+ * Presence as the away-update reads it: the tabs' own claims (presence.mjs,
366
+ * fed by POST /api/presence), and every terminal socket open on this deck
367
+ * counted as one more tab that is being looked at.
368
+ *
369
+ * A terminal panel is somebody at an agent's keyboard. A tab claims presence
370
+ * only while it is visible AND holds focus (src/web/presence.ts), so a person
371
+ * reading a running agent in the panel while their keyboard is in another
372
+ * window, or one whose tab sits behind the window they are typing a reply in,
373
+ * is not "looking" by that rule — and a restart then cuts their terminal: the
374
+ * socket closes with `server-shutdown`, the tickets die with the process, and
375
+ * whatever they type before the panel has reconnected goes nowhere. The tmux
376
+ * session survives all of it; the person's attention is what the away-update
377
+ * promises not to interrupt.
378
+ *
379
+ * The cost is that a panel left open holds the away-update off until it is
380
+ * closed. That is bounded: four sockets at most (MAX_TERMINALS); a tab that
381
+ * is closed takes its socket with it at once, and one that loses its network
382
+ * is dropped after two unanswered pings, about a minute (ws-frames.mjs) —
383
+ * which is when this stops counting it.
384
+ *
385
+ * `report` is the tabs' own; `openTerminals` answers how many sockets are
386
+ * open (terminal-socket's openTerminalCount).
387
+ */
388
+ export function deckPresence(tabs, openTerminals) {
389
+ return {
390
+ report: (tab, looking, now) => tabs.report(tab, looking, now),
391
+ looking: (now) => tabs.looking(now) || openTerminals() > 0,
392
+ };
393
+ }
394
+
362
395
  // The two facts the away-update waits on (awayUpdateTick): whether a turn is
363
- // running, fed from pushEvent, and whether a tab is being looked at, fed from
364
- // POST /api/presence. They sat at the top of index.mjs while pushEvent was
365
- // that file's, because pushEvent can run before the module holding it has
366
- // finished evaluating; made here, they exist before event-pipeline.mjs's own
367
- // body runs at all.
396
+ // running, fed from pushEvent, and whether anybody is at the deck — a tab
397
+ // being looked at, fed from POST /api/presence, or a terminal panel open on
398
+ // it. They sat at the top of index.mjs while pushEvent was that file's,
399
+ // because pushEvent can run before the module holding it has finished
400
+ // evaluating; made here, they exist before event-pipeline.mjs's own body runs
401
+ // at all.
368
402
  const activity = createActivity();
369
- const presence = createPresence();
403
+ const presence = deckPresence(createPresence(), openTerminalCount);
370
404
 
371
405
  // ── updating while nobody is looking ────────────────────────────────────────
372
406
  //
@@ -480,6 +514,35 @@ async function handlePresence(req, res) {
480
514
  return send(res, ok ? 200 : 400, { ok });
481
515
  }
482
516
 
517
+ /**
518
+ * What has to happen on the way out that the launcher cannot know about: the
519
+ * account's last status frame, so the console says "ccdeck stopped" at once
520
+ * rather than after 90 seconds of silence (account-status.mjs sendStopping).
521
+ * Registered by whatever needs it, while it needs it — nothing registers one
522
+ * on a deck with the account off, and then `beforeShutdown` is free.
523
+ */
524
+ const _beforeShutdown = new Set();
525
+
526
+ /** Run `fn` on the way out; answers the unregister. */
527
+ export function onBeforeShutdown(fn) {
528
+ _beforeShutdown.add(fn);
529
+ return () => _beforeShutdown.delete(fn);
530
+ }
531
+
532
+ /** The registered steps, all at once, bounded: bin/deck.js's shutdown awaits
533
+ * this on every way out — a signal, `ccdeck --stop`, a restart into an update
534
+ * — and never waits past `ms`, nor on a step that throws. */
535
+ export async function beforeShutdown(ms = 1_500) {
536
+ if (_beforeShutdown.size === 0) return;
537
+ const steps = [..._beforeShutdown].map(fn => Promise.resolve().then(fn).catch(() => {}));
538
+ let timer;
539
+ await Promise.race([
540
+ Promise.all(steps),
541
+ new Promise(r => { timer = setTimeout(r, ms); timer.unref?.(); }),
542
+ ]);
543
+ clearTimeout(timer);
544
+ }
545
+
483
546
  // What index.mjs calls besides the two exported above. Listed rather than
484
547
  // marked at each declaration, so the declarations read as they did where they
485
548
  // came from.
@@ -135,6 +135,10 @@ export function replayScope(workspace, platform = process.platform, providers =
135
135
  function admits(payload) {
136
136
  if (!payload || typeof payload !== "object") return false;
137
137
  if (payload.hook_event_name === "__clear") return true;
138
+ // The deck's record of what its Command Panel started (panel-provenance.mjs):
139
+ // no cwd and no session_id, and not a session's own event, so neither scope
140
+ // decides it. Admitted, like `__clear`, only when the server recorded it.
141
+ if (payload.hook_event_name === "__panel_launch") return true;
138
142
  // The provider gate, ahead of the workspace one and exempting `__clear` for
139
143
  // the same reason it does: the marker carries no provider, and a deck that
140
144
  // dropped it would replay a canvas the user had explicitly cleared.
@@ -43,6 +43,7 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node
43
43
  // from a Mac — the same reason deck-home.mjs and claudeCliCandidates do it, and
44
44
  // the third time this class of bug has been caught here.
45
45
  import { posix as posixPath, win32 as winPath } from "node:path";
46
+ import { writeFileAtomic } from "./atomic-write.mjs";
46
47
 
47
48
  /** The joiner for the platform being ASKED ABOUT, which is not always this one. */
48
49
  const joinFor = (platform) => (platform === "win32" ? winPath.join : posixPath.join);
@@ -95,7 +96,7 @@ export function xmlEscape(s) {
95
96
  * at. The default band is the honest one.
96
97
  */
97
98
  export function plistFor({ execPath, script, logPath, label = SERVICE_LABEL, args = [], env = {} } = {}) {
98
- const argv = [execPath, script, ...args].map(a => ` <string>${xmlEscape(a)}</string>`).join("\n");
99
+ const argv = [...GUARD_WORDS, execPath, script, ...args].map(a => ` <string>${xmlEscape(a)}</string>`).join("\n");
99
100
  const vars = Object.entries({ AGENTS_DECK_DETACHED: "1", ...env })
100
101
  .map(([k, v]) => ` <key>${xmlEscape(k)}</key>\n <string>${xmlEscape(v)}</string>`)
101
102
  .join("\n");
@@ -128,6 +129,27 @@ ${vars}
128
129
  * unit, and `%%` is the literal. */
129
130
  const sdEscape = (s) => String(s).replace(/%/g, "%%");
130
131
 
132
+ /**
133
+ * What a login item runs on Linux and macOS, as the shell's own program text.
134
+ *
135
+ * ONE CONSTANT, with the paths handed over as positional arguments after it,
136
+ * never spliced into the text, so a space, a quote or a `$` in an install path
137
+ * is only ever an argument (the rule NODE_FALLBACK in installer.mjs follows).
138
+ * `$0` is the label, `$1` node, `$2` the deck's script and the rest its
139
+ * arguments. When the script is gone, because `npm uninstall -g ccdeck` took it
140
+ * and nothing took the login item, the job ends 0 and says nothing. Before, it
141
+ * was a node "Cannot find module" stack in deck.log and a failed unit at every
142
+ * login.
143
+ */
144
+ export const LOGIN_GUARD = '[ -f "$2" ] || exit 0; exec "$@"';
145
+ /** The words in front of the old command, which is exactly [node, script, ...args]. */
146
+ const GUARD_WORDS = ["/bin/sh", "-c", LOGIN_GUARD, "ccdeck-login"];
147
+ /** The same words, as they stand in a systemd ExecStart line. */
148
+ const sdWord = (a) => {
149
+ const v = sdEscape(a).replace(/\$/g, "$$$$");
150
+ return /[\s"'\\]/.test(v) ? `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : v;
151
+ };
152
+
131
153
  /**
132
154
  * The systemd --user unit.
133
155
  *
@@ -144,10 +166,7 @@ export function unitFor({ execPath, script, logPath, args = [], env = {}, produc
144
166
  // and the same `%` in an install path made ExecStart a fatal error.
145
167
  // An argument with whitespace, a quote or a backslash is quoted, with the
146
168
  // C escapes systemd's word splitting reads inside the quotes.
147
- const cmd = [execPath, script, ...args].map(a => {
148
- const v = sdEscape(a).replace(/\$/g, "$$$$");
149
- return /[\s"'\\]/.test(v) ? `"${v.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"` : v;
150
- }).join(" ");
169
+ const cmd = [...GUARD_WORDS, execPath, script, ...args].map(sdWord).join(" ");
151
170
  // QUOTED, AND `%` ESCAPED. systemd.exec(5) splits an Environment= assignment
152
171
  // on whitespace unless the whole thing is double-quoted, and it expands `%`
153
172
  // specifiers in the value. ExecStart above quotes its own arguments; this
@@ -188,6 +207,19 @@ WantedBy=default.target
188
207
  `;
189
208
  }
190
209
 
210
+ /**
211
+ * The Windows account this process runs as, in the form a Task Scheduler
212
+ * <UserId> takes: DOMAIN\user (the machine name for a local account), or the
213
+ * bare user name when Windows left USERDOMAIN out. Empty when neither is set,
214
+ * and then the task is written without one, as before.
215
+ */
216
+ export function windowsAccount(env = process.env) {
217
+ const user = String(env?.USERNAME ?? "").trim();
218
+ if (!user) return "";
219
+ const domain = String(env?.USERDOMAIN ?? "").trim();
220
+ return domain ? `${domain}\\${user}` : user;
221
+ }
222
+
191
223
  /**
192
224
  * The Task Scheduler job, as XML.
193
225
  *
@@ -202,11 +234,20 @@ WantedBy=default.target
202
234
  * UTF-16LE with a BOM on disk, which is what schtasks requires and what a file
203
235
  * written as UTF-8 is silently rejected for.
204
236
  *
205
- * No <UserId>: schtasks fills in the account running it, which is the one whose
206
- * login this task is about. Naming it would be a guess that breaks on a renamed
207
- * account, a domain user or a machine in another locale.
237
+ * No <UserId> in the PRINCIPAL: schtasks fills in the account running it, which
238
+ * is the one whose login this task is about.
239
+ *
240
+ * But the LOGON TRIGGER names the account, when the caller knows it. A logon
241
+ * trigger without one fires at ANY user's logon, and Windows lets only an
242
+ * administrator register that: on a real Windows 11 standard account, schtasks
243
+ * answered this file with "ERROR: Access is denied." while the same file with
244
+ * the account in the trigger was accepted (VM check, 2026-11-15). So the login
245
+ * item this deck offers never registered for an ordinary account. The name is
246
+ * the process's own USERDOMAIN\USERNAME (windowsAccount): not a guess, not
247
+ * translated on a localised Windows, the domain form for a domain user, and
248
+ * Task Scheduler resolves it to the account's SID when the task is registered.
208
249
  */
209
- export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } = {}) {
250
+ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck", userId = "" } = {}) {
210
251
  // NO ENVIRONMENT BLOCK, and that is the schema's doing rather than an
211
252
  // omission here: there is nowhere in a Task Scheduler task to put a variable.
212
253
  // Which is the second reason Windows runs the LAUNCHER and lets it detach
@@ -214,7 +255,14 @@ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } =
214
255
  // way to carry it. The launcher writes deck.log either way, so the output
215
256
  // this platform also cannot redirect lands in the same file as everywhere
216
257
  // else.
217
- const argLine = [script, ...args].map(a => (/\s/.test(a) ? `"${a}"` : a)).join(" ");
258
+ // THROUGH cmd.exe, so a deck script that `npm uninstall -g` took away ends the
259
+ // task with exit 0 instead of node's "Cannot find module" window at every
260
+ // logon. `if exist` has no else, so a missing script runs nothing; /s strips
261
+ // the one outer pair of quotes and every path inside is quoted on its own.
262
+ // When the script exists this runs the same node on the same script with the
263
+ // same arguments as before.
264
+ const rest = args.map(a => ` ${/\s/.test(a) ? `"${a}"` : a}`).join("");
265
+ const argLine = `/d /s /c "if exist "${script}" ("${execPath}" "${script}"${rest})"`;
218
266
  return `<?xml version="1.0" encoding="UTF-16"?>
219
267
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
220
268
  <RegistrationInfo>
@@ -222,7 +270,7 @@ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } =
222
270
  </RegistrationInfo>
223
271
  <Triggers>
224
272
  <LogonTrigger>
225
- <Enabled>true</Enabled>
273
+ <Enabled>true</Enabled>${userId ? `\n <UserId>${xmlEscape(userId)}</UserId>` : ""}
226
274
  </LogonTrigger>
227
275
  </Triggers>
228
276
  <Principals>
@@ -252,7 +300,7 @@ export function taskXmlFor({ execPath, script, args = [], product = "ccdeck" } =
252
300
  </Settings>
253
301
  <Actions Context="Author">
254
302
  <Exec>
255
- <Command>${xmlEscape(execPath)}</Command>
303
+ <Command>cmd.exe</Command>
256
304
  <Arguments>${xmlEscape(argLine)}</Arguments>
257
305
  </Exec>
258
306
  </Actions>
@@ -411,6 +459,12 @@ export const SETTING_VARS = Object.freeze([
411
459
  "AGENTS_DECK_NO_RADAR",
412
460
  // Keep native Codex account control disabled after a login-service restart.
413
461
  "AGENTS_DECK_NO_CODEX_LIVE",
462
+ // The account's veto (account-flag.mjs), carried because a veto is always
463
+ // safe to pass on — and the one name here the README's table does not list:
464
+ // the account it vetoes is hidden, so documenting the veto would announce
465
+ // it. login-item-opt-outs.test.ts names it as that exception. The switch
466
+ // that turns the account on, CCDECK_ACCOUNT, is not carried at all.
467
+ "AGENTS_DECK_NO_ACCOUNT",
414
468
  ]);
415
469
 
416
470
  export function settingsEnv(env = process.env) {
@@ -520,7 +574,7 @@ export function installService({
520
574
  // and both answer a missing one by failing the job silently. On a machine
521
575
  // where the deck has never run — which is every machine `--install-service`
522
576
  // is typed on first — that directory does not exist yet.
523
- fs.mkdirSync(logPathDir(logPath), { recursive: true });
577
+ fs.mkdirSync(logPathDir(logPath), { recursive: true, mode: 0o700 });
524
578
  if (platform === "win32") {
525
579
  // The XML goes to a temp file beside the deck's own data rather than to
526
580
  // %TEMP%: schtasks reads it once and this way a machine that refuses the
@@ -528,7 +582,7 @@ export function installService({
528
582
  // this deck owns.
529
583
  const xmlPath = joinFor(platform)(logPathDir(logPath), `${SERVICE_LABEL}-task.xml`);
530
584
  // UTF-16LE with a BOM: schtasks rejects UTF-8 with an unhelpful error.
531
- fs.writeFileSync(xmlPath, "\uFEFF" + taskXmlFor({ execPath, script, args, product }), "utf16le");
585
+ fs.writeFileSync(xmlPath, "\uFEFF" + taskXmlFor({ execPath, script, args, product, userId: windowsAccount(env) }), "utf16le");
532
586
  const cmd = registerCommand(platform, xmlPath);
533
587
  const out = run(cmd.file, cmd.args, { encoding: "utf8", windowsHide: true });
534
588
  if (out?.status !== 0) {
@@ -567,6 +621,54 @@ export function installService({
567
621
  }
568
622
  }
569
623
 
624
+ /**
625
+ * A login item written before the guard, as the guarded one. Text in, text
626
+ * out, null when there is nothing to change (already guarded, or not a shape
627
+ * this file writes). The old command was exactly [node, script, ...args], which
628
+ * is what the guard takes as its own positional arguments, so the words are put
629
+ * in front of it and nothing else in the file moves.
630
+ */
631
+ export function guardedItemText(text, platform = process.platform) {
632
+ if (platform === "linux") {
633
+ const m = /^ExecStart=(.*)$/m.exec(text);
634
+ if (!m || m[1].startsWith("/bin/sh -c ") || m[1].trim() === "") return null;
635
+ return text.replace(/^ExecStart=.*$/m, () => `ExecStart=${GUARD_WORDS.map(sdWord).join(" ")} ${m[1]}`);
636
+ }
637
+ if (platform === "darwin") {
638
+ const m = /(<key>ProgramArguments<\/key>\s*<array>\n)(\s*<string>)([^<]*)(<\/string>)/.exec(text);
639
+ if (!m || m[3] === "/bin/sh") return null;
640
+ const words = GUARD_WORDS.map(a => ` <string>${xmlEscape(a)}</string>\n`).join("");
641
+ return text.replace(m[0], () => `${m[1]}${words}${m[2]}${m[3]}${m[4]}`);
642
+ }
643
+ return null;
644
+ }
645
+
646
+ /**
647
+ * Bring the login item of an older deck to the guarded form, on the platform's
648
+ * own file. File content only: no enable, no load, no schtasks, so nothing is
649
+ * started, stopped or registered by it. Windows keeps its task in the scheduler
650
+ * rather than in a file, and rewriting it would take schtasks, so it is not
651
+ * touched here. Answers whether it rewrote the file, never throws.
652
+ */
653
+ export async function refreshLoginItem({
654
+ platform = process.platform,
655
+ home = homedir(),
656
+ env = process.env,
657
+ read = readFileSync,
658
+ } = {}) {
659
+ try {
660
+ if (platform !== "linux" && platform !== "darwin") return false;
661
+ const path = servicePath(platform, home, env);
662
+ const text = read(path, "utf8");
663
+ // Ours: the marker both writers put in every job.
664
+ if (!text.includes("AGENTS_DECK_DETACHED")) return false;
665
+ const next = guardedItemText(text, platform);
666
+ if (next === null || next === text) return false;
667
+ await writeFileAtomic(path, next);
668
+ return true;
669
+ } catch { return false; }
670
+ }
671
+
570
672
  /**
571
673
  * Take it away. Same contract: a verdict, never a throw.
572
674
  *
@@ -271,7 +271,7 @@ export async function bootstrapMacmon({
271
271
  // rather than accepting a directory somebody else made.
272
272
  // Staged beside the destination rather than in the system temp directory,
273
273
  // so the rename below is same-filesystem and therefore atomic.
274
- await mkdir(dir, { recursive: true });
274
+ await mkdir(dir, { recursive: true, mode: 0o700 });
275
275
  staging = await mkdtemp(join(dir, "macmon-staging-"));
276
276
  const archivePath = join(staging, "macmon.tar.gz");
277
277
  await writeFile(archivePath, archive);
@@ -261,7 +261,7 @@ export function lastKnownLatest(name = PUBLISHED_NAME) {
261
261
  function writeMarker(name, marker) {
262
262
  const path = markerPath(name);
263
263
  try {
264
- mkdirSync(dirname(path), { recursive: true });
264
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
265
265
  writeFileSync(path, JSON.stringify(marker));
266
266
  } catch { /* a read-only home must not break the deck */ }
267
267
  }
@@ -165,7 +165,7 @@ export async function observeOrgTelemetry({
165
165
  writtenAt: Math.round(mtime),
166
166
  },
167
167
  };
168
- await makeDir(dataDir, { recursive: true })
168
+ await makeDir(dataDir, { recursive: true, mode: 0o700 })
169
169
  .then(() => write(recordsPath, `${JSON.stringify(_records, null, 2)}\n`))
170
170
  .catch(() => {});
171
171
  } catch { /* no file, or one that could not be read: nothing new to say */ }
@@ -143,6 +143,9 @@ export function createOutputWatch(io = {}) {
143
143
 
144
144
  function forget(sid) { seen.delete(sid); }
145
145
 
146
+ /** Where a session's transcript is, as `note` last heard it, or undefined. */
147
+ function pathOf(sid) { return seen.get(sid)?.path; }
148
+
146
149
  /** For the suite, and for the one place the server clears everything. */
147
150
  function clear() { seen.clear(); }
148
151
  function size() { return seen.size; }
@@ -270,5 +273,5 @@ export function createOutputWatch(io = {}) {
270
273
  }
271
274
  }
272
275
 
273
- return { note, forget, clear, size, poll };
276
+ return { note, forget, clear, size, pathOf, poll };
274
277
  }