@seekskyworld/open-browser 0.1.0 → 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 (61) hide show
  1. package/Docs/open-browser-api.d.ts +23 -5
  2. 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 +51 -3
  3. package/README.md +14 -5
  4. package/README.zh-CN.md +16 -5
  5. package/access-registry.mjs +5 -0
  6. package/action-execution.mjs +32 -21
  7. package/api-contract.mjs +14 -2
  8. package/browser-extension/manifest.json +1 -4
  9. package/browser-extension/newtab.css +6 -0
  10. package/browser-extension/newtab.js +53 -2
  11. package/browser-extension/phase-labels.js +1 -1
  12. package/browser-extension/popup.css +1 -1
  13. package/browser-extension/popup.html +14 -4
  14. package/browser-extension/popup.js +101 -20
  15. package/browser-extension/tab-action.js +3 -2
  16. package/browser-extension/worker.js +102 -9
  17. package/build-profile.mjs +23 -0
  18. package/capability-matrix.mjs +3 -3
  19. package/chromium-host.mjs +78 -18
  20. package/chromium-shell.mjs +77 -48
  21. package/cli.mjs +59 -1
  22. package/contract-validation.mjs +1 -1
  23. package/desktop/Info.plist +1 -1
  24. package/desktop/OBControlBar.m +7 -3
  25. package/desktop/WorkspacePanel.m +2 -1
  26. package/desktop/brand-keychain.py +20 -4
  27. package/desktop/build-macos.mjs +26 -10
  28. package/desktop/build-managed-input.mjs +37 -0
  29. package/desktop/build-profile.mjs +6 -0
  30. package/desktop/build.mjs +8 -0
  31. package/desktop/macos-entitlements.plist +12 -0
  32. package/desktop/notarize-macos.mjs +145 -0
  33. package/desktop/package-macos.mjs +54 -0
  34. package/desktop/patches/chromium-managed-input.patch +144 -0
  35. package/desktop/sign.mjs +48 -4
  36. package/desktop/start-profile.mjs +5 -0
  37. package/desktop/start.mjs +25 -3
  38. package/desktop/verify-macos-release.mjs +61 -0
  39. package/diagnostics.mjs +9 -0
  40. package/engine-service.mjs +174 -18
  41. package/managed-input.mjs +138 -0
  42. package/mcp-http.mjs +84 -0
  43. package/mcp-server.mjs +41 -0
  44. package/mcp.mjs +2 -40
  45. package/package.json +22 -2
  46. package/page-activity.mjs +95 -28
  47. package/page-observation.mjs +41 -3
  48. package/paths.mjs +5 -3
  49. package/receipt-store.mjs +9 -2
  50. package/runtime.mjs +10 -1
  51. package/sdk.mjs +32 -15
  52. package/service.mjs +21 -2
  53. package/skill-links.mjs +90 -0
  54. package/skills/open-browser/SKILL.macos.md +112 -0
  55. package/skills/open-browser/SKILL.md +24 -3
  56. package/skills/open-browser/SKILL.windows.md +112 -0
  57. package/skills/open-browser/scripts/bootstrap.mjs +80 -1
  58. package/tab-adoption.mjs +77 -0
  59. package/uploads.mjs +4 -4
  60. package/workspace-lifecycle.mjs +74 -6
  61. package/workspace-state.mjs +14 -2
package/mcp-http.mjs ADDED
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+ import { createServer } from 'node:http';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { readFile } from 'node:fs/promises';
5
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
6
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
7
+ import { createMcpServer } from './mcp-server.mjs';
8
+ import { tokenPath } from './paths.mjs';
9
+
10
+ const host = process.env.OPEN_BROWSER_MCP_HTTP_HOST || '127.0.0.1';
11
+ const port = Number(process.env.OPEN_BROWSER_MCP_HTTP_PORT || 9239);
12
+ if (!['127.0.0.1', '::1'].includes(host)) throw new Error('MCP HTTP 只允许绑定回环地址。');
13
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('OPEN_BROWSER_MCP_HTTP_PORT 无效。');
14
+
15
+ async function readToken() {
16
+ const configured = process.env.OPEN_BROWSER_MCP_HTTP_TOKEN?.trim();
17
+ if (configured) return configured;
18
+ try { return (await readFile(tokenPath, 'utf8')).trim(); } catch { return ''; }
19
+ }
20
+
21
+ async function readBody(req) {
22
+ const chunks = [];
23
+ let bytes = 0;
24
+ for await (const chunk of req) {
25
+ bytes += chunk.length;
26
+ if (bytes > 1024 * 1024) throw new Error('request_too_large');
27
+ chunks.push(chunk);
28
+ }
29
+ if (!Buffer.concat(chunks).length) return undefined;
30
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
31
+ }
32
+
33
+ const sessions = new Map();
34
+ const server = createServer(async (req, res) => {
35
+ if (req.url !== '/mcp') { res.writeHead(404).end(); return; }
36
+ const token = await readToken();
37
+ const authorization = req.headers.authorization || '';
38
+ if (!token || authorization !== `Bearer ${token}`) {
39
+ res.writeHead(401, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'unauthorized' }));
40
+ return;
41
+ }
42
+ const sessionId = req.headers['mcp-session-id'];
43
+ if (req.method === 'DELETE') {
44
+ const session = sessions.get(sessionId);
45
+ if (!session) { res.writeHead(404).end(); return; }
46
+ sessions.delete(sessionId);
47
+ await session.transport.close().catch(() => {});
48
+ await session.mcp.close().catch(() => {});
49
+ res.writeHead(204).end();
50
+ return;
51
+ }
52
+ if (!['POST', 'GET'].includes(req.method)) { res.writeHead(405, { allow: 'GET, POST, DELETE' }).end(); return; }
53
+ let body;
54
+ try { body = req.method === 'POST' ? await readBody(req) : undefined; } catch {
55
+ res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'invalid_json' }));
56
+ return;
57
+ }
58
+ let session = sessionId ? sessions.get(sessionId) : undefined;
59
+ if (!session) {
60
+ if (req.method !== 'POST' || !isInitializeRequest(body)) {
61
+ res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'initialize_required' }));
62
+ return;
63
+ }
64
+ const mcp = createMcpServer();
65
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() });
66
+ session = { mcp, transport };
67
+ transport.onclose = () => { if (transport.sessionId) sessions.delete(transport.sessionId); };
68
+ await mcp.connect(transport);
69
+ }
70
+ try {
71
+ await session.transport.handleRequest(req, res, body);
72
+ if (session.transport.sessionId) sessions.set(session.transport.sessionId, session);
73
+ } catch (error) {
74
+ if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'mcp_server_error' }));
75
+ }
76
+ });
77
+
78
+ server.listen(port, host, () => console.error(`open-browser MCP HTTP listening on http://${host}:${port}/mcp`));
79
+ for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => {
80
+ void Promise.all([...sessions.values()].map(async session => {
81
+ await session.transport.close().catch(() => {});
82
+ await session.mcp.close().catch(() => {});
83
+ })).finally(() => server.close(() => process.exit(0)));
84
+ });
package/mcp-server.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } from '@modelcontextprotocol/sdk/types.js';
3
+ import { checkAgentRequest } from './contract-validation.mjs';
4
+ import { OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
5
+ import { tools } from './api-contract.mjs';
6
+
7
+ export function createMcpServer() {
8
+ const server = new Server({ name: 'open-browser', version: '0.2.0' }, { capabilities: { tools: {} } });
9
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
10
+ server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
11
+ let args;
12
+ try {
13
+ const arguments_ = params.arguments ?? {};
14
+ if (['createWorkspace', 'open'].includes(params.name) &&
15
+ (typeof arguments_.name !== 'string' || !arguments_.name.trim()))
16
+ throw new McpError(ErrorCode.InvalidParams, '创建 Agent 任务时必须提供非空任务名称 name。');
17
+ args = checkAgentRequest(params.name, arguments_);
18
+ } catch (error) {
19
+ if (error instanceof McpError) throw error;
20
+ throw new McpError(ErrorCode.InvalidParams, 'Invalid open-browser tool name or arguments');
21
+ }
22
+ try {
23
+ const client = server.getClientVersion();
24
+ const clientName = client?.title?.trim() || client?.name?.trim() || 'MCP';
25
+ const api = new OpenBrowserClient({ agentName: process.env.OPEN_BROWSER_AGENT_NAME?.trim() ||
26
+ Array.from(clientName).slice(0, 80).join('') });
27
+ const result = params.name === 'capabilities' ? await api.capabilities() : await api.call(params.name, args);
28
+ if (params.name === 'captureVisual') {
29
+ const { data, mimeType, ...geometry } = result;
30
+ return { content: [{ type: 'image', mimeType, data }, { type: 'text', text: JSON.stringify(geometry) }] };
31
+ }
32
+ return { content: [{ type: 'text', text: JSON.stringify(result) }] };
33
+ } catch (error) {
34
+ const detail = error instanceof OpenBrowserError
35
+ ? { code: error.code, message: error.message, ...(error.nextAction ? { nextAction: error.nextAction } : {}) }
36
+ : { code: 'CLIENT_ERROR', message: '本地服务调用失败。' };
37
+ return { isError: true, content: [{ type: 'text', text: JSON.stringify(detail) }] };
38
+ }
39
+ });
40
+ return server;
41
+ }
package/mcp.mjs CHANGED
@@ -1,43 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
- import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } from '@modelcontextprotocol/sdk/types.js';
5
- import { checkAgentRequest } from './contract-validation.mjs';
6
- import { OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
7
-
8
- import { tools } from './api-contract.mjs';
9
- const server = new Server({ name: 'open-browser', version: '0.1.0' }, { capabilities: { tools: {} } });
10
-
11
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
12
- server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
13
- let args;
14
- try {
15
- const arguments_ = params.arguments ?? {};
16
- if (['createWorkspace', 'open'].includes(params.name) &&
17
- (typeof arguments_.name !== 'string' || !arguments_.name.trim()))
18
- throw new McpError(ErrorCode.InvalidParams, '创建 Agent 任务时必须提供非空任务名称 name。');
19
- args = checkAgentRequest(params.name, arguments_);
20
- } catch (error) {
21
- if (error instanceof McpError) throw error;
22
- throw new McpError(ErrorCode.InvalidParams, 'Invalid open-browser tool name or arguments');
23
- }
24
- try {
25
- const client = server.getClientVersion();
26
- const clientName = client?.title?.trim() || client?.name?.trim() || 'MCP';
27
- const api = new OpenBrowserClient({ agentName: process.env.OPEN_BROWSER_AGENT_NAME?.trim() ||
28
- Array.from(clientName).slice(0, 80).join('') });
29
- const result = params.name === 'capabilities' ? await api.capabilities() : await api.call(params.name, args);
30
- if (params.name === 'captureVisual') {
31
- const {data,mimeType,...geometry}=result;
32
- return {content:[{type:'image',mimeType,data},{type:'text',text:JSON.stringify(geometry)}]};
33
- }
34
- return { content: [{ type: 'text', text: JSON.stringify(result) }] };
35
- } catch (error) {
36
- const detail = error instanceof OpenBrowserError
37
- ? { code: error.code, message: error.message, ...(error.nextAction ? { nextAction: error.nextAction } : {}) }
38
- : { code: 'CLIENT_ERROR', message: '本地服务调用失败。' };
39
- return { isError: true, content: [{ type: 'text', text: JSON.stringify(detail) }] };
40
- }
41
- });
42
-
3
+ import { createMcpServer } from './mcp-server.mjs';
4
+ const server = createMcpServer();
43
5
  await server.connect(new StdioServerTransport());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seekskyworld/open-browser",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -18,6 +18,7 @@
18
18
  "bin": {
19
19
  "open-browser": "cli.mjs",
20
20
  "open-browser-mcp": "mcp.mjs",
21
+ "open-browser-mcp-http": "mcp-http.mjs",
21
22
  "open-browser-skill": "skills/open-browser/scripts/open-browser"
22
23
  },
23
24
  "exports": {
@@ -34,9 +35,20 @@
34
35
  },
35
36
  "scripts": {
36
37
  "start": "node desktop/start.mjs",
38
+ "start:dev": "node desktop/start-profile.mjs dev",
39
+ "start:stable": "node desktop/start-profile.mjs stable",
37
40
  "build": "node desktop/build.mjs",
41
+ "build:dev": "node desktop/build-profile.mjs dev",
42
+ "build:stable": "node desktop/build-profile.mjs stable",
43
+ "build:macos:x64": "node desktop/build-macos.mjs --arch x64",
44
+ "build:macos:arm64": "node desktop/build-macos.mjs --arch arm64",
45
+ "build:release-macos": "npm run build:stable && node desktop/notarize-macos.mjs",
46
+ "build:release-macos:x64": "npm run build:macos:x64 && node desktop/notarize-macos.mjs dist/open-browser-x64.app --zip dist/open-browser-macos-x64.zip",
47
+ "build:release-macos:arm64": "npm run build:macos:arm64 && node desktop/notarize-macos.mjs dist/open-browser.app --zip dist/open-browser-macos-arm64.zip",
48
+ "release:verify-macos": "node desktop/verify-macos-release.mjs",
38
49
  "cli": "node cli.mjs",
39
50
  "mcp": "node mcp.mjs",
51
+ "mcp:http": "node mcp-http.mjs",
40
52
  "package:check": "npm pack --dry-run",
41
53
  "browser:install": "node runtime.mjs",
42
54
  "control": "node control.mjs",
@@ -46,7 +58,15 @@
46
58
  "test:all": "npm run test:unit && npm run test:contract",
47
59
  "test:headed": "OPEN_BROWSER_QA_HEADED=1 node desktop/verify-upgrade.mjs",
48
60
  "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}))) )\""
61
+ "clean": "node -e \"import('node:fs/promises').then(({rm}) => Promise.all(['dist','.open-browser'].map(p => rm(p,{recursive:true,force:true}))) )\"",
62
+ "package:macos": "npm run build:stable && node desktop/package-macos.mjs --arch arm64 --format both",
63
+ "package:macos:dmg": "npm run build:stable && node desktop/package-macos.mjs --arch arm64 --format dmg",
64
+ "package:macos:arm64": "npm run build:macos:arm64 && node desktop/package-macos.mjs --arch arm64 --format both",
65
+ "package:macos:x64": "npm run build:macos:x64 && node desktop/package-macos.mjs --arch x64 --format both",
66
+ "package:windows:x64": "node desktop/build-portable.mjs win32-x64",
67
+ "package:linux:x64": "node desktop/build-portable.mjs linux-x64",
68
+ "package:portable:all": "npm run package:windows:x64 && npm run package:linux:x64",
69
+ "package:all": "npm run package:macos && npm run package:portable:all"
50
70
  },
51
71
  "dependencies": {
52
72
  "@modelcontextprotocol/sdk": "1.32.2",
package/page-activity.mjs CHANGED
@@ -1,81 +1,142 @@
1
1
  // Runs in a Chromium isolated world. The page receives only a decorative,
2
2
  // input-transparent edge. Control requests stay in the browser toolbar.
3
- function paintEdge(active, origin) {
3
+ function paintEdge(state, origin) {
4
4
  const key = '__openBrowserActivityEdge';
5
- if (!active || location.origin !== origin) {
5
+ if (!state || location.origin !== origin) {
6
6
  globalThis[key]?.remove();
7
7
  delete globalThis[key];
8
8
  return;
9
9
  }
10
- if (globalThis[key]?.isConnected || !document.documentElement) return;
10
+ if (!document.documentElement) return;
11
+ if (globalThis[key]?.isConnected && globalThis[key].dataset.openBrowserActivity === state) return;
12
+ globalThis[key]?.remove();
11
13
  const edge = document.createElement('div');
12
14
  edge.setAttribute('aria-hidden', 'true');
13
- edge.setAttribute('data-open-browser-activity', '');
15
+ edge.setAttribute('data-open-browser-activity', state);
14
16
  edge.inert = true;
15
17
  for (const [property, value] of Object.entries({
16
18
  all: 'initial', position: 'fixed', inset: '0', 'z-index': '2147483647',
17
19
  '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)',
20
+ 'box-shadow': state === 'running' ? 'inset 0 0 0 2px #7762e8, inset 0 0 12px 1px rgba(62,159,215,.55)'
21
+ : 'inset 0 0 0 2px rgba(119,98,232,.55)',
19
22
  })) edge.style.setProperty(property, value, 'important');
20
- if (!matchMedia('(prefers-reduced-motion: reduce)').matches)
23
+ if (state === 'running' && !matchMedia('(prefers-reduced-motion: reduce)').matches)
21
24
  edge.animate([{ opacity: .6 }, { opacity: 1 }], { duration: 850, iterations: Infinity, direction: 'alternate' });
22
25
  document.documentElement.append(edge);
23
26
  globalThis[key] = edge;
24
27
  }
25
28
 
26
- function paintTarget(x, y, origin) {
29
+ function paintTarget(x, y, origin, actionKind = '操作') {
27
30
  const key = '__openBrowserActionRing';
28
31
  globalThis[key]?.remove();
29
32
  delete globalThis[key];
30
33
  if (origin !== location.origin || !Number.isFinite(x) || !Number.isFinite(y) ||
31
- x < 0 || y < 0 || x > innerWidth || y > innerHeight || !document.documentElement) return;
34
+ x < 0 || y < 0 || x > innerWidth || y > innerHeight || !document.documentElement) {
35
+ globalThis.__openBrowserAgentCursor?.remove();
36
+ delete globalThis.__openBrowserAgentCursor;
37
+ return;
38
+ }
32
39
  const ring = document.createElement('div');
33
40
  ring.inert = true;
34
41
  ring.setAttribute('aria-hidden', 'true');
35
42
  ring.setAttribute('data-open-browser-target', '');
43
+ const actionLabels = { click: '点击', doubleClick: '双击', hover: '悬停', press: '按键',
44
+ scroll: '滚动', drag: '拖拽', fill: '填写', fillCredential: '填写凭据', select: '选择',
45
+ upload: '上传', setChecked: '切换' };
36
46
  for (const [property, value] of Object.entries({
37
47
  all: 'initial', position: 'fixed', left: (x - 11) + 'px', top: (y - 11) + 'px',
38
48
  width: '18px', height: '18px', border: '2px solid #7659e8', 'border-radius': '50%',
39
49
  'box-shadow': '0 0 0 2px white', 'z-index': '2147483647', 'pointer-events': 'none',
40
50
  })) ring.style.setProperty(property, value, 'important');
51
+ let cursor = globalThis.__openBrowserAgentCursor;
52
+ if (!cursor?.isConnected || cursor.children.length !== 2) {
53
+ cursor?.remove();
54
+ cursor = document.createElement('div');
55
+ cursor.inert = true;
56
+ cursor.setAttribute('aria-hidden', 'true');
57
+ cursor.setAttribute('data-open-browser-agent-cursor', '');
58
+ const arrow = document.createElement('span'), label = document.createElement('span');
59
+ const style = (node, properties) => {
60
+ for (const [property, value] of Object.entries(properties)) node.style.setProperty(property, value, 'important');
61
+ };
62
+ style(cursor, { all: 'initial', position: 'fixed', width: '18px', height: '24px',
63
+ 'z-index': '2147483647', 'pointer-events': 'none',
64
+ transition: matchMedia('(prefers-reduced-motion: reduce)').matches ? 'none' : 'left 140ms ease, top 140ms ease' });
65
+ style(arrow, { all: 'initial', display: 'block', width: '18px', height: '24px', background: '#7659e8',
66
+ 'clip-path': 'polygon(0 0, 0 100%, 30% 72%, 48% 100%, 60% 94%, 43% 66%, 86% 66%)', 'pointer-events': 'none' });
67
+ style(label, { all: 'initial', display: 'block', position: 'absolute', padding: '3px 7px',
68
+ color: 'white', background: 'rgba(45,35,90,.92)', 'border-radius': '5px',
69
+ font: '12px/1.2 -apple-system,BlinkMacSystemFont,sans-serif', 'white-space': 'nowrap', 'pointer-events': 'none' });
70
+ cursor.append(arrow, label);
71
+ document.documentElement.append(cursor);
72
+ globalThis.__openBrowserAgentCursor = cursor;
73
+ }
74
+ cursor.style.setProperty('left', x + 'px', 'important');
75
+ cursor.style.setProperty('top', y + 'px', 'important');
76
+ const label = cursor.lastElementChild;
77
+ label.textContent = 'Agent · ' + (actionLabels[actionKind] || '操作');
78
+ label.style.setProperty('left', x + 120 > innerWidth ? 'auto' : '12px', 'important');
79
+ label.style.setProperty('right', x + 120 > innerWidth ? '18px' : 'auto', 'important');
80
+ label.style.setProperty('top', y + 40 > innerHeight ? '-22px' : '10px', 'important');
41
81
  document.documentElement.append(ring);
42
82
  globalThis[key] = ring;
43
83
  if (!matchMedia('(prefers-reduced-motion: reduce)').matches)
44
84
  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);
85
+ setTimeout(() => {
86
+ ring.remove();
87
+ if (globalThis[key] === ring) delete globalThis[key];
88
+ }, 470);
46
89
  }
47
90
 
48
- async function paint(tab, fn, args, current) {
91
+ async function paint(tab, fn, args, current, retry = true) {
49
92
  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
- });
93
+ let executionContextId = tab.context?.navigation === tab.navigation ? tab.context.id : undefined;
94
+ if (!executionContextId) {
95
+ const navigation = tab.navigation;
96
+ const { frameTree } = await tab.session.send('Page.getFrameTree');
97
+ const created = await tab.session.send('Page.createIsolatedWorld', {
98
+ frameId: frameTree.frame.id, worldName: 'open-browser-activity',
99
+ });
100
+ executionContextId = created.executionContextId;
101
+ if (navigation !== tab.navigation || !current()) return;
102
+ tab.context = { navigation, id: executionContextId };
103
+ }
54
104
  if (!current()) return;
55
- await tab.session.send('Runtime.evaluate', { contextId: executionContextId,
56
- expression: '(' + fn.toString() + ')(...' + JSON.stringify(args) + ')' });
105
+ try {
106
+ await tab.session.send('Runtime.evaluate', { contextId: executionContextId,
107
+ expression: '(' + fn.toString() + ')(...' + JSON.stringify(args) + ')' });
108
+ } catch (error) {
109
+ if (tab.context?.id === executionContextId && /context|execution|target/i.test(error.message)) {
110
+ tab.context = undefined;
111
+ if (retry) return paint(tab, fn, args, current, false);
112
+ }
113
+ throw error;
114
+ }
57
115
  }
58
116
 
59
117
  export function pageActivity() {
60
118
  const tabs = new Map();
61
- function render(tab, origin, force = false) {
62
- if (!force && tab.origin === origin) return;
119
+ function render(tab, origin, state, force = false) {
120
+ if (!force && tab.origin === origin && tab.edgeState === state) return;
63
121
  const wasActive = !!tab.origin;
64
122
  tab.origin = origin;
123
+ tab.edgeState = state;
65
124
  if (!wasActive && !origin) return;
66
125
  const revision = ++tab.revision;
67
126
  tab.pending = tab.pending.then(() =>
68
- paint(tab, paintEdge, [Boolean(origin), origin], () => tab.revision === revision)).catch(() => {});
127
+ paint(tab, paintEdge, [state, origin], () => tab.revision === revision)
128
+ .then(() => { if (state !== 'running') return paint(tab, paintTarget, [null, null, null], () => tab.revision === revision); })
129
+ .catch(() => {}));
69
130
  }
70
131
  return {
71
132
  track(page, session, workspaceId, pageId) {
72
133
  if (tabs.has(pageId)) return;
73
- const tab = { page, session, workspaceId, origin: null, revision: 0, pending: Promise.resolve() };
134
+ const tab = { page, session, workspaceId, origin: null, revision: 0, targetRevision: 0, pending: Promise.resolve() };
74
135
  tabs.set(pageId, tab);
75
136
  tab.navigation = 0;
76
- tab.navigated = frame => { if (frame === page.mainFrame()) tab.navigation++; };
137
+ tab.navigated = frame => { if (frame === page.mainFrame()) { tab.navigation++; tab.context = undefined; } };
77
138
  page.on('framenavigated',tab.navigated);
78
- tab.loaded = () => { if (tab.origin) render(tab, tab.origin, true); };
139
+ tab.loaded = () => { if (tab.origin) render(tab, tab.origin, tab.edgeState, true); };
79
140
  page.on('domcontentloaded',tab.loaded);
80
141
  tab.closed = () => tabs.delete(pageId);
81
142
  page.once('close',tab.closed);
@@ -87,6 +148,7 @@ export function pageActivity() {
87
148
  tab.mode = 'released';
88
149
  tab.generation = null;
89
150
  tab.revision++;
151
+ tab.context = undefined;
90
152
  tab.page.off('framenavigated',tab.navigated);
91
153
  tab.page.off('domcontentloaded',tab.loaded);
92
154
  tab.page.off('close',tab.closed);
@@ -103,18 +165,23 @@ export function pageActivity() {
103
165
  const previous = tab.generation;
104
166
  tab.generation = controlGeneration;
105
167
  if (previous && previous !== controlGeneration)
106
- void paint(tab, paintTarget, [null, null, null], () => tab.generation === controlGeneration).catch(() => {});
168
+ tab.pending = tab.pending.then(() => paint(tab, paintTarget, [null, null, null],
169
+ () => tab.generation === controlGeneration)).catch(() => {});
107
170
  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);
171
+ const page = pages.find(page => page.pageId === id);
172
+ const origin = mode === 'agent' && /^https?:/.test(page?.origin) ? page.origin : null;
173
+ const state = origin ? (running.has(id) ? 'running' : 'idle') : null;
174
+ render(tab, origin, state);
110
175
  }
111
176
  },
112
- target({ workspaceId, pageId, x, y, origin, controlGeneration }) {
177
+ target({ workspaceId, pageId, x, y, origin, controlGeneration, actionKind }) {
113
178
  const tab = tabs.get(pageId);
114
179
  if (!tab || tab.workspaceId !== workspaceId) return;
115
180
  const navigation = tab.navigation;
116
- void paint(tab, paintTarget, [x, y, origin], () => tab.generation === controlGeneration &&
117
- tab.navigation === navigation && tab.mode === 'agent').catch(() => {});
181
+ const ticket = ++tab.targetRevision;
182
+ tab.pending = tab.pending.then(() => paint(tab, paintTarget, [x, y, origin, actionKind], () =>
183
+ tab.generation === controlGeneration && tab.navigation === navigation && tab.mode === 'agent' &&
184
+ tab.origin === origin && tab.edgeState === 'running' && tab.targetRevision === ticket)).catch(() => {});
118
185
  },
119
186
  has(pageId) { return tabs.has(pageId); },
120
187
  };
@@ -74,6 +74,36 @@ export function inspectDocument(options = {}) {
74
74
  foreground={role:front.getAttribute('role') || 'dialog',name:(label || front.getAttribute('aria-label') || '').slice(0,160),
75
75
  bounds:{x,y,width,height}};
76
76
  }
77
+ if (options.canvas) {
78
+ const root = front || document;
79
+ let truncated = false;
80
+ const rows = (selector, describe) => {
81
+ const result = [];
82
+ for (const el of root.querySelectorAll(selector)) {
83
+ if (!visible(el) || composedMatch(el, 'input,textarea,select,[contenteditable]')) continue;
84
+ if (result.length >= 100) { truncated = true; break; }
85
+ result.push(describe(el));
86
+ }
87
+ return result;
88
+ };
89
+ const label = el => visibleText(el, 512) || (el.getAttribute('aria-label') || '').slice(0, 512);
90
+ const nodeRows = rows('.react-flow__node', el => ({
91
+ id:(el.getAttribute('data-id') || '').slice(0,128), label:label(el), selected:el.classList.contains('selected')
92
+ }));
93
+ const edges = rows('.react-flow__edge', el => {
94
+ const accessibleLabel = (el.getAttribute('aria-label') || '').slice(0,512);
95
+ const endpoints = /^Edge from (\S+) to (\S+)$/.exec(accessibleLabel);
96
+ return {id:(el.getAttribute('data-id') || '').slice(0,128), label:accessibleLabel || label(el),
97
+ selected:el.classList.contains('selected'), ...(endpoints && {source:endpoints[1],target:endpoints[2]})};
98
+ });
99
+ const messages = rows('[data-message-author-role], [role="log"] > [role="article"]', el => ({
100
+ role:['user','assistant','system','tool'].includes(el.dataset.messageAuthorRole) ? el.dataset.messageAuthorRole : 'message',
101
+ text:label(el)
102
+ }));
103
+ const attachments = rows('a[download]', el => ({label:label(el)}));
104
+ return {adapter:root.querySelector('.react-flow') ? 'react-flow' : messages.length ? 'chat' : 'unsupported',
105
+ nodes:nodeRows, edges, messages, attachments, truncated};
106
+ }
77
107
  const nodes=[],details=[];
78
108
  function stateOf(el) {
79
109
  const state = {};
@@ -245,10 +275,18 @@ export async function observeFrames(page, origins, redact, padding=0) {
245
275
  let remaining = 8000;
246
276
  // Direct visible child frames only. A blank or opaque sandbox has no
247
277
  // explicit HTTP(S) origin. No cross-frame action handles leave this helper.
248
- for (const frame of page.mainFrame().childFrames().slice(0, 16)) {
249
- if (!remaining || !origins.has(URL.parse(frame.url())?.origin)) continue;
278
+ const candidates = page.mainFrame().childFrames().slice(0, 16)
279
+ .filter(frame => origins.has(URL.parse(frame.url())?.origin));
280
+ const allowed = (await Promise.all(candidates.map(async frame => {
281
+ try { return await frameAllowed(frame, origins) ? frame : null; }
282
+ catch (error) {
283
+ if (!frame.isDetached() && !/context was destroyed|navigat/i.test(error.message)) throw error;
284
+ return null;
285
+ }
286
+ }))).filter(Boolean);
287
+ for (const frame of allowed) {
288
+ if (!remaining) break;
250
289
  try {
251
- if (!(await frameAllowed(frame,origins))) continue;
252
290
  const data=await frame.evaluate(inspectDocument,{textOnly:true,origins:[...origins],textLimit:remaining,padding});
253
291
  if (data && origins.has(data.origin) && URL.parse(frame.url())?.origin === data.origin) {
254
292
  const text = redact(data.text,data.textWindowInfo);
package/paths.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { homedir } from 'node:os';
3
3
  import path from 'node:path';
4
+ import { buildProfile, scopedBuildRoot } from './build-profile.mjs';
4
5
 
5
6
  export const profileId = process.env.OPEN_BROWSER_PROFILE || 'default';
6
- const base = path.resolve(process.env.OPEN_BROWSER_STATE_DIR || path.join(homedir(), '.open-browser'));
7
+ const base = scopedBuildRoot(path.resolve(process.env.OPEN_BROWSER_STATE_DIR || path.join(homedir(), '.open-browser')));
7
8
 
8
9
  export function pathsForProfile(id) {
9
10
  if (typeof id !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,47}$/.test(id)) throw new Error('invalid_profile');
@@ -13,8 +14,9 @@ export function pathsForProfile(id) {
13
14
  const socketPath = process.platform === 'win32'
14
15
  ? '\\\\.\\pipe\\open-browser-' + instance
15
16
  : Buffer.byteLength(socketFile) < 100 ? socketFile : path.join('/tmp', 'open-browser-' + process.getuid() + '-' + instance + '.sock');
16
- return {stateDir, socketPath, tokenPath:path.join(stateDir, 'open-browser.token')};
17
+ return {stateDir, socketPath, tokenPath:path.join(stateDir, 'open-browser.token'), pidPath:path.join(stateDir, 'open-browser.pid')};
17
18
  }
18
19
 
19
- export const {stateDir, socketPath, tokenPath} = pathsForProfile(profileId);
20
+ export { buildProfile };
21
+ export const {stateDir, socketPath, tokenPath, pidPath} = pathsForProfile(profileId);
20
22
  export const adminTokenPath = path.join(stateDir, 'open-browser-admin.token');
package/receipt-store.mjs CHANGED
@@ -36,6 +36,8 @@ export class ReceiptStore {
36
36
  operationId TEXT, completedSteps INTEGER, expires INTEGER, actorId TEXT, pixelWidth INTEGER, pixelHeight INTEGER);
37
37
  CREATE INDEX IF NOT EXISTS event_feed ON events(owner,workspace,sequence);
38
38
  CREATE INDEX IF NOT EXISTS event_expiry ON events(expires);`);
39
+ if (!this.db.prepare('PRAGMA table_info(recovery_objects)').all().some(field => field.name === 'disposition'))
40
+ this.db.exec('ALTER TABLE recovery_objects ADD COLUMN disposition TEXT');
39
41
  this.sweep = this.db.prepare('DELETE FROM receipts WHERE expires <= ?');
40
42
  this.sweepRecovery = this.db.prepare('DELETE FROM recovery_objects WHERE expires<=?');
41
43
  this.sweepRecovery.run(Date.now());
@@ -61,14 +63,19 @@ export class ReceiptStore {
61
63
  }
62
64
 
63
65
  remember(owner, workspace, kind, id) {
64
- this.db.prepare('INSERT OR REPLACE INTO recovery_objects VALUES (?,?,?,?,?)')
66
+ this.db.prepare('INSERT OR REPLACE INTO recovery_objects(owner,workspace,kind,id,expires) VALUES (?,?,?,?,?)')
65
67
  .run(owner, workspace, kind, id, Date.now() + retentionMs);
66
68
  }
67
69
 
70
+ pageDisposition(owner, workspace, id, disposition) {
71
+ this.db.prepare("UPDATE recovery_objects SET disposition=? WHERE owner=? AND workspace=? AND kind='page' AND id=?")
72
+ .run(disposition, owner, workspace, id);
73
+ }
74
+
68
75
  recoveryObjects(owner, workspace, after = 0, limit = 50) {
69
76
  if (!Number.isSafeInteger(after) || after < 0) throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
70
77
  // ReceiptStore.list has already validated the common limit.
71
- const rows = this.db.prepare('SELECT rowid,kind,id FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
78
+ const rows = this.db.prepare('SELECT rowid,kind,id,disposition FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
72
79
  .all(owner, workspace, Date.now(), after, limit + 1);
73
80
  return {records:rows.slice(0,limit), nextObjectCursor:rows.length > limit ? rows[limit-1].rowid : null};
74
81
  }
package/runtime.mjs CHANGED
@@ -8,9 +8,15 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
8
8
  const require = createRequire(import.meta.url);
9
9
  const version = require('playwright-core/package.json').version;
10
10
  const engineDir = fileURLToPath(new URL('./.open-browser/engine/', import.meta.url));
11
- const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${process.arch}.json`);
11
+ function targetArch() {
12
+ return process.env.OPEN_BROWSER_TARGET_ARCH?.trim() || process.arch;
13
+ }
12
14
 
13
15
  export async function engineExecutable() {
16
+ const arch = targetArch();
17
+ const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${arch}.json`);
18
+ if (process.platform === 'darwin' && !['arm64', 'x64'].includes(arch))
19
+ throw new Error('macOS 引擎目标架构必须是 arm64 或 x64。');
14
20
  try {
15
21
  const entry = JSON.parse(await readFile(manifest, 'utf8'));
16
22
  const executable = await realpath(path.join(engineDir, entry.executable));
@@ -24,6 +30,8 @@ export async function engineExecutable() {
24
30
  }
25
31
 
26
32
  async function install() {
33
+ if (process.platform === 'darwin' && targetArch !== process.arch)
34
+ throw new Error(`当前 Node 是 ${process.arch},不能下载并登记 ${targetArch} 引擎。请在对应架构的 macOS 或 Rosetta x64 Node 下运行。`);
27
35
  process.env.PLAYWRIGHT_BROWSERS_PATH = engineDir;
28
36
  const cli = path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js');
29
37
  execFileSync(process.execPath, [cli, 'install', 'chromium', '--no-shell'], { stdio: 'inherit' });
@@ -34,6 +42,7 @@ async function install() {
34
42
  binary = await installWindowsIcons(binary);
35
43
  }
36
44
  const executable = path.relative(engineDir, binary);
45
+ const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${targetArch()}.json`);
37
46
  const temp = manifest + '.' + randomUUID();
38
47
  await writeFile(temp, JSON.stringify({ executable }) + '\n', { flag: 'wx' });
39
48
  await rename(temp, manifest);