@seekskyworld/open-browser 0.0.0-stage → 0.1.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 (109) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
  3. package/Docs/THIRD-PARTY-NOTICES.md +12 -0
  4. package/Docs/open-browser-api.d.ts +273 -0
  5. package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
  6. package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
  7. package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
  8. package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +36 -0
  9. package/LICENSE +200 -0
  10. package/README.md +150 -2
  11. package/README.zh-CN.md +155 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +151 -0
  14. package/action-execution.mjs +374 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +122 -0
  17. package/browser-extension/icons/open-browser-128.png +0 -0
  18. package/browser-extension/icons/open-browser-16.png +0 -0
  19. package/browser-extension/icons/open-browser-32.png +0 -0
  20. package/browser-extension/icons/open-browser-48.png +0 -0
  21. package/browser-extension/icons/open-browser-wordmark.png +0 -0
  22. package/browser-extension/manifest.json +38 -0
  23. package/browser-extension/newtab.css +20 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +123 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +46 -0
  29. package/browser-extension/popup.js +324 -0
  30. package/browser-extension/tab-action.js +137 -0
  31. package/browser-extension/worker.js +188 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/capability-matrix.mjs +21 -0
  34. package/chromium-host.mjs +149 -0
  35. package/chromium-shell.mjs +150 -0
  36. package/cli.mjs +83 -0
  37. package/contract-validation.mjs +27 -0
  38. package/control.mjs +107 -0
  39. package/desktop/Info.plist +13 -0
  40. package/desktop/Launcher.m +117 -0
  41. package/desktop/OBControlBar.h +7 -0
  42. package/desktop/OBControlBar.m +213 -0
  43. package/desktop/OBPageView.h +6 -0
  44. package/desktop/OBPageView.m +348 -0
  45. package/desktop/WorkspacePanel.h +16 -0
  46. package/desktop/WorkspacePanel.m +915 -0
  47. package/desktop/archive-release.py +129 -0
  48. package/desktop/brand-keychain.py +95 -0
  49. package/desktop/brand-locales.py +93 -0
  50. package/desktop/brand-macos-icons.py +24 -0
  51. package/desktop/brand-windows-icons.mjs +48 -0
  52. package/desktop/build-macos.mjs +96 -0
  53. package/desktop/build-portable.mjs +95 -0
  54. package/desktop/build.mjs +5 -0
  55. package/desktop/create-shortcut.ps1 +9 -0
  56. package/desktop/generate-icons.py +39 -0
  57. package/desktop/icons/open-browser.icns +0 -0
  58. package/desktop/icons/open-browser.ico +0 -0
  59. package/desktop/install-menu-entry.mjs +24 -0
  60. package/desktop/package-assets.mjs +34 -0
  61. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  62. package/desktop/portable-archive.py +22 -0
  63. package/desktop/sign.mjs +33 -0
  64. package/desktop/smoke-portable.mjs +65 -0
  65. package/desktop/start.mjs +12 -0
  66. package/desktop/verify-upgrade.mjs +74 -0
  67. package/desktop/verify-version.mjs +12 -0
  68. package/desktop-page.mjs +211 -0
  69. package/diagnostics.mjs +28 -0
  70. package/downloads.mjs +110 -0
  71. package/engine-service.mjs +1002 -0
  72. package/hosted/README.md +74 -0
  73. package/hosted/cli.mjs +17 -0
  74. package/hosted/directory.mjs +261 -0
  75. package/hosted/init.mjs +37 -0
  76. package/hosted/server.mjs +129 -0
  77. package/managed-popup.mjs +54 -0
  78. package/mcp.mjs +43 -0
  79. package/network-policy.mjs +107 -0
  80. package/output-store.mjs +96 -0
  81. package/package.json +57 -4
  82. package/page-activity.mjs +121 -0
  83. package/page-dialogs.mjs +53 -0
  84. package/page-observation.mjs +280 -0
  85. package/paths.mjs +20 -0
  86. package/privacy-config.mjs +95 -0
  87. package/receipt-store.mjs +191 -0
  88. package/runtime.mjs +44 -0
  89. package/scheduler.mjs +70 -0
  90. package/sdk.mjs +176 -0
  91. package/service.mjs +271 -0
  92. package/site-workflow.mjs +115 -0
  93. package/skills/open-browser/SKILL.md +86 -0
  94. package/skills/open-browser/scripts/bootstrap.mjs +134 -0
  95. package/skills/open-browser/scripts/open-browser +21 -0
  96. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  97. package/skills/open-browser/workflows/login-export.json +10 -0
  98. package/skills/open-browser/workflows/upload-verify.json +8 -0
  99. package/studio/demo-site.mjs +111 -0
  100. package/studio/demo.css +1 -0
  101. package/studio/index.html +66 -0
  102. package/studio/index.mjs +57 -0
  103. package/studio/native-demo.mjs +124 -0
  104. package/studio/studio.css +119 -0
  105. package/studio/studio.js +438 -0
  106. package/uploads.mjs +63 -0
  107. package/visual-page.mjs +306 -0
  108. package/workspace-lifecycle.mjs +170 -0
  109. package/workspace-state.mjs +95 -0
@@ -0,0 +1,107 @@
1
+ import { request as httpClient } from 'playwright-core';
2
+ const passiveResources = new Set(['stylesheet', 'image', 'font', 'media']);
3
+ const blocked = new WeakMap();
4
+
5
+ export function blockedRequests(page) {
6
+ return [...(blocked.get(page)?.values() || [])];
7
+ }
8
+ export function rememberBlock(ws, origin, scope, resourceType, reason) {
9
+ const key = scope + '\n' + origin;
10
+ if (!ws.blockedOrigins.has(key) && ws.blockedOrigins.size === 32)
11
+ ws.blockedOrigins.delete(ws.blockedOrigins.keys().next().value);
12
+ ws.blockedOrigins.set(key, { origin, scope, resourceType, reason });
13
+ }
14
+ function record(page, origin, resourceType, reason) {
15
+ if (!page) return;
16
+ let entries = blocked.get(page);
17
+ if (!entries) { entries = new Map(); blocked.set(page, entries); }
18
+ const key = JSON.stringify([origin, resourceType, reason]);
19
+ if (!entries.has(key) && entries.size === 16) entries.delete(entries.keys().next().value);
20
+ entries.set(key, { origin, resourceType, reason });
21
+ }
22
+
23
+ export async function routeWorkspace(target, ws, shared) {
24
+ if (ws.networkMode === 'browser') return async () => {};
25
+ let released = false;
26
+ let anonymousContext;
27
+ let anonymousContextPromise;
28
+ const getAnonymousContext = async () => {
29
+ anonymousContextPromise ??= httpClient.newContext().then(context => {
30
+ anonymousContext = context;
31
+ return context;
32
+ });
33
+ return anonymousContextPromise;
34
+ };
35
+ async function httpRoute(route) {
36
+ const req = route.request(), type = req.resourceType();
37
+ let response;
38
+ let page;
39
+ try {
40
+ try { page = req.frame().page(); } catch { /* The first popup request may have no frame yet. */ }
41
+ function allowed(url) {
42
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return false;
43
+ return ws.origins.has(url.origin) || (ws.resourceOrigins.has(url.origin) &&
44
+ passiveResources.has(type) && ['GET', 'HEAD'].includes(req.method()));
45
+ }
46
+ async function deny(url, reason) {
47
+ record(page, url.origin, type, reason);
48
+ if (['http:', 'https:'].includes(url.protocol) && !url.username && !url.password) {
49
+ if (type === 'document') rememberBlock(ws, url.origin, 'navigation', type, reason);
50
+ else if (passiveResources.has(type) && ['GET', 'HEAD'].includes(req.method()))
51
+ rememberBlock(ws, url.origin, 'resource', type, reason);
52
+ }
53
+ await route.abort('blockedbyclient');
54
+ }
55
+ const url = new URL(req.url());
56
+ if (!allowed(url)) return await deny(url, 'origin_denied');
57
+ const passiveOnly = !ws.origins.has(url.origin);
58
+ const options = { maxRedirects: 0, timeout: 12000 };
59
+ if (passiveOnly) {
60
+ // An approved stylesheet or image never inherits the profile's cookies or authorization.
61
+ const anonymous = await getAnonymousContext();
62
+ const headers = Object.fromEntries(Object.entries(req.headers()).filter(([key]) => ['accept','range'].includes(key)));
63
+ response = await anonymous.fetch(url.href, {...options,method:req.method(),headers});
64
+ } else response = await route.fetch(options);
65
+ // An attachment requested while the page was managed must not become a
66
+ // personal download if its headers arrive after the workspace ends.
67
+ if ((released || ws.finishing || ws.mode === 'closed') &&
68
+ /^attachment(?:;|$)/i.test(response.headers()['content-disposition']?.trim() || ''))
69
+ return await route.abort('aborted');
70
+ const location = response.headers().location;
71
+ if (location && response.status() >= 300 && response.status() < 400) {
72
+ const next = new URL(location, url);
73
+ if (!allowed(next)) return await deny(next, 'redirect_origin_denied');
74
+ }
75
+ if (passiveOnly) {
76
+ const headers = response.headers();
77
+ delete headers['set-cookie'];
78
+ await route.fulfill({response,headers});
79
+ } else if (type === 'document') {
80
+ const headers = response.headers();
81
+ const sandbox = "sandbox allow-same-origin allow-scripts allow-forms allow-downloads allow-modals allow-pointer-lock " +
82
+ "allow-presentation allow-orientation-lock allow-storage-access-by-user-activation; worker-src 'none'";
83
+ headers['content-security-policy'] = [headers['content-security-policy'], sandbox].filter(Boolean).join(', ');
84
+ await route.fulfill({ response, headers });
85
+ } else await route.fulfill({ response });
86
+ } catch { await route.abort().catch(() => {}); }
87
+ finally { await response?.dispose().catch(() => {}); }
88
+ }
89
+ await target.route('**/*', httpRoute);
90
+ await target.routeWebSocket('**/*', route => {
91
+ if (released) return route.connectToServer();
92
+ const url = new URL(route.url());
93
+ if (!ws.finishing && ws.mode !== 'closed' && !url.username && !url.password &&
94
+ ['ws:', 'wss:'].includes(url.protocol)) {
95
+ url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:';
96
+ if (ws.origins.has(url.origin)) return route.connectToServer();
97
+ }
98
+ return route.close();
99
+ });
100
+ return async () => {
101
+ released = true;
102
+ await target.unroute('**/*', httpRoute);
103
+ await anonymousContextPromise?.catch(() => {});
104
+ await anonymousContext?.dispose().catch(() => {});
105
+ anonymousContext = undefined;
106
+ };
107
+ }
@@ -0,0 +1,96 @@
1
+ import { chmod, copyFile, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+
5
+ const maxReadBytes = 64 * 1024;
6
+ const maxOutputBytes = 128 * 1024 * 1024;
7
+ const retentionMs = 24 * 3600_000;
8
+
9
+ function fail(code) { throw Object.assign(new Error(code), { code }); }
10
+
11
+ function safeId(value) {
12
+ if (typeof value !== 'string' || !/^[0-9a-f-]{36}$/.test(value)) fail('output_not_found');
13
+ return value;
14
+ }
15
+
16
+ function safeWorkspaceId(value) {
17
+ return safeId(value);
18
+ }
19
+
20
+ function safePart(value) {
21
+ if (typeof value !== 'string' || !value.length || value.length > 180 || value === '.' || value === '..' ||
22
+ /[\\/\p{Cc}\p{Bidi_Control}]/u.test(value)) fail('output_not_found');
23
+ return value;
24
+ }
25
+
26
+ export class OutputStore {
27
+ constructor(root) { this.root = root; }
28
+
29
+ directory(workspaceId, outputId) {
30
+ safeWorkspaceId(workspaceId);
31
+ safeId(outputId);
32
+ return path.join(this.root, workspaceId, outputId);
33
+ }
34
+
35
+ async publishFile(workspaceId, source, name, mimeType = 'application/octet-stream') {
36
+ const bytes = (await stat(source)).size;
37
+ if (!Number.isSafeInteger(bytes) || bytes > maxOutputBytes) fail('output_too_large');
38
+ const outputId = randomUUID();
39
+ const directory = this.directory(workspaceId, outputId);
40
+ await mkdir(directory, { recursive: true, mode: 0o700 });
41
+ try {
42
+ const filename = safePart(name);
43
+ const dataPath = path.join(directory, 'part-0');
44
+ await copyFile(source, dataPath);
45
+ await chmod(dataPath, 0o600);
46
+ const manifest = { id: outputId, expiresAt: Date.now() + retentionMs,
47
+ parts: [{ name: filename, mimeType, bytes }] };
48
+ const manifestPath = path.join(directory, 'manifest.json');
49
+ const temporaryManifest = manifestPath + '.' + randomUUID() + '.tmp';
50
+ await writeFile(temporaryManifest, JSON.stringify(manifest) + '\n', { mode: 0o600 });
51
+ await rename(temporaryManifest, manifestPath);
52
+ await chmod(directory, 0o700);
53
+ return manifest;
54
+ } catch (error) {
55
+ await rm(directory, { recursive: true, force: true });
56
+ throw error;
57
+ }
58
+ }
59
+
60
+ async read(workspaceId, outputId, { partName, offset = 0, limit = maxReadBytes } = {}) {
61
+ const directory = this.directory(workspaceId, outputId);
62
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > maxReadBytes)
63
+ fail('invalid_params');
64
+ let manifest;
65
+ try { manifest = JSON.parse(await readFile(path.join(directory, 'manifest.json'), 'utf8')); }
66
+ catch { fail('output_not_found'); }
67
+ if (manifest.expiresAt <= Date.now()) fail('output_expired');
68
+ const part = manifest.parts.find(entry => entry.name === (partName ?? manifest.parts[0]?.name));
69
+ if (!part) fail('output_part_not_found');
70
+ const file = path.join(directory, 'part-0');
71
+ if (offset > part.bytes) fail('invalid_offset');
72
+ const handle = await open(file, 'r');
73
+ const chunk = Buffer.alloc(Math.min(limit, Math.max(0, part.bytes - offset)));
74
+ try { await handle.read(chunk, 0, chunk.length, offset); }
75
+ finally { await handle.close(); }
76
+ const nextOffset = offset + chunk.length < part.bytes ? offset + chunk.length : null;
77
+ return { outputId, part: { ...part }, offset, bytes: chunk.length,
78
+ nextOffset, done: nextOffset === null, data: chunk.toString('base64') };
79
+ }
80
+
81
+ async list(workspaceId) {
82
+ safeWorkspaceId(workspaceId);
83
+ let entries = [];
84
+ for (const outputId of await readdir(path.join(this.root, workspaceId), { withFileTypes: true }).catch(() => [])) {
85
+ if (!outputId.isDirectory()) continue;
86
+ try {
87
+ const manifest = JSON.parse(await readFile(path.join(this.root, workspaceId, outputId.name, 'manifest.json'), 'utf8'));
88
+ if (manifest.expiresAt > Date.now()) entries.push(manifest);
89
+ else await rm(path.join(this.root, workspaceId, outputId.name), { recursive: true, force: true });
90
+ } catch {}
91
+ }
92
+ return entries;
93
+ }
94
+ }
95
+
96
+ export const outputLimits = Object.freeze({ maxReadBytes, maxOutputBytes, retentionMs });
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@seekskyworld/open-browser",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "private": false,
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/seekskyworld/open-browser.git"
10
+ },
11
+ "homepage": "https://github.com/seekskyworld/open-browser#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/seekskyworld/open-browser/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "bin": {
19
+ "open-browser": "cli.mjs",
20
+ "open-browser-mcp": "mcp.mjs",
21
+ "open-browser-skill": "skills/open-browser/scripts/open-browser"
22
+ },
23
+ "exports": {
24
+ ".": "./sdk.mjs",
25
+ "./sdk": "./sdk.mjs",
26
+ "./cli": "./cli.mjs",
27
+ "./mcp": "./mcp.mjs",
28
+ "./skill": "./skills/open-browser/SKILL.md",
29
+ "./api": "./Docs/open-browser-api.d.ts",
30
+ "./package.json": "./package.json"
31
+ },
32
+ "engines": {
33
+ "node": ">=22"
34
+ },
35
+ "scripts": {
36
+ "start": "node desktop/start.mjs",
37
+ "build": "node desktop/build.mjs",
38
+ "cli": "node cli.mjs",
39
+ "mcp": "node mcp.mjs",
40
+ "package:check": "npm pack --dry-run",
41
+ "browser:install": "node runtime.mjs",
42
+ "control": "node control.mjs",
43
+ "test": "npm run test:unit",
44
+ "test:unit": "node --test --test-concurrency=1 *.test.mjs studio/*.test.mjs",
45
+ "test:contract": "node --test --test-concurrency=1 experiments/observe-contract.test.mjs hosted/hosted.test.mjs",
46
+ "test:all": "npm run test:unit && npm run test:contract",
47
+ "test:headed": "OPEN_BROWSER_QA_HEADED=1 node desktop/verify-upgrade.mjs",
48
+ "build:verify": "node desktop/verify-version.mjs && npm run build",
49
+ "clean": "node -e \"import('node:fs/promises').then(({rm}) => Promise.all(['dist','.open-browser'].map(p => rm(p,{recursive:true,force:true}))) )\""
50
+ },
51
+ "dependencies": {
52
+ "@modelcontextprotocol/sdk": "1.32.2",
53
+ "playwright-core": "1.65.1",
54
+ "pngjs": "7.0.0"
55
+ },
56
+ "devDependencies": {
57
+ "resedit": "3.1.1"
58
+ }
59
+ }
@@ -0,0 +1,121 @@
1
+ // Runs in a Chromium isolated world. The page receives only a decorative,
2
+ // input-transparent edge. Control requests stay in the browser toolbar.
3
+ function paintEdge(active, origin) {
4
+ const key = '__openBrowserActivityEdge';
5
+ if (!active || location.origin !== origin) {
6
+ globalThis[key]?.remove();
7
+ delete globalThis[key];
8
+ return;
9
+ }
10
+ if (globalThis[key]?.isConnected || !document.documentElement) return;
11
+ const edge = document.createElement('div');
12
+ edge.setAttribute('aria-hidden', 'true');
13
+ edge.setAttribute('data-open-browser-activity', '');
14
+ edge.inert = true;
15
+ for (const [property, value] of Object.entries({
16
+ all: 'initial', position: 'fixed', inset: '0', 'z-index': '2147483647',
17
+ 'pointer-events': 'none', 'border-radius': '4px',
18
+ 'box-shadow': 'inset 0 0 0 2px #7762e8, inset 0 0 12px 1px rgba(62,159,215,.55)',
19
+ })) edge.style.setProperty(property, value, 'important');
20
+ if (!matchMedia('(prefers-reduced-motion: reduce)').matches)
21
+ edge.animate([{ opacity: .6 }, { opacity: 1 }], { duration: 850, iterations: Infinity, direction: 'alternate' });
22
+ document.documentElement.append(edge);
23
+ globalThis[key] = edge;
24
+ }
25
+
26
+ function paintTarget(x, y, origin) {
27
+ const key = '__openBrowserActionRing';
28
+ globalThis[key]?.remove();
29
+ delete globalThis[key];
30
+ if (origin !== location.origin || !Number.isFinite(x) || !Number.isFinite(y) ||
31
+ x < 0 || y < 0 || x > innerWidth || y > innerHeight || !document.documentElement) return;
32
+ const ring = document.createElement('div');
33
+ ring.inert = true;
34
+ ring.setAttribute('aria-hidden', 'true');
35
+ ring.setAttribute('data-open-browser-target', '');
36
+ for (const [property, value] of Object.entries({
37
+ all: 'initial', position: 'fixed', left: (x - 11) + 'px', top: (y - 11) + 'px',
38
+ width: '18px', height: '18px', border: '2px solid #7659e8', 'border-radius': '50%',
39
+ 'box-shadow': '0 0 0 2px white', 'z-index': '2147483647', 'pointer-events': 'none',
40
+ })) ring.style.setProperty(property, value, 'important');
41
+ document.documentElement.append(ring);
42
+ globalThis[key] = ring;
43
+ if (!matchMedia('(prefers-reduced-motion: reduce)').matches)
44
+ ring.animate([{ transform: 'scale(.75)', opacity: 1 }, { transform: 'scale(1.75)', opacity: 0 }], 460);
45
+ setTimeout(() => { ring.remove(); if (globalThis[key] === ring) delete globalThis[key]; }, 470);
46
+ }
47
+
48
+ async function paint(tab, fn, args, current) {
49
+ if (!current() || tab.page.isClosed() || !/^https?:/.test(tab.page.url())) return;
50
+ const { frameTree } = await tab.session.send('Page.getFrameTree');
51
+ const { executionContextId } = await tab.session.send('Page.createIsolatedWorld', {
52
+ frameId: frameTree.frame.id, worldName: 'open-browser-activity',
53
+ });
54
+ if (!current()) return;
55
+ await tab.session.send('Runtime.evaluate', { contextId: executionContextId,
56
+ expression: '(' + fn.toString() + ')(...' + JSON.stringify(args) + ')' });
57
+ }
58
+
59
+ export function pageActivity() {
60
+ const tabs = new Map();
61
+ function render(tab, origin, force = false) {
62
+ if (!force && tab.origin === origin) return;
63
+ const wasActive = !!tab.origin;
64
+ tab.origin = origin;
65
+ if (!wasActive && !origin) return;
66
+ const revision = ++tab.revision;
67
+ tab.pending = tab.pending.then(() =>
68
+ paint(tab, paintEdge, [Boolean(origin), origin], () => tab.revision === revision)).catch(() => {});
69
+ }
70
+ return {
71
+ track(page, session, workspaceId, pageId) {
72
+ if (tabs.has(pageId)) return;
73
+ const tab = { page, session, workspaceId, origin: null, revision: 0, pending: Promise.resolve() };
74
+ tabs.set(pageId, tab);
75
+ tab.navigation = 0;
76
+ tab.navigated = frame => { if (frame === page.mainFrame()) tab.navigation++; };
77
+ page.on('framenavigated',tab.navigated);
78
+ tab.loaded = () => { if (tab.origin) render(tab, tab.origin, true); };
79
+ page.on('domcontentloaded',tab.loaded);
80
+ tab.closed = () => tabs.delete(pageId);
81
+ page.once('close',tab.closed);
82
+ },
83
+ async release(pageId) {
84
+ const tab = tabs.get(pageId);
85
+ if (!tab) return;
86
+ tabs.delete(pageId);
87
+ tab.mode = 'released';
88
+ tab.generation = null;
89
+ tab.revision++;
90
+ tab.page.off('framenavigated',tab.navigated);
91
+ tab.page.off('domcontentloaded',tab.loaded);
92
+ tab.page.off('close',tab.closed);
93
+ await tab.pending;
94
+ try {
95
+ await paint(tab,paintEdge,[false,null],() => true);
96
+ await paint(tab,paintTarget,[null,null,null],() => true);
97
+ } finally { await tab.session.detach().catch(() => {}); }
98
+ },
99
+ update({ workspaceId, pages, mode, activity, controlGeneration }) {
100
+ const running = new Set((activity.running || [activity.current]).filter(job => mode === 'agent' && job?.state === 'running').map(job => job.pageId));
101
+ for (const [id, tab] of tabs) {
102
+ if (tab.workspaceId !== workspaceId) continue;
103
+ const previous = tab.generation;
104
+ tab.generation = controlGeneration;
105
+ if (previous && previous !== controlGeneration)
106
+ void paint(tab, paintTarget, [null, null, null], () => tab.generation === controlGeneration).catch(() => {});
107
+ tab.mode = mode;
108
+ const origin = running.has(id) && pages.find(page => page.pageId === id)?.origin;
109
+ render(tab, origin && /^https?:/.test(origin) ? origin : null);
110
+ }
111
+ },
112
+ target({ workspaceId, pageId, x, y, origin, controlGeneration }) {
113
+ const tab = tabs.get(pageId);
114
+ if (!tab || tab.workspaceId !== workspaceId) return;
115
+ const navigation = tab.navigation;
116
+ void paint(tab, paintTarget, [x, y, origin], () => tab.generation === controlGeneration &&
117
+ tab.navigation === navigation && tab.mode === 'agent').catch(() => {});
118
+ },
119
+ has(pageId) { return tabs.has(pageId); },
120
+ };
121
+ }
@@ -0,0 +1,53 @@
1
+ import {randomUUID} from 'node:crypto';
2
+
3
+ function fail(code) { throw Object.assign(new Error(code), {code}); }
4
+
5
+ export function attachDialogs(ws, tab, notify) {
6
+ function receive(dialog) {
7
+ const origin = URL.parse(tab.page.url())?.origin;
8
+ const op = [...ws.jobs].find(job => job.pageId === tab.id && job.dispatched);
9
+ // Playwright's Dialog identifies a page, but not the initiating frame.
10
+ // Only attribute a message to this origin if every frame shares it.
11
+ const singleOrigin = tab.page.frames().every(frame => URL.parse(frame.url())?.origin === origin);
12
+ if (!op || tab.dialog || ws.mode !== 'agent' || !ws.origins.has(origin) || !singleOrigin ||
13
+ !['alert','confirm','prompt'].includes(dialog.type())) {
14
+ void dialog.dismiss().catch(() => {});
15
+ return;
16
+ }
17
+ const type = dialog.type();
18
+ let message = dialog.message();
19
+ for (const secret of ws.credentials.values()) message = message.replaceAll(secret, '[redacted]');
20
+ const info = {dialogId:randomUUID(), pageId:tab.id, documentId:tab.documentId, origin,
21
+ operationId:op.receipt.operationId, type, message:message.slice(0,1024)};
22
+ tab.dialog = {dialog, info};
23
+ (op.receipt.dialogIds ??= []).push(info.dialogId);
24
+ notify();
25
+ }
26
+ tab.page.on('dialog',receive);
27
+ return () => {tab.page.off('dialog',receive); discardDialog(tab);};
28
+ }
29
+
30
+ export function discardDialog(tab) {
31
+ const pending = tab.dialog;
32
+ tab.dialog = null;
33
+ if (pending) void pending.dialog.dismiss().catch(() => {});
34
+ }
35
+
36
+ export async function respondDialog(ws,tab,params,desktop) {
37
+ if (ws.generation !== params.controlGeneration) fail('stale_control');
38
+ if (desktop ? !['human','transferring'].includes(ws.mode) : ws.mode !== 'agent')
39
+ fail(desktop ? 'take_control_first' : 'workspace_under_user_control');
40
+ const pending = tab.dialog;
41
+ if (!pending || pending.info.dialogId !== params.dialogId) fail('dialog_not_found');
42
+ if (pending.info.documentId !== tab.documentId || !ws.origins.has(pending.info.origin) ||
43
+ pending.info.origin !== URL.parse(tab.page.url())?.origin) fail('stale_document');
44
+ if (typeof params.accept !== 'boolean' || (params.text !== undefined &&
45
+ (!params.accept || pending.info.type !== 'prompt' || typeof params.text !== 'string' || params.text.length > 2048)))
46
+ fail('invalid_params');
47
+ tab.dialog = null; // Claim before the first await so concurrent replies cannot both reach the site.
48
+ try {
49
+ if (params.accept) await pending.dialog.accept(params.text);
50
+ else await pending.dialog.dismiss();
51
+ } catch { fail('inspect_before_retry'); }
52
+ return {dialogId:params.dialogId, accepted:params.accept};
53
+ }