@seekskyworld/open-browser 0.0.0-stage → 0.2.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 (125) 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 +291 -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 +84 -0
  9. package/LICENSE +200 -0
  10. package/README.md +159 -2
  11. package/README.zh-CN.md +166 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +156 -0
  14. package/action-execution.mjs +385 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +134 -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 +35 -0
  23. package/browser-extension/newtab.css +26 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +174 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +56 -0
  29. package/browser-extension/popup.js +405 -0
  30. package/browser-extension/tab-action.js +138 -0
  31. package/browser-extension/worker.js +281 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/build-profile.mjs +23 -0
  34. package/capability-matrix.mjs +21 -0
  35. package/chromium-host.mjs +209 -0
  36. package/chromium-shell.mjs +179 -0
  37. package/cli.mjs +141 -0
  38. package/contract-validation.mjs +27 -0
  39. package/control.mjs +107 -0
  40. package/desktop/Info.plist +13 -0
  41. package/desktop/Launcher.m +117 -0
  42. package/desktop/OBControlBar.h +7 -0
  43. package/desktop/OBControlBar.m +217 -0
  44. package/desktop/OBPageView.h +6 -0
  45. package/desktop/OBPageView.m +348 -0
  46. package/desktop/WorkspacePanel.h +16 -0
  47. package/desktop/WorkspacePanel.m +916 -0
  48. package/desktop/archive-release.py +129 -0
  49. package/desktop/brand-keychain.py +111 -0
  50. package/desktop/brand-locales.py +93 -0
  51. package/desktop/brand-macos-icons.py +24 -0
  52. package/desktop/brand-windows-icons.mjs +48 -0
  53. package/desktop/build-macos.mjs +112 -0
  54. package/desktop/build-managed-input.mjs +37 -0
  55. package/desktop/build-portable.mjs +95 -0
  56. package/desktop/build-profile.mjs +6 -0
  57. package/desktop/build.mjs +13 -0
  58. package/desktop/create-shortcut.ps1 +9 -0
  59. package/desktop/generate-icons.py +39 -0
  60. package/desktop/icons/open-browser.icns +0 -0
  61. package/desktop/icons/open-browser.ico +0 -0
  62. package/desktop/install-menu-entry.mjs +24 -0
  63. package/desktop/macos-entitlements.plist +12 -0
  64. package/desktop/notarize-macos.mjs +145 -0
  65. package/desktop/package-assets.mjs +34 -0
  66. package/desktop/package-macos.mjs +54 -0
  67. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  68. package/desktop/patches/chromium-managed-input.patch +144 -0
  69. package/desktop/portable-archive.py +22 -0
  70. package/desktop/sign.mjs +77 -0
  71. package/desktop/smoke-portable.mjs +65 -0
  72. package/desktop/start-profile.mjs +5 -0
  73. package/desktop/start.mjs +34 -0
  74. package/desktop/verify-macos-release.mjs +61 -0
  75. package/desktop/verify-upgrade.mjs +74 -0
  76. package/desktop/verify-version.mjs +12 -0
  77. package/desktop-page.mjs +211 -0
  78. package/diagnostics.mjs +37 -0
  79. package/downloads.mjs +110 -0
  80. package/engine-service.mjs +1158 -0
  81. package/hosted/README.md +74 -0
  82. package/hosted/cli.mjs +17 -0
  83. package/hosted/directory.mjs +261 -0
  84. package/hosted/init.mjs +37 -0
  85. package/hosted/server.mjs +129 -0
  86. package/managed-input.mjs +138 -0
  87. package/managed-popup.mjs +54 -0
  88. package/mcp-http.mjs +84 -0
  89. package/mcp-server.mjs +41 -0
  90. package/mcp.mjs +5 -0
  91. package/network-policy.mjs +107 -0
  92. package/output-store.mjs +96 -0
  93. package/package.json +77 -4
  94. package/page-activity.mjs +188 -0
  95. package/page-dialogs.mjs +53 -0
  96. package/page-observation.mjs +318 -0
  97. package/paths.mjs +22 -0
  98. package/privacy-config.mjs +95 -0
  99. package/receipt-store.mjs +198 -0
  100. package/runtime.mjs +53 -0
  101. package/scheduler.mjs +70 -0
  102. package/sdk.mjs +193 -0
  103. package/service.mjs +290 -0
  104. package/site-workflow.mjs +115 -0
  105. package/skill-links.mjs +90 -0
  106. package/skills/open-browser/SKILL.macos.md +112 -0
  107. package/skills/open-browser/SKILL.md +107 -0
  108. package/skills/open-browser/SKILL.windows.md +112 -0
  109. package/skills/open-browser/scripts/bootstrap.mjs +213 -0
  110. package/skills/open-browser/scripts/open-browser +21 -0
  111. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  112. package/skills/open-browser/workflows/login-export.json +10 -0
  113. package/skills/open-browser/workflows/upload-verify.json +8 -0
  114. package/studio/demo-site.mjs +111 -0
  115. package/studio/demo.css +1 -0
  116. package/studio/index.html +66 -0
  117. package/studio/index.mjs +57 -0
  118. package/studio/native-demo.mjs +124 -0
  119. package/studio/studio.css +119 -0
  120. package/studio/studio.js +438 -0
  121. package/tab-adoption.mjs +77 -0
  122. package/uploads.mjs +63 -0
  123. package/visual-page.mjs +306 -0
  124. package/workspace-lifecycle.mjs +238 -0
  125. package/workspace-state.mjs +107 -0
@@ -0,0 +1,65 @@
1
+ import assert from 'node:assert/strict';
2
+ import { spawn } from 'node:child_process';
3
+ import { once } from 'node:events';
4
+ import { mkdtemp, rm } from 'node:fs/promises';
5
+ import { createServer } from 'node:http';
6
+ import { tmpdir } from 'node:os';
7
+ import path from 'node:path';
8
+ import { createInterface } from 'node:readline';
9
+ import { setTimeout as delay } from 'node:timers/promises';
10
+
11
+ if (!process.argv[2]) throw new Error('Expected the extracted open-browser directory.');
12
+ const bundle = path.resolve(process.argv[2]), app = path.join(bundle, 'app');
13
+ const windows = process.platform === 'win32';
14
+ const runtime = path.join(bundle, 'node', windows ? 'node.exe' : 'bin/node');
15
+ const state = await mkdtemp(path.join(tmpdir(), 'ob-package-'));
16
+ const env = { ...process.env, OPEN_BROWSER_STATE_DIR: state };
17
+ delete env.OPEN_BROWSER_CLIENT_TOKEN_FILE;
18
+ const site = createServer((req, res) => {
19
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
20
+ res.end('<title>open-browser test</title><h1>Package smoke test</h1>');
21
+ });
22
+ let service, stopped;
23
+ async function shutdown() {
24
+ service.stdin.end();
25
+ const timeout = setTimeout(() => service.kill('SIGKILL'), 10_000);
26
+ try { return await stopped; } finally { clearTimeout(timeout); }
27
+ }
28
+ async function cli(method, params = {}) {
29
+ const command = spawn(runtime, [path.join(app, 'cli.mjs'), method], { env, cwd: state, stdio: ['pipe', 'pipe', 'inherit'] });
30
+ const exit = once(command, 'close');
31
+ let result = '';
32
+ command.stdout.setEncoding('utf8').on('data', chunk => { result += chunk; });
33
+ command.stdin.end(JSON.stringify(params));
34
+ assert.equal((await exit)[0], 0, method);
35
+ return JSON.parse(result);
36
+ }
37
+ try {
38
+ site.listen(0, '127.0.0.1');
39
+ await once(site, 'listening');
40
+ // The private channel provides readiness and a graceful exit on EOF on both operating systems.
41
+ service = spawn(runtime, [path.join(app, 'service.mjs'), '--chromium', '--headless', '--desktop-bar'], {
42
+ cwd: state, env, stdio: ['pipe', 'pipe', 'inherit'],
43
+ });
44
+ stopped = once(service, 'close');
45
+ const lines = createInterface({ input: service.stdout });
46
+ const controller = new AbortController();
47
+ try {
48
+ await Promise.race([
49
+ (async () => { for await (const line of lines) if (JSON.parse(line).ready) return; throw new Error('Service ended before ready'); })(),
50
+ delay(180_000, null, { signal: controller.signal }).then(() => { throw new Error('Launch timed out'); }),
51
+ ]);
52
+ } finally { controller.abort(); }
53
+ const w = await cli('createWorkspace', { name: 'Portable verification' });
54
+ const page = await cli('openPage', { workspaceId: w.workspaceId, url: 'http://127.0.0.1:' + site.address().port });
55
+ assert.match((await cli('observe', page)).text, /Package smoke test/);
56
+ await cli('closeWorkspace', { workspaceId: w.workspaceId });
57
+ assert.deepEqual(await cli('listWorkspaces'), []);
58
+ assert.equal((await shutdown())[0], 0);
59
+ console.log('Packaged runtime, Chromium, extension bridge, local service and CLI passed.');
60
+ } finally {
61
+ if (service && service.exitCode === null && service.signalCode === null) await shutdown();
62
+ site.closeAllConnections();
63
+ await new Promise(resolve => site.close(resolve));
64
+ await rm(state, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
65
+ }
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ const [profile] = process.argv.slice(2);
3
+ if (!['dev', 'stable'].includes(profile)) throw new Error('usage: start-profile.mjs <dev|stable>');
4
+ process.env.OPEN_BROWSER_BUILD_PROFILE = profile;
5
+ await import('./start.mjs');
@@ -0,0 +1,34 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import net from 'node:net';
5
+ import { pidPath, socketPath } from '../paths.mjs';
6
+ import { isDevelopmentBuild } from '../build-profile.mjs';
7
+
8
+ async function wakeExisting() {
9
+ try {
10
+ const pid = Number(readFileSync(pidPath, 'utf8').trim());
11
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
12
+ process.kill(pid, 0);
13
+ const active = await new Promise(resolve => {
14
+ const probe = net.connect(socketPath);
15
+ probe.once('connect', () => { probe.destroy(); resolve(true); });
16
+ probe.once('error', () => resolve(false));
17
+ });
18
+ if (!active) return false;
19
+ process.kill(pid, 'SIGUSR2');
20
+ return true;
21
+ } catch { return false; }
22
+ }
23
+
24
+ if (await wakeExisting()) process.exit(0);
25
+
26
+ if (process.platform === 'darwin' && !(isDevelopmentBuild && process.env.OPEN_BROWSER_DEV_CHROMIUM)) {
27
+ const bundleName = isDevelopmentBuild ? 'open-browser-dev.app' : process.arch === 'x64' ? 'open-browser-x64.app' : 'open-browser.app';
28
+ const bundle = fileURLToPath(new URL('../dist/' + bundleName, import.meta.url));
29
+ if (!existsSync(bundle)) await import('./build.mjs');
30
+ execFileSync('open', [bundle], { stdio: 'inherit' });
31
+ } else {
32
+ const service = fileURLToPath(new URL('../service.mjs', import.meta.url));
33
+ execFileSync(process.execPath, [service, '--chromium'], { stdio: 'inherit' });
34
+ }
@@ -0,0 +1,61 @@
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { access, readFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const root = fileURLToPath(new URL('../', import.meta.url));
8
+ const defaultApp = path.join(root, 'dist', 'open-browser.app');
9
+
10
+ function commandPath(name, fallback) {
11
+ try {
12
+ return execFileSync('/usr/bin/xcrun', ['--find', name], { encoding: 'utf8' }).trim();
13
+ } catch {
14
+ return fallback;
15
+ }
16
+ }
17
+
18
+ function run(command, args) {
19
+ execFileSync(command, args, { stdio: 'inherit' });
20
+ }
21
+
22
+ async function main() {
23
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
24
+ console.log('用法:node desktop/verify-macos-release.mjs [app-path]');
25
+ return;
26
+ }
27
+ if (process.platform !== 'darwin') throw new Error('macOS 发行验收只能在 macOS 执行。');
28
+ const app = path.resolve(process.argv[2] || process.env.OPEN_BROWSER_APP_PATH || defaultApp);
29
+ await access(app);
30
+ if (!app.endsWith('.app')) throw new Error('验收输入必须是 .app 应用包。');
31
+ run('/usr/bin/codesign', ['--verify', '--strict', '--deep', '--verbose=2', app]);
32
+ const details = spawnSync('/usr/bin/codesign', ['-d', '--verbose=4', app], { encoding: 'utf8' });
33
+ if (details.status !== 0) throw new Error(details.stderr || '无法读取应用签名详情。');
34
+ const signatureDetails = details.stdout + details.stderr;
35
+ if (!/CodeDirectory.*\bruntime\b/.test(signatureDetails))
36
+ throw new Error('应用没有启用 Hardened Runtime。');
37
+ const stapler = commandPath('stapler', '/usr/bin/xcrun');
38
+ run(stapler, stapler === '/usr/bin/xcrun' ? ['stapler', 'validate', app] : ['validate', app]);
39
+ run(commandPath('spctl', '/usr/sbin/spctl'), ['--assess', '--type', 'execute', '--verbose=4', app]);
40
+
41
+ const appArch = app.endsWith('-x64.app') ? 'x64' : app.endsWith('-arm64.app') ? 'arm64' : process.env.OPEN_BROWSER_TARGET_ARCH || process.arch;
42
+ const zip = process.env.OPEN_BROWSER_NOTARY_ZIP || path.join(path.dirname(app), `open-browser-macos-${appArch}.zip`);
43
+ try {
44
+ await access(zip);
45
+ const checksumFile = zip + '.sha256';
46
+ await access(checksumFile);
47
+ const expected = (await readFile(checksumFile, 'utf8')).trim().split(/\s+/)[0];
48
+ const actual = createHash('sha256').update(await readFile(zip)).digest('hex');
49
+ if (expected !== actual) throw new Error(`ZIP SHA-256 不匹配:${zip}`);
50
+ console.log(`${zip}\nSHA-256 ${actual}`);
51
+ } catch (error) {
52
+ if (error?.code === 'ENOENT') throw new Error(`缺少已固化票据的 ZIP 或校验和:${zip}`);
53
+ throw error;
54
+ }
55
+ console.log(`macOS 发行验收通过:${app}`);
56
+ }
57
+
58
+ main().catch(error => {
59
+ console.error(error instanceof Error ? error.message : error);
60
+ process.exitCode = 1;
61
+ });
@@ -0,0 +1,74 @@
1
+ // Run using the new package's Node runtime. Arguments are the prior and candidate package app directories.
2
+ import assert from 'node:assert/strict';
3
+ import { once } from 'node:events';
4
+ import { mkdtemp, rm } from 'node:fs/promises';
5
+ import { createServer } from 'node:http';
6
+ import { tmpdir } from 'node:os';
7
+ import path from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ const [oldApp,newApp] = process.argv.slice(2);
11
+ assert.ok(oldApp && newApp);
12
+ const state = await mkdtemp(path.join(tmpdir(),'open-browser-upgrade-'));
13
+ process.env.OPEN_BROWSER_STATE_DIR = state;
14
+ delete process.env.OPEN_BROWSER_PROFILE;
15
+ delete process.env.OPEN_BROWSER_CLIENT_TOKEN_FILE;
16
+ const site = createServer((req,res) => {
17
+ res.setHeader('content-type','text/html;charset=utf-8');
18
+ if (req.url === '/login') res.setHeader('set-cookie','ticket=fixture-user; Max-Age=1800; Path=/; HttpOnly; SameSite=Lax');
19
+ res.end('<title>Local account</title><p>' + (req.headers.cookie?.includes('ticket=fixture-user') ? 'signed in' : 'welcome') +
20
+ '</p><label>Draft<textarea></textarea></label>');
21
+ });
22
+ site.listen(0,'127.0.0.1'); await once(site,'listening');
23
+ const origin = 'http://127.0.0.1:'+site.address().port;
24
+ const headed = process.env.OPEN_BROWSER_QA_HEADED === '1';
25
+ let app;
26
+ async function launch(dir) {
27
+ const mod = name => pathToFileURL(path.resolve(dir,name)).href;
28
+ const {startApplication} = await import(mod('service.mjs'));
29
+ app = await startApplication({headless:!headed,mode:'chromium'});
30
+ const {OpenBrowserClient} = await import(mod('sdk.mjs'));
31
+ return new OpenBrowserClient();
32
+ }
33
+
34
+ try {
35
+ const previous = await launch(oldApp);
36
+ const {workspaceId} = await previous.createWorkspace({name:'prior release'});
37
+ const page = await previous.openPage(workspaceId,origin+'/login');
38
+ await previous.finishWorkspace(workspaceId,[page.pageId],'prior-delivery');
39
+ await app.close(); app = null;
40
+ const current = await launch(newApp);
41
+ const receipt = await current.getOperation(workspaceId,'prior-delivery');
42
+ assert.equal(receipt.state,'completed');
43
+ assert.deepEqual(receipt.keptPageIds,[page.pageId]);
44
+ const editor = await app.sharedContext.newPage();
45
+ await editor.goto(origin+'/account');
46
+ assert.match(await editor.locator('p').innerText(),/signed in/);
47
+ await editor.bringToFront();
48
+ await editor.locator('textarea').focus();
49
+ const cdp = await app.sharedContext.newCDPSession(editor);
50
+ await cdp.send('Emulation.setFocusEmulationEnabled',{enabled:false});
51
+ await cdp.send('Emulation.setPageScaleFactor',{pageScaleFactor:1.5});
52
+ assert.equal(await editor.evaluate(()=>visualViewport.scale),1.5);
53
+ // Exercise Chromium composition on a real text control, including committing the composition.
54
+ await cdp.send('Input.imeSetComposition',{text:'输入',selectionStart:2,selectionEnd:2});
55
+ await cdp.send('Input.insertText',{text:'输入'});
56
+ const handles = await Promise.all(['left','right'].map(async name => {
57
+ const ws = await current.createWorkspace({name,agentName:name});
58
+ const handle = await current.openPage(ws.workspaceId,origin+'/work');
59
+ const snapshot = await current.observe(handle);
60
+ assert.match(snapshot.text,/signed in/);
61
+ await current.finishWorkspace(ws.workspaceId,[],name+'-done');
62
+ return handle;
63
+ }));
64
+ assert.equal(handles.length,2);
65
+ assert.equal(await editor.locator('textarea').inputValue(),'输入');
66
+ assert.equal(await editor.evaluate(()=>document.activeElement.tagName),'TEXTAREA');
67
+ if (headed) assert.ok(await editor.evaluate(()=>document.hasFocus()),'background tasks must preserve front editor focus');
68
+ console.log(JSON.stringify({platform:process.platform,headed,upgradeLogin:true,priorReceipt:true,
69
+ pageZoom:1.5,chromiumComposition:'committed',backgroundWorkspaces:2}));
70
+ } finally {
71
+ await app?.close();
72
+ site.closeAllConnections(); await new Promise(resolve=>site.close(resolve));
73
+ await rm(state,{recursive:true,force:true,maxRetries:6,retryDelay:200});
74
+ }
@@ -0,0 +1,12 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const root = fileURLToPath(new URL('../', import.meta.url));
6
+ const packageInfo = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
7
+ const manifest = JSON.parse(await readFile(path.join(root, 'browser-extension/manifest.json'), 'utf8'));
8
+ const plist = await readFile(path.join(root, 'desktop/Info.plist'), 'utf8');
9
+ const expected = packageInfo.version;
10
+ if (manifest.version !== expected || !plist.includes(`<key>CFBundleShortVersionString</key><string>${expected}</string>`))
11
+ throw new Error(`Version mismatch. package=${expected}, extension=${manifest.version}`);
12
+ console.log(`open-browser version ${expected} is consistent`);
@@ -0,0 +1,211 @@
1
+ // Native desktop surface. Its pixel stream and input are private host calls.
2
+ function reject(code) { throw Object.assign(new Error(code), { code }); }
3
+
4
+ function checkPage(ws, tab, documentId, generation) {
5
+ if (ws.pages.get(tab.id) !== tab || tab.page.isClosed()) reject('page_not_found');
6
+ if (ws.generation !== generation || !['agent', 'human'].includes(ws.mode)) reject('stale_control');
7
+ if (tab.documentId !== documentId) reject('stale_observation');
8
+ if (!ws.origins.has(URL.parse(tab.page.url())?.origin)) reject('origin_denied');
9
+ }
10
+
11
+ export async function refreshTitle(ws, tab) {
12
+ const { documentId } = tab;
13
+ const url = URL.parse(tab.page.url());
14
+ if (!url || !ws.origins.has(url.origin)) return '';
15
+ const raw = await tab.page.title().catch(() => '');
16
+ if (tab.documentId !== documentId) return '';
17
+ // Some title-less pages supply the address as a title. Hide URL credentials,
18
+ // query strings and fragments in workspace summaries.
19
+ const asUrl = URL.parse(raw);
20
+ const clean = asUrl && ['http:', 'https:'].includes(asUrl.protocol)
21
+ ? asUrl.origin : raw.replace(/(?:https?:\/\/|\/)[^\s?#]*[?#][^\s]*/gi, address =>
22
+ address.split(/[?#]/, 1)[0]).trim().slice(0, 160);
23
+ tab.title = clean;
24
+ return clean;
25
+ }
26
+
27
+ const keyNames = new Set([
28
+ 'Tab', 'Enter', 'Backspace', 'Delete', 'Escape', 'Space', 'Home', 'End',
29
+ 'PageUp', 'PageDown', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight',
30
+ 'Alt', 'Control', 'Meta', 'Shift', 'Insert', 'CapsLock',
31
+ ]);
32
+
33
+ function validateEvent(event) {
34
+ if (!event || typeof event !== 'object' || Array.isArray(event)) reject('invalid_input');
35
+ let fields;
36
+ switch (event.type) {
37
+ case 'mouseMove': case 'mouseDown': case 'mouseUp':
38
+ fields = ['type', 'x', 'y', 'button', 'clickCount'];
39
+ if (event.button !== undefined && !['left', 'right', 'middle'].includes(event.button))
40
+ reject('invalid_input');
41
+ if (event.clickCount !== undefined && ![1, 2, 3].includes(event.clickCount))
42
+ reject('invalid_input');
43
+ break;
44
+ case 'wheel':
45
+ fields = ['type', 'x', 'y', 'deltaX', 'deltaY'];
46
+ if (![event.deltaX, event.deltaY].every(value => Number.isFinite(value) && Math.abs(value) <= 10000))
47
+ reject('invalid_input');
48
+ break;
49
+ case 'text':
50
+ fields = ['type', 'text'];
51
+ if (typeof event.text !== 'string' || !event.text.length || event.text.length > 8192)
52
+ reject('invalid_input');
53
+ break;
54
+ case 'keyDown': case 'keyUp':
55
+ fields = ['type', 'key'];
56
+ if (typeof event.key !== 'string' || !(keyNames.has(event.key) || /^[ -~]$/.test(event.key)
57
+ || /^F(?:[1-9]|1[0-2])$/.test(event.key))) reject('invalid_input');
58
+ break;
59
+ default: reject('invalid_input');
60
+ }
61
+ if (Object.keys(event).some(field => !fields.includes(field))) reject('invalid_input');
62
+ }
63
+
64
+ function navigationKey(held, key) {
65
+ const command = held.has('Meta') || held.has('Control');
66
+ if (key === 'F5' || (command && key.toLowerCase() === 'r')) return 'reload';
67
+ if ((held.has('Meta') && key === '[') || (held.has('Alt') && key === 'ArrowLeft')) return 'back';
68
+ if ((held.has('Meta') && key === ']') || (held.has('Alt') && key === 'ArrowRight')) return 'forward';
69
+ }
70
+
71
+ export async function pageLocation(ws, tab) {
72
+ // CDP reports pushState, redirects, back/forward and in-page navigation from
73
+ // Chromium's real history. The private session closes along with the tab.
74
+ tab.historySession ??= tab.page.context().newCDPSession(tab.page).catch(error => {
75
+ tab.historySession = undefined;
76
+ throw error;
77
+ });
78
+ const session = await tab.historySession;
79
+ const { entries, currentIndex } = await session.send('Page.getNavigationHistory');
80
+ const urlAt = index => {
81
+ const url = URL.parse(entries[index]?.url);
82
+ return url && ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password &&
83
+ ws.origins.has(url.origin) ? url.href : '';
84
+ };
85
+ return { url: urlAt(currentIndex), canGoBack: !!urlAt(currentIndex - 1),
86
+ canGoForward: !!urlAt(currentIndex + 1) };
87
+ }
88
+
89
+ export async function navigatePage(ws, tab, action, url, check) {
90
+ const options = { waitUntil: 'domcontentloaded', timeout: 15000 };
91
+ const { page } = tab;
92
+ if (action === 'go') {
93
+ check();
94
+ await page.goto(url, options);
95
+ } else {
96
+ const location = await pageLocation(ws, tab);
97
+ check();
98
+ if (action === 'back' && location.canGoBack) await page.goBack(options);
99
+ if (action === 'forward' && location.canGoForward) await page.goForward(options);
100
+ if (action === 'reload' && location.url) await page.reload(options);
101
+ }
102
+ return pageLocation(ws, tab);
103
+ }
104
+
105
+ async function dispatch(ws, tab, event, check) {
106
+ const { page } = tab;
107
+ if (event.type === 'text') return page.keyboard.insertText(event.text);
108
+ if (event.type === 'keyDown') {
109
+ const navigation = navigationKey(tab.heldKeys, event.key);
110
+ if (navigation) return navigatePage(ws, tab, navigation, undefined, check);
111
+ tab.heldKeys.add(event.key);
112
+ return page.keyboard.down(event.key);
113
+ }
114
+ if (event.type === 'keyUp') {
115
+ await page.keyboard.up(event.key);
116
+ tab.heldKeys.delete(event.key);
117
+ return;
118
+ }
119
+ const size = page.viewportSize();
120
+ if (!size || !Number.isFinite(event.x) || !Number.isFinite(event.y) ||
121
+ event.x < 0 || event.x >= size.width || event.y < 0 || event.y >= size.height)
122
+ reject('invalid_input');
123
+ await page.mouse.move(event.x, event.y);
124
+ check();
125
+ const button = event.button || 'left';
126
+ const options = { button, clickCount: event.clickCount || 1 };
127
+ switch (event.type) {
128
+ case 'mouseDown':
129
+ tab.heldButtons.add(button);
130
+ return page.mouse.down(options);
131
+ case 'mouseUp':
132
+ await page.mouse.up(options);
133
+ tab.heldButtons.delete(button);
134
+ return;
135
+ case 'wheel': return page.mouse.wheel(event.deltaX, event.deltaY);
136
+ }
137
+ }
138
+
139
+ export async function releaseInput(tab) {
140
+ for (const key of tab.heldKeys) await tab.page.keyboard.up(key).catch(() => {});
141
+ tab.heldKeys.clear();
142
+ for (const button of tab.heldButtons) {
143
+ // Release outside the viewport to avoid activating a link when the native
144
+ // window loses the physical mouse-up event during a control transition.
145
+ await tab.page.mouse.move(-1, -1).catch(() => {});
146
+ await tab.page.mouse.up({ button }).catch(() => {});
147
+ }
148
+ tab.heldButtons.clear();
149
+ }
150
+
151
+ export function enqueueHuman(ws, generation, work) {
152
+ const check = () => {
153
+ if (ws.mode !== 'human') reject('not_in_human_control');
154
+ if (ws.generation !== generation) reject('stale_control');
155
+ };
156
+ check();
157
+ if (ws.inputPending >= 128) reject('queue_full');
158
+ ws.inputPending++;
159
+ const task = ws.inputTail.then(async () => {
160
+ check();
161
+ return work(check);
162
+ }).finally(() => { ws.inputPending--; });
163
+ ws.inputTail = task.catch(() => {});
164
+ return task;
165
+ }
166
+
167
+ export function pageInput(ws, tab, { documentId, controlGeneration, event }) {
168
+ validateEvent(event);
169
+ return enqueueHuman(ws, controlGeneration, async checkOwner => {
170
+ const check = () => {
171
+ checkOwner();
172
+ checkPage(ws, tab, documentId, controlGeneration);
173
+ };
174
+ check();
175
+ await dispatch(ws, tab, event, check);
176
+ return { accepted: true };
177
+ });
178
+ }
179
+
180
+ export class DesktopFrames {
181
+ active = 0;
182
+
183
+ async capture(ws, tab, { width, height }) {
184
+ const { page, documentId } = tab;
185
+ const controlGeneration = ws.generation;
186
+ const check = () => checkPage(ws, tab, documentId, controlGeneration);
187
+ check();
188
+ const current = page.viewportSize();
189
+ width ??= current?.width || 1024;
190
+ height ??= current?.height || 768;
191
+ if (!Number.isInteger(width) || width < 320 || width > 1920 ||
192
+ !Number.isInteger(height) || height < 200 || height > 1200) reject('invalid_viewport');
193
+ if (tab.capturing || this.active >= 3) reject('frame_busy');
194
+ tab.capturing = true;
195
+ this.active++;
196
+ try {
197
+ if (current?.width !== width || current?.height !== height)
198
+ await page.setViewportSize({ width, height });
199
+ check();
200
+ const [jpeg, title] = await Promise.all([
201
+ page.screenshot({ type: 'jpeg', quality: 78, scale: 'css', caret: 'initial', timeout: 3000 }),
202
+ refreshTitle(ws, tab),
203
+ ]);
204
+ check();
205
+ return { data: jpeg.toString('base64'), width, height, documentId, controlGeneration, title };
206
+ } finally {
207
+ tab.capturing = false;
208
+ this.active--;
209
+ }
210
+ }
211
+ }
@@ -0,0 +1,37 @@
1
+ // Export only categories from this table. IDs, URLs, page text and errors can contain user input.
2
+ const advice = new Map([
3
+ ['human_verification_required',['verification','take_control_and_complete_verification']],
4
+ ['target_obscured',['obscured','observe_foreground']],
5
+ ['timeout',['timeout','check_site_result']],
6
+ ['wait_timeout',['timeout','check_site_result']],
7
+ ['workspace_under_user_control',['control_changed','wait_for_user']],
8
+ ['stale_control',['control_changed','observe_after_return']],
9
+ ['operation_cancelled',['cancelled','inspect_progress']],
10
+ ['credential_required',['credential','bind_credential']],
11
+ ['inspect_before_retry',['uncertain','check_site_result']],
12
+ ['run_timeout',['budget','inspect_progress']],
13
+ ['stale_ref',['stale_target','observe_again']],
14
+ ['stale_document',['navigation','observe_again']],
15
+ ['target_missing',['target','observe_again']],
16
+ ['target_ambiguous',['target','narrow_locator']],
17
+ ['origin_denied',['permission','grant_origin']],
18
+ ['invalid_actions',['input','read_schema']],
19
+ ['invalid_params',['input','read_schema']],
20
+ ['browser_action_failed',['browser','observe_again']],
21
+ ['page_not_found',['page','list_workspaces']],
22
+ ['service_restarted',['recovery','inspect_progress']],
23
+ ]);
24
+ const states = new Set(['queued','running','failed','completed','cancelled','outcome_unknown']);
25
+ export function operationDiagnostic(receipt, dispatched) {
26
+ const state = states.has(receipt.state) ? receipt.state : 'unknown';
27
+ let next = advice.get(receipt.error);
28
+ if (state === 'outcome_unknown') next = ['uncertain','check_site_result'];
29
+ if (!next) {
30
+ if (state === 'completed') next = ['completed','verify_site_result'];
31
+ else if (state === 'running' || state === 'queued') next = ['pending','poll_receipt'];
32
+ else next = ['interrupted','inspect_progress'];
33
+ }
34
+ return {version:1, state, ...(receipt.phase && {phase:receipt.phase}), completedSteps:receipt.completedSteps,
35
+ ...(receipt.totalSteps !== undefined && {totalSteps:receipt.totalSteps}), dispatchRecorded:dispatched,
36
+ category:next[0], nextAction:next[1]};
37
+ }
package/downloads.mjs ADDED
@@ -0,0 +1,110 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { chmod, mkdir, rename, rm } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { stateDir } from './paths.mjs';
5
+
6
+ function fail(code) { throw Object.assign(new Error(code), {code}); }
7
+
8
+ function safeName(value) {
9
+ const leaf = value.split(/[\\/]/).at(-1).replace(/[<>:"|?*\p{Cc}\p{Bidi_Control}]/gu,'_').replace(/^[. ]+|[. ]+$/g,'');
10
+ if (!leaf || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(leaf)) return 'download';
11
+ let name = '';
12
+ for (const char of leaf) {
13
+ if (Buffer.byteLength(name + char) > 180) break;
14
+ name += char;
15
+ }
16
+ return name;
17
+ }
18
+
19
+ async function discard(artifact) {
20
+ await artifact.cancel().catch(() => {});
21
+ // Chromium removes incomplete files on cancellation. Playwright.delete()
22
+ // only exposes the path of a successfully completed artifact.
23
+ if (!await artifact.failure()) await artifact.delete();
24
+ }
25
+
26
+ export class WorkspaceDownloads {
27
+ constructor(ws, outputs) {
28
+ this.workspace = ws;
29
+ this.entries = new Map();
30
+ this.closed = false;
31
+ this.outputs = outputs;
32
+ if (!this.outputs) throw new Error('output_store_required');
33
+ }
34
+
35
+ receive(pageId, artifact) {
36
+ const ws = this.workspace;
37
+ const url = URL.parse(artifact.url());
38
+ if (this.closed || ws.finishing || ws.mode === 'closed' || !url || !['http:','https:','blob:'].includes(url.protocol)
39
+ || !ws.origins.has(url.origin) || this.entries.size >= 128) {
40
+ void discard(artifact).catch(() => {});
41
+ return;
42
+ }
43
+ // Playwright has already bound this Download to its Chromium GUID and page.
44
+ // Keep that handle for every cancel/save/delete, including equal filenames.
45
+ const downloadId = randomUUID();
46
+ const info = { downloadId, workspaceId:ws.id, pageId, filename:safeName(artifact.suggestedFilename()), state:'receiving' };
47
+ const entry = { info, artifact };
48
+ this.entries.set(downloadId, entry);
49
+ entry.settled = artifact.failure().then(failure => {
50
+ if (info.state === 'receiving') info.state = failure ? 'failed' : 'ready';
51
+ }, () => { if (info.state === 'receiving') info.state = 'failed'; });
52
+ return downloadId;
53
+ }
54
+
55
+ list() { return [...this.entries.values()].map(entry => ({...entry.info})); }
56
+
57
+ get(id) {
58
+ const entry = this.entries.get(id);
59
+ if (!entry) fail('download_not_found');
60
+ return entry;
61
+ }
62
+
63
+ async cancel(id) {
64
+ const entry = this.get(id);
65
+ if (entry.saving || entry.info.state === 'kept') fail('download_already_kept');
66
+ entry.info.state = 'cancelled';
67
+ entry.discarded ??= discard(entry.artifact);
68
+ await entry.discarded;
69
+ return {...entry.info};
70
+ }
71
+
72
+ async keep(id) {
73
+ const entry = this.get(id);
74
+ if (entry.saving) return entry.saving;
75
+ if (entry.info.state !== 'ready') fail('download_not_ready');
76
+ const directory = path.join(stateDir,'open-browser-deliveries',this.workspace.id,id);
77
+ const destination = path.join(directory,entry.info.filename);
78
+ entry.saving = (async () => {
79
+ const partial = path.join(directory,'.' + randomUUID() + '.part');
80
+ try {
81
+ await mkdir(directory,{recursive:true, mode:0o700});
82
+ await entry.artifact.saveAs(partial);
83
+ await chmod(partial,0o600);
84
+ await rename(partial, destination);
85
+ entry.info.state = 'kept';
86
+ const output = await this.outputs.publishFile(this.workspace.id, destination, entry.info.filename, 'application/octet-stream');
87
+ return {download:{...entry.info},path:destination,output};
88
+ } catch (error) {
89
+ await rm(partial,{force:true});
90
+ entry.saving = undefined;
91
+ throw error;
92
+ }
93
+ })();
94
+ return entry.saving;
95
+ }
96
+
97
+ listOutputs() { return this.outputs.list(this.workspace.id); }
98
+
99
+ readOutput(outputId, params) { return this.outputs.read(this.workspace.id, outputId, params); }
100
+
101
+ async close() {
102
+ this.closed = true;
103
+ await Promise.all([...this.entries.values()].map(async entry => {
104
+ await entry.saving?.catch(() => {});
105
+ await (entry.discarded || discard(entry.artifact));
106
+ await entry.settled;
107
+ }));
108
+ this.entries.clear();
109
+ }
110
+ }