@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,54 @@
1
+ // A page can only ask for a URL. The host decides ownership, origin and generation
2
+ // before a background target exists. Chromium's document sandbox keeps its native
3
+ // popup capability disabled, including for frames and unregistered pages.
4
+ export async function installPopupBridge(page, accept) {
5
+ const binding = '__openBrowserPopupRequest';
6
+ const exposed = await page.exposeBinding(binding, ({frame}, token, url) => {
7
+ if (frame !== page.mainFrame() || typeof token !== 'string' || typeof url !== 'string' || url.length>8192) return;
8
+ return accept(token,url);
9
+ });
10
+ const script = await page.addInitScript(bindingName => {
11
+ if (window !== top) return;
12
+ const nativeOpen=window.open, nativeTimeout=window.setTimeout;
13
+ const request=(...args)=>window[bindingName](...args).catch(()=>{});
14
+ let armed, current;
15
+ function onClick(event) {
16
+ if (!event.isTrusted || !armed) return;
17
+ const token=armed;
18
+ armed=undefined;current=token;
19
+ request(token,'');
20
+ nativeTimeout.call(window,()=>{if(current===token)current=undefined;},0);
21
+ }
22
+ window.addEventListener('click',onClick,true);
23
+ window.__openBrowserArmPopup=token=>{armed=token;};
24
+ function managedOpen(url, target='_blank') {
25
+ if (!current || !url || ['_self','_top','_parent'].includes(String(target).toLowerCase())) return null;
26
+ try { request(current,new URL(String(url),document.baseURI).href); } catch { /* Invalid URL. */ }
27
+ return null;
28
+ }
29
+ // Propagate only the initiating click's capability to its own timer callbacks.
30
+ function managedTimeout(callback,ms,...args) {
31
+ const token=current;
32
+ if (!token || typeof callback!=='function') return nativeTimeout.call(window,callback,ms,...args);
33
+ return nativeTimeout.call(window,function(...params){
34
+ const previous=current;current=token;
35
+ try { return callback.apply(this,params); } finally {current=previous;}
36
+ },ms,...args);
37
+ }
38
+ window.open=managedOpen;
39
+ window.setTimeout=managedTimeout;
40
+ window.__openBrowserReleasePopups=()=>{
41
+ window.removeEventListener('click',onClick,true);
42
+ if (window.open===managedOpen) window.open=nativeOpen;
43
+ if (window.setTimeout===managedTimeout) window.setTimeout=nativeTimeout;
44
+ armed=current=undefined;
45
+ delete window.__openBrowserArmPopup;
46
+ delete window.__openBrowserReleasePopups;
47
+ };
48
+ }, binding);
49
+ return async () => {
50
+ await script.dispose();
51
+ await exposed.dispose();
52
+ await page.evaluate(()=>window.__openBrowserReleasePopups?.()).catch(()=>{});
53
+ };
54
+ }
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 ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { createMcpServer } from './mcp-server.mjs';
4
+ const server = createMcpServer();
5
+ await server.connect(new StdioServerTransport());
@@ -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,79 @@
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.2.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-mcp-http": "mcp-http.mjs",
22
+ "open-browser-skill": "skills/open-browser/scripts/open-browser"
23
+ },
24
+ "exports": {
25
+ ".": "./sdk.mjs",
26
+ "./sdk": "./sdk.mjs",
27
+ "./cli": "./cli.mjs",
28
+ "./mcp": "./mcp.mjs",
29
+ "./skill": "./skills/open-browser/SKILL.md",
30
+ "./api": "./Docs/open-browser-api.d.ts",
31
+ "./package.json": "./package.json"
32
+ },
33
+ "engines": {
34
+ "node": ">=22"
35
+ },
36
+ "scripts": {
37
+ "start": "node desktop/start.mjs",
38
+ "start:dev": "node desktop/start-profile.mjs dev",
39
+ "start:stable": "node desktop/start-profile.mjs stable",
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",
49
+ "cli": "node cli.mjs",
50
+ "mcp": "node mcp.mjs",
51
+ "mcp:http": "node mcp-http.mjs",
52
+ "package:check": "npm pack --dry-run",
53
+ "browser:install": "node runtime.mjs",
54
+ "control": "node control.mjs",
55
+ "test": "npm run test:unit",
56
+ "test:unit": "node --test --test-concurrency=1 *.test.mjs studio/*.test.mjs",
57
+ "test:contract": "node --test --test-concurrency=1 experiments/observe-contract.test.mjs hosted/hosted.test.mjs",
58
+ "test:all": "npm run test:unit && npm run test:contract",
59
+ "test:headed": "OPEN_BROWSER_QA_HEADED=1 node desktop/verify-upgrade.mjs",
60
+ "build:verify": "node desktop/verify-version.mjs && npm run build",
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"
70
+ },
71
+ "dependencies": {
72
+ "@modelcontextprotocol/sdk": "1.32.2",
73
+ "playwright-core": "1.65.1",
74
+ "pngjs": "7.0.0"
75
+ },
76
+ "devDependencies": {
77
+ "resedit": "3.1.1"
78
+ }
79
+ }
@@ -0,0 +1,188 @@
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(state, origin) {
4
+ const key = '__openBrowserActivityEdge';
5
+ if (!state || location.origin !== origin) {
6
+ globalThis[key]?.remove();
7
+ delete globalThis[key];
8
+ return;
9
+ }
10
+ if (!document.documentElement) return;
11
+ if (globalThis[key]?.isConnected && globalThis[key].dataset.openBrowserActivity === state) return;
12
+ globalThis[key]?.remove();
13
+ const edge = document.createElement('div');
14
+ edge.setAttribute('aria-hidden', 'true');
15
+ edge.setAttribute('data-open-browser-activity', state);
16
+ edge.inert = true;
17
+ for (const [property, value] of Object.entries({
18
+ all: 'initial', position: 'fixed', inset: '0', 'z-index': '2147483647',
19
+ 'pointer-events': 'none', 'border-radius': '4px',
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)',
22
+ })) edge.style.setProperty(property, value, 'important');
23
+ if (state === 'running' && !matchMedia('(prefers-reduced-motion: reduce)').matches)
24
+ edge.animate([{ opacity: .6 }, { opacity: 1 }], { duration: 850, iterations: Infinity, direction: 'alternate' });
25
+ document.documentElement.append(edge);
26
+ globalThis[key] = edge;
27
+ }
28
+
29
+ function paintTarget(x, y, origin, actionKind = '操作') {
30
+ const key = '__openBrowserActionRing';
31
+ globalThis[key]?.remove();
32
+ delete globalThis[key];
33
+ if (origin !== location.origin || !Number.isFinite(x) || !Number.isFinite(y) ||
34
+ x < 0 || y < 0 || x > innerWidth || y > innerHeight || !document.documentElement) {
35
+ globalThis.__openBrowserAgentCursor?.remove();
36
+ delete globalThis.__openBrowserAgentCursor;
37
+ return;
38
+ }
39
+ const ring = document.createElement('div');
40
+ ring.inert = true;
41
+ ring.setAttribute('aria-hidden', 'true');
42
+ ring.setAttribute('data-open-browser-target', '');
43
+ const actionLabels = { click: '点击', doubleClick: '双击', hover: '悬停', press: '按键',
44
+ scroll: '滚动', drag: '拖拽', fill: '填写', fillCredential: '填写凭据', select: '选择',
45
+ upload: '上传', setChecked: '切换' };
46
+ for (const [property, value] of Object.entries({
47
+ all: 'initial', position: 'fixed', left: (x - 11) + 'px', top: (y - 11) + 'px',
48
+ width: '18px', height: '18px', border: '2px solid #7659e8', 'border-radius': '50%',
49
+ 'box-shadow': '0 0 0 2px white', 'z-index': '2147483647', 'pointer-events': 'none',
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');
81
+ document.documentElement.append(ring);
82
+ globalThis[key] = ring;
83
+ if (!matchMedia('(prefers-reduced-motion: reduce)').matches)
84
+ ring.animate([{ transform: 'scale(.75)', opacity: 1 }, { transform: 'scale(1.75)', opacity: 0 }], 460);
85
+ setTimeout(() => {
86
+ ring.remove();
87
+ if (globalThis[key] === ring) delete globalThis[key];
88
+ }, 470);
89
+ }
90
+
91
+ async function paint(tab, fn, args, current, retry = true) {
92
+ if (!current() || tab.page.isClosed() || !/^https?:/.test(tab.page.url())) return;
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
+ }
104
+ if (!current()) return;
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
+ }
115
+ }
116
+
117
+ export function pageActivity() {
118
+ const tabs = new Map();
119
+ function render(tab, origin, state, force = false) {
120
+ if (!force && tab.origin === origin && tab.edgeState === state) return;
121
+ const wasActive = !!tab.origin;
122
+ tab.origin = origin;
123
+ tab.edgeState = state;
124
+ if (!wasActive && !origin) return;
125
+ const revision = ++tab.revision;
126
+ tab.pending = tab.pending.then(() =>
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(() => {}));
130
+ }
131
+ return {
132
+ track(page, session, workspaceId, pageId) {
133
+ if (tabs.has(pageId)) return;
134
+ const tab = { page, session, workspaceId, origin: null, revision: 0, targetRevision: 0, pending: Promise.resolve() };
135
+ tabs.set(pageId, tab);
136
+ tab.navigation = 0;
137
+ tab.navigated = frame => { if (frame === page.mainFrame()) { tab.navigation++; tab.context = undefined; } };
138
+ page.on('framenavigated',tab.navigated);
139
+ tab.loaded = () => { if (tab.origin) render(tab, tab.origin, tab.edgeState, true); };
140
+ page.on('domcontentloaded',tab.loaded);
141
+ tab.closed = () => tabs.delete(pageId);
142
+ page.once('close',tab.closed);
143
+ },
144
+ async release(pageId) {
145
+ const tab = tabs.get(pageId);
146
+ if (!tab) return;
147
+ tabs.delete(pageId);
148
+ tab.mode = 'released';
149
+ tab.generation = null;
150
+ tab.revision++;
151
+ tab.context = undefined;
152
+ tab.page.off('framenavigated',tab.navigated);
153
+ tab.page.off('domcontentloaded',tab.loaded);
154
+ tab.page.off('close',tab.closed);
155
+ await tab.pending;
156
+ try {
157
+ await paint(tab,paintEdge,[false,null],() => true);
158
+ await paint(tab,paintTarget,[null,null,null],() => true);
159
+ } finally { await tab.session.detach().catch(() => {}); }
160
+ },
161
+ update({ workspaceId, pages, mode, activity, controlGeneration }) {
162
+ const running = new Set((activity.running || [activity.current]).filter(job => mode === 'agent' && job?.state === 'running').map(job => job.pageId));
163
+ for (const [id, tab] of tabs) {
164
+ if (tab.workspaceId !== workspaceId) continue;
165
+ const previous = tab.generation;
166
+ tab.generation = controlGeneration;
167
+ if (previous && previous !== controlGeneration)
168
+ tab.pending = tab.pending.then(() => paint(tab, paintTarget, [null, null, null],
169
+ () => tab.generation === controlGeneration)).catch(() => {});
170
+ tab.mode = mode;
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);
175
+ }
176
+ },
177
+ target({ workspaceId, pageId, x, y, origin, controlGeneration, actionKind }) {
178
+ const tab = tabs.get(pageId);
179
+ if (!tab || tab.workspaceId !== workspaceId) return;
180
+ const navigation = tab.navigation;
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(() => {});
185
+ },
186
+ has(pageId) { return tabs.has(pageId); },
187
+ };
188
+ }