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,759 @@
1
+ // The tmux sessions the deck launches, and how it finds them again.
2
+ //
3
+ // A session the deck starts — a new Claude or Codex, or one reopened here with
4
+ // `--resume` — runs on the deck's own tmux server (DECK_SOCKET in tmux.mjs)
5
+ // under a name only the deck uses, and carries four tmux user options that say
6
+ // what it is: which agent session it holds, which agent, how it was started,
7
+ // and the project folder. Those options are the whole record. The deck keeps no
8
+ // file of its own about what it launched, so after a restart, an upgrade or a
9
+ // crash there is nothing to disagree with what tmux says is running — the
10
+ // listing below IS the state.
11
+ //
12
+ // The same server also holds the small wrappers that reach Claude's own
13
+ // background sessions: `claude attach <id>` running in a deck pane, named
14
+ // `ccdeck-att-<first 8 of the id>` so the deck reuses one rather than stacking
15
+ // a second attach onto the same session.
16
+ //
17
+ // REMAIN-ON-EXIT. When an agent exits, its pane stays, dead, holding the last
18
+ // frame it drew. That frame is evidence — the panel shows it frozen under
19
+ // "session ended" — and tmux's own "Pane is dead" banner is switched off so
20
+ // the frame is the agent's, not a line scrolled up under tmux's caption.
21
+ import { randomBytes, randomUUID } from "node:crypto";
22
+ import { stat } from "node:fs/promises";
23
+ import { existsSync } from "node:fs";
24
+ import { homedir } from "node:os";
25
+ import { isAbsolute, posix as posixPath } from "node:path";
26
+ import { setTimeout as delay } from "node:timers/promises";
27
+ import { pathLookup } from "./exec-spec.mjs";
28
+ // The one answer to "which claude" — AGENTS_DECK_CLAUDE first, then PATH, then
29
+ // the places its installers put it (#553, #570). Not decided again here.
30
+ import { adminClaudeBin } from "./claude-identity.mjs";
31
+ import {
32
+ DECK_SOCKET, findTmux, paneArgv, runTmux, serverScope, tmuxFormatLiteral, tmuxHasNoServer, tmuxSequence,
33
+ } from "./tmux.mjs";
34
+
35
+ /** The agents the deck can launch. */
36
+ export const AGENTS = Object.freeze(["claude", "codex"]);
37
+
38
+ /** How a deck session came to be: started fresh, reopened from its id, or a
39
+ * wrapper attached to a Claude background session. */
40
+ export const KINDS = Object.freeze(["launch", "resume", "attach"]);
41
+
42
+ /** The tmux user options a deck session carries. */
43
+ export const SESSION_OPTIONS = Object.freeze({
44
+ session: "@ccdeck-session",
45
+ agent: "@ccdeck-agent",
46
+ kind: "@ccdeck-kind",
47
+ cwd: "@ccdeck-cwd",
48
+ launch: "@ccdeck-launch",
49
+ });
50
+
51
+ /** The default size, and the clamp the panel's own resizes are held to. */
52
+ const COLS = Object.freeze({ min: 20, max: 500, fallback: 120 });
53
+ const ROWS = Object.freeze({ min: 5, max: 200, fallback: 40 });
54
+
55
+ const DECK_NAME = /^ccdeck-(?:claude|codex|att)-[0-9a-f]{8}$/;
56
+ const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
57
+ const LAUNCH_KEY = /^[A-Za-z0-9_-]{1,96}$/;
58
+
59
+ /**
60
+ * Why a terminal session could not be started, listed or closed.
61
+ *
62
+ * `code` is for the caller to branch on; `message` is one short sentence fit to
63
+ * show as it is, with no path, pid or tmux wording in it; `detail` is what tmux
64
+ * said, for the log only.
65
+ *
66
+ * Codes: bad-agent, bad-kind, bad-cwd, bad-session-id, bad-argv, bad-name,
67
+ * bad-size, agent-missing, tmux-unavailable, exists, tmux-failed.
68
+ */
69
+ export class TerminalSessionError extends Error {
70
+ constructor(code, message, detail = "") {
71
+ super(message);
72
+ this.name = "TerminalSessionError";
73
+ this.code = code;
74
+ this.detail = detail;
75
+ }
76
+ }
77
+
78
+ function checkAgent(agent) {
79
+ if (!AGENTS.includes(agent)) throw new TerminalSessionError("bad-agent", "The deck can start Claude or Codex sessions only.");
80
+ }
81
+
82
+ function checkKind(kind) {
83
+ if (!KINDS.includes(kind)) throw new TerminalSessionError("bad-kind", "That is not a way the deck starts a session.");
84
+ }
85
+
86
+ function checkSessionId(id) {
87
+ // A session id is an argument to the agent's own CLI. Anything but a UUID —
88
+ // one that began with a dash, say — would be read as a flag.
89
+ if (!SESSION_ID.test(String(id ?? ""))) {
90
+ throw new TerminalSessionError("bad-session-id", "That session id is not one Claude or Codex would have written.");
91
+ }
92
+ }
93
+
94
+ /** Whether `key` can label a launch: the page's own name for it, which a
95
+ * tmux option holds as is. */
96
+ export function isLaunchKey(key) {
97
+ return typeof key === "string" && LAUNCH_KEY.test(key);
98
+ }
99
+
100
+ /** Whether `name` is one the deck gives its own tmux sessions — the only
101
+ * sessions it will ever close. */
102
+ export function isDeckSessionName(name) {
103
+ return typeof name === "string" && DECK_NAME.test(name);
104
+ }
105
+
106
+ /**
107
+ * The tmux session name for a new deck session.
108
+ *
109
+ * `ccdeck-<agent>-<8 random hex>` for a launch or a resume. Random rather than
110
+ * derived from the session id, because a launched Codex has no id until it
111
+ * writes its first rollout, and because one conversation can be reopened
112
+ * after an earlier deck session for it has ended and still lies there, dead.
113
+ *
114
+ * `ccdeck-att-<first 8 of the id>` for an attach wrapper: derived ON PURPOSE,
115
+ * so a second open of the same background session collides with the first
116
+ * wrapper instead of starting another `claude attach` beside it.
117
+ */
118
+ export function deckSessionName({ agent, kind = "launch", sessionId = "", random = randomBytes }) {
119
+ if (kind === "attach") {
120
+ checkSessionId(sessionId);
121
+ return `ccdeck-att-${String(sessionId).slice(0, 8).toLowerCase()}`;
122
+ }
123
+ checkAgent(agent);
124
+ return `ccdeck-${agent}-${random(4).toString("hex")}`;
125
+ }
126
+
127
+ /**
128
+ * The argv that starts an agent session. Pure.
129
+ *
130
+ * claude launch → [claude, "--session-id", <id, or a new v4 UUID>]
131
+ * claude resume → [claude, "--resume", id]
132
+ * claude attach → [claude, "attach", id]
133
+ * codex launch → [codex]
134
+ * codex resume → [codex, "resume", id]
135
+ *
136
+ * A new Claude is told its id rather than left to pick one, so the deck knows
137
+ * which board node the pane belongs to before the first hook arrives. Codex has
138
+ * no such flag: a launched Codex is matched to its session later, by the
139
+ * rollout it opens. So a launch of Codex refuses an id rather than dropping it
140
+ * where a caller would assume it had been used. Codex has no background
141
+ * sessions, so it has no attach.
142
+ */
143
+ export function agentArgv({
144
+ agent, kind = "launch", sessionId = "", claudeBin = "claude", codexBin = "codex", uuid = randomUUID, options = null,
145
+ } = {}) {
146
+ checkAgent(agent);
147
+ checkKind(kind);
148
+ const extra = launchOptionArgs(agent, kind, options);
149
+ if (agent === "claude") {
150
+ if (kind === "launch") {
151
+ if (sessionId) checkSessionId(sessionId);
152
+ return [claudeBin, "--session-id", sessionId || uuid(), ...extra];
153
+ }
154
+ checkSessionId(sessionId);
155
+ return kind === "resume" ? [claudeBin, "--resume", sessionId] : [claudeBin, "attach", sessionId];
156
+ }
157
+ if (kind === "attach") throw new TerminalSessionError("bad-kind", "Codex sessions cannot be attached to that way.");
158
+ if (kind === "launch") {
159
+ if (sessionId) throw new TerminalSessionError("bad-session-id", "A new Codex session chooses its own id.");
160
+ return [codexBin];
161
+ }
162
+ checkSessionId(sessionId);
163
+ return [codexBin, "resume", sessionId];
164
+ }
165
+
166
+ /** What New session may ask of a new Claude, each a value Claude Code's own
167
+ * CLI lists (2.1.301: `--model <alias>`, `--permission-mode <mode>`,
168
+ * `--worktree`). Never a mode that stops asking — bypassPermissions, dontAsk:
169
+ * a deck that never answers for the reader does not start an agent that
170
+ * answers for itself. Anything else is refused, so nothing a page sends
171
+ * becomes a flag the deck did not choose. */
172
+ export const LAUNCH_MODELS = Object.freeze(["opus", "sonnet", "haiku"]);
173
+ export const LAUNCH_PERMISSION_MODES = Object.freeze(["manual", "auto", "acceptEdits", "plan"]);
174
+
175
+ /** The flags for a launch's options, after the session id. Pure; throws
176
+ * `bad-options` for anything not on the lists above, or for options on
177
+ * anything but a new Claude. `--worktree` goes last: its value is optional,
178
+ * and last it can take nothing that was meant as another flag. */
179
+ export function launchOptionArgs(agent, kind, options) {
180
+ if (options == null) return [];
181
+ if (typeof options !== "object" || Array.isArray(options)) throw new TerminalSessionError("bad-options", "Those session options are not ones the deck knows.");
182
+ const { model, permissionMode, worktree, ...rest } = options;
183
+ if (Object.keys(rest).length || (worktree != null && typeof worktree !== "boolean")) {
184
+ throw new TerminalSessionError("bad-options", "Those session options are not ones the deck knows.");
185
+ }
186
+ if (model == null && permissionMode == null && worktree !== true) return [];
187
+ if (agent !== "claude" || kind !== "launch") throw new TerminalSessionError("bad-options", "Only a new Claude session takes those options.");
188
+ const out = [];
189
+ if (model != null) {
190
+ if (!LAUNCH_MODELS.includes(model)) throw new TerminalSessionError("bad-options", "That is not a model the deck can start Claude with.");
191
+ out.push("--model", model);
192
+ }
193
+ if (permissionMode != null) {
194
+ if (!LAUNCH_PERMISSION_MODES.includes(permissionMode)) throw new TerminalSessionError("bad-options", "That is not a permission mode the deck can start Claude in.");
195
+ out.push("--permission-mode", permissionMode);
196
+ }
197
+ if (worktree === true) out.push("--worktree");
198
+ return out;
199
+ }
200
+
201
+ /**
202
+ * The agent's binary as an absolute path, or null when this machine has none.
203
+ *
204
+ * Absolute because the pane is exec'd by the tmux SERVER, with the PATH the
205
+ * server was started with — and that server may be older than this deck,
206
+ * started by a previous run whose PATH was different. A bare name would be
207
+ * looked up there; a path is not looked up at all.
208
+ *
209
+ * Claude comes from adminClaudeBin, the resolver the accounts surface and the
210
+ * boot check share. Codex has no resolver of its own yet: PATH, then the
211
+ * places its npm and Homebrew installs land, the same shape claudeCliCandidates
212
+ * gives Claude and for the same reason — a deck started from a shortcut has a
213
+ * PATH that never sourced the shell rc that put Codex on it.
214
+ */
215
+ export function resolveAgentBin(agent, {
216
+ env = process.env, platform = process.platform, home = homedir(), exists = existsSync,
217
+ } = {}) {
218
+ checkAgent(agent);
219
+ const pathEnv = env.PATH ?? env.Path ?? "";
220
+ const located = (bin) => {
221
+ if (!/[\\/]/.test(bin)) return pathLookup(bin, platform, { pathEnv, exists });
222
+ try { return exists(bin) ? bin : null; } catch { return null; }
223
+ };
224
+ if (agent === "claude") return located(adminClaudeBin(platform, env, home, exists));
225
+ for (const bin of ["codex", posixPath.join(home, ".local", "bin", "codex"), "/opt/homebrew/bin/codex", "/usr/local/bin/codex"]) {
226
+ const at = located(bin);
227
+ if (at) return at;
228
+ }
229
+ return null;
230
+ }
231
+
232
+ /**
233
+ * The project folder a session starts in, checked: an absolute path to a
234
+ * directory that exists, with no control characters in it.
235
+ *
236
+ * Control characters are refused rather than carried. The folder is stored in a
237
+ * tmux option and read back from a tab-separated listing, and a newline or a
238
+ * tab in it would split that listing's line; no real project path needs one.
239
+ */
240
+ export async function checkCwd(cwd, { statFn = stat } = {}) {
241
+ if (typeof cwd !== "string" || cwd === "" || !isAbsolute(cwd)) {
242
+ throw new TerminalSessionError("bad-cwd", "The project folder has to be a full path.");
243
+ }
244
+ if (/[\u0000-\u001f\u007f]/.test(cwd)) {
245
+ throw new TerminalSessionError("bad-cwd", "That project folder's name has control characters in it.");
246
+ }
247
+ let st;
248
+ try { st = await statFn(cwd); } catch {
249
+ throw new TerminalSessionError("bad-cwd", "That project folder does not exist.");
250
+ }
251
+ if (!st.isDirectory()) throw new TerminalSessionError("bad-cwd", "That project path is not a folder.");
252
+ return cwd;
253
+ }
254
+
255
+ /** `cols` × `rows` held to what a terminal can sensibly be; a value that is not
256
+ * a number takes the default rather than the floor. */
257
+ export function clampSize(cols, rows) {
258
+ const fit = (v, { min, max, fallback }) =>
259
+ v == null || v === "" || !Number.isFinite(Number(v)) ? fallback : Math.min(max, Math.max(min, Math.round(Number(v))));
260
+ return { cols: fit(cols, COLS), rows: fit(rows, ROWS) };
261
+ }
262
+
263
+ /**
264
+ * The tmux arguments that create one labelled deck session, after the socket.
265
+ *
266
+ * `-f /dev/null`: the deck's server reads no tmux.conf. It is the deck's, not
267
+ * the user's, and a user's config can break it outright — measured on 3.6, a
268
+ * ~/.tmux.conf with `destroy-unattached on` destroyed a `new-session -d`
269
+ * session, and with it the server, before the next command could list it; and
270
+ * every deck session is detached. The flag only matters to the call that
271
+ * starts the server; any other client ignores it.
272
+ *
273
+ * `-e COLORTERM=truecolor` (new-session's -e is 3.2, the floor): the terminal
274
+ * that draws this pane is the panel's xterm, which renders 24-bit colour, and
275
+ * control mode hands it the pane's bytes untranslated; anyone who attaches by
276
+ * hand gets tmux's own translation for their terminal. Without it a deck
277
+ * started from a login item — no COLORTERM in its environment — would launch
278
+ * agents that pick a 256-colour palette for a screen that never needed one.
279
+ *
280
+ * `-e CLAUDE_CODE_NONBLOCKING_STDOUT=1` for Claude: Claude Code documents it
281
+ * (2.1.261 and later) for exactly this pane — "a terminal that stops reading,
282
+ * such as a paused tmux control-mode pane … can't freeze Claude Code
283
+ * mid-session" — and the bridge pauses a pane whose panel falls behind. An
284
+ * older Claude ignores it.
285
+ *
286
+ * `-e CLAUDE_CODE_TMUX_TRUECOLOR=1` for Claude: Claude Code drops to 256
287
+ * colours whenever $TMUX is set, whatever COLORTERM says, "because tmux does
288
+ * not pass through truecolor escape sequences unless configured to", and
289
+ * documents this variable to lift that clamp. Here tmux does pass them: control
290
+ * mode hands the panel the pane's bytes untranslated, and capture-pane -e seeds
291
+ * a reattach with the 24-bit colours the grid stored. Clamped, Claude's colours
292
+ * reached the panel as the nearest 256-colour slot and the palette repainted
293
+ * that slot by role (terminal-palette.ts), so its orange mascot came out deep
294
+ * rust on a light theme; with it, Claude draws its own /theme's colours, the
295
+ * block-drawn mascot exactly. Its "auto" theme follows the panel: tmux answers
296
+ * the background from window-style below and, from 3.6, tells the pane when it
297
+ * changes. A tmux the deck did not start keeps Claude's clamp.
298
+ *
299
+ * `-e CLAUDE_CODE_SCROLL_SPEED=3` for Claude: xterm.js sends one wheel report
300
+ * per notch to a program that has the mouse, and Claude Code's fullscreen
301
+ * scrolls a line per report, so it moved a third of what every native
302
+ * terminal moves (three lines a notch). Claude Code documents the variable
303
+ * for exactly such terminals.
304
+ *
305
+ * `default-terminal` and `history-limit`: with no config read, tmux's own
306
+ * defaults are `screen` — eight colours and no italics for vim, less, htop
307
+ * and git's pager, since they go by terminfo, not COLORTERM — and 2000 lines
308
+ * of history, where native terminals keep 10,000. `tmux-256color` where this
309
+ * machine's terminfo has it, else `screen-256color`, which every terminfo
310
+ * has (macOS's own lacks the tmux entry).
311
+ *
312
+ * Everything else rides in the same sequence as new-session; see tmuxSequence
313
+ * for why that ordering is what keeps a pane that dies at once on the board.
314
+ */
315
+ export function launchCommand({ name, cwd, cols, rows, argv, sessionId = "", agent, kind, term = PANE_TERM_FALLBACK, colours = null, launchKey = "" }) {
316
+ const at = `=${name}:`;
317
+ const style = paneColours(colours);
318
+ return ["-f", "/dev/null", ...tmuxSequence([
319
+ // The server's own defaults, set ahead of the pane they shape — and
320
+ // again on every launch, so a server an older deck started picks them up
321
+ // for the panes it makes from now on. Ahead of new-session in the same
322
+ // sequence, so the first launch starts the server with them.
323
+ ["set-option", "-g", "default-terminal", term],
324
+ ["set-option", "-g", "history-limit", String(PANE_HISTORY)],
325
+ ["new-session", "-d", "-s", name, "-x", String(cols), "-y", String(rows),
326
+ "-c", tmuxFormatLiteral(cwd), "-e", "COLORTERM=truecolor",
327
+ ...(agent === "claude" ? ["-e", "CLAUDE_CODE_NONBLOCKING_STDOUT=1", "-e", "CLAUDE_CODE_TMUX_TRUECOLOR=1", "-e", `CLAUDE_CODE_SCROLL_SPEED=${CLAUDE_SCROLL_SPEED}`] : []),
328
+ "-P", "-F", "#{pane_id}",
329
+ "--", ...paneArgv(argv)],
330
+ // The panel's colours, straight after the pane and in the same sequence,
331
+ // so they are tmux's answer before the program can ask. A program asking
332
+ // its terminal's colours (OSC 10/11: Codex at its first frame, Claude
333
+ // Code's auto theme, vim) is answered by tmux, from a control client's
334
+ // report when one has made it and from the window's style otherwise — and
335
+ // at launch no client has attached yet, so without a style tmux answered
336
+ // black, and a light deck got a session drawn for a dark terminal. Every
337
+ // tmux from 3.2 answers from the style; the socket keeps it current.
338
+ ...(style ? [["set-option", "-w", "-t", at, "window-style", style]] : []),
339
+ ["set-option", "-t", at, SESSION_OPTIONS.session, sessionId],
340
+ ["set-option", "-t", at, SESSION_OPTIONS.agent, agent],
341
+ ["set-option", "-t", at, SESSION_OPTIONS.kind, kind],
342
+ ["set-option", "-t", at, SESSION_OPTIONS.cwd, cwd],
343
+ ...(launchKey ? [["set-option", "-t", at, SESSION_OPTIONS.launch, launchKey]] : []),
344
+ ["set-option", "-w", "-t", at, "remain-on-exit", "on"],
345
+ // Last, and -q: remain-on-exit-format arrived in 3.3, above the 3.2 floor,
346
+ // and an option a tmux does not know must not fail a sequence that has
347
+ // already made the session. On 3.2 the dead pane keeps tmux's caption.
348
+ ["set-option", "-q", "-w", "-t", at, "remain-on-exit-format", ""],
349
+ ])];
350
+ }
351
+
352
+ /** A colour as the panel sends one: six lowercase hex digits after a #. */
353
+ const PANE_COLOUR = /^#[0-9a-f]{6}$/;
354
+
355
+ /** `fg=#…,bg=#…` for tmux's window-style, from the panel's `{ fg, bg }`, or
356
+ * null when either is missing or not a colour — never a failed launch: the
357
+ * colours are a courtesy, and the socket sends them again on attach. */
358
+ export function paneColours(colours) {
359
+ if (!colours || typeof colours !== "object") return null;
360
+ const { fg, bg } = colours;
361
+ if (!PANE_COLOUR.test(String(fg)) || !PANE_COLOUR.test(String(bg))) return null;
362
+ return `fg=${fg},bg=${bg}`;
363
+ }
364
+
365
+ /** Lines of history a deck pane keeps: what native terminals keep. */
366
+ export const PANE_HISTORY = 10_000;
367
+ /** Lines one wheel notch scrolls Claude Code's fullscreen by (see launchCommand). */
368
+ export const CLAUDE_SCROLL_SPEED = 3;
369
+ /** The terminal type every terminfo database has entries for. */
370
+ export const PANE_TERM_FALLBACK = "screen-256color";
371
+
372
+ /** Where terminfo databases live: ncurses' own list, Homebrew's, the user's. */
373
+ const TERMINFO_DIRS = [
374
+ "/usr/share/terminfo", "/lib/terminfo", "/etc/terminfo", "/usr/lib/terminfo",
375
+ "/opt/homebrew/share/terminfo", "/usr/local/share/terminfo",
376
+ ];
377
+
378
+ /**
379
+ * The TERM a deck pane is given: `tmux-256color` when this machine's terminfo
380
+ * has an entry for it — under its first letter, or its hex code as macOS and
381
+ * some BSDs file them — else `screen-256color`. TERMINFO and TERMINFO_DIRS
382
+ * are honoured first, as ncurses honours them.
383
+ */
384
+ export function paneTerm({ env = process.env, home = homedir(), exists = existsSync } = {}) {
385
+ // POSIX paths whatever runs this: terminfo is a Unix database, and the
386
+ // panel never runs where paths are spelled otherwise.
387
+ const at = posixPath.join;
388
+ const dirs = [
389
+ env.TERMINFO, ...String(env.TERMINFO_DIRS ?? "").split(":"), at(home, ".terminfo"), ...TERMINFO_DIRS,
390
+ ].filter(Boolean);
391
+ const found = dirs.some((d) => exists(at(d, "t", "tmux-256color")) || exists(at(d, "74", "tmux-256color")));
392
+ return found ? "tmux-256color" : PANE_TERM_FALLBACK;
393
+ }
394
+
395
+ /** systemd-run's own failures, as opposed to tmux's: the scope was never
396
+ * started, so tmux never ran and the plain call is safe to make instead. */
397
+ const SYSTEMD_REFUSED = /^Failed to (?:connect|start|create|allocate|set up|find)\b/m;
398
+
399
+ /** What a tmux client says when the server it reached exited before
400
+ * answering: a server whose last session had just gone (exit-empty) still
401
+ * takes a connection on its way out. */
402
+ const SERVER_EXITED = /server exited unexpectedly/i;
403
+ /** How long a launch that met an exiting server waits before it asks again,
404
+ * times the attempt: long enough for that server to be gone, so the next
405
+ * call starts a fresh one. */
406
+ export const RELAUNCH_WAIT_MS = 50;
407
+
408
+ async function requireTmux(env) {
409
+ const found = await findTmux({ env });
410
+ if (!found.ok) throw new TerminalSessionError("tmux-unavailable", "tmux is not available on this machine.");
411
+ return found;
412
+ }
413
+
414
+ /**
415
+ * Start an agent in a new deck-owned tmux session: `{ name, sessionId, pane }`.
416
+ *
417
+ * `argv` overrides the agent's own command line (the suite runs `cat` there);
418
+ * without it the agent's binary is resolved and agentArgv decides. A Claude
419
+ * launch with no `sessionId` is given a new one, which is returned; a Codex
420
+ * launch returns "" because Codex has not chosen its id yet. `tmux` is a path
421
+ * or findTmux's answer, and is looked up when omitted. `socket` and `env`
422
+ * exist so the suite can run all of this on a server of its own; the product
423
+ * passes neither. `launchKey`, the page's name for the launch, is kept on the
424
+ * session (SESSION_OPTIONS.launch) for findLaunchedSession.
425
+ *
426
+ * Throws TerminalSessionError. A random name that collides is retried; an
427
+ * attach wrapper's name colliding means one already exists ("exists"), and
428
+ * reusing it is the caller's call. A launch that reached a server on its way
429
+ * out (its last session had just gone) is retried once nothing of its name is
430
+ * there. A session created but not fully labelled is killed before the error
431
+ * is thrown: unlabelled, nothing would ever find it.
432
+ *
433
+ * new-session is the one call that can start the deck's tmux server, so it is
434
+ * the one run through `scope` (tmux.mjs's serverScope): under the login item's
435
+ * systemd service, a server started plainly would die with the service on
436
+ * `ccdeck --stop`, taking every agent in it along. If systemd itself refuses
437
+ * the scope, the session is started plainly rather than not at all.
438
+ */
439
+ export async function launchSession({
440
+ tmux, agent, cwd, cols = COLS.fallback, rows = ROWS.fallback, argv, sessionId = "", kind = "launch",
441
+ socket = DECK_SOCKET, env = process.env, platform = process.platform, run = runTmux, scope = serverScope,
442
+ options = null, colours = null, launchKey = "",
443
+ } = {}) {
444
+ checkAgent(agent);
445
+ checkKind(kind);
446
+ if (launchKey && !isLaunchKey(launchKey)) {
447
+ throw new TerminalSessionError("bad-launch-key", "The launch's key is not one the deck can keep.");
448
+ }
449
+ if (kind === "attach" && agent !== "claude") {
450
+ throw new TerminalSessionError("bad-kind", "Codex sessions cannot be attached to that way.");
451
+ }
452
+ const dir = await checkCwd(cwd);
453
+ const size = clampSize(cols, rows);
454
+ let id = String(sessionId ?? "");
455
+ let command;
456
+ if (argv !== undefined) {
457
+ if (!Array.isArray(argv) || argv.length === 0 || argv.some(a => typeof a !== "string" || a === "")) {
458
+ throw new TerminalSessionError("bad-argv", "The session's command line is empty.");
459
+ }
460
+ if (id || kind !== "launch") checkSessionId(id);
461
+ command = argv;
462
+ } else {
463
+ if (agent === "claude" && kind === "launch" && !id) id = randomUUID();
464
+ const bin = resolveAgentBin(agent, { env, platform });
465
+ if (!bin) {
466
+ throw new TerminalSessionError("agent-missing", agent === "claude"
467
+ ? "Claude Code is not installed on this machine."
468
+ : "Codex is not installed on this machine.");
469
+ }
470
+ command = agentArgv({ agent, kind, sessionId: id, claudeBin: bin, codexBin: bin, options });
471
+ }
472
+ const bin = tmux ?? await requireTmux(env);
473
+ let outside = null;
474
+ try { outside = await scope({ env, platform }); } catch { outside = null; }
475
+
476
+ for (let attempt = 0; ; attempt++) {
477
+ const name = deckSessionName({ agent, kind, sessionId: id });
478
+ const args = launchCommand({ name, cwd: dir, ...size, argv: command, sessionId: id, agent, kind, term: paneTerm({ env }), colours, launchKey });
479
+ let r = await run(bin, socket, args, outside ? { env, scope: outside } : { env });
480
+ if (outside && !r.ok && SYSTEMD_REFUSED.test(r.stderr)) {
481
+ outside = null;
482
+ r = await run(bin, socket, args, { env });
483
+ }
484
+ const pane = /^%\d+$/m.exec(r.stdout)?.[0] ?? "";
485
+ // A client that timed out after the pane was printed (tmuxTimedOut) still
486
+ // made it: tmux runs the whole sequence in the server, and the stall was
487
+ // after. Closing it would ask the same stalled server, and a kill that
488
+ // timed out too would leave the agent running behind a failure that
489
+ // invites a second launch.
490
+ if ((r.ok || r.code === "ETIMEDOUT") && pane) return { name, sessionId: id, pane };
491
+ if (pane) {
492
+ await run(bin, socket, ["kill-session", "-t", `=${name}`], { env });
493
+ throw new TerminalSessionError("tmux-failed", "tmux started the session but could not label it.", r.stderr.trim());
494
+ }
495
+ if (/duplicate session/i.test(r.stderr)) {
496
+ if (kind === "attach") throw new TerminalSessionError("exists", "The deck is already attached to that session.", r.stderr.trim());
497
+ if (attempt < 2) continue;
498
+ }
499
+ // A launch right after the last session ended reached a server that was
500
+ // exiting: it made nothing. Asked by name first, so that a session that
501
+ // somehow was made is never started twice; then asked again, of the
502
+ // fresh server that call starts.
503
+ if (SERVER_EXITED.test(r.stderr) && attempt < 2) {
504
+ const there = await run(bin, socket, ["has-session", "-t", `=${name}`], { env });
505
+ if (!there.ok) {
506
+ await delay(RELAUNCH_WAIT_MS * (attempt + 1));
507
+ continue;
508
+ }
509
+ }
510
+ throw new TerminalSessionError("tmux-failed", "tmux could not start the session.", r.stderr.trim());
511
+ }
512
+ }
513
+
514
+ /** The listing's columns, tab-separated, the free-text folder last. */
515
+ const PANE_FORMAT = [
516
+ "#{session_name}", "#{pane_id}", "#{pane_pid}", "#{pane_dead}", "#{pane_dead_status}",
517
+ "#{session_created}", "#{pane_width}", "#{pane_height}",
518
+ `#{${SESSION_OPTIONS.session}}`, `#{${SESSION_OPTIONS.agent}}`, `#{${SESSION_OPTIONS.kind}}`,
519
+ `#{${SESSION_OPTIONS.launch}}`, `#{${SESSION_OPTIONS.cwd}}`,
520
+ ].join("\t");
521
+
522
+ /**
523
+ * One deck session per line of a `list-panes -a -F PANE_FORMAT` listing. Pure.
524
+ *
525
+ * Sessions whose name is not a deck name are left out: somebody may have made
526
+ * one by hand on the deck's server, and the deck does not claim it. A session
527
+ * with more than one pane — split by hand, same story — is its first pane,
528
+ * which is the one the deck started.
529
+ */
530
+ export function parseDeckPanes(stdout) {
531
+ const out = [];
532
+ const seen = new Set();
533
+ const int = (s) => (s === "" || !Number.isFinite(Number(s)) ? null : Number(s));
534
+ for (const line of String(stdout ?? "").split("\n")) {
535
+ const f = line.split("\t");
536
+ if (f.length < 13) continue;
537
+ const [name, pane, panePid, dead, deadStatus, created, cols, rows, sessionId, agent, kind, launchKey] = f;
538
+ if (!isDeckSessionName(name) || seen.has(name)) continue;
539
+ seen.add(name);
540
+ const isDead = dead === "1";
541
+ out.push({
542
+ name, sessionId, agent, kind, launchKey, cwd: f.slice(12).join("\t"), pane,
543
+ panePid: int(panePid), dead: isDead, exitStatus: isDead ? int(deadStatus) : null,
544
+ created: int(created) == null ? null : int(created) * 1000, cols: int(cols), rows: int(rows),
545
+ });
546
+ }
547
+ return out;
548
+ }
549
+
550
+ /**
551
+ * Every session on the deck's tmux server:
552
+ * `[{ name, sessionId, agent, kind, launchKey, cwd, pane, panePid, dead,
553
+ * exitStatus, created, cols, rows }]`, `created` in epoch milliseconds;
554
+ * `launchKey` "" for a session no page launch named.
555
+ *
556
+ * No server is an empty list, not an error — it is what a deck that has never
557
+ * launched anything, or whose last session was closed, looks like.
558
+ */
559
+ export async function listDeckSessions({ tmux, socket = DECK_SOCKET, env = process.env, run = runTmux } = {}) {
560
+ const bin = tmux ?? await requireTmux(env);
561
+ const r = await run(bin, socket, ["list-panes", "-a", "-F", PANE_FORMAT], { env });
562
+ if (r.ok) return parseDeckPanes(r.stdout);
563
+ if (tmuxHasNoServer(r.stderr)) return [];
564
+ throw new TerminalSessionError("tmux-failed", "tmux could not list the deck's sessions.", r.stderr.trim());
565
+ }
566
+
567
+ /**
568
+ * The deck session holding `sessionId`, or null. Pure.
569
+ *
570
+ * One conversation can have more than one: reopened after its first deck
571
+ * session ended, the old one is still there, dead, beside the new. A live one
572
+ * wins, then the newest. `kinds` narrows the search — case A wants a launch or
573
+ * resume, case D an attach wrapper.
574
+ */
575
+ export function findDeckSession(list, sessionId, { kinds = null } = {}) {
576
+ const want = String(sessionId ?? "").toLowerCase();
577
+ if (!want) return null;
578
+ const hits = (list ?? []).filter(s =>
579
+ String(s.sessionId ?? "").toLowerCase() === want && (!kinds || kinds.includes(s.kind)));
580
+ hits.sort((a, b) => Number(a.dead) - Number(b.dead) || (b.created ?? 0) - (a.created ?? 0));
581
+ return hits[0] ?? null;
582
+ }
583
+
584
+ /**
585
+ * The deck session a launch named `key` started, or null. Pure. One at most:
586
+ * the page names each launch once, and a launch asked again with its key
587
+ * comes here before it starts anything (terminal-routes.mjs).
588
+ */
589
+ export function findLaunchedSession(list, key) {
590
+ if (!isLaunchKey(key)) return null;
591
+ return (list ?? []).find(s => s.launchKey === key) ?? null;
592
+ }
593
+
594
+ /**
595
+ * The names of every DEAD deck session that held `sessionId`, of any kind,
596
+ * oldest first. Pure.
597
+ *
598
+ * remain-on-exit keeps each one for its last frame, and that frame is worth
599
+ * keeping only while it is the latest word on the conversation. Once the
600
+ * conversation is reopened, nothing can show a dead pane for it again —
601
+ * terminal-target answers a live pane or none — so every reopen would leave
602
+ * one more corpse on the deck's server for good. The adopt route clears these
603
+ * before it starts the resume. A live session is never in this list, whatever
604
+ * its id.
605
+ */
606
+ export function deadDeckSessions(list, sessionId) {
607
+ const want = String(sessionId ?? "").toLowerCase();
608
+ if (!want) return [];
609
+ return (list ?? [])
610
+ .filter(s => s?.dead === true && isDeckSessionName(s.name) && String(s.sessionId ?? "").toLowerCase() === want)
611
+ .sort((a, b) => (a.created ?? 0) - (b.created ?? 0))
612
+ .map(s => s.name);
613
+ }
614
+
615
+ /** How long a dead deck session is kept for its last frame, and how many of
616
+ * them at most. A week covers coming back after a weekend to see how
617
+ * something ended; past that, or past the twenty most recent, the frame is
618
+ * history the board no longer shows and the server only carries. */
619
+ export const DEAD_KEEP = Object.freeze({ maxAgeMs: 7 * 24 * 60 * 60_000, count: 20 });
620
+
621
+ /** The prune's columns: which session, whether its pane is dead and since
622
+ * when. pane_dead_time is 3.3; on 3.2 it is empty and the session's creation
623
+ * stands in, which only ever makes a session look older than it is dead. */
624
+ const DEAD_FORMAT = ["#{session_name}", "#{pane_dead}", "#{pane_dead_time}", "#{session_created}"].join("\t");
625
+
626
+ /**
627
+ * The deck sessions a prune closes, from a `list-panes -a -F DEAD_FORMAT`
628
+ * listing, oldest death last in the order they were found. Pure.
629
+ *
630
+ * Only deck names, and only a session whose every pane is dead — one split by
631
+ * hand with a live pane beside the dead agent is somebody's work. Of those,
632
+ * every one dead longer than `maxAgeMs`, and every one past the `count` most
633
+ * recently dead. A launched Codex that never learned its id is dead like any
634
+ * other: it carries no id, and needs none to be found here.
635
+ */
636
+ export function staleDeadSessions(stdout, { now = Date.now(), maxAgeMs = DEAD_KEEP.maxAgeMs, count = DEAD_KEEP.count } = {}) {
637
+ const sessions = new Map();
638
+ for (const line of String(stdout ?? "").split("\n")) {
639
+ const [name, dead, deadTime, created] = line.split("\t");
640
+ if (created === undefined || !isDeckSessionName(name)) continue;
641
+ const s = sessions.get(name) ?? { dead: true, at: 0 };
642
+ if (dead !== "1") s.dead = false;
643
+ s.at = Math.max(s.at, (Number(deadTime) || Number(created) || 0) * 1000);
644
+ sessions.set(name, s);
645
+ }
646
+ return [...sessions]
647
+ .filter(([, s]) => s.dead)
648
+ .sort((a, b) => b[1].at - a[1].at)
649
+ .filter(([, s], i) => i >= count || now - s.at > maxAgeMs)
650
+ .map(([name]) => name);
651
+ }
652
+
653
+ /**
654
+ * Close the dead deck sessions staleDeadSessions picks: the names it closed.
655
+ *
656
+ * remain-on-exit keeps every agent that exits, for its last frame, and
657
+ * nothing else ever closes one unless that conversation is reopened — so
658
+ * without this, every session a person quits stays on the deck's server for
659
+ * good, and every listing walks all of them. Never a live pane, and only on
660
+ * the deck's own server: killDeckSession refuses any other name, and the
661
+ * user's own tmux is a different server this never lists. Never rejects.
662
+ */
663
+ export async function pruneDeadDeckSessions({
664
+ tmux, socket = DECK_SOCKET, env = process.env, run = runTmux, now = Date.now(), maxAgeMs, count,
665
+ } = {}) {
666
+ try {
667
+ const bin = tmux ?? await requireTmux(env);
668
+ const r = await run(bin, socket, ["list-panes", "-a", "-F", DEAD_FORMAT], { env });
669
+ if (!r.ok) return [];
670
+ const closed = [];
671
+ for (const name of staleDeadSessions(r.stdout, { now, ...(maxAgeMs ? { maxAgeMs } : {}), ...(count ? { count } : {}) })) {
672
+ try {
673
+ if (await killDeckSession({ tmux: bin, name, socket, env, run })) closed.push(name);
674
+ } catch { /* the next prune tries again */ }
675
+ }
676
+ return closed;
677
+ } catch {
678
+ return [];
679
+ }
680
+ }
681
+
682
+ /**
683
+ * Write a session id the deck has just learned into a deck session's
684
+ * `@ccdeck-session`: one set-option, true when it landed, false when the
685
+ * session has gone meanwhile.
686
+ *
687
+ * A launched Codex starts with that option empty, because Codex chooses its
688
+ * id only once it writes its first rollout. Until the option says it, every
689
+ * lookup of that session walks every process on the machine for the rollout
690
+ * it holds open (terminal-target.mjs, codexHolder); written once, the next
691
+ * lookup is the listing alone. The id comes from that walk, never from a page,
692
+ * and both values are checked here anyway: the id is later handed to
693
+ * `codex resume`, and the name decides which session is touched.
694
+ */
695
+ export async function labelDeckSession({
696
+ tmux, name, sessionId, socket = DECK_SOCKET, env = process.env, run = runTmux,
697
+ } = {}) {
698
+ if (!isDeckSessionName(name)) {
699
+ throw new TerminalSessionError("bad-name", "The deck only labels sessions it started.");
700
+ }
701
+ checkSessionId(sessionId);
702
+ const bin = tmux ?? await requireTmux(env);
703
+ const r = await run(bin, socket, ["set-option", "-t", `=${name}:`, SESSION_OPTIONS.session, String(sessionId).toLowerCase()], { env });
704
+ if (r.ok) return true;
705
+ if (tmuxHasNoServer(r.stderr) || /can't find session|no such session/i.test(r.stderr)) return false;
706
+ throw new TerminalSessionError("tmux-failed", "tmux could not label the session.", r.stderr.trim());
707
+ }
708
+
709
+ /**
710
+ * Close one deck session, agent and all. True when it was there to close,
711
+ * false when it was already gone.
712
+ *
713
+ * Refuses any name the deck does not give its own sessions, before tmux is
714
+ * asked anything: this is the one call here that ends somebody's work, and the
715
+ * deck ends only work it started.
716
+ */
717
+ export async function killDeckSession({ tmux, name, socket = DECK_SOCKET, env = process.env, run = runTmux } = {}) {
718
+ if (!isDeckSessionName(name)) {
719
+ throw new TerminalSessionError("bad-name", "The deck only closes sessions it started.");
720
+ }
721
+ const bin = tmux ?? await requireTmux(env);
722
+ const r = await run(bin, socket, ["kill-session", "-t", `=${name}`], { env });
723
+ if (r.ok) return true;
724
+ if (tmuxHasNoServer(r.stderr) || /can't find session|no such session/i.test(r.stderr)) return false;
725
+ throw new TerminalSessionError("tmux-failed", "tmux could not close the session.", r.stderr.trim());
726
+ }
727
+
728
+ /** The largest side resizeWrapper takes: what tmux itself allows a window. */
729
+ const WRAPPER_SIDE_MAX = 10_000;
730
+
731
+ /**
732
+ * Size an attach wrapper's window to `cols` x `rows`, which its `claude
733
+ * attach` passes on to the background session. True when it was done, false
734
+ * when the wrapper has already gone.
735
+ *
736
+ * One invocation: resize-window pins the window (window-size manual), so the
737
+ * option is unset in the same sequence, and a panel back on the wrapper can
738
+ * still fit it. With no client sizing it, the window keeps the size given.
739
+ * Only a wrapper, refused before tmux is asked: a deck agent's own session is
740
+ * never resized behind its panel.
741
+ */
742
+ export async function resizeWrapper({ tmux, name, cols, rows, socket = DECK_SOCKET, env = process.env, run = runTmux } = {}) {
743
+ if (!isDeckSessionName(name) || !name.startsWith("ccdeck-att-")) {
744
+ throw new TerminalSessionError("bad-name", "The deck only resizes the wrappers it started.");
745
+ }
746
+ const side = (n) => Number.isInteger(n) && n >= 1 && n <= WRAPPER_SIDE_MAX;
747
+ if (!side(cols) || !side(rows)) {
748
+ throw new TerminalSessionError("bad-size", "A size is two whole numbers up to 10000.");
749
+ }
750
+ const bin = tmux ?? await requireTmux(env);
751
+ const at = `=${name}:`;
752
+ const r = await run(bin, socket, tmuxSequence([
753
+ ["resize-window", "-t", at, "-x", String(cols), "-y", String(rows)],
754
+ ["set-option", "-w", "-u", "-t", at, "window-size"],
755
+ ]), { env });
756
+ if (r.ok) return true;
757
+ if (tmuxHasNoServer(r.stderr) || /can't find session|no such session/i.test(r.stderr)) return false;
758
+ throw new TerminalSessionError("tmux-failed", "tmux could not resize the session.", r.stderr.trim());
759
+ }