townmouse 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/DESIGN.md +169 -0
  3. package/LICENSE +661 -0
  4. package/README.md +368 -2
  5. package/SECURITY.md +57 -0
  6. package/TOWNMOUSE.md +91 -0
  7. package/assets/brand/mascot/README.md +23 -0
  8. package/assets/brand/mascot/townmouse-aristocrat.png +0 -0
  9. package/assets/brand/mascot/townmouse-icon.svg +1 -0
  10. package/assets/brand/mascot/townmouse-monocled.png +0 -0
  11. package/bin/townmouse +68 -0
  12. package/docs/PACKAGING.md +275 -0
  13. package/docs/browser-workspace.md +184 -0
  14. package/docs/panes.md +252 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/package.json +89 -4
  17. package/public/apple-touch-icon.png +0 -0
  18. package/public/brand/floydslabs-credit.png +0 -0
  19. package/public/brand/floydslabs-credit.webp +0 -0
  20. package/public/brand/townmouse-aristocrat.webp +0 -0
  21. package/public/brand/townmouse-monocled.webp +0 -0
  22. package/public/clipboard-text.mjs +5 -0
  23. package/public/favicon-16x16.png +0 -0
  24. package/public/favicon-32x32.png +0 -0
  25. package/public/favicon.ico +0 -0
  26. package/public/favicon.svg +1 -0
  27. package/public/features/autosave.mjs +76 -0
  28. package/public/features/clipboard.mjs +69 -0
  29. package/public/features/command-palette.mjs +181 -0
  30. package/public/features/desktop-palette.mjs +19 -0
  31. package/public/features/export.mjs +37 -0
  32. package/public/features/file-drop.mjs +77 -0
  33. package/public/features/floating-palette.mjs +113 -0
  34. package/public/features/fontsize.mjs +72 -0
  35. package/public/features/haptic-keys.mjs +42 -0
  36. package/public/features/history-undo.mjs +102 -0
  37. package/public/features/keepalive.mjs +36 -0
  38. package/public/features/keybar-config.mjs +70 -0
  39. package/public/features/keyboard-shortcuts.mjs +74 -0
  40. package/public/features/links.mjs +139 -0
  41. package/public/features/multi-window-sync.mjs +74 -0
  42. package/public/features/osc-bridge.mjs +59 -0
  43. package/public/features/phone-landscape-focus.mjs +157 -0
  44. package/public/features/recent-commands.mjs +100 -0
  45. package/public/features/search.mjs +134 -0
  46. package/public/features/session-lock.mjs +96 -0
  47. package/public/features/session-manager.mjs +149 -0
  48. package/public/features/settings-sync.mjs +77 -0
  49. package/public/features/shortcut-help.mjs +85 -0
  50. package/public/features/smart-completions.mjs +101 -0
  51. package/public/features/smart-suggest.mjs +124 -0
  52. package/public/features/snippets.mjs +85 -0
  53. package/public/features/split-view.mjs +102 -0
  54. package/public/features/status-metrics.mjs +114 -0
  55. package/public/features/stylus-support.mjs +124 -0
  56. package/public/features/swipe-history.mjs +141 -0
  57. package/public/features/swipe-sessions.mjs +85 -0
  58. package/public/features/tab-reorder.mjs +62 -0
  59. package/public/features/theme-system.mjs +51 -0
  60. package/public/features/toast-status.mjs +118 -0
  61. package/public/features/two-finger-menu.mjs +87 -0
  62. package/public/features/voice-input.mjs +244 -0
  63. package/public/features/wake-fullscreen.mjs +67 -0
  64. package/public/features/window-title.mjs +40 -0
  65. package/public/features/zoom.mjs +80 -0
  66. package/public/icon-128.png +0 -0
  67. package/public/icon-180.png +0 -0
  68. package/public/icon-192.png +0 -0
  69. package/public/icon-48.png +0 -0
  70. package/public/icon-512-maskable.png +0 -0
  71. package/public/icon-512.png +0 -0
  72. package/public/icon.svg +1 -0
  73. package/public/index.html +1765 -0
  74. package/public/input-chunks.mjs +22 -0
  75. package/public/input-guard.mjs +210 -0
  76. package/public/manifest.json +56 -0
  77. package/public/panes.css +1257 -0
  78. package/public/panes.html +208 -0
  79. package/public/panes.mjs +2625 -0
  80. package/public/service-worker.js +67 -0
  81. package/public/workspace.css +1447 -0
  82. package/public/workspace.mjs +1475 -0
  83. package/scripts/install-service.sh +269 -0
  84. package/scripts/node-runtime.sh +138 -0
  85. package/scripts/panes +439 -0
  86. package/scripts/prepare-native.sh +35 -0
  87. package/scripts/run-hooks +69 -0
  88. package/scripts/t1.sh +113 -0
  89. package/scripts/uninstall-service.sh +49 -0
  90. package/src/agent-guide.js +260 -0
  91. package/src/attachments.js +128 -0
  92. package/src/browser-dom.js +545 -0
  93. package/src/browser-workspace.js +1246 -0
  94. package/src/chrome-resolve.js +80 -0
  95. package/src/pty-permissions.js +99 -0
  96. package/src/regex-worker.js +13 -0
  97. package/src/replay-text.js +189 -0
  98. package/src/request-boundary.js +58 -0
  99. package/src/safe-regex.js +87 -0
  100. package/src/server.js +1122 -0
  101. package/src/shell-resolve.js +42 -0
  102. package/src/static-deps.js +61 -0
  103. package/src/workspace-panes.js +1099 -0
package/src/server.js ADDED
@@ -0,0 +1,1122 @@
1
+ 'use strict';
2
+
3
+ const express = require('express');
4
+ const crypto = require('crypto');
5
+ const path = require('path');
6
+ const http = require('http');
7
+ const os = require('os');
8
+ const { resolveShell } = require('./shell-resolve');
9
+ const { replayTranscript } = require('./replay-text');
10
+ const fs = require('fs');
11
+ const { spawn } = require('child_process');
12
+
13
+ const WebSocket = require('ws');
14
+ const { v4: uuidv4 } = require('uuid');
15
+ const { ensurePtyHelpers, isTerminalEngineError, terminalEngineHelp } = require('./pty-permissions');
16
+
17
+ // The terminal engine is native. If it is missing (npm 12 skips dependency
18
+ // install scripts; node-pty has no Linux prebuild) the useful answer is the
19
+ // remedy, not a require stack.
20
+ let pty;
21
+ try {
22
+ pty = require('node-pty');
23
+ } catch (error) {
24
+ if (isTerminalEngineError(error)) {
25
+ console.error(terminalEngineHelp(process.platform, error.message));
26
+ process.exit(78);
27
+ }
28
+ throw error;
29
+ }
30
+
31
+ // ─── Constants ────────────────────────────────────────────────────────────────
32
+
33
+ const PORT = process.env.PORT || 11001;
34
+ // Loopback by default. Docker sets HOST=0.0.0.0 because a container's
35
+ // loopback is not reachable from the host; publish that port to loopback only.
36
+ const HOST = process.env.HOST || '127.0.0.1';
37
+ const { createRequestBoundary } = require('./request-boundary');
38
+ const { installStaticDependencies } = require('./static-deps');
39
+ const isTrustedRequest = createRequestBoundary(PORT, process.env.TERMINALONE_TRUSTED_ORIGINS || '');
40
+ const MAX_CONCURRENT_SESSIONS = 10;
41
+
42
+ // Input typed in the moment between the socket opening and the shell existing
43
+ // used to be discarded without a word, which read as "my typing does not work"
44
+ // until the user pressed the key again. Hold it instead and flush on spawn.
45
+ const MAX_PENDING_INPUT = 8192;
46
+ const PING_INTERVAL_MS = 30_000;
47
+ const PONG_TIMEOUT_MS = 5_000;
48
+ const KILL_GRACE_MS = 1_000;
49
+ const MAX_COLS = 500;
50
+ const MAX_ROWS = 200;
51
+ const STT_MAX_CHUNK_BYTES = 512 * 1024;
52
+ const STT_MAX_UTTERANCE_BYTES = 8 * 1024 * 1024;
53
+ const STT_TIMEOUT_MS = Number(process.env.TERMINALONE_STT_TIMEOUT_MS || 60_000);
54
+
55
+ // Voice settings live in the member's home so any STT command and model can be
56
+ // chosen without environment variables. Audio is staged under the cache dir so
57
+ // it never lands in the shared system temp directory.
58
+ const VOICE_CONFIG_PATH = path.join(os.homedir(), '.config', 'terminalone', 'voice.json');
59
+ const VOICE_TMP_BASE = path.join(os.homedir(), '.cache', 'terminalone');
60
+ const VOICE_DEFAULT_ARGS = '{audio} --model {model} --language {language} --output_format txt --output_dir {dir} --verbose False --fp16 False';
61
+ const VOICE_PLACEHOLDERS = new Set(['audio', 'model', 'language', 'dir', 'base', 'output']);
62
+
63
+ // Resume: when a WS drops unexpectedly, keep the PTY alive this long so the
64
+ // client can reconnect to the same session. Output produced while detached
65
+ // (and while attached) is buffered in a ring and replayed on resume.
66
+ const RESUME_GRACE_MS = 5 * 60 * 1000;
67
+
68
+ // A shell that cannot start exits immediately. Respawning it without a limit
69
+ // produced roughly 26 respawns per second, indefinitely, and looked like a
70
+ // frozen terminal. Count rapid exits, back off, then stop and explain.
71
+ const RAPID_EXIT_MS = 1500;
72
+ const MAX_RAPID_RESPAWNS = 5;
73
+ const RESPAWN_BASE_MS = 100;
74
+ const RESPAWN_MAX_MS = 5000;
75
+ const RESUME_BUFFER_MAX = 512 * 1024;
76
+
77
+ // ─── In-memory state ──────────────────────────────────────────────────────────
78
+
79
+ /** @type {Map<string, Session>} */
80
+ const activeSessions = new Map();
81
+
82
+ /** @type {Map<string, NodeJS.Timeout>} */
83
+ const pingTimers = new Map();
84
+
85
+ /** @type {Map<string, NodeJS.Timeout>} */
86
+ const pongTimers = new Map();
87
+
88
+ /** @type {Map<string, NodeJS.Timeout>} */
89
+ const graceTimers = new Map();
90
+
91
+ // ─── Structured logger ───────────────────────────────────────────────────────
92
+
93
+ /** @param {'info'|'warn'|'error'} level */
94
+ function log(level, sessionId, msg, meta = {}) {
95
+ const entry = { ts: new Date().toISOString(), level, sessionId: sessionId || null, msg, ...meta };
96
+ if (level === 'error') console.error(JSON.stringify(entry));
97
+ else console.log(JSON.stringify(entry));
98
+ }
99
+
100
+ const info = (id, msg, m) => log('info', id, msg, m);
101
+ const warn = (id, msg, m) => log('warn', id, msg, m);
102
+ const error = (id, msg, m) => log('error', id, msg, m);
103
+
104
+ // ─── Input validation ────────────────────────────────────────────────────────
105
+
106
+ /** @returns {{ cols: number, rows: number }} */
107
+ function clampDims(cols, rows) {
108
+ return {
109
+ cols: Math.max(1, Math.min(Math.floor(Number(cols)) || 120, MAX_COLS)),
110
+ rows: Math.max(1, Math.min(Math.floor(Number(rows)) || 40, MAX_ROWS))
111
+ };
112
+ }
113
+
114
+ /** Count sessions running a live shell, optionally excluding one id. */
115
+ function countRealShells(excludeId) {
116
+ let n = 0;
117
+ for (const s of activeSessions.values()) {
118
+ if (s.id === excludeId) continue;
119
+ if (s.ptyProcess && !s.processExited) n += 1;
120
+ }
121
+ return n;
122
+ }
123
+
124
+ /** @param {import('ws').WebSocket} ws @param {string} code @param {string} message @param {string|null} id */
125
+ function wsError(ws, code, message, id) {
126
+ if (ws.readyState === WebSocket.OPEN) {
127
+ try { ws.send(JSON.stringify({ type: 'error', code, message })); }
128
+ catch (e) { error(id, 'WS send error failed', { code, err: e.message }); }
129
+ }
130
+ }
131
+
132
+ /** Send one JSON message to one socket if it is open. */
133
+ function sendToSocket(ws, payload) {
134
+ if (!ws || ws.readyState !== WebSocket.OPEN) return false;
135
+ try { ws.send(JSON.stringify(payload)); return true; }
136
+ catch (_) { return false; }
137
+ }
138
+
139
+ /** Send a JSON message to every window currently attached to a session. */
140
+ function sendToSession(session, payload) {
141
+ const sockets = session.sockets && session.sockets.size
142
+ ? session.sockets
143
+ : (session.ws ? new Set([session.ws]) : new Set());
144
+ let sent = false;
145
+ const data = JSON.stringify(payload);
146
+ for (const ws of sockets) {
147
+ if (!ws || ws.readyState !== WebSocket.OPEN) continue;
148
+ try { ws.send(data); sent = true; }
149
+ catch (e) { error(session.id, 'WS send failed', { err: e.message }); }
150
+ }
151
+ return sent;
152
+ }
153
+
154
+ // ─── Output ring buffer ──────────────────────────────────────────────────────
155
+
156
+ /** Append PTY output to the session ring, evicting from the head when capped. */
157
+ function bufferOutput(session, data) {
158
+ session.outputBuffer += data;
159
+ if (session.outputBuffer.length > RESUME_BUFFER_MAX) {
160
+ // Keep only the tail beyond the cap so the most recent output survives.
161
+ const over = session.outputBuffer.length - RESUME_BUFFER_MAX;
162
+ session.outputBuffer = session.outputBuffer.slice(over);
163
+ }
164
+ }
165
+
166
+ // ─── PTY helpers ────────────────────────────────────────────────────────────
167
+
168
+ /** @param {import('node-pty').IPty|undefined} ptyProcess @param {string} id */
169
+ function killPty(ptyProcess, id) {
170
+ if (!ptyProcess || typeof ptyProcess.kill !== 'function') return;
171
+ try { ptyProcess.kill('SIGTERM'); }
172
+ catch (e) { warn(id, 'SIGTERM failed — already dead', { err: e.message }); return; }
173
+ const timer = setTimeout(() => {
174
+ try { if (ptyProcess && typeof ptyProcess.kill === 'function') ptyProcess.kill('SIGKILL'); }
175
+ catch (_) {}
176
+ }, KILL_GRACE_MS);
177
+ if (typeof ptyProcess.once === 'function') ptyProcess.once('exit', () => clearTimeout(timer));
178
+ }
179
+
180
+ // ─── Session lifecycle ───────────────────────────────────────────────────────
181
+
182
+ /** Clear the resume grace timer for a session, if any. */
183
+ function clearGraceTimer(session) {
184
+ const gt = graceTimers.get(session.id);
185
+ if (gt) { clearTimeout(gt); graceTimers.delete(session.id); }
186
+ }
187
+
188
+ function cleanupSession(session) {
189
+ const { id, ptyProcess } = session;
190
+ info(id, 'Cleaning up session');
191
+
192
+ for (const socket of session.sockets || []) socket.voice = null;
193
+ clearGraceTimer(session);
194
+
195
+ const pt = pingTimers.get(id);
196
+ clearInterval(pt);
197
+ pingTimers.delete(id);
198
+ const po = pongTimers.get(id);
199
+ clearTimeout(po);
200
+ pongTimers.delete(id);
201
+
202
+ if (ptyProcess) { killPty(ptyProcess, id); session.ptyProcess = undefined; }
203
+ for (const socket of session.sockets || []) {
204
+ try { socket.close(1000, 'session ended'); } catch (_) { /* already gone */ }
205
+ }
206
+ if (session.sockets) session.sockets.clear();
207
+ activeSessions.delete(id);
208
+ info(id, 'Session cleaned up');
209
+ }
210
+
211
+ /** @param {Session} session */
212
+ function startHeartbeat(session) {
213
+ const { id } = session;
214
+ // Replace any prior interval for this session.
215
+ clearInterval(pingTimers.get(id));
216
+
217
+ const t = setInterval(() => {
218
+ const s = activeSessions.get(id);
219
+ if (!s || !s.ws || s.ws.readyState !== WebSocket.OPEN) { clearInterval(t); pingTimers.delete(id); return; }
220
+ try { s.ws.ping(); }
221
+ catch (_) { clearInterval(t); return; }
222
+ const po = setTimeout(() => {
223
+ warn(id, 'Pong missed — closing stale session');
224
+ if (s.ws) s.ws.terminate();
225
+ }, PONG_TIMEOUT_MS);
226
+ pongTimers.set(id, po);
227
+ }, PING_INTERVAL_MS);
228
+ pingTimers.set(id, t);
229
+ }
230
+
231
+ /** Stop the heartbeat ping interval for a session (used when detaching). */
232
+ function stopHeartbeat(session) {
233
+ const { id } = session;
234
+ clearInterval(pingTimers.get(id)); pingTimers.delete(id);
235
+ clearTimeout(pongTimers.get(id)); pongTimers.delete(id);
236
+ }
237
+
238
+ // ─── PTY event wiring ──────────────────────────────────────────────────────
239
+
240
+ /**
241
+ * Attach PTY data/exit/error handlers to a session. The data handler reads
242
+ * `session.ws` dynamically so a re-attached WebSocket (resume) receives output
243
+ * without rewiring.
244
+ * @param {import('node-pty').IPty} ptyProcess
245
+ * @param {Session} session
246
+ */
247
+ function wirePtyToSession(ptyProcess, session) {
248
+ const { id } = session;
249
+
250
+ ptyProcess.onData((data) => {
251
+ // Remember the width this output was actually produced at. A resize just
252
+ // before a reload updates lastCols but not this marker.
253
+ session.lastDataCols = session.lastCols;
254
+ session.lastDataRows = session.lastRows;
255
+ session.outputChars += data.length;
256
+ // Always buffer so a subsequent resume can replay this output.
257
+ bufferOutput(session, data);
258
+ if (!session.sessionActive) return;
259
+ sendToSession(session, { type: 'output', data });
260
+ });
261
+
262
+ ptyProcess.once('exit', (code) => {
263
+ if (session.processExited) return;
264
+ session.processExited = true;
265
+
266
+ const ranFor = session.startedAt ? Date.now() - session.startedAt : Infinity;
267
+ session.rapidExits = ranFor < RAPID_EXIT_MS ? (session.rapidExits || 0) + 1 : 0;
268
+ info(id, 'Shell exited', { code, ranForMs: ranFor, rapidExits: session.rapidExits });
269
+
270
+ // If detached when the shell exits, there is nobody to receive a respawn —
271
+ // tear the session down.
272
+ if (!session.ws || session.ws.readyState !== WebSocket.OPEN) {
273
+ cleanupSession(session);
274
+ return;
275
+ }
276
+ if (!session.sessionActive) { cleanupSession(session); return; }
277
+
278
+ // Stop rather than loop. Say what happened and what to check.
279
+ if (session.rapidExits >= MAX_RAPID_RESPAWNS) {
280
+ wsError(session.ws, 'SHELL_WILL_NOT_START',
281
+ 'The shell exited immediately ' + session.rapidExits + ' times in a row, so it was '
282
+ + 'not restarted again. Check $SHELL (currently ' + resolveShell()
283
+ + ') and your shell profile.', id);
284
+ cleanupSession(session);
285
+ return;
286
+ }
287
+
288
+ try { session.ws.send(JSON.stringify({ type: 'shell-reset', code: code || 0 })); }
289
+ catch (_) {}
290
+
291
+ const delay = Math.min(RESPAWN_BASE_MS * Math.pow(2, session.rapidExits), RESPAWN_MAX_MS);
292
+ setTimeout(() => {
293
+ if (session.sessionActive && session.ws && session.ws.readyState === WebSocket.OPEN) {
294
+ spawnShell(session, session.shellCwd);
295
+ } else {
296
+ cleanupSession(session);
297
+ }
298
+ }, delay);
299
+ });
300
+
301
+ ptyProcess.on('error', (err) => {
302
+ error(id, 'PTY error', { err: err.message || String(err) });
303
+ if (session.ws) wsError(session.ws, 'PROCESS_ERROR', `Process error: ${err.message || String(err)}`, id);
304
+ cleanupSession(session);
305
+ });
306
+ }
307
+
308
+ // ─── Shell spawn helper ─────────────────────────────────────────────────────
309
+
310
+ /**
311
+ * Spawn the user's default shell into the session and wire it up.
312
+ * @param {Session} session
313
+ * @param {string} [cwd]
314
+ */
315
+ function spawnShell(session, cwd) {
316
+ const { id } = session;
317
+ const cols = session.lastCols || 120;
318
+ const rows = session.lastRows || 40;
319
+
320
+ let workingDir = cwd || process.env.HOME || os.homedir();
321
+ if (!fs.existsSync(workingDir)) workingDir = os.homedir();
322
+
323
+ const ptyEnv = { ...process.env, TERM: 'xterm-256color' };
324
+ const shell = resolveShell();
325
+
326
+ session.shellCwd = workingDir;
327
+
328
+ let ptyProcess;
329
+ try {
330
+ ptyProcess = pty.spawn(shell, ['-l'], { name: 'xterm-256color', cols, rows, cwd: workingDir, env: ptyEnv });
331
+ } catch (e) {
332
+ error(id, 'shell spawn failed', { err: e.message });
333
+ return;
334
+ }
335
+
336
+ session.ptyProcess = ptyProcess;
337
+ session.processExited = false;
338
+ session.startedAt = Date.now();
339
+ session.resizeMarkers.push({ at: session.outputChars, cols, rows });
340
+ activeSessions.set(id, session);
341
+ wirePtyToSession(ptyProcess, session);
342
+
343
+ // Deliver anything typed while this shell did not yet exist.
344
+ if (session.pendingInput) {
345
+ const queued = session.pendingInput;
346
+ session.pendingInput = '';
347
+ try { ptyProcess.write(queued); }
348
+ catch (e) { error(id, 'pending input flush failed', { err: e.message }); }
349
+ }
350
+ }
351
+
352
+ // ─── Resume: re-attach a new WebSocket to an existing session ────────────────
353
+
354
+ /**
355
+ * Re-attach `ws` onto an existing resumable session, replay buffered output,
356
+ * and resume live delivery.
357
+ *
358
+ * Handlers are bound to the WebSocket once at connect time and read the active
359
+ * session through `ws.__sessionRef` (a mutable property). On resume we simply
360
+ * re-point that property at the target session — no second set of listeners is
361
+ * registered, so there is no double-dispatch.
362
+ * @param {Session} target
363
+ * @param {import('ws').WebSocket} ws
364
+ * @param {{ cols: number, rows: number }} dims
365
+ * @param {Session} placeholder The throwaway connection session to retire.
366
+ */
367
+ function resumeSession(target, ws, dims, placeholder) {
368
+ const { id } = target;
369
+ const bufferedBytes = target.outputBuffer ? target.outputBuffer.length : 0;
370
+ // The buffer was produced at the old PTY width. Replay it into an xterm set
371
+ // to those dimensions, then fit the client to the new viewport. Replaying
372
+ // old cursor-addressed output at a new width splits words and loses lines.
373
+ const replayCols = target.lastDataCols || target.lastCols || dims.cols;
374
+ const replayRows = target.lastDataRows || target.lastRows || dims.rows;
375
+ // Same-width resume can replay colors and cursor addressing safely. A width
376
+ // change cannot: xterm's reflow of old shell redraws splits command lines.
377
+ // Use a control-code-free transcript of the final screen text instead.
378
+ const transcript = target.widthChanged || replayCols !== dims.cols || replayRows !== dims.rows;
379
+
380
+ // Retire the placeholder connection session (the one created at connect).
381
+ activeSessions.delete(placeholder.id);
382
+ stopHeartbeat(placeholder);
383
+
384
+ // Adopt the new connection onto the target session.
385
+ target.ws = ws;
386
+ target.sessionActive = true;
387
+ if (!target.sockets) target.sockets = new Set();
388
+ target.sockets.add(ws);
389
+ ws.__sessionRef = target; // re-point handlers at the resumed session
390
+
391
+ // Cancel the resume grace countdown — we're live again.
392
+ clearGraceTimer(target);
393
+
394
+ // Restart heartbeat for the new socket.
395
+ startHeartbeat(target);
396
+
397
+ // Acknowledge resume with the dimensions the buffered output was rendered
398
+ // at. The client resizes its xterm to these before writing any replay bytes
399
+ // and waits for `replay-end` before fitting to the viewport.
400
+ sendToSocket(ws, {
401
+ type: 'ready',
402
+ sessionId: id,
403
+ command: target.command || resolveShell(),
404
+ cwd: target.shellCwd,
405
+ resumed: true,
406
+ transcript,
407
+ cols: replayCols,
408
+ rows: replayRows
409
+ });
410
+
411
+ if (target.outputBuffer) {
412
+ const raw = target.outputBuffer;
413
+ target.outputBuffer = '';
414
+ let buf = raw;
415
+ if (transcript) {
416
+ const rawStart = Math.max(0, target.outputChars - raw.length);
417
+ let initial = { cols: replayCols };
418
+ const segments = [];
419
+ for (const marker of target.resizeMarkers) {
420
+ if (marker.at <= rawStart) initial = marker;
421
+ else if (marker.at < target.outputChars) {
422
+ segments.push({ at: marker.at - rawStart, cols: marker.cols });
423
+ }
424
+ }
425
+ segments.unshift({ at: 0, cols: initial.cols });
426
+ buf = replayTranscript(raw, segments).replace(/\n/g, '\r\n');
427
+ }
428
+ // Send in chunks to avoid a single oversized WS frame.
429
+ const CHUNK = 16 * 1024;
430
+ for (let i = 0; i < buf.length; i += CHUNK) {
431
+ let end = Math.min(i + CHUNK, buf.length);
432
+ if (end < buf.length) {
433
+ const last = buf.charCodeAt(end - 1);
434
+ if (last >= 0xD800 && last <= 0xDBFF) end -= 1;
435
+ }
436
+ sendToSocket(ws, { type: 'output', data: buf.slice(i, end) });
437
+ i = end - CHUNK;
438
+ }
439
+ }
440
+ sendToSocket(ws, { type: 'replay-end' });
441
+
442
+ // Only after the replay is on the wire do we resize the live PTY to the new
443
+ // client viewport. New output is therefore produced at the new width while
444
+ // the old buffer remains coherent at the old width.
445
+ if (dims.cols !== target.lastCols || dims.rows !== target.lastRows) {
446
+ target.widthChanged = true;
447
+ target.resizeMarkers.push({ at: target.outputChars, cols: dims.cols, rows: dims.rows });
448
+ }
449
+ target.lastCols = dims.cols;
450
+ target.lastRows = dims.rows;
451
+ if (target.ptyProcess && !target.processExited) {
452
+ try { target.ptyProcess.resize(dims.cols, dims.rows); }
453
+ catch (e) { warn(id, 'resume resize failed', { err: e.message }); }
454
+ }
455
+
456
+ info(id, 'Session resumed', { bufferedBytes, replayCols, replayRows, cols: dims.cols, rows: dims.rows });
457
+ }
458
+
459
+ // ─── Speech-to-text helpers ─────────────────────────────────────────────────
460
+
461
+ function voiceError(ws, code, message) {
462
+ sendToSocket(ws, { type: 'voice-error', code, message });
463
+ }
464
+
465
+ function extForMime(mimeType) {
466
+ const mt = String(mimeType || '').toLowerCase();
467
+ if (mt.includes('wav')) return 'wav';
468
+ if (mt.includes('mp4') || mt.includes('aac') || mt.includes('m4a')) return 'm4a';
469
+ if (mt.includes('ogg')) return 'ogg';
470
+ return 'webm';
471
+ }
472
+
473
+ function defaultVoiceConfig() {
474
+ return {
475
+ command: process.env.TERMINALONE_STT_BIN || 'whisper',
476
+ model: process.env.TERMINALONE_STT_MODEL || 'tiny.en',
477
+ language: process.env.TERMINALONE_STT_LANGUAGE || 'en',
478
+ args: VOICE_DEFAULT_ARGS
479
+ };
480
+ }
481
+
482
+ function readVoiceConfig() {
483
+ const config = defaultVoiceConfig();
484
+ // Explicit deployment or test environment wins over the saved UI setting.
485
+ if (process.env.TERMINALONE_STT_BIN || process.env.TERMINALONE_STT_MODEL || process.env.TERMINALONE_STT_LANGUAGE) {
486
+ return config;
487
+ }
488
+ let raw;
489
+ try { raw = fs.readFileSync(VOICE_CONFIG_PATH, 'utf8'); }
490
+ catch (_) { return config; }
491
+ let saved;
492
+ try { saved = JSON.parse(raw); }
493
+ catch (_) { return config; }
494
+ if (!saved || typeof saved !== 'object') return config;
495
+ for (const key of ['command', 'model', 'language', 'args']) {
496
+ if (typeof saved[key] === 'string') config[key] = saved[key];
497
+ }
498
+ return config;
499
+ }
500
+
501
+ function validateVoiceConfig(input) {
502
+ const source = input && typeof input === 'object' ? input : {};
503
+ const command = typeof source.command === 'string' ? source.command.trim() : '';
504
+ if (!command) return { ok: false, error: 'command must not be empty' };
505
+ if (/[\u0000-\u001f\u007f]/.test(command)) return { ok: false, error: 'command must not contain NUL, newline, or control characters' };
506
+
507
+ const model = typeof source.model === 'string' ? source.model.trim() : '';
508
+ if (!model) return { ok: false, error: 'model must not be empty' };
509
+ if (/[\u0000-\u001f\u007f]/.test(model)) return { ok: false, error: 'model must not contain NUL, newline, or control characters' };
510
+
511
+ const language = typeof source.language === 'string' ? source.language.trim().toLowerCase() : '';
512
+ if (!/^(?:[a-z]{2,3}|auto)$/.test(language)) return { ok: false, error: 'language must be a two- or three-letter code, or auto' };
513
+
514
+ const args = typeof source.args === 'string' ? source.args.trim() : '';
515
+ if (!args) return { ok: false, error: 'args must not be empty' };
516
+ if (args.includes('\u0000')) return { ok: false, error: 'args must not contain NUL characters' };
517
+ if (!args.includes('{audio}')) return { ok: false, error: 'args must contain {audio}' };
518
+ const unknown = [...args.matchAll(/\{([^{}]*)\}/g)]
519
+ .map((match) => match[1])
520
+ .filter((name) => !VOICE_PLACEHOLDERS.has(name));
521
+ if (unknown.length) return { ok: false, error: `unknown placeholder {${unknown[0]}}` };
522
+
523
+ return { ok: true, value: { command, model, language, args } };
524
+ }
525
+
526
+ function writeVoiceConfig(config) {
527
+ fs.mkdirSync(path.dirname(VOICE_CONFIG_PATH), { recursive: true, mode: 0o700 });
528
+ const body = JSON.stringify({
529
+ command: config.command,
530
+ model: config.model,
531
+ language: config.language,
532
+ args: config.args
533
+ }, null, 2) + '\n';
534
+ fs.writeFileSync(VOICE_CONFIG_PATH, body, { mode: 0o600 });
535
+ try { fs.chmodSync(VOICE_CONFIG_PATH, 0o600); } catch (_) {}
536
+ }
537
+
538
+ function resolveVoiceCommand(command) {
539
+ if (typeof command !== 'string' || !command) return { commandFound: false, commandPath: null };
540
+ if (command.includes('/')) {
541
+ const candidate = path.isAbsolute(command) ? command : path.resolve(command);
542
+ try {
543
+ fs.accessSync(candidate, fs.constants.X_OK);
544
+ return { commandFound: true, commandPath: candidate };
545
+ } catch (_) {
546
+ return { commandFound: false, commandPath: null };
547
+ }
548
+ }
549
+ for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
550
+ if (!dir) continue;
551
+ const candidate = path.join(dir, command);
552
+ try {
553
+ fs.accessSync(candidate, fs.constants.X_OK);
554
+ return { commandFound: true, commandPath: candidate };
555
+ } catch (_) {}
556
+ }
557
+ return { commandFound: false, commandPath: null };
558
+ }
559
+
560
+ function voiceSettingsPayload() {
561
+ const config = readVoiceConfig();
562
+ return { ...config, resolved: resolveVoiceCommand(config.command) };
563
+ }
564
+
565
+ function buildVoiceArgs(config, values) {
566
+ return config.args
567
+ .split(/\s+/)
568
+ .filter(Boolean)
569
+ .map((token) => token.replace(/\{(audio|model|language|dir|base|output)\}/g, (_, key) => values[key]));
570
+ }
571
+
572
+ function cleanupTempDir(dir) {
573
+ if (!dir) return;
574
+ const absolute = path.resolve(dir);
575
+ const allowed = [path.resolve(VOICE_TMP_BASE), path.resolve(os.tmpdir())];
576
+ if (!allowed.some((base) => absolute.startsWith(base + path.sep))) return;
577
+ fs.rm(dir, { recursive: true, force: true }, () => {});
578
+ }
579
+
580
+ function transcriptFromSrt(text) {
581
+ return String(text || '')
582
+ .split(/\r?\n/)
583
+ .map((line) => line.trim())
584
+ .filter((line) => line && !/^\d+$/.test(line) && !line.includes('-->'))
585
+ .join('\n')
586
+ .trim();
587
+ }
588
+
589
+ function readTranscriptText(tmpDir, base, cb) {
590
+ const txtPath = path.join(tmpDir, `${base}.txt`);
591
+ fs.readFile(txtPath, 'utf8', (err, text) => {
592
+ if (!err) { cb(null, text); return; }
593
+ if (err.code !== 'ENOENT') { cb(err); return; }
594
+ fs.readFile(path.join(tmpDir, `${base}.srt`), 'utf8', (srtErr, srt) => {
595
+ if (srtErr) { cb(srtErr); return; }
596
+ cb(null, transcriptFromSrt(srt));
597
+ });
598
+ });
599
+ }
600
+
601
+ function transcribeAudioFile(session, ws, audioPath, tmpDir) {
602
+ const checked = validateVoiceConfig(readVoiceConfig());
603
+ if (!checked.ok) {
604
+ warn(session.id, 'Voice settings are invalid', { error: checked.error });
605
+ voiceError(ws, 'STT_FAILED', `Voice settings are invalid: ${checked.error}`);
606
+ cleanupTempDir(tmpDir);
607
+ return;
608
+ }
609
+ const config = checked.value;
610
+ const base = path.basename(audioPath, path.extname(audioPath));
611
+ const args = buildVoiceArgs(config, {
612
+ audio: audioPath,
613
+ model: config.model,
614
+ language: config.language,
615
+ dir: tmpDir,
616
+ base,
617
+ output: path.join(tmpDir, `${base}.txt`)
618
+ });
619
+
620
+ info(session.id, 'Starting local STT transcription', {
621
+ command: config.command, model: config.model, language: config.language
622
+ });
623
+ const child = spawn(config.command, args, { stdio: ['ignore', 'ignore', 'pipe'] });
624
+ let stderr = '';
625
+ let settled = false;
626
+ const timer = setTimeout(() => {
627
+ settled = true;
628
+ child.kill('SIGTERM');
629
+ voiceError(ws, 'STT_TIMEOUT', 'Speech transcription timed out');
630
+ cleanupTempDir(tmpDir);
631
+ }, STT_TIMEOUT_MS);
632
+
633
+ child.stderr.on('data', (chunk) => {
634
+ stderr = (stderr + chunk.toString()).slice(-4000);
635
+ });
636
+ child.on('error', (err) => {
637
+ if (settled) return;
638
+ settled = true;
639
+ clearTimeout(timer);
640
+ const code = err.code === 'ENOENT' ? 'STT_UNAVAILABLE' : 'STT_ERROR';
641
+ voiceError(ws, code, err.code === 'ENOENT' ? 'Local whisper command not found' : err.message);
642
+ cleanupTempDir(tmpDir);
643
+ });
644
+ child.on('exit', (code) => {
645
+ if (settled) return;
646
+ settled = true;
647
+ clearTimeout(timer);
648
+ if (code !== 0) {
649
+ warn(session.id, 'Local STT failed', { code, stderr });
650
+ voiceError(ws, 'STT_FAILED', 'Speech transcription failed');
651
+ cleanupTempDir(tmpDir);
652
+ return;
653
+ }
654
+ readTranscriptText(tmpDir, base, (readErr, text) => {
655
+ cleanupTempDir(tmpDir);
656
+ if (readErr) {
657
+ voiceError(ws, 'STT_NO_TRANSCRIPT', 'Speech transcription produced no text');
658
+ return;
659
+ }
660
+ const transcript = String(text || '').trim();
661
+ if (!transcript) {
662
+ voiceError(ws, 'STT_NO_TRANSCRIPT', 'Speech transcription produced no text');
663
+ return;
664
+ }
665
+ sendToSocket(ws, { type: 'voice-transcript', text: transcript });
666
+ info(session.id, 'Local STT transcript ready', { chars: transcript.length });
667
+ });
668
+ });
669
+ }
670
+
671
+ function finalizeVoice(session, ws) {
672
+ const voice = ws.voice;
673
+ ws.voice = null;
674
+ if (!voice || !voice.chunks.length || voice.bytes <= 0) {
675
+ voiceError(ws, 'VOICE_EMPTY', 'No voice audio was captured');
676
+ return;
677
+ }
678
+
679
+ let tmpDir;
680
+ try {
681
+ fs.mkdirSync(VOICE_TMP_BASE, { recursive: true, mode: 0o700 });
682
+ tmpDir = fs.mkdtempSync(path.join(VOICE_TMP_BASE, 'stt-'));
683
+ } catch (err) {
684
+ voiceError(ws, 'VOICE_WRITE_FAILED', 'Could not create a voice transcription folder');
685
+ return;
686
+ }
687
+ const audioPath = path.join(tmpDir, `utterance.${extForMime(voice.mimeType)}`);
688
+ fs.writeFile(audioPath, Buffer.concat(voice.chunks), (err) => {
689
+ if (err) {
690
+ voiceError(ws, 'VOICE_WRITE_FAILED', 'Could not save voice audio for transcription');
691
+ cleanupTempDir(tmpDir);
692
+ return;
693
+ }
694
+ transcribeAudioFile(session, ws, audioPath, tmpDir);
695
+ });
696
+ }
697
+
698
+ // ─── Message dispatcher ─────────────────────────────────────────────────────
699
+
700
+ /** @param {Session} session @param {import('ws').WebSocket} ws @param {object} data */
701
+ function handleMessage(session, ws, data) {
702
+ if (!session.sessionActive && data.type !== 'resume' && data.type !== 'shell') return;
703
+ // A superseded socket must not close, re-shell, or re-adopt the session out
704
+ // from under the window that currently owns it.
705
+ if (session.ws && session.ws !== ws && ['close', 'shell', 'resume'].includes(data.type)) return;
706
+
707
+ switch (data.type) {
708
+ case 'shell': {
709
+ if (session.ptyProcess && !session.processExited) {
710
+ try { session.ptyProcess.kill(); } catch (_) {}
711
+ }
712
+ const { cols, rows } = clampDims(data.cols, data.rows);
713
+ session.lastCols = cols;
714
+ session.lastRows = rows;
715
+ // Enforce the concurrent-shell cap. Fresh spawns only — resume reuses an
716
+ // existing session and is exempt. The current (placeholder) session has no
717
+ // PTY yet and is excluded from the count.
718
+ if (countRealShells(session.id) >= MAX_CONCURRENT_SESSIONS) {
719
+ wsError(ws, 'SESSION_LIMIT', 'Maximum concurrent sessions reached', session.id);
720
+ break;
721
+ }
722
+ spawnShell(session, data.cwd || process.env.HOME || os.homedir());
723
+ if (ws.readyState === WebSocket.OPEN) {
724
+ ws.send(JSON.stringify({ type: 'ready', sessionId: session.id, command: resolveShell(), cwd: session.shellCwd }));
725
+ }
726
+ break;
727
+ }
728
+ case 'resume': {
729
+ // Look up the requested session and adopt it onto this connection.
730
+ const targetId = String(data.sessionId || '');
731
+ const target = activeSessions.get(targetId);
732
+ if (target && target.ptyProcess && !target.processExited) {
733
+ resumeSession(target, ws, clampDims(data.cols, data.rows), session);
734
+ } else {
735
+ info(session.id, 'Resume failed — target not resumable', { targetId });
736
+ if (ws.readyState === WebSocket.OPEN) {
737
+ ws.send(JSON.stringify({ type: 'resume-failed', sessionId: targetId, reason: 'not-found' }));
738
+ }
739
+ }
740
+ break;
741
+ }
742
+ case 'input': {
743
+ if (typeof data.data !== 'string') break;
744
+ if (session.ptyProcess && !session.processExited) {
745
+ try { session.ptyProcess.write(data.data); }
746
+ catch (e) { wsError(ws, 'WRITE_FAILED', `Write failed: ${e.message}`, session.id); }
747
+ } else {
748
+ // No shell yet: keep the keys rather than throwing them away.
749
+ const queued = (session.pendingInput || '') + data.data;
750
+ session.pendingInput = queued.length > MAX_PENDING_INPUT
751
+ ? queued.slice(-MAX_PENDING_INPUT)
752
+ : queued;
753
+ }
754
+ break;
755
+ }
756
+ case 'voice-start': {
757
+ // Capture and response ownership belong to this window, not the shared PTY.
758
+ ws.voice = {
759
+ chunks: [],
760
+ bytes: 0,
761
+ mimeType: typeof data.mimeType === 'string' ? data.mimeType.slice(0, 80) : '',
762
+ startedAt: Date.now()
763
+ };
764
+ sendToSocket(ws, { type: 'voice-ready' });
765
+ break;
766
+ }
767
+ case 'voice-chunk': {
768
+ if (!ws.voice) {
769
+ voiceError(ws, 'VOICE_NOT_STARTED', 'Voice input was not started');
770
+ break;
771
+ }
772
+ if (typeof data.b64 !== 'string' || data.b64.length === 0) {
773
+ voiceError(ws, 'VOICE_BAD_CHUNK', 'Voice chunk was empty or invalid');
774
+ break;
775
+ }
776
+ let chunk;
777
+ try { chunk = Buffer.from(data.b64, 'base64'); }
778
+ catch (_) { chunk = Buffer.alloc(0); }
779
+ if (!chunk.length) {
780
+ voiceError(ws, 'VOICE_BAD_CHUNK', 'Voice chunk could not be decoded');
781
+ break;
782
+ }
783
+ if (chunk.length > STT_MAX_CHUNK_BYTES) {
784
+ ws.voice = null;
785
+ voiceError(ws, 'VOICE_CHUNK_TOO_LARGE', 'Voice chunk exceeded the size limit');
786
+ break;
787
+ }
788
+ if (ws.voice.bytes + chunk.length > STT_MAX_UTTERANCE_BYTES) {
789
+ ws.voice = null;
790
+ voiceError(ws, 'VOICE_TOO_LARGE', 'Voice utterance exceeded the size limit');
791
+ break;
792
+ }
793
+ ws.voice.chunks.push(chunk);
794
+ ws.voice.bytes += chunk.length;
795
+ break;
796
+ }
797
+ case 'voice-end': {
798
+ finalizeVoice(session, ws);
799
+ break;
800
+ }
801
+ case 'resize': {
802
+ const { cols, rows } = clampDims(data.cols, data.rows);
803
+ if (cols !== session.lastCols || rows !== session.lastRows) {
804
+ session.widthChanged = true;
805
+ session.resizeMarkers.push({ at: session.outputChars, cols, rows });
806
+ }
807
+ session.lastCols = cols;
808
+ session.lastRows = rows;
809
+ if (session.ptyProcess && !session.processExited) {
810
+ try { session.ptyProcess.resize(cols, rows); }
811
+ catch (e) { wsError(ws, 'RESIZE_FAILED', `Resize failed: ${e.message}`, session.id); }
812
+ }
813
+ break;
814
+ }
815
+ case 'close': {
816
+ // Explicit user-initiated close → full teardown of this session.
817
+ session.userClosed = true;
818
+ if (session.ptyProcess && !session.processExited) cleanupSession(session);
819
+ break;
820
+ }
821
+ case 'ping': {
822
+ if (ws.readyState === WebSocket.OPEN) {
823
+ ws.send(JSON.stringify({ type: 'pong', ts: data.ts }));
824
+ }
825
+ break;
826
+ }
827
+ case 'pong': {
828
+ clearTimeout(pongTimers.get(session.id));
829
+ pongTimers.delete(session.id);
830
+ break;
831
+ }
832
+ default: wsError(ws, 'UNKNOWN_MESSAGE', `Unknown message type: ${data.type}`, session.id);
833
+ }
834
+ }
835
+
836
+ // ─── WS event binding ───────────────────────────────────────────────────────
837
+
838
+ /**
839
+ * Bind a freshly-connected WS onto a session. Handlers read the active session
840
+ * through `ws.__sessionRef`, so a resume that re-points that property needs no
841
+ * re-registration (and therefore cannot double-dispatch).
842
+ * @param {import('ws').WebSocket} ws
843
+ * @param {Session} session
844
+ */
845
+ function bindWsToSession(ws, session) {
846
+ ws.__sessionRef = session;
847
+
848
+ const remoteAddr = ws._socket?.remoteAddress || null;
849
+ info(session.id, 'WebSocket connected', { ip: remoteAddr });
850
+
851
+ ws.on('message', (message) => {
852
+ const s = ws.__sessionRef;
853
+ if (!s) return;
854
+ try { handleMessage(s, ws, JSON.parse(message)); }
855
+ catch (err) { error(s.id, 'Failed to parse WS message', { err: err.message }); wsError(ws, 'PARSE_ERROR', 'Malformed JSON message', s.id); }
856
+ });
857
+
858
+ ws.on('pong', () => {
859
+ const s = ws.__sessionRef;
860
+ if (!s) return;
861
+ clearTimeout(pongTimers.get(s.id));
862
+ pongTimers.delete(s.id);
863
+ });
864
+
865
+ ws.on('close', (code, reason) => {
866
+ ws.voice = null;
867
+ const s = ws.__sessionRef;
868
+ if (!s) return;
869
+ info(s.id, 'WebSocket disconnected', { code, reason: reason?.toString?.() || '', userClosed: !!s.userClosed });
870
+
871
+ // Explicit close already cleaned up the session; close any other windows
872
+ // attached to it and retire the record.
873
+ if (s.userClosed) {
874
+ for (const socket of s.sockets || []) {
875
+ if (socket !== ws) {
876
+ try { socket.close(1000, 'session closed'); } catch (_) { /* already gone */ }
877
+ }
878
+ }
879
+ if (s.sockets) s.sockets.clear();
880
+ activeSessions.delete(s.id);
881
+ return;
882
+ }
883
+ if (!s.sockets) s.sockets = new Set(s.ws ? [s.ws] : []);
884
+ s.sockets.delete(ws);
885
+ // Other windows still hold this shell: keep it live and hand ownership to
886
+ // one of them. Closing one window must not detach the rest.
887
+ if (s.sockets.size > 0) {
888
+ if (s.ws === ws || !s.ws) {
889
+ s.ws = [...s.sockets].find((socket) => socket.readyState === WebSocket.OPEN) || null;
890
+ }
891
+ return;
892
+ }
893
+ // A socket that was superseded by a newer resume must not detach the new
894
+ // window or start a grace timer underneath it.
895
+ if (s.ws && s.ws !== ws) return;
896
+ // Unexpected drop: keep the PTY alive and start the resume grace window.
897
+ if (s.ptyProcess && !s.processExited) {
898
+ s.ws = null;
899
+ s.sessionActive = false;
900
+ stopHeartbeat(s);
901
+ if (!graceTimers.has(s.id)) {
902
+ info(s.id, 'Session entering resume grace', { graceMs: RESUME_GRACE_MS });
903
+ const gt = setTimeout(() => {
904
+ warn(s.id, 'Resume grace expired — cleaning up detached session');
905
+ cleanupSession(s);
906
+ }, RESUME_GRACE_MS);
907
+ graceTimers.set(s.id, gt);
908
+ }
909
+ } else {
910
+ // No live PTY to preserve — just drop the placeholder.
911
+ activeSessions.delete(s.id);
912
+ }
913
+ });
914
+
915
+ ws.on('error', (err) => {
916
+ const s = ws.__sessionRef;
917
+ error(s ? s.id : null, 'WebSocket error', { err: err.message || String(err) });
918
+ // An error does not necessarily kill the socket; mark inactive and let the
919
+ // close handler decide grace vs cleanup. Never let a superseded socket
920
+ // mark the live owner inactive.
921
+ if (s && (!s.ws || s.ws === ws) && (!s.sockets || s.sockets.size <= 1)) s.sessionActive = false;
922
+ });
923
+ }
924
+
925
+ // ─── Express app ────────────────────────────────────────────────────────────
926
+
927
+ const app = express();
928
+ app.use((req, res, next) => {
929
+ if (!isTrustedRequest(req)) return res.status(403).json({ error: 'This address or request origin is not allowed. Use the local address or a configured authenticated HTTPS proxy.' });
930
+ res.setHeader('X-Content-Type-Options', 'nosniff');
931
+ res.setHeader('Content-Security-Policy', "frame-ancestors 'none'");
932
+ next();
933
+ });
934
+
935
+ // Owner capability cookie. Terminal agents must never be able to bootstrap the
936
+ // human workspace just because they can reach loopback: an Authorization header
937
+ // is denied at the bootstrap routes, and a header-less local client has no
938
+ // capability at all. The cookie is minted only on a real page navigation and is
939
+ // HttpOnly + SameSite=Strict, so page scripts and cross-site requests cannot
940
+ // read or replay it.
941
+ const OWNER_COOKIE = 'townmouse_owner';
942
+ const OWNER_CAPABILITY = crypto.randomBytes(32).toString('hex');
943
+ app.use((req, res, next) => {
944
+ const ownerPage = req.method === 'GET' &&
945
+ (req.path === '/' || req.path === '/index.html' || req.path === '/panes' || req.path === '/panes.html');
946
+ // Node's fetch (used by the integration tests) cannot send Sec-Fetch-Mode;
947
+ // a document navigation also identifies itself with Accept: text/html.
948
+ const navigates = req.get('Sec-Fetch-Mode') === 'navigate' ||
949
+ String(req.get('Accept') || '').includes('text/html');
950
+ if (ownerPage && !req.get('Authorization') && navigates) {
951
+ res.cookie(OWNER_COOKIE, OWNER_CAPABILITY, {
952
+ httpOnly: true,
953
+ sameSite: 'strict',
954
+ path: '/',
955
+ maxAge: 12 * 60 * 60 * 1000
956
+ });
957
+ }
958
+ const cookies = String(req.headers.cookie || '').split(/;\s*/);
959
+ req.isOwner = cookies.includes(`${OWNER_COOKIE}=${OWNER_CAPABILITY}`);
960
+ next();
961
+ });
962
+
963
+ // Attachments must be mounted before the global JSON parser: JSON files are
964
+ // valid uploads and the raw parser, not express.json, must consume their body.
965
+ require('./attachments').installAttachments(app);
966
+ // Pane input/command bodies can be large pastes. 2 MB keeps a single request
967
+ // below the attachment limit while still bounding local API requests.
968
+ app.use(express.json({ limit: '2mb' }));
969
+ // Repair node-pty's spawn-helper mode before any pane can spawn. npm tarballs do
970
+ // not carry the executable bit, and npm 12 does not run dependency postinstalls,
971
+ // so this cannot be left to the install step.
972
+ const ptyHelpers = ensurePtyHelpers();
973
+ if (ptyHelpers.fixed.length) {
974
+ info(null, 'Repaired node-pty spawn helper permissions', { dir: ptyHelpers.dir, files: ptyHelpers.fixed.length });
975
+ }
976
+
977
+ const browserWorkspace = require('./browser-workspace').installBrowserWorkspace(app);
978
+ const closeBrowsers = () => browserWorkspace.closeAll();
979
+
980
+ // workspace-panes loads node-pty at module load. If the native engine is
981
+ // missing, explain the actual fix instead of dying in a require stack.
982
+ let paneWorkspace;
983
+ try {
984
+ paneWorkspace = require('./workspace-panes').installWorkspacePanes(app, browserWorkspace, { port: PORT });
985
+ } catch (error) {
986
+ if (isTerminalEngineError(error)) {
987
+ console.error(terminalEngineHelp(process.platform, error.message));
988
+ process.exit(78);
989
+ }
990
+ throw error;
991
+ }
992
+
993
+ // App assets are served with no-store so the browser always runs the latest
994
+ // frontend (critical during input/dictation iteration — a cached input-guard.mjs
995
+ // silently reproduces already-fixed echo bugs).
996
+ app.get('/panes', (req, res) => res.sendFile(path.join(__dirname, '..', 'public', 'panes.html')));
997
+ app.use(express.static(path.join(__dirname, '..', 'public'), {
998
+ setHeaders: (res) => res.setHeader('Cache-Control', 'no-store'),
999
+ }));
1000
+ // Resolve dependency assets through Node's lookup paths: a hoisted `npm install`
1001
+ // has no package-local node_modules, and the terminal page would 404 its engine.
1002
+ // This replaces the old blanket static mount, which both missed hoisted installs
1003
+ // and served every file under node_modules.
1004
+ installStaticDependencies(app);
1005
+
1006
+ app.get('/health', (req, res) => {
1007
+ // `browser.engine` is reported without launching it: an install with no
1008
+ // Chromium is healthy for terminal work and should say why browser panes
1009
+ // cannot start instead of failing later with a stack trace.
1010
+ let browser = { engine: 'unknown' };
1011
+ try { browser = browserWorkspace.engineStatus(); } catch (_) { /* reported as unknown */ }
1012
+ res.json({ status: 'ok', sessions: activeSessions.size, browser });
1013
+ });
1014
+ app.get('/api/voice/settings', (req, res) => {
1015
+ res.json(voiceSettingsPayload());
1016
+ });
1017
+ app.put('/api/voice/settings', (req, res) => {
1018
+ const checked = validateVoiceConfig(req.body || {});
1019
+ if (!checked.ok) { res.status(400).json({ error: checked.error }); return; }
1020
+ try {
1021
+ writeVoiceConfig(checked.value);
1022
+ } catch (err) {
1023
+ error(null, 'Could not save voice settings', { err: err.message });
1024
+ res.status(500).json({ error: `Could not save voice settings: ${err.message}` });
1025
+ return;
1026
+ }
1027
+ res.json({ ...checked.value, resolved: resolveVoiceCommand(checked.value.command) });
1028
+ });
1029
+ app.get('/admin/sessions', (req, res) => {
1030
+ const sessions = Array.from(activeSessions.values()).map((s) => {
1031
+ const resumable = !s.ws && !!s.ptyProcess && !s.processExited && graceTimers.has(s.id);
1032
+ return {
1033
+ id: s.id, command: s.command || resolveShell(),
1034
+ startedAt: s.startedAt || null, durationMs: s.startedAt ? Date.now() - s.startedAt : null,
1035
+ processExited: s.processExited,
1036
+ attached: !!s.ws,
1037
+ resumable,
1038
+ bufferedBytes: s.outputBuffer ? s.outputBuffer.length : 0
1039
+ };
1040
+ });
1041
+ const resumableCount = sessions.filter((s) => s.resumable).length;
1042
+ res.json({ active: activeSessions.size, max: MAX_CONCURRENT_SESSIONS, resumableCount, sessions });
1043
+ });
1044
+ app.post('/admin/sessions/:id/kill', (req, res) => {
1045
+ const s = activeSessions.get(req.params.id);
1046
+ if (!s) { res.status(404).json({ error: 'Session not found' }); return; }
1047
+ cleanupSession(s);
1048
+ res.json({ ok: true, id: req.params.id });
1049
+ });
1050
+
1051
+ // ─── HTTP + WebSocket server ────────────────────────────────────────────────
1052
+
1053
+ const server = http.createServer(app);
1054
+ const wss = new WebSocket.Server({ server, verifyClient: ({ req }) => isTrustedRequest(req) });
1055
+
1056
+ wss.on('connection', (ws) => {
1057
+ // Each connection starts as a fresh placeholder session. It becomes "real"
1058
+ // when the client sends `shell`, or it adopts an existing session via `resume`.
1059
+ const sessionId = uuidv4();
1060
+ /** @type {Session} */
1061
+ const session = {
1062
+ id: sessionId,
1063
+ command: null,
1064
+ ptyProcess: undefined,
1065
+ sessionActive: true,
1066
+ processExited: false,
1067
+ ws,
1068
+ startedAt: Date.now(),
1069
+ outputBuffer: '',
1070
+ lastCols: 120,
1071
+ lastRows: 40,
1072
+ lastDataCols: null,
1073
+ lastDataRows: null,
1074
+ widthChanged: false,
1075
+ outputChars: 0,
1076
+ resizeMarkers: [],
1077
+ sockets: new Set([ws]),
1078
+ userClosed: false
1079
+ };
1080
+ activeSessions.set(sessionId, session);
1081
+
1082
+ bindWsToSession(ws, session);
1083
+ startHeartbeat(session);
1084
+ });
1085
+
1086
+ // ─── Graceful shutdown ─────────────────────────────────────────────────────
1087
+
1088
+ /** @param {string} signal */
1089
+ async function shutdown(signal, exitCode = 0) {
1090
+ info(null, `Received ${signal}, starting graceful shutdown`, { activeSessions: activeSessions.size });
1091
+ server.close();
1092
+ await paneWorkspace.closeAll().catch(err => error(null, 'Pane shutdown failed', {err:err.message}));
1093
+ await closeBrowsers().catch(err => error(null, 'Browser shutdown failed', {err:err.message}));
1094
+ const promises = Array.from(activeSessions.values()).map((s) => {
1095
+ clearGraceTimer(s);
1096
+ if (s.ptyProcess) killPty(s.ptyProcess, s.id);
1097
+ activeSessions.delete(s.id);
1098
+ return new Promise((r) => setTimeout(r, KILL_GRACE_MS + 100));
1099
+ });
1100
+ await Promise.race([Promise.all(promises), new Promise((r) => setTimeout(r, 5_000))]);
1101
+ info(null, 'Shutdown complete', { activeSessions: activeSessions.size });
1102
+ process.exit(exitCode);
1103
+ }
1104
+
1105
+ process.on('unhandledRejection', (reason) => {
1106
+ const message = reason instanceof Error ? reason.stack || reason.message : String(reason);
1107
+ error(null, 'Unhandled promise rejection', { err: message });
1108
+ });
1109
+
1110
+ process.on('uncaughtException', (err) => {
1111
+ error(null, 'Uncaught exception — shutting down', { err: err?.stack || String(err) });
1112
+ const force = setTimeout(() => process.exit(1), 6000);
1113
+ force.unref?.();
1114
+ shutdown('uncaughtException', 1).catch(() => process.exit(1));
1115
+ });
1116
+
1117
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
1118
+ process.on('SIGINT', () => shutdown('SIGINT'));
1119
+
1120
+ server.listen(PORT, HOST, () => {
1121
+ info(null, `Townmouse running at http://localhost:${PORT}`, { maxSessions: MAX_CONCURRENT_SESSIONS });
1122
+ });