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
@@ -0,0 +1,1099 @@
1
+ 'use strict';
2
+ const crypto = require('crypto');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const { spawn } = require('child_process');
7
+ const { StringDecoder } = require('string_decoder');
8
+ const pty = require('node-pty');
9
+ const { resolveShell } = require('./shell-resolve');
10
+ const { replayTranscript } = require('./replay-text');
11
+ const { buildGuide } = require('./agent-guide');
12
+ const { createPatternMatcher } = require('./safe-regex');
13
+
14
+ const MAX_PANES_PER_TAB = 4;
15
+ const MAX_TABS = 24;
16
+ const MAX_TERMINAL_PANES = 24;
17
+ const MAX_BUFFER = 200_000;
18
+ // HTTP/1.1 browsers allow six connections per origin. Keep two slots free for
19
+ // input/state/close so terminal streams cannot starve the controls. Panes over
20
+ // this cap fall back to the polling API instead of holding a socket open.
21
+ const MAX_ACTIVE_STREAMS = 4;
22
+
23
+ // Tracked, non-interactive jobs. Bounded so a long session cannot accumulate
24
+ // output forever. Interactive programs still belong in the PTY.
25
+ const MAX_JOBS_PER_PANE = 40;
26
+ const MAX_JOB_OUTPUT = 512 * 1024;
27
+
28
+ // Variables a parent AI harness exports about *its own* process. A pane is an
29
+ // independent session, not a child of whatever launched the TownMouse server,
30
+ // so inheriting these makes a fresh harness believe it is a nested child
31
+ // (which, among other things, disables conversation saving). Credentials and
32
+ // configuration are deliberately kept.
33
+ const INHERITED_SESSION_ENV = new Set([
34
+ 'CLAUDECODE',
35
+ 'CLAUDE_CODE_CHILD_SESSION',
36
+ 'CLAUDE_CODE_SESSION_ID',
37
+ 'CLAUDE_CODE_ENTRYPOINT',
38
+ 'CLAUDE_CODE_SESSION_ATTENDED',
39
+ 'CLAUDE_CODE_MESSAGING_SOCKET',
40
+ 'CLAUDE_CODE_MESSAGING_TOKEN',
41
+ 'CLAUDE_CODE_AUTO_MODE_SERVER',
42
+ 'CLAUDE_PID',
43
+ 'CLAUDE_EFFORT'
44
+ ]);
45
+
46
+ function paneEnvironment(extra = {}) {
47
+ const env = {};
48
+ const strip = new Set(INHERITED_SESSION_ENV);
49
+ for (const name of String(process.env.TOWNMOUSE_PANE_ENV_STRIP || '').split(',')) {
50
+ const trimmed = name.trim();
51
+ if (trimmed) strip.add(trimmed);
52
+ }
53
+ for (const [key, value] of Object.entries(process.env)) {
54
+ if (strip.has(key)) continue;
55
+ env[key] = value;
56
+ }
57
+ return { ...env, ...extra };
58
+ }
59
+
60
+ function installWorkspacePanes(app, browserWorkspace, options = {}) {
61
+ const port = options.port || Number(process.env.PORT) || 11357;
62
+ const apiUrl = `http://127.0.0.1:${port}/api/panes`;
63
+ const cliPath = path.join(__dirname, '..', 'scripts', 'panes');
64
+ const epoch = crypto.randomUUID();
65
+ const tokenDir = path.join(os.homedir(), '.townmouse');
66
+ const tokenFile = path.join(tokenDir, 'pane-token');
67
+ let token = '';
68
+ try { token = fs.readFileSync(tokenFile, 'utf8').trim(); } catch (_) { /* first run */ }
69
+ if (!token) {
70
+ token = crypto.randomBytes(32).toString('hex');
71
+ fs.mkdirSync(tokenDir, { recursive: true, mode: 0o700 });
72
+ fs.writeFileSync(tokenFile, token, { mode: 0o600 });
73
+ }
74
+ try { fs.chmodSync(tokenFile, 0o600); } catch (_) { /* best effort */ }
75
+ // Attachment uploads are owner-gated at the page boundary, but a terminal
76
+ // agent inside the workspace presents this scoped pane token instead.
77
+ app.locals.townmousePaneToken = token;
78
+ const stateDir = process.env.TOWNMOUSE_STATE_DIR || path.join(os.homedir(), '.townmouse');
79
+ const stateFile = path.join(stateDir, 'workspace.json');
80
+
81
+ const tabs = new Map();
82
+ const panes = new Map();
83
+ let activeTabId = null;
84
+ let activePaneId = null;
85
+ let restored = false;
86
+ let savedWorkspace = false;
87
+ let restorePromise = null;
88
+ let saveTimer = null;
89
+ let shuttingDown = false;
90
+ let activeStreams = 0;
91
+
92
+ const id = (prefix) => prefix + '_' + crypto.randomBytes(6).toString('hex');
93
+ const route = (fn) => async (req, res) => {
94
+ res.set('Cache-Control', 'no-store');
95
+ try { await fn(req, res); }
96
+ catch (error) {
97
+ // Some refusals (a stale target) carry a structured body so the caller can
98
+ // tell "rejected, look again" apart from an ordinary error.
99
+ res.status(error.status || 400).json(error.body || { error: error.message });
100
+ }
101
+ };
102
+ app.use('/api/panes', (req, res, next) => {
103
+ if (req.body == null) req.body = {};
104
+ next();
105
+ });
106
+ const auth = (req, res, next) => {
107
+ const supplied = req.get('X-Townmouse-Token') || (req.get('Authorization') || '').replace(/^Bearer\s+/i, '');
108
+ if (supplied !== token) { res.status(403).json({ error: 'Workspace token required.' }); return; }
109
+ next();
110
+ };
111
+ const tabOf = (pane) => tabs.get(pane.tabId) || null;
112
+
113
+ function createTab(title, createdBy = 'human') {
114
+ if (tabs.size >= MAX_TABS) {
115
+ throw Object.assign(new Error('Close a workspace tab before opening another.'), { status: 409 });
116
+ }
117
+ const tab = { id: id('t'), title: title || `Workspace ${tabs.size + 1}`, createdBy, panes: [] };
118
+ tabs.set(tab.id, tab);
119
+ if (!activeTabId) activeTabId = tab.id;
120
+ scheduleSave();
121
+ return tab;
122
+ }
123
+
124
+ const clampCols = (value) => Math.max(20, Math.min(400, Math.round(Number(value) || 100)));
125
+ const clampRows = (value) => Math.max(5, Math.min(200, Math.round(Number(value) || 30)));
126
+ const KEY_SEQUENCES = {
127
+ enter: '\r', return: '\r', esc: '\x1b', escape: '\x1b', tab: '\t',
128
+ backspace: '\x7f', delete: '\x1b[3~', space: ' ',
129
+ up: '\x1b[A', down: '\x1b[B', right: '\x1b[C', left: '\x1b[D',
130
+ home: '\x1b[H', end: '\x1b[F', pgup: '\x1b[5~', pgdn: '\x1b[6~',
131
+ pageup: '\x1b[5~', pagedown: '\x1b[6~'
132
+ };
133
+
134
+ function keySequence(name) {
135
+ const raw = String(name || '').trim();
136
+ if (!raw || raw.length > 40) throw Object.assign(new Error('Invalid key name.'), { status: 400 });
137
+ const parts = raw.toLowerCase().split('+').filter(Boolean);
138
+ const key = parts.pop();
139
+ let sequence = KEY_SEQUENCES[key];
140
+ if (!sequence && key.length === 1) sequence = key;
141
+ if (!sequence) throw Object.assign(new Error(`Unknown key: ${raw}`), { status: 400 });
142
+ const ctrl = parts.includes('ctrl') || parts.includes('control');
143
+ const alt = parts.includes('alt') || parts.includes('option');
144
+ const shift = parts.includes('shift');
145
+ if (key === 'tab' && shift) sequence = '\x1b[Z';
146
+ else if (ctrl && key.length === 1) sequence = String.fromCharCode(key.charCodeAt(0) & 0x1f);
147
+ if (alt) sequence = '\x1b' + sequence;
148
+ return sequence;
149
+ }
150
+
151
+ // A terminal can outrun a slow SSE reader. Honor write backpressure instead
152
+ // of letting Node queue every chunk in memory. Once a reader falls behind we
153
+ // end its stream; the client's polling fallback catches up from /read.
154
+ function sendStreamEvent(stream, event) {
155
+ if (stream._sseBlocked) {
156
+ stream._sseDropped = true;
157
+ return;
158
+ }
159
+ try {
160
+ if (!stream.write(event)) {
161
+ stream._sseBlocked = true;
162
+ stream.once('drain', () => {
163
+ stream._sseBlocked = false;
164
+ if (stream._sseDropped) {
165
+ try { stream.end(); } catch (_) { /* already gone */ }
166
+ }
167
+ });
168
+ }
169
+ } catch (_) {
170
+ stream._sseDropped = true;
171
+ try { stream.end(); } catch (_) { /* already gone */ }
172
+ }
173
+ }
174
+
175
+ function startPanePty(pane) {
176
+ const env = paneEnvironment({
177
+ TERM: 'xterm-256color',
178
+ TOWNMOUSE_API: apiUrl,
179
+ TOWNMOUSE_TOKEN: token,
180
+ TOWNMOUSE_TAB_ID: pane.tabId,
181
+ TOWNMOUSE_PANE_ID: pane.id,
182
+ TOWNMOUSE_PANES_CLI: cliPath
183
+ });
184
+ pane.cwd = pane.cwd || os.homedir();
185
+ const shell = resolveShell();
186
+ // A fresh program is not the previous task. Drop the old agent-reported
187
+ // "done"/"working" label rather than presenting it as a report about this
188
+ // program.
189
+ pane.agentState = null;
190
+ pane.agentMessage = '';
191
+ pane.agentStateAt = null;
192
+ pane.exited = false;
193
+ pane.exitCode = null;
194
+ pane.exitSignal = null;
195
+ pane.startedAt = Date.now();
196
+ const child = pty.spawn(shell, ['-l'], {
197
+ name: 'xterm-256color', cols: pane.cols, rows: pane.rows,
198
+ cwd: pane.cwd, env
199
+ });
200
+ pane.pty = child;
201
+ child.onData((data) => {
202
+ pane.lastOutputAt = Date.now();
203
+ pane.buffer += data;
204
+ pane.totalOffset += data.length;
205
+ if (pane.buffer.length > MAX_BUFFER) pane.buffer = pane.buffer.slice(-MAX_BUFFER);
206
+ pane.bufferStart = pane.totalOffset - pane.buffer.length;
207
+ const event = `data: ${JSON.stringify({ data, offset: pane.totalOffset })}\n\n`;
208
+ for (const stream of pane.streams) sendStreamEvent(stream, event);
209
+ });
210
+ child.onExit((event = {}) => {
211
+ // Program status only. Whether the *agent* finished is its own report,
212
+ // and a quiet or exited program is not that report.
213
+ pane.exited = true;
214
+ pane.exitCode = Number.isFinite(Number(event.exitCode)) ? Number(event.exitCode) : null;
215
+ pane.exitSignal = event.signal ?? null;
216
+ pane.exitedAt = Date.now();
217
+ pane.lastOutputAt = Date.now();
218
+ });
219
+ }
220
+
221
+ async function createPane(tabId, kind, opts = {}) {
222
+ let tab = tabs.get(tabId);
223
+ if (!tab) throw Object.assign(new Error('Workspace tab not found.'), { status: 404 });
224
+ if (tab.panes.length >= MAX_PANES_PER_TAB) {
225
+ throw Object.assign(new Error('A workspace tab holds at most four panes.'), { status: 409 });
226
+ }
227
+ if (kind !== 'browser' && [...panes.values()].filter((pane) => pane.kind === 'terminal').length >= MAX_TERMINAL_PANES) {
228
+ throw Object.assign(new Error('Close a terminal pane before opening another.'), { status: 409 });
229
+ }
230
+ const pane = {
231
+ id: id('p'), tabId, kind: kind === 'browser' ? 'browser' : 'terminal',
232
+ title: opts.title || '', titleLocked: Boolean(opts.title), url: '', browserId: null, pty: null,
233
+ createdBy: opts.createdBy === 'agent' ? 'agent' : 'human',
234
+ cwd: opts.cwd || null,
235
+ buffer: '', bufferStart: 0, totalOffset: 0, streams: new Set(),
236
+ cols: clampCols(opts.cols), rows: clampRows(opts.rows), exited: false,
237
+ exitCode: null, exitSignal: null, lastOutputAt: Date.now(), createdAt: Date.now(),
238
+ startedAt: null, exitedAt: null, jobs: [], liveJobs: 0,
239
+ agentState: null, agentMessage: '', agentStateAt: null
240
+ };
241
+ if (pane.kind === 'browser') {
242
+ const browser = await browserWorkspace.create('agent', opts.url);
243
+ tab = tabs.get(tabId);
244
+ if (!tab) {
245
+ await browserWorkspace.close(browser.id).catch(() => {});
246
+ throw Object.assign(new Error('Workspace tab was closed while the browser opened.'), { status: 404 });
247
+ }
248
+ if (tab.panes.length >= MAX_PANES_PER_TAB) {
249
+ await browserWorkspace.close(browser.id).catch(() => {});
250
+ throw Object.assign(new Error('A workspace tab holds at most four panes.'), { status: 409 });
251
+ }
252
+ pane.browserId = browser.id;
253
+ pane.url = browser.url && browser.url !== 'about:blank' ? browser.url : (opts.url || '');
254
+ pane.title = opts.title || browser.title || 'Browser';
255
+ } else {
256
+ pane.title = opts.title || `Terminal ${tab.panes.length + 1}`;
257
+ pane.cwd = opts.cwd || os.homedir();
258
+ // UI-created panes defer the PTY until the client has measured the pane,
259
+ // so the first prompt wraps at the width the user can actually see.
260
+ if (opts.start !== false) startPanePty(pane);
261
+ }
262
+ tab.panes.push(pane);
263
+ panes.set(pane.id, pane);
264
+ scheduleSave();
265
+ return pane;
266
+ }
267
+
268
+ function scheduleSave() {
269
+ if (!restored || shuttingDown) return;
270
+ if (saveTimer) clearTimeout(saveTimer);
271
+ saveTimer = setTimeout(() => {
272
+ saveTimer = null;
273
+ saveState().catch(() => { /* the next mutation retries */ });
274
+ }, 150).unref?.();
275
+ }
276
+
277
+ async function saveState() {
278
+ const list = [...tabs.values()];
279
+ const activeIndex = Math.max(0, list.findIndex((tab) => tab.id === activeTabId));
280
+ const activeTab = list[activeIndex];
281
+ const activePaneIndex = activeTab
282
+ ? Math.max(0, activeTab.panes.findIndex((pane) => pane.id === activePaneId))
283
+ : 0;
284
+ const payload = {
285
+ version: 1,
286
+ savedAt: new Date().toISOString(),
287
+ activeTabIndex: activeIndex,
288
+ activePaneIndex,
289
+ tabs: list.map((tab) => ({
290
+ title: tab.title,
291
+ createdBy: tab.createdBy,
292
+ panes: tab.panes.map((pane) => ({
293
+ kind: pane.kind,
294
+ title: pane.titleLocked ? pane.title : undefined,
295
+ url: pane.kind === 'browser' ? pane.url : undefined,
296
+ cwd: pane.kind === 'terminal' ? pane.cwd : undefined,
297
+ cols: pane.kind === 'terminal' ? pane.cols : undefined,
298
+ rows: pane.kind === 'terminal' ? pane.rows : undefined,
299
+ createdBy: pane.createdBy
300
+ }))
301
+ }))
302
+ };
303
+ await fs.promises.mkdir(stateDir, { recursive: true, mode: 0o700 });
304
+ const temp = stateFile + '.tmp';
305
+ await fs.promises.writeFile(temp, JSON.stringify(payload, null, 2), { mode: 0o600 });
306
+ await fs.promises.rename(temp, stateFile);
307
+ }
308
+
309
+ async function restoreState() {
310
+ let saved;
311
+ try { saved = JSON.parse(await fs.promises.readFile(stateFile, 'utf8')); }
312
+ catch (_) { return; }
313
+ if (!saved || !Array.isArray(saved.tabs)) return;
314
+ savedWorkspace = true;
315
+ for (const savedTab of saved.tabs.slice(0, MAX_TABS)) {
316
+ const tab = createTab(
317
+ typeof savedTab.title === 'string' ? savedTab.title : 'Workspace',
318
+ savedTab.createdBy === 'agent' ? 'agent' : 'human'
319
+ );
320
+ for (const savedPane of (savedTab.panes || []).slice(0, MAX_PANES_PER_TAB)) {
321
+ try {
322
+ // A browser pane that was never navigated saves about:blank, which
323
+ // the address validator correctly rejects. Omitting it creates a
324
+ // fresh blank browser pane instead of silently dropping the pane.
325
+ const savedUrl = typeof savedPane.url === 'string' && savedPane.url !== 'about:blank'
326
+ ? savedPane.url
327
+ : undefined;
328
+ await createPane(tab.id, savedPane.kind === 'browser' ? 'browser' : 'terminal', {
329
+ title: typeof savedPane.title === 'string' ? savedPane.title : undefined,
330
+ url: savedUrl,
331
+ cwd: typeof savedPane.cwd === 'string' ? savedPane.cwd : undefined,
332
+ cols: savedPane.cols,
333
+ rows: savedPane.rows
334
+ });
335
+ } catch (_) { /* one bad pane must not lose the rest of the workspace */ }
336
+ }
337
+ }
338
+ const list = [...tabs.values()];
339
+ if (!list.length) return;
340
+ const active = list[Math.min(Math.max(0, Number(saved.activeTabIndex) || 0), list.length - 1)];
341
+ if (!active) return;
342
+ activeTabId = active.id;
343
+ const pane = active.panes[Math.min(Math.max(0, Number(saved.activePaneIndex) || 0), Math.max(0, active.panes.length - 1))];
344
+ activePaneId = pane ? pane.id : (active.panes[0]?.id || null);
345
+ }
346
+
347
+ function serializePane(pane) {
348
+ if (pane.kind === 'browser' && pane.browserId) {
349
+ const browser = browserWorkspace.get(pane.browserId);
350
+ if (browser) {
351
+ const liveUrl = browser.page.url();
352
+ if (liveUrl && liveUrl !== 'about:blank') pane.url = liveUrl;
353
+ if (!pane.titleLocked) pane.title = browser.title || pane.title;
354
+ pane.sizing = browser.sizing;
355
+ } else {
356
+ pane.url = '';
357
+ if (!pane.titleLocked) pane.title = 'Browser unavailable';
358
+ }
359
+ }
360
+ const programStatus = pane.exited ? 'exited' : (pane.kind === 'terminal' && !pane.pty ? 'starting' : 'running');
361
+ const latestJob = pane.jobs.length ? serializeJob(pane.jobs[pane.jobs.length - 1], false) : null;
362
+ return {
363
+ id: pane.id, tabId: pane.tabId, kind: pane.kind, title: pane.title,
364
+ url: pane.url, browserId: pane.browserId,
365
+ sizing: pane.kind === 'browser' ? pane.sizing : undefined,
366
+ cwd: pane.kind === 'terminal' ? pane.cwd : undefined,
367
+ cols: pane.cols, rows: pane.rows,
368
+ // Kept flat for existing callers; the three meanings are also exposed
369
+ // separately below so they cannot be confused with one another.
370
+ status: programStatus,
371
+ programStatus,
372
+ program: {
373
+ status: programStatus,
374
+ startedAt: pane.startedAt,
375
+ exitedAt: pane.exitedAt,
376
+ exitCode: pane.exitCode,
377
+ exitSignal: pane.exitSignal
378
+ },
379
+ lastOutputAt: pane.lastOutputAt,
380
+ idleMs: Math.max(0, Date.now() - pane.lastOutputAt),
381
+ exitCode: pane.exitCode,
382
+ exitSignal: pane.exitSignal,
383
+ // Agent-reported status: what the AI last said about its own work.
384
+ agentState: pane.agentState,
385
+ agentMessage: pane.agentMessage,
386
+ agentStateAt: pane.agentStateAt,
387
+ agentStateAgeMs: pane.agentStateAt ? Math.max(0, Date.now() - pane.agentStateAt) : null,
388
+ agent: {
389
+ state: pane.agentState,
390
+ message: pane.agentMessage,
391
+ reportedAt: pane.agentStateAt,
392
+ ageMs: pane.agentStateAt ? Math.max(0, Date.now() - pane.agentStateAt) : null
393
+ },
394
+ // Command status: the most recent tracked job, if any.
395
+ command: latestJob ? {
396
+ jobId: latestJob.id,
397
+ status: latestJob.status,
398
+ exitCode: latestJob.exitCode,
399
+ startedAt: latestJob.startedAt,
400
+ endedAt: latestJob.endedAt
401
+ } : null,
402
+ createdBy: pane.createdBy,
403
+ active: pane.id === activePaneId
404
+ };
405
+ }
406
+
407
+ function serializeJob(job, includeOutput = true) {
408
+ const payload = {
409
+ id: job.id,
410
+ paneId: job.paneId,
411
+ command: job.command,
412
+ status: job.status,
413
+ startedAt: job.startedAt,
414
+ endedAt: job.endedAt,
415
+ elapsedMs: (job.endedAt || Date.now()) - job.startedAt,
416
+ exitCode: job.exitCode,
417
+ signal: job.signal,
418
+ timedOut: job.timedOut
419
+ };
420
+ if (includeOutput) {
421
+ payload.stdout = job.stdout;
422
+ payload.stderr = job.stderr;
423
+ payload.stdoutTruncated = job.stdoutTruncated;
424
+ payload.stderrTruncated = job.stderrTruncated;
425
+ }
426
+ return payload;
427
+ }
428
+ function serializeTab(tab) {
429
+ return { id: tab.id, title: tab.title, createdBy: tab.createdBy || 'human', active: tab.id === activeTabId, panes: tab.panes.map(serializePane) };
430
+ }
431
+ function state() {
432
+ return {
433
+ host: os.hostname().replace(/\.local$/i, '').toLowerCase(),
434
+ epoch,
435
+ restored,
436
+ tabs: [...tabs.values()].map(serializeTab),
437
+ activeTabId, activePaneId,
438
+ limits: { maxTabs: MAX_TABS, maxPanesPerTab: MAX_PANES_PER_TAB, maxTerminalPanes: MAX_TERMINAL_PANES }
439
+ };
440
+ }
441
+ function ensureInitial() {
442
+ if (!restorePromise) {
443
+ // Seed exactly once. An intentionally empty workspace (the user closed
444
+ // the last tab) must stay empty across state polls.
445
+ restorePromise = restoreState()
446
+ .catch(() => { /* corrupt state is not fatal */ })
447
+ .then(async () => {
448
+ restored = true;
449
+ if (savedWorkspace || tabs.size) return;
450
+ const tab = createTab('Workspace 1');
451
+ const pane = await createPane(tab.id, 'terminal', { title: 'Orchestrator' });
452
+ activeTabId = tab.id;
453
+ activePaneId = pane.id;
454
+ });
455
+ }
456
+ return restorePromise;
457
+ }
458
+ function killPty(pane) {
459
+ if (!pane.pty) return;
460
+ try { pane.pty.kill('SIGTERM'); } catch (_) { /* already gone */ }
461
+ setTimeout(() => {
462
+ try { pane.pty.kill('SIGKILL'); } catch (_) { /* exited cleanly */ }
463
+ }, 1000).unref?.();
464
+ }
465
+ function closePane(pane) {
466
+ if (!pane) return;
467
+ const tab = tabOf(pane);
468
+ if (tab) tab.panes = tab.panes.filter((candidate) => candidate.id !== pane.id);
469
+ panes.delete(pane.id);
470
+ for (const stream of pane.streams) { try { stream.end(); } catch (_) { /* already closed */ } }
471
+ pane.streams.clear();
472
+ for (const job of pane.jobs || []) cancelJob(job);
473
+ killPty(pane);
474
+ if (pane.kind === 'browser' && pane.browserId) browserWorkspace.close(pane.browserId).catch(() => {});
475
+ if (activePaneId === pane.id) {
476
+ const next = tab && tab.panes[0];
477
+ activePaneId = next ? next.id : null;
478
+ }
479
+ scheduleSave();
480
+ }
481
+
482
+ // ── Tracked jobs ─────────────────────────────────────────────────────────
483
+ //
484
+ // An ordinary, non-interactive command gets a real process with a pid, an
485
+ // exit code, and output attributed to it. Typing into the interactive shell
486
+ // and reading back recent output does not prove anything finished, and the
487
+ // two operations are kept separate on purpose.
488
+
489
+ function pruneJobs(pane) {
490
+ while (pane.jobs.length > MAX_JOBS_PER_PANE) {
491
+ const index = pane.jobs.findIndex((job) => job.status !== 'running');
492
+ if (index < 0) break;
493
+ pane.jobs.splice(index, 1);
494
+ }
495
+ }
496
+
497
+ function startJob(pane, command) {
498
+ const job = {
499
+ id: 'j_' + crypto.randomBytes(6).toString('hex'),
500
+ paneId: pane.id,
501
+ command,
502
+ status: 'running',
503
+ startedAt: Date.now(),
504
+ endedAt: null,
505
+ exitCode: null,
506
+ signal: null,
507
+ timedOut: false,
508
+ stdout: '',
509
+ stderr: '',
510
+ stdoutTruncated: false,
511
+ stderrTruncated: false,
512
+ child: null,
513
+ cancelled: false,
514
+ waiters: []
515
+ };
516
+ const env = paneEnvironment({
517
+ TERM: 'dumb',
518
+ TOWNMOUSE_API: apiUrl,
519
+ TOWNMOUSE_TOKEN: token,
520
+ TOWNMOUSE_TAB_ID: pane.tabId,
521
+ TOWNMOUSE_PANE_ID: pane.id,
522
+ TOWNMOUSE_PANES_CLI: cliPath
523
+ });
524
+ const shell = resolveShell();
525
+ // A compound command's children are not killed by signalling only the
526
+ // shell. Run the job in its own process group so cancellation and pane
527
+ // close can terminate the whole workload.
528
+ const child = spawn(shell, ['-lc', command], {
529
+ cwd: pane.cwd || os.homedir(),
530
+ env,
531
+ stdio: ['ignore', 'pipe', 'pipe'],
532
+ detached: process.platform !== 'win32'
533
+ });
534
+ job.child = child;
535
+ // Pipe chunks split multi-byte characters at arbitrary byte boundaries.
536
+ // Decode per stream so `é` is not turned into two replacement characters.
537
+ const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
538
+ const append = (key, text) => {
539
+ if (!text) return;
540
+ if (job[key].length < MAX_JOB_OUTPUT) {
541
+ job[key] += text.slice(0, MAX_JOB_OUTPUT - job[key].length);
542
+ }
543
+ if (job[key].length >= MAX_JOB_OUTPUT || text.length > MAX_JOB_OUTPUT) job[key + 'Truncated'] = true;
544
+ };
545
+ const collect = (channel) => (chunk) => append(channel, decoders[channel].write(chunk));
546
+ child.stdout.on('data', collect('stdout'));
547
+ child.stderr.on('data', collect('stderr'));
548
+ const finish = (status, detail = {}) => {
549
+ if (job.status !== 'running') return;
550
+ append('stdout', decoders.stdout.end());
551
+ append('stderr', decoders.stderr.end());
552
+ job.status = status;
553
+ job.endedAt = Date.now();
554
+ job.exitCode = detail.exitCode ?? null;
555
+ job.signal = detail.signal ?? null;
556
+ if (detail.timedOut) job.timedOut = true;
557
+ delete job.child;
558
+ for (const waiter of job.waiters.splice(0)) waiter();
559
+ };
560
+ child.on('error', (error) => {
561
+ job.stderr += (job.stderr ? '\n' : '') + String(error.message || error);
562
+ finish('failed', { exitCode: null });
563
+ });
564
+ child.on('close', (code, signal) => {
565
+ finish(job.cancelled ? 'cancelled' : (code === 0 ? 'completed' : 'failed'), { exitCode: code, signal });
566
+ });
567
+ pane.jobs.push(job);
568
+ pane.liveJobs += 1;
569
+ pruneJobs(pane);
570
+ return job;
571
+ }
572
+
573
+ function waitForJob(job, timeoutMs) {
574
+ if (job.status !== 'running') return Promise.resolve(job);
575
+ return new Promise((resolve) => {
576
+ let settled = false;
577
+ const done = () => {
578
+ if (settled) return;
579
+ settled = true;
580
+ clearTimeout(timer);
581
+ resolve(job);
582
+ };
583
+ const timer = setTimeout(() => {
584
+ // The job keeps running; the caller simply learns it is not done yet.
585
+ done();
586
+ }, Math.max(50, Math.min(120000, Number(timeoutMs) || 30000)));
587
+ job.waiters.push(done);
588
+ timer.unref?.();
589
+ });
590
+ }
591
+
592
+ function cancelJob(job) {
593
+ if (job.status !== 'running' || !job.child) return false;
594
+ job.cancelled = true;
595
+ const child = job.child;
596
+ const pid = child.pid;
597
+ const signalGroup = (signal) => {
598
+ if (process.platform !== 'win32' && pid) {
599
+ try { process.kill(-pid, signal); return true; } catch (_) { /* fall through */ }
600
+ }
601
+ try { child.kill(signal); return true; } catch (_) { return false; }
602
+ };
603
+ signalGroup('SIGTERM');
604
+ const escalate = setTimeout(() => { signalGroup('SIGKILL'); }, 1000);
605
+ escalate.unref?.();
606
+ if (typeof child.once === 'function') child.once('exit', () => clearTimeout(escalate));
607
+ return true;
608
+ }
609
+
610
+ // ── Clean terminal text ──────────────────────────────────────────────────
611
+
612
+ function cleanPaneText(pane, since) {
613
+ const start = Math.max(pane.bufferStart, Number(since) || pane.bufferStart);
614
+ const raw = pane.buffer.slice(start - pane.bufferStart);
615
+ // Render at the width the output was produced at where possible; the
616
+ // transcript renderer is what resume already uses for the same reason.
617
+ const text = replayTranscript(raw, Math.max(20, Math.min(400, pane.cols || 120)));
618
+ return {
619
+ text,
620
+ raw,
621
+ mode: 'clean',
622
+ cols: pane.cols,
623
+ bufferStart: pane.bufferStart,
624
+ offset: pane.totalOffset,
625
+ // The ring buffer is bounded; when the requested position predates what
626
+ // is still held, say so rather than quietly returning less.
627
+ truncated: Number(since) > 0 && Number(since) < pane.bufferStart,
628
+ evicted: pane.bufferStart
629
+ };
630
+ }
631
+
632
+ app.get('/api/panes/bootstrap', route(async (req, res) => {
633
+ if (req.get('Authorization')) throw Object.assign(new Error('Agent tokens cannot bootstrap the owner workspace.'), { status: 403 });
634
+ if (!req.isOwner) throw Object.assign(new Error('Owner page required.'), { status: 403 });
635
+ const site = req.get('Sec-Fetch-Site');
636
+ if (site && site !== 'same-origin' && site !== 'none') throw Object.assign(new Error('Owner page required.'), { status: 403 });
637
+ await ensureInitial();
638
+ res.json({ token, state: state(), api: apiUrl });
639
+ }));
640
+ app.get('/api/panes/state', auth, route(async (req, res) => { await ensureInitial(); res.json(state()); }));
641
+
642
+ // The instruction sheet an agent gets when it connects. It describes the
643
+ // tools and this connection's permissions; it never enlarges them.
644
+ app.get('/api/panes/guide', auth, route(async (req, res) => {
645
+ const cli = {
646
+ available: fs.existsSync(cliPath),
647
+ path: cliPath,
648
+ env: {
649
+ api: 'TOWNMOUSE_API',
650
+ token: 'TOWNMOUSE_TOKEN',
651
+ tab: 'TOWNMOUSE_TAB_ID',
652
+ pane: 'TOWNMOUSE_PANE_ID'
653
+ }
654
+ };
655
+ res.json(buildGuide({ cli }));
656
+ }));
657
+ app.post('/api/panes/tabs', auth, route(async (req, res) => {
658
+ await ensureInitial();
659
+ const createdBy = req.body.createdBy === 'agent' ? 'agent' : 'human';
660
+ const tab = createTab(typeof req.body.title === 'string' ? req.body.title.slice(0, 80) : '', createdBy);
661
+ const activate = req.body.activate === true || (createdBy === 'human' && req.body.activate !== false);
662
+ if (activate) {
663
+ activeTabId = tab.id;
664
+ activePaneId = tab.panes[0]?.id || null;
665
+ scheduleSave();
666
+ }
667
+ res.json(serializeTab(tab));
668
+ }));
669
+ app.delete('/api/panes/tabs/:id', auth, route(async (req, res) => {
670
+ const tab = tabs.get(req.params.id);
671
+ if (!tab) { res.status(404).json({ error: 'Workspace tab not found.' }); return; }
672
+ for (const pane of [...tab.panes]) closePane(pane);
673
+ tabs.delete(tab.id);
674
+ if (activeTabId === tab.id) {
675
+ const next = [...tabs.values()][0];
676
+ activeTabId = next ? next.id : null;
677
+ activePaneId = next?.panes[0]?.id || null;
678
+ }
679
+ scheduleSave();
680
+ res.json({ closed: true, state: state() });
681
+ }));
682
+ app.post('/api/panes/tabs/:id/panes', auth, route(async (req, res) => {
683
+ await ensureInitial();
684
+ const pane = await createPane(req.params.id, req.body.kind, {
685
+ url: req.body.url, cwd: req.body.cwd, title: req.body.title,
686
+ cols: req.body.cols, rows: req.body.rows, start: req.body.start,
687
+ createdBy: req.body.createdBy
688
+ });
689
+ res.json(serializePane(pane));
690
+ }));
691
+ app.post('/api/panes/panes/:id/status', auth, route(async (req, res) => {
692
+ const pane = panes.get(req.params.id);
693
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
694
+ const state = String(req.body.state || '').toLowerCase();
695
+ if (!['working', 'blocked', 'idle', 'done', 'unknown'].includes(state)) {
696
+ res.status(400).json({ error: 'State must be working, blocked, idle, done, or unknown.' });
697
+ return;
698
+ }
699
+ pane.agentState = state === 'unknown' ? null : state;
700
+ pane.agentMessage = String(req.body.message || '').slice(0, 1000);
701
+ pane.agentStateAt = Date.now();
702
+ scheduleSave();
703
+ res.json(serializePane(pane));
704
+ }));
705
+ app.post('/api/panes/panes/:id/start', auth, route(async (req, res) => {
706
+ const pane = panes.get(req.params.id);
707
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
708
+ if (pane.exited) { res.status(409).json({ error: 'Terminal pane has exited.' }); return; }
709
+ if (!pane.pty) {
710
+ pane.cols = clampCols(req.body.cols);
711
+ pane.rows = clampRows(req.body.rows);
712
+ startPanePty(pane);
713
+ scheduleSave();
714
+ }
715
+ res.json(serializePane(pane));
716
+ }));
717
+ app.post('/api/panes/tabs/:id/reorder', auth, route(async (req, res) => {
718
+ const tab = tabs.get(req.params.id);
719
+ if (!tab) { res.status(404).json({ error: 'Workspace tab not found.' }); return; }
720
+ const from = tab.panes.findIndex((pane) => pane.id === req.body.paneId);
721
+ if (from < 0) { res.status(404).json({ error: 'Pane not found in this tab.' }); return; }
722
+ const to = Math.max(0, Math.min(tab.panes.length - 1, Math.round(Number(req.body.index))));
723
+ if (!Number.isFinite(to) || to === from) { res.json(state()); return; }
724
+ const [pane] = tab.panes.splice(from, 1);
725
+ tab.panes.splice(to, 0, pane);
726
+ scheduleSave();
727
+ res.json(state());
728
+ }));
729
+ app.delete('/api/panes/panes/:id', auth, route(async (req, res) => {
730
+ const pane = panes.get(req.params.id);
731
+ if (!pane) { res.status(404).json({ error: 'Pane not found.' }); return; }
732
+ closePane(pane);
733
+ res.json({ closed: true, state: state() });
734
+ }));
735
+ app.post('/api/panes/active', auth, route(async (req, res) => {
736
+ if (req.body.tabId && tabs.has(req.body.tabId)) activeTabId = req.body.tabId;
737
+ if (req.body.paneId && panes.has(req.body.paneId)) activePaneId = req.body.paneId;
738
+ scheduleSave();
739
+ res.json(state());
740
+ }));
741
+ app.post('/api/panes/panes/:id/url', auth, route(async (req, res) => {
742
+ const pane = panes.get(req.params.id);
743
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
744
+ const browser = await browserWorkspace.navigate(pane.browserId, req.body.url);
745
+ pane.url = browser.url;
746
+ if (!pane.titleLocked) pane.title = browser.title || pane.title;
747
+ scheduleSave();
748
+ res.json(serializePane(pane));
749
+ }));
750
+ app.post('/api/panes/panes/:id/browser/action', auth, route(async (req, res) => {
751
+ const pane = panes.get(req.params.id);
752
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
753
+ const outcome = await browserWorkspace.action(pane.browserId, req.body.action, req.body);
754
+ pane.url = outcome.url;
755
+ if (!pane.titleLocked) pane.title = outcome.title || pane.title;
756
+ if (!['click', 'type', 'key', 'scroll', 'select', 'setValue', 'selectAt', 'setValueAt', 'hover', 'drag'].includes(req.body.action)) scheduleSave();
757
+ // The action result is nested so it cannot be mistaken for the pane's
758
+ // program status; those are three different meanings of "status".
759
+ res.status(outcome.httpStatus || 200).json({
760
+ ...serializePane(pane),
761
+ // Flat `control` stays for the human viewer's picker overlay.
762
+ control: outcome.control || null,
763
+ action: {
764
+ ok: outcome.ok,
765
+ status: outcome.status,
766
+ message: outcome.message || null,
767
+ warning: outcome.warning || null,
768
+ target: outcome.target || null,
769
+ control: outcome.control || null,
770
+ observationId: outcome.observationId || null
771
+ }
772
+ });
773
+ }));
774
+ app.post('/api/panes/panes/:id/browser/reopen', auth, route(async (req, res) => {
775
+ const pane = panes.get(req.params.id);
776
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
777
+ const previous = pane.browserId;
778
+ const browser = await browserWorkspace.create('agent', req.body.url);
779
+ pane.browserId = browser.id;
780
+ pane.url = browser.url && browser.url !== 'about:blank' ? browser.url : 'about:blank';
781
+ if (!pane.titleLocked) pane.title = browser.title || 'Browser';
782
+ if (previous) await browserWorkspace.close(previous).catch(() => {});
783
+ scheduleSave();
784
+ res.json(serializePane(pane));
785
+ }));
786
+ app.post('/api/panes/panes/:id/browser/dialog', auth, route(async (req, res) => {
787
+ const pane = panes.get(req.params.id);
788
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
789
+ const browser = await browserWorkspace.respondDialog(pane.browserId, req.body.action, req.body.text);
790
+ res.json(browser);
791
+ }));
792
+ app.get('/api/panes/panes/:id/browser/snapshot', auth, route(async (req, res) => {
793
+ const pane = panes.get(req.params.id);
794
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
795
+ const snap = await browserWorkspace.snapshot(pane.browserId);
796
+ pane.url = snap.url;
797
+ if (!pane.titleLocked) pane.title = snap.title || pane.title;
798
+ res.json(snap);
799
+ }));
800
+ app.get('/api/panes/panes/:id/browser/observe', auth, route(async (req, res) => {
801
+ const pane = panes.get(req.params.id);
802
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
803
+ const observed = await browserWorkspace.observe(pane.browserId, {
804
+ elements: req.query.elements === '1' || req.query.elements === 'true',
805
+ max: req.query.max
806
+ });
807
+ pane.url = observed.url;
808
+ if (!pane.titleLocked) pane.title = observed.title || pane.title;
809
+ res.json(observed);
810
+ }));
811
+ app.get('/api/panes/panes/:id/browser/elements', auth, route(async (req, res) => {
812
+ const pane = panes.get(req.params.id);
813
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
814
+ const catalogued = await browserWorkspace.elements(pane.browserId, { max: req.query.max });
815
+ pane.url = catalogued.url;
816
+ if (!pane.titleLocked) pane.title = catalogued.title || pane.title;
817
+ res.json(catalogued);
818
+ }));
819
+ app.post('/api/panes/panes/:id/browser/wait', auth, route(async (req, res) => {
820
+ const pane = panes.get(req.params.id);
821
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
822
+ res.json(await browserWorkspace.wait(pane.browserId, req.body || {}));
823
+ }));
824
+ app.post('/api/panes/panes/:id/browser/sizing', auth, route(async (req, res) => {
825
+ const pane = panes.get(req.params.id);
826
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
827
+ const size = await browserWorkspace.sizing(pane.browserId, req.body.mode, req.body);
828
+ res.json(size);
829
+ }));
830
+ app.get('/api/panes/panes/:id/browser/content', auth, route(async (req, res) => {
831
+ const pane = panes.get(req.params.id);
832
+ if (!pane || pane.kind !== 'browser') { res.status(400).json({ error: 'Browser pane required.' }); return; }
833
+ const browser = browserWorkspace.get(pane.browserId);
834
+ if (!browser) { res.status(404).json({ error: 'Browser pane no longer exists.' }); return; }
835
+ const info = await browserWorkspace.content(pane.browserId, { limit: req.query.limit });
836
+ res.json({
837
+ url: info.url,
838
+ title: info.title || browser.title || pane.title,
839
+ text: info.text,
840
+ totalLength: info.totalLength,
841
+ truncated: info.truncated,
842
+ frameCount: info.frameCount,
843
+ frames: info.frames
844
+ });
845
+ }));
846
+ app.get('/api/panes/panes/:id/stream', auth, (req, res) => {
847
+ const pane = panes.get(req.params.id);
848
+ if (!pane || pane.kind !== 'terminal') {
849
+ res.status(400).json({ error: 'Terminal pane required.' });
850
+ return;
851
+ }
852
+ if (activeStreams >= MAX_ACTIVE_STREAMS) {
853
+ res.status(429).json({ error: 'Terminal stream capacity reached; polling this pane.' });
854
+ return;
855
+ }
856
+ activeStreams++;
857
+ let ping = null;
858
+ let closed = false;
859
+ const end = () => {
860
+ if (closed) return;
861
+ closed = true;
862
+ if (ping) clearInterval(ping);
863
+ pane.streams.delete(res);
864
+ activeStreams = Math.max(0, activeStreams - 1);
865
+ };
866
+ // Register cleanup before the first write so a client that vanishes during
867
+ // the handshake cannot leak a stream slot forever.
868
+ req.on('close', end);
869
+ res.on('close', end);
870
+ res.writeHead(200, {
871
+ 'Content-Type': 'text/event-stream',
872
+ 'Cache-Control': 'no-store',
873
+ Connection: 'keep-alive',
874
+ 'X-Accel-Buffering': 'no'
875
+ });
876
+ let since = Math.max(0, Number(req.query.since) || 0);
877
+ if (since < pane.bufferStart) since = pane.bufferStart;
878
+ sendStreamEvent(res, `data: ${JSON.stringify({ data: pane.buffer.slice(since - pane.bufferStart), offset: pane.totalOffset, exited: pane.exited })}\n\n`);
879
+ pane.streams.add(res);
880
+ ping = setInterval(() => {
881
+ if (!res._sseBlocked) {
882
+ try { res.write(': ping\n\n'); } catch (_) { /* client vanished */ }
883
+ }
884
+ }, 15000);
885
+ ping.unref?.();
886
+ });
887
+ app.get('/api/panes/panes/:id/read', auth, route(async (req, res) => {
888
+ const pane = panes.get(req.params.id);
889
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
890
+ let since = Math.max(0, Number(req.query.since) || 0);
891
+ if (since < pane.bufferStart) since = pane.bufferStart;
892
+ res.json({ data: pane.buffer.slice(since - pane.bufferStart), offset: pane.totalOffset, exited: pane.exited });
893
+ }));
894
+ app.post('/api/panes/panes/:id/input', auth, route(async (req, res) => {
895
+ const pane = panes.get(req.params.id);
896
+ if (!pane || pane.kind !== 'terminal' || !pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
897
+ pane.pty.write(String(req.body.data ?? ''));
898
+ res.json({ ok: true });
899
+ }));
900
+ app.post('/api/panes/panes/:id/keys', auth, route(async (req, res) => {
901
+ const pane = panes.get(req.params.id);
902
+ if (!pane || pane.kind !== 'terminal' || !pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
903
+ const keys = Array.isArray(req.body.keys) ? req.body.keys : [req.body.key];
904
+ if (!keys.length || keys.length > 32) { res.status(400).json({ error: 'Send between 1 and 32 keys.' }); return; }
905
+ const sequence = keys.map(keySequence).join('');
906
+ if (sequence.length > 4096) { res.status(400).json({ error: 'Key sequence is too large.' }); return; }
907
+ pane.pty.write(sequence);
908
+ res.json({ ok: true, bytes: sequence.length });
909
+ }));
910
+ app.get('/api/panes/panes/:id/wait', auth, route(async (req, res) => {
911
+ const pane = panes.get(req.params.id);
912
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
913
+ const timeout = Math.max(100, Math.min(120000, Number(req.query.timeout) || 30000));
914
+ const since = req.query.since === undefined ? pane.totalOffset : Math.max(0, Number(req.query.since) || 0);
915
+ const match = typeof req.query.match === 'string' ? req.query.match : '';
916
+ const pattern = typeof req.query.regex === 'string' ? req.query.regex : '';
917
+ const idleMs = Math.max(0, Math.min(120000, Number(req.query.idleMs) || 0));
918
+ const state = typeof req.query.state === 'string' ? req.query.state.toLowerCase() : '';
919
+ if (state && !['working', 'blocked', 'idle', 'done', 'unknown'].includes(state)) {
920
+ res.status(400).json({ error: 'Unknown agent state.' });
921
+ return;
922
+ }
923
+ if (!match && !pattern && !idleMs && !state) {
924
+ res.status(400).json({ error: 'Provide match, regex, idleMs, or state.' });
925
+ return;
926
+ }
927
+ // A client-supplied regex is evaluated in a worker thread so a pattern with
928
+ // catastrophic backtracking can be terminated instead of freezing the
929
+ // event loop every other request shares.
930
+ let matcher = null;
931
+ if (pattern) {
932
+ const created = createPatternMatcher(pattern);
933
+ if (created.error) { res.status(400).json({ error: created.error }); return; }
934
+ matcher = created;
935
+ }
936
+ const started = Date.now();
937
+ let result;
938
+ try {
939
+ result = await new Promise((resolve) => {
940
+ let finished = false;
941
+ const finish = (payload) => {
942
+ if (finished) return;
943
+ finished = true;
944
+ resolve(payload);
945
+ };
946
+ const snapshot = (matched, reason) => {
947
+ const data = pane.buffer.slice(Math.max(0, since - pane.bufferStart));
948
+ finish({
949
+ matched, reason,
950
+ data: data.slice(-100000),
951
+ offset: pane.totalOffset,
952
+ idleMs: Math.max(0, Date.now() - pane.lastOutputAt),
953
+ agentState: pane.agentState,
954
+ agentMessage: pane.agentMessage,
955
+ elapsedMs: Date.now() - started
956
+ });
957
+ };
958
+ res.on('close', () => finish({ aborted: true }));
959
+ const run = async () => {
960
+ while (!finished) {
961
+ const data = pane.buffer.slice(Math.max(0, since - pane.bufferStart));
962
+ if (state && pane.agentState === (state === 'unknown' ? null : state)) return snapshot(true, 'state');
963
+ if (match && data.includes(match)) return snapshot(true, 'match');
964
+ if (matcher) {
965
+ try {
966
+ if (await matcher.test(data)) return snapshot(true, 'match');
967
+ } catch (error) {
968
+ return finish({ error: error.message, status: error.status || 400 });
969
+ }
970
+ }
971
+ if (idleMs && Date.now() - pane.lastOutputAt >= idleMs) return snapshot(true, 'idle');
972
+ if (Date.now() - started >= timeout) return snapshot(false, 'timeout');
973
+ await new Promise((next) => setTimeout(next, 100));
974
+ }
975
+ };
976
+ void run();
977
+ });
978
+ } finally {
979
+ if (matcher) matcher.close();
980
+ }
981
+ if (result && result.error) {
982
+ if (!res.writableEnded) res.status(result.status || 400).json({ error: result.error });
983
+ return;
984
+ }
985
+ if (!res.writableEnded) res.json(result);
986
+ }));
987
+ app.post('/api/panes/panes/:id/resize', auth, route(async (req, res) => {
988
+ const pane = panes.get(req.params.id);
989
+ if (!pane) { res.status(400).json({ error: 'Pane required.' }); return; }
990
+ if (pane.kind === 'browser') {
991
+ const size = await browserWorkspace.setViewport(pane.browserId, req.body.width, req.body.height);
992
+ res.json(size);
993
+ return;
994
+ }
995
+ pane.cols = clampCols(req.body.cols);
996
+ pane.rows = clampRows(req.body.rows);
997
+ if (!pane.pty) {
998
+ // A deferred pane is about to start at these measured dimensions.
999
+ res.json({ cols: pane.cols, rows: pane.rows });
1000
+ return;
1001
+ }
1002
+ pane.pty.resize(pane.cols, pane.rows);
1003
+ res.json({ cols: pane.cols, rows: pane.rows });
1004
+ }));
1005
+ app.get('/api/panes/panes/:id/text', auth, route(async (req, res) => {
1006
+ const pane = panes.get(req.params.id);
1007
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1008
+ const mode = req.query.mode === 'raw' ? 'raw' : 'clean';
1009
+ const since = req.query.since === undefined ? pane.bufferStart : Number(req.query.since);
1010
+ if (mode === 'raw') {
1011
+ const start = Math.max(pane.bufferStart, Number(since) || pane.bufferStart);
1012
+ res.json({
1013
+ mode: 'raw',
1014
+ text: pane.buffer.slice(start - pane.bufferStart),
1015
+ offset: pane.totalOffset,
1016
+ bufferStart: pane.bufferStart,
1017
+ truncated: Number(since) > 0 && Number(since) < pane.bufferStart
1018
+ });
1019
+ return;
1020
+ }
1021
+ const clean = cleanPaneText(pane, since);
1022
+ res.json({
1023
+ mode: 'clean',
1024
+ text: clean.text,
1025
+ cols: clean.cols,
1026
+ offset: clean.offset,
1027
+ bufferStart: clean.bufferStart,
1028
+ truncated: clean.truncated
1029
+ });
1030
+ }));
1031
+
1032
+ app.post('/api/panes/panes/:id/jobs', auth, route(async (req, res) => {
1033
+ const pane = panes.get(req.params.id);
1034
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1035
+ const command = String(req.body.command || '').replace(/\r?\n$/, '');
1036
+ if (!command.trim()) { res.status(400).json({ error: 'command must not be empty.' }); return; }
1037
+ if (command.length > 10000) { res.status(400).json({ error: 'command is too long.' }); return; }
1038
+ const job = startJob(pane, command);
1039
+ const wait = req.body.wait !== false;
1040
+ if (wait) await waitForJob(job, req.body.timeoutMs);
1041
+ scheduleSave();
1042
+ res.status(202).json(serializeJob(job));
1043
+ }));
1044
+
1045
+ app.get('/api/panes/panes/:id/jobs/:jobId', auth, route(async (req, res) => {
1046
+ const pane = panes.get(req.params.id);
1047
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1048
+ const job = pane.jobs.find((candidate) => candidate.id === req.params.jobId);
1049
+ if (!job) { res.status(404).json({ error: 'Job not found.' }); return; }
1050
+ res.json(serializeJob(job));
1051
+ }));
1052
+
1053
+ app.delete('/api/panes/panes/:id/jobs/:jobId', auth, route(async (req, res) => {
1054
+ const pane = panes.get(req.params.id);
1055
+ if (!pane || pane.kind !== 'terminal') { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1056
+ const job = pane.jobs.find((candidate) => candidate.id === req.params.jobId);
1057
+ if (!job) { res.status(404).json({ error: 'Job not found.' }); return; }
1058
+ const cancelled = cancelJob(job);
1059
+ res.json({ cancelled, job: serializeJob(job) });
1060
+ }));
1061
+
1062
+ app.post('/api/panes/panes/:id/command', auth, route(async (req, res) => {
1063
+ const pane = panes.get(req.params.id);
1064
+ if (!pane || pane.kind !== 'terminal' || !pane.pty) { res.status(400).json({ error: 'Terminal pane required.' }); return; }
1065
+ const command = String(req.body.command || '').replace(/\r?\n$/, '');
1066
+ pane.pty.write(command + '\n');
1067
+ await new Promise((resolve) => setTimeout(resolve, Number(req.body.waitMs) || 300));
1068
+ // This proves the line was written and shows recent output. It does not
1069
+ // prove the command finished; use POST /jobs for that.
1070
+ res.json({
1071
+ ok: true,
1072
+ confirmed: false,
1073
+ note: 'The line was typed into the interactive terminal. For a tracked completion and exit code, use POST /api/panes/panes/<id>/jobs.',
1074
+ output: pane.buffer.slice(-4000),
1075
+ offset: pane.totalOffset
1076
+ });
1077
+ }));
1078
+
1079
+ async function closeAll() {
1080
+ // Stop new debounced writes before the final snapshot. saveState itself
1081
+ // does not schedule, so the explicit save below still lands.
1082
+ shuttingDown = true;
1083
+ if (saveTimer) { clearTimeout(saveTimer); saveTimer = null; }
1084
+ if (restored) await saveState().catch(() => { /* best effort on shutdown */ });
1085
+ for (const pane of [...panes.values()]) {
1086
+ for (const job of pane.jobs || []) cancelJob(job);
1087
+ killPty(pane);
1088
+ if (pane.kind === 'browser' && pane.browserId) {
1089
+ await browserWorkspace.close(pane.browserId).catch(() => {});
1090
+ }
1091
+ }
1092
+ panes.clear();
1093
+ tabs.clear();
1094
+ }
1095
+
1096
+ return { closeAll, state };
1097
+ }
1098
+
1099
+ module.exports = { installWorkspacePanes };