townmouse 0.0.0-stage → 0.4.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 (108) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/DESIGN.md +153 -0
  3. package/LICENSE +661 -0
  4. package/README.md +600 -2
  5. package/SECURITY.md +60 -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 +371 -0
  13. package/docs/browser-workspace.md +237 -0
  14. package/docs/panes.md +442 -0
  15. package/native/TownmouseApp.swift +108 -0
  16. package/npm-shrinkwrap.json +1282 -0
  17. package/package.json +93 -4
  18. package/public/apple-touch-icon.png +0 -0
  19. package/public/brand/floydslabs-credit.png +0 -0
  20. package/public/brand/floydslabs-credit.webp +0 -0
  21. package/public/brand/townmouse-aristocrat.webp +0 -0
  22. package/public/brand/townmouse-monocled.webp +0 -0
  23. package/public/browser-picture.mjs +159 -0
  24. package/public/clipboard-text.mjs +5 -0
  25. package/public/favicon-16x16.png +0 -0
  26. package/public/favicon-32x32.png +0 -0
  27. package/public/favicon.ico +0 -0
  28. package/public/favicon.svg +1 -0
  29. package/public/features/app-version.mjs +35 -0
  30. package/public/features/autosave.mjs +80 -0
  31. package/public/features/clipboard.mjs +69 -0
  32. package/public/features/command-palette.mjs +181 -0
  33. package/public/features/desktop-palette.mjs +19 -0
  34. package/public/features/export.mjs +37 -0
  35. package/public/features/file-drop.mjs +77 -0
  36. package/public/features/floating-palette.mjs +113 -0
  37. package/public/features/fontsize.mjs +72 -0
  38. package/public/features/haptic-keys.mjs +42 -0
  39. package/public/features/history-undo.mjs +102 -0
  40. package/public/features/keepalive.mjs +36 -0
  41. package/public/features/keybar-config.mjs +70 -0
  42. package/public/features/keyboard-shortcuts.mjs +74 -0
  43. package/public/features/links.mjs +139 -0
  44. package/public/features/multi-window-sync.mjs +76 -0
  45. package/public/features/osc-bridge.mjs +64 -0
  46. package/public/features/phone-landscape-focus.mjs +157 -0
  47. package/public/features/recent-commands.mjs +100 -0
  48. package/public/features/search.mjs +134 -0
  49. package/public/features/session-lock.mjs +96 -0
  50. package/public/features/session-manager.mjs +251 -0
  51. package/public/features/settings-sync.mjs +77 -0
  52. package/public/features/shortcut-help.mjs +85 -0
  53. package/public/features/smart-completions.mjs +101 -0
  54. package/public/features/smart-suggest.mjs +124 -0
  55. package/public/features/snippets.mjs +85 -0
  56. package/public/features/split-view.mjs +102 -0
  57. package/public/features/status-metrics.mjs +137 -0
  58. package/public/features/stylus-support.mjs +124 -0
  59. package/public/features/swipe-history.mjs +141 -0
  60. package/public/features/swipe-sessions.mjs +85 -0
  61. package/public/features/tab-reorder.mjs +70 -0
  62. package/public/features/theme-system.mjs +51 -0
  63. package/public/features/toast-status.mjs +118 -0
  64. package/public/features/two-finger-menu.mjs +87 -0
  65. package/public/features/voice-input.mjs +244 -0
  66. package/public/features/wake-fullscreen.mjs +67 -0
  67. package/public/features/window-title.mjs +47 -0
  68. package/public/features/zoom.mjs +80 -0
  69. package/public/icon-128.png +0 -0
  70. package/public/icon-180.png +0 -0
  71. package/public/icon-192.png +0 -0
  72. package/public/icon-48.png +0 -0
  73. package/public/icon-512-maskable.png +0 -0
  74. package/public/icon-512.png +0 -0
  75. package/public/icon.svg +1 -0
  76. package/public/index.html +2304 -0
  77. package/public/input-chunks.mjs +22 -0
  78. package/public/input-guard.mjs +218 -0
  79. package/public/manifest.json +56 -0
  80. package/public/panes.css +1433 -0
  81. package/public/panes.html +211 -0
  82. package/public/panes.mjs +3183 -0
  83. package/public/service-worker.js +67 -0
  84. package/public/workspace.css +1621 -0
  85. package/public/workspace.mjs +1715 -0
  86. package/scripts/install-service.sh +303 -0
  87. package/scripts/node-runtime.sh +138 -0
  88. package/scripts/panes +568 -0
  89. package/scripts/prepare-native.sh +35 -0
  90. package/scripts/retire-legacy-service.sh +76 -0
  91. package/scripts/run-hooks +69 -0
  92. package/scripts/townmouse.sh +152 -0
  93. package/scripts/uninstall-service.sh +65 -0
  94. package/src/agent-guide.js +329 -0
  95. package/src/attachments.js +128 -0
  96. package/src/browser-dom.js +548 -0
  97. package/src/browser-workspace.js +1733 -0
  98. package/src/chrome-resolve.js +80 -0
  99. package/src/owner-page.js +43 -0
  100. package/src/pty-permissions.js +99 -0
  101. package/src/regex-worker.js +13 -0
  102. package/src/replay-text.js +189 -0
  103. package/src/request-boundary.js +58 -0
  104. package/src/safe-regex.js +87 -0
  105. package/src/server.js +1582 -0
  106. package/src/shell-resolve.js +42 -0
  107. package/src/static-deps.js +61 -0
  108. package/src/workspace-panes.js +1431 -0
package/src/server.js ADDED
@@ -0,0 +1,1582 @@
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
+ // Port 11001 belongs to TerminalOne, the engine Townmouse embeds, so the two
34
+ // products can run on one machine.
35
+ const PORT = process.env.PORT || 11002;
36
+ // Loopback by default. Docker sets HOST=0.0.0.0 because a container's
37
+ // loopback is not reachable from the host; publish that port to loopback only.
38
+ const HOST = process.env.HOST || '127.0.0.1';
39
+ const { createRequestBoundary } = require('./request-boundary');
40
+ const { installStaticDependencies } = require('./static-deps');
41
+ const isTrustedRequest = createRequestBoundary(PORT, process.env.TERMINALONE_TRUSTED_ORIGINS || '');
42
+ const MAX_CONCURRENT_SESSIONS = 10;
43
+ // Reported by the health check, so a running copy can say which version it is.
44
+ const APP_VERSION = require('../package.json').version;
45
+
46
+ // Input typed in the moment between the socket opening and the shell existing
47
+ // used to be discarded without a word, which read as "my typing does not work"
48
+ // until the user pressed the key again. Hold it instead and flush on spawn.
49
+ const MAX_PENDING_INPUT = 8192;
50
+ const PING_INTERVAL_MS = 30_000;
51
+ const PONG_TIMEOUT_MS = 5_000;
52
+ const KILL_GRACE_MS = 1_000;
53
+ const MAX_COLS = 500;
54
+ const MAX_ROWS = 200;
55
+ const STT_MAX_CHUNK_BYTES = 512 * 1024;
56
+ const STT_MAX_UTTERANCE_BYTES = 8 * 1024 * 1024;
57
+ const STT_TIMEOUT_MS = Number(process.env.TERMINALONE_STT_TIMEOUT_MS || 60_000);
58
+
59
+ // Voice settings live in the member's home so any STT command and model can be
60
+ // chosen without environment variables. Audio is staged under the cache dir so
61
+ // it never lands in the shared system temp directory.
62
+ const VOICE_CONFIG_PATH = path.join(os.homedir(), '.config', 'terminalone', 'voice.json');
63
+ const VOICE_TMP_BASE = path.join(os.homedir(), '.cache', 'terminalone');
64
+ const VOICE_DEFAULT_ARGS = '{audio} --model {model} --language {language} --output_format txt --output_dir {dir} --verbose False --fp16 False';
65
+ const VOICE_PLACEHOLDERS = new Set(['audio', 'model', 'language', 'dir', 'base', 'output']);
66
+
67
+ // A session is a shell the person or an agent opened on purpose. It keeps
68
+ // running while nobody views it (output is buffered in a ring and replayed on
69
+ // resume) until it is closed, its shell exits, or the app stops. It used to be
70
+ // killed five minutes after the last viewer left, which silently destroyed
71
+ // every shell the person had merely switched away from.
72
+ const SESSION_NAME_MAX = 40;
73
+ // An agent's "show this session" request only counts as fresh for this long.
74
+ const ACTIVATION_TTL_MS = 60 * 1000;
75
+ // Minted per process. A page that reconnects to a different epoch knows the
76
+ // app was restarted, which is not the same thing as one session being closed.
77
+ const SESSION_EPOCH = crypto.randomUUID();
78
+
79
+ // A shell that cannot start exits immediately. Respawning it without a limit
80
+ // produced roughly 26 respawns per second, indefinitely, and looked like a
81
+ // frozen terminal. Count rapid exits, back off, then stop and explain.
82
+ const RAPID_EXIT_MS = 1500;
83
+ const MAX_RAPID_RESPAWNS = 5;
84
+ const RESPAWN_BASE_MS = 100;
85
+ const RESPAWN_MAX_MS = 5000;
86
+ // The shell's recent output is kept so that every rejoin can show it: the
87
+ // most recent RESUME_BUFFER_MAX characters (measured 2026-11-29: rebuilding a
88
+ // replay from that much costs about 20 ms on the server). Eviction is done in
89
+ // batches of about RESUME_BUFFER_EVICTION so it runs once per that much output
90
+ // rather than on every piece the terminal engine delivers. Small pieces are
91
+ // gathered into blocks of about RESUME_BLOCK.
92
+ const RESUME_BUFFER_MAX = 512 * 1024;
93
+ const RESUME_BUFFER_EVICTION = 64 * 1024;
94
+ const RESUME_BLOCK = 16 * 1024;
95
+ // When eviction cuts a line, the rest of that line is dropped, up to this far.
96
+ const RESUME_LINE_TRIM_MAX = 4096;
97
+ // Instructions in a shell's output that do something on the page as soon as
98
+ // they are shown: OSC 52 sets the clipboard, OSC 777 raises a notification.
99
+ // They act the first time their output is shown. Output is now replayed at
100
+ // every rejoin, so a replay of output shown before must not carry them, or
101
+ // every rejoin would overwrite the clipboard with something old.
102
+ const SIDE_EFFECT_SEQUENCE = /\x1b\](?:52;[cCsS];[A-Za-z0-9+/=]*|777;[^\x07\x1b]*)(?:\x07|\x1b\\)/g;
103
+
104
+ // ─── In-memory state ──────────────────────────────────────────────────────────
105
+
106
+ /** @type {Map<string, Session>} */
107
+ const activeSessions = new Map();
108
+
109
+ /** @type {Map<string, NodeJS.Timeout>} */
110
+ const pingTimers = new Map();
111
+
112
+ /** @type {Map<string, NodeJS.Timeout>} */
113
+ const pongTimers = new Map();
114
+
115
+ // Session registry. `activeSessions` also holds the short-lived placeholder a
116
+ // connection starts as; only sessions with `listed` set ever had a shell and
117
+ // only those are counted, listed or closed.
118
+ /** The session a viewer attached to most recently. */
119
+ let activeSessionId = null;
120
+ /** Creation order, for the default "Shell N" names. Never reused in one run. */
121
+ let sessionCounter = 0;
122
+ /** The newest explicit "show this session" request, if it is still fresh. */
123
+ let activation = null;
124
+ let activationSeq = 0;
125
+
126
+ // ─── Structured logger ───────────────────────────────────────────────────────
127
+
128
+ /** @param {'info'|'warn'|'error'} level */
129
+ function log(level, sessionId, msg, meta = {}) {
130
+ const entry = { ts: new Date().toISOString(), level, sessionId: sessionId || null, msg, ...meta };
131
+ if (level === 'error') console.error(JSON.stringify(entry));
132
+ else console.log(JSON.stringify(entry));
133
+ }
134
+
135
+ const info = (id, msg, m) => log('info', id, msg, m);
136
+ const warn = (id, msg, m) => log('warn', id, msg, m);
137
+ const error = (id, msg, m) => log('error', id, msg, m);
138
+
139
+ // ─── Input validation ────────────────────────────────────────────────────────
140
+
141
+ /** @returns {{ cols: number, rows: number }} */
142
+ function clampDims(cols, rows) {
143
+ return {
144
+ cols: Math.max(1, Math.min(Math.floor(Number(cols)) || 120, MAX_COLS)),
145
+ rows: Math.max(1, Math.min(Math.floor(Number(rows)) || 40, MAX_ROWS))
146
+ };
147
+ }
148
+
149
+ /** Count sessions running a live shell, optionally excluding one id. */
150
+ function countRealShells(excludeId) {
151
+ let n = 0;
152
+ for (const s of activeSessions.values()) {
153
+ if (s.id === excludeId) continue;
154
+ if (s.ptyProcess && !s.processExited) n += 1;
155
+ }
156
+ return n;
157
+ }
158
+
159
+ // ─── Session registry ────────────────────────────────────────────────────────
160
+ // One description of "which shells exist". The page's row, its Sessions list,
161
+ // /health and the agent API are all read from here, so they cannot disagree.
162
+
163
+ /** The record every connection and every agent-created session starts from. */
164
+ function newSessionRecord(ws, createdBy = 'human') {
165
+ return {
166
+ id: uuidv4(),
167
+ command: resolveShell(),
168
+ ptyProcess: undefined,
169
+ sessionActive: true,
170
+ processExited: false,
171
+ ws,
172
+ startedAt: null,
173
+ // The shell's recent output, kept for every rejoin (see bufferOutput).
174
+ // `outputChars` counts all of it ever, so the retained part starts at
175
+ // outputChars - outputBuffered.
176
+ outputBlocks: [],
177
+ outputPieces: [],
178
+ outputPending: 0,
179
+ outputBuffered: 0,
180
+ // Output before this offset, counted like `outputChars`, has been shown
181
+ // to a viewer, live or in a replay. See withoutRepeatedEffects.
182
+ shownUpTo: 0,
183
+ lastCols: 120,
184
+ lastRows: 40,
185
+ lastDataCols: null,
186
+ lastDataRows: null,
187
+ widthChanged: false,
188
+ outputChars: 0,
189
+ resizeMarkers: [],
190
+ sockets: ws ? new Set([ws]) : new Set(),
191
+ userClosed: false,
192
+ // Set the first time a shell starts; only then is the session listed.
193
+ listed: false,
194
+ name: '',
195
+ createdBy,
196
+ createdAt: null,
197
+ lastViewedAt: null
198
+ };
199
+ }
200
+
201
+ /** @returns {{ ok: true, value: string } | { ok: false, error: string }} */
202
+ function validSessionName(value) {
203
+ if (typeof value !== 'string') return { ok: false, error: 'name must be a string' };
204
+ const name = value.trim();
205
+ if (!name) return { ok: false, error: 'name must not be empty' };
206
+ if (name.length > SESSION_NAME_MAX) return { ok: false, error: `name must be at most ${SESSION_NAME_MAX} characters` };
207
+ if (/[\u0000-\u001f\u007f]/.test(name)) return { ok: false, error: 'name must not contain control characters' };
208
+ return { ok: true, value: name };
209
+ }
210
+
211
+ function nameInUse(name, exceptId) {
212
+ for (const s of activeSessions.values()) {
213
+ if (s.listed && s.id !== exceptId && s.name === name) return true;
214
+ }
215
+ return false;
216
+ }
217
+
218
+ function listedSessions() {
219
+ return [...activeSessions.values()].filter((s) => s.listed);
220
+ }
221
+
222
+ function openSockets(session) {
223
+ return [...(session.sockets || [])].filter((socket) => socket.readyState === WebSocket.OPEN);
224
+ }
225
+
226
+ /** The session a viewer looked at most recently, other than `exceptId`. */
227
+ function mostRecentlyViewed(exceptId) {
228
+ let best = null;
229
+ for (const s of listedSessions()) {
230
+ if (s.id === exceptId) continue;
231
+ if (!best || (s.lastViewedAt || 0) > (best.lastViewedAt || 0)) best = s;
232
+ }
233
+ return best;
234
+ }
235
+
236
+ function serializeSession(s) {
237
+ return {
238
+ id: s.id,
239
+ name: s.name,
240
+ command: s.command || resolveShell(),
241
+ cwd: s.shellCwd || null,
242
+ createdBy: s.createdBy,
243
+ createdAt: s.createdAt,
244
+ startedAt: s.startedAt || null,
245
+ lastViewedAt: s.lastViewedAt,
246
+ viewers: openSockets(s).length,
247
+ active: s.id === activeSessionId,
248
+ status: s.processExited ? 'restarting' : 'running'
249
+ };
250
+ }
251
+
252
+ /**
253
+ * Everything a client needs to draw the row. Who is asking decides how much
254
+ * of it they see, as with panes. The owner's page sees every shell. An agent
255
+ * sees the shells agents started, in row order, and of the owner's shells only
256
+ * how many there are (`ownerStarted`): no id, name or folder. `activeSessionId`
257
+ * and `activation` refer to a shell the caller may see, or are null.
258
+ * `activation` is an explicit request to show a shell, while it is still fresh.
259
+ * @param {'owner'|'agent'} viewer
260
+ */
261
+ function sessionState(viewer = 'owner') {
262
+ const all = listedSessions();
263
+ const shown = viewer === 'agent' ? all.filter((s) => s.createdBy === 'agent') : all;
264
+ const seen = new Set(shown.map((s) => s.id));
265
+ const state = {
266
+ epoch: SESSION_EPOCH,
267
+ sessions: shown.map(serializeSession),
268
+ activeSessionId: activeSessionId && seen.has(activeSessionId) ? activeSessionId : null,
269
+ max: MAX_CONCURRENT_SESSIONS
270
+ };
271
+ if (viewer === 'agent') state.ownerStarted = all.length - shown.length;
272
+ const current = activation && Date.now() - activation.at <= ACTIVATION_TTL_MS && seen.has(activation.id)
273
+ ? activation
274
+ : null;
275
+ state.activation = current ? { seq: current.seq, id: current.id, at: current.at } : null;
276
+ return state;
277
+ }
278
+
279
+ /** Tell every attached page what exists now. `except` just received its own copy. */
280
+ function broadcastSessions(except) {
281
+ const data = JSON.stringify({ type: 'sessions', ...sessionState() });
282
+ let reached = 0;
283
+ for (const s of activeSessions.values()) {
284
+ for (const socket of s.sockets || []) {
285
+ if (socket === except || socket.readyState !== WebSocket.OPEN) continue;
286
+ try { socket.send(data); reached += 1; } catch (_) { /* its close handler cleans up */ }
287
+ }
288
+ }
289
+ return reached;
290
+ }
291
+
292
+ function sendSessionState(ws) {
293
+ sendToSocket(ws, { type: 'sessions', ...sessionState() });
294
+ }
295
+
296
+ /**
297
+ * Start a session nobody is viewing yet: an agent opening a shell for the
298
+ * person, or a fresh shell with a chosen name.
299
+ * @param {{ cwd?: string, name?: string, createdBy: 'human'|'agent', activate?: boolean }} options
300
+ * @returns {Session}
301
+ */
302
+ function createSession({ cwd, name, createdBy, activate }) {
303
+ const session = newSessionRecord(null, createdBy);
304
+ session.sessionActive = false;
305
+ session.name = name || '';
306
+ activeSessions.set(session.id, session);
307
+ if (!spawnShell(session, cwd)) {
308
+ activeSessions.delete(session.id);
309
+ throw Object.assign(new Error('The shell could not be started.'), { status: 500 });
310
+ }
311
+ info(session.id, 'Session created', { createdBy, name: session.name });
312
+ if (activate) activateSession(session);
313
+ broadcastSessions();
314
+ return session;
315
+ }
316
+
317
+ // An explicit "show this session" request. Every open terminal page follows
318
+ // it once, while it is fresh; the person asked for it.
319
+ function activateSession(session) {
320
+ activationSeq += 1;
321
+ activation = { seq: activationSeq, id: session.id, at: Date.now() };
322
+ activeSessionId = session.id;
323
+ }
324
+
325
+ /** @param {import('ws').WebSocket} ws @param {string} code @param {string} message @param {string|null} id */
326
+ function wsError(ws, code, message, id) {
327
+ if (ws.readyState === WebSocket.OPEN) {
328
+ try { ws.send(JSON.stringify({ type: 'error', code, message })); }
329
+ catch (e) { error(id, 'WS send error failed', { code, err: e.message }); }
330
+ }
331
+ }
332
+
333
+ /** Send one JSON message to one socket if it is open. */
334
+ function sendToSocket(ws, payload) {
335
+ if (!ws || ws.readyState !== WebSocket.OPEN) return false;
336
+ try { ws.send(JSON.stringify(payload)); return true; }
337
+ catch (_) { return false; }
338
+ }
339
+
340
+ /** Send a JSON message to every window currently attached to a session. */
341
+ function sendToSession(session, payload) {
342
+ const sockets = session.sockets && session.sockets.size
343
+ ? session.sockets
344
+ : (session.ws ? new Set([session.ws]) : new Set());
345
+ let sent = false;
346
+ const data = JSON.stringify(payload);
347
+ for (const ws of sockets) {
348
+ if (!ws || ws.readyState !== WebSocket.OPEN) continue;
349
+ try { ws.send(data); sent = true; }
350
+ catch (e) { error(session.id, 'WS send failed', { err: e.message }); }
351
+ }
352
+ return sent;
353
+ }
354
+
355
+ // ─── Output ring buffer ──────────────────────────────────────────────────────
356
+
357
+ /** Where the next line starts at or after `from`; `from` when no line ends
358
+ * within RESUME_LINE_TRIM_MAX. */
359
+ function lineStartAt(text, from) {
360
+ const end = text.indexOf('\n', from);
361
+ return end >= 0 && end < from + RESUME_LINE_TRIM_MAX ? end + 1 : from;
362
+ }
363
+
364
+ /**
365
+ * Forget the resize markers that fell out of the ring. Of those before the
366
+ * retained output only the last still matters: it is the width that output
367
+ * starts at. Markers are recorded in order, so this stops at that one.
368
+ * @param {Session} session
369
+ * @param {number} start Offset, from the shell's first character, of the
370
+ * first retained character.
371
+ */
372
+ function pruneResizeMarkers(session, start) {
373
+ const markers = session.resizeMarkers;
374
+ let drop = 0;
375
+ while (drop < markers.length - 1 && markers[drop + 1].at <= start) drop += 1;
376
+ if (drop > 0) markers.splice(0, drop);
377
+ }
378
+
379
+ /**
380
+ * Append PTY output to the session's ring: the most recent output, at most
381
+ * RESUME_BUFFER_MAX characters, kept for every rejoin.
382
+ *
383
+ * The terminal engine delivers small pieces (measured 2026-11-29: 30 to 60
384
+ * characters is typical and none is longer than 1024), so pieces are gathered
385
+ * into blocks and blocks are evicted in batches. Buffering is then a
386
+ * constant-time append per piece. The ring used to be one string cut on every
387
+ * append once full, about a tenth of a millisecond a time, which held a busy
388
+ * shell nobody was watching to about ten thousand pieces a second; and a rejoin
389
+ * used to empty it, so a second rejoin showed only what was printed since.
390
+ *
391
+ * Offsets in `outputChars` and `resizeMarkers` count from the shell's first
392
+ * character and never reset. The retained output is the tail that ends at
393
+ * `outputChars` and is `outputBuffered` long, and always begins at a line
394
+ * start.
395
+ * @param {Session} session
396
+ * @param {string} data
397
+ */
398
+ function bufferOutput(session, data) {
399
+ const buffered = session.outputBuffered + data.length;
400
+ session.outputBuffered = buffered;
401
+ session.outputPieces.push(data);
402
+ session.outputPending += data.length;
403
+ if (session.outputPending >= RESUME_BLOCK || buffered > RESUME_BUFFER_MAX) {
404
+ session.outputBlocks.push(session.outputPieces.join(''));
405
+ session.outputPieces.length = 0;
406
+ session.outputPending = 0;
407
+ }
408
+ if (buffered <= RESUME_BUFFER_MAX) return;
409
+
410
+ // Over the cap. Whole blocks go first, until less than a block above the low
411
+ // mark, so the next eviction is that far away. One block is always kept.
412
+ const low = RESUME_BUFFER_MAX - RESUME_BUFFER_EVICTION;
413
+ const blocks = session.outputBlocks;
414
+ let kept = buffered;
415
+ while (blocks.length > 1 && kept - blocks[0].length >= low) {
416
+ kept -= blocks[0].length;
417
+ blocks.shift();
418
+ }
419
+ // The head block now begins part way through a line. Start where the next
420
+ // one begins, so a rejoin does not open on a fragment of a line or inside an
421
+ // escape sequence. A lone low surrogate is never left at the head.
422
+ const head = blocks[0];
423
+ const from = Math.min(head.length, Math.max(0, kept - low));
424
+ let cut = Math.min(head.length, lineStartAt(head, from));
425
+ if (cut < head.length) {
426
+ const code = head.charCodeAt(cut);
427
+ if (code >= 0xDC00 && code <= 0xDFFF) cut += 1;
428
+ }
429
+ if (cut > 0) {
430
+ blocks[0] = head.slice(cut);
431
+ kept -= cut;
432
+ }
433
+ session.outputBuffered = kept;
434
+ pruneResizeMarkers(session, session.outputChars - kept);
435
+ }
436
+
437
+ /** The retained output of `session` as one string: the tail of what it printed. */
438
+ function bufferedOutput(session) {
439
+ const blocks = session.outputPieces.length
440
+ ? session.outputBlocks.concat([session.outputPieces.join('')])
441
+ : session.outputBlocks;
442
+ return blocks.length === 1 ? blocks[0] : blocks.join('');
443
+ }
444
+
445
+ /**
446
+ * `raw` without the side-effecting instructions (see SIDE_EFFECT_SEQUENCE) of
447
+ * the part that was shown before. The rest is replayed as it was, so an
448
+ * instruction in output nobody has seen yet still acts when it is first shown.
449
+ * @param {Session} session
450
+ * @param {string} raw The retained output
451
+ * @param {number} rawStart Where `raw` begins, counted like `outputChars`
452
+ * @returns {string}
453
+ */
454
+ function withoutRepeatedEffects(session, raw, rawStart) {
455
+ const shown = session.shownUpTo - rawStart;
456
+ if (shown <= 0) return raw;
457
+ return raw.replace(SIDE_EFFECT_SEQUENCE, (sequence, at) => (at < shown ? '' : sequence));
458
+ }
459
+
460
+ // ─── PTY helpers ────────────────────────────────────────────────────────────
461
+
462
+ /** @param {import('node-pty').IPty|undefined} ptyProcess @param {string} id */
463
+ function killPty(ptyProcess, id) {
464
+ if (!ptyProcess || typeof ptyProcess.kill !== 'function') return;
465
+ try { ptyProcess.kill('SIGTERM'); }
466
+ catch (e) { warn(id, 'SIGTERM failed — already dead', { err: e.message }); return; }
467
+ const timer = setTimeout(() => {
468
+ try { if (ptyProcess && typeof ptyProcess.kill === 'function') ptyProcess.kill('SIGKILL'); }
469
+ catch (_) {}
470
+ }, KILL_GRACE_MS);
471
+ if (typeof ptyProcess.once === 'function') ptyProcess.once('exit', () => clearTimeout(timer));
472
+ }
473
+
474
+ // ─── Session lifecycle ───────────────────────────────────────────────────────
475
+
476
+ /**
477
+ * A viewer stopped looking at `session`. The shell is the person's, not the
478
+ * window's: it keeps running with nobody attached until it is closed. Only
479
+ * when a session has no viewer at all does the heartbeat stop.
480
+ * @returns {boolean} true once no viewer is left
481
+ */
482
+ function releaseSocket(session, ws) {
483
+ if (!session.sockets) session.sockets = new Set(session.ws ? [session.ws] : []);
484
+ session.sockets.delete(ws);
485
+ if (session.sockets.size > 0) {
486
+ // Other windows still hold this shell: hand ownership to one of them.
487
+ if (session.ws === ws || !session.ws) {
488
+ session.ws = [...session.sockets].find((socket) => socket.readyState === WebSocket.OPEN) || null;
489
+ }
490
+ return false;
491
+ }
492
+ session.ws = null;
493
+ session.sessionActive = false;
494
+ stopHeartbeat(session);
495
+ return true;
496
+ }
497
+
498
+ /**
499
+ * End a session for good: tell its viewers why, stop the shell, forget it,
500
+ * and tell every other page the list changed. Safe to call more than once.
501
+ * @param {Session} session
502
+ * @param {'closed'|'exited'|'error'} reason Who ended it: a person or agent,
503
+ * the shell itself, or a shell that would not start.
504
+ */
505
+ function cleanupSession(session, reason = 'closed') {
506
+ const { id, ptyProcess } = session;
507
+ if (!activeSessions.has(id)) return;
508
+ info(id, 'Cleaning up session', { reason });
509
+
510
+ for (const socket of session.sockets || []) socket.voice = null;
511
+ // Said before the socket closes, so a page can tell "this session was
512
+ // ended" from "the connection dropped" and never reconnect into a new shell.
513
+ // The list still includes this session; the page knows which one ended.
514
+ sendToSession(session, { type: 'session-ended', sessionId: id, reason, ...sessionState() });
515
+
516
+ stopHeartbeat(session);
517
+
518
+ session.sessionActive = false;
519
+ if (ptyProcess) { killPty(ptyProcess, id); session.ptyProcess = undefined; }
520
+ for (const socket of session.sockets || []) {
521
+ try { socket.close(1000, 'session ended'); } catch (_) { /* already gone */ }
522
+ }
523
+ if (session.sockets) session.sockets.clear();
524
+ session.ws = null;
525
+ activeSessions.delete(id);
526
+ if (activeSessionId === id) {
527
+ const next = mostRecentlyViewed(id);
528
+ activeSessionId = next ? next.id : null;
529
+ }
530
+ info(id, 'Session cleaned up', { reason });
531
+ if (session.listed) broadcastSessions();
532
+ }
533
+
534
+ /** @param {Session} session */
535
+ function startHeartbeat(session) {
536
+ const { id } = session;
537
+ // Replace any prior interval for this session.
538
+ clearInterval(pingTimers.get(id));
539
+
540
+ const t = setInterval(() => {
541
+ const s = activeSessions.get(id);
542
+ if (!s || !s.ws || s.ws.readyState !== WebSocket.OPEN) { clearInterval(t); pingTimers.delete(id); return; }
543
+ try { s.ws.ping(); }
544
+ catch (_) { clearInterval(t); return; }
545
+ const po = setTimeout(() => {
546
+ warn(id, 'Pong missed — closing stale session');
547
+ if (s.ws) s.ws.terminate();
548
+ }, PONG_TIMEOUT_MS);
549
+ pongTimers.set(id, po);
550
+ }, PING_INTERVAL_MS);
551
+ pingTimers.set(id, t);
552
+ }
553
+
554
+ /** Stop the heartbeat ping interval for a session (used when detaching). */
555
+ function stopHeartbeat(session) {
556
+ const { id } = session;
557
+ clearInterval(pingTimers.get(id)); pingTimers.delete(id);
558
+ clearTimeout(pongTimers.get(id)); pongTimers.delete(id);
559
+ }
560
+
561
+ // ─── PTY event wiring ──────────────────────────────────────────────────────
562
+
563
+ /**
564
+ * Attach PTY data/exit/error handlers to a session. The data handler reads
565
+ * `session.ws` dynamically so a re-attached WebSocket (resume) receives output
566
+ * without rewiring.
567
+ * @param {import('node-pty').IPty} ptyProcess
568
+ * @param {Session} session
569
+ */
570
+ function wirePtyToSession(ptyProcess, session) {
571
+ const { id } = session;
572
+
573
+ ptyProcess.onData((data) => {
574
+ // Remember the width this output was actually produced at. A resize just
575
+ // before a reload updates lastCols but not this marker.
576
+ session.lastDataCols = session.lastCols;
577
+ session.lastDataRows = session.lastRows;
578
+ session.outputChars += data.length;
579
+ // Always buffer so a subsequent resume can replay this output.
580
+ bufferOutput(session, data);
581
+ if (!session.sessionActive) return;
582
+ if (sendToSession(session, { type: 'output', data })) {
583
+ // Shown live, so whatever it instructs the page to do has been done.
584
+ session.shownUpTo = session.outputChars;
585
+ }
586
+ });
587
+
588
+ ptyProcess.once('exit', (code) => {
589
+ if (session.processExited) return;
590
+ session.processExited = true;
591
+
592
+ const ranFor = session.startedAt ? Date.now() - session.startedAt : Infinity;
593
+ session.rapidExits = ranFor < RAPID_EXIT_MS ? (session.rapidExits || 0) + 1 : 0;
594
+ info(id, 'Shell exited', { code, ranForMs: ranFor, rapidExits: session.rapidExits });
595
+
596
+ // If detached when the shell exits, there is nobody to receive a respawn —
597
+ // tear the session down.
598
+ if (!session.ws || session.ws.readyState !== WebSocket.OPEN) {
599
+ cleanupSession(session, 'exited');
600
+ return;
601
+ }
602
+ if (!session.sessionActive) { cleanupSession(session, 'exited'); return; }
603
+
604
+ // Stop rather than loop. Say what happened and what to check.
605
+ if (session.rapidExits >= MAX_RAPID_RESPAWNS) {
606
+ wsError(session.ws, 'SHELL_WILL_NOT_START',
607
+ 'The shell exited immediately ' + session.rapidExits + ' times in a row, so it was '
608
+ + 'not restarted again. Check $SHELL (currently ' + resolveShell()
609
+ + ') and your shell profile.', id);
610
+ cleanupSession(session, 'error');
611
+ return;
612
+ }
613
+
614
+ try { session.ws.send(JSON.stringify({ type: 'shell-reset', code: code || 0 })); }
615
+ catch (_) {}
616
+
617
+ const delay = Math.min(RESPAWN_BASE_MS * Math.pow(2, session.rapidExits), RESPAWN_MAX_MS);
618
+ setTimeout(() => {
619
+ if (session.sessionActive && session.ws && session.ws.readyState === WebSocket.OPEN) {
620
+ spawnShell(session, session.shellCwd);
621
+ } else {
622
+ cleanupSession(session, 'exited');
623
+ }
624
+ }, delay);
625
+ });
626
+
627
+ ptyProcess.on('error', (err) => {
628
+ error(id, 'PTY error', { err: err.message || String(err) });
629
+ if (session.ws) wsError(session.ws, 'PROCESS_ERROR', `Process error: ${err.message || String(err)}`, id);
630
+ cleanupSession(session, 'error');
631
+ });
632
+ }
633
+
634
+ // ─── Shell spawn helper ─────────────────────────────────────────────────────
635
+
636
+ /**
637
+ * Spawn the user's default shell into the session and wire it up. The first
638
+ * shell is what makes a session real: it is listed and named from then on.
639
+ * @param {Session} session
640
+ * @param {string} [cwd]
641
+ * @returns {boolean} false when the shell could not be started
642
+ */
643
+ function spawnShell(session, cwd) {
644
+ const { id } = session;
645
+ const cols = session.lastCols || 120;
646
+ const rows = session.lastRows || 40;
647
+
648
+ let workingDir = cwd || process.env.HOME || os.homedir();
649
+ if (!fs.existsSync(workingDir)) workingDir = os.homedir();
650
+
651
+ const ptyEnv = { ...process.env, TERM: 'xterm-256color' };
652
+ const shell = resolveShell();
653
+
654
+ session.shellCwd = workingDir;
655
+ session.command = session.command || shell;
656
+
657
+ let ptyProcess;
658
+ try {
659
+ ptyProcess = pty.spawn(shell, ['-l'], { name: 'xterm-256color', cols, rows, cwd: workingDir, env: ptyEnv });
660
+ } catch (e) {
661
+ error(id, 'shell spawn failed', { err: e.message });
662
+ return false;
663
+ }
664
+
665
+ if (!session.listed) {
666
+ session.listed = true;
667
+ sessionCounter += 1;
668
+ session.createdAt = Date.now();
669
+ if (!session.name) session.name = `Shell ${sessionCounter}`;
670
+ }
671
+
672
+ session.ptyProcess = ptyProcess;
673
+ session.processExited = false;
674
+ session.startedAt = Date.now();
675
+ session.resizeMarkers.push({ at: session.outputChars, cols, rows });
676
+ activeSessions.set(id, session);
677
+ wirePtyToSession(ptyProcess, session);
678
+
679
+ // Deliver anything typed while this shell did not yet exist.
680
+ if (session.pendingInput) {
681
+ const queued = session.pendingInput;
682
+ session.pendingInput = '';
683
+ try { ptyProcess.write(queued); }
684
+ catch (e) { error(id, 'pending input flush failed', { err: e.message }); }
685
+ }
686
+ return true;
687
+ }
688
+
689
+ // ─── Resume: re-attach a new WebSocket to an existing session ────────────────
690
+
691
+ /**
692
+ * Re-attach `ws` onto an existing resumable session, replay buffered output,
693
+ * and resume live delivery.
694
+ *
695
+ * Handlers are bound to the WebSocket once at connect time and read the active
696
+ * session through `ws.__sessionRef` (a mutable property). On resume we simply
697
+ * re-point that property at the target session — no second set of listeners is
698
+ * registered, so there is no double-dispatch.
699
+ * @param {Session} target
700
+ * @param {import('ws').WebSocket} ws
701
+ * @param {{ cols: number, rows: number }} dims
702
+ * @param {Session} previous What this socket was attached to: the throwaway
703
+ * record a connection starts as, or a real session it is being re-pointed
704
+ * away from (whose shell must keep running).
705
+ */
706
+ function resumeSession(target, ws, dims, previous) {
707
+ const { id } = target;
708
+ // The recent output is replayed to this page and kept. The shell will be
709
+ // rejoined again (a switch, a reload, a window opened anew) and must show the
710
+ // same thing each time. It used to be handed over and cleared here, so the
711
+ // second rejoin found nothing but what was printed since the first, which
712
+ // read as "my session is gone".
713
+ const raw = bufferedOutput(target);
714
+ // The buffer was produced at the old PTY width. Replay it into an xterm set
715
+ // to those dimensions, then fit the client to the new viewport. Replaying
716
+ // old cursor-addressed output at a new width splits words and loses lines.
717
+ const replayCols = target.lastDataCols || target.lastCols || dims.cols;
718
+ const replayRows = target.lastDataRows || target.lastRows || dims.rows;
719
+ // Same-width resume can replay colors and cursor addressing safely. A width
720
+ // change cannot: xterm's reflow of old shell redraws splits command lines.
721
+ // Use a control-code-free transcript of the final screen text instead.
722
+ const transcript = target.widthChanged || replayCols !== dims.cols || replayRows !== dims.rows;
723
+
724
+ // Retire what the socket was attached to. A placeholder is simply dropped;
725
+ // a real session only loses this viewer and keeps its shell.
726
+ if (previous.listed) {
727
+ releaseSocket(previous, ws);
728
+ } else {
729
+ activeSessions.delete(previous.id);
730
+ stopHeartbeat(previous);
731
+ }
732
+
733
+ // Adopt the new connection onto the target session.
734
+ target.ws = ws;
735
+ target.sessionActive = true;
736
+ if (!target.sockets) target.sockets = new Set();
737
+ target.sockets.add(ws);
738
+ ws.__sessionRef = target; // re-point handlers at the resumed session
739
+
740
+ // Restart heartbeat for the new socket.
741
+ startHeartbeat(target);
742
+
743
+ // Acknowledge resume with the dimensions the buffered output was rendered
744
+ // at. The client resizes its xterm to these before writing any replay bytes
745
+ // and waits for `replay-end` before fitting to the viewport.
746
+ sendToSocket(ws, {
747
+ type: 'ready',
748
+ sessionId: id,
749
+ command: target.command || resolveShell(),
750
+ cwd: target.shellCwd,
751
+ name: target.name,
752
+ epoch: SESSION_EPOCH,
753
+ resumed: true,
754
+ transcript,
755
+ cols: replayCols,
756
+ rows: replayRows
757
+ });
758
+
759
+ if (raw) {
760
+ // Markers count from the shell's first character; the retained output
761
+ // begins this far in.
762
+ const rawStart = target.outputChars - raw.length;
763
+ let buf = raw;
764
+ if (transcript) {
765
+ let initial = { cols: replayCols };
766
+ const segments = [];
767
+ for (const marker of target.resizeMarkers) {
768
+ if (marker.at <= rawStart) initial = marker;
769
+ else if (marker.at < target.outputChars) {
770
+ segments.push({ at: marker.at - rawStart, cols: marker.cols });
771
+ }
772
+ }
773
+ segments.unshift({ at: 0, cols: initial.cols });
774
+ buf = replayTranscript(raw, segments).replace(/\n/g, '\r\n');
775
+ } else {
776
+ // A transcript has no control codes. A raw replay keeps the colours and
777
+ // cursor addressing, and with them any instruction to set the clipboard
778
+ // or raise a notification, which must not act a second time.
779
+ buf = withoutRepeatedEffects(target, raw, rawStart);
780
+ }
781
+ // Shown now, either way.
782
+ target.shownUpTo = target.outputChars;
783
+ // Send in chunks to avoid a single oversized WS frame.
784
+ const CHUNK = 16 * 1024;
785
+ for (let i = 0; i < buf.length; i += CHUNK) {
786
+ let end = Math.min(i + CHUNK, buf.length);
787
+ if (end < buf.length) {
788
+ const last = buf.charCodeAt(end - 1);
789
+ if (last >= 0xD800 && last <= 0xDBFF) end -= 1;
790
+ }
791
+ sendToSocket(ws, { type: 'output', data: buf.slice(i, end) });
792
+ i = end - CHUNK;
793
+ }
794
+ }
795
+ sendToSocket(ws, { type: 'replay-end' });
796
+
797
+ // Only after the replay is on the wire do we resize the live PTY to the new
798
+ // client viewport. New output is therefore produced at the new width while
799
+ // the old buffer remains coherent at the old width.
800
+ if (dims.cols !== target.lastCols || dims.rows !== target.lastRows) {
801
+ target.widthChanged = true;
802
+ target.resizeMarkers.push({ at: target.outputChars, cols: dims.cols, rows: dims.rows });
803
+ }
804
+ target.lastCols = dims.cols;
805
+ target.lastRows = dims.rows;
806
+ if (target.ptyProcess && !target.processExited) {
807
+ try { target.ptyProcess.resize(dims.cols, dims.rows); }
808
+ catch (e) { warn(id, 'resume resize failed', { err: e.message }); }
809
+ }
810
+
811
+ info(id, 'Session resumed', { replayChars: raw.length, transcript, replayCols, replayRows, cols: dims.cols, rows: dims.rows });
812
+ }
813
+
814
+ // ─── Speech-to-text helpers ─────────────────────────────────────────────────
815
+
816
+ function voiceError(ws, code, message) {
817
+ sendToSocket(ws, { type: 'voice-error', code, message });
818
+ }
819
+
820
+ function extForMime(mimeType) {
821
+ const mt = String(mimeType || '').toLowerCase();
822
+ if (mt.includes('wav')) return 'wav';
823
+ if (mt.includes('mp4') || mt.includes('aac') || mt.includes('m4a')) return 'm4a';
824
+ if (mt.includes('ogg')) return 'ogg';
825
+ return 'webm';
826
+ }
827
+
828
+ function defaultVoiceConfig() {
829
+ return {
830
+ command: process.env.TERMINALONE_STT_BIN || 'whisper',
831
+ model: process.env.TERMINALONE_STT_MODEL || 'tiny.en',
832
+ language: process.env.TERMINALONE_STT_LANGUAGE || 'en',
833
+ args: VOICE_DEFAULT_ARGS
834
+ };
835
+ }
836
+
837
+ function readVoiceConfig() {
838
+ const config = defaultVoiceConfig();
839
+ // Explicit deployment or test environment wins over the saved UI setting.
840
+ if (process.env.TERMINALONE_STT_BIN || process.env.TERMINALONE_STT_MODEL || process.env.TERMINALONE_STT_LANGUAGE) {
841
+ return config;
842
+ }
843
+ let raw;
844
+ try { raw = fs.readFileSync(VOICE_CONFIG_PATH, 'utf8'); }
845
+ catch (_) { return config; }
846
+ let saved;
847
+ try { saved = JSON.parse(raw); }
848
+ catch (_) { return config; }
849
+ if (!saved || typeof saved !== 'object') return config;
850
+ for (const key of ['command', 'model', 'language', 'args']) {
851
+ if (typeof saved[key] === 'string') config[key] = saved[key];
852
+ }
853
+ return config;
854
+ }
855
+
856
+ function validateVoiceConfig(input) {
857
+ const source = input && typeof input === 'object' ? input : {};
858
+ const command = typeof source.command === 'string' ? source.command.trim() : '';
859
+ if (!command) return { ok: false, error: 'command must not be empty' };
860
+ if (/[\u0000-\u001f\u007f]/.test(command)) return { ok: false, error: 'command must not contain NUL, newline, or control characters' };
861
+
862
+ const model = typeof source.model === 'string' ? source.model.trim() : '';
863
+ if (!model) return { ok: false, error: 'model must not be empty' };
864
+ if (/[\u0000-\u001f\u007f]/.test(model)) return { ok: false, error: 'model must not contain NUL, newline, or control characters' };
865
+
866
+ const language = typeof source.language === 'string' ? source.language.trim().toLowerCase() : '';
867
+ if (!/^(?:[a-z]{2,3}|auto)$/.test(language)) return { ok: false, error: 'language must be a two- or three-letter code, or auto' };
868
+
869
+ const args = typeof source.args === 'string' ? source.args.trim() : '';
870
+ if (!args) return { ok: false, error: 'args must not be empty' };
871
+ if (args.includes('\u0000')) return { ok: false, error: 'args must not contain NUL characters' };
872
+ if (!args.includes('{audio}')) return { ok: false, error: 'args must contain {audio}' };
873
+ const unknown = [...args.matchAll(/\{([^{}]*)\}/g)]
874
+ .map((match) => match[1])
875
+ .filter((name) => !VOICE_PLACEHOLDERS.has(name));
876
+ if (unknown.length) return { ok: false, error: `unknown placeholder {${unknown[0]}}` };
877
+
878
+ return { ok: true, value: { command, model, language, args } };
879
+ }
880
+
881
+ function writeVoiceConfig(config) {
882
+ fs.mkdirSync(path.dirname(VOICE_CONFIG_PATH), { recursive: true, mode: 0o700 });
883
+ const body = JSON.stringify({
884
+ command: config.command,
885
+ model: config.model,
886
+ language: config.language,
887
+ args: config.args
888
+ }, null, 2) + '\n';
889
+ fs.writeFileSync(VOICE_CONFIG_PATH, body, { mode: 0o600 });
890
+ try { fs.chmodSync(VOICE_CONFIG_PATH, 0o600); } catch (_) {}
891
+ }
892
+
893
+ function resolveVoiceCommand(command) {
894
+ if (typeof command !== 'string' || !command) return { commandFound: false, commandPath: null };
895
+ if (command.includes('/')) {
896
+ const candidate = path.isAbsolute(command) ? command : path.resolve(command);
897
+ try {
898
+ fs.accessSync(candidate, fs.constants.X_OK);
899
+ return { commandFound: true, commandPath: candidate };
900
+ } catch (_) {
901
+ return { commandFound: false, commandPath: null };
902
+ }
903
+ }
904
+ for (const dir of String(process.env.PATH || '').split(path.delimiter)) {
905
+ if (!dir) continue;
906
+ const candidate = path.join(dir, command);
907
+ try {
908
+ fs.accessSync(candidate, fs.constants.X_OK);
909
+ return { commandFound: true, commandPath: candidate };
910
+ } catch (_) {}
911
+ }
912
+ return { commandFound: false, commandPath: null };
913
+ }
914
+
915
+ function voiceSettingsPayload() {
916
+ const config = readVoiceConfig();
917
+ return { ...config, resolved: resolveVoiceCommand(config.command) };
918
+ }
919
+
920
+ function buildVoiceArgs(config, values) {
921
+ return config.args
922
+ .split(/\s+/)
923
+ .filter(Boolean)
924
+ .map((token) => token.replace(/\{(audio|model|language|dir|base|output)\}/g, (_, key) => values[key]));
925
+ }
926
+
927
+ function cleanupTempDir(dir) {
928
+ if (!dir) return;
929
+ const absolute = path.resolve(dir);
930
+ const allowed = [path.resolve(VOICE_TMP_BASE), path.resolve(os.tmpdir())];
931
+ if (!allowed.some((base) => absolute.startsWith(base + path.sep))) return;
932
+ fs.rm(dir, { recursive: true, force: true }, () => {});
933
+ }
934
+
935
+ function transcriptFromSrt(text) {
936
+ return String(text || '')
937
+ .split(/\r?\n/)
938
+ .map((line) => line.trim())
939
+ .filter((line) => line && !/^\d+$/.test(line) && !line.includes('-->'))
940
+ .join('\n')
941
+ .trim();
942
+ }
943
+
944
+ function readTranscriptText(tmpDir, base, cb) {
945
+ const txtPath = path.join(tmpDir, `${base}.txt`);
946
+ fs.readFile(txtPath, 'utf8', (err, text) => {
947
+ if (!err) { cb(null, text); return; }
948
+ if (err.code !== 'ENOENT') { cb(err); return; }
949
+ fs.readFile(path.join(tmpDir, `${base}.srt`), 'utf8', (srtErr, srt) => {
950
+ if (srtErr) { cb(srtErr); return; }
951
+ cb(null, transcriptFromSrt(srt));
952
+ });
953
+ });
954
+ }
955
+
956
+ function transcribeAudioFile(session, ws, audioPath, tmpDir) {
957
+ const checked = validateVoiceConfig(readVoiceConfig());
958
+ if (!checked.ok) {
959
+ warn(session.id, 'Voice settings are invalid', { error: checked.error });
960
+ voiceError(ws, 'STT_FAILED', `Voice settings are invalid: ${checked.error}`);
961
+ cleanupTempDir(tmpDir);
962
+ return;
963
+ }
964
+ const config = checked.value;
965
+ const base = path.basename(audioPath, path.extname(audioPath));
966
+ const args = buildVoiceArgs(config, {
967
+ audio: audioPath,
968
+ model: config.model,
969
+ language: config.language,
970
+ dir: tmpDir,
971
+ base,
972
+ output: path.join(tmpDir, `${base}.txt`)
973
+ });
974
+
975
+ info(session.id, 'Starting local STT transcription', {
976
+ command: config.command, model: config.model, language: config.language
977
+ });
978
+ const child = spawn(config.command, args, { stdio: ['ignore', 'ignore', 'pipe'] });
979
+ let stderr = '';
980
+ let settled = false;
981
+ const timer = setTimeout(() => {
982
+ settled = true;
983
+ child.kill('SIGTERM');
984
+ voiceError(ws, 'STT_TIMEOUT', 'Speech transcription timed out');
985
+ cleanupTempDir(tmpDir);
986
+ }, STT_TIMEOUT_MS);
987
+
988
+ child.stderr.on('data', (chunk) => {
989
+ stderr = (stderr + chunk.toString()).slice(-4000);
990
+ });
991
+ child.on('error', (err) => {
992
+ if (settled) return;
993
+ settled = true;
994
+ clearTimeout(timer);
995
+ const code = err.code === 'ENOENT' ? 'STT_UNAVAILABLE' : 'STT_ERROR';
996
+ voiceError(ws, code, err.code === 'ENOENT' ? 'Local whisper command not found' : err.message);
997
+ cleanupTempDir(tmpDir);
998
+ });
999
+ child.on('exit', (code) => {
1000
+ if (settled) return;
1001
+ settled = true;
1002
+ clearTimeout(timer);
1003
+ if (code !== 0) {
1004
+ warn(session.id, 'Local STT failed', { code, stderr });
1005
+ voiceError(ws, 'STT_FAILED', 'Speech transcription failed');
1006
+ cleanupTempDir(tmpDir);
1007
+ return;
1008
+ }
1009
+ readTranscriptText(tmpDir, base, (readErr, text) => {
1010
+ cleanupTempDir(tmpDir);
1011
+ if (readErr) {
1012
+ voiceError(ws, 'STT_NO_TRANSCRIPT', 'Speech transcription produced no text');
1013
+ return;
1014
+ }
1015
+ const transcript = String(text || '').trim();
1016
+ if (!transcript) {
1017
+ voiceError(ws, 'STT_NO_TRANSCRIPT', 'Speech transcription produced no text');
1018
+ return;
1019
+ }
1020
+ sendToSocket(ws, { type: 'voice-transcript', text: transcript });
1021
+ info(session.id, 'Local STT transcript ready', { chars: transcript.length });
1022
+ });
1023
+ });
1024
+ }
1025
+
1026
+ function finalizeVoice(session, ws) {
1027
+ const voice = ws.voice;
1028
+ ws.voice = null;
1029
+ if (!voice || !voice.chunks.length || voice.bytes <= 0) {
1030
+ voiceError(ws, 'VOICE_EMPTY', 'No voice audio was captured');
1031
+ return;
1032
+ }
1033
+
1034
+ let tmpDir;
1035
+ try {
1036
+ fs.mkdirSync(VOICE_TMP_BASE, { recursive: true, mode: 0o700 });
1037
+ tmpDir = fs.mkdtempSync(path.join(VOICE_TMP_BASE, 'stt-'));
1038
+ } catch (err) {
1039
+ voiceError(ws, 'VOICE_WRITE_FAILED', 'Could not create a voice transcription folder');
1040
+ return;
1041
+ }
1042
+ const audioPath = path.join(tmpDir, `utterance.${extForMime(voice.mimeType)}`);
1043
+ fs.writeFile(audioPath, Buffer.concat(voice.chunks), (err) => {
1044
+ if (err) {
1045
+ voiceError(ws, 'VOICE_WRITE_FAILED', 'Could not save voice audio for transcription');
1046
+ cleanupTempDir(tmpDir);
1047
+ return;
1048
+ }
1049
+ transcribeAudioFile(session, ws, audioPath, tmpDir);
1050
+ });
1051
+ }
1052
+
1053
+ // ─── Message dispatcher ─────────────────────────────────────────────────────
1054
+
1055
+ /** Answer a page command that carried a requestId, so it can show the outcome where it was asked. */
1056
+ function commandResult(ws, data, outcome) {
1057
+ if (!data || data.requestId == null) return;
1058
+ const reply = { type: 'result', requestId: data.requestId, ok: outcome.ok };
1059
+ if (!outcome.ok) { reply.code = outcome.code; reply.error = outcome.error; }
1060
+ else if (outcome.name !== undefined) reply.name = outcome.name;
1061
+ sendToSocket(ws, reply);
1062
+ }
1063
+
1064
+ /** @param {Session} session @param {import('ws').WebSocket} ws @param {object} data */
1065
+ function handleMessage(session, ws, data) {
1066
+ if (!session.sessionActive && data.type !== 'resume' && data.type !== 'shell') return;
1067
+ // A superseded socket must not close, re-shell, or re-adopt the session out
1068
+ // from under the window that currently owns it.
1069
+ if (session.ws && session.ws !== ws && ['close', 'shell', 'resume'].includes(data.type)) return;
1070
+
1071
+ switch (data.type) {
1072
+ case 'shell': {
1073
+ if (session.ptyProcess && !session.processExited) {
1074
+ try { session.ptyProcess.kill(); } catch (_) {}
1075
+ }
1076
+ const { cols, rows } = clampDims(data.cols, data.rows);
1077
+ session.lastCols = cols;
1078
+ session.lastRows = rows;
1079
+ // Enforce the concurrent-shell cap. Fresh spawns only — resume reuses an
1080
+ // existing session and is exempt. The current (placeholder) session has no
1081
+ // PTY yet and is excluded from the count.
1082
+ if (countRealShells(session.id) >= MAX_CONCURRENT_SESSIONS) {
1083
+ wsError(ws, 'SESSION_LIMIT', 'Maximum concurrent sessions reached', session.id);
1084
+ break;
1085
+ }
1086
+ if (!session.listed) session.createdBy = data.createdBy === 'agent' ? 'agent' : 'human';
1087
+ if (!spawnShell(session, data.cwd || process.env.HOME || os.homedir())) {
1088
+ wsError(ws, 'SHELL_SPAWN_FAILED', 'The shell could not be started.', session.id);
1089
+ break;
1090
+ }
1091
+ session.lastViewedAt = Date.now();
1092
+ activeSessionId = session.id;
1093
+ if (ws.readyState === WebSocket.OPEN) {
1094
+ ws.send(JSON.stringify({
1095
+ type: 'ready', sessionId: session.id, command: resolveShell(), cwd: session.shellCwd,
1096
+ name: session.name, epoch: SESSION_EPOCH
1097
+ }));
1098
+ sendSessionState(ws);
1099
+ }
1100
+ broadcastSessions(ws);
1101
+ break;
1102
+ }
1103
+ case 'resume': {
1104
+ // Look up the requested session and adopt it onto this connection.
1105
+ const targetId = String(data.sessionId || '');
1106
+ const target = activeSessions.get(targetId);
1107
+ if (target && target.listed) {
1108
+ resumeSession(target, ws, clampDims(data.cols, data.rows), session);
1109
+ target.lastViewedAt = Date.now();
1110
+ activeSessionId = target.id;
1111
+ sendSessionState(ws);
1112
+ broadcastSessions(ws);
1113
+ } else {
1114
+ info(session.id, 'Resume failed — target not resumable', { targetId });
1115
+ // The page decides what to do next from the real list, and says so.
1116
+ if (ws.readyState === WebSocket.OPEN) {
1117
+ ws.send(JSON.stringify({ type: 'resume-failed', sessionId: targetId, reason: 'not-found', ...sessionState() }));
1118
+ }
1119
+ }
1120
+ break;
1121
+ }
1122
+ case 'sessions': {
1123
+ sendSessionState(ws);
1124
+ break;
1125
+ }
1126
+ case 'rename': {
1127
+ const target = data.sessionId ? activeSessions.get(String(data.sessionId)) : session;
1128
+ const refused = (code, error) => commandResult(ws, data, { ok: false, code, error });
1129
+ if (!target || !target.listed) { refused('SESSION_NOT_FOUND', 'That session is no longer available.'); break; }
1130
+ const checked = validSessionName(data.name);
1131
+ if (!checked.ok) { refused('INVALID_NAME', `That name cannot be used: ${checked.error}.`); break; }
1132
+ if (nameInUse(checked.value, target.id)) {
1133
+ refused('NAME_IN_USE', `Another session is already named “${checked.value}”.`);
1134
+ break;
1135
+ }
1136
+ target.name = checked.value;
1137
+ info(target.id, 'Session renamed', { name: target.name });
1138
+ commandResult(ws, data, { ok: true, name: target.name });
1139
+ broadcastSessions();
1140
+ break;
1141
+ }
1142
+ case 'input': {
1143
+ if (typeof data.data !== 'string') break;
1144
+ if (session.ptyProcess && !session.processExited) {
1145
+ try { session.ptyProcess.write(data.data); }
1146
+ catch (e) { wsError(ws, 'WRITE_FAILED', `Write failed: ${e.message}`, session.id); }
1147
+ } else {
1148
+ // No shell yet: keep the keys rather than throwing them away.
1149
+ const queued = (session.pendingInput || '') + data.data;
1150
+ session.pendingInput = queued.length > MAX_PENDING_INPUT
1151
+ ? queued.slice(-MAX_PENDING_INPUT)
1152
+ : queued;
1153
+ }
1154
+ break;
1155
+ }
1156
+ case 'voice-start': {
1157
+ // Capture and response ownership belong to this window, not the shared PTY.
1158
+ ws.voice = {
1159
+ chunks: [],
1160
+ bytes: 0,
1161
+ mimeType: typeof data.mimeType === 'string' ? data.mimeType.slice(0, 80) : '',
1162
+ startedAt: Date.now()
1163
+ };
1164
+ sendToSocket(ws, { type: 'voice-ready' });
1165
+ break;
1166
+ }
1167
+ case 'voice-chunk': {
1168
+ if (!ws.voice) {
1169
+ voiceError(ws, 'VOICE_NOT_STARTED', 'Voice input was not started');
1170
+ break;
1171
+ }
1172
+ if (typeof data.b64 !== 'string' || data.b64.length === 0) {
1173
+ voiceError(ws, 'VOICE_BAD_CHUNK', 'Voice chunk was empty or invalid');
1174
+ break;
1175
+ }
1176
+ let chunk;
1177
+ try { chunk = Buffer.from(data.b64, 'base64'); }
1178
+ catch (_) { chunk = Buffer.alloc(0); }
1179
+ if (!chunk.length) {
1180
+ voiceError(ws, 'VOICE_BAD_CHUNK', 'Voice chunk could not be decoded');
1181
+ break;
1182
+ }
1183
+ if (chunk.length > STT_MAX_CHUNK_BYTES) {
1184
+ ws.voice = null;
1185
+ voiceError(ws, 'VOICE_CHUNK_TOO_LARGE', 'Voice chunk exceeded the size limit');
1186
+ break;
1187
+ }
1188
+ if (ws.voice.bytes + chunk.length > STT_MAX_UTTERANCE_BYTES) {
1189
+ ws.voice = null;
1190
+ voiceError(ws, 'VOICE_TOO_LARGE', 'Voice utterance exceeded the size limit');
1191
+ break;
1192
+ }
1193
+ ws.voice.chunks.push(chunk);
1194
+ ws.voice.bytes += chunk.length;
1195
+ break;
1196
+ }
1197
+ case 'voice-end': {
1198
+ finalizeVoice(session, ws);
1199
+ break;
1200
+ }
1201
+ case 'resize': {
1202
+ const { cols, rows } = clampDims(data.cols, data.rows);
1203
+ if (cols !== session.lastCols || rows !== session.lastRows) {
1204
+ session.widthChanged = true;
1205
+ session.resizeMarkers.push({ at: session.outputChars, cols, rows });
1206
+ }
1207
+ session.lastCols = cols;
1208
+ session.lastRows = rows;
1209
+ if (session.ptyProcess && !session.processExited) {
1210
+ try { session.ptyProcess.resize(cols, rows); }
1211
+ catch (e) { wsError(ws, 'RESIZE_FAILED', `Resize failed: ${e.message}`, session.id); }
1212
+ }
1213
+ break;
1214
+ }
1215
+ case 'close': {
1216
+ // Explicit close → full teardown. With a sessionId it ends another
1217
+ // session this page is not viewing; without one it ends its own.
1218
+ const target = data.sessionId ? activeSessions.get(String(data.sessionId)) : session;
1219
+ if (!target || !target.listed) {
1220
+ commandResult(ws, data, { ok: false, code: 'SESSION_NOT_FOUND', error: 'That session is no longer available.' });
1221
+ break;
1222
+ }
1223
+ target.userClosed = true;
1224
+ commandResult(ws, data, { ok: true });
1225
+ cleanupSession(target, 'closed');
1226
+ break;
1227
+ }
1228
+ case 'ping': {
1229
+ if (ws.readyState === WebSocket.OPEN) {
1230
+ ws.send(JSON.stringify({ type: 'pong', ts: data.ts }));
1231
+ }
1232
+ break;
1233
+ }
1234
+ case 'pong': {
1235
+ clearTimeout(pongTimers.get(session.id));
1236
+ pongTimers.delete(session.id);
1237
+ break;
1238
+ }
1239
+ default: wsError(ws, 'UNKNOWN_MESSAGE', `Unknown message type: ${data.type}`, session.id);
1240
+ }
1241
+ }
1242
+
1243
+ // ─── WS event binding ───────────────────────────────────────────────────────
1244
+
1245
+ /**
1246
+ * Bind a freshly-connected WS onto a session. Handlers read the active session
1247
+ * through `ws.__sessionRef`, so a resume that re-points that property needs no
1248
+ * re-registration (and therefore cannot double-dispatch).
1249
+ * @param {import('ws').WebSocket} ws
1250
+ * @param {Session} session
1251
+ */
1252
+ function bindWsToSession(ws, session) {
1253
+ ws.__sessionRef = session;
1254
+
1255
+ const remoteAddr = ws._socket?.remoteAddress || null;
1256
+ info(session.id, 'WebSocket connected', { ip: remoteAddr });
1257
+
1258
+ ws.on('message', (message) => {
1259
+ const s = ws.__sessionRef;
1260
+ if (!s) return;
1261
+ try { handleMessage(s, ws, JSON.parse(message)); }
1262
+ catch (err) { error(s.id, 'Failed to parse WS message', { err: err.message }); wsError(ws, 'PARSE_ERROR', 'Malformed JSON message', s.id); }
1263
+ });
1264
+
1265
+ ws.on('pong', () => {
1266
+ const s = ws.__sessionRef;
1267
+ if (!s) return;
1268
+ clearTimeout(pongTimers.get(s.id));
1269
+ pongTimers.delete(s.id);
1270
+ });
1271
+
1272
+ ws.on('close', (code, reason) => {
1273
+ ws.voice = null;
1274
+ const s = ws.__sessionRef;
1275
+ if (!s) return;
1276
+ info(s.id, 'WebSocket disconnected', { code, reason: reason?.toString?.() || '', userClosed: !!s.userClosed });
1277
+
1278
+ // Explicit close already cleaned up the session; close any other windows
1279
+ // attached to it and retire the record.
1280
+ if (s.userClosed) {
1281
+ for (const socket of s.sockets || []) {
1282
+ if (socket !== ws) {
1283
+ try { socket.close(1000, 'session closed'); } catch (_) { /* already gone */ }
1284
+ }
1285
+ }
1286
+ if (s.sockets) s.sockets.clear();
1287
+ activeSessions.delete(s.id);
1288
+ return;
1289
+ }
1290
+ // Other windows still hold this shell: keep it live and hand ownership to
1291
+ // one of them. Closing one window must not detach the rest.
1292
+ if (!releaseSocket(s, ws)) return;
1293
+ if (s.ptyProcess && !s.processExited) {
1294
+ // The window went away, not the session. The shell keeps running, listed,
1295
+ // until it is closed or the app stops.
1296
+ info(s.id, 'Session detached; shell keeps running');
1297
+ } else {
1298
+ // No live shell to preserve — just drop the placeholder.
1299
+ activeSessions.delete(s.id);
1300
+ return;
1301
+ }
1302
+ if (s.listed) broadcastSessions();
1303
+ });
1304
+
1305
+ ws.on('error', (err) => {
1306
+ const s = ws.__sessionRef;
1307
+ error(s ? s.id : null, 'WebSocket error', { err: err.message || String(err) });
1308
+ // An error does not necessarily kill the socket; mark inactive and let the
1309
+ // close handler decide grace vs cleanup. Never let a superseded socket
1310
+ // mark the live owner inactive.
1311
+ if (s && (!s.ws || s.ws === ws) && (!s.sockets || s.sockets.size <= 1)) s.sessionActive = false;
1312
+ });
1313
+ }
1314
+
1315
+ // ─── Express app ────────────────────────────────────────────────────────────
1316
+
1317
+ const app = express();
1318
+ app.use((req, res, next) => {
1319
+ 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.' });
1320
+ res.setHeader('X-Content-Type-Options', 'nosniff');
1321
+ res.setHeader('Content-Security-Policy', "frame-ancestors 'none'");
1322
+ next();
1323
+ });
1324
+
1325
+ // Owner capability cookie. Terminal agents must never be able to bootstrap the
1326
+ // human workspace just because they can reach loopback: an Authorization header
1327
+ // is denied at the bootstrap routes, and a header-less local client has no
1328
+ // capability at all. The cookie is minted only on a real page navigation and is
1329
+ // HttpOnly + SameSite=Strict, so page scripts and cross-site requests cannot
1330
+ // read or replay it.
1331
+ const OWNER_COOKIE = 'townmouse_owner';
1332
+ const OWNER_CAPABILITY = crypto.randomBytes(32).toString('hex');
1333
+ app.use((req, res, next) => {
1334
+ const ownerPage = req.method === 'GET' &&
1335
+ (req.path === '/' || req.path === '/index.html' || req.path === '/panes' || req.path === '/panes.html');
1336
+ // A navigation is known by the one detail a browser sets on every request
1337
+ // and nothing else sends unless it sets it on purpose: Sec-Fetch-Mode.
1338
+ // A plain HTTP client that merely asks for the page with "Accept: text/html"
1339
+ // gets the page and no cookie. Sec-Fetch-Dest is deliberately not required:
1340
+ // a document opened through a service worker's fetch() arrives as a
1341
+ // navigation with dest "empty" (measured in Chrome on the terminal surface's
1342
+ // second load), and requiring "document" would lock the person out of it.
1343
+ const navigates = req.get('Sec-Fetch-Mode') === 'navigate';
1344
+ if (ownerPage && !req.get('Authorization') && navigates) {
1345
+ res.cookie(OWNER_COOKIE, OWNER_CAPABILITY, {
1346
+ httpOnly: true,
1347
+ sameSite: 'strict',
1348
+ path: '/',
1349
+ maxAge: 12 * 60 * 60 * 1000
1350
+ });
1351
+ }
1352
+ const cookies = String(req.headers.cookie || '').split(/;\s*/);
1353
+ req.isOwner = cookies.includes(`${OWNER_COOKIE}=${OWNER_CAPABILITY}`);
1354
+ next();
1355
+ });
1356
+
1357
+ // Attachments must be mounted before the global JSON parser: JSON files are
1358
+ // valid uploads and the raw parser, not express.json, must consume their body.
1359
+ require('./attachments').installAttachments(app);
1360
+ // Pane input/command bodies can be large pastes. 2 MB keeps a single request
1361
+ // below the attachment limit while still bounding local API requests.
1362
+ app.use(express.json({ limit: '2mb' }));
1363
+ // Repair node-pty's spawn-helper mode before any pane can spawn. npm tarballs do
1364
+ // not carry the executable bit, and npm 12 does not run dependency postinstalls,
1365
+ // so this cannot be left to the install step.
1366
+ const ptyHelpers = ensurePtyHelpers();
1367
+ if (ptyHelpers.fixed.length) {
1368
+ info(null, 'Repaired node-pty spawn helper permissions', { dir: ptyHelpers.dir, files: ptyHelpers.fixed.length });
1369
+ }
1370
+
1371
+ const browserWorkspace = require('./browser-workspace').installBrowserWorkspace(app);
1372
+ const closeBrowsers = () => browserWorkspace.closeAll();
1373
+
1374
+ // workspace-panes loads node-pty at module load. If the native engine is
1375
+ // missing, explain the actual fix instead of dying in a require stack.
1376
+ let paneWorkspace;
1377
+ try {
1378
+ paneWorkspace = require('./workspace-panes').installWorkspacePanes(app, browserWorkspace, { port: PORT });
1379
+ } catch (error) {
1380
+ if (isTerminalEngineError(error)) {
1381
+ console.error(terminalEngineHelp(process.platform, error.message));
1382
+ process.exit(78);
1383
+ }
1384
+ throw error;
1385
+ }
1386
+
1387
+ // App assets are served with no-store so the browser always runs the latest
1388
+ // frontend (critical during input/dictation iteration — a cached input-guard.mjs
1389
+ // silently reproduces already-fixed echo bugs).
1390
+ app.get('/panes', (req, res) => res.sendFile(path.join(__dirname, '..', 'public', 'panes.html')));
1391
+ app.use(express.static(path.join(__dirname, '..', 'public'), {
1392
+ setHeaders: (res) => res.setHeader('Cache-Control', 'no-store'),
1393
+ }));
1394
+ // Resolve dependency assets through Node's lookup paths: a hoisted `npm install`
1395
+ // has no package-local node_modules, and the terminal page would 404 its engine.
1396
+ // This replaces the old blanket static mount, which both missed hoisted installs
1397
+ // and served every file under node_modules.
1398
+ installStaticDependencies(app);
1399
+
1400
+ app.get('/health', (req, res) => {
1401
+ // `browser.engine` is reported without launching it: an install with no
1402
+ // Chromium is healthy for terminal work and should say why browser panes
1403
+ // cannot start instead of failing later with a stack trace.
1404
+ let browser = { engine: 'unknown' };
1405
+ try { browser = browserWorkspace.engineStatus(); } catch (_) { /* reported as unknown */ }
1406
+ // The shells a person can see in the row, not the short-lived record every
1407
+ // connection starts as.
1408
+ res.json({ status: 'ok', version: APP_VERSION, sessions: listedSessions().length, browser });
1409
+ });
1410
+ app.get('/api/voice/settings', (req, res) => {
1411
+ res.json(voiceSettingsPayload());
1412
+ });
1413
+ app.put('/api/voice/settings', (req, res) => {
1414
+ const checked = validateVoiceConfig(req.body || {});
1415
+ if (!checked.ok) { res.status(400).json({ error: checked.error }); return; }
1416
+ try {
1417
+ writeVoiceConfig(checked.value);
1418
+ } catch (err) {
1419
+ error(null, 'Could not save voice settings', { err: err.message });
1420
+ res.status(500).json({ error: `Could not save voice settings: ${err.message}` });
1421
+ return;
1422
+ }
1423
+ res.json({ ...checked.value, resolved: resolveVoiceCommand(checked.value.command) });
1424
+ });
1425
+ // ── Shell sessions for agents ────────────────────────────────────────────────
1426
+ // Same token, caller and error shapes as /api/panes. `auth` has already read
1427
+ // who is asking from the key: 'owner' is the person's page with its own key,
1428
+ // 'agent' is anything holding the workspace token. The person's page drives
1429
+ // the same actions over its own WebSocket; this is the agent's door.
1430
+ const sessionAuth = paneWorkspace.auth;
1431
+ const sessionRoute = paneWorkspace.route;
1432
+ // The owner is the owner's page; anything else is an agent.
1433
+ const sessionViewer = (req) => (req.caller === 'owner' ? 'owner' : 'agent');
1434
+ const refuse = (status, code, message, extra = {}) => {
1435
+ throw Object.assign(new Error(message), { status, body: { error: message, code, ...extra } });
1436
+ };
1437
+ function liveSession(id) {
1438
+ const session = activeSessions.get(String(id || ''));
1439
+ if (!session || !session.listed) refuse(404, 'SESSION_NOT_FOUND', 'Session not found.');
1440
+ return session;
1441
+ }
1442
+ // A shell belongs to whoever started it, as a pane does. Renaming, showing
1443
+ // and ending a shell the owner started are the owner's alone, whatever an
1444
+ // agent has been given; on a shell an agent started, any agent may.
1445
+ function requireSessionOwner(session, caller, verb) {
1446
+ if (caller === 'owner' || session.createdBy === 'agent') return;
1447
+ refuse(403, 'OWNER_ONLY', `The owner started this shell, so only the owner can ${verb} it.`);
1448
+ }
1449
+ function checkedName(value, exceptId) {
1450
+ const checked = validSessionName(value);
1451
+ if (!checked.ok) refuse(400, 'INVALID_NAME', `name cannot be used: ${checked.error}.`);
1452
+ if (nameInUse(checked.value, exceptId)) {
1453
+ refuse(409, 'NAME_IN_USE', `Another session is already named “${checked.value}”.`);
1454
+ }
1455
+ return checked.value;
1456
+ }
1457
+
1458
+ // The shells that exist right now, in row order, as the caller may see them.
1459
+ app.get('/api/sessions', sessionAuth, sessionRoute(async (req, res) => {
1460
+ res.json(sessionState(sessionViewer(req)));
1461
+ }));
1462
+
1463
+ // Start a shell nobody is viewing yet. It appears in the person's row and
1464
+ // does not change which shell the person is looking at, unless `activate` is
1465
+ // asked for.
1466
+ app.post('/api/sessions', sessionAuth, sessionRoute(async (req, res) => {
1467
+ const body = req.body || {};
1468
+ // The key that asks decides whose shell it is. createdBy in the body is
1469
+ // ignored, as it is for panes: it was how a client described itself, and
1470
+ // trusting it let an agent label a shell as the owner's.
1471
+ const createdBy = sessionViewer(req) === 'owner' ? 'human' : 'agent';
1472
+ if (countRealShells() >= MAX_CONCURRENT_SESSIONS) {
1473
+ // An agent that holds no shell it may close cannot make room itself, and
1474
+ // must be told why rather than be sent looking for something to close.
1475
+ if (createdBy === 'agent' && !listedSessions().some((s) => s.createdBy === 'agent')) {
1476
+ const ownerStarted = listedSessions().length;
1477
+ refuse(409, 'SESSION_LIMIT',
1478
+ `All ${MAX_CONCURRENT_SESSIONS} sessions are in use and the owner started all ${ownerStarted} of them, so there is none an agent may close. Ask the owner to close one.`,
1479
+ { max: MAX_CONCURRENT_SESSIONS, ownerStarted });
1480
+ }
1481
+ refuse(409, 'SESSION_LIMIT', 'Close a session before opening another.', { max: MAX_CONCURRENT_SESSIONS });
1482
+ }
1483
+ const name = body.name === undefined || body.name === null || body.name === '' ? '' : checkedName(body.name);
1484
+ let cwd;
1485
+ if (body.cwd !== undefined && body.cwd !== null && body.cwd !== '') {
1486
+ cwd = String(body.cwd);
1487
+ let stat = null;
1488
+ try { stat = fs.statSync(cwd); } catch (_) { /* refused below */ }
1489
+ if (!stat || !stat.isDirectory()) refuse(400, 'INVALID_CWD', 'cwd must be an existing directory.');
1490
+ }
1491
+ const session = createSession({
1492
+ cwd, name,
1493
+ createdBy,
1494
+ activate: body.activate === true
1495
+ });
1496
+ res.json(serializeSession(session));
1497
+ }));
1498
+
1499
+ // Give a shell a name the person can read. Names are unique.
1500
+ app.patch('/api/sessions/:id', sessionAuth, sessionRoute(async (req, res) => {
1501
+ const session = liveSession(req.params.id);
1502
+ requireSessionOwner(session, req.caller, 'rename');
1503
+ session.name = checkedName((req.body || {}).name, session.id);
1504
+ info(session.id, 'Session renamed', { name: session.name, by: sessionViewer(req) });
1505
+ broadcastSessions();
1506
+ res.json(serializeSession(session));
1507
+ }));
1508
+
1509
+ // The one action that moves the person's view: every open terminal page shows
1510
+ // this shell. An agent uses it only when the person asked to see that shell.
1511
+ app.post('/api/sessions/:id/activate', sessionAuth, sessionRoute(async (req, res) => {
1512
+ const session = liveSession(req.params.id);
1513
+ requireSessionOwner(session, req.caller, 'show');
1514
+ activateSession(session);
1515
+ const windows = broadcastSessions();
1516
+ info(session.id, 'Session activated', { by: sessionViewer(req), windows });
1517
+ res.json({ activated: windows > 0, windows, session: serializeSession(session) });
1518
+ }));
1519
+
1520
+ // End a shell and its shell process. A page that was viewing it moves to
1521
+ // another one. It cannot be taken back.
1522
+ app.delete('/api/sessions/:id', sessionAuth, sessionRoute(async (req, res) => {
1523
+ const session = liveSession(req.params.id);
1524
+ requireSessionOwner(session, req.caller, 'close');
1525
+ session.userClosed = true;
1526
+ cleanupSession(session, 'closed');
1527
+ res.json({ closed: true, ...sessionState(sessionViewer(req)) });
1528
+ }));
1529
+
1530
+ // ─── HTTP + WebSocket server ────────────────────────────────────────────────
1531
+
1532
+ const server = http.createServer(app);
1533
+ const wss = new WebSocket.Server({ server, verifyClient: ({ req }) => isTrustedRequest(req) });
1534
+
1535
+ wss.on('connection', (ws) => {
1536
+ // Each connection starts as a fresh placeholder session. It becomes "real"
1537
+ // when the client sends `shell`, or it adopts an existing session via `resume`.
1538
+ const session = newSessionRecord(ws);
1539
+ session.startedAt = Date.now();
1540
+ activeSessions.set(session.id, session);
1541
+
1542
+ bindWsToSession(ws, session);
1543
+ startHeartbeat(session);
1544
+ });
1545
+
1546
+ // ─── Graceful shutdown ─────────────────────────────────────────────────────
1547
+
1548
+ /** @param {string} signal */
1549
+ async function shutdown(signal, exitCode = 0) {
1550
+ info(null, `Received ${signal}, starting graceful shutdown`, { activeSessions: activeSessions.size });
1551
+ server.close();
1552
+ await paneWorkspace.closeAll().catch(err => error(null, 'Pane shutdown failed', {err:err.message}));
1553
+ await closeBrowsers().catch(err => error(null, 'Browser shutdown failed', {err:err.message}));
1554
+ const promises = Array.from(activeSessions.values()).map((s) => {
1555
+ // A stopped app ends every shell; none of them survives the process.
1556
+ if (s.ptyProcess) killPty(s.ptyProcess, s.id);
1557
+ activeSessions.delete(s.id);
1558
+ return new Promise((r) => setTimeout(r, KILL_GRACE_MS + 100));
1559
+ });
1560
+ await Promise.race([Promise.all(promises), new Promise((r) => setTimeout(r, 5_000))]);
1561
+ info(null, 'Shutdown complete', { activeSessions: activeSessions.size });
1562
+ process.exit(exitCode);
1563
+ }
1564
+
1565
+ process.on('unhandledRejection', (reason) => {
1566
+ const message = reason instanceof Error ? reason.stack || reason.message : String(reason);
1567
+ error(null, 'Unhandled promise rejection', { err: message });
1568
+ });
1569
+
1570
+ process.on('uncaughtException', (err) => {
1571
+ error(null, 'Uncaught exception — shutting down', { err: err?.stack || String(err) });
1572
+ const force = setTimeout(() => process.exit(1), 6000);
1573
+ force.unref?.();
1574
+ shutdown('uncaughtException', 1).catch(() => process.exit(1));
1575
+ });
1576
+
1577
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
1578
+ process.on('SIGINT', () => shutdown('SIGINT'));
1579
+
1580
+ server.listen(PORT, HOST, () => {
1581
+ info(null, `Townmouse running at http://localhost:${PORT}`, { maxSessions: MAX_CONCURRENT_SESSIONS });
1582
+ });