ccdeck 3.82.4 → 4.0.1

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 (145) 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/tui.js +58 -4
  5. package/bin/deck.js +27 -1
  6. package/dist/web/assets/AccountBridge-fp-fsMx-.js +1 -0
  7. package/dist/web/assets/AccountSection-Cu-96Q00.js +1 -0
  8. package/dist/web/assets/BrowserWatchModal-CvUx07C6.js +1 -0
  9. package/dist/web/assets/FeedbackConversations-BgVk0nkA.js +1 -0
  10. package/dist/web/assets/IntegrationModal-CEj5oJg4.js +7 -0
  11. package/dist/web/assets/IntegrationSkeleton-DD7YiFgd.js +1 -0
  12. package/dist/web/assets/RadioPanel-BhnzWRCT.js +1 -0
  13. package/dist/web/assets/StageShell-DmJu3dU1.js +4 -0
  14. package/dist/web/assets/TrafficRadar-C8-ieIw5.js +8 -0
  15. package/dist/web/assets/UsageHistoryModal-BThv9Kja.js +1 -0
  16. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  17. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  18. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  19. package/dist/web/assets/app-DtosBis5.css +1 -0
  20. package/dist/web/assets/app-ZMmmEHxF.js +361 -0
  21. package/dist/web/assets/{index-B-l-VxLm.js → index-zSxC5ueJ.js} +1 -1
  22. package/dist/web/assets/inspector-status-pane-BgQG0bQi.js +1 -0
  23. package/dist/web/assets/screens-DD0uCtat.js +12 -0
  24. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  25. package/dist/web/assets/stage-board-J2rKA9Pg.js +2 -0
  26. package/dist/web/assets/use-account-DvFObI4M.js +1 -0
  27. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  28. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  29. package/dist/web/index.html +16 -6
  30. package/package.json +13 -1
  31. package/release-notes.json +69 -1
  32. package/src/server/account-client.mjs +196 -0
  33. package/src/server/account-connect.mjs +238 -0
  34. package/src/server/account-flag.mjs +106 -0
  35. package/src/server/account-projects.mjs +1 -1
  36. package/src/server/account-service.mjs +532 -0
  37. package/src/server/account-status.mjs +293 -0
  38. package/src/server/account-store.mjs +137 -0
  39. package/src/server/account-sync.mjs +473 -0
  40. package/src/server/account-token-store.mjs +216 -0
  41. package/src/server/account-ui-fields.mjs +126 -0
  42. package/src/server/account-watch.mjs +1 -1
  43. package/src/server/browser-watch-log.mjs +1 -1
  44. package/src/server/browser-watch-store.mjs +1 -1
  45. package/src/server/ccdeck-account-routes.mjs +252 -0
  46. package/src/server/ccusage-install.mjs +2 -2
  47. package/src/server/ccusage-registry.mjs +4 -4
  48. package/src/server/ccusage-session.mjs +11 -0
  49. package/src/server/claude-accounts.mjs +1 -1
  50. package/src/server/claude-recovery.mjs +9 -4
  51. package/src/server/claude-settings-catalog.mjs +6 -6
  52. package/src/server/claude-settings.mjs +1 -1
  53. package/src/server/codex-auto.mjs +1 -1
  54. package/src/server/codex-cost-usage.mjs +7 -2
  55. package/src/server/codex-live-checkpoint.mjs +24 -9
  56. package/src/server/codex-live-engine.mjs +14 -4
  57. package/src/server/codex-live-handoff.mjs +53 -9
  58. package/src/server/codex-names.mjs +49 -0
  59. package/src/server/codex-translate.mjs +1 -1
  60. package/src/server/codex-ultrafast.d.mts +3 -0
  61. package/src/server/codex-ultrafast.mjs +5 -0
  62. package/src/server/codex-watch.mjs +25 -0
  63. package/src/server/command-panel-engine.mjs +300 -0
  64. package/src/server/command-panel-platform.mjs +99 -0
  65. package/src/server/cswap-auto-choice.mjs +1 -1
  66. package/src/server/cswap-auto-loop.mjs +1 -1
  67. package/src/server/cswap-install.mjs +21 -40
  68. package/src/server/deck-home.mjs +6 -0
  69. package/src/server/deck-prefs.mjs +53 -1
  70. package/src/server/detach.mjs +1 -1
  71. package/src/server/engine-download.mjs +277 -0
  72. package/src/server/engine-install.mjs +378 -0
  73. package/src/server/engine-package.mjs +267 -0
  74. package/src/server/event-log.mjs +7 -1
  75. package/src/server/event-pipeline.mjs +29 -1
  76. package/src/server/ghostty-handoff.mjs +81 -0
  77. package/src/server/index.mjs +143 -5
  78. package/src/server/installer.mjs +4 -1
  79. package/src/server/integrations/jira-write-guard.mjs +14 -208
  80. package/src/server/integrations/store.mjs +37 -19
  81. package/src/server/integrations/write-guard.mjs +223 -0
  82. package/src/server/intel-cpu-temperature.mjs +26 -0
  83. package/src/server/lifecycle.mjs +69 -6
  84. package/src/server/log-replay.mjs +4 -0
  85. package/src/server/login-service.mjs +7 -1
  86. package/src/server/macmon.mjs +1 -1
  87. package/src/server/npm-latest.mjs +1 -1
  88. package/src/server/org-telemetry.mjs +1 -1
  89. package/src/server/output-watch.mjs +4 -1
  90. package/src/server/panel-provenance.mjs +390 -0
  91. package/src/server/pinned-build.mjs +14 -0
  92. package/src/server/prefs-refusal.mjs +8 -1
  93. package/src/server/prefs-routes.mjs +60 -11
  94. package/src/server/pro-engine-client.mjs +339 -0
  95. package/src/server/pro-engine-install.mjs +294 -0
  96. package/src/server/pro-engine-terminal.mjs +308 -0
  97. package/src/server/project-discovery.mjs +139 -0
  98. package/src/server/provider-session-name.mjs +58 -0
  99. package/src/server/quota-closes.mjs +1 -1
  100. package/src/server/quota-history.mjs +1 -1
  101. package/src/server/reports.mjs +86 -21
  102. package/src/server/request-gates.mjs +34 -5
  103. package/src/server/restart-note.mjs +1 -1
  104. package/src/server/seed-boundary.mjs +489 -0
  105. package/src/server/session-counts.mjs +244 -0
  106. package/src/server/session-deck-names.mjs +143 -0
  107. package/src/server/session-enrichment.mjs +43 -6
  108. package/src/server/session-name-route.mjs +73 -0
  109. package/src/server/session-summary.mjs +12 -1
  110. package/src/server/session-transcript-routes.mjs +167 -0
  111. package/src/server/swap-log.mjs +1 -1
  112. package/src/server/system-metrics.mjs +57 -0
  113. package/src/server/terminal-bridge.mjs +485 -0
  114. package/src/server/terminal-folder.mjs +61 -0
  115. package/src/server/terminal-js-routes.mjs +752 -0
  116. package/src/server/terminal-routes.mjs +553 -0
  117. package/src/server/terminal-sessions.mjs +759 -0
  118. package/src/server/terminal-socket.mjs +403 -0
  119. package/src/server/terminal-target.mjs +928 -0
  120. package/src/server/thermal-metrics.mjs +13 -9
  121. package/src/server/tmux-control.mjs +1319 -0
  122. package/src/server/tmux-download.mjs +220 -0
  123. package/src/server/tmux.mjs +542 -0
  124. package/src/server/token-redact.mjs +42 -3
  125. package/src/server/tool-audit-report.mjs +44 -6
  126. package/src/server/tool-audit-routes.mjs +12 -1
  127. package/src/server/tool-audit.mjs +42 -8
  128. package/src/server/traffic-radar-monitor.mjs +1 -1
  129. package/src/server/traffic-radar-permission.mjs +1 -1
  130. package/src/server/transcript-gate.mjs +1 -1
  131. package/src/server/transcript-scan.mjs +15 -7
  132. package/src/server/transcript-turns.mjs +154 -0
  133. package/src/server/tui-network.mjs +1 -0
  134. package/src/server/tui-view.mjs +28 -0
  135. package/src/server/utf8-carry.mjs +159 -0
  136. package/src/server/uv-bootstrap.mjs +2 -2
  137. package/src/server/windows-acl.mjs +158 -0
  138. package/src/server/ws-frames.mjs +690 -0
  139. package/dist/web/assets/BrowserWatchModal-CWVooKxD.js +0 -1
  140. package/dist/web/assets/IntegrationModal-DLX43RIK.js +0 -7
  141. package/dist/web/assets/RadioPanel-Cj6PjrvQ.js +0 -1
  142. package/dist/web/assets/TrafficRadar-Bq1YcuHB.js +0 -8
  143. package/dist/web/assets/UsageHistoryModal-CMSCca5_.js +0 -1
  144. package/dist/web/assets/app-BHxsMz3-.js +0 -358
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
@@ -0,0 +1,267 @@
1
+ // How the Command Panel's engine gets from the npm package that carries it
2
+ // into the deck's own engine folder, verified.
3
+ //
4
+ // ONE PACKAGE PER PLATFORM, installed beside the deck. `npm i -g ccdeck` also
5
+ // brings the engine for the machine it runs on, as esbuild does for its
6
+ // binary: each platform's engine is its own package (ENGINE_PACKAGE_NAMES) with
7
+ // `os` and `cpu` fields, listed as an optional dependency of the deck, so npm
8
+ // installs the one that fits and skips the rest. The package holds exactly what
9
+ // an installation holds: the engine executable and its signed `manifest.json`.
10
+ //
11
+ // NOTHING HAPPENS UNTIL A ROUTE ASKS, WITH THE SWITCH ON. Importing this does
12
+ // no I/O. command-panel-engine.mjs calls importEngine only when a question for
13
+ // the Command Panel arrives while its switch is on, on a platform that has the
14
+ // panel, and only when the deck holds keys to verify with. With the switch off
15
+ // (the default) nothing here is called: the package folder is never looked at.
16
+ //
17
+ // THE PACKAGE IS FOUND BY WALKING UP FROM THE DECK'S OWN FOLDER through each
18
+ // `node_modules`, the way Node finds a dependency, and nowhere else: not on
19
+ // PATH, not in the working directory, not in NODE_PATH, not from any path a
20
+ // user, a setting or a request supplies. No package, no import, and the panel
21
+ // answers what it always has (`not-installed`).
22
+ //
23
+ // WHAT IS CHECKED BEFORE A BYTE IS COPIED, on the bytes read once through
24
+ // O_NOFOLLOW (a link anywhere in the source is refused) from files owned by
25
+ // the user or root and writable by nobody outside their group (npm writes the
26
+ // package under the user's umask, often 002; the installed copy is owner-only):
27
+ // - the manifest's Ed25519 signature, by one of the deck's keys, and its six
28
+ // signed fields for this machine's target;
29
+ // - the executable's size and SHA-256 against the manifest;
30
+ // - the executable's own header: ELF, Mach-O or PE, with the machine of this
31
+ // OS and arch (an x64 engine on an arm64 machine is refused);
32
+ // - the version against the floor: never lower than the engine already
33
+ // installed, nor than the lowest version the deck has ever kept
34
+ // (MINIMUM_VERSION_FILE, below).
35
+ // What is written is those same bytes, not a second read of the source.
36
+ //
37
+ // HOW IT IS INSTALLED. The bytes go to a new folder inside the deck's data
38
+ // folder (0700, files 0700 and 0600, each fsynced), which the installer's own
39
+ // verifier (pro-engine-install.mjs) must accept before anything moves. Then the
40
+ // old folder is set aside, the new one renamed to `engine`, the result verified
41
+ // again where it now stands, and only then the old one removed. A step that
42
+ // fails puts the old folder back: the previous installation is never touched
43
+ // by an import that did not complete. A source whose signed digest and version
44
+ // are those of an installation that verifies is not copied again.
45
+ //
46
+ // THE FLOOR. The lowest version the deck accepts is kept in one small file
47
+ // beside the engine folder, written after each completed import to the highest
48
+ // version seen. It is the deck's own record, read only by the deck: nothing
49
+ // from a request or a setting reaches it. Same-user tampering with it is out of
50
+ // scope, as it is for the engine folder itself.
51
+ //
52
+ // WINDOWS ships like the other platforms: ENGINE_ON_WINDOWS below is the one
53
+ // switch. The installer builds its own ACL reader (windows-acl.mjs) when a
54
+ // caller gives none, and asks it about the package and the engine folder.
55
+ import { constants, promises as fs } from "node:fs";
56
+ import { randomBytes, createHash } from "node:crypto";
57
+ import { dirname, join, basename } from "node:path";
58
+ import { fileURLToPath } from "node:url";
59
+ import { deckDataDir } from "./deck-home.mjs";
60
+ import {
61
+ ENGINE_MANIFEST_MAX, TARGETS, UNSAFE_FOLDER, compareVersions, executableMatchesMachine, readTrusted, signedEntry, trustGate,
62
+ verifyEngineInstallation,
63
+ } from "./pro-engine-install.mjs";
64
+
65
+ /** The npm package that carries the engine for each `<platform>-<arch>`. The
66
+ * one place the names live. */
67
+ export const ENGINE_PACKAGE_NAMES = Object.freeze({
68
+ "linux-x64": "@ccdeck/engine-linux-x64",
69
+ "linux-arm64": "@ccdeck/engine-linux-arm64",
70
+ "darwin-x64": "@ccdeck/engine-darwin-x64",
71
+ "darwin-arm64": "@ccdeck/engine-darwin-arm64",
72
+ "win32-x64": "@ccdeck/engine-win32-x64",
73
+ });
74
+
75
+ /** Whether the Command Panel is offered on Windows: the engine ships there, so
76
+ * the panel is offered like on Linux and macOS (its sessions live in the
77
+ * per-user session host). */
78
+ export const ENGINE_ON_WINDOWS = true;
79
+
80
+ /** The lowest engine version the deck has kept, beside the engine folder. */
81
+ export const MINIMUM_VERSION_FILE = "engine-minimum-version";
82
+
83
+ /** Where the deck itself lives: the folder lookups of the package start at. */
84
+ const DECK_FOLDER = dirname(fileURLToPath(import.meta.url));
85
+
86
+ /** The package name for a platform and arch, or null. */
87
+ export function enginePackageName(platform = process.platform, arch = process.arch) {
88
+ return Object.hasOwn(ENGINE_PACKAGE_NAMES, `${platform}-${arch}`) ? ENGINE_PACKAGE_NAMES[`${platform}-${arch}`] : null;
89
+ }
90
+
91
+ /** The folder of the installed package `name`, found by walking up from
92
+ * `from` through each `node_modules` (never PATH, the working directory or
93
+ * NODE_PATH), or null. Its package.json must be a regular file naming it. */
94
+ export async function findEnginePackage(name, from = DECK_FOLDER) {
95
+ let dir = from;
96
+ while (true) {
97
+ const modules = basename(dir) === "node_modules" ? dir : join(dir, "node_modules");
98
+ const candidate = join(modules, name);
99
+ try {
100
+ const manifest = await fs.lstat(join(candidate, "package.json"));
101
+ if (manifest.isFile() || manifest.isSymbolicLink()) {
102
+ const root = await fs.realpath(candidate);
103
+ const handle = await fs.open(join(root, "package.json"), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
104
+ try {
105
+ const stat = await handle.stat();
106
+ if (stat.isFile() && stat.size > 0 && stat.size <= 64 * 1024 && JSON.parse(await handle.readFile("utf8"))?.name === name) return root;
107
+ } finally { await handle.close(); }
108
+ }
109
+ } catch { /* not here: look further up */ }
110
+ const up = dirname(dir);
111
+ if (up === dir) return null;
112
+ dir = up;
113
+ }
114
+ }
115
+
116
+ /** The kept floor as text, `undefined` when there is none, and a text that is
117
+ * no version when the file cannot be trusted (which refuses every engine). */
118
+ async function readFloor(dataDir, gateOptions) {
119
+ const file = join(dataDir, MINIMUM_VERSION_FILE);
120
+ try {
121
+ await fs.lstat(file);
122
+ } catch (error) {
123
+ return error?.code === "ENOENT" || error?.code === "ENOTDIR" ? undefined : "unreadable";
124
+ }
125
+ try {
126
+ const { data } = await readTrusted(file, 64, await trustGate(gateOptions));
127
+ const text = data.toString("utf8").trim();
128
+ compareVersions(text, "0.0.0");
129
+ return text;
130
+ } catch {
131
+ return "unreadable";
132
+ }
133
+ }
134
+
135
+ const higher = (a, b) => (a === undefined ? b : b === undefined ? a : compareVersions(a, b) >= 0 ? a : b);
136
+
137
+ /** Writes `bytes` to a new file, owner-only, flushed. */
138
+ async function writeNew(file, bytes, mode) {
139
+ const handle = await fs.open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, mode);
140
+ try {
141
+ await handle.writeFile(bytes);
142
+ await handle.sync();
143
+ } finally { await handle.close(); }
144
+ }
145
+
146
+ /** Flushes a directory's entries where the OS lets one be opened. */
147
+ async function syncDirectory(dir) {
148
+ let handle;
149
+ try {
150
+ handle = await fs.open(dir, constants.O_RDONLY);
151
+ await handle.sync();
152
+ } catch { /* Windows cannot open a directory: nothing to flush there */ } finally { await handle?.close().catch(() => {}); }
153
+ }
154
+
155
+ async function writeFloor(dataDir, version) {
156
+ const temporary = join(dataDir, `${MINIMUM_VERSION_FILE}.${randomBytes(6).toString("hex")}`);
157
+ try {
158
+ await writeNew(temporary, Buffer.from(`${version}\n`), 0o600);
159
+ await fs.rename(temporary, join(dataDir, MINIMUM_VERSION_FILE));
160
+ await syncDirectory(dataDir);
161
+ } catch {
162
+ await fs.rm(temporary, { force: true }).catch(() => {});
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Brings the engine from its npm package into the engine folder, verified.
168
+ * Resolves to `{ status, minimumVersion? }`:
169
+ * "absent" no package for this machine (nothing is read from anywhere else);
170
+ * "current" the installation already is this package's engine, left alone;
171
+ * "imported" installed now;
172
+ * "refused" with `reason` "unverified", "unsafe-folder" (a folder above
173
+ * the data folder that other accounts can change), "wrong-machine"
174
+ * or "downgrade": nothing was changed.
175
+ * `minimumVersion` is what the installer is to hold the engine to, when
176
+ * there is one. Never throws.
177
+ *
178
+ * `platform`, `arch`, `env`, `keys`, `from` (where the package lookup starts),
179
+ * `dataFolder` (instead of the one `env` names), `windowsAcl` and `uid` are
180
+ * there for tests; the deck passes `platform`, `env` and `keys` only.
181
+ */
182
+ export async function importEngine({
183
+ platform = process.platform, arch = process.arch, env = process.env, keys, from, dataFolder, windowsAcl, uid,
184
+ } = {}) {
185
+ const name = enginePackageName(platform, arch);
186
+ const target = TARGETS[`${platform}-${arch}`];
187
+ const dataDir = dataFolder ?? deckDataDir(platform, env);
188
+ const destination = join(dataDir, "engine");
189
+ const gateOptions = { platform, windowsAcl, uid };
190
+ if (!name || !target || !Array.isArray(keys) || keys.length === 0) return { status: "absent" };
191
+ let staging = null;
192
+ let aside = null;
193
+ try {
194
+ const source = await findEnginePackage(name, from);
195
+ const floor = await readFloor(dataDir, gateOptions);
196
+ if (!source) return { status: "absent", ...(floor === undefined ? {} : { minimumVersion: floor }) };
197
+
198
+ // The package, checked as read: files owned by the user or root, no links,
199
+ // nobody but the owner and its group able to write (npm's usual umask).
200
+ const gate = await trustGate({ ...gateOptions, allowRoot: true, allowGroupWrite: true });
201
+ const sourceStat = await fs.lstat(source);
202
+ if (!sourceStat.isDirectory()) throw new Error("source");
203
+ await gate.directory(source, sourceStat);
204
+ const { data: manifestBytes } = await readTrusted(join(source, "manifest.json"), ENGINE_MANIFEST_MAX, gate);
205
+ const entry = signedEntry(manifestBytes, keys, target, platform);
206
+ const { data: executable } = await readTrusted(join(source, entry.file), entry.size, gate);
207
+ if (executable.length !== entry.size || createHash("sha256").update(executable).digest("hex") !== entry.sha256) throw new Error("digest");
208
+ if (!executableMatchesMachine(executable, platform, arch)) return { status: "refused", reason: "wrong-machine", ...(floor === undefined ? {} : { minimumVersion: floor }) };
209
+
210
+ // What is installed now, if it still verifies, and the floor it sets.
211
+ const installed = await verifyEngineInstallation({ directory: destination, publicKey: keys, windowsAcl, platform, arch }).catch(() => null);
212
+ const minimum = higher(floor, installed?.version);
213
+ if (minimum !== undefined && compareVersions(entry.version, minimum) < 0) {
214
+ return { status: "refused", reason: "downgrade", minimumVersion: minimum };
215
+ }
216
+ if (installed && installed.digest === entry.sha256 && installed.version === entry.version) {
217
+ return { status: "current", minimumVersion: higher(minimum, entry.version) };
218
+ }
219
+
220
+ // Staged beside the destination, so the final rename never crosses a volume.
221
+ await fs.mkdir(dataDir, { recursive: true, mode: 0o700 });
222
+ staging = await fs.mkdtemp(join(dataDir, "engine-import-"));
223
+ await fs.chmod(staging, 0o700).catch(() => {});
224
+ await writeNew(join(staging, entry.file), executable, 0o700);
225
+ await writeNew(join(staging, "manifest.json"), manifestBytes, 0o600);
226
+ await syncDirectory(staging);
227
+ await verifyEngineInstallation({ directory: staging, publicKey: keys, minimumVersion: minimum, windowsAcl, platform, arch });
228
+
229
+ // Swap: the old folder aside, the new one in, the result verified where
230
+ // it stands, the old one removed last. Any failure puts the old one back.
231
+ const previous = await fs.lstat(destination).then(() => true, (error) => {
232
+ if (error?.code === "ENOENT" || error?.code === "ENOTDIR") return false;
233
+ throw error;
234
+ });
235
+ if (previous) {
236
+ aside = join(dataDir, `engine-previous-${randomBytes(6).toString("hex")}`);
237
+ await fs.rename(destination, aside);
238
+ }
239
+ try {
240
+ await fs.rename(staging, destination);
241
+ staging = null;
242
+ await verifyEngineInstallation({ directory: destination, publicKey: keys, minimumVersion: minimum, windowsAcl, platform, arch });
243
+ } catch (error) {
244
+ if (staging === null) await fs.rm(destination, { recursive: true, force: true }).catch(() => {});
245
+ if (aside) {
246
+ // Put back; if even that fails the old folder stays where it is, never deleted.
247
+ const old = aside;
248
+ aside = null;
249
+ await fs.rename(old, destination).catch(() => {});
250
+ }
251
+ throw error;
252
+ }
253
+ await syncDirectory(dataDir);
254
+ if (aside) await fs.rm(aside, { recursive: true, force: true }).catch(() => {});
255
+ aside = null;
256
+ const kept = higher(minimum, entry.version);
257
+ await writeFloor(dataDir, kept);
258
+ return { status: "imported", minimumVersion: kept };
259
+ } catch (error) {
260
+ // Refused all the same; a folder above says so, so the page does not
261
+ // blame the signature (pro-engine-install.mjs UNSAFE_FOLDER).
262
+ return { status: "refused", reason: error?.code === UNSAFE_FOLDER ? UNSAFE_FOLDER : "unverified" };
263
+ } finally {
264
+ if (staging) await fs.rm(staging, { recursive: true, force: true }).catch(() => {});
265
+ if (aside) await fs.rm(aside, { recursive: true, force: true }).catch(() => {});
266
+ }
267
+ }
@@ -76,6 +76,12 @@ export function writesLogFor(payload) {
76
76
  return typeof sid !== "string" || sid === "" || !foreignSessions.has(sid);
77
77
  }
78
78
 
79
+ /** Whether a hook said another deck logs session `sid` (panel-provenance.mjs:
80
+ * that deck, not this one, knows whether its panel started it). */
81
+ export function isForeignSession(sid) {
82
+ return typeof sid === "string" && foreignSessions.has(sid);
83
+ }
84
+
79
85
  /**
80
86
  * Who else is holding the log this deck would empty, and whose it is to empty.
81
87
  *
@@ -313,7 +319,7 @@ async function openEventLog(persist) {
313
319
  _persistWritable = false;
314
320
  if (!persist) return;
315
321
  persistPath = resolve(persist);
316
- try { await mkdir(pdirname(persistPath), { recursive: true }); } catch {}
322
+ try { await mkdir(pdirname(persistPath), { recursive: true, mode: 0o700 }); } catch {}
317
323
  // Asked before the first event, so a log that cannot be written is a fact
318
324
  // the deck states rather than one the user discovers by pressing Restart.
319
325
  // The mkdir above is inside a bare try/catch, so its failure is already
@@ -10,6 +10,7 @@
10
10
  // module loads; index.mjs's routes import it from here. The bodies are
11
11
  // unchanged.
12
12
  import { noteToolAudit } from "./tool-audit.mjs";
13
+ import { panelProvenance } from "./panel-provenance.mjs";
13
14
  import { PRODUCT } from "./brand.mjs";
14
15
  import { createBlockNotifier } from "./block-notify.mjs";
15
16
  import { notify as osNotify } from "./browser-react.mjs";
@@ -43,7 +44,7 @@ import { outputWatch, touchSession } from "./session-tracking.mjs";
43
44
  import { usageDay } from "./usage-day.mjs";
44
45
  // What the deck learns about a session that its hooks never say, read off the
45
46
  // transcript and sent back through pushEvent — see session-enrichment.mjs.
46
- import { knownModelId, maybeResolveContext, maybeResolveModel, maybeResolveSessionName, maybeResolveUsage } from "./session-enrichment.mjs";
47
+ import { knownModelId, maybeAnnounceDeckName, maybeResolveContext, maybeResolveModel, maybeResolveSessionName, maybeResolveUsage } from "./session-enrichment.mjs";
47
48
  // The Codex half: a session's rollout, found by id — see codex-enrichment.mjs.
48
49
  import { maybeResolveCodex } from "./codex-enrichment.mjs";
49
50
  // The gate pushEvent asks before a transcript path is followed — see
@@ -58,6 +59,20 @@ import { connectEventSink } from "./event-sink.mjs";
58
59
  // emits until a request or a timer startServer arms asks it to.
59
60
  connectEventSink(pushEvent);
60
61
 
62
+ /**
63
+ * One more reader of every event, connected by whoever needs it: the
64
+ * account's session counts (session-counts.mjs), which keep the waiting and
65
+ * running numbers the status frame carries. A slot rather than an import, so
66
+ * a deck with the account off never loads the module and pays one null check
67
+ * per event. Handed the payload after the token is taken out, its stamp, and
68
+ * the options — a replay included, which the counts consume and activity does
69
+ * not. A tap that throws is the tap's problem, never the event's.
70
+ */
71
+ let eventTap = null;
72
+ export function connectEventTap(fn) {
73
+ eventTap = typeof fn === "function" ? fn : null;
74
+ }
75
+
61
76
  /**
62
77
  * Where a notification goes. The desktop app, while it is connected, raises it
63
78
  * itself — under its own name, icon and permission, with a click that opens its
@@ -129,6 +144,9 @@ export function pushEvent(raw, source, opts = {}) {
129
144
  const evt = admitEvent(raw, source, opts.receivedAt ?? Date.now());
130
145
  const seq = evt.seq;
131
146
  noteToolAudit(raw, source, opts);
147
+ // Which sessions the Command Panel started, read off the same stream: its own
148
+ // records, and the starts and ends it weighs them against (panel-provenance.mjs).
149
+ panelProvenance.observe(raw, source, evt.receivedAt, opts);
132
150
 
133
151
  // Does this event reach the log at all? Not on a replay (it came from
134
152
  // there), not when the hook told us another deck owns this session's log,
@@ -221,6 +239,9 @@ export function pushEvent(raw, source, opts = {}) {
221
239
  // Persisted history is not current activity. Fresh recovery snapshots are
222
240
  // current evidence even though they bypass replayed-tool accounting.
223
241
  if (shouldTrackActivity(raw, opts)) activity.note(raw, evt.receivedAt);
242
+ if (eventTap) {
243
+ try { eventTap(raw, evt.receivedAt, opts); } catch { /* the event goes on */ }
244
+ }
224
245
 
225
246
  if (persisting) {
226
247
  // Fire-and-forget append. JSONL = newline-delimited JSON, so the whole line
@@ -246,6 +267,13 @@ export function pushEvent(raw, source, opts = {}) {
246
267
  // dead session ids before the first live event even arrives.
247
268
  if (!opts.replay && raw && typeof raw === "object") touchSession(raw.session_id);
248
269
 
270
+ // A session the reader named in the deck is told its name once per run, on
271
+ // the first live word from it (internal #101, session-enrichment.mjs). Its
272
+ // own traffic only: a hook, or the rollout watcher's line.
273
+ if (!opts.replay && (source === "hook" || source === "codex") && raw && typeof raw === "object") {
274
+ maybeAnnounceDeckName(raw, source === "codex" || raw.provider === "codex" ? "codex" : "claude");
275
+ }
276
+
249
277
  // Kick off async transcript scans. Model and usage are both re-read
250
278
  // periodically (throttled to 2.5s per session) so the cost columns track
251
279
  // running totals as the session progresses and late subagent models still
@@ -0,0 +1,81 @@
1
+ // Ask a verified Ghostty surface to invoke Claude's empty-prompt background
2
+ // shortcut. Never send Enter or submit text: the prompt may contain a draft.
3
+ import { basename } from "node:path";
4
+ import { realpath } from "node:fs/promises";
5
+ import { adminClaudeBin } from "./claude-identity.mjs";
6
+ import { run } from "./exec.mjs";
7
+
8
+ const LOOKUP_OPTIONS = { timeout: 4000, maxBuffer: 1024 * 1024 };
9
+
10
+ const sendLeft = (app) => `
11
+ on run argv
12
+ set wantedPid to (item 1 of argv) as integer
13
+ set wantedTty to item 2 of argv
14
+ tell application ${JSON.stringify(app)}
15
+ set matched to missing value
16
+ repeat with surface in terminals
17
+ if (pid of surface) is wantedPid and (tty of surface) is wantedTty then
18
+ if matched is not missing value then return "ambiguous"
19
+ set matched to contents of surface
20
+ end if
21
+ end repeat
22
+ if matched is missing value then return "unmatched"
23
+ if (pid of matched) is not wantedPid or (tty of matched) is not wantedTty then return "changed"
24
+ if (perform action "csi:D" on matched) then return "sent"
25
+ return "failed"
26
+ end tell
27
+ end run
28
+ `;
29
+
30
+ // `check`: answer whether the move could be asked, by every lookup the real
31
+ // move makes, and stop before Ghostty is asked anything. The pane offers the
32
+ // move only where this says yes, so Linux, Windows and a Mac terminal other
33
+ // than Ghostty never show a button that can only fail.
34
+ export async function backgroundInGhostty(session, {
35
+ exec = run, resolvePath = realpath, cli = adminClaudeBin, platform = process.platform,
36
+ enabled = () => true, check = false,
37
+ } = {}) {
38
+ if (platform !== "darwin") return false;
39
+ const listed = await exec(cli(), ["agents", "--json", "--cwd", session.cwd], LOOKUP_OPTIONS);
40
+ if (!listed.ok) return false;
41
+ let agents;
42
+ try { agents = JSON.parse(listed.stdout); } catch { return false; }
43
+ if (!Array.isArray(agents)) return false;
44
+ const matches = agents.filter(agent => agent?.sessionId === session.sessionId && agent.kind === "interactive");
45
+ if (matches.length !== 1) return false;
46
+ const [agent] = matches;
47
+ if (!Number.isSafeInteger(agent.pid) || agent.pid < 2 || typeof agent.cwd !== "string") return false;
48
+ try { if (await resolvePath(agent.cwd) !== await resolvePath(session.cwd)) return false; }
49
+ catch { return false; }
50
+
51
+ const processInfo = await exec("/bin/ps", ["-ax", "-o", "pid=,ppid=,pgid=,tpgid=,tty=,comm="], LOOKUP_OPTIONS);
52
+ if (!processInfo.ok) return false;
53
+ const processes = new Map();
54
+ for (const line of processInfo.stdout.split("\n")) {
55
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+(.+)$/);
56
+ if (!match) continue;
57
+ const [, pid, parent, group, foreground, tty, command] = match;
58
+ processes.set(Number(pid), { pid: Number(pid), parent: Number(parent), group, foreground, tty, command });
59
+ }
60
+ const claude = processes.get(agent.pid);
61
+ if (!claude || basename(claude.command) !== "claude" || !/^ttys\d+$/.test(claude.tty) ||
62
+ claude.group !== claude.foreground) return false;
63
+ // The installed API can report the surface's login process even when a
64
+ // descendant owns the foreground group. Match that login PID and the TTY.
65
+ let surface = claude;
66
+ for (let depth = 0; depth < 8; depth++) {
67
+ const parent = processes.get(surface.parent);
68
+ if (!parent) return false;
69
+ const app = parent.command.match(/^(\/[^\r\n]+\/Ghostty\.app)\/Contents\/MacOS\/ghostty$/)?.[1];
70
+ if (app) {
71
+ if (!enabled()) return false;
72
+ if (check) return true;
73
+ const result = await exec("/usr/bin/osascript", ["-e", sendLeft(app), String(surface.pid), `/dev/${claude.tty}`],
74
+ { timeout: 30_000, maxBuffer: 8192 });
75
+ return result.ok && result.stdout.trim() === "sent";
76
+ }
77
+ if (parent.tty !== claude.tty) return false;
78
+ surface = parent;
79
+ }
80
+ return false;
81
+ }