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,1246 @@
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
+
7
+ // How many past observations a session keeps. Enough for an agent to compare a
8
+ // few steps back; bounded so a long session cannot grow without limit.
9
+ const MAX_OBSERVATIONS = 20;
10
+ // Ref records are cheap but should not accumulate forever across navigations.
11
+ const MAX_REF_RECORDS = 4000;
12
+ const MAX_ACTION_TEXT = 10000;
13
+
14
+ // Action result statuses. These distinguish "the instruction was received" from
15
+ // "the instruction happened", which is the point of the assessment.
16
+ const STATUS = {
17
+ completed: 'completed',
18
+ missing: 'missing',
19
+ wrongKind: 'wrong-kind',
20
+ failed: 'failed',
21
+ stale: 'stale',
22
+ unconfirmed: 'unconfirmed'
23
+ };
24
+
25
+ const STATUS_HTTP = {
26
+ completed: 200,
27
+ missing: 404,
28
+ 'wrong-kind': 400,
29
+ failed: 500,
30
+ stale: 409,
31
+ unconfirmed: 200
32
+ };
33
+
34
+ function installBrowserWorkspace(app) {
35
+ const humanKey = crypto.randomBytes(32).toString('hex');
36
+ const MAX_BROWSER_TABS = 32;
37
+ const sessions = new Map();
38
+ let browserPromise;
39
+ let opening = 0;
40
+ let observationCounter = 0;
41
+
42
+ const resolveEngine = () => resolveChrome();
43
+ const engineStatus = () => {
44
+ const chrome = resolveEngine();
45
+ return chrome
46
+ ? { engine: 'ready', path: chrome.path, source: chrome.source }
47
+ : { engine: 'missing', path: null, source: null };
48
+ };
49
+
50
+ const engine = () => {
51
+ if (!browserPromise) {
52
+ // Keep Chromium's renderer sandbox by default. Containers and CI runners
53
+ // without user namespaces need an explicit opt-out; it is never implied
54
+ // by running with elevated privileges or by opening an untrusted page.
55
+ const unsandboxed = process.env.CI === 'true' || process.env.TOWNMOUSE_CHROMIUM_NO_SANDBOX === '1';
56
+ // A packaged install may have neither Puppeteer's download (npm 12 skips
57
+ // install scripts) nor a configured path; find an existing browser first.
58
+ const chrome = resolveEngine();
59
+ browserPromise = puppeteer.launch({
60
+ headless: true,
61
+ args: [
62
+ ...(unsandboxed ? ['--no-sandbox', '--disable-setuid-sandbox'] : []),
63
+ '--disable-dev-shm-usage', '--disable-gpu', '--disable-background-timer-throttling',
64
+ '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows'
65
+ ],
66
+ ...(chrome ? { executablePath: chrome.path } : {})
67
+ }).then((browser) => {
68
+ browser.on('disconnected', () => {
69
+ browserPromise = null;
70
+ // Every session belonged to the dead browser. Clearing the map lets
71
+ // the UI reconcile instead of offering unclosable ghost tabs.
72
+ sessions.clear();
73
+ });
74
+ return browser;
75
+ }).catch((error) => {
76
+ browserPromise = null;
77
+ if (!chrome) throw new Error(`${missingBrowserMessage()}\n\n${error.message}`);
78
+ throw error;
79
+ });
80
+ }
81
+ return browserPromise;
82
+ };
83
+
84
+ const human = (req) => req.get('X-Workspace-Key') === humanKey;
85
+
86
+ const describe = (s) => ({
87
+ id: s.id,
88
+ kind: s.kind,
89
+ permission: s.permission,
90
+ url: s.page.url(),
91
+ title: s.title || 'New tab',
92
+ dialog: s.dialog || null,
93
+ sizing: s.sizing,
94
+ viewport: { width: s.width, height: s.height }
95
+ });
96
+
97
+ // Screenshot capture and viewport changes share one page. Serialize them or
98
+ // a resize can land mid-capture and label an old-size image with new
99
+ // dimensions, which makes pane click mapping land in the wrong place.
100
+ const enqueue = (s, task) => {
101
+ const work = (s.queue || Promise.resolve()).then(task, task);
102
+ s.queue = work.catch(() => {});
103
+ return work;
104
+ };
105
+
106
+ // Work that touches the page is serialized by the operation itself (each
107
+ // `…Tab` function calls `enqueue`). The route wrapper must not enqueue again:
108
+ // nesting the same queue would make the inner task wait for the outer one.
109
+ const route = (fn) => async (req, res) => {
110
+ res.set('Cache-Control', 'no-store');
111
+ try {
112
+ await fn(req, res);
113
+ } catch (error) {
114
+ const body = error.body || { error: error.message };
115
+ res.status(error.status || 400).json(body);
116
+ }
117
+ };
118
+
119
+ function deny(message, status = 403, body) {
120
+ throw Object.assign(new Error(message), { status, body });
121
+ }
122
+
123
+ function session(req, control = false) {
124
+ const s = sessions.get(req.params.id);
125
+ if (!s) deny('Browser tab no longer exists.', 404);
126
+ if (s.internal) deny('This browser belongs to a pane workspace.', 403);
127
+ if (!human(req)) {
128
+ if (req.get('Authorization') !== 'Bearer ' + s.token) deny('Browser access token required.');
129
+ if (s.permission === 'private' || (control && s.permission !== 'control')) deny('The owner has not granted this browser permission.');
130
+ }
131
+ return s;
132
+ }
133
+
134
+ function address(value) {
135
+ const u = new URL(value);
136
+ if (!['http:', 'https:'].includes(u.protocol) || u.username || u.password) {
137
+ deny('Use an HTTP or HTTPS address without embedded credentials.', 400);
138
+ }
139
+ return u.href;
140
+ }
141
+
142
+ // A popup can fire before its main frame exists; calling popup.url() then
143
+ // throws asynchronously and used to take the whole server down. Never let
144
+ // popup bookkeeping escape the emitter.
145
+ function followPopup(popup, page) {
146
+ void (async () => {
147
+ try {
148
+ await Promise.resolve();
149
+ let popupUrl = '';
150
+ try { popupUrl = popup.url(); } catch (_) { popupUrl = ''; }
151
+ if (!popupUrl || popupUrl === 'about:blank') {
152
+ // window.open('', name) starts blank and is navigated by script a
153
+ // moment later. Wait for the real address before deciding.
154
+ popupUrl = await new Promise((resolve) => {
155
+ const timer = setTimeout(() => {
156
+ try { resolve(popup.url()); } catch (_) { resolve(''); }
157
+ }, 2500);
158
+ const check = () => {
159
+ let candidate = '';
160
+ try { candidate = popup.url(); } catch (_) { /* frame not ready */ }
161
+ if (candidate && candidate !== 'about:blank') {
162
+ clearTimeout(timer);
163
+ resolve(candidate);
164
+ }
165
+ };
166
+ popup.on('framenavigated', check);
167
+ popup.on('load', check);
168
+ popup.once('close', () => { clearTimeout(timer); resolve(''); });
169
+ });
170
+ }
171
+ await popup.close().catch(() => {});
172
+ if (popupUrl && popupUrl !== 'about:blank' && /^https?:/i.test(popupUrl)) {
173
+ await page.goto(address(popupUrl)).catch(() => {});
174
+ }
175
+ } catch (_) {
176
+ try { await popup.close(); } catch (_) { /* already gone */ }
177
+ }
178
+ })();
179
+ }
180
+
181
+ // A JS dialog blocks the page until answered. Keep it open long enough for
182
+ // the human or agent to answer through the UI/API, then dismiss so a forgotten
183
+ // tab cannot stay wedged forever. Never dismiss silently at t=0.
184
+ function attachDialog(s) {
185
+ s.page.on('dialog', (dialog) => {
186
+ clearTimeout(s.dialogTimer);
187
+ s.dialog = {
188
+ id: crypto.randomUUID(),
189
+ type: dialog.type(),
190
+ message: dialog.message(),
191
+ defaultValue: typeof dialog.defaultValue === 'function' ? dialog.defaultValue() : '',
192
+ at: new Date().toISOString()
193
+ };
194
+ s.pendingDialog = dialog;
195
+ s.dialogTimer = setTimeout(async () => {
196
+ if (s.pendingDialog !== dialog) return;
197
+ s.pendingDialog = null;
198
+ s.lastDialog = { ...s.dialog, timedOut: true };
199
+ s.dialog = null;
200
+ try { await dialog.dismiss(); } catch (_) { /* page or dialog already gone */ }
201
+ }, 30000);
202
+ s.dialogTimer.unref?.();
203
+ });
204
+ }
205
+
206
+ async function respondDialog(id, action, text) {
207
+ const s = sessions.get(id);
208
+ if (!s) deny('Browser pane no longer exists.', 404);
209
+ if (!['accept', 'dismiss'].includes(action)) deny('Dialog action must be accept or dismiss.', 400);
210
+ const dialog = s.pendingDialog;
211
+ if (!dialog) deny('No page dialog is waiting for an answer.', 409);
212
+ clearTimeout(s.dialogTimer);
213
+ s.dialogTimer = null;
214
+ s.lastDialog = { ...s.dialog, answered: action, answeredAt: new Date().toISOString() };
215
+ s.pendingDialog = null;
216
+ s.dialog = null;
217
+ try {
218
+ if (action === 'accept') await dialog.accept(typeof text === 'string' ? text : undefined);
219
+ else await dialog.dismiss();
220
+ } catch (error) {
221
+ deny(`The page dialog could not be answered: ${error.message}`, 409);
222
+ }
223
+ return describe(s);
224
+ }
225
+
226
+ // ── Observation bookkeeping ───────────────────────────────────────────────
227
+
228
+ function currentPage(s) {
229
+ return {
230
+ width: s.width,
231
+ height: s.height,
232
+ url: (() => { try { return s.page.url(); } catch (_) { return ''; } })(),
233
+ title: s.title || ''
234
+ };
235
+ }
236
+
237
+ function recordObservation(s, extra = {}) {
238
+ observationCounter += 1;
239
+ const observation = {
240
+ id: observationCounter,
241
+ capturedAt: new Date().toISOString(),
242
+ width: s.width,
243
+ height: s.height,
244
+ scrollX: 0,
245
+ scrollY: 0,
246
+ url: (() => { try { return s.page.url(); } catch (_) { return ''; } })(),
247
+ title: s.title || '',
248
+ revision: s.revision,
249
+ layoutHash: '',
250
+ ...extra
251
+ };
252
+ s.observations.set(observation.id, observation);
253
+ s.observationOrder.push(observation.id);
254
+ while (s.observationOrder.length > MAX_OBSERVATIONS) {
255
+ const evicted = s.observationOrder.shift();
256
+ s.observations.delete(evicted);
257
+ }
258
+ s.lastObservationId = observation.id;
259
+ return observation;
260
+ }
261
+
262
+ function rememberRef(s, descriptor, observationId) {
263
+ s.refRecords.set(descriptor.ref, {
264
+ observationId,
265
+ role: descriptor.role,
266
+ name: descriptor.name,
267
+ tag: descriptor.tag,
268
+ frame: descriptor.frame,
269
+ seenAt: Date.now()
270
+ });
271
+ while (s.refRecords.size > MAX_REF_RECORDS) {
272
+ const oldest = s.refRecords.keys().next();
273
+ if (oldest.done) break;
274
+ s.refRecords.delete(oldest.value);
275
+ }
276
+ }
277
+
278
+ // ── Action helpers ────────────────────────────────────────────────────────
279
+
280
+ function result(status, extra = {}) {
281
+ return {
282
+ ok: status !== STATUS.stale && status !== STATUS.missing && status !== STATUS.failed && status !== STATUS.wrongKind,
283
+ status,
284
+ httpStatus: STATUS_HTTP[status] || 200,
285
+ ...extra
286
+ };
287
+ }
288
+
289
+ function parseKeyCombo(spec) {
290
+ const raw = String(spec || '').trim();
291
+ if (!raw || raw.length > 60) deny('Invalid key name.', 400);
292
+ const parts = raw.split('+').map((part) => part.trim()).filter(Boolean);
293
+ const keyToken = parts.pop();
294
+ if (!keyToken) deny('Invalid key name.', 400);
295
+ const modifiers = { ctrl: false, alt: false, shift: false, meta: false };
296
+ for (const part of parts) {
297
+ const name = part.toLowerCase();
298
+ if (name === 'ctrl' || name === 'control') modifiers.ctrl = true;
299
+ else if (name === 'alt' || name === 'option') modifiers.alt = true;
300
+ else if (name === 'shift') modifiers.shift = true;
301
+ else if (name === 'meta' || name === 'cmd' || name === 'command' || name === 'super') modifiers.meta = true;
302
+ else deny(`Unknown modifier: ${part}`, 400);
303
+ }
304
+ // Puppeteer accepts single characters as-is and named keys in title case.
305
+ const named = {
306
+ enter: 'Enter', return: 'Enter', esc: 'Escape', escape: 'Escape', tab: 'Tab',
307
+ space: ' ', backspace: 'Backspace', delete: 'Delete', insert: 'Insert',
308
+ up: 'ArrowUp', down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight',
309
+ home: 'Home', end: 'End', pageup: 'PageUp', pagedown: 'PageDown'
310
+ };
311
+ const lower = keyToken.toLowerCase();
312
+ let key = named[lower];
313
+ if (!key) {
314
+ if (keyToken.length === 1) key = keyToken;
315
+ else if (/^f\d{1,2}$/i.test(keyToken)) key = keyToken.toUpperCase();
316
+ else key = keyToken;
317
+ }
318
+ return { key, modifiers };
319
+ }
320
+
321
+ async function pressCombo(page, spec) {
322
+ const { key, modifiers } = parseKeyCombo(spec);
323
+ const down = [];
324
+ if (modifiers.ctrl) down.push('Control');
325
+ if (modifiers.alt) down.push('Alt');
326
+ if (modifiers.shift) down.push('Shift');
327
+ if (modifiers.meta) down.push('Meta');
328
+ for (const modifier of down) await page.keyboard.down(modifier);
329
+ try {
330
+ await page.keyboard.press(key);
331
+ } finally {
332
+ for (const modifier of down.reverse()) await page.keyboard.up(modifier);
333
+ }
334
+ }
335
+
336
+ function point(s, data) {
337
+ const x = Number(data.x);
338
+ const y = Number(data.y);
339
+ if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x > s.width || y > s.height) {
340
+ deny('Invalid pointer position.', 400);
341
+ }
342
+ return { x, y };
343
+ }
344
+
345
+ async function targetFromRef(s, ref) {
346
+ if (!ref || typeof ref !== 'string') deny('A ref is required.', 400);
347
+ const handle = await dom.resolveRef(s.page, ref);
348
+ if (!handle) {
349
+ const record = s.refRecords.get(ref);
350
+ const stale = record && record.observationId !== undefined && !s.observations.has(record.observationId);
351
+ return {
352
+ status: STATUS.missing,
353
+ message: stale || !record
354
+ ? `Element ${ref} is not on the page. Look again with a fresh observation.`
355
+ : `Element ${ref} is no longer present.`
356
+ };
357
+ }
358
+ // Identity check: the marker could survive while the node was replaced by a
359
+ // different control in a re-render.
360
+ let current = null;
361
+ try {
362
+ current = await handle.evaluate((node) => ({
363
+ tag: node.tagName ? node.tagName.toLowerCase() : '',
364
+ role: (node.getAttribute && node.getAttribute('role')) || '',
365
+ name: ((node.getAttribute && (node.getAttribute('aria-label') || node.getAttribute('placeholder'))) || '')
366
+ || (node.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 160),
367
+ box: (() => {
368
+ const rect = node.getBoundingClientRect();
369
+ return { x: Math.round(rect.left), y: Math.round(rect.top), width: Math.round(rect.width), height: Math.round(rect.height) };
370
+ })()
371
+ }));
372
+ } catch (_) { current = null; }
373
+ const record = s.refRecords.get(ref);
374
+ // A surviving marker normally means the same node. The tag check catches a
375
+ // cloned or replaced node that inherited the attribute. The label is not
376
+ // compared: text legitimately changes on the same control ("Save" →
377
+ // "Saved") and that is not a stale target.
378
+ const stale = Boolean(record && current && record.tag && current.tag && record.tag !== current.tag);
379
+ return { status: stale ? STATUS.stale : STATUS.completed, handle, current, record };
380
+ }
381
+
382
+ async function assertFreshObservation(s, observationId) {
383
+ const id = Number(observationId);
384
+ if (!Number.isFinite(id)) deny('observation must be a number.', 400);
385
+ const observation = s.observations.get(id);
386
+ if (!observation) {
387
+ deny('That observation is out of date. Look again before clicking.', 409, {
388
+ ok: false,
389
+ status: STATUS.stale,
390
+ code: 'STALE_OBSERVATION',
391
+ message: `Observation ${id} is no longer held. Take a fresh observation and use its numbers.`,
392
+ latestObservationId: s.lastObservationId || null
393
+ });
394
+ }
395
+ const current = await dom.signature(s.page);
396
+ const changed = observation.revision !== s.revision ||
397
+ observation.layoutHash !== current.hash ||
398
+ Math.abs((observation.scrollX || 0) - current.scrollX) > 2 ||
399
+ Math.abs((observation.scrollY || 0) - current.scrollY) > 2;
400
+ if (changed) {
401
+ deny('That target is out of date. Look again before clicking.', 409, {
402
+ ok: false,
403
+ status: STATUS.stale,
404
+ code: 'STALE_OBSERVATION',
405
+ message: 'The page changed since that observation. Look again before clicking, then use the fresh observation\'s numbers.',
406
+ observationId: id,
407
+ latestObservationId: s.lastObservationId || null
408
+ });
409
+ }
410
+ return observation;
411
+ }
412
+
413
+ // ── Sessions ──────────────────────────────────────────────────────────────
414
+
415
+ function initSession(fields) {
416
+ return {
417
+ observations: new Map(),
418
+ observationOrder: [],
419
+ lastObservationId: null,
420
+ refRecords: new Map(),
421
+ nextRef: 0,
422
+ revision: 0,
423
+ sizing: 'fit',
424
+ fixedWidth: 1280,
425
+ fixedHeight: 800,
426
+ queue: Promise.resolve(),
427
+ ...fields
428
+ };
429
+ }
430
+
431
+ function wireSession(s) {
432
+ attachDialog(s);
433
+ s.page.on('popup', (popup) => followPopup(popup, s.page));
434
+ // Any navigation in any frame invalidates coordinate targets, because the
435
+ // layout is no longer the one that was observed.
436
+ s.page.on('framenavigated', () => { s.revision += 1; });
437
+ }
438
+
439
+ // Internal control surface for the pane workspace. These bypass the human
440
+ // header key because the caller already holds the pane workspace token.
441
+ async function createTab(kind = 'agent', url) {
442
+ if (sessions.size + opening >= MAX_BROWSER_TABS) deny('Close a browser pane before opening another.', 409);
443
+ opening++;
444
+ let context;
445
+ let s;
446
+ try {
447
+ context = await (await engine()).createBrowserContext();
448
+ const page = await context.newPage();
449
+ await page.setViewport({ width: 1280, height: 800 });
450
+ s = initSession({
451
+ id: crypto.randomUUID(),
452
+ token: crypto.randomBytes(32).toString('hex'),
453
+ page,
454
+ context,
455
+ kind,
456
+ width: 1280,
457
+ height: 800,
458
+ permission: kind === 'agent' ? 'control' : 'private',
459
+ internal: true
460
+ });
461
+ wireSession(s);
462
+ // Register before navigation. A page that opens a dialog on load would
463
+ // otherwise block goto while the pane is invisible and impossible to
464
+ // answer; the snapshot route can now return the dialog immediately.
465
+ sessions.set(s.id, s);
466
+ page.once('close', () => sessions.delete(s.id));
467
+ if (url) {
468
+ s.navigation = page.goto(address(url), { waitUntil: 'domcontentloaded', timeout: 30000 })
469
+ .then(() => page.title())
470
+ .then((title) => { s.title = title; })
471
+ .catch(() => { /* the snapshot route reports the failure */ });
472
+ } else {
473
+ s.title = await page.title();
474
+ }
475
+ return describe(s);
476
+ } catch (error) {
477
+ if (s) sessions.delete(s.id);
478
+ if (context) await context.close().catch(() => {});
479
+ throw error;
480
+ } finally {
481
+ opening--;
482
+ }
483
+ }
484
+
485
+ async function historyState(s) {
486
+ let client = null;
487
+ try {
488
+ client = await s.page.createCDPSession();
489
+ const history = await client.send('Page.getNavigationHistory');
490
+ return {
491
+ canGoBack: Number(history.currentIndex) > 0,
492
+ canGoForward: Number(history.currentIndex) < (history.entries || []).length - 1
493
+ };
494
+ } catch (_) {
495
+ return { canGoBack: false, canGoForward: false };
496
+ } finally {
497
+ if (client) await client.detach().catch(() => {});
498
+ }
499
+ }
500
+
501
+ async function capture(s) {
502
+ const client = await s.page.createCDPSession();
503
+ try {
504
+ return await client.send('Page.captureScreenshot', { format: 'jpeg', quality: 75, captureBeyondViewport: false }, { timeout: 10000 });
505
+ } finally {
506
+ await client.detach().catch(() => {});
507
+ }
508
+ }
509
+
510
+ async function refreshTitle(s) {
511
+ try { s.title = await s.page.title(); } catch (_) { /* page gone */ }
512
+ }
513
+
514
+ async function snapshotTab(id, options = {}) {
515
+ const s = sessions.get(id);
516
+ if (!s) deny('Browser pane no longer exists.', 404);
517
+ return enqueue(s, async () => {
518
+ // CDP screenshot waits for a JS dialog and times out. Keep the last
519
+ // frame, but return the dialog so the human/agent can answer it.
520
+ if (s.pendingDialog) {
521
+ return {
522
+ ...describe(s),
523
+ ...(await historyState(s)),
524
+ image: null,
525
+ width: s.width,
526
+ height: s.height,
527
+ dialog: s.dialog,
528
+ page: { ...currentPage(s), scrollX: 0, scrollY: 0 }
529
+ };
530
+ }
531
+ await s.page.bringToFront();
532
+ const captureResult = await capture(s);
533
+ await refreshTitle(s);
534
+ // A cheap position read: the full layout signature is only needed when
535
+ // deciding whether a coordinate target is still valid.
536
+ const info = await dom.scrollPosition(s.page);
537
+ return {
538
+ ...describe(s),
539
+ ...(await historyState(s)),
540
+ image: captureResult.data,
541
+ width: s.width,
542
+ height: s.height,
543
+ page: {
544
+ width: s.width,
545
+ height: s.height,
546
+ scrollX: info.scrollX,
547
+ scrollY: info.scrollY,
548
+ url: s.page.url(),
549
+ title: s.title || '',
550
+ capturedAt: new Date().toISOString(),
551
+ revision: s.revision
552
+ },
553
+ ...(options.observation ? { observation: recordObservation(s, { scrollX: info.scrollX, scrollY: info.scrollY, layoutHash: info.hash }) } : {})
554
+ };
555
+ });
556
+ }
557
+
558
+ /**
559
+ * A named observation: screenshot plus a label describing exactly what the
560
+ * agent is looking at, and optionally the controls with stable refs.
561
+ */
562
+ async function observeTab(id, options = {}) {
563
+ const s = sessions.get(id);
564
+ if (!s) deny('Browser pane no longer exists.', 404);
565
+ return enqueue(s, async () => {
566
+ let image = null;
567
+ let history = null;
568
+ if (s.pendingDialog) {
569
+ history = await historyState(s);
570
+ } else {
571
+ await s.page.bringToFront();
572
+ image = (await capture(s)).data;
573
+ history = await historyState(s);
574
+ }
575
+ await refreshTitle(s);
576
+ const info = await dom.signature(s.page);
577
+ const observation = recordObservation(s, {
578
+ scrollX: info.scrollX,
579
+ scrollY: info.scrollY,
580
+ layoutHash: info.hash,
581
+ dialog: s.dialog || null
582
+ });
583
+ const payload = {
584
+ ...describe(s),
585
+ ...(history || {}),
586
+ observation,
587
+ width: s.width,
588
+ height: s.height,
589
+ image,
590
+ dialog: s.dialog || null
591
+ };
592
+ if (options.elements) {
593
+ const catalogued = await dom.catalog(s.page, { max: options.max, start: s.nextRef });
594
+ s.nextRef = Math.max(s.nextRef, catalogued.nextRef);
595
+ for (const element of catalogued.elements) rememberRef(s, element, observation.id);
596
+ payload.elements = catalogued.elements;
597
+ payload.frameCount = catalogued.frameCount;
598
+ payload.truncated = catalogued.elements.length >= Math.max(1, Math.min(500, Number(options.max) || 200));
599
+ }
600
+ return payload;
601
+ });
602
+ }
603
+
604
+ async function elementsTab(id, options = {}) {
605
+ const s = sessions.get(id);
606
+ if (!s) deny('Browser pane no longer exists.', 404);
607
+ return enqueue(s, async () => {
608
+ await refreshTitle(s);
609
+ const info = await dom.signature(s.page);
610
+ const observation = recordObservation(s, {
611
+ scrollX: info.scrollX,
612
+ scrollY: info.scrollY,
613
+ layoutHash: info.hash,
614
+ elementsOnly: true
615
+ });
616
+ const catalogued = await dom.catalog(s.page, { max: options.max, start: s.nextRef });
617
+ s.nextRef = Math.max(s.nextRef, catalogued.nextRef);
618
+ for (const element of catalogued.elements) rememberRef(s, element, observation.id);
619
+ return {
620
+ ...describe(s),
621
+ observation,
622
+ elements: catalogued.elements,
623
+ frameCount: catalogued.frameCount,
624
+ truncated: catalogued.elements.length >= Math.max(1, Math.min(500, Number(options.max) || 200))
625
+ };
626
+ });
627
+ }
628
+
629
+ async function contentTab(id, options = {}) {
630
+ const s = sessions.get(id);
631
+ if (!s) deny('Browser pane no longer exists.', 404);
632
+ return enqueue(s, async () => {
633
+ const info = await dom.content(s.page, options.limit || 200000);
634
+ await refreshTitle(s);
635
+ return {
636
+ ...describe(s),
637
+ text: info.text,
638
+ totalLength: info.totalLength,
639
+ truncated: info.truncated,
640
+ frameCount: info.frameCount,
641
+ frames: info.frames,
642
+ url: info.url || s.page.url(),
643
+ title: s.title || info.title || ''
644
+ };
645
+ });
646
+ }
647
+
648
+ async function navigateTab(id, url) {
649
+ const s = sessions.get(id);
650
+ if (!s) deny('Browser pane no longer exists.', 404);
651
+ return enqueue(s, async () => {
652
+ await s.page.goto(address(url), { waitUntil: 'domcontentloaded', timeout: 20000 });
653
+ // Read the title *after* the navigation. Returning the new address with
654
+ // the previous page's title was the bug reported in the assessment.
655
+ await refreshTitle(s);
656
+ return describe(s);
657
+ });
658
+ }
659
+
660
+ // What is under a coordinate: a select or a date-like input has a value the
661
+ // human UI can offer a native picker for.
662
+ const readControlAt = (p, position) => p.evaluate(({ x, y }) => {
663
+ const el = document.elementFromPoint(x, y);
664
+ if (!el) return null;
665
+ if (el.tagName === 'SELECT') {
666
+ return {
667
+ kind: 'select',
668
+ value: el.value,
669
+ options: Array.from(el.options).map((option) => ({ value: option.value, label: option.textContent || option.value }))
670
+ };
671
+ }
672
+ if (el.tagName === 'INPUT' && ['date', 'color', 'time', 'datetime-local', 'month', 'week'].includes(el.type)) {
673
+ return { kind: el.type, value: el.value };
674
+ }
675
+ return null;
676
+ }, position).catch(() => null);
677
+
678
+ async function readControlValue(handle) {
679
+ if (!handle) return null;
680
+ try {
681
+ return await handle.evaluate((node) => {
682
+ if (!node || !('value' in node)) return null;
683
+ return {
684
+ tag: node.tagName ? node.tagName.toLowerCase() : '',
685
+ type: String(node.type || ''),
686
+ value: String(node.value == null ? '' : node.value).slice(0, 400)
687
+ };
688
+ });
689
+ } catch (_) { return null; }
690
+ }
691
+
692
+ // The body runs inside the session queue so an action cannot interleave with
693
+ // a screenshot or a viewport change on the same page.
694
+ async function performAction(s, action, data = {}) {
695
+ const p = s.page;
696
+ let control = null;
697
+ let target = null;
698
+ let actionStatus = STATUS.completed;
699
+ let message = '';
700
+ let warning = '';
701
+ let handle = null;
702
+
703
+ const resolveTarget = async () => {
704
+ if (data.ref) {
705
+ const resolved = await targetFromRef(s, data.ref);
706
+ if (resolved.status !== STATUS.completed) {
707
+ actionStatus = resolved.status;
708
+ message = resolved.message || '';
709
+ return false;
710
+ }
711
+ handle = resolved.handle;
712
+ target = resolved.current && {
713
+ ref: data.ref,
714
+ role: resolved.current.role || resolved.record?.role,
715
+ name: resolved.record?.name || resolved.current.name,
716
+ box: resolved.current.box
717
+ };
718
+ return true;
719
+ }
720
+ return false;
721
+ };
722
+
723
+ try {
724
+ switch (action) {
725
+ case 'navigate': await p.goto(address(data.url), { waitUntil: 'domcontentloaded', timeout: 20000 }); break;
726
+ case 'back': await p.goBack({ waitUntil: 'domcontentloaded', timeout: 20000 }); break;
727
+ case 'forward': await p.goForward({ waitUntil: 'domcontentloaded', timeout: 20000 }); break;
728
+ case 'reload': await p.reload({ waitUntil: 'domcontentloaded', timeout: 20000 }); break;
729
+ case 'click': {
730
+ if (data.ref) {
731
+ if (await resolveTarget()) {
732
+ if (target && target.box && target.box.width === 0) {
733
+ actionStatus = STATUS.failed; message = 'The target has no clickable area.';
734
+ } else {
735
+ await handle.click({ timeout: 10000 });
736
+ control = await readControlValue(handle);
737
+ }
738
+ }
739
+ } else {
740
+ const position = point(s, data);
741
+ if (data.observationId !== undefined && data.observationId !== null) {
742
+ await assertFreshObservation(s, data.observationId);
743
+ } else {
744
+ warning = 'unverified-position';
745
+ }
746
+ await p.mouse.click(position.x, position.y);
747
+ control = await readControlAt(p, position);
748
+ }
749
+ break;
750
+ }
751
+ case 'hover': {
752
+ if (data.ref) {
753
+ // Stay with the reported status when the ref is gone; do not fall
754
+ // through to a coordinate path that was never supplied.
755
+ if (await resolveTarget()) await handle.hover();
756
+ } else if (data.x !== undefined && data.y !== undefined) {
757
+ const position = point(s, data);
758
+ await p.mouse.move(position.x, position.y);
759
+ } else {
760
+ deny('hover needs a ref or x/y coordinates.', 400);
761
+ }
762
+ break;
763
+ }
764
+ case 'drag': {
765
+ if (!(data.fromRef || data.fromX !== undefined) || !(data.toRef || data.toX !== undefined)) {
766
+ deny('drag needs fromRef/toRef or fromX/toX.', 400);
767
+ }
768
+ let from = null;
769
+ let to = null;
770
+ if (data.fromRef) {
771
+ const resolved = await targetFromRef(s, data.fromRef);
772
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
773
+ from = await resolved.handle.boundingBox();
774
+ } else if (data.fromX !== undefined) {
775
+ from = { x: Number(data.fromX), y: Number(data.fromY), width: 0, height: 0 };
776
+ }
777
+ if (data.toRef) {
778
+ const resolved = await targetFromRef(s, data.toRef);
779
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
780
+ to = await resolved.handle.boundingBox();
781
+ } else if (data.toX !== undefined) {
782
+ to = { x: Number(data.toX), y: Number(data.toY), width: 0, height: 0 };
783
+ }
784
+ if (!from || !to) {
785
+ actionStatus = STATUS.failed;
786
+ message = 'A drag target has no visible area to grab.';
787
+ break;
788
+ }
789
+ await p.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
790
+ await p.mouse.down();
791
+ await p.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 12 });
792
+ await p.mouse.up();
793
+ target = { from: { x: from.x, y: from.y }, to: { x: to.x, y: to.y } };
794
+ break;
795
+ }
796
+ case 'type': {
797
+ const text = String(data.text || '').slice(0, MAX_ACTION_TEXT);
798
+ if (data.ref) {
799
+ const resolved = await targetFromRef(s, data.ref);
800
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
801
+ handle = resolved.handle;
802
+ const kind = resolved.current ? resolved.current.tag : '';
803
+ if (['button', 'a', 'img', 'iframe', 'select', 'option'].includes(kind)) {
804
+ actionStatus = STATUS.wrongKind;
805
+ message = `Element ${data.ref} is a <${kind}>, not a text field.`;
806
+ break;
807
+ }
808
+ await handle.click({ timeout: 10000 });
809
+ if (data.replace) {
810
+ // Select the field's whole content with the DOM API rather than a
811
+ // platform shortcut, then delete it. Appending without clearing
812
+ // was the reported "clearing did not clear" bug.
813
+ await handle.evaluate((node) => {
814
+ if (node && typeof node.focus === 'function') node.focus();
815
+ if (node && typeof node.select === 'function') { node.select(); return; }
816
+ if (node && typeof node.setSelectionRange === 'function' && typeof node.value === 'string') {
817
+ node.setSelectionRange(0, node.value.length);
818
+ return;
819
+ }
820
+ // A contenteditable is a textbox with neither API; select its
821
+ // contents with a Range so Backspace clears all of it.
822
+ if (node && node.isContentEditable) {
823
+ const range = document.createRange();
824
+ range.selectNodeContents(node);
825
+ const selection = window.getSelection();
826
+ if (selection) { selection.removeAllRanges(); selection.addRange(range); }
827
+ }
828
+ });
829
+ await p.keyboard.press('Backspace');
830
+ }
831
+ await p.keyboard.type(text);
832
+ control = await readControlValue(handle);
833
+ target = { ref: data.ref, role: resolved.current?.role, name: resolved.record?.name };
834
+ } else {
835
+ await p.keyboard.type(text);
836
+ }
837
+ break;
838
+ }
839
+ case 'key':
840
+ if (Array.isArray(data.keys)) {
841
+ for (const spec of data.keys.slice(0, 32)) await pressCombo(p, spec);
842
+ } else {
843
+ await pressCombo(p, data.key);
844
+ }
845
+ break;
846
+ case 'scroll': {
847
+ if (data.pointer) {
848
+ // The human viewer's wheel gesture keeps the old pointer-targeted
849
+ // behaviour, so a list or iframe under the cursor scrolls itself.
850
+ const deltaX = Math.max(-1500, Math.min(1500, Number(data.deltaX ?? data.dx) || 0));
851
+ const deltaY = Math.max(-1500, Math.min(1500, Number(data.deltaY ?? data.dy) || 0));
852
+ await p.mouse.wheel({ deltaX, deltaY });
853
+ target = { scroller: 'pointer' };
854
+ } else if (data.ref || data.selector) {
855
+ const scrolled = await dom.scroll(p, {
856
+ marker: data.ref,
857
+ selector: data.selector,
858
+ dx: Math.max(-1500, Math.min(1500, Number(data.deltaX ?? data.dx) || 0)),
859
+ dy: Math.max(-1500, Math.min(1500, Number(data.deltaY ?? data.dy) || 0))
860
+ });
861
+ if (!scrolled.found) {
862
+ actionStatus = scrolled.reason === 'missing' ? STATUS.missing : STATUS.failed;
863
+ message = scrolled.reason === 'missing'
864
+ ? 'The area to scroll was not found.'
865
+ : `The area could not be scrolled: ${scrolled.error || scrolled.reason}`;
866
+ }
867
+ target = { scroller: scrolled.scroller || null, moved: Boolean(scrolled.moved) };
868
+ } else {
869
+ const deltaX = Math.max(-1500, Math.min(1500, Number(data.deltaX ?? data.dx) || 0));
870
+ const deltaY = Math.max(-1500, Math.min(1500, Number(data.deltaY ?? data.dy) || 0));
871
+ if (data.observationId !== undefined && data.observationId !== null) {
872
+ await assertFreshObservation(s, data.observationId);
873
+ }
874
+ // Scroll the page itself, not wherever the invisible pointer last
875
+ // happened to rest.
876
+ await p.mainFrame().evaluate(({ dx, dy }) => {
877
+ const scroller = document.scrollingElement || document.documentElement;
878
+ scroller.scrollBy({ left: dx, top: dy, behavior: 'instant' });
879
+ }, { dx: deltaX, dy: deltaY });
880
+ const info = await dom.scrollPosition(p);
881
+ target = { scroller: 'page', scrollX: info.scrollX, scrollY: info.scrollY };
882
+ }
883
+ break;
884
+ }
885
+ case 'select':
886
+ case 'setValue':
887
+ case 'selectAt':
888
+ case 'setValueAt': {
889
+ if (data.ref) {
890
+ const resolved = await targetFromRef(s, data.ref);
891
+ if (resolved.status !== STATUS.completed) { actionStatus = resolved.status; message = resolved.message || ''; break; }
892
+ handle = resolved.handle;
893
+ const applied = await handle.evaluate((node, value) => {
894
+ if (!node || !('value' in node)) return { ok: false, reason: 'not-a-control' };
895
+ const setter = Object.getOwnPropertyDescriptor(
896
+ node.tagName === 'SELECT' ? window.HTMLSelectElement.prototype : window.HTMLInputElement.prototype,
897
+ 'value'
898
+ );
899
+ // A framework-controlled input ignores a plain assignment; use the
900
+ // native setter so its own change handling sees the update.
901
+ if (node.tagName === 'SELECT') node.value = String(value ?? '');
902
+ else if (setter && setter.set) setter.set.call(node, String(value ?? ''));
903
+ else node.value = String(value ?? '');
904
+ node.dispatchEvent(new Event('input', { bubbles: true }));
905
+ node.dispatchEvent(new Event('change', { bubbles: true }));
906
+ return { ok: true, value: String(node.value ?? '') };
907
+ }, data.value);
908
+ if (!applied.ok) { actionStatus = STATUS.wrongKind; message = 'That element does not hold a value.'; break; }
909
+ control = { value: applied.value };
910
+ } else {
911
+ const position = data.x !== undefined ? point(s, data) : null;
912
+ if (!position) deny('select needs a ref or x/y coordinates.', 400);
913
+ if (data.observationId !== undefined && data.observationId !== null) {
914
+ await assertFreshObservation(s, data.observationId);
915
+ }
916
+ control = await p.evaluate(({ x, y, value }) => {
917
+ const el = document.elementFromPoint(x, y);
918
+ if (!el || (el.tagName !== 'SELECT' && el.tagName !== 'INPUT')) return null;
919
+ el.value = String(value ?? '');
920
+ el.dispatchEvent(new Event('input', { bubbles: true }));
921
+ el.dispatchEvent(new Event('change', { bubbles: true }));
922
+ if (el.tagName === 'SELECT') {
923
+ return {
924
+ kind: 'select',
925
+ value: el.value,
926
+ options: Array.from(el.options).map((option) => ({ value: option.value, label: option.textContent || option.value }))
927
+ };
928
+ }
929
+ return { kind: el.type, value: el.value };
930
+ }, { ...position, value: data.value });
931
+ if (!control) { actionStatus = STATUS.missing; message = 'No select or input at that position.'; }
932
+ }
933
+ break;
934
+ }
935
+ default: deny('Unknown browser action.', 400);
936
+ }
937
+ } catch (error) {
938
+ if (error.status === 409) throw error;
939
+ actionStatus = STATUS.failed;
940
+ message = error.message || String(error);
941
+ }
942
+
943
+ await refreshTitle(s);
944
+ let focus = null;
945
+ try { focus = await dom.focusInfo(p); } catch (_) { focus = null; }
946
+ const described = describe(s);
947
+ const payload = result(actionStatus, {
948
+ ...described,
949
+ // A completed action whose effect the page has not reported yet is
950
+ // honestly labelled unconfirmed rather than assumed to have worked.
951
+ message: message || undefined,
952
+ warning: warning || undefined,
953
+ target: target || undefined,
954
+ control: control || null,
955
+ focused: focus || null,
956
+ observationId: s.lastObservationId || null
957
+ });
958
+ return payload;
959
+ }
960
+
961
+ function actionTab(id, action, data = {}, options = {}) {
962
+ const s = sessions.get(id);
963
+ if (!s) deny('Browser pane no longer exists.', 404);
964
+ return enqueue(s, () => {
965
+ // An action can wait behind a slow navigation or capture. Re-check the
966
+ // caller's grant inside the queue so a revoked token cannot execute a
967
+ // side effect it was authorized for moments earlier.
968
+ if (typeof options.authorize === 'function') options.authorize();
969
+ return performAction(s, action, data);
970
+ });
971
+ }
972
+
973
+ async function waitTab(id, conditions = {}) {
974
+ const s = sessions.get(id);
975
+ if (!s) deny('Browser pane no longer exists.', 404);
976
+ const timeout = Math.max(100, Math.min(120000, Number(conditions.timeout) || 30000));
977
+ const hasUrl = typeof conditions.url === 'string' && conditions.url;
978
+ const hasText = typeof conditions.text === 'string' && conditions.text;
979
+ const hasSelector = typeof conditions.selector === 'string' && conditions.selector;
980
+ const hasValue = typeof conditions.value === 'string' && conditions.ref;
981
+ const hasTitle = typeof conditions.title === 'string' && conditions.title;
982
+ if (!hasUrl && !hasText && !hasSelector && !hasValue && !hasTitle) {
983
+ deny('Provide url, title, text, selector, or value with ref.', 400);
984
+ }
985
+ const started = Date.now();
986
+ const check = async () => {
987
+ const url = (() => { try { return s.page.url(); } catch (_) { return ''; } })();
988
+ // A literal, not a regular expression: an untrusted pattern tested on the
989
+ // event loop can stall every request through catastrophic backtracking.
990
+ if (hasUrl && url.includes(conditions.url)) return { matched: true, reason: 'url' };
991
+ if (hasTitle) {
992
+ const title = await s.page.title().catch(() => '');
993
+ if (title.includes(conditions.title)) return { matched: true, reason: 'title' };
994
+ }
995
+ if (hasSelector) {
996
+ for (const frame of s.page.frames()) {
997
+ let found = false;
998
+ try { found = await frame.evaluate((sel) => Boolean(document.querySelector(sel)), conditions.selector); }
999
+ catch (_) { found = false; }
1000
+ if (found) return { matched: true, reason: 'selector' };
1001
+ }
1002
+ }
1003
+ if (hasText) {
1004
+ const info = await dom.content(s.page, 2000000);
1005
+ if (info.text.includes(conditions.text)) return { matched: true, reason: 'text' };
1006
+ }
1007
+ if (hasValue) {
1008
+ const handle = await dom.resolveRef(s.page, conditions.ref);
1009
+ if (handle) {
1010
+ const value = await handle.evaluate((node) => (node && 'value' in node ? String(node.value) : null)).catch(() => null);
1011
+ if (value === conditions.value) return { matched: true, reason: 'value' };
1012
+ }
1013
+ }
1014
+ return null;
1015
+ };
1016
+ let outcome = null;
1017
+ for (;;) {
1018
+ outcome = await check().catch(() => null);
1019
+ if (outcome) break;
1020
+ if (Date.now() - started >= timeout) break;
1021
+ await new Promise((resolve) => setTimeout(resolve, 150));
1022
+ }
1023
+ await refreshTitle(s);
1024
+ const info = await dom.signature(s.page);
1025
+ return {
1026
+ ok: Boolean(outcome),
1027
+ status: outcome ? STATUS.completed : STATUS.unconfirmed,
1028
+ matched: Boolean(outcome),
1029
+ reason: outcome ? outcome.reason : 'timeout',
1030
+ elapsedMs: Date.now() - started,
1031
+ url: s.page.url(),
1032
+ title: s.title || '',
1033
+ scrollX: info.scrollX,
1034
+ scrollY: info.scrollY,
1035
+ observationId: s.lastObservationId || null
1036
+ };
1037
+ }
1038
+
1039
+ async function sizingTab(id, mode, options = {}) {
1040
+ const s = sessions.get(id);
1041
+ if (!s) deny('Browser pane no longer exists.', 404);
1042
+ if (!['fit', 'fixed'].includes(mode)) deny('Sizing mode must be fit or fixed.', 400);
1043
+ return enqueue(s, async () => {
1044
+ if (mode === 'fixed') {
1045
+ s.sizing = 'fixed';
1046
+ s.fixedWidth = Math.max(320, Math.min(1920, Math.round(Number(options.width) || s.width)));
1047
+ s.fixedHeight = Math.max(240, Math.min(1200, Math.round(Number(options.height) || s.height)));
1048
+ s.width = s.fixedWidth;
1049
+ s.height = s.fixedHeight;
1050
+ await s.page.setViewport({ width: s.width, height: s.height });
1051
+ } else {
1052
+ s.sizing = 'fit';
1053
+ }
1054
+ return { sizing: s.sizing, width: s.width, height: s.height };
1055
+ });
1056
+ }
1057
+
1058
+ async function closeTabInternal(id) {
1059
+ const s = sessions.get(id);
1060
+ if (!s) return false;
1061
+ clearTimeout(s.dialogTimer);
1062
+ sessions.delete(id);
1063
+ await s.context.close();
1064
+ return true;
1065
+ }
1066
+
1067
+ function getTab(id) { return sessions.get(id) || null; }
1068
+
1069
+ async function setViewportTab(id, width, height, options = {}) {
1070
+ const s = sessions.get(id);
1071
+ if (!s) deny('Browser pane no longer exists.', 404);
1072
+ return enqueue(s, async () => {
1073
+ // Fixed-size mode: the owner resizing their viewer must not rearrange the
1074
+ // page. Only an explicit (force) request changes a locked viewport.
1075
+ if (s.sizing === 'fixed' && !options.force) {
1076
+ return { width: s.width, height: s.height, sizing: s.sizing, ignored: true };
1077
+ }
1078
+ s.width = Math.max(320, Math.min(1920, Math.round(Number(width) || 1280)));
1079
+ s.height = Math.max(240, Math.min(1200, Math.round(Number(height) || 800)));
1080
+ await s.page.setViewport({ width: s.width, height: s.height });
1081
+ return { width: s.width, height: s.height, sizing: s.sizing };
1082
+ });
1083
+ }
1084
+
1085
+ // ── Routes ────────────────────────────────────────────────────────────────
1086
+
1087
+ app.get('/api/browser/bootstrap', route(async (req, res) => {
1088
+ if (req.get('Authorization')) deny('Agent tokens cannot manage workspace permissions.');
1089
+ if (!req.isOwner) deny('Owner page required.');
1090
+ const site = req.get('Sec-Fetch-Site');
1091
+ if (site && site !== 'same-origin' && site !== 'none') deny('Owner page required.');
1092
+ res.json({ key: humanKey });
1093
+ }));
1094
+
1095
+ app.get('/api/browser', route(async (req, res) => {
1096
+ if (!human(req)) deny('Workspace access required.');
1097
+ res.json([...sessions.values()].filter((s) => !s.internal).map(describe));
1098
+ }));
1099
+
1100
+ app.post('/api/browser', route(async (req, res) => {
1101
+ if (!human(req)) deny('Only the owner can create browser tabs.');
1102
+ if (sessions.size + opening >= MAX_BROWSER_TABS) deny('Close a tab before opening another.', 409);
1103
+ opening++;
1104
+ let context;
1105
+ let s;
1106
+ try {
1107
+ context = await (await engine()).createBrowserContext();
1108
+ const page = await context.newPage();
1109
+ await page.setViewport({ width: 1280, height: 800 });
1110
+ const kind = req.body.kind === 'agent' ? 'agent' : 'human';
1111
+ s = initSession({
1112
+ id: crypto.randomUUID(),
1113
+ token: crypto.randomBytes(32).toString('hex'),
1114
+ page,
1115
+ context,
1116
+ kind,
1117
+ width: 1280,
1118
+ height: 800,
1119
+ permission: kind === 'agent' ? 'control' : 'private'
1120
+ });
1121
+ wireSession(s);
1122
+ sessions.set(s.id, s);
1123
+ page.once('close', () => sessions.delete(s.id));
1124
+ res.json(describe(s));
1125
+ } catch (error) {
1126
+ if (s) sessions.delete(s.id);
1127
+ if (context) await context.close().catch(() => {});
1128
+ throw error;
1129
+ } finally { opening--; }
1130
+ }));
1131
+
1132
+ app.post('/api/browser/:id/permission', route(async (req, res) => {
1133
+ if (!human(req)) deny('Only the owner can change sharing.');
1134
+ const s = session(req);
1135
+ if (!['private', 'view', 'control'].includes(req.body.permission)) deny('Unknown sharing permission.', 400);
1136
+ s.permission = req.body.permission;
1137
+ s.token = crypto.randomBytes(32).toString('hex'); // Revoke every previous capability.
1138
+ res.json(describe(s));
1139
+ }));
1140
+
1141
+ app.get('/api/browser/:id/access', route(async (req, res) => {
1142
+ if (!human(req)) deny('Only the owner can reveal access.');
1143
+ const s = session(req);
1144
+ if (s.permission === 'private') deny('Choose View or Control before sharing.');
1145
+ res.json({ id: s.id, token: s.token, permission: s.permission, endpoint: '/api/browser/' + s.id });
1146
+ }));
1147
+
1148
+ app.get('/api/browser/:id/snapshot', route(async (req, res) => {
1149
+ session(req); // Permission check before the expensive capture.
1150
+ const snapshot = await snapshotTab(req.params.id);
1151
+ session(req); // Recheck grants after asynchronous work.
1152
+ res.json(snapshot);
1153
+ }));
1154
+
1155
+ app.get('/api/browser/:id/observe', route(async (req, res) => {
1156
+ session(req);
1157
+ const observed = await observeTab(req.params.id, {
1158
+ elements: req.query.elements === '1' || req.query.elements === 'true',
1159
+ max: req.query.max
1160
+ });
1161
+ session(req);
1162
+ res.json(observed);
1163
+ }));
1164
+
1165
+ app.get('/api/browser/:id/elements', route(async (req, res) => {
1166
+ session(req);
1167
+ const catalogued = await elementsTab(req.params.id, { max: req.query.max });
1168
+ session(req);
1169
+ res.json(catalogued);
1170
+ }));
1171
+
1172
+ app.post('/api/browser/:id/viewport', route(async (req, res) => {
1173
+ if (!human(req)) deny('Only the owner can resize the viewer.');
1174
+ session(req);
1175
+ const size = await setViewportTab(req.params.id, req.body.width, req.body.height, { force: req.body.force === true });
1176
+ res.json(size);
1177
+ }));
1178
+
1179
+ app.post('/api/browser/:id/sizing', route(async (req, res) => {
1180
+ session(req, true);
1181
+ res.json(await sizingTab(req.params.id, req.body.mode, req.body));
1182
+ }));
1183
+
1184
+ app.get('/api/browser/:id/content', route(async (req, res) => {
1185
+ session(req);
1186
+ const info = await contentTab(req.params.id, { limit: req.query.limit });
1187
+ session(req);
1188
+ res.json(info);
1189
+ }));
1190
+
1191
+ app.post('/api/browser/:id/action', route(async (req, res) => {
1192
+ session(req, true);
1193
+ const outcome = await actionTab(req.params.id, req.body.action, req.body, {
1194
+ authorize: () => session(req, true)
1195
+ });
1196
+ session(req); // Recheck grants after asynchronous work.
1197
+ res.status(outcome.httpStatus || 200).json(outcome);
1198
+ }));
1199
+
1200
+ app.post('/api/browser/:id/wait', route(async (req, res) => {
1201
+ session(req);
1202
+ res.json(await waitTab(req.params.id, req.body || {}));
1203
+ }));
1204
+
1205
+ app.post('/api/browser/:id/dialog', route(async (req, res) => {
1206
+ if (!human(req)) deny('Only the owner can answer a page dialog.');
1207
+ const s = session(req);
1208
+ res.json(await respondDialog(s.id, req.body.action, req.body.text));
1209
+ }));
1210
+
1211
+ app.delete('/api/browser/:id', route(async (req, res) => {
1212
+ if (!human(req)) deny('Only the owner can close tabs.');
1213
+ const s = session(req);
1214
+ clearTimeout(s.dialogTimer);
1215
+ sessions.delete(s.id);
1216
+ await s.context.close();
1217
+ res.json({ closed: true });
1218
+ }));
1219
+
1220
+ const closeAll = async () => {
1221
+ sessions.clear();
1222
+ if (browserPromise) await (await browserPromise).close();
1223
+ };
1224
+
1225
+ return {
1226
+ closeAll,
1227
+ create: createTab,
1228
+ snapshot: snapshotTab,
1229
+ observe: observeTab,
1230
+ elements: elementsTab,
1231
+ content: contentTab,
1232
+ navigate: navigateTab,
1233
+ action: actionTab,
1234
+ wait: waitTab,
1235
+ sizing: sizingTab,
1236
+ close: closeTabInternal,
1237
+ get: getTab,
1238
+ setViewport: setViewportTab,
1239
+ respondDialog,
1240
+ describe,
1241
+ engineStatus,
1242
+ STATUS
1243
+ };
1244
+ }
1245
+
1246
+ module.exports = { installBrowserWorkspace };