ccdeck 3.82.4 → 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 (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-OQHT5qmS.js +1 -0
  7. package/dist/web/assets/AccountSection-BpIHPhF3.js +1 -0
  8. package/dist/web/assets/BrowserWatchModal-DBdt52v7.js +1 -0
  9. package/dist/web/assets/FeedbackConversations-BJjgXI0-.js +1 -0
  10. package/dist/web/assets/IntegrationModal-DQ0vEz4X.js +7 -0
  11. package/dist/web/assets/IntegrationSkeleton-JCPbqp96.js +1 -0
  12. package/dist/web/assets/RadioPanel-Be6AkrKl.js +1 -0
  13. package/dist/web/assets/StageShell-Dq0JOQhd.js +4 -0
  14. package/dist/web/assets/TrafficRadar-7jqJbhaK.js +8 -0
  15. package/dist/web/assets/UsageHistoryModal-ckawZGoe.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-40gNTTfq.js +361 -0
  20. package/dist/web/assets/app-BRjYF6oD.css +1 -0
  21. package/dist/web/assets/{index-B-l-VxLm.js → index-XIY3yFiN.js} +1 -1
  22. package/dist/web/assets/inspector-status-pane-BV_m7eBv.js +1 -0
  23. package/dist/web/assets/screens-9_ivqfcF.js +12 -0
  24. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  25. package/dist/web/assets/stage-board-NF_wgGRA.js +2 -0
  26. package/dist/web/assets/use-account-BUmI-A8e.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 +67 -0
  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,542 @@
1
+ // Finding tmux, and spelling a tmux command the one way the deck runs it.
2
+ //
3
+ // The terminal panel owns no pty. tmux does: the deck restarts itself on every
4
+ // self-update, and a terminal that died with the deck would be no terminal at
5
+ // all. So every byte the panel shows comes from a tmux server, and this module
6
+ // is the only place that knows which binary that is, which server a command
7
+ // goes to, and what environment the server is started with.
8
+ //
9
+ // THE DECK'S OWN SERVER, NEVER THE USER'S. `-L ccdeck` is a separate tmux
10
+ // server behind its own socket. Sessions the deck launches live there, so the
11
+ // user's `tmux ls` never lists them, the user's `kill-server` never takes them,
12
+ // and nothing the deck does to its sessions can resize, rename or kill one the
13
+ // user made. The one time the deck reaches into the user's own server — a
14
+ // session that was already running in their tmux — it names that server by its
15
+ // socket path, which is the other shape a socket has here.
16
+ //
17
+ // tmux 3.2 IS THE FLOOR. `refresh-client -f` (ignore-size, pause-after,
18
+ // read-only) arrived in 3.2, and without it the control-mode client can neither
19
+ // do flow control nor watch a pane in the user's tmux without shrinking their
20
+ // window to the panel's size. Ubuntu 22.04 ships 3.2a.
21
+ //
22
+ // REQUIRED, NOT SHIPPED. tmux publishes source only, so there is no release the
23
+ // deck could verify against a checksum the way it does claude-swap or uv, and
24
+ // building C on somebody's machine is not something a tool that "installs
25
+ // nothing" gets to do. A machine without tmux is told the one line that
26
+ // installs it for that platform — a fact about the machine, not an error.
27
+ import { execFile } from "node:child_process";
28
+ import { existsSync, readFileSync } from "node:fs";
29
+ import { pathLookup } from "./exec-spec.mjs";
30
+ // Every tmux client the deck starts is tracked like any other child, so a
31
+ // deck shut down mid-command reaps it. The tmux SERVER is not a child of
32
+ // anything here — it daemonises — which is the whole point of using it.
33
+ import { watchChild } from "./exec-children.mjs";
34
+ import { deckDataDir } from "./deck-home.mjs";
35
+ import { managedTmuxPath } from "./tmux-download.mjs";
36
+
37
+ /** The deck's own tmux server. Every deck-launched session lives here. */
38
+ export const DECK_SOCKET = Object.freeze({ name: "ccdeck" });
39
+
40
+ /** The oldest tmux the terminal works with, as [major, minor]. */
41
+ export const MIN_TMUX_VERSION = Object.freeze([3, 2]);
42
+
43
+ /** Point the deck at one particular tmux. A development and test knob, not a
44
+ * setting: it is how the suite reaches a tmux that is not on PATH, and it is
45
+ * deliberately absent from the README. Read through this constant the way
46
+ * CCDECK_HOME is in deck-home.mjs. */
47
+ const TMUX_ENV = "CCDECK_TMUX";
48
+
49
+ /** Where tmux lives when PATH does not say. Homebrew on Apple silicon, then
50
+ * Homebrew on Intel and most hand-built installs, then the distribution's.
51
+ * A deck started from a login item or a desktop shortcut often has a PATH
52
+ * that never sourced a shell rc, which is exactly when these matter. */
53
+ const KNOWN_PLACES = ["/opt/homebrew/bin/tmux", "/usr/local/bin/tmux", "/usr/bin/tmux"];
54
+
55
+ /** How long "no usable tmux" is believed. An answer that tmux is present is
56
+ * kept until resetTmuxCache; an answer that it is missing is not, because the
57
+ * panel's own advice is to go and install it — and the click after that
58
+ * install has to see it without a deck restart. */
59
+ const MISS_TTL_MS = 10_000;
60
+
61
+ /** The line shown when no install command is known for this machine. */
62
+ const NEUTRAL_INSTALL = "Install tmux 3.2 or newer with your system's package manager.";
63
+
64
+ /** Linux install lines, matched against os-release ID and then ID_LIKE, so a
65
+ * derivative (Mint, Rocky, Manjaro) gets its parent's command. */
66
+ const LINUX_INSTALL = [
67
+ ["sudo apt install tmux", ["debian", "ubuntu", "linuxmint", "pop", "raspbian", "elementary"]],
68
+ ["sudo dnf install tmux", ["fedora", "rhel", "centos", "rocky", "almalinux", "amzn"]],
69
+ ["sudo pacman -S tmux", ["arch", "manjaro", "endeavouros"]],
70
+ ["sudo zypper install tmux", ["opensuse", "suse", "sles", "opensuse-leap", "opensuse-tumbleweed"]],
71
+ ["sudo apk add tmux", ["alpine"]],
72
+ ];
73
+
74
+ /**
75
+ * Variables a deck-launched agent must not inherit because they describe the
76
+ * process that started the DECK, not the session being started.
77
+ *
78
+ * Measured, not guessed. Claude Code 2.1.294 stamps every child it runs with
79
+ * CLAUDECODE, CLAUDE_CODE_SESSION_ID, CLAUDE_CODE_CHILD_SESSION,
80
+ * CLAUDE_CODE_SESSION_ATTENDED and CLAUDE_PID (and lists the rest of these
81
+ * among the variables it strips from its own shell snapshots). A deck started
82
+ * from inside a Claude session — `npx ccdeck` typed into its Bash tool, which
83
+ * is how an agent runs the deck — carries all of them, and the tmux server
84
+ * would hand them to every agent it launched: a Claude that takes itself for a
85
+ * child of a conversation it has nothing to do with (2.1.294 consults
86
+ * CLAUDE_CODE_CHILD_SESSION when deciding whether to keep prompt history, for
87
+ * one) and is handed that conversation's id, pid and messaging socket. The two
88
+ * Codex names are its sandbox markers, which a Codex started under them reads
89
+ * as being inside a sandbox.
90
+ *
91
+ * BY NAME, NOT BY PREFIX. CLAUDE_CODE_USE_BEDROCK, CLAUDE_CONFIG_DIR and
92
+ * CODEX_HOME are the user's own settings, and the launched agent needs every
93
+ * one of them.
94
+ */
95
+ const INHERITED_AGENT_MARKERS = [
96
+ "CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_SESSION_ID", "CLAUDE_CODE_CHILD_SESSION",
97
+ "CLAUDE_CODE_SESSION_ATTENDED", "CLAUDE_PID", "CLAUDE_CODE_EXECPATH", "CLAUDE_EFFORT",
98
+ "CLAUDE_CODE_INVOKED_SKILLS", "CLAUDE_CODE_MESSAGING_SOCKET", "CLAUDE_CODE_AGENT", "CLAUDE_JOB_DIR",
99
+ "CLAUDE_AGENTS_AUTO_RELAUNCHED_AT", "AI_AGENT", "TRACEPARENT",
100
+ "CODEX_SANDBOX", "CODEX_SANDBOX_NETWORK_DISABLED",
101
+ ];
102
+ const DROPPED_NAMES = new Set(["TMUX", "TMUX_PANE", ...INHERITED_AGENT_MARKERS]);
103
+ const DROPPED_PREFIXES = ["AGENTS_DECK_", "AGENT_DAG_", "CCDECK_"];
104
+
105
+ /**
106
+ * The environment a tmux client — and so, the first time, the deck's tmux
107
+ * server — is started with: the deck's own, minus what belongs to the deck.
108
+ *
109
+ * The server keeps the environment of the client that started it for its whole
110
+ * life and hands it to every pane, so whatever is here is what a launched agent
111
+ * sees. Three kinds of thing come out:
112
+ *
113
+ * - The deck's own variables, AGENTS_DECK_*, AGENT_DAG_* and CCDECK_*. They
114
+ * configure this deck, not the agent, and one of them is actively harmful:
115
+ * the hook goes silent under AGENTS_DECK_INTERNAL=1 (that is how the quota
116
+ * probe keeps its own runs off the board), so a leak would launch a session
117
+ * the board could never show.
118
+ * - TMUX and TMUX_PANE, so a deck started from inside the user's tmux does
119
+ * not start its server as a nested client of theirs.
120
+ * - The agent-session markers above.
121
+ *
122
+ * Everything else stays, PATH first among it: the agent has to find node, git
123
+ * and whatever else the user's shell would have given it.
124
+ */
125
+ export function tmuxEnv(env = process.env) {
126
+ const out = {};
127
+ for (const [key, value] of Object.entries(env ?? {})) {
128
+ if (value === undefined) continue;
129
+ if (DROPPED_NAMES.has(key) || DROPPED_PREFIXES.some(p => key.startsWith(p))) continue;
130
+ out[key] = value;
131
+ }
132
+ return out;
133
+ }
134
+
135
+ /**
136
+ * `tmux -V` read as [major, minor], or null when it does not say.
137
+ *
138
+ * "tmux 3.6a" and "tmux 3.2a" carry a letter for patch releases; "tmux
139
+ * next-3.6" is a build from the development branch on its way to the number
140
+ * it names: newer than every release before it, and read as that number.
141
+ * "tmux openbsd-7.4" is OpenBSD's base-system tmux, which
142
+ * follows upstream closely but numbers itself after the OS — reading 7.4 out of
143
+ * it as a tmux version would be a guess that happens to pass, so it reads as
144
+ * unknown instead and findTmux lets it through with a warning.
145
+ */
146
+ export function parseTmuxVersion(raw) {
147
+ const m = /^tmux\s+(?:next-)?(\d+)\.(\d+)/.exec(String(raw ?? "").trim());
148
+ return m ? [Number(m[1]), Number(m[2])] : null;
149
+ }
150
+
151
+ const atLeast = (v, min) => v[0] > min[0] || (v[0] === min[0] && v[1] >= min[1]);
152
+
153
+ /**
154
+ * The one line that installs tmux on this platform, or undefined where the
155
+ * terminal is not offered at all (Windows has no tmux).
156
+ *
157
+ * `osRelease` is the text of /etc/os-release, passed in so every branch can be
158
+ * checked from any machine.
159
+ */
160
+ export function tmuxInstallLine(platform = process.platform, osRelease = "") {
161
+ if (platform === "win32") return undefined;
162
+ if (platform === "darwin") return "brew install tmux";
163
+ if (platform === "freebsd") return "sudo pkg install tmux";
164
+ if (platform === "linux") {
165
+ const fields = Object.fromEntries(String(osRelease ?? "").split("\n").map(line => {
166
+ const i = line.indexOf("=");
167
+ return i < 0 ? ["", ""] : [line.slice(0, i).trim(), line.slice(i + 1).trim().replace(/^["']|["']$/g, "")];
168
+ }));
169
+ const ids = [fields.ID, ...String(fields.ID_LIKE ?? "").split(/\s+/)]
170
+ .filter(Boolean).map(id => id.toLowerCase());
171
+ for (const id of ids) {
172
+ const hit = LINUX_INSTALL.find(([, family]) => family.includes(id));
173
+ if (hit) return hit[0];
174
+ }
175
+ }
176
+ return NEUTRAL_INSTALL;
177
+ }
178
+
179
+ /**
180
+ * Every tmux on this machine worth asking, in the order to ask them, as
181
+ * absolute paths that exist.
182
+ *
183
+ * CCDECK_TMUX, when set, is the ONLY candidate. Whoever set it meant that tmux;
184
+ * quietly falling through to another one when it is wrong would hand them a
185
+ * passing run against a binary they did not choose — the opposite of why the
186
+ * variable exists. Otherwise: `tmux` on PATH, then the known install places.
187
+ */
188
+ export function tmuxCandidates({
189
+ env = process.env, platform = process.platform, exists = existsSync,
190
+ managed = managedTmuxPath(deckDataDir(platform, env)),
191
+ } = {}) {
192
+ const pathEnv = env.PATH ?? env.Path ?? "";
193
+ const located = (bin) => {
194
+ if (!/[\\/]/.test(bin)) return pathLookup(bin, platform, { pathEnv, exists });
195
+ try { return exists(bin) ? bin : null; } catch { return null; }
196
+ };
197
+ const forced = env[TMUX_ENV]?.trim();
198
+ if (forced) {
199
+ const at = located(forced);
200
+ return at ? [at] : [];
201
+ }
202
+ const out = [];
203
+ // ccdeck's own build last (tmux-download.mjs): a tmux the user installed
204
+ // is the one they chose, and theirs wins whenever it is new enough.
205
+ for (const bin of ["tmux", ...KNOWN_PLACES, ...(managed ? [managed] : [])]) {
206
+ const at = located(bin);
207
+ if (at && !out.includes(at)) out.push(at);
208
+ }
209
+ return out;
210
+ }
211
+
212
+ let cached = null;
213
+
214
+ /** Forget the remembered answer. For tests, and for nothing else. */
215
+ export function resetTmuxCache() {
216
+ cached = null;
217
+ }
218
+
219
+ /**
220
+ * Which tmux the terminal runs, and whether it is good enough.
221
+ *
222
+ * Answers `{ ok: true, path, version: [major, minor], raw }`, plus
223
+ * `warning: "unknown-version"` (and `version: null`) for a tmux whose `-V` does
224
+ * not carry a version this can read. Otherwise `{ ok: false, reason }` with
225
+ * reason `missing`, `too-old` (with the path, version and raw text of the
226
+ * first one found) or `unsupported-platform`, and — except on Windows — an
227
+ * `install` line for this machine.
228
+ *
229
+ * Every candidate is asked before the answer is `too-old`. A Mac with an old
230
+ * tmux first on PATH and a current Homebrew one behind it has a tmux that
231
+ * works, and saying otherwise would send its owner off to install something
232
+ * they already have.
233
+ *
234
+ * A candidate that exists but will not run `-V` is skipped as if absent. Never
235
+ * rejects.
236
+ *
237
+ * Remembered: a usable answer until resetTmuxCache, a missing one for ten
238
+ * seconds (see MISS_TTL_MS), and concurrent callers share one probe. The
239
+ * memory is keyed on the inputs that decide the answer — platform, CCDECK_TMUX,
240
+ * PATH — and on the very `run`, `exists` and `readFile` it was found with, so
241
+ * a case in the suite that injects fakes is never answered from another
242
+ * case's.
243
+ *
244
+ * `run(file, args, { env })` resolves `{ code, stdout }`; the real one is
245
+ * execFile with a three-second deadline.
246
+ */
247
+ export function findTmux({
248
+ env = process.env, platform = process.platform,
249
+ run = runVersion, exists = existsSync, readFile = readText, now = Date.now,
250
+ } = {}) {
251
+ const key = [platform, env[TMUX_ENV] ?? "", env.PATH ?? env.Path ?? ""].join("\0");
252
+ const same = cached && cached.key === key && cached.run === run && cached.exists === exists && cached.readFile === readFile;
253
+ if (same && (cached.ok || now() - cached.at < MISS_TTL_MS)) return cached.promise;
254
+ const promise = probeTmux({ env, platform, run, exists, readFile });
255
+ const entry = { key, run, exists, readFile, at: now(), ok: false, promise };
256
+ cached = entry;
257
+ promise.then(r => { entry.ok = r.ok; });
258
+ return promise;
259
+ }
260
+
261
+ const runVersion = (file, args, { env } = {}) => execTmux(file, args, { timeoutMs: 3000, env: tmuxEnv(env) });
262
+ const readText = (p) => readFileSync(p, "utf8");
263
+
264
+ async function probeTmux({ env, platform, run, exists, readFile }) {
265
+ if (platform === "win32") return Object.freeze({ ok: false, reason: "unsupported-platform" });
266
+ let tooOld = null;
267
+ for (const path of tmuxCandidates({ env, platform, exists })) {
268
+ let r;
269
+ try { r = await run(path, ["-V"], { env }); } catch { continue; }
270
+ if (!r || r.code !== 0) continue;
271
+ const raw = String(r.stdout ?? "").trim();
272
+ const version = parseTmuxVersion(raw);
273
+ if (!version) return Object.freeze({ ok: true, path, version: null, raw, warning: "unknown-version" });
274
+ if (atLeast(version, MIN_TMUX_VERSION)) return Object.freeze({ ok: true, path, version: Object.freeze(version), raw });
275
+ tooOld ??= { ok: false, reason: "too-old", path, version: Object.freeze(version), raw };
276
+ }
277
+ const install = tmuxInstallLine(platform, platform === "linux" ? osReleaseText(readFile) : "");
278
+ return Object.freeze(tooOld ? { ...tooOld, install } : { ok: false, reason: "missing", install });
279
+ }
280
+
281
+ /** /etc/os-release, or the copy systemd keeps when /etc has none. */
282
+ function osReleaseText(readFile) {
283
+ for (const p of ["/etc/os-release", "/usr/lib/os-release"]) {
284
+ try { return String(readFile(p) ?? ""); } catch { /* try the next */ }
285
+ }
286
+ return "";
287
+ }
288
+
289
+ /**
290
+ * The argv for one tmux invocation against one server: the binary, `-u`, the
291
+ * socket, then `args` exactly as given.
292
+ *
293
+ * `tmux` is a path or findTmux's answer. `socket` is `{ name }` for a server in
294
+ * tmux's own socket directory (`-L`), `{ path }` for one named by its socket
295
+ * file (`-S`), or null for the user's default server.
296
+ *
297
+ * WHY `-u` ON EVERY CALL. A tmux client decides whether it may print UTF-8 from
298
+ * LC_ALL, LC_CTYPE and LANG, and a deck started by a login item or a service
299
+ * manager often has none of them. Such a client prints every non-ASCII
300
+ * character as `_`: measured on 3.6, a session started in `~/проект 日本`
301
+ * listed its directory as `~/______ ____`. `-u` says the reader handles UTF-8,
302
+ * which this one always does. It changes nothing on the server.
303
+ */
304
+ export function tmuxCommand(tmux, socket, args = []) {
305
+ const bin = typeof tmux === "string" ? tmux : tmux?.path;
306
+ if (typeof bin !== "string" || bin === "") throw new TypeError("tmuxCommand needs the tmux binary");
307
+ return [bin, "-u", ...socketFlags(socket), ...args.map(String)];
308
+ }
309
+
310
+ function socketFlags(socket) {
311
+ if (socket == null) return [];
312
+ if (typeof socket.name === "string" && socket.name !== "") {
313
+ // -L names a file inside tmux's socket directory; a separator would point
314
+ // it somewhere else entirely.
315
+ if (/[\\/]/.test(socket.name)) throw new TypeError("a tmux socket name cannot contain a path separator");
316
+ return ["-L", socket.name];
317
+ }
318
+ if (typeof socket.path === "string" && socket.path !== "") return ["-S", socket.path];
319
+ throw new TypeError("a tmux socket is { name } or { path }");
320
+ }
321
+
322
+ /**
323
+ * One literal argument, safe from tmux's own command parser.
324
+ *
325
+ * tmux splits its argv into commands on any argument that ENDS in `;`, not
326
+ * only on a lone `;` — so a project folder named `notes;` passed as `-c
327
+ * notes;` ends the command there, and what follows is parsed as a new command.
328
+ * Measured on 3.6: the whole invocation then fails to parse, and the client
329
+ * reports "error connecting" as though no server existed. A trailing `\;` is
330
+ * tmux's escape for a literal one.
331
+ */
332
+ export function tmuxArg(value) {
333
+ const s = String(value);
334
+ return s.endsWith(";") ? `${s.slice(0, -1)}\\;` : s;
335
+ }
336
+
337
+ /**
338
+ * Several tmux commands as one invocation's arguments: every argument escaped
339
+ * with tmuxArg, the commands joined by lone `;` tokens.
340
+ *
341
+ * One invocation rather than several because tmux runs a sequence back to back
342
+ * in one turn of its event loop. A pane whose program exits at once — a binary
343
+ * that is not there — is reaped only on a later turn, so options set in the
344
+ * same sequence as new-session are always in place before tmux decides what to
345
+ * do with the corpse. Set from a second invocation, remain-on-exit can arrive
346
+ * after the session it was meant for has already been destroyed.
347
+ */
348
+ export function tmuxSequence(commands) {
349
+ const out = [];
350
+ commands.forEach((cmd, i) => {
351
+ if (i > 0) out.push(";");
352
+ for (const arg of cmd) out.push(tmuxArg(arg));
353
+ });
354
+ return out;
355
+ }
356
+
357
+ /**
358
+ * A literal value for an argument tmux expands as a format, such as
359
+ * new-session's `-c`.
360
+ *
361
+ * `-c` is expanded before it is used, so a folder named `x#{pane_id}` is
362
+ * opened as `x%0` — and `#(...)` in a format RUNS a shell command. Measured on
363
+ * 3.6: a directory with `#{pane_id}` in its name made tmux fall back to $HOME.
364
+ * `##` is a literal `#`.
365
+ */
366
+ export function tmuxFormatLiteral(value) {
367
+ return String(value).replaceAll("#", "##");
368
+ }
369
+
370
+ /**
371
+ * The command a pane runs, in the form tmux executes directly.
372
+ *
373
+ * tmux runs a command given as two or more arguments with execvp, and one given
374
+ * as a SINGLE argument through `default-shell -c` — the user's login shell,
375
+ * which re-splits it on spaces and reads its metacharacters, and may be fish.
376
+ * So a lone `/Volumes/My Disk/bin/codex` would not start, and the same argv
377
+ * would mean different things on different machines. A single argument is
378
+ * handed to /bin/sh as `$0` instead and exec'd from there: no word splitting,
379
+ * no expansion, and the agent replaces sh, so the pane's pid is the agent's.
380
+ */
381
+ export function paneArgv(argv) {
382
+ return argv.length === 1 ? ["/bin/sh", "-c", 'exec "$0"', argv[0]] : [...argv];
383
+ }
384
+
385
+ /**
386
+ * Whether a failed tmux call failed only because there is no server (or no
387
+ * session) to answer it, which for every caller here means "nothing is
388
+ * running" rather than "something is wrong".
389
+ */
390
+ export function tmuxHasNoServer(stderr) {
391
+ return /no server running|error connecting to|server exited unexpectedly|^no sessions/im.test(String(stderr ?? ""));
392
+ }
393
+
394
+ /**
395
+ * Whether a tmux client run through execFile with a `timeout` outran it. The
396
+ * kill alone says so: tmux's client catches the SIGTERM and exits 0 with
397
+ * nothing printed, so a stalled server (stopped, swapped out) would otherwise
398
+ * read as a clean, empty answer: no sessions, no panes. Measured on tmux 3.8.
399
+ */
400
+ export function tmuxTimedOut(child, err) {
401
+ return Boolean(err?.killed || child?.killed);
402
+ }
403
+
404
+ /**
405
+ * Run one tmux invocation and collect its output: `{ ok, code, stdout, stderr }`.
406
+ *
407
+ * execFile with an argument vector, never a shell — a project path is an
408
+ * argument, not a command line. `code` is the exit status, or a string when
409
+ * there was none: "ETIMEDOUT" for a client that outran `timeoutMs`, a spawn
410
+ * error's own code such as "ENOENT". Never rejects; every caller treats a
411
+ * failed tmux as a state to report.
412
+ *
413
+ * `env` is the deck's environment and is passed through tmuxEnv here, on every
414
+ * call, rather than at the one call that happens to start the server: which
415
+ * call that is depends on what ran before it, and a server started dirty stays
416
+ * dirty for its whole life.
417
+ */
418
+ export function runTmux(tmux, socket, args, { timeoutMs = 3000, env = process.env, scope = null } = {}) {
419
+ const [file, ...argv] = tmuxCommand(tmux, socket, args);
420
+ // `scope` is serverScope's answer: the same tmux, started by systemd-run in
421
+ // a scope of its own.
422
+ if (Array.isArray(scope) && scope.length) return execTmux(scope[0], [...scope.slice(1), file, ...argv], { timeoutMs, env: tmuxEnv(env) });
423
+ return execTmux(file, argv, { timeoutMs, env: tmuxEnv(env) });
424
+ }
425
+
426
+ // ── a server that outlives the deck's service ──────────────────────────────
427
+ //
428
+ // On Linux the login item is a systemd user service (login-service.mjs), and
429
+ // systemd stops a service by killing everything in its cgroup — KillMode's
430
+ // default, control-group. A tmux server forked by the deck worker daemonizes,
431
+ // but daemonizing does not leave a cgroup: it stays in the service's, so
432
+ // `ccdeck --stop`, `systemctl --user stop` or the crash ceiling would kill the
433
+ // server and every agent running in it, mid-turn. (A restart or an upgrade is
434
+ // safe: the supervisor stays up through those.) macOS is not affected — tmux's
435
+ // setsid() is enough to escape launchd's process-group kill.
436
+ //
437
+ // So the call that may START the deck's server runs through
438
+ // `systemd-run --user --scope`, which puts the client — and the server it
439
+ // forks — in a transient scope of their own, outside the service. Only when
440
+ // the deck is in a service at all: a deck started from a terminal is in that
441
+ // terminal's scope, which nothing stops on the deck's behalf.
442
+
443
+ /** The cgroup systemd tracks this process in, from a /proc/self/cgroup text:
444
+ * its own named hierarchy where there is one (a v1 or hybrid host, whose
445
+ * unified line may say only "/"), else the unified line. Pure. */
446
+ export function cgroupPath(text) {
447
+ const lines = String(text ?? "").split("\n");
448
+ const named = lines.find(l => /^\d+:name=systemd:/.test(l));
449
+ if (named) return named.replace(/^\d+:name=systemd:/, "").trim();
450
+ const unified = lines.find(l => l.startsWith("0::"));
451
+ return unified ? unified.slice(3).trim() : "";
452
+ }
453
+
454
+ /** systemd-run's arguments before the command it starts in a new scope.
455
+ * `--expand-environment=no` keeps that command as the deck wrote it: the
456
+ * systemd-run on Ubuntu 26.04 (systemd 259) expands `$NAME` and `${NAME}` in
457
+ * a scope's command line, as ExecStart= does, from systemd-run's own
458
+ * environment — a name it does not have, or one that is not a valid name,
459
+ * becomes an empty string — so a `$` in an agent's arguments or in a
460
+ * folder's name reached tmux rewritten. Ubuntu 24.04's (255) left a scope's
461
+ * command alone. */
462
+ export const SCOPE_ARGS = Object.freeze(["--user", "--scope", "--collect", "--quiet", "--expand-environment=no", "--description=ccdeck terminal sessions", "--"]);
463
+
464
+ /** The same without `--expand-environment=no`, for a systemd-run older than
465
+ * 254, which refuses the option and does not expand a scope's command. */
466
+ export const LEGACY_SCOPE_ARGS = Object.freeze(SCOPE_ARGS.filter(a => a !== "--expand-environment=no"));
467
+
468
+ const scopeProbes = new Map();
469
+
470
+ /** Whether systemd-run starts a scope here with `args` — a service under the
471
+ * SYSTEM manager has no user bus to ask, a minimal container has no systemd
472
+ * behind its systemd-run, and one older than 254 refuses SCOPE_ARGS. Asked
473
+ * with `true`. */
474
+ function probeScope(bin, env, args) {
475
+ return new Promise((resolve) => {
476
+ try {
477
+ execFile(bin, [...args, "true"], { env: tmuxEnv(env), timeout: 5000, windowsHide: true }, (err) => resolve(!err));
478
+ } catch {
479
+ resolve(false);
480
+ }
481
+ });
482
+ }
483
+
484
+ /** The first of SCOPE_ARGS and LEGACY_SCOPE_ARGS this systemd-run starts a
485
+ * scope with, or null when it starts none. */
486
+ async function scopeArgsFor(bin, env, probe) {
487
+ for (const args of [SCOPE_ARGS, LEGACY_SCOPE_ARGS]) {
488
+ let ok = false;
489
+ try { ok = await probe(bin, env, args); } catch { ok = false; }
490
+ if (ok) return args;
491
+ }
492
+ return null;
493
+ }
494
+
495
+ /**
496
+ * The prefix that starts a tmux server outside the deck's systemd service —
497
+ * `[systemd-run, ...SCOPE_ARGS]`, or LEGACY_SCOPE_ARGS for an older
498
+ * systemd-run — or null where none is needed or none works: not Linux, not
499
+ * in a `.service` cgroup, no systemd-run, or one that cannot start a scope.
500
+ * Asked once per binary. Never rejects; null means "run tmux as it is".
501
+ */
502
+ export async function serverScope({
503
+ platform = process.platform, env = process.env,
504
+ readCgroup = () => readFileSync("/proc/self/cgroup", "utf8"),
505
+ exists = existsSync, probe = probeScope,
506
+ } = {}) {
507
+ if (platform !== "linux") return null;
508
+ let path = "";
509
+ try { path = cgroupPath(readCgroup()); } catch { return null; }
510
+ if (!/\.service$/.test(path)) return null;
511
+ const bin = pathLookup("systemd-run", platform, { pathEnv: env.PATH ?? "", exists })
512
+ ?? ["/usr/bin/systemd-run", "/bin/systemd-run"].find(p => exists(p)) ?? null;
513
+ if (!bin) return null;
514
+ if (!scopeProbes.has(bin)) scopeProbes.set(bin, scopeArgsFor(bin, env, probe));
515
+ const args = await scopeProbes.get(bin);
516
+ return args ? [bin, ...args] : null;
517
+ }
518
+
519
+ /** For tests: forget what systemd-run answered. */
520
+ export function resetServerScope() { scopeProbes.clear(); }
521
+
522
+ function execTmux(file, argv, { timeoutMs, env }) {
523
+ return new Promise((resolve) => {
524
+ const settle = (code, stdout, stderr) =>
525
+ resolve({ ok: code === 0, code, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
526
+ let child;
527
+ try {
528
+ child = execFile(file, argv, { env, timeout: timeoutMs, maxBuffer: 4 << 20, windowsHide: true }, (err, stdout, stderr) => {
529
+ if (!err && tmuxTimedOut(child)) return settle("ETIMEDOUT", stdout, stderr || "tmux did not answer in time");
530
+ if (!err) return settle(0, stdout, stderr);
531
+ const code = typeof err.code === "number" || typeof err.code === "string" ? err.code
532
+ : err.killed ? "ETIMEDOUT"
533
+ : err.signal ?? "EFAIL";
534
+ settle(code, stdout, stderr || err.message);
535
+ });
536
+ } catch (err) {
537
+ settle(err?.code ?? "EFAIL", "", String(err?.message ?? err));
538
+ return;
539
+ }
540
+ watchChild(child);
541
+ });
542
+ }
@@ -13,6 +13,45 @@ import { HOOK_TOKEN } from "./request-gates.mjs";
13
13
  // response and get debugged as one.
14
14
  const TOKEN_REDACTED = "[redacted: ccdeck token]";
15
15
 
16
+ /** What the account's device token is replaced with — the same visible marker,
17
+ * naming which secret it was. */
18
+ const DEVICE_TOKEN_REDACTED = "[redacted: ccdeck device token]";
19
+
20
+ /**
21
+ * The account's device token, while this deck holds one (account-service.mjs
22
+ * sets it on connect, on every rotation and on restart, and clears it on
23
+ * disconnect). It is a bearer credential to the user's account, and an agent
24
+ * that `cat`s account.json on a machine without a keychain puts it into the
25
+ * ring exactly the way the discovery file's token gets there — so it is taken
26
+ * out at the same door.
27
+ *
28
+ * Empty unless the account is on and connected: a deck with the account off
29
+ * never sets it, and the walk below then costs what it always did.
30
+ */
31
+ let deviceTokens = [];
32
+
33
+ /** The device tokens to redact from now on — the live one, and the one a
34
+ * rotation is handing over to while both are valid. Anything that is not a
35
+ * long enough string is ignored, so a mistake cannot make every event match. */
36
+ export function setDeviceTokens(tokens) {
37
+ deviceTokens = (Array.isArray(tokens) ? tokens : []).filter(t => typeof t === "string" && t.length >= 20);
38
+ }
39
+
40
+ /** One string with every secret this deck holds taken out. */
41
+ function scrubString(v, token) {
42
+ let out = v.includes(token) ? v.replaceAll(token, TOKEN_REDACTED) : v;
43
+ for (const t of deviceTokens) if (out.includes(t)) out = out.replaceAll(t, DEVICE_TOKEN_REDACTED);
44
+ return out;
45
+ }
46
+
47
+ /** Whether a string holds any of them — the walk's cheap test, which allocates
48
+ * nothing. */
49
+ function holdsSecret(v, token) {
50
+ if (v.includes(token)) return true;
51
+ for (const t of deviceTokens) if (v.includes(t)) return true;
52
+ return false;
53
+ }
54
+
16
55
  /**
17
56
  * Take the deck's own token back out of an event, before anything stores it.
18
57
  *
@@ -84,7 +123,7 @@ function redactDeckToken(raw) {
84
123
  // HOOK_TOKEN is request-gates.mjs's, and an import is bound before this
85
124
  // module's body runs, so it is set long before the first event arrives.
86
125
  const token = HOOK_TOKEN;
87
- if (typeof raw === "string") return raw.includes(token) ? raw.replaceAll(token, TOKEN_REDACTED) : raw;
126
+ if (typeof raw === "string") return holdsSecret(raw, token) ? scrubString(raw, token) : raw;
88
127
  if (raw === null || typeof raw !== "object") return raw;
89
128
 
90
129
  const stack = [raw];
@@ -97,7 +136,7 @@ function redactDeckToken(raw) {
97
136
  for (let i = 0; i < node.length; i++) {
98
137
  const v = node[i];
99
138
  if (typeof v === "string") {
100
- if (v.includes(token)) node[i] = v.replaceAll(token, TOKEN_REDACTED);
139
+ if (holdsSecret(v, token)) node[i] = scrubString(v, token);
101
140
  } else if (v !== null && typeof v === "object") stack.push(v);
102
141
  }
103
142
  } else {
@@ -110,7 +149,7 @@ function redactDeckToken(raw) {
110
149
  for (const k in node) {
111
150
  const v = node[k];
112
151
  if (typeof v === "string") {
113
- if (v.includes(token)) node[k] = v.replaceAll(token, TOKEN_REDACTED);
152
+ if (holdsSecret(v, token)) node[k] = scrubString(v, token);
114
153
  } else if (v !== null && typeof v === "object") stack.push(v);
115
154
  }
116
155
  }