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
@@ -0,0 +1,1733 @@
1
+ 'use strict';
2
+ const crypto = require('crypto');
3
+ const puppeteer = require('puppeteer');
4
+ const dom = require('./browser-dom');
5
+ const { resolveChrome, missingBrowserMessage } = require('./chrome-resolve');
6
+ const { ownerPageRefusal } = require('./owner-page');
7
+
8
+ // How many past observations a session keeps. Enough for an agent to compare a
9
+ // few steps back; bounded so a long session cannot grow without limit.
10
+ const MAX_OBSERVATIONS = 20;
11
+ // Ref records are cheap but should not accumulate forever across navigations.
12
+ const MAX_REF_RECORDS = 4000;
13
+ const MAX_ACTION_TEXT = 10000;
14
+
15
+ // ── Pictures for someone watching a page ────────────────────────────────────
16
+ //
17
+ // The numbers come from measuring this Chrome on a desktop-class machine: one
18
+ // 1280x800 picture of a page with real content costs about 0.6 ms of Chrome's
19
+ // time to encode, and a picture asked for one by one (Page.captureScreenshot)
20
+ // takes 65 to 85 ms, so twelve to fifteen a second at the very most. Chrome
21
+ // pushing its own pictures (Page.startScreencast) reaches 60 a second if
22
+ // unheld, so the pace is set here rather than left to Chrome.
23
+ const PICTURE_QUALITY = 75;
24
+ const PICTURE_PERIOD_MS = 1000 / 30; // one pane: thirty pictures a second
25
+ const ALL_PICTURES_PERIOD_MS = 1000 / 48; // every pane together: forty-eight
26
+ // Right after an action on the page the next picture is not held back, so the
27
+ // person sees what they did at once. This is the closest two of those may be.
28
+ const HURRY_PERIOD_MS = 1000 / 60;
29
+ // A viewer renews this with every request. When it runs out, nobody is looking
30
+ // and the screencast stops, whether or not the viewer said goodbye.
31
+ const VIEW_LEASE_MS = 1500;
32
+ // Viewer requests waiting for a picture hold a connection each. The same count
33
+ // terminal streams allow, so two of a browser's six stay free for input.
34
+ const WAITING_VIEWERS_MAX = 4;
35
+ const PICTURE_WAIT_MAX_MS = 2000;
36
+ // A screencast that has sent nothing by then is treated as not working, and
37
+ // pictures are taken one by one instead until it is tried again. A stream
38
+ // cannot start while its page is still opening, which is exactly when a new
39
+ // pane gets its first look, so the retry is quick.
40
+ const CAST_GRACE_MS = 600;
41
+ const CAST_RETRY_MS = 500;
42
+ // What Chrome answers a page command with while the page is still opening.
43
+ const OPENING_PAGE = /Not attached to an active page/;
44
+ const OPENING_PAGE_RETRY_MS = 50;
45
+ const OPENING_PAGE_WAIT_MS = 2000;
46
+ // With no usable picture in hand (a first look, just after a resize), this is
47
+ // how long Chrome's own next picture is given before one is taken instead. It
48
+ // normally comes within 30 ms; a capture takes 65 to 85.
49
+ const PICTURE_GRACE_MS = 300;
50
+ // Title and history are read from the page at most this often for a viewer.
51
+ const METADATA_PERIOD_MS = 1000;
52
+
53
+ // The pixel size of a JPEG, read from its own header. A picture is labelled
54
+ // with this and never with what the viewport is believed to be at the time.
55
+ function jpegSize(buffer) {
56
+ let offset = 2;
57
+ while (offset + 9 < buffer.length) {
58
+ if (buffer[offset] !== 0xff) { offset += 1; continue; }
59
+ const marker = buffer[offset + 1];
60
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
61
+ return { height: buffer.readUInt16BE(offset + 5), width: buffer.readUInt16BE(offset + 7) };
62
+ }
63
+ offset += 2 + buffer.readUInt16BE(offset + 2);
64
+ }
65
+ return null;
66
+ }
67
+
68
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
69
+
70
+ // A page read that must not hold a response: the page may be mid-navigation.
71
+ async function promptly(promise, ms, fallback) {
72
+ return Promise.race([promise, sleep(ms).then(() => fallback)]);
73
+ }
74
+
75
+ // Action result statuses. These distinguish "the instruction was received" from
76
+ // "the instruction happened", which is the point of the assessment.
77
+ const STATUS = {
78
+ completed: 'completed',
79
+ missing: 'missing',
80
+ wrongKind: 'wrong-kind',
81
+ failed: 'failed',
82
+ stale: 'stale',
83
+ unconfirmed: 'unconfirmed'
84
+ };
85
+
86
+ const STATUS_HTTP = {
87
+ completed: 200,
88
+ missing: 404,
89
+ 'wrong-kind': 400,
90
+ failed: 500,
91
+ stale: 409,
92
+ unconfirmed: 200
93
+ };
94
+
95
+ function installBrowserWorkspace(app) {
96
+ const humanKey = crypto.randomBytes(32).toString('hex');
97
+ const MAX_BROWSER_TABS = 32;
98
+ const sessions = new Map();
99
+ let browserPromise;
100
+ let opening = 0;
101
+ let observationCounter = 0;
102
+ // Shared by every pane: when the last picture of any pane was due, and how
103
+ // many viewer requests are holding a connection while they wait.
104
+ let lastPictureAt = 0;
105
+ let waitingViewers = 0;
106
+
107
+ const resolveEngine = () => resolveChrome();
108
+ const engineStatus = () => {
109
+ const chrome = resolveEngine();
110
+ return chrome
111
+ ? { engine: 'ready', path: chrome.path, source: chrome.source }
112
+ : { engine: 'missing', path: null, source: null };
113
+ };
114
+
115
+ const engine = () => {
116
+ if (!browserPromise) {
117
+ // Keep Chromium's renderer sandbox by default. Containers and CI runners
118
+ // without user namespaces need an explicit opt-out; it is never implied
119
+ // by running with elevated privileges or by opening an untrusted page.
120
+ const unsandboxed = process.env.CI === 'true' || process.env.TOWNMOUSE_CHROMIUM_NO_SANDBOX === '1';
121
+ // A packaged install may have neither Puppeteer's download (npm 12 skips
122
+ // install scripts) nor a configured path; find an existing browser first.
123
+ const chrome = resolveEngine();
124
+ browserPromise = puppeteer.launch({
125
+ headless: true,
126
+ args: [
127
+ ...(unsandboxed ? ['--no-sandbox', '--disable-setuid-sandbox'] : []),
128
+ '--disable-dev-shm-usage', '--disable-gpu', '--disable-background-timer-throttling',
129
+ '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'
130
+ ],
131
+ ...(chrome ? { executablePath: chrome.path } : {})
132
+ }).then((browser) => {
133
+ browser.on('disconnected', () => {
134
+ browserPromise = null;
135
+ // Every session belonged to the dead browser. Clearing the map lets
136
+ // the UI reconcile instead of offering unclosable ghost tabs.
137
+ for (const s of sessions.values()) settlePictures(s);
138
+ sessions.clear();
139
+ });
140
+ return browser;
141
+ }).catch((error) => {
142
+ browserPromise = null;
143
+ if (!chrome) throw new Error(`${missingBrowserMessage()}\n\n${error.message}`);
144
+ throw error;
145
+ });
146
+ }
147
+ return browserPromise;
148
+ };
149
+
150
+ const human = (req) => req.get('X-Workspace-Key') === humanKey;
151
+
152
+ // No password value ever leaves the server. The page reports what it holds
153
+ // about a control (its value and its type), and this is the one place that
154
+ // decides what may go on: a password field's value is dropped and the field
155
+ // is marked redacted, as the catalog already does inside the page. Every
156
+ // path a control description takes into a result passes through here, so a
157
+ // new action or route cannot forget. Typing into the field is untouched:
158
+ // only what comes back is masked.
159
+ function redactControl(control) {
160
+ if (!control || typeof control !== 'object') return control;
161
+ const type = String(control.type ?? control.kind ?? '').toLowerCase();
162
+ if (type !== 'password') return control;
163
+ return { ...control, value: null, redacted: true };
164
+ }
165
+
166
+ const describe = (s) => ({
167
+ id: s.id,
168
+ kind: s.kind,
169
+ permission: s.permission,
170
+ url: s.page.url(),
171
+ title: s.title || 'New tab',
172
+ dialog: s.dialog || null,
173
+ sizing: s.sizing,
174
+ viewport: { width: s.width, height: s.height }
175
+ });
176
+
177
+ // Screenshot capture and viewport changes share one page. Serialize them or
178
+ // a resize can land mid-capture and label an old-size image with new
179
+ // dimensions, which makes pane click mapping land in the wrong place.
180
+ const enqueue = (s, task) => {
181
+ const work = (s.queue || Promise.resolve()).then(task, task);
182
+ s.queue = work.catch(() => {});
183
+ return work;
184
+ };
185
+
186
+ // Work that touches the page is serialized by the operation itself (each
187
+ // `…Tab` function calls `enqueue`). The route wrapper must not enqueue again:
188
+ // nesting the same queue would make the inner task wait for the outer one.
189
+ const route = (fn) => async (req, res) => {
190
+ res.set('Cache-Control', 'no-store');
191
+ try {
192
+ await fn(req, res);
193
+ } catch (error) {
194
+ const body = error.body || { error: error.message };
195
+ res.status(error.status || 400).json(body);
196
+ }
197
+ };
198
+
199
+ function deny(message, status = 403, body) {
200
+ throw Object.assign(new Error(message), { status, body });
201
+ }
202
+
203
+ function session(req, control = false) {
204
+ const s = sessions.get(req.params.id);
205
+ if (!s) deny('Browser tab no longer exists.', 404);
206
+ if (s.internal) deny('This browser belongs to a pane workspace.', 403);
207
+ if (!human(req)) {
208
+ if (req.get('Authorization') !== 'Bearer ' + s.token) deny('Browser access token required.');
209
+ if (s.permission === 'private' || (control && s.permission !== 'control')) deny('The owner has not granted this browser permission.');
210
+ }
211
+ return s;
212
+ }
213
+
214
+ function address(value) {
215
+ const u = new URL(value);
216
+ if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) {
217
+ deny('Use an HTTP or HTTPS address without embedded credentials.', 400);
218
+ }
219
+ return u.href;
220
+ }
221
+
222
+ // A popup can fire before its main frame exists; calling popup.url() then
223
+ // throws asynchronously and used to take the whole server down. Never let
224
+ // popup bookkeeping escape the emitter.
225
+ function followPopup(popup, page) {
226
+ void (async () => {
227
+ try {
228
+ await Promise.resolve();
229
+ let popupUrl = '';
230
+ try { popupUrl = popup.url(); } catch (_) { popupUrl = ''; }
231
+ if (!popupUrl || popupUrl === 'about:blank') {
232
+ // window.open('', name) starts blank and is navigated by script a
233
+ // moment later. Wait for the real address before deciding.
234
+ popupUrl = await new Promise((resolve) => {
235
+ const timer = setTimeout(() => {
236
+ try { resolve(popup.url()); } catch (_) { resolve(''); }
237
+ }, 2500);
238
+ const check = () => {
239
+ let candidate = '';
240
+ try { candidate = popup.url(); } catch (_) { /* frame not ready */ }
241
+ if (candidate && candidate !== 'about:blank') {
242
+ clearTimeout(timer);
243
+ resolve(candidate);
244
+ }
245
+ };
246
+ popup.on('framenavigated', check);
247
+ popup.on('load', check);
248
+ popup.once('close', () => { clearTimeout(timer); resolve(''); });
249
+ });
250
+ }
251
+ await popup.close().catch(() => {});
252
+ if (popupUrl && popupUrl !== 'about:blank' && /^https?:/i.test(popupUrl)) {
253
+ await page.goto(address(popupUrl)).catch(() => {});
254
+ }
255
+ } catch (_) {
256
+ try { await popup.close(); } catch (_) { /* already gone */ }
257
+ }
258
+ })();
259
+ }
260
+
261
+ // A JS dialog blocks the page until answered. Keep it open long enough for
262
+ // the human or agent to answer through the UI/API, then dismiss so a forgotten
263
+ // tab cannot stay wedged forever. Never dismiss silently at t=0.
264
+ function attachDialog(s) {
265
+ s.page.on('dialog', (dialog) => {
266
+ clearTimeout(s.dialogTimer);
267
+ s.dialog = {
268
+ id: crypto.randomUUID(),
269
+ type: dialog.type(),
270
+ message: dialog.message(),
271
+ defaultValue: typeof dialog.defaultValue === 'function' ? dialog.defaultValue() : '',
272
+ at: new Date().toISOString()
273
+ };
274
+ s.pendingDialog = dialog;
275
+ s.dialogTimer = setTimeout(async () => {
276
+ if (s.pendingDialog !== dialog) return;
277
+ s.pendingDialog = null;
278
+ s.lastDialog = { ...s.dialog, timedOut: true };
279
+ s.dialog = null;
280
+ try { await dialog.dismiss(); } catch (_) { /* page or dialog already gone */ }
281
+ }, 30000);
282
+ s.dialogTimer.unref?.();
283
+ });
284
+ }
285
+
286
+ async function respondDialog(id, action, text) {
287
+ const s = sessions.get(id);
288
+ if (!s) deny('Browser pane no longer exists.', 404);
289
+ if (!['accept', 'dismiss'].includes(action)) deny('Dialog action must be accept or dismiss.', 400);
290
+ const dialog = s.pendingDialog;
291
+ if (!dialog) deny('No page dialog is waiting for an answer.', 409);
292
+ clearTimeout(s.dialogTimer);
293
+ s.dialogTimer = null;
294
+ s.lastDialog = { ...s.dialog, answered: action, answeredAt: new Date().toISOString() };
295
+ s.pendingDialog = null;
296
+ s.dialog = null;
297
+ try {
298
+ if (action === 'accept') await dialog.accept(typeof text === 'string' ? text : undefined);
299
+ else await dialog.dismiss();
300
+ } catch (error) {
301
+ deny(`The page dialog could not be answered: ${error.message}`, 409);
302
+ }
303
+ // The page can draw again from here on; a viewer should see it at once.
304
+ hurryCast(s);
305
+ return describe(s);
306
+ }
307
+
308
+ // ── Observation bookkeeping ───────────────────────────────────────────────
309
+
310
+ function currentPage(s) {
311
+ return {
312
+ width: s.width,
313
+ height: s.height,
314
+ url: (() => { try { return s.page.url(); } catch (_) { return ''; } })(),
315
+ title: s.title || ''
316
+ };
317
+ }
318
+
319
+ function recordObservation(s, extra = {}) {
320
+ observationCounter += 1;
321
+ const observation = {
322
+ id: observationCounter,
323
+ capturedAt: new Date().toISOString(),
324
+ width: s.width,
325
+ height: s.height,
326
+ scrollX: 0,
327
+ scrollY: 0,
328
+ url: (() => { try { return s.page.url(); } catch (_) { return ''; } })(),
329
+ title: s.title || '',
330
+ revision: s.revision,
331
+ layoutHash: '',
332
+ ...extra
333
+ };
334
+ s.observations.set(observation.id, observation);
335
+ s.observationOrder.push(observation.id);
336
+ while (s.observationOrder.length > MAX_OBSERVATIONS) {
337
+ const evicted = s.observationOrder.shift();
338
+ s.observations.delete(evicted);
339
+ }
340
+ s.lastObservationId = observation.id;
341
+ return observation;
342
+ }
343
+
344
+ function rememberRef(s, descriptor, observationId) {
345
+ s.refRecords.set(descriptor.ref, {
346
+ observationId,
347
+ role: descriptor.role,
348
+ name: descriptor.name,
349
+ tag: descriptor.tag,
350
+ frame: descriptor.frame,
351
+ seenAt: Date.now()
352
+ });
353
+ while (s.refRecords.size > MAX_REF_RECORDS) {
354
+ const oldest = s.refRecords.keys().next();
355
+ if (oldest.done) break;
356
+ s.refRecords.delete(oldest.value);
357
+ }
358
+ }
359
+
360
+ // ── Action helpers ────────────────────────────────────────────────────────
361
+
362
+ function result(status, extra = {}) {
363
+ return {
364
+ ok: status !== STATUS.stale && status !== STATUS.missing && status !== STATUS.failed && status !== STATUS.wrongKind,
365
+ status,
366
+ httpStatus: STATUS_HTTP[status] || 200,
367
+ ...extra
368
+ };
369
+ }
370
+
371
+ function parseKeyCombo(spec) {
372
+ const raw = String(spec || '').trim();
373
+ if (!raw || raw.length > 60) deny('Invalid key name.', 400);
374
+ const parts = raw.split('+').map((part) => part.trim()).filter(Boolean);
375
+ const keyToken = parts.pop();
376
+ if (!keyToken) deny('Invalid key name.', 400);
377
+ const modifiers = { ctrl: false, alt: false, shift: false, meta: false };
378
+ for (const part of parts) {
379
+ const name = part.toLowerCase();
380
+ if (name === 'ctrl' || name === 'control') modifiers.ctrl = true;
381
+ else if (name === 'alt' || name === 'option') modifiers.alt = true;
382
+ else if (name === 'shift') modifiers.shift = true;
383
+ else if (name === 'meta' || name === 'cmd' || name === 'command' || name === 'super') modifiers.meta = true;
384
+ else deny(`Unknown modifier: ${part}`, 400);
385
+ }
386
+ // Puppeteer accepts single characters as-is and named keys in title case.
387
+ const named = {
388
+ enter: 'Enter', return: 'Enter', esc: 'Escape', escape: 'Escape', tab: 'Tab',
389
+ space: ' ', backspace: 'Backspace', delete: 'Delete', insert: 'Insert',
390
+ up: 'ArrowUp', down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight',
391
+ home: 'Home', end: 'End', pageup: 'PageUp', pagedown: 'PageDown'
392
+ };
393
+ const lower = keyToken.toLowerCase();
394
+ let key = named[lower];
395
+ if (!key) {
396
+ if (keyToken.length === 1) key = keyToken;
397
+ else if (/^f\d{1,2}$/i.test(keyToken)) key = keyToken.toUpperCase();
398
+ else key = keyToken;
399
+ }
400
+ return { key, modifiers };
401
+ }
402
+
403
+ async function pressCombo(page, spec) {
404
+ const { key, modifiers } = parseKeyCombo(spec);
405
+ const down = [];
406
+ if (modifiers.ctrl) down.push('Control');
407
+ if (modifiers.alt) down.push('Alt');
408
+ if (modifiers.shift) down.push('Shift');
409
+ if (modifiers.meta) down.push('Meta');
410
+ for (const modifier of down) await page.keyboard.down(modifier);
411
+ try {
412
+ await page.keyboard.press(key);
413
+ } finally {
414
+ for (const modifier of down.reverse()) await page.keyboard.up(modifier);
415
+ }
416
+ }
417
+
418
+ function point(s, data) {
419
+ const x = Number(data.x);
420
+ const y = Number(data.y);
421
+ if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x > s.width || y > s.height) {
422
+ deny('Invalid pointer position.', 400);
423
+ }
424
+ return { x, y };
425
+ }
426
+
427
+ async function targetFromRef(s, ref) {
428
+ if (!ref || typeof ref !== 'string') deny('A ref is required.', 400);
429
+ const handle = await dom.resolveRef(s.page, ref);
430
+ if (!handle) {
431
+ const record = s.refRecords.get(ref);
432
+ const stale = record && record.observationId !== undefined && !s.observations.has(record.observationId);
433
+ return {
434
+ status: STATUS.missing,
435
+ message: stale || !record
436
+ ? `Element ${ref} is not on the page. Look again with a fresh observation.`
437
+ : `Element ${ref} is no longer present.`
438
+ };
439
+ }
440
+ // Identity check: the marker could survive while the node was replaced by a
441
+ // different control in a re-render.
442
+ let current = null;
443
+ try {
444
+ current = await handle.evaluate((node) => ({
445
+ tag: node.tagName ? node.tagName.toLowerCase() : '',
446
+ role: (node.getAttribute && node.getAttribute('role')) || '',
447
+ name: ((node.getAttribute && (node.getAttribute('aria-label') || node.getAttribute('placeholder'))) || '')
448
+ || (node.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 160),
449
+ box: (() => {
450
+ const rect = node.getBoundingClientRect();
451
+ return { x: Math.round(rect.left), y: Math.round(rect.top), width: Math.round(rect.width), height: Math.round(rect.height) };
452
+ })()
453
+ }));
454
+ } catch (_) { current = null; }
455
+ const record = s.refRecords.get(ref);
456
+ // A surviving marker normally means the same node. The tag check catches a
457
+ // cloned or replaced node that inherited the attribute. The label is not
458
+ // compared: text legitimately changes on the same control ("Save" →
459
+ // "Saved") and that is not a stale target.
460
+ const stale = Boolean(record && current && record.tag && current.tag && record.tag !== current.tag);
461
+ return { status: stale ? STATUS.stale : STATUS.completed, handle, current, record };
462
+ }
463
+
464
+ async function assertFreshObservation(s, observationId) {
465
+ const id = Number(observationId);
466
+ if (!Number.isFinite(id)) deny('observation must be a number.', 400);
467
+ const observation = s.observations.get(id);
468
+ if (!observation) {
469
+ deny('That observation is out of date. Look again before clicking.', 409, {
470
+ ok: false,
471
+ status: STATUS.stale,
472
+ code: 'STALE_OBSERVATION',
473
+ message: `Observation ${id} is no longer held. Take a fresh observation and use its numbers.`,
474
+ latestObservationId: s.lastObservationId || null
475
+ });
476
+ }
477
+ const current = await dom.signature(s.page);
478
+ const changed = observation.revision !== s.revision ||
479
+ observation.layoutHash !== current.hash ||
480
+ Math.abs((observation.scrollX || 0) - current.scrollX) > 2 ||
481
+ Math.abs((observation.scrollY || 0) - current.scrollY) > 2;
482
+ if (changed) {
483
+ deny('That target is out of date. Look again before clicking.', 409, {
484
+ ok: false,
485
+ status: STATUS.stale,
486
+ code: 'STALE_OBSERVATION',
487
+ message: 'The page changed since that observation. Look again before clicking, then use the fresh observation\'s numbers.',
488
+ observationId: id,
489
+ latestObservationId: s.lastObservationId || null
490
+ });
491
+ }
492
+ return observation;
493
+ }
494
+
495
+ // ── Sessions ──────────────────────────────────────────────────────────────
496
+
497
+ function initSession(fields) {
498
+ return {
499
+ observations: new Map(),
500
+ observationOrder: [],
501
+ lastObservationId: null,
502
+ refRecords: new Map(),
503
+ nextRef: 0,
504
+ revision: 0,
505
+ sizing: 'fit',
506
+ fixedWidth: 1280,
507
+ fixedHeight: 800,
508
+ queue: Promise.resolve(),
509
+ // One protocol session for the page, made on first use.
510
+ cdp: null,
511
+ // The newest picture of the page, with the size it really has in pixels.
512
+ frame: null,
513
+ frameSeq: 0,
514
+ // Who is watching: a lease renewed by each viewer request, and Chrome's
515
+ // own picture stream while it holds.
516
+ viewLease: 0,
517
+ viewTimer: null,
518
+ cast: null,
519
+ castFailedAt: 0,
520
+ // Viewer requests waiting for the next picture.
521
+ waiters: new Set(),
522
+ titleAt: 0,
523
+ history: { canGoBack: false, canGoForward: false },
524
+ historyAt: 0,
525
+ ...fields
526
+ };
527
+ }
528
+
529
+ function wireSession(s) {
530
+ attachDialog(s);
531
+ s.page.on('popup', (popup) => followPopup(popup, s.page));
532
+ // Any navigation in any frame invalidates coordinate targets, because the
533
+ // layout is no longer the one that was observed.
534
+ s.page.on('framenavigated', () => { s.revision += 1; });
535
+ }
536
+
537
+ // Internal control surface for the pane workspace. These bypass the human
538
+ // header key because the caller already holds the pane workspace token.
539
+ async function createTab(kind = 'agent', url) {
540
+ if (sessions.size + opening >= MAX_BROWSER_TABS) deny('Close a browser pane before opening another.', 409);
541
+ opening++;
542
+ let context;
543
+ let s;
544
+ try {
545
+ context = await (await engine()).createBrowserContext();
546
+ const page = await context.newPage();
547
+ await page.setViewport({ width: 1280, height: 800 });
548
+ s = initSession({
549
+ id: crypto.randomUUID(),
550
+ token: crypto.randomBytes(32).toString('hex'),
551
+ page,
552
+ context,
553
+ kind,
554
+ width: 1280,
555
+ height: 800,
556
+ permission: kind === 'agent' ? 'control' : 'private',
557
+ internal: true
558
+ });
559
+ wireSession(s);
560
+ // Register before navigation. A page that opens a dialog on load would
561
+ // otherwise block goto while the pane is invisible and impossible to
562
+ // answer; the snapshot route can now return the dialog immediately.
563
+ sessions.set(s.id, s);
564
+ page.once('close', () => sessions.delete(s.id));
565
+ if (url) {
566
+ s.navigation = page.goto(address(url), { waitUntil: 'domcontentloaded', timeout: 30000 })
567
+ .then(() => page.title())
568
+ .then((title) => { s.title = title; })
569
+ .catch(() => { /* the snapshot route reports the failure */ });
570
+ } else {
571
+ s.title = await page.title();
572
+ }
573
+ return describe(s);
574
+ } catch (error) {
575
+ if (s) sessions.delete(s.id);
576
+ if (context) await context.close().catch(() => {});
577
+ throw error;
578
+ } finally {
579
+ opening--;
580
+ }
581
+ }
582
+
583
+ // One protocol session per page for its whole life. It used to be made and
584
+ // detached around every picture, which was pure overhead.
585
+ function cdpSession(s) {
586
+ if (!s.cdp) {
587
+ const pending = s.page.createCDPSession().then((client) => {
588
+ client.on('disconnected', () => {
589
+ if (s.cdp === pending) s.cdp = null;
590
+ if (s.cast && s.cast.client === client) { clearTimeout(s.cast.timer); s.cast = null; }
591
+ });
592
+ return client;
593
+ });
594
+ pending.catch(() => { if (s.cdp === pending) s.cdp = null; });
595
+ s.cdp = pending;
596
+ }
597
+ return s.cdp;
598
+ }
599
+
600
+ async function historyState(s) {
601
+ try {
602
+ const client = await cdpSession(s);
603
+ const history = await client.send('Page.getNavigationHistory', {}, { timeout: 2000 });
604
+ return {
605
+ canGoBack: Number(history.currentIndex) > 0,
606
+ canGoForward: Number(history.currentIndex) < (history.entries || []).length - 1
607
+ };
608
+ } catch (_) {
609
+ return { ...s.history };
610
+ }
611
+ }
612
+
613
+ async function capture(s) {
614
+ const client = await cdpSession(s);
615
+ return client.send('Page.captureScreenshot', { format: 'jpeg', quality: PICTURE_QUALITY, captureBeyondViewport: false }, { timeout: 10000 });
616
+ }
617
+
618
+ async function refreshTitle(s) {
619
+ try { s.title = await promptly(s.page.title(), 1500, s.title); } catch (_) { /* page gone */ }
620
+ }
621
+
622
+ // ── The picture stream for someone watching ───────────────────────────────
623
+ //
624
+ // A person's viewer asks with `watch=1` while its pane is on screen. While
625
+ // such a request has arrived within VIEW_LEASE_MS, Chrome itself sends a
626
+ // picture each time the page repaints (Page.startScreencast): a still page
627
+ // costs nothing, and a changing one is shown as it changes. Agents never
628
+ // send `watch`; an observation is its own capture, when it is asked for.
629
+ //
630
+ // Chrome sends its next picture only once the last one is acknowledged, and
631
+ // an acknowledgement is held to one pane period and one all-panes period. So
632
+ // each pane is capped and all the panes together are capped. Measured: about
633
+ // 1.05 pictures for each acknowledgement once a stream is running. (In its
634
+ // first 150 ms a stream sends five or six pictures before that takes hold,
635
+ // and while an acknowledgement is held Chrome may have two more ready; that
636
+ // is Chrome's own doing, and bounded.) The picture itself is handed over the
637
+ // moment it arrives; only Chrome's leave to make the next one waits.
638
+ //
639
+ // A picture Chrome pushes can have been taken at any moment, including
640
+ // while the viewport is being changed. It is accepted only if its own pixel
641
+ // size is the viewport's, so a picture is never labelled with a size that is
642
+ // not its own and click mapping stays exact. Pictures taken on request still
643
+ // run inside the session queue, as before, and so never meet a resize.
644
+
645
+ const viewLeased = (s) => s.viewLease > Date.now();
646
+
647
+ const wakeViewers = (s) => { for (const waiter of [...s.waiters]) waiter.wake(); };
648
+
649
+ async function startCast(s) {
650
+ if (Date.now() - s.castFailedAt < CAST_RETRY_MS) return;
651
+ const client = await cdpSession(s);
652
+ if (s.cast || !viewLeased(s)) return;
653
+ const cast = { client, listener: null, timer: null, held: null, slot: 0, acked: 0, healthy: false, startedAt: Date.now() };
654
+ cast.listener = (event) => onCastFrame(s, cast, event);
655
+ s.cast = cast;
656
+ client.on('Page.screencastFrame', cast.listener);
657
+ try {
658
+ await client.send('Page.startScreencast', { format: 'jpeg', quality: PICTURE_QUALITY });
659
+ } catch (error) {
660
+ if (s.cast === cast) s.cast = null;
661
+ await detachCast(cast);
662
+ s.castFailedAt = Date.now();
663
+ throw error;
664
+ }
665
+ }
666
+
667
+ async function detachCast(cast) {
668
+ clearTimeout(cast.timer);
669
+ cast.client.off('Page.screencastFrame', cast.listener);
670
+ await cast.client.send('Page.stopScreencast').catch(() => {});
671
+ }
672
+
673
+ async function stopCast(s) {
674
+ const cast = s.cast;
675
+ s.cast = null;
676
+ if (cast) await detachCast(cast);
677
+ }
678
+
679
+ function onCastFrame(s, cast, event) {
680
+ if (s.cast !== cast) return;
681
+ const now = performance.now();
682
+ const acknowledge = () => {
683
+ if (s.cast !== cast) return;
684
+ cast.acked = performance.now();
685
+ cast.client.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch(() => {});
686
+ };
687
+ cast.healthy = true;
688
+ const size = jpegSize(Buffer.from(event.data, 'base64'));
689
+ if (!size || size.width !== s.width || size.height !== s.height) {
690
+ // Taken while the viewport was changing: not a picture of the page as it is.
691
+ acknowledge();
692
+ return;
693
+ }
694
+ // When Chrome may send its next picture. The pace applies to every picture
695
+ // it sends, whether or not this one is kept.
696
+ cast.slot = Math.max(now, cast.slot + PICTURE_PERIOD_MS, lastPictureAt + ALL_PICTURES_PERIOD_MS);
697
+ lastPictureAt = cast.slot;
698
+ if (cast.slot > now) {
699
+ cast.held = acknowledge;
700
+ cast.timer = setTimeout(() => { cast.timer = null; cast.held = null; acknowledge(); }, cast.slot - now);
701
+ } else {
702
+ acknowledge();
703
+ }
704
+ // The same picture as the one held (the stream's first, right after one
705
+ // was taken for a first look): nothing changed, and nothing is sent.
706
+ if (s.frame && s.frame.data === event.data) return;
707
+ s.frameSeq += 1;
708
+ s.frame = { seq: s.frameSeq, data: event.data, width: size.width, height: size.height, at: new Date().toISOString() };
709
+ wakeViewers(s);
710
+ }
711
+
712
+ // An action just happened on a page someone is watching. The picture whose
713
+ // acknowledgement is being held shows the page from before the action; let it
714
+ // through now so the next picture, the one with the action, is not kept
715
+ // waiting. The slot it was given stays taken, so the pane keeps its pace.
716
+ function hurryCast(s) {
717
+ const cast = s.cast;
718
+ if (!cast || !cast.timer) return;
719
+ const now = performance.now();
720
+ if (now - cast.acked < HURRY_PERIOD_MS) return;
721
+ clearTimeout(cast.timer);
722
+ cast.timer = null;
723
+ const release = cast.held;
724
+ cast.held = null;
725
+ if (release) release();
726
+ }
727
+
728
+ function leaseViewer(s) {
729
+ const lapsed = !viewLeased(s);
730
+ s.viewLease = Date.now() + VIEW_LEASE_MS;
731
+ clearTimeout(s.viewTimer);
732
+ s.viewTimer = setTimeout(() => {
733
+ s.viewTimer = null;
734
+ if (!viewLeased(s)) stopCast(s).catch(() => {});
735
+ }, VIEW_LEASE_MS + 100).unref?.();
736
+ if (s.cast) return Promise.resolve();
737
+ // Nobody was watching, so the picture held may be from any time since: the
738
+ // first request waits for a fresh one. With the lease still valid (the
739
+ // stream stopped for another reason) the picture is kept until one comes.
740
+ if (lapsed) s.frame = null;
741
+ return startCast(s).catch(() => {});
742
+ }
743
+
744
+ const castBroken = (s) => (s.cast
745
+ ? !s.cast.healthy && Date.now() - s.cast.startedAt > CAST_GRACE_MS
746
+ : viewLeased(s) && Date.now() - s.castFailedAt < CAST_RETRY_MS);
747
+
748
+ const currentPicture = (s) => (s.frame && s.frame.width === s.width && s.frame.height === s.height ? s.frame : null);
749
+
750
+ // End a wait when the viewer goes away or the page is gone.
751
+ function waitForPicture(s, wait, signal) {
752
+ if (signal?.aborted || waitingViewers >= WAITING_VIEWERS_MAX) return Promise.resolve('skipped');
753
+ return new Promise((resolve) => {
754
+ const waiter = {};
755
+ const finish = (outcome) => {
756
+ clearTimeout(timer);
757
+ s.waiters.delete(waiter);
758
+ signal?.removeEventListener('abort', aborted);
759
+ waitingViewers -= 1;
760
+ resolve(outcome);
761
+ };
762
+ waiter.wake = () => finish('picture');
763
+ const aborted = () => finish('aborted');
764
+ const timer = setTimeout(() => finish('timeout'), wait);
765
+ s.waiters.add(waiter);
766
+ waitingViewers += 1;
767
+ if (signal) signal.addEventListener('abort', aborted, { once: true });
768
+ });
769
+ }
770
+
771
+ // Everything about the page except the picture, for a viewer. The title and
772
+ // history are read from the page at most METADATA_PERIOD_MS, and never inside
773
+ // the session queue: a viewer must not wait behind an agent's slow navigation
774
+ // to be answered.
775
+ async function refreshMetadata(s) {
776
+ const now = Date.now();
777
+ if (now - s.titleAt < METADATA_PERIOD_MS && now - s.historyAt < METADATA_PERIOD_MS) return;
778
+ s.titleAt = now;
779
+ s.historyAt = now;
780
+ await Promise.all([
781
+ refreshTitle(s),
782
+ historyState(s).then((history) => { s.history = history; })
783
+ ]);
784
+ }
785
+
786
+ function describeForViewer(s, extra = {}) {
787
+ return {
788
+ ...describe(s),
789
+ ...s.history,
790
+ width: s.width,
791
+ height: s.height,
792
+ seq: s.frameSeq,
793
+ page: { ...currentPage(s), scrollX: null, scrollY: null, capturedAt: (s.frame && s.frame.at) || null, revision: s.revision },
794
+ ...extra
795
+ };
796
+ }
797
+
798
+ function pictureAnswer(s, picture) {
799
+ // A picture is not held back for a title read; the next answer carries it.
800
+ void refreshMetadata(s);
801
+ return describeForViewer(s, {
802
+ changed: true,
803
+ held: true,
804
+ image: picture.data,
805
+ width: picture.width,
806
+ height: picture.height,
807
+ seq: picture.seq,
808
+ page: { ...currentPage(s), width: picture.width, height: picture.height, scrollX: null, scrollY: null, capturedAt: picture.at, revision: s.revision }
809
+ });
810
+ }
811
+
812
+ // A picture taken on request, inside the session queue: the viewer's stream
813
+ // is left running. Stopping and restarting it for each capture was tried and
814
+ // is worse: every start costs a burst of five or six pictures in Chrome's
815
+ // first 150 ms. So a page has at most one capture out at a time and, once
816
+ // its stream is running, about one stream picture out for each
817
+ // acknowledgement; and an agent's capture never waits for a viewer's pictures.
818
+ async function takePicture(s) {
819
+ // A page that is still opening has nothing to take a picture of yet: a
820
+ // request that arrives then waits for the page instead of failing.
821
+ let taken = null;
822
+ for (const deadline = Date.now() + OPENING_PAGE_WAIT_MS; !taken; await sleep(OPENING_PAGE_RETRY_MS)) {
823
+ try {
824
+ taken = await capture(s);
825
+ } catch (error) {
826
+ if (!OPENING_PAGE.test(error.message) || Date.now() >= deadline) throw error;
827
+ }
828
+ }
829
+ lastPictureAt = performance.now();
830
+ const size = jpegSize(Buffer.from(taken.data, 'base64')) || { width: s.width, height: s.height };
831
+ s.frameSeq += 1;
832
+ s.frame = { seq: s.frameSeq, data: taken.data, width: size.width, height: size.height, at: new Date().toISOString() };
833
+ wakeViewers(s);
834
+ return s.frame;
835
+ }
836
+
837
+ // A picture taken on request. Runs in the session queue, so it never meets a
838
+ // viewport change. This is what an agent's `snapshot` and an old client get.
839
+ async function fullSnapshot(s, options = {}) {
840
+ // CDP screenshot waits for a JS dialog and times out. Keep the last
841
+ // frame, but return the dialog so the human/agent can answer it.
842
+ if (s.pendingDialog) {
843
+ const history = await historyState(s);
844
+ return {
845
+ ...describe(s),
846
+ ...history,
847
+ image: null,
848
+ width: s.width,
849
+ height: s.height,
850
+ seq: s.frameSeq,
851
+ changed: false,
852
+ dialog: s.dialog,
853
+ page: { ...currentPage(s), scrollX: 0, scrollY: 0 }
854
+ };
855
+ }
856
+ await s.page.bringToFront();
857
+ const picture = await takePicture(s);
858
+ await refreshTitle(s);
859
+ // A cheap position read: the full layout signature is only needed when
860
+ // deciding whether a coordinate target is still valid.
861
+ const info = await dom.scrollPosition(s.page);
862
+ return {
863
+ ...describe(s),
864
+ ...(await historyState(s)),
865
+ image: picture.data,
866
+ width: picture.width,
867
+ height: picture.height,
868
+ seq: picture.seq,
869
+ changed: true,
870
+ page: {
871
+ width: picture.width,
872
+ height: picture.height,
873
+ scrollX: info.scrollX,
874
+ scrollY: info.scrollY,
875
+ url: s.page.url(),
876
+ title: s.title || '',
877
+ capturedAt: picture.at,
878
+ revision: s.revision
879
+ },
880
+ ...(options.observation ? { observation: recordObservation(s, { scrollX: info.scrollX, scrollY: info.scrollY, layoutHash: info.hash }) } : {})
881
+ };
882
+ }
883
+
884
+ // How long to give Chrome's stream to bring a picture before one is taken.
885
+ // A stream that has not yet sent anything gets its start-up grace, no more.
886
+ function castPatience(s) {
887
+ const cast = s.cast;
888
+ if (!cast) return 0;
889
+ if (cast.healthy) return PICTURE_GRACE_MS;
890
+ return Math.max(0, Math.min(PICTURE_GRACE_MS, CAST_GRACE_MS - (Date.now() - cast.startedAt)));
891
+ }
892
+
893
+ async function viewerSnapshot(s, { watch, since, wait, signal }) {
894
+ const live = () => { if (sessions.get(s.id) !== s) deny('Browser pane no longer exists.', 404); };
895
+ live();
896
+ // A pane nobody can see: its title, address and page prompt only. No
897
+ // picture is taken and the stream is not started.
898
+ if (!watch) {
899
+ await refreshMetadata(s);
900
+ return describeForViewer(s, { changed: false, held: false });
901
+ }
902
+ await leaseViewer(s);
903
+ const deadline = Date.now() + wait;
904
+ let held = false;
905
+ for (;;) {
906
+ live();
907
+ if (signal?.aborted) return null;
908
+ if (s.pendingDialog) return describeForViewer(s, { changed: false, held: false, dialog: s.dialog });
909
+ const picture = currentPicture(s);
910
+ const left = deadline - Date.now();
911
+ if (!picture || castBroken(s)) {
912
+ // No picture of the page as it is now: a first look, or the viewport
913
+ // has just changed. Chrome's next one is quicker than a capture and is
914
+ // of the page as it is now, so give it a moment, then take one.
915
+ const patience = castBroken(s) ? 0 : castPatience(s);
916
+ if (left > 0 && patience > 0) {
917
+ const outcome = await waitForPicture(s, Math.min(left, patience), signal);
918
+ if (outcome === 'aborted') return null;
919
+ // No free waiting slot: take a picture now rather than ask the viewer to ask again with none in hand.
920
+ if (outcome !== 'skipped') continue;
921
+ }
922
+ // The all-panes pace holds for a picture taken one at a time too.
923
+ const turn = lastPictureAt + ALL_PICTURES_PERIOD_MS - performance.now();
924
+ if (turn > 0) await sleep(turn);
925
+ return enqueue(s, () => fullSnapshot(s));
926
+ }
927
+ if (since > s.frameSeq) since = -1; // The viewer has a picture of an earlier page.
928
+ if (picture.seq > since) return pictureAnswer(s, picture);
929
+ if (left <= 0) {
930
+ await refreshMetadata(s);
931
+ return describeForViewer(s, { changed: false, held });
932
+ }
933
+ // Do not wait past the moment a stream that has sent nothing would be
934
+ // given up on.
935
+ const grace = s.cast && !s.cast.healthy ? Math.max(0, s.cast.startedAt + CAST_GRACE_MS - Date.now()) : left;
936
+ const outcome = await waitForPicture(s, Math.min(left, grace), signal);
937
+ if (outcome === 'aborted') return null;
938
+ if (outcome === 'skipped') {
939
+ // Every waiting slot is taken (another viewer is holding it): answer
940
+ // now, saying so, and the viewer asks again shortly.
941
+ await refreshMetadata(s);
942
+ return describeForViewer(s, { changed: false, held: false });
943
+ }
944
+ // A picture came, or the wait ran out: look once more, then answer.
945
+ held = true;
946
+ }
947
+ }
948
+
949
+ // What a viewer's request asks for, and a way to learn that the viewer went
950
+ // away while it waited. `{}` for every other caller: an agent, or an old
951
+ // client, gets a picture taken for it there and then.
952
+ function viewerRequest(req, res) {
953
+ const watch = req.query.watch;
954
+ if (watch !== '0' && watch !== '1') return {};
955
+ const controller = new AbortController();
956
+ res.once('close', () => { if (!res.writableEnded) controller.abort(); });
957
+ return {
958
+ viewer: {
959
+ watch: watch === '1',
960
+ since: Math.max(-1, Math.floor(Number(req.query.since) || -1)),
961
+ wait: Math.max(0, Math.min(PICTURE_WAIT_MAX_MS, Number(req.query.wait) || 0))
962
+ },
963
+ signal: controller.signal
964
+ };
965
+ }
966
+
967
+ async function snapshotTab(id, options = {}) {
968
+ const s = sessions.get(id);
969
+ if (!s) deny('Browser pane no longer exists.', 404);
970
+ if (options.viewer) return viewerSnapshot(s, { ...options.viewer, signal: options.signal });
971
+ return enqueue(s, () => fullSnapshot(s, options));
972
+ }
973
+
974
+ // Nothing of a page's picture stream outlives the page.
975
+ function settlePictures(s) {
976
+ clearTimeout(s.viewTimer);
977
+ s.viewLease = 0;
978
+ for (const waiter of [...s.waiters]) waiter.wake();
979
+ stopCast(s).catch(() => {});
980
+ }
981
+
982
+ /**
983
+ * A named observation: screenshot plus a label describing exactly what the
984
+ * agent is looking at, and optionally the controls with stable refs.
985
+ */
986
+ async function observeTab(id, options = {}) {
987
+ const s = sessions.get(id);
988
+ if (!s) deny('Browser pane no longer exists.', 404);
989
+ return enqueue(s, async () => {
990
+ let image = null;
991
+ let history = null;
992
+ if (s.pendingDialog) {
993
+ history = await historyState(s);
994
+ } else {
995
+ await s.page.bringToFront();
996
+ image = (await capture(s)).data;
997
+ // An agent's capture is never made to wait for a viewer's pictures,
998
+ // but it is counted against every pane's allowance.
999
+ lastPictureAt = performance.now();
1000
+ history = await historyState(s);
1001
+ }
1002
+ await refreshTitle(s);
1003
+ const info = await dom.signature(s.page);
1004
+ const observation = recordObservation(s, {
1005
+ scrollX: info.scrollX,
1006
+ scrollY: info.scrollY,
1007
+ layoutHash: info.hash,
1008
+ dialog: s.dialog || null
1009
+ });
1010
+ const payload = {
1011
+ ...describe(s),
1012
+ ...(history || {}),
1013
+ observation,
1014
+ width: s.width,
1015
+ height: s.height,
1016
+ image,
1017
+ dialog: s.dialog || null
1018
+ };
1019
+ if (options.elements) {
1020
+ const catalogued = await dom.catalog(s.page, { max: options.max, start: s.nextRef });
1021
+ s.nextRef = Math.max(s.nextRef, catalogued.nextRef);
1022
+ for (const element of catalogued.elements) rememberRef(s, element, observation.id);
1023
+ payload.elements = catalogued.elements.map(redactControl);
1024
+ payload.frameCount = catalogued.frameCount;
1025
+ payload.truncated = catalogued.elements.length >= Math.max(1, Math.min(500, Number(options.max) || 200));
1026
+ }
1027
+ return payload;
1028
+ });
1029
+ }
1030
+
1031
+ async function elementsTab(id, options = {}) {
1032
+ const s = sessions.get(id);
1033
+ if (!s) deny('Browser pane no longer exists.', 404);
1034
+ return enqueue(s, async () => {
1035
+ await refreshTitle(s);
1036
+ const info = await dom.signature(s.page);
1037
+ const observation = recordObservation(s, {
1038
+ scrollX: info.scrollX,
1039
+ scrollY: info.scrollY,
1040
+ layoutHash: info.hash,
1041
+ elementsOnly: true
1042
+ });
1043
+ const catalogued = await dom.catalog(s.page, { max: options.max, start: s.nextRef });
1044
+ s.nextRef = Math.max(s.nextRef, catalogued.nextRef);
1045
+ for (const element of catalogued.elements) rememberRef(s, element, observation.id);
1046
+ return {
1047
+ ...describe(s),
1048
+ observation,
1049
+ elements: catalogued.elements.map(redactControl),
1050
+ frameCount: catalogued.frameCount,
1051
+ truncated: catalogued.elements.length >= Math.max(1, Math.min(500, Number(options.max) || 200))
1052
+ };
1053
+ });
1054
+ }
1055
+
1056
+ async function contentTab(id, options = {}) {
1057
+ const s = sessions.get(id);
1058
+ if (!s) deny('Browser pane no longer exists.', 404);
1059
+ return enqueue(s, async () => {
1060
+ const info = await dom.content(s.page, options.limit || 200000);
1061
+ await refreshTitle(s);
1062
+ return {
1063
+ ...describe(s),
1064
+ text: info.text,
1065
+ totalLength: info.totalLength,
1066
+ truncated: info.truncated,
1067
+ frameCount: info.frameCount,
1068
+ frames: info.frames,
1069
+ url: info.url || s.page.url(),
1070
+ title: s.title || info.title || ''
1071
+ };
1072
+ });
1073
+ }
1074
+
1075
+ async function navigateTab(id, url) {
1076
+ const s = sessions.get(id);
1077
+ if (!s) deny('Browser pane no longer exists.', 404);
1078
+ return enqueue(s, async () => {
1079
+ await s.page.goto(address(url), { waitUntil: 'domcontentloaded', timeout: 20000 });
1080
+ // Read the title *after* the navigation. Returning the new address with
1081
+ // the previous page's title was the bug reported in the assessment.
1082
+ await refreshTitle(s);
1083
+ hurryCast(s);
1084
+ return describe(s);
1085
+ });
1086
+ }
1087
+
1088
+ // What is under a coordinate: a select or a date-like input has a value the
1089
+ // human UI can offer a native picker for.
1090
+ const readControlAt = (p, position) => p.evaluate(({ x, y }) => {
1091
+ const el = document.elementFromPoint(x, y);
1092
+ if (!el) return null;
1093
+ if (el.tagName === 'SELECT') {
1094
+ return {
1095
+ kind: 'select',
1096
+ value: el.value,
1097
+ options: Array.from(el.options).map((option) => ({ value: option.value, label: option.textContent || option.value }))
1098
+ };
1099
+ }
1100
+ if (el.tagName === 'INPUT' && ['date', 'color', 'time', 'datetime-local', 'month', 'week'].includes(el.type)) {
1101
+ return { kind: el.type, value: el.value };
1102
+ }
1103
+ return null;
1104
+ }, position).catch(() => null);
1105
+
1106
+ async function readControlValue(handle) {
1107
+ if (!handle) return null;
1108
+ try {
1109
+ return await handle.evaluate((node) => {
1110
+ if (!node || !('value' in node)) return null;
1111
+ return {
1112
+ tag: node.tagName ? node.tagName.toLowerCase() : '',
1113
+ type: String(node.type || ''),
1114
+ value: String(node.value == null ? '' : node.value).slice(0, 400)
1115
+ };
1116
+ });
1117
+ } catch (_) { return null; }
1118
+ }
1119
+
1120
+ // The body runs inside the session queue so an action cannot interleave with
1121
+ // a screenshot or a viewport change on the same page.
1122
+ async function performAction(s, action, data = {}) {
1123
+ const p = s.page;
1124
+ let control = null;
1125
+ let target = null;
1126
+ let actionStatus = STATUS.completed;
1127
+ let message = '';
1128
+ let warning = '';
1129
+ let handle = null;
1130
+
1131
+ const resolveTarget = async () => {
1132
+ if (data.ref) {
1133
+ const resolved = await targetFromRef(s, data.ref);
1134
+ if (resolved.status !== STATUS.completed) {
1135
+ actionStatus = resolved.status;
1136
+ message = resolved.message || '';
1137
+ return false;
1138
+ }
1139
+ handle = resolved.handle;
1140
+ target = resolved.current && {
1141
+ ref: data.ref,
1142
+ role: resolved.current.role || resolved.record?.role,
1143
+ name: resolved.record?.name || resolved.current.name,
1144
+ box: resolved.current.box
1145
+ };
1146
+ return true;
1147
+ }
1148
+ return false;
1149
+ };
1150
+
1151
+ try {
1152
+ switch (action) {
1153
+ case 'navigate': await p.goto(address(data.url), { waitUntil: 'domcontentloaded', timeout: 20000 }); break;
1154
+ case 'back': await p.goBack({ waitUntil: 'domcontentloaded', timeout: 20000 }); break;
1155
+ case 'forward': await p.goForward({ waitUntil: 'domcontentloaded', timeout: 20000 }); break;
1156
+ case 'reload': await p.reload({ waitUntil: 'domcontentloaded', timeout: 20000 }); break;
1157
+ case 'click': {
1158
+ if (data.ref) {
1159
+ if (await resolveTarget()) {
1160
+ if (target && target.box && target.box.width === 0) {
1161
+ actionStatus = STATUS.failed; message = 'The target has no clickable area.';
1162
+ } else {
1163
+ await handle.click({ timeout: 10000 });
1164
+ control = await readControlValue(handle);
1165
+ }
1166
+ }
1167
+ } else {
1168
+ const position = point(s, data);
1169
+ if (data.observationId !== undefined && data.observationId !== null) {
1170
+ await assertFreshObservation(s, data.observationId);
1171
+ } else {
1172
+ warning = 'unverified-position';
1173
+ }
1174
+ await p.mouse.click(position.x, position.y);
1175
+ control = await readControlAt(p, position);
1176
+ }
1177
+ break;
1178
+ }
1179
+ case 'hover': {
1180
+ if (data.ref) {
1181
+ // Stay with the reported status when the ref is gone; do not fall
1182
+ // through to a coordinate path that was never supplied.
1183
+ if (await resolveTarget()) await handle.hover();
1184
+ } else if (data.x !== undefined && data.y !== undefined) {
1185
+ const position = point(s, data);
1186
+ await p.mouse.move(position.x, position.y);
1187
+ } else {
1188
+ deny('hover needs a ref or x/y coordinates.', 400);
1189
+ }
1190
+ break;
1191
+ }
1192
+ case 'drag': {
1193
+ if (!(data.fromRef || data.fromX !== undefined) || !(data.toRef || data.toX !== undefined)) {
1194
+ deny('drag needs fromRef/toRef or fromX/toX.', 400);
1195
+ }
1196
+ let from = null;
1197
+ let to = null;
1198
+ if (data.fromRef) {
1199
+ const resolved = await targetFromRef(s, data.fromRef);
1200
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
1201
+ from = await resolved.handle.boundingBox();
1202
+ } else if (data.fromX !== undefined) {
1203
+ from = { x: Number(data.fromX), y: Number(data.fromY), width: 0, height: 0 };
1204
+ }
1205
+ if (data.toRef) {
1206
+ const resolved = await targetFromRef(s, data.toRef);
1207
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
1208
+ to = await resolved.handle.boundingBox();
1209
+ } else if (data.toX !== undefined) {
1210
+ to = { x: Number(data.toX), y: Number(data.toY), width: 0, height: 0 };
1211
+ }
1212
+ if (!from || !to) {
1213
+ actionStatus = STATUS.failed;
1214
+ message = 'A drag target has no visible area to grab.';
1215
+ break;
1216
+ }
1217
+ await p.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
1218
+ await p.mouse.down();
1219
+ await p.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 12 });
1220
+ await p.mouse.up();
1221
+ target = { from: { x: from.x, y: from.y }, to: { x: to.x, y: to.y } };
1222
+ break;
1223
+ }
1224
+ case 'type': {
1225
+ const text = String(data.text || '').slice(0, MAX_ACTION_TEXT);
1226
+ if (data.ref) {
1227
+ const resolved = await targetFromRef(s, data.ref);
1228
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
1229
+ handle = resolved.handle;
1230
+ const kind = resolved.current ? resolved.current.tag : '';
1231
+ if (['button', 'a', 'img', 'iframe', 'select', 'option'].includes(kind)) {
1232
+ actionStatus = STATUS.wrongKind;
1233
+ message = `Element ${data.ref} is a <${kind}>, not a text field.`;
1234
+ break;
1235
+ }
1236
+ await handle.click({ timeout: 10000 });
1237
+ if (data.replace) {
1238
+ // Select the field's whole content with the DOM API rather than a
1239
+ // platform shortcut, then delete it. Appending without clearing
1240
+ // was the reported "clearing did not clear" bug.
1241
+ await handle.evaluate((node) => {
1242
+ if (node && typeof node.focus === 'function') node.focus();
1243
+ if (node && typeof node.select === 'function') { node.select(); return; }
1244
+ if (node && typeof node.setSelectionRange === 'function' && typeof node.value === 'string') {
1245
+ node.setSelectionRange(0, node.value.length);
1246
+ return;
1247
+ }
1248
+ // A contenteditable is a textbox with neither API; select its
1249
+ // contents with a Range so Backspace clears all of it.
1250
+ if (node && node.isContentEditable) {
1251
+ const range = document.createRange();
1252
+ range.selectNodeContents(node);
1253
+ const selection = window.getSelection();
1254
+ if (selection) { selection.removeAllRanges(); selection.addRange(range); }
1255
+ }
1256
+ });
1257
+ await p.keyboard.press('Backspace');
1258
+ }
1259
+ await p.keyboard.type(text);
1260
+ control = await readControlValue(handle);
1261
+ target = { ref: data.ref, role: resolved.current?.role, name: resolved.record?.name };
1262
+ } else {
1263
+ await p.keyboard.type(text);
1264
+ }
1265
+ break;
1266
+ }
1267
+ case 'key':
1268
+ if (Array.isArray(data.keys)) {
1269
+ for (const spec of data.keys.slice(0, 32)) await pressCombo(p, spec);
1270
+ } else {
1271
+ await pressCombo(p, data.key);
1272
+ }
1273
+ break;
1274
+ case 'scroll': {
1275
+ if (data.pointer) {
1276
+ // The human viewer's wheel gesture keeps the old pointer-targeted
1277
+ // behaviour, so a list or iframe under the cursor scrolls itself.
1278
+ const deltaX = Math.max(-1500, Math.min(1500, Number(data.deltaX ?? data.dx) || 0));
1279
+ const deltaY = Math.max(-1500, Math.min(1500, Number(data.deltaY ?? data.dy) || 0));
1280
+ await p.mouse.wheel({ deltaX, deltaY });
1281
+ target = { scroller: 'pointer' };
1282
+ } else if (data.ref || data.selector) {
1283
+ const scrolled = await dom.scroll(p, {
1284
+ marker: data.ref,
1285
+ selector: data.selector,
1286
+ dx: Math.max(-1500, Math.min(1500, Number(data.deltaX ?? data.dx) || 0)),
1287
+ dy: Math.max(-1500, Math.min(1500, Number(data.deltaY ?? data.dy) || 0))
1288
+ });
1289
+ if (!scrolled.found) {
1290
+ actionStatus = scrolled.reason === 'missing' ? STATUS.missing : STATUS.failed;
1291
+ message = scrolled.reason === 'missing'
1292
+ ? 'The area to scroll was not found.'
1293
+ : `The area could not be scrolled: ${scrolled.error || scrolled.reason}`;
1294
+ }
1295
+ target = { scroller: scrolled.scroller || null, moved: Boolean(scrolled.moved) };
1296
+ } else {
1297
+ const deltaX = Math.max(-1500, Math.min(1500, Number(data.deltaX ?? data.dx) || 0));
1298
+ const deltaY = Math.max(-1500, Math.min(1500, Number(data.deltaY ?? data.dy) || 0));
1299
+ if (data.observationId !== undefined && data.observationId !== null) {
1300
+ await assertFreshObservation(s, data.observationId);
1301
+ }
1302
+ // Scroll the page itself, not wherever the invisible pointer last
1303
+ // happened to rest.
1304
+ await p.mainFrame().evaluate(({ dx, dy }) => {
1305
+ const scroller = document.scrollingElement || document.documentElement;
1306
+ scroller.scrollBy({ left: dx, top: dy, behavior: 'instant' });
1307
+ }, { dx: deltaX, dy: deltaY });
1308
+ const info = await dom.scrollPosition(p);
1309
+ target = { scroller: 'page', scrollX: info.scrollX, scrollY: info.scrollY };
1310
+ }
1311
+ break;
1312
+ }
1313
+ case 'select':
1314
+ case 'setValue':
1315
+ case 'selectAt':
1316
+ case 'setValueAt': {
1317
+ if (data.ref) {
1318
+ const resolved = await targetFromRef(s, data.ref);
1319
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
1320
+ handle = resolved.handle;
1321
+ const applied = await handle.evaluate((node, value) => {
1322
+ if (!node || !('value' in node)) return { ok: false, reason: 'not-a-control' };
1323
+ const setter = Object.getOwnPropertyDescriptor(
1324
+ node.tagName === 'SELECT' ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype,
1325
+ 'value'
1326
+ );
1327
+ // A framework-controlled input ignores a plain assignment; use the
1328
+ // native setter so its own change handling sees the update.
1329
+ if (node.tagName === 'SELECT') node.value = String(value ?? '');
1330
+ else if (setter && setter.set) setter.set.call(node, String(value ?? ''));
1331
+ else node.value = String(value ?? '');
1332
+ node.dispatchEvent(new Event('input', { bubbles: true }));
1333
+ node.dispatchEvent(new Event('change', { bubbles: true }));
1334
+ return {
1335
+ ok: true,
1336
+ value: String(node.value ?? ''),
1337
+ // The field's type travels with its value so the server can
1338
+ // tell a password field before the value goes any further.
1339
+ type: node.tagName === 'INPUT' ? String(node.type || '').toLowerCase() : ''
1340
+ };
1341
+ }, data.value);
1342
+ if (!applied.ok) { actionStatus = STATUS.wrongKind; message = 'That element does not hold a value.'; break; }
1343
+ control = { value: applied.value, type: applied.type };
1344
+ } else {
1345
+ const position = data.x !== undefined ? point(s, data) : null;
1346
+ if (!position) deny('select needs a ref or x/y coordinates.', 400);
1347
+ if (data.observationId !== undefined && data.observationId !== null) {
1348
+ await assertFreshObservation(s, data.observationId);
1349
+ }
1350
+ control = await p.evaluate(({ x, y, value }) => {
1351
+ const el = document.elementFromPoint(x, y);
1352
+ if (!el || (el.tagName !== 'SELECT' && el.tagName !== 'INPUT')) return null;
1353
+ el.value = String(value ?? '');
1354
+ el.dispatchEvent(new Event('input', { bubbles: true }));
1355
+ el.dispatchEvent(new Event('change', { bubbles: true }));
1356
+ if (el.tagName === 'SELECT') {
1357
+ return {
1358
+ kind: 'select',
1359
+ value: el.value,
1360
+ options: Array.from(el.options).map((option) => ({ value: option.value, label: option.textContent || option.value }))
1361
+ };
1362
+ }
1363
+ return { kind: el.type, value: el.value };
1364
+ }, { ...position, value: data.value });
1365
+ if (!control) { actionStatus = STATUS.missing; message = 'No select or input at that position.'; }
1366
+ }
1367
+ break;
1368
+ }
1369
+ default: deny('Unknown browser action.', 400);
1370
+ }
1371
+ } catch (error) {
1372
+ if (error.status === 409) throw error;
1373
+ actionStatus = STATUS.failed;
1374
+ message = error.message || String(error);
1375
+ }
1376
+
1377
+ await refreshTitle(s);
1378
+ let focus = null;
1379
+ try { focus = await dom.focusInfo(p); } catch (_) { focus = null; }
1380
+ const described = describe(s);
1381
+ const payload = result(actionStatus, {
1382
+ ...described,
1383
+ // A completed action whose effect the page has not reported yet is
1384
+ // honestly labelled unconfirmed rather than assumed to have worked.
1385
+ message: message || undefined,
1386
+ warning: warning || undefined,
1387
+ target: target || undefined,
1388
+ // These two are every value a page reports about a control in an action
1389
+ // (a click or typing reading the field back, and the focused element).
1390
+ control: redactControl(control),
1391
+ focused: redactControl(focus),
1392
+ observationId: s.lastObservationId || null
1393
+ });
1394
+ return payload;
1395
+ }
1396
+
1397
+ function actionTab(id, action, data = {}, options = {}) {
1398
+ const s = sessions.get(id);
1399
+ if (!s) deny('Browser pane no longer exists.', 404);
1400
+ return enqueue(s, () => {
1401
+ // An action can wait behind a slow navigation or capture. Re-check the
1402
+ // caller's grant inside the queue so a revoked token cannot execute a
1403
+ // side effect it was authorized for moments earlier.
1404
+ if (typeof options.authorize === 'function') options.authorize();
1405
+ return performAction(s, action, data).then((outcome) => {
1406
+ // The picture being held back is from before the action.
1407
+ hurryCast(s);
1408
+ return outcome;
1409
+ });
1410
+ });
1411
+ }
1412
+
1413
+ async function waitTab(id, conditions = {}, options = {}) {
1414
+ const s = sessions.get(id);
1415
+ if (!s) deny('Browser pane no longer exists.', 404);
1416
+ const timeout = Math.max(100, Math.min(120000, Number(conditions.timeout) || 30000));
1417
+ const hasUrl = typeof conditions.url === 'string' && conditions.url;
1418
+ const hasText = typeof conditions.text === 'string' && conditions.text;
1419
+ const hasSelector = typeof conditions.selector === 'string' && conditions.selector;
1420
+ const hasValue = typeof conditions.value === 'string' && conditions.ref;
1421
+ const hasTitle = typeof conditions.title === 'string' && conditions.title;
1422
+ if (!hasUrl && !hasText && !hasSelector && !hasValue && !hasTitle) {
1423
+ deny('Provide url, title, text, selector, or value with ref.', 400);
1424
+ }
1425
+ if (hasValue) {
1426
+ // A password field's value never leaves the page, so it cannot be a
1427
+ // condition either: a match would confirm a guess of the value.
1428
+ const probe = await dom.resolveRef(s.page, conditions.ref);
1429
+ const type = probe
1430
+ ? await probe.evaluate((node) => String((node && node.type) || '').toLowerCase()).catch(() => '')
1431
+ : '';
1432
+ if (probe) await probe.dispose().catch(() => {});
1433
+ if (type === 'password') {
1434
+ deny("A password field's value never leaves the page, so it cannot be waited on. Wait on a selector or on page text instead.", 400);
1435
+ }
1436
+ }
1437
+ const started = Date.now();
1438
+ const check = async () => {
1439
+ const url = (() => { try { return s.page.url(); } catch (_) { return ''; } })();
1440
+ // A literal, not a regular expression: an untrusted pattern tested on the
1441
+ // event loop can stall every request through catastrophic backtracking.
1442
+ if (hasUrl && url.includes(conditions.url)) return { matched: true, reason: 'url' };
1443
+ if (hasTitle) {
1444
+ const title = await s.page.title().catch(() => '');
1445
+ if (title.includes(conditions.title)) return { matched: true, reason: 'title' };
1446
+ }
1447
+ if (hasSelector) {
1448
+ for (const frame of s.page.frames()) {
1449
+ let found = false;
1450
+ try { found = await frame.evaluate((sel) => Boolean(document.querySelector(sel)), conditions.selector); }
1451
+ catch (_) { found = false; }
1452
+ if (found) return { matched: true, reason: 'selector' };
1453
+ }
1454
+ }
1455
+ if (hasText) {
1456
+ const info = await dom.content(s.page, 2000000);
1457
+ if (info.text.includes(conditions.text)) return { matched: true, reason: 'text' };
1458
+ }
1459
+ if (hasValue) {
1460
+ const handle = await dom.resolveRef(s.page, conditions.ref);
1461
+ if (handle) {
1462
+ // Re-checked on every pass: a field that became a password field
1463
+ // after the wait started is never compared.
1464
+ const value = await handle.evaluate((node) => (node && 'value' in node && String(node.type || '').toLowerCase() !== 'password' ? String(node.value) : null))
1465
+ .catch(() => null);
1466
+ if (value === conditions.value) return { matched: true, reason: 'value' };
1467
+ }
1468
+ }
1469
+ return null;
1470
+ };
1471
+ let outcome = null;
1472
+ for (;;) {
1473
+ // A caller that lost the right to read this page while waiting is told
1474
+ // so by the caller's own check rather than left waiting for an answer.
1475
+ if (typeof options.interrupted === 'function' && options.interrupted()) {
1476
+ return {
1477
+ ok: false,
1478
+ status: STATUS.unconfirmed,
1479
+ matched: false,
1480
+ reason: 'interrupted',
1481
+ elapsedMs: Date.now() - started,
1482
+ url: s.page.url(),
1483
+ title: s.title || '',
1484
+ observationId: s.lastObservationId || null
1485
+ };
1486
+ }
1487
+ outcome = await check().catch(() => null);
1488
+ if (outcome) break;
1489
+ if (Date.now() - started >= timeout) break;
1490
+ await new Promise((resolve) => setTimeout(resolve, 150));
1491
+ }
1492
+ await refreshTitle(s);
1493
+ const info = await dom.signature(s.page);
1494
+ return {
1495
+ ok: Boolean(outcome),
1496
+ status: outcome ? STATUS.completed : STATUS.unconfirmed,
1497
+ matched: Boolean(outcome),
1498
+ reason: outcome ? outcome.reason : 'timeout',
1499
+ elapsedMs: Date.now() - started,
1500
+ url: s.page.url(),
1501
+ title: s.title || '',
1502
+ scrollX: info.scrollX,
1503
+ scrollY: info.scrollY,
1504
+ observationId: s.lastObservationId || null
1505
+ };
1506
+ }
1507
+
1508
+ async function sizingTab(id, mode, options = {}) {
1509
+ const s = sessions.get(id);
1510
+ if (!s) deny('Browser pane no longer exists.', 404);
1511
+ if (!['fit', 'fixed'].includes(mode)) deny('Sizing mode must be fit or fixed.', 400);
1512
+ return enqueue(s, async () => {
1513
+ if (mode === 'fixed') {
1514
+ s.sizing = 'fixed';
1515
+ s.fixedWidth = Math.max(320, Math.min(1920, Math.round(Number(options.width) || s.width)));
1516
+ s.fixedHeight = Math.max(240, Math.min(1200, Math.round(Number(options.height) || s.height)));
1517
+ s.width = s.fixedWidth;
1518
+ s.height = s.fixedHeight;
1519
+ await s.page.setViewport({ width: s.width, height: s.height });
1520
+ // A viewer waiting for a picture now needs one of the new size.
1521
+ wakeViewers(s);
1522
+ } else {
1523
+ s.sizing = 'fit';
1524
+ }
1525
+ return { sizing: s.sizing, width: s.width, height: s.height };
1526
+ });
1527
+ }
1528
+
1529
+ async function closeTabInternal(id) {
1530
+ const s = sessions.get(id);
1531
+ if (!s) return false;
1532
+ clearTimeout(s.dialogTimer);
1533
+ sessions.delete(id);
1534
+ settlePictures(s);
1535
+ await s.context.close();
1536
+ return true;
1537
+ }
1538
+
1539
+ function getTab(id) { return sessions.get(id) || null; }
1540
+
1541
+ // A pane workspace browser keeps its record in step with the pane's grant,
1542
+ // so what a snapshot says about a session is what the pane's routes enforce.
1543
+ function grantTab(id, permission) {
1544
+ const s = sessions.get(id);
1545
+ if (s && ['private', 'view', 'control'].includes(permission)) s.permission = permission;
1546
+ return s ? s.permission : null;
1547
+ }
1548
+
1549
+ async function setViewportTab(id, width, height, options = {}) {
1550
+ const s = sessions.get(id);
1551
+ if (!s) deny('Browser pane no longer exists.', 404);
1552
+ return enqueue(s, async () => {
1553
+ // Fixed-size mode: the owner resizing their viewer must not rearrange the
1554
+ // page. Only an explicit (force) request changes a locked viewport.
1555
+ if (s.sizing === 'fixed' && !options.force) {
1556
+ return { width: s.width, height: s.height, sizing: s.sizing, ignored: true };
1557
+ }
1558
+ s.width = Math.max(320, Math.min(1920, Math.round(Number(width) || 1280)));
1559
+ s.height = Math.max(240, Math.min(1200, Math.round(Number(height) || 800)));
1560
+ await s.page.setViewport({ width: s.width, height: s.height });
1561
+ // A viewer waiting for a picture now needs one of the new size.
1562
+ wakeViewers(s);
1563
+ return { width: s.width, height: s.height, sizing: s.sizing };
1564
+ });
1565
+ }
1566
+
1567
+ // ── Routes ────────────────────────────────────────────────────────────────
1568
+
1569
+ // The single-browser workspace's owner key is guarded exactly like the pane
1570
+ // workspace's: the same proof, the same refusals, in one place.
1571
+ app.get('/api/browser/bootstrap', route(async (req, res) => {
1572
+ const refused = ownerPageRefusal(req);
1573
+ if (refused) deny(refused.body.error, refused.status, refused.body);
1574
+ res.json({ key: humanKey });
1575
+ }));
1576
+
1577
+ app.get('/api/browser', route(async (req, res) => {
1578
+ if (!human(req)) deny('Workspace access required.');
1579
+ res.json([...sessions.values()].filter((s) => !s.internal).map(describe));
1580
+ }));
1581
+
1582
+ app.post('/api/browser', route(async (req, res) => {
1583
+ if (!human(req)) deny('Only the owner can create browser tabs.');
1584
+ if (sessions.size + opening >= MAX_BROWSER_TABS) deny('Close a tab before opening another.', 409);
1585
+ opening++;
1586
+ let context;
1587
+ let s;
1588
+ try {
1589
+ context = await (await engine()).createBrowserContext();
1590
+ const page = await context.newPage();
1591
+ await page.setViewport({ width: 1280, height: 800 });
1592
+ const kind = req.body.kind === 'agent' ? 'agent' : 'human';
1593
+ s = initSession({
1594
+ id: crypto.randomUUID(),
1595
+ token: crypto.randomBytes(32).toString('hex'),
1596
+ page,
1597
+ context,
1598
+ kind,
1599
+ width: 1280,
1600
+ height: 800,
1601
+ permission: kind === 'agent' ? 'control' : 'private'
1602
+ });
1603
+ wireSession(s);
1604
+ sessions.set(s.id, s);
1605
+ page.once('close', () => sessions.delete(s.id));
1606
+ res.json(describe(s));
1607
+ } catch (error) {
1608
+ if (s) sessions.delete(s.id);
1609
+ if (context) await context.close().catch(() => {});
1610
+ throw error;
1611
+ } finally { opening--; }
1612
+ }));
1613
+
1614
+ app.post('/api/browser/:id/permission', route(async (req, res) => {
1615
+ if (!human(req)) deny('Only the owner can change sharing.');
1616
+ const s = session(req);
1617
+ if (!['private', 'view', 'control'].includes(req.body.permission)) deny('Unknown sharing permission.', 400);
1618
+ s.permission = req.body.permission;
1619
+ s.token = crypto.randomBytes(32).toString('hex'); // Revoke every previous capability.
1620
+ res.json(describe(s));
1621
+ }));
1622
+
1623
+ app.get('/api/browser/:id/access', route(async (req, res) => {
1624
+ if (!human(req)) deny('Only the owner can reveal access.');
1625
+ const s = session(req);
1626
+ if (s.permission === 'private') deny('Choose View or Control before sharing.');
1627
+ res.json({ id: s.id, token: s.token, permission: s.permission, endpoint: '/api/browser/' + s.id });
1628
+ }));
1629
+
1630
+ app.get('/api/browser/:id/snapshot', route(async (req, res) => {
1631
+ session(req); // Permission check before the expensive capture.
1632
+ const snapshot = await snapshotTab(req.params.id, viewerRequest(req, res));
1633
+ if (!snapshot) return; // The viewer went away while its request waited.
1634
+ session(req); // Recheck grants after asynchronous work.
1635
+ res.json(snapshot);
1636
+ }));
1637
+
1638
+ app.get('/api/browser/:id/observe', route(async (req, res) => {
1639
+ session(req);
1640
+ const observed = await observeTab(req.params.id, {
1641
+ elements: req.query.elements === '1' || req.query.elements === 'true',
1642
+ max: req.query.max
1643
+ });
1644
+ session(req);
1645
+ res.json(observed);
1646
+ }));
1647
+
1648
+ app.get('/api/browser/:id/elements', route(async (req, res) => {
1649
+ session(req);
1650
+ const catalogued = await elementsTab(req.params.id, { max: req.query.max });
1651
+ session(req);
1652
+ res.json(catalogued);
1653
+ }));
1654
+
1655
+ app.post('/api/browser/:id/viewport', route(async (req, res) => {
1656
+ if (!human(req)) deny('Only the owner can resize the viewer.');
1657
+ session(req);
1658
+ const size = await setViewportTab(req.params.id, req.body.width, req.body.height, { force: req.body.force === true });
1659
+ res.json(size);
1660
+ }));
1661
+
1662
+ app.post('/api/browser/:id/sizing', route(async (req, res) => {
1663
+ session(req, true);
1664
+ res.json(await sizingTab(req.params.id, req.body.mode, req.body));
1665
+ }));
1666
+
1667
+ app.get('/api/browser/:id/content', route(async (req, res) => {
1668
+ session(req);
1669
+ const info = await contentTab(req.params.id, { limit: req.query.limit });
1670
+ session(req);
1671
+ res.json(info);
1672
+ }));
1673
+
1674
+ app.post('/api/browser/:id/action', route(async (req, res) => {
1675
+ session(req, true);
1676
+ const outcome = await actionTab(req.params.id, req.body.action, req.body, {
1677
+ authorize: () => session(req, true)
1678
+ });
1679
+ session(req); // Recheck grants after asynchronous work.
1680
+ res.status(outcome.httpStatus || 200).json(outcome);
1681
+ }));
1682
+
1683
+ app.post('/api/browser/:id/wait', route(async (req, res) => {
1684
+ session(req);
1685
+ res.json(await waitTab(req.params.id, req.body || {}));
1686
+ }));
1687
+
1688
+ app.post('/api/browser/:id/dialog', route(async (req, res) => {
1689
+ if (!human(req)) deny('Only the owner can answer a page dialog.');
1690
+ const s = session(req);
1691
+ res.json(await respondDialog(s.id, req.body.action, req.body.text));
1692
+ }));
1693
+
1694
+ app.delete('/api/browser/:id', route(async (req, res) => {
1695
+ if (!human(req)) deny('Only the owner can close tabs.');
1696
+ const s = session(req);
1697
+ clearTimeout(s.dialogTimer);
1698
+ sessions.delete(s.id);
1699
+ settlePictures(s);
1700
+ await s.context.close();
1701
+ res.json({ closed: true });
1702
+ }));
1703
+
1704
+ const closeAll = async () => {
1705
+ for (const s of sessions.values()) settlePictures(s);
1706
+ sessions.clear();
1707
+ if (browserPromise) await (await browserPromise).close();
1708
+ };
1709
+
1710
+ return {
1711
+ closeAll,
1712
+ create: createTab,
1713
+ snapshot: snapshotTab,
1714
+ viewerRequest,
1715
+ observe: observeTab,
1716
+ elements: elementsTab,
1717
+ content: contentTab,
1718
+ navigate: navigateTab,
1719
+ action: actionTab,
1720
+ wait: waitTab,
1721
+ sizing: sizingTab,
1722
+ close: closeTabInternal,
1723
+ get: getTab,
1724
+ grant: grantTab,
1725
+ setViewport: setViewportTab,
1726
+ respondDialog,
1727
+ describe,
1728
+ engineStatus,
1729
+ STATUS
1730
+ };
1731
+ }
1732
+
1733
+ module.exports = { installBrowserWorkspace };