@seekskyworld/open-browser 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
  3. package/Docs/THIRD-PARTY-NOTICES.md +12 -0
  4. package/Docs/open-browser-api.d.ts +273 -0
  5. package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
  6. package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
  7. package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
  8. package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +36 -0
  9. package/LICENSE +200 -0
  10. package/README.md +150 -2
  11. package/README.zh-CN.md +155 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +151 -0
  14. package/action-execution.mjs +374 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +122 -0
  17. package/browser-extension/icons/open-browser-128.png +0 -0
  18. package/browser-extension/icons/open-browser-16.png +0 -0
  19. package/browser-extension/icons/open-browser-32.png +0 -0
  20. package/browser-extension/icons/open-browser-48.png +0 -0
  21. package/browser-extension/icons/open-browser-wordmark.png +0 -0
  22. package/browser-extension/manifest.json +38 -0
  23. package/browser-extension/newtab.css +20 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +123 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +46 -0
  29. package/browser-extension/popup.js +324 -0
  30. package/browser-extension/tab-action.js +137 -0
  31. package/browser-extension/worker.js +188 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/capability-matrix.mjs +21 -0
  34. package/chromium-host.mjs +149 -0
  35. package/chromium-shell.mjs +150 -0
  36. package/cli.mjs +83 -0
  37. package/contract-validation.mjs +27 -0
  38. package/control.mjs +107 -0
  39. package/desktop/Info.plist +13 -0
  40. package/desktop/Launcher.m +117 -0
  41. package/desktop/OBControlBar.h +7 -0
  42. package/desktop/OBControlBar.m +213 -0
  43. package/desktop/OBPageView.h +6 -0
  44. package/desktop/OBPageView.m +348 -0
  45. package/desktop/WorkspacePanel.h +16 -0
  46. package/desktop/WorkspacePanel.m +915 -0
  47. package/desktop/archive-release.py +129 -0
  48. package/desktop/brand-keychain.py +95 -0
  49. package/desktop/brand-locales.py +93 -0
  50. package/desktop/brand-macos-icons.py +24 -0
  51. package/desktop/brand-windows-icons.mjs +48 -0
  52. package/desktop/build-macos.mjs +96 -0
  53. package/desktop/build-portable.mjs +95 -0
  54. package/desktop/build.mjs +5 -0
  55. package/desktop/create-shortcut.ps1 +9 -0
  56. package/desktop/generate-icons.py +39 -0
  57. package/desktop/icons/open-browser.icns +0 -0
  58. package/desktop/icons/open-browser.ico +0 -0
  59. package/desktop/install-menu-entry.mjs +24 -0
  60. package/desktop/package-assets.mjs +34 -0
  61. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  62. package/desktop/portable-archive.py +22 -0
  63. package/desktop/sign.mjs +33 -0
  64. package/desktop/smoke-portable.mjs +65 -0
  65. package/desktop/start.mjs +12 -0
  66. package/desktop/verify-upgrade.mjs +74 -0
  67. package/desktop/verify-version.mjs +12 -0
  68. package/desktop-page.mjs +211 -0
  69. package/diagnostics.mjs +28 -0
  70. package/downloads.mjs +110 -0
  71. package/engine-service.mjs +1002 -0
  72. package/hosted/README.md +74 -0
  73. package/hosted/cli.mjs +17 -0
  74. package/hosted/directory.mjs +261 -0
  75. package/hosted/init.mjs +37 -0
  76. package/hosted/server.mjs +129 -0
  77. package/managed-popup.mjs +54 -0
  78. package/mcp.mjs +43 -0
  79. package/network-policy.mjs +107 -0
  80. package/output-store.mjs +96 -0
  81. package/package.json +57 -4
  82. package/page-activity.mjs +121 -0
  83. package/page-dialogs.mjs +53 -0
  84. package/page-observation.mjs +280 -0
  85. package/paths.mjs +20 -0
  86. package/privacy-config.mjs +95 -0
  87. package/receipt-store.mjs +191 -0
  88. package/runtime.mjs +44 -0
  89. package/scheduler.mjs +70 -0
  90. package/sdk.mjs +176 -0
  91. package/service.mjs +271 -0
  92. package/site-workflow.mjs +115 -0
  93. package/skills/open-browser/SKILL.md +86 -0
  94. package/skills/open-browser/scripts/bootstrap.mjs +134 -0
  95. package/skills/open-browser/scripts/open-browser +21 -0
  96. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  97. package/skills/open-browser/workflows/login-export.json +10 -0
  98. package/skills/open-browser/workflows/upload-verify.json +8 -0
  99. package/studio/demo-site.mjs +111 -0
  100. package/studio/demo.css +1 -0
  101. package/studio/index.html +66 -0
  102. package/studio/index.mjs +57 -0
  103. package/studio/native-demo.mjs +124 -0
  104. package/studio/studio.css +119 -0
  105. package/studio/studio.js +438 -0
  106. package/uploads.mjs +63 -0
  107. package/visual-page.mjs +306 -0
  108. package/workspace-lifecycle.mjs +170 -0
  109. package/workspace-state.mjs +95 -0
@@ -0,0 +1,21 @@
1
+ // One capability source for server-side guards and the packaged desktop host.
2
+ // Browser-extension/worker.js mirrors the generated desktop list because MV3
3
+ // service workers cannot import the Node ESM runtime.
4
+ export const readCapabilities = Object.freeze([
5
+ 'getWorkspace', 'diagnoseOperation', 'getOperation', 'getRecoverySummary',
6
+ 'listOperations', 'listEvents', 'eventCursor', 'waitForEvent',
7
+ 'listDownloads', 'listOutputs', 'readOutput', 'observe', 'captureVisual',
8
+ ]);
9
+
10
+ export const desktopCapabilities = Object.freeze([
11
+ 'listUploads', 'grantUpload', 'revokeUpload', 'respondDialog',
12
+ 'listDownloads', 'cancelDownload', 'keepDownload', 'visualStatus',
13
+ 'diagnoseOperation', 'listWorkspaces', 'getWorkspace', 'takeControl',
14
+ 'returnToAgent', 'resolveCredential', 'grantOrigin', 'finishWorkspace',
15
+ 'listOperations', 'listAgentHistory', 'closeWorkspace', 'showPage',
16
+ ]);
17
+
18
+ export const capabilityProfiles = Object.freeze({
19
+ read: readCapabilities,
20
+ desktop: desktopCapabilities,
21
+ });
@@ -0,0 +1,149 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+
4
+ import { pageActivity } from './page-activity.mjs';
5
+ import { desktopCapabilities } from './capability-matrix.mjs';
6
+
7
+ export const extensionId = 'ehmdmliolflappfnmopemgojhbiilmpl';
8
+ const workerUrl = 'chrome-extension://' + extensionId + '/worker.js';
9
+ const isHost = worker => worker.url() === workerUrl;
10
+
11
+ // No page bindings, shared secret or loopback listener. Only our packaged
12
+ // extension's service worker can submit desktop control requests.
13
+ export async function chromiumHost(context) {
14
+ const findWorker = () => context.serviceWorkers().find(isHost);
15
+ const worker = async () => findWorker() || context.waitForEvent('serviceworker', { predicate: isHost, timeout: 10000 });
16
+ let initial = await worker();
17
+ const currentVersion = host => host.evaluate(() => globalThis.openBrowserGroupVersion);
18
+ if (await currentVersion(initial) !== 10) {
19
+ // A persistent Chromium profile can start the previous cached MV3 worker.
20
+ const replacement = context.waitForEvent('serviceworker', { predicate: isHost, timeout: 10000 });
21
+ try {
22
+ [initial] = await Promise.all([replacement, initial.evaluate(() => {
23
+ setTimeout(() => chrome.runtime.reload(), 0);
24
+ })]);
25
+ } catch (cause) {
26
+ // Chromium can defer the replacement worker until its next profile launch.
27
+ throw Object.assign(new Error('工作区扩展已请求更新', { cause }), { code: 'extension_reload' });
28
+ }
29
+ if (await currentVersion(initial) !== 10) throw new Error('请重新构建 open-browser 工作区扩展。');
30
+ }
31
+ let stopped = false;
32
+ let lastState;
33
+ const effects = pageActivity();
34
+ let revision = 0, wakeSync;
35
+ function changed() { revision++; wakeSync?.(); }
36
+ const allowed = new Set(desktopCapabilities);
37
+
38
+ async function respond(host, request, call) {
39
+ let response;
40
+ try {
41
+ if (!allowed.has(request.method)) throw Object.assign(new Error(), { code: 'unknown_method' });
42
+ response = { id: request.id, result: await call(request.method, request.params || {}) };
43
+ } catch (error) {
44
+ response = { id: request.id, error: error.code || 'operation_failed' };
45
+ }
46
+ await host.evaluate(value => globalThis.openBrowserReply(value), response);
47
+ }
48
+ async function requests(call) {
49
+ while (!stopped) {
50
+ try {
51
+ const host = await worker();
52
+ const request = await host.evaluate(() => globalThis.openBrowserNext());
53
+ if (!request || stopped) continue;
54
+ // Accept takeover while a longer popup operation (such as login) is in flight.
55
+ void respond(host, request, call).catch(() => {});
56
+ } catch {
57
+ if (!stopped) await delay(300);
58
+ }
59
+ }
60
+ }
61
+ async function sync(list) {
62
+ while (!stopped) {
63
+ const startRevision = revision;
64
+ try {
65
+ const state = (await list()).map(({workspaceId, agentName, name, mode, activity, pages, controlGeneration}) => ({
66
+ workspaceId, agentName, name, mode, controlGeneration, pages: pages.map(({pageId}) => ({pageId})),
67
+ running: activity.running, currentPageId: activity.current?.pageId, stepKind: activity.current?.stepKind,
68
+ dispatchState: activity.current?.dispatchState, phase: activity.phase, needsCredential: activity.needsCredential,
69
+ }));
70
+ const signature = JSON.stringify(state);
71
+ if (signature !== lastState) {
72
+ await (await worker()).evaluate(items => globalThis.openBrowserSync(items), state);
73
+ lastState = signature;
74
+ }
75
+ } catch { lastState = undefined; }
76
+ if (!stopped && revision === startRevision) await new Promise(resolve => {
77
+ const timer = setTimeout(resolve, 750);
78
+ wakeSync = () => { clearTimeout(timer); resolve(); };
79
+ });
80
+ wakeSync = undefined;
81
+ }
82
+ }
83
+ const frontTab = async () => (await worker()).evaluate(() => globalThis.openBrowserFrontTab());
84
+ let lastBar;
85
+ async function watchFrontTab(send) {
86
+ while (!stopped) {
87
+ const bar = await frontTab().catch(() => null);
88
+ const signature = JSON.stringify(bar);
89
+ if (!stopped && signature !== lastBar) {
90
+ lastBar = signature;
91
+ send(bar);
92
+ }
93
+ // Foreground tab changes have no stable cross-process event. Keep a
94
+ // modest fallback poll while workspace revisions remain event-driven.
95
+ await delay(300);
96
+ }
97
+ }
98
+ async function clickBar(frame, call) {
99
+ const front = await frontTab();
100
+ if (!front || !['agent', 'human'].includes(front.mode) ||
101
+ ['workspaceId', 'pageId', 'windowId', 'mode', 'controlGeneration'].some(key => frame[key] !== front[key])) return;
102
+ if (frame.action === 'delivery') {
103
+ const workspace = await call('getWorkspace', { workspaceId: front.workspaceId });
104
+ const keepPageIds = (workspace.pages || []).map(page => page.pageId);
105
+ await call('finishWorkspace', {
106
+ workspaceId: front.workspaceId,
107
+ keepPageIds,
108
+ operationId: randomUUID(),
109
+ controlGeneration: front.controlGeneration,
110
+ });
111
+ return;
112
+ }
113
+ const { workspaceId, pageId, controlGeneration } = front;
114
+ await call(front.mode === 'agent' ? 'takeControl' : 'returnToAgent', { workspaceId, pageId, controlGeneration });
115
+ }
116
+ return {
117
+ onActionTarget(event) { if (!stopped) effects.target(event); },
118
+ onActivity(view) { if (!stopped) { effects.update(view); changed(); } },
119
+ async groupTab(page, workspaceId, name, mode, agentName, pageId) {
120
+ const session = await context.newCDPSession(page);
121
+ let retained = false;
122
+ try {
123
+ const { targetInfo } = await session.send('Target.getTargetInfo');
124
+ const args = { targetId: targetInfo.targetId, workspaceId, name, mode, agentName, pageId };
125
+ await (await worker()).evaluate(info => globalThis.openBrowserGroup(info), args);
126
+ if (pageId && !effects.has(pageId)) {
127
+ effects.track(page, session, workspaceId, pageId);
128
+ retained = true;
129
+ }
130
+ lastState = undefined;
131
+ changed();
132
+ } finally { if (!retained) await session.detach().catch(() => {}); }
133
+ },
134
+ async releaseTab(page, workspaceId, pageId) {
135
+ if (!page.isClosed()) await (await worker()).evaluate(params => globalThis.openBrowserRelease(params), {workspaceId,pageId});
136
+ await effects.release(pageId);
137
+ lastState = undefined;
138
+ changed();
139
+ },
140
+ async show() { await (await worker()).evaluate(() => globalThis.openBrowserShow()); },
141
+ clickBar,
142
+ start(call, onBar) {
143
+ void requests(call);
144
+ void sync(() => call('listWorkspaces'));
145
+ if (onBar) void watchFrontTab(onBar);
146
+ },
147
+ stop() { stopped = true; changed(); },
148
+ };
149
+ }
@@ -0,0 +1,150 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { copyFile, link, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { createRequire } from 'node:module';
5
+ import path from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { chromium } from 'playwright-core';
9
+ import { stateDir } from './paths.mjs';
10
+ import { engineExecutable } from './runtime.mjs';
11
+ import { chromiumPrivacyArgs } from './privacy-config.mjs';
12
+
13
+ const extensionDir = fileURLToPath(new URL('./browser-extension', import.meta.url));
14
+ const extensionId = 'ehmdmliolflappfnmopemgojhbiilmpl';
15
+
16
+ const mac = process.platform === 'darwin';
17
+ const defaultProfile = path.join(stateDir, mac ? 'open-browser-profile-v2' : 'open-browser-profile');
18
+ const run = promisify(execFile);
19
+
20
+ async function macPersistentEngine() {
21
+ const here = fileURLToPath(new URL('.', import.meta.url));
22
+ const appCode = path.join('Contents', 'Resources', 'app');
23
+ const packaged = path.normalize(here).endsWith(path.sep + appCode + path.sep);
24
+ const outer = packaged ? path.resolve(here, '../../..') : path.join(here, 'dist', 'open-browser.app');
25
+ try {
26
+ const engineDir = await realpath(path.join(outer, appCode, '.open-browser', 'engine'));
27
+ const { version } = createRequire(import.meta.url)('playwright-core/package.json');
28
+ const manifest = JSON.parse(await readFile(path.join(engineDir, `engine-${version}-darwin-${process.arch}.json`), 'utf8'));
29
+ if (manifest.profileVersion !== 2) throw new Error('v2 engine manifest required');
30
+ const executable = await realpath(path.resolve(engineDir, manifest.executable));
31
+ const relative = path.relative(engineDir, executable);
32
+ if (relative.startsWith('..' + path.sep) || path.isAbsolute(relative) ||
33
+ !relative.endsWith('/open-browser.app/Contents/MacOS/open-browser')) throw new Error('invalid branded engine path');
34
+ const { stderr } = await run('/usr/bin/codesign', ['-dv', '--verbose=2', outer]);
35
+ const team = /^TeamIdentifier=([A-Z0-9]{10})$/m.exec(stderr)?.[1];
36
+ if (!team) throw new Error('Developer ID team required');
37
+ const requirement = 'identifier "local.open-browser.chromium" and anchor apple generic and ' +
38
+ 'certificate 1[field.1.2.840.113635.100.6.2.6] exists and ' +
39
+ 'certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "' + team + '"';
40
+ await run('/usr/bin/codesign', ['--verify', '-R=' + requirement, path.resolve(executable, '../../..')]);
41
+ return executable;
42
+ } catch (cause) {
43
+ throw new Error('macOS 持久浏览需要已用 Developer ID 签名的 open-browser v2 引擎。请在项目目录执行 npm run build,再重新启动。', { cause });
44
+ }
45
+ }
46
+
47
+ async function copyLegacyBookmarks(destination) {
48
+ const legacy = path.join(stateDir, 'open-browser-profile');
49
+ const profile = path.join(legacy, 'Default');
50
+ const bookmarks = path.join(profile, 'Bookmarks');
51
+ try {
52
+ if (!(await lstat(legacy)).isDirectory() || !(await lstat(profile)).isDirectory() ||
53
+ !(await lstat(bookmarks)).isFile()) return;
54
+ await copyFile(bookmarks, path.join(destination, 'Default', 'Bookmarks'));
55
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
56
+ }
57
+
58
+ async function prepareProfile(profileDir) {
59
+ if (!mac || path.resolve(profileDir) !== defaultProfile) return seedProfile(profileDir);
60
+ // Publish a complete v2 directory at once, including the optional bookmark copy.
61
+ // Its existence is the migration record, even if the user later deletes all bookmarks.
62
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
63
+ try {
64
+ if (!(await lstat(profileDir)).isDirectory()) throw new Error('无效的 open-browser v2 资料目录。');
65
+ return;
66
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
67
+ const staging = await mkdtemp(path.join(stateDir, '.open-browser-profile-v2-'));
68
+ try {
69
+ await seedProfile(staging);
70
+ await copyLegacyBookmarks(staging);
71
+ try { await rename(staging, profileDir); }
72
+ catch (error) { if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error; }
73
+ } finally { await rm(staging, { recursive: true, force: true }); }
74
+ }
75
+
76
+ async function seedProfile(profileDir) {
77
+ const directory = path.join(profileDir, 'Default');
78
+ await mkdir(directory, { recursive: true, mode: 0o700 });
79
+ const temporary = path.join(directory, 'open-browser-preferences-' + randomUUID());
80
+ const defaults = {
81
+ // The cockpit is an intentional first-party new-tab surface. Mark the
82
+ // built-in override as acknowledged so a fresh open-browser profile does
83
+ // not show Chromium's "use this extension for new tabs" bubble.
84
+ ack_existing_ntp_extensions: true,
85
+ vertical_tabs: { enabled: true },
86
+ bookmark_bar: { show_tab_groups: false },
87
+ extensions: { pinned_extensions: [extensionId] },
88
+ autofill: { enabled: false, profile_enabled: false },
89
+ credentials_enable_service: false,
90
+ profile: { password_manager_enabled: false },
91
+ signin: { allowed: false },
92
+ sync: { disabled: true },
93
+ };
94
+ // Publish the initial preferences once. Chromium owns subsequent writes,
95
+ // including the user's choice to switch back to horizontal tabs.
96
+ await writeFile(temporary, JSON.stringify(defaults), { flag: 'wx', mode: 0o600 });
97
+ try { await link(temporary, path.join(directory, 'Preferences')); }
98
+ catch (error) { if (error.code !== 'EEXIST') throw error; }
99
+ finally { await rm(temporary, { force: true }); }
100
+ }
101
+
102
+ export async function launchChromiumShell({ profileDir = defaultProfile, headless = false, netLogPath } = {}) {
103
+ const executablePath = mac ? await macPersistentEngine() : await engineExecutable();
104
+ await prepareProfile(profileDir);
105
+ const preferences = path.join(profileDir, 'Default', 'Preferences');
106
+ const raw = await readFile(preferences,'utf8').catch(error => {
107
+ if (error.code !== 'ENOENT') throw error;
108
+ return '{}';
109
+ });
110
+ let stored;
111
+ try { stored = JSON.parse(raw); } catch { /* Chromium recovers malformed preferences. */ }
112
+ const context = await chromium.launchPersistentContext(profileDir, {
113
+ executablePath, headless, chromiumSandbox: true, viewport: null,
114
+ // Start with a local page so extensions and the profile initialize before
115
+ // the first visible tab is redirected to the open-browser cockpit.
116
+ ignoreDefaultArgs: ['--disable-extensions', '--disable-popup-blocking',
117
+ '--use-mock-keychain', '--password-store=basic'],
118
+ args: [...chromiumPrivacyArgs(), '--load-extension=' + extensionDir, '--window-size=1240,860',
119
+ ...(process.platform === 'linux' ? ['--class=open-browser', '--name=open-browser'] : []),
120
+ ...(netLogPath ? ['--log-net-log=' + netLogPath, '--net-log-capture-mode=Default'] : [])],
121
+ });
122
+ if (stored?.bookmark_bar?.show_tab_groups !== false) {
123
+ // Let Chromium migrate its own live preference store; it also owns the
124
+ // user's bookmarks, toolbar visibility, and any concurrent profile writes.
125
+ const session = await context.browser().newBrowserCDPSession();
126
+ let targetId;
127
+ try {
128
+ const marker = 'about:blank#open-browser-settings-' + randomUUID();
129
+ const ready = context.waitForEvent('page', {predicate: page => page.url() === marker,timeout:10000});
130
+ const [page] = await Promise.all([ready, session.send('Target.createTarget',
131
+ {url:marker,background:true,focus:false}).then(target => { targetId = target.targetId; })]);
132
+ await page.goto('chrome://settings/appearance');
133
+ const applied = await page.evaluate(() => chrome.settingsPrivate.setPref('bookmark_bar.show_tab_groups',false,''));
134
+ if (!applied) throw new Error('无法设置书签栏的标签组显示方式。');
135
+ } catch (error) {
136
+ await context.close();
137
+ throw error;
138
+ } finally {
139
+ if (targetId) await session.send('Target.closeTarget',{targetId}).catch(() => {});
140
+ await session.detach().catch(() => {});
141
+ }
142
+ }
143
+ // Chromium starts a persistent context with an ordinary blank document.
144
+ // The first visible tab should use the same cockpit as subsequent new tabs.
145
+ const initialPage = context.pages()[0];
146
+ if (initialPage?.url() === 'about:blank') {
147
+ await initialPage.goto('chrome://newtab/', { waitUntil: 'domcontentloaded' });
148
+ }
149
+ return context;
150
+ }
package/cli.mjs ADDED
@@ -0,0 +1,83 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile } from 'node:fs/promises';
3
+ import { socketPath, adminTokenPath } from './paths.mjs';
4
+ import { localRequest, agentMethods, OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
5
+
6
+ const help = `open-browser <method> [< params.json]
7
+
8
+ 每个命令从标准输入读取一个 JSON 对象,向本地服务发起调用,将结果写到标准输出。
9
+ 可用方法:${agentMethods.join('、')}
10
+
11
+ 最短路径:
12
+ printf '%s\\n' '{"url":"https://example.org","name":"页面检查"}' | open-browser open
13
+ printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","pageId":"PAGE_ID"}' | open-browser observe
14
+ printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","operationId":"finish-UNIQUE-ID","keepPageIds":[]}' | open-browser finishWorkspace
15
+
16
+ echo '{"name":"网页检查","agentName":"研究助手"}' | node cli.mjs createWorkspace
17
+ echo '{"url":"https://example.org","name":"网页检查"}' | node cli.mjs open
18
+ node cli.mjs listWorkspaces
19
+ echo '{"workspaceId":"WORKSPACE_ID","url":"https://example.org"}' | node cli.mjs openPage
20
+ echo '{"workspaceId":"WORKSPACE_ID","pageId":"PAGE_ID"}' | node cli.mjs observe
21
+
22
+ 失败输出包含 code、message 和可用时的 nextAction。动作超时后优先使用同一 operationId 查询 getOperation。
23
+ 需要完整参数契约时运行:node cli.mjs --schema
24
+ 本机管理命令:admin.pair、admin.list、admin.grant、admin.revoke、admin.revokeClient、admin.clearHistory、admin.scheduler、admin.setPixelPermission。
25
+ 凭据在可信的本地控制台设置;使用 fillCredential 和 credentialRef 填写登录字段。
26
+ `;
27
+
28
+ async function readParams() {
29
+ const chunks = [];
30
+ let bytes = 0;
31
+ if (process.stdin.isTTY) return {};
32
+ for await (const chunk of process.stdin) {
33
+ bytes += chunk.length;
34
+ if (bytes > 1024 * 1024) throw new OpenBrowserError('REQUEST_TOO_LARGE', '标准输入超过 1 MiB。');
35
+ chunks.push(chunk);
36
+ }
37
+ const text = Buffer.concat(chunks).toString('utf8');
38
+ if (!text.trim()) return {};
39
+ try { return JSON.parse(text); }
40
+ catch { throw new OpenBrowserError('INVALID_JSON', '标准输入必须是 JSON 对象。'); }
41
+ }
42
+
43
+ async function main() {
44
+ const [method, ...extra] = process.argv.slice(2);
45
+ if (method === '--schema') {
46
+ const { tools } = await import('./api-contract.mjs');
47
+ process.stdout.write(JSON.stringify(tools, null, 2) + '\n');
48
+ return;
49
+ }
50
+ if (!method || method === '--help' || method === '-h') {
51
+ process.stdout.write(help);
52
+ return;
53
+ }
54
+ if (extra.length) throw new OpenBrowserError('INVALID_PARAMS', '请通过标准输入提供 JSON 参数。');
55
+ if (method.startsWith('admin.')) {
56
+ if (process.env.OPEN_BROWSER_CLIENT_TOKEN_FILE) throw new OpenBrowserError('forbidden', '请从本机管理会话运行。');
57
+ const params = await readParams();
58
+ const {tokenFile, ...args} = params;
59
+ const admin = (name, values) => localRequest(socketPath,adminTokenPath,'/v1/admin',name,values);
60
+ if (method === 'admin.pair' && (typeof tokenFile !== 'string' || !tokenFile)) throw new OpenBrowserError('INVALID_PARAMS','需要新令牌文件路径 tokenFile');
61
+ const result = await admin(method.slice(6),args);
62
+ if (method === 'admin.pair') {
63
+ try { await writeFile(tokenFile,result.token + '\n',{flag:'wx',mode:0o600}); }
64
+ catch (error) { await admin('revokeClient',{principalId:result.principalId}); throw error; }
65
+ delete result.token;
66
+ }
67
+ process.stdout.write(JSON.stringify(result) + '\n');
68
+ return;
69
+ }
70
+ if (!agentMethods.includes(method)) throw new OpenBrowserError('UNKNOWN_METHOD', '未知的方法,请用 --help 查看命令。');
71
+ const api = new OpenBrowserClient({ fallbackName: 'CLI' });
72
+ const params = await readParams();
73
+ const result = method === 'capabilities' ? await api.capabilities() : await api.call(method, params);
74
+ process.stdout.write(JSON.stringify(result) + '\n');
75
+ }
76
+
77
+ main().catch(error => {
78
+ process.stderr.write(JSON.stringify({ error: {
79
+ code: error.code ?? 'CLI_ERROR', message: error.message,
80
+ ...(error.nextAction ? { nextAction: error.nextAction } : {}),
81
+ } }) + '\n');
82
+ process.exitCode = 1;
83
+ });
@@ -0,0 +1,27 @@
1
+ import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
2
+ import { tools } from './api-contract.mjs';
3
+
4
+ const validators = new Map();
5
+ const validator = new AjvJsonSchemaValidator();
6
+ const schemas = new Map(tools.map(tool => [tool.name,tool.inputSchema]));
7
+ // Older callers spread a returned page or workspace handle into a subsequent request.
8
+ // Strip only the known read-only handle fields before checking that request.
9
+ const viewFields = new Set(['agentName','name','mode','pages','controlGeneration','activity','blockedOrigins','pageId','origin','title','profile','profileId','profileAlias',
10
+ 'openedByOperationId','openerPageId','documentId','pendingDialogs']);
11
+
12
+ export function checkAgentRequest(method, params) {
13
+ const schema = schemas.get(method);
14
+ if (!schema) throw Object.assign(new Error('unknown_method'), {code:'unknown_method'});
15
+ let check = validators.get(method);
16
+ if (!check) {
17
+ check = validator.getValidator(schema);
18
+ validators.set(method,check);
19
+ }
20
+ const args = {...params};
21
+ if (schema.properties.workspaceId) {
22
+ for (const key of Object.keys(args))
23
+ if (!Object.hasOwn(schema.properties,key) && viewFields.has(key)) delete args[key];
24
+ }
25
+ if (!check(args).valid) throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
26
+ return args;
27
+ }
package/control.mjs ADDED
@@ -0,0 +1,107 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { chromium } from 'playwright-core';
3
+ import { engineExecutable } from './runtime.mjs';
4
+ import { chromiumPrivacyArgs } from './privacy-config.mjs';
5
+
6
+ export async function launchBrowser({ headless = true } = {}) {
7
+ return chromium.launch({
8
+ executablePath: await engineExecutable(),
9
+ args: [...chromiumPrivacyArgs(), ...(headless ? ['--enable-automation'] : ['--window-size=1140,820'])],
10
+ headless,
11
+ chromiumSandbox: true,
12
+ });
13
+ }
14
+
15
+ function validate({ tasks, concurrency = 4 }) {
16
+ if (!Array.isArray(tasks) || !tasks.length)
17
+ throw new Error('tasks must be a nonempty array');
18
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16)
19
+ throw new Error('concurrency must be an integer between 1 and 16');
20
+ const ids = new Set();
21
+ for (const task of tasks) {
22
+ if (!task || typeof task.id !== 'string' || !task.id || ids.has(task.id))
23
+ throw new Error('each task needs a unique string id');
24
+ ids.add(task.id);
25
+ if (!URL.canParse(task.url) || !['http:', 'https:'].includes(new URL(task.url).protocol))
26
+ throw new Error('each task needs an HTTP(S) URL');
27
+ if (!Array.isArray(task.steps)) throw new Error('steps must be an array');
28
+ for (const step of task.steps) {
29
+ if (!step || !['fill', 'click', 'read'].includes(step.op) ||
30
+ typeof step.selector !== 'string' || !step.selector.trim())
31
+ throw new Error('each step needs a fill, click or read operation and a selector');
32
+ if (step.op === 'fill' && typeof step.value !== 'string')
33
+ throw new Error('fill needs a string value');
34
+ }
35
+ }
36
+ }
37
+
38
+ async function runTask(browser, task) {
39
+ let context;
40
+ let stage = 'open';
41
+ let stepIndex = null;
42
+ const reads = [];
43
+ try {
44
+ context = await browser.newContext({ acceptDownloads: false, serviceWorkers: 'block' });
45
+ context.setDefaultTimeout(10_000);
46
+ const page = await context.newPage();
47
+ await page.goto(task.url, { waitUntil: 'domcontentloaded' });
48
+ for (const [index, step] of task.steps.entries()) {
49
+ stepIndex = index;
50
+ stage = step.op;
51
+ const target = page.locator(step.selector);
52
+ switch (step.op) {
53
+ case 'fill': await target.fill(step.value); break;
54
+ case 'click': await target.click(); break;
55
+ case 'read': reads.push(await target.innerText()); break;
56
+ }
57
+ }
58
+ return { id: task.id, ok: true, reads };
59
+ } catch (error) {
60
+ // Browser error messages can contain form values, page text and full URLs.
61
+ return { id: task.id, ok: false, stage, stepIndex, reads,
62
+ error: error.name === 'TimeoutError' ? 'timeout' : 'browser_action_failed' };
63
+ } finally {
64
+ if (context) await context.close();
65
+ }
66
+ }
67
+
68
+ // Long-lived callers can reuse one browser across batches. The limit is per batch.
69
+ export async function runBatch(browser, batch) {
70
+ validate(batch);
71
+ const { tasks, concurrency = 4 } = batch;
72
+ const results = new Array(tasks.length);
73
+ let next = 0;
74
+ async function worker() {
75
+ while (next < tasks.length) {
76
+ const index = next++;
77
+ results[index] = await runTask(browser, tasks[index]);
78
+ }
79
+ }
80
+ await Promise.all(Array.from({ length: Math.min(concurrency, tasks.length) }, worker));
81
+ return results;
82
+ }
83
+
84
+ async function main() {
85
+ let input = '';
86
+ process.stdin.setEncoding('utf8');
87
+ for await (const chunk of process.stdin) input += chunk;
88
+ let batch;
89
+ try { batch = JSON.parse(input); }
90
+ catch { throw new Error('stdin must contain a JSON batch'); }
91
+ validate(batch);
92
+ const browser = await launchBrowser();
93
+ try {
94
+ const results = await runBatch(browser, batch);
95
+ console.log(JSON.stringify(results));
96
+ if (results.some(result => !result.ok)) process.exitCode = 1;
97
+ } finally {
98
+ await browser.close();
99
+ }
100
+ }
101
+
102
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
103
+ main().catch(error => {
104
+ console.error(error.message);
105
+ process.exitCode = 1;
106
+ });
107
+ }
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>CFBundleIdentifier</key><string>local.open-browser.desktop</string>
5
+ <key>CFBundleName</key><string>open-browser</string>
6
+ <key>CFBundleDisplayName</key><string>open-browser</string>
7
+ <key>CFBundleExecutable</key><string>open-browser</string>
8
+ <key>CFBundlePackageType</key><string>APPL</string>
9
+ <key>CFBundleIconFile</key><string>open-browser.icns</string>
10
+ <key>CFBundleVersion</key><string>1</string>
11
+ <key>CFBundleShortVersionString</key><string>0.1.0</string>
12
+ <key>NSHighResolutionCapable</key><true/>
13
+ </dict></plist>