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,403 @@
1
+ // The Command Panel's WebSocket: the upgrade that admits one, and the
2
+ // single-use tickets that say which session it may reach. What runs behind an
3
+ // admitted socket is the optional local engine's (see "THE BRIDGE IS THE
4
+ // ENGINE'S" below).
5
+ //
6
+ // THE UPGRADE RUNS ITS OWN GATES, because nothing else will. The moment a
7
+ // server has one 'upgrade' listener, Node hands that listener EVERY request
8
+ // that carries an Upgrade header — on any path — and the route table in
9
+ // index.mjs, with the four gates in front of it, never sees them. So this
10
+ // handler is the whole of the protection for the socket, and it asks the same
11
+ // questions in the same words: a loopback Host (isLoopbackHost, the rebinding
12
+ // defence), an Origin that is present and names this very server
13
+ // (originMatchesHost — browsers apply no same-origin policy to a WebSocket, so
14
+ // this is the only thing between a page on another site and a typeable
15
+ // terminal), and fetch metadata, when there is any, saying `same-origin`. A
16
+ // path that is not the attach path, or a deck with the panel switched off, is
17
+ // answered exactly as an /api path with no route is: a 404, and the socket
18
+ // hung up. Nothing here ever answers 101 to a request it has not admitted.
19
+ //
20
+ // A TICKET, BECAUSE THE BROWSER CANNOT SEND A CREDENTIAL. A WebSocket handshake
21
+ // carries no custom header the page can set, so the token every other client
22
+ // of this deck presents has no way onto it. The page asks one of the POST
23
+ // routes — which pass the mutation gate the ordinary way — and is handed a
24
+ // ticket: 32 random bytes, good once, for thirty seconds, bound to the one
25
+ // pane the route resolved. The binding stays here; the page never names a
26
+ // pane, a socket or a tmux, so a page cannot ask for anything the routes did
27
+ // not already decide it may have. What a ticket is not is authentication
28
+ // against a local process that forges headers — request-gates.mjs says why
29
+ // nothing on this machine can be — so it adds replay protection and binding,
30
+ // and the gates do the rest.
31
+ //
32
+ // THE BRIDGE IS THE ENGINE'S. An admitted socket whose ticket is bound to an
33
+ // engine handle is relayed to the optional local engine (`engine`, below;
34
+ // pro-engine-terminal.mjs), which speaks the protocol
35
+ // src/web/terminal-protocol.ts speaks. A test may hand `openBridge` instead,
36
+ // for a ticket the JS backend minted (terminal-bridge.mjs); the deck passes
37
+ // none, and a ticket nothing can serve is refused before the 101.
38
+ //
39
+ // NOTHING THROWS OUT OF HERE. An exception inside an 'upgrade' listener or a
40
+ // socket callback has nothing above it to catch it: it is an uncaughtException,
41
+ // the worker exits, and every terminal and SSE stream on the deck goes with it.
42
+ // Every entry point catches and ends only its own connection.
43
+ import { randomBytes } from "node:crypto";
44
+ import { isLoopbackHost, originMatchesHost } from "./request-gates.mjs";
45
+ import { httpRefusal, upgradeResponse, validateUpgrade, wsConnection } from "./ws-frames.mjs";
46
+
47
+ /** The one path a terminal socket is opened on. Every other upgrade is a 404.
48
+ * src/web/terminal-protocol.ts states it again, and a test holds the two. */
49
+ export const ATTACH_PATH = "/api/terminal/attach";
50
+
51
+ /** How long a minted ticket may wait for its socket. The page opens the socket
52
+ * the moment the POST answers, so this is a round trip plus a slow tab; a
53
+ * ticket that outlives it has leaked somewhere or been forgotten. */
54
+ export const TICKET_TTL_MS = 30_000;
55
+
56
+ /** The most tickets that may be outstanding at once. Minting is behind the
57
+ * mutation gate, but the question OPEN_MUTATIONS asks of every route — what
58
+ * does an unbounded number of these accumulate in — has an answer here too:
59
+ * this Map, and no further. The oldest is dropped first; a panel whose ticket
60
+ * was dropped asks for another. */
61
+ export const MAX_TICKETS = 32;
62
+
63
+ /** The most terminal sockets one deck keeps open. The panel shows one session
64
+ * at a time; four is that panel in a few tabs, and a fifth is refused with a
65
+ * 503 rather than letting tabs pile up tmux clients nobody is looking at. */
66
+ export const MAX_TERMINALS = 4;
67
+
68
+ /** How long a refused upgrade's socket is held for its answer to drain before
69
+ * it is destroyed anyway. */
70
+ const REFUSAL_GRACE_MS = 1_000;
71
+
72
+ /**
73
+ * A store of single-use tickets: `mint(binding)` answers a fresh ticket for
74
+ * the binding, `redeem(ticket)` answers that binding once — and null for a
75
+ * ticket it never minted, one already redeemed, or one older than `ttlMs`.
76
+ *
77
+ * A ticket is 32 random bytes in base64url, so it can ride in a query string
78
+ * untouched. Redeeming takes it out whether or not it was still in date, so a
79
+ * ticket is spent by the first attempt to use it.
80
+ *
81
+ * Looked up as a Map key rather than compared in constant time: a hash lookup
82
+ * of a 256-bit random value says nothing usable about any other value, and the
83
+ * timing of a string comparison is only a leak when the caller can grow a
84
+ * correct prefix one byte at a time — which a hash table never lets it do.
85
+ */
86
+ export function createTicketStore({ ttlMs = TICKET_TTL_MS, now = Date.now, max = MAX_TICKETS } = {}) {
87
+ const held = new Map();
88
+ const sweep = (t) => {
89
+ for (const [ticket, entry] of held) if (entry.expires <= t) held.delete(ticket);
90
+ };
91
+ return {
92
+ mint(binding) {
93
+ const t = now();
94
+ sweep(t);
95
+ // A Map iterates in insertion order, so the first key is the oldest.
96
+ while (held.size >= max) held.delete(held.keys().next().value);
97
+ const ticket = randomBytes(32).toString("base64url");
98
+ held.set(ticket, { binding, expires: t + ttlMs });
99
+ return ticket;
100
+ },
101
+ redeem(ticket) {
102
+ if (typeof ticket !== "string" || ticket === "") return null;
103
+ const entry = held.get(ticket);
104
+ if (!entry) return null;
105
+ held.delete(ticket);
106
+ return entry.expires > now() ? entry.binding : null;
107
+ },
108
+ /** Tickets minted and not yet redeemed or expired. For tests. */
109
+ get size() {
110
+ sweep(now());
111
+ return held.size;
112
+ },
113
+ };
114
+ }
115
+
116
+ /**
117
+ * Whether an upgrade request may become a terminal socket, from the request
118
+ * alone: `{ ok: true, key, ticket, origin }`, or `{ ok: false, status,
119
+ * headers? }` with the HTTP status to refuse it with. Pure, so the order the
120
+ * questions are asked in is pinned without a socket.
121
+ *
122
+ * The order is the answer a caller sees, so it goes from the cheapest and
123
+ * least revealing to the most: not this path or not switched on (404, the
124
+ * same as a route that does not exist); not addressed to this machine, or not
125
+ * from it (403); not this deck's own page (403); not a WebSocket handshake
126
+ * this server speaks (ws-frames' own status); no room (503); no ticket (401).
127
+ * The ticket itself is redeemed by the caller only after all of this, so a
128
+ * request turned away for any other reason does not spend it.
129
+ *
130
+ * `remoteAddress` is the socket's peer. The deck binds 127.0.0.1, so a peer
131
+ * elsewhere means somebody bound it wider; the Host test alone would not
132
+ * notice, because a tunnelled browser names a loopback Host from anywhere.
133
+ */
134
+ export function upgradeVerdict(req, { enabled = () => false, live = 0, max = MAX_TERMINALS, remoteAddress } = {}) {
135
+ const url = parseTarget(req?.url);
136
+ if (!url || url.pathname !== ATTACH_PATH || !enabled()) return refusal(404);
137
+ const headers = req?.headers ?? {};
138
+ if (!isLoopbackHost(headers.host)) return refusal(403);
139
+ if (typeof remoteAddress === "string" && !isLoopbackAddress(remoteAddress)) return refusal(403);
140
+ // REQUIRED, unlike on a POST: every browser sends Origin on a WebSocket
141
+ // handshake, so a request without one was not opened by a page, and the
142
+ // only thing that may open this socket is the deck's own page.
143
+ const origin = typeof headers.origin === "string" ? headers.origin.trim() : "";
144
+ if (!origin || !originMatchesHost(origin, headers.host)) return refusal(403);
145
+ const site = typeof headers["sec-fetch-site"] === "string" ? headers["sec-fetch-site"].trim().toLowerCase() : "";
146
+ if (site !== "" && site !== "same-origin") return refusal(403);
147
+ const handshake = validateUpgrade(req);
148
+ if (!handshake.ok) return { ok: false, status: handshake.status, ...(handshake.headers ? { headers: handshake.headers } : {}) };
149
+ if (live >= max) return refusal(503);
150
+ const ticket = url.searchParams.get("ticket") ?? "";
151
+ if (!ticket) return refusal(401);
152
+ return { ok: true, key: handshake.key, ticket, origin: origin.toLowerCase() };
153
+ }
154
+
155
+ function refusal(status) {
156
+ return { ok: false, status };
157
+ }
158
+
159
+ // The base is a constant, never the Host header, for the reason requestUrl in
160
+ // index.mjs gives: a malformed Host must not be able to throw out of here.
161
+ function parseTarget(raw) {
162
+ try { return new URL(raw ?? "/", "http://localhost"); } catch { return null; }
163
+ }
164
+
165
+ /** A peer address that can only be this machine: 127/8, ::1, or 127/8 as an
166
+ * IPv4-mapped IPv6 address, which is how a dual-stack socket reports it. */
167
+ function isLoopbackAddress(address) {
168
+ const a = address.toLowerCase().replace(/^::ffff:/, "");
169
+ return a === "::1" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a);
170
+ }
171
+
172
+ // Every terminal socket this process has open, across every server it
173
+ // installed the upgrade on, so the shutdown can reach them all.
174
+ const everyTerminal = new Set();
175
+ // Set by closeAllTerminals: from then on the process is on its way out and
176
+ // every upgrade is a 503, so nothing starts a tmux client after the shutdown
177
+ // has already told the others to go.
178
+ let shuttingDown = false;
179
+ // Upgrades waiting on the engine's answer to their attach (relayAdmit). Not
180
+ // open yet, so not counted above, but told of a switch-off once they are.
181
+ const attaching = new Set();
182
+
183
+ /**
184
+ * Add the terminal's one 'upgrade' listener to `server`.
185
+ *
186
+ * enabled() whether the panel is switched on, asked on every upgrade
187
+ * tickets a createTicketStore() the routes mint into
188
+ * engine the optional local engine's terminals (engineTerminals in
189
+ * pro-engine-terminal.mjs answers them). A ticket whose
190
+ * binding is an engine `handle` is relayed through it while
191
+ * it is enabled (relayAdmit). This file imports nothing of
192
+ * the engine's.
193
+ * openBridge({ conn, socket, binding }) TESTS ONLY: starts a bridge in
194
+ * this process for a ticket that is not an engine handle and
195
+ * answers `{ message, closed, shutdown }` — the JS backend's
196
+ * (terminal-js-routes.mjs), which only a test hands
197
+ * startServer. The deck passes none.
198
+ * max live terminal sockets allowed (MAX_TERMINALS)
199
+ *
200
+ * A refused upgrade gets a plain HTTP status and its socket hung up — never a
201
+ * 101. An admitted one gets the 101, a wsConnection, and its bridge. A ticket
202
+ * nothing here can serve — an engine handle with no engine enabled, or any
203
+ * other binding with no `openBridge` — is refused 503 before the 101: the
204
+ * deck has no terminal of its own to fall back on.
205
+ *
206
+ * THE LISTENER IS THERE ONLY WHILE THE PANEL IS ON. Node hands every request
207
+ * carrying an Upgrade header to an 'upgrade' listener when one exists, and to
208
+ * the ordinary request handler when none does — so a listener left in place
209
+ * on a deck with the panel off would turn `curl --http2`'s h2c probe, or any
210
+ * client that offers an upgrade, from the deck's normal answer into a 404 and
211
+ * a hang-up. The switch can flip while the deck runs (Settings), so
212
+ * the listener follows it: checked now, and again ahead of every ordinary
213
+ * request, which is how a page always reaches the socket — it mints its ticket
214
+ * first. A socket already upgraded is no longer the server's and is left
215
+ * alone either way. Answers `{ sync }` for a caller that knows better.
216
+ */
217
+ export function installTerminalUpgrade(server, { enabled = () => false, tickets, openBridge, max = MAX_TERMINALS, engine } = {}) {
218
+ const live = new Set();
219
+ const isOn = () => {
220
+ try { return enabled() === true; } catch { return false; }
221
+ };
222
+
223
+ const onUpgrade = (req, socket, head) => {
224
+ // At once, before anything that can wait: a peer that resets now would
225
+ // otherwise raise an 'error' with no listener, which ends the process.
226
+ socket.on("error", () => {});
227
+ try {
228
+ admit(req, socket, head);
229
+ } catch {
230
+ refuseSocket(socket, 500);
231
+ }
232
+ };
233
+ let armed = false;
234
+ const sync = () => {
235
+ const on = isOn();
236
+ if (on && !armed) server.on("upgrade", onUpgrade);
237
+ else if (!on && armed) server.off("upgrade", onUpgrade);
238
+ armed = on;
239
+ };
240
+ sync();
241
+ // Ahead of the deck's own handler, so the request that turned the panel on
242
+ // — or the next one after the settings file did — arms the socket in time.
243
+ server.prependListener("request", sync);
244
+
245
+ function admit(req, socket, head) {
246
+ const verdict = upgradeVerdict(req, { enabled: isOn, live: live.size, max, remoteAddress: socket.remoteAddress });
247
+ if (!verdict.ok) return refuseSocket(socket, verdict.status, verdict.headers);
248
+ if (shuttingDown) return refuseSocket(socket, 503);
249
+ const binding = tickets?.redeem(verdict.ticket) ?? null;
250
+ if (!binding) return refuseSocket(socket, 401);
251
+ // A ticket minted for one origin is not good for another: the page that
252
+ // asked for it is the page that opens the socket.
253
+ if (binding.origin && binding.origin !== verdict.origin) return refuseSocket(socket, 403);
254
+ // A ticket an engine route minted is relayed to the engine. Any other
255
+ // ticket has a bridge in this process only where a test handed one in;
256
+ // the deck has none, and refuses it before the 101 rather than serve it
257
+ // some other way.
258
+ if (typeof binding.handle === "string") {
259
+ if (engine?.enabled === true) return relayAdmit(verdict.key, socket, head, binding.handle);
260
+ return refuseSocket(socket, 503);
261
+ }
262
+ if (typeof openBridge !== "function") return refuseSocket(socket, 503);
263
+ accept(verdict.key, socket, head, (conn) => openBridge({ conn, socket, binding }));
264
+ }
265
+
266
+ /** Answer an admitted upgrade with the 101 and run its socket, every
267
+ * message going to the bridge `open(conn)` answers. Answers the entry. */
268
+ function accept(key, socket, head, open) {
269
+ // An upgraded socket keeps whatever timeout the HTTP server gave it, and
270
+ // an idle terminal is not a hung request. The keepalive in wsConnection
271
+ // is what notices a peer that has gone.
272
+ socket.setTimeout?.(0);
273
+ socket.write(upgradeResponse(key));
274
+ const entry = { socket, conn: null, bridge: null };
275
+ entry.conn = wsConnection(socket, head, {
276
+ // wsConnection reads nothing until the next tick, so the bridge below
277
+ // is in place before the first message can arrive.
278
+ onMessage: (message) => entry.bridge?.message(message),
279
+ onClose: (code, reason) => {
280
+ live.delete(entry);
281
+ everyTerminal.delete(entry);
282
+ entry.bridge?.closed(code, reason);
283
+ },
284
+ });
285
+ live.add(entry);
286
+ everyTerminal.add(entry);
287
+ try {
288
+ entry.bridge = open(entry.conn);
289
+ } catch {
290
+ entry.conn.close(1011, "the terminal could not be opened");
291
+ }
292
+ return entry;
293
+ }
294
+
295
+ /**
296
+ * An engine ticket, past every gate above: the engine runs the bridge and
297
+ * this socket is relayed to it (`engine.attach`). Until the engine has
298
+ * answered there is no 101, and the upgrade holds its place among `max`.
299
+ * A refusal is a plain status like any
300
+ * other; a socket gone meanwhile, or a deck that began shutting down, gives
301
+ * the attach up, as the deck refuses any upgrade then.
302
+ */
303
+ function relayAdmit(key, socket, head, handle) {
304
+ const held = { told: null };
305
+ live.add(held);
306
+ attaching.add(held);
307
+ attachRelay(key, socket, head, handle, held).catch(() => socket.destroy());
308
+ }
309
+
310
+ async function attachRelay(key, socket, head, handle, held) {
311
+ let attached;
312
+ try {
313
+ attached = await engine.attach(handle, socket);
314
+ } catch {
315
+ attached = { ok: false, status: 500 };
316
+ } finally {
317
+ live.delete(held);
318
+ attaching.delete(held);
319
+ }
320
+ if (!attached.ok) return refuseSocket(socket, attached.status);
321
+ if (socket.destroyed || shuttingDown) {
322
+ attached.giveUp();
323
+ return refuseSocket(socket, 503);
324
+ }
325
+ try {
326
+ const entry = accept(key, socket, head, attached.start);
327
+ entry.relayed = true;
328
+ // The switch went off while the engine was answering: told now, as it
329
+ // would have been had the socket opened a moment sooner.
330
+ if (held.told) entry.bridge?.shutdown(held.told.reason, held.told.text);
331
+ } catch {
332
+ // Past the 101 a plain status cannot be sent any more.
333
+ attached.giveUp();
334
+ socket.destroy();
335
+ }
336
+ }
337
+
338
+ return { sync };
339
+ }
340
+
341
+ /** Answer an upgrade with a plain status and hang up. The answer is ended
342
+ * rather than destroyed with it, so it reaches a client that is still
343
+ * sending; a client that never closes its half is destroyed after a grace. */
344
+ function refuseSocket(socket, status, headers = {}) {
345
+ if (socket.destroyed) return;
346
+ try {
347
+ socket.end(httpRefusal(status, headers));
348
+ } catch {
349
+ socket.destroy();
350
+ return;
351
+ }
352
+ const grace = setTimeout(() => socket.destroy(), REFUSAL_GRACE_MS);
353
+ grace.unref?.();
354
+ socket.once("close", () => clearTimeout(grace));
355
+ }
356
+
357
+ /**
358
+ * Tell every open terminal why it is closing, and close it: each panel is sent
359
+ * `{ t: "exit", reason }` and a close frame, its tmux client is detached (the
360
+ * session keeps running — that is the point of tmux), and its socket is ended.
361
+ *
362
+ * bin/deck.js calls this first in its shutdown, ahead of reaping children: an
363
+ * upgraded socket is not in the HTTP server's connection list, so
364
+ * closeAllConnections() never sees it, and a tmux client killed before its
365
+ * panel was told would reach the panel as an unexplained error rather than as
366
+ * the deck going away. Answers how many it told. After it, every new upgrade
367
+ * is refused with a 503.
368
+ */
369
+ export function closeAllTerminals(reason = "server-shutdown") {
370
+ shuttingDown = true;
371
+ return closeOpenTerminals(reason);
372
+ }
373
+
374
+ /**
375
+ * Close every open terminal the way closeAllTerminals does — told why, tmux
376
+ * client detached, socket ended — without refusing the next one: the switch in
377
+ * Settings going off (prefs-routes.mjs), after which the upgrade refuses on
378
+ * its own. `text` is the sentence the panel shows. Answers how many it told.
379
+ */
380
+ export function closeOpenTerminals(reason, text) {
381
+ let told = 0;
382
+ for (const entry of [...everyTerminal]) {
383
+ told += 1;
384
+ try {
385
+ if (entry.bridge) entry.bridge.shutdown(reason, text);
386
+ else entry.conn?.close(reason === "server-shutdown" ? 1001 : 1000, reason);
387
+ } catch { /* this one is going away regardless */ }
388
+ // A relayed terminal ends its socket itself, once the engine's own close
389
+ // has gone down it (pro-engine-terminal.mjs).
390
+ if (entry.relayed && entry.bridge) continue;
391
+ // Ended rather than left for the close handshake: the shutdown has a
392
+ // second and a half, and a panel that answers its close does so to a
393
+ // socket that is already on its way out.
394
+ try { entry.socket.end(); } catch { /* already gone */ }
395
+ }
396
+ for (const held of attaching) held.told = { reason, text };
397
+ return told;
398
+ }
399
+
400
+ /** Terminal sockets open in this process, for tests and diagnostics. */
401
+ export function openTerminalCount() {
402
+ return everyTerminal.size;
403
+ }