@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.
- package/CONTRIBUTING.md +15 -0
- 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
- package/Docs/THIRD-PARTY-NOTICES.md +12 -0
- package/Docs/open-browser-api.d.ts +291 -0
- 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
- 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
- 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
- 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
- package/LICENSE +200 -0
- package/README.md +159 -2
- package/README.zh-CN.md +166 -0
- package/SECURITY.md +9 -0
- package/access-registry.mjs +156 -0
- package/action-execution.mjs +385 -0
- package/activity-notifier.mjs +34 -0
- package/api-contract.mjs +134 -0
- package/browser-extension/icons/open-browser-128.png +0 -0
- package/browser-extension/icons/open-browser-16.png +0 -0
- package/browser-extension/icons/open-browser-32.png +0 -0
- package/browser-extension/icons/open-browser-48.png +0 -0
- package/browser-extension/icons/open-browser-wordmark.png +0 -0
- package/browser-extension/manifest.json +35 -0
- package/browser-extension/newtab.css +26 -0
- package/browser-extension/newtab.html +19 -0
- package/browser-extension/newtab.js +174 -0
- package/browser-extension/phase-labels.js +9 -0
- package/browser-extension/popup.css +19 -0
- package/browser-extension/popup.html +56 -0
- package/browser-extension/popup.js +405 -0
- package/browser-extension/tab-action.js +138 -0
- package/browser-extension/worker.js +281 -0
- package/browser-extension/workspace-title.js +15 -0
- package/build-profile.mjs +23 -0
- package/capability-matrix.mjs +21 -0
- package/chromium-host.mjs +209 -0
- package/chromium-shell.mjs +179 -0
- package/cli.mjs +141 -0
- package/contract-validation.mjs +27 -0
- package/control.mjs +107 -0
- package/desktop/Info.plist +13 -0
- package/desktop/Launcher.m +117 -0
- package/desktop/OBControlBar.h +7 -0
- package/desktop/OBControlBar.m +217 -0
- package/desktop/OBPageView.h +6 -0
- package/desktop/OBPageView.m +348 -0
- package/desktop/WorkspacePanel.h +16 -0
- package/desktop/WorkspacePanel.m +916 -0
- package/desktop/archive-release.py +129 -0
- package/desktop/brand-keychain.py +111 -0
- package/desktop/brand-locales.py +93 -0
- package/desktop/brand-macos-icons.py +24 -0
- package/desktop/brand-windows-icons.mjs +48 -0
- package/desktop/build-macos.mjs +112 -0
- package/desktop/build-managed-input.mjs +37 -0
- package/desktop/build-portable.mjs +95 -0
- package/desktop/build-profile.mjs +6 -0
- package/desktop/build.mjs +13 -0
- package/desktop/create-shortcut.ps1 +9 -0
- package/desktop/generate-icons.py +39 -0
- package/desktop/icons/open-browser.icns +0 -0
- package/desktop/icons/open-browser.ico +0 -0
- package/desktop/install-menu-entry.mjs +24 -0
- package/desktop/macos-entitlements.plist +12 -0
- package/desktop/notarize-macos.mjs +145 -0
- package/desktop/package-assets.mjs +34 -0
- package/desktop/package-macos.mjs +54 -0
- package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
- package/desktop/patches/chromium-managed-input.patch +144 -0
- package/desktop/portable-archive.py +22 -0
- package/desktop/sign.mjs +77 -0
- package/desktop/smoke-portable.mjs +65 -0
- package/desktop/start-profile.mjs +5 -0
- package/desktop/start.mjs +34 -0
- package/desktop/verify-macos-release.mjs +61 -0
- package/desktop/verify-upgrade.mjs +74 -0
- package/desktop/verify-version.mjs +12 -0
- package/desktop-page.mjs +211 -0
- package/diagnostics.mjs +37 -0
- package/downloads.mjs +110 -0
- package/engine-service.mjs +1158 -0
- package/hosted/README.md +74 -0
- package/hosted/cli.mjs +17 -0
- package/hosted/directory.mjs +261 -0
- package/hosted/init.mjs +37 -0
- package/hosted/server.mjs +129 -0
- package/managed-input.mjs +138 -0
- package/managed-popup.mjs +54 -0
- package/mcp-http.mjs +84 -0
- package/mcp-server.mjs +41 -0
- package/mcp.mjs +5 -0
- package/network-policy.mjs +107 -0
- package/output-store.mjs +96 -0
- package/package.json +77 -4
- package/page-activity.mjs +188 -0
- package/page-dialogs.mjs +53 -0
- package/page-observation.mjs +318 -0
- package/paths.mjs +22 -0
- package/privacy-config.mjs +95 -0
- package/receipt-store.mjs +198 -0
- package/runtime.mjs +53 -0
- package/scheduler.mjs +70 -0
- package/sdk.mjs +193 -0
- package/service.mjs +290 -0
- package/site-workflow.mjs +115 -0
- package/skill-links.mjs +90 -0
- package/skills/open-browser/SKILL.macos.md +112 -0
- package/skills/open-browser/SKILL.md +107 -0
- package/skills/open-browser/SKILL.windows.md +112 -0
- package/skills/open-browser/scripts/bootstrap.mjs +213 -0
- package/skills/open-browser/scripts/open-browser +21 -0
- package/skills/open-browser/scripts/open-browser.cmd +9 -0
- package/skills/open-browser/workflows/login-export.json +10 -0
- package/skills/open-browser/workflows/upload-verify.json +8 -0
- package/studio/demo-site.mjs +111 -0
- package/studio/demo.css +1 -0
- package/studio/index.html +66 -0
- package/studio/index.mjs +57 -0
- package/studio/native-demo.mjs +124 -0
- package/studio/studio.css +119 -0
- package/studio/studio.js +438 -0
- package/tab-adoption.mjs +77 -0
- package/uploads.mjs +63 -0
- package/visual-page.mjs +306 -0
- package/workspace-lifecycle.mjs +238 -0
- package/workspace-state.mjs +107 -0
|
@@ -0,0 +1,179 @@
|
|
|
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 { tmpdir } from 'node:os';
|
|
10
|
+
import { stateDir } from './paths.mjs';
|
|
11
|
+
import { engineExecutable } from './runtime.mjs';
|
|
12
|
+
import { chromiumPrivacyArgs } from './privacy-config.mjs';
|
|
13
|
+
import { isDevelopmentBuild } from './build-profile.mjs';
|
|
14
|
+
|
|
15
|
+
const extensionDir = fileURLToPath(new URL('./browser-extension', import.meta.url));
|
|
16
|
+
const extensionId = 'ehmdmliolflappfnmopemgojhbiilmpl';
|
|
17
|
+
|
|
18
|
+
const mac = process.platform === 'darwin';
|
|
19
|
+
const defaultProfile = path.join(stateDir, mac ? 'open-browser-profile-v2' : 'open-browser-profile');
|
|
20
|
+
const run = promisify(execFile);
|
|
21
|
+
const cockpitUrl = `chrome-extension://${extensionId}/newtab.html`;
|
|
22
|
+
|
|
23
|
+
async function routeNewTab(page) {
|
|
24
|
+
try {
|
|
25
|
+
if (!['chrome://newtab/', 'chrome://newtab', 'chrome://new-tab-page/'].includes(page.url())) return;
|
|
26
|
+
await page.goto(cockpitUrl, { waitUntil: 'domcontentloaded' });
|
|
27
|
+
} catch {
|
|
28
|
+
// A tab can be closed while Chromium is creating it. The browser remains usable.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function macPersistentEngine() {
|
|
33
|
+
const here = fileURLToPath(new URL('.', import.meta.url));
|
|
34
|
+
const appCode = path.join('Contents', 'Resources', 'app');
|
|
35
|
+
const packaged = path.normalize(here).endsWith(path.sep + appCode + path.sep);
|
|
36
|
+
const outer = packaged ? path.resolve(here, '../../..') : path.join(here, 'dist', isDevelopmentBuild ? 'open-browser-dev.app' : process.arch === 'x64' ? 'open-browser-x64.app' : 'open-browser.app');
|
|
37
|
+
try {
|
|
38
|
+
const engineDir = await realpath(path.join(outer, appCode, '.open-browser', 'engine'));
|
|
39
|
+
const { version } = createRequire(import.meta.url)('playwright-core/package.json');
|
|
40
|
+
const manifest = JSON.parse(await readFile(path.join(engineDir, `engine-${version}-darwin-${process.arch}.json`), 'utf8'));
|
|
41
|
+
if (manifest.profileVersion !== 2) throw new Error('v2 engine manifest required');
|
|
42
|
+
const executable = await realpath(path.resolve(engineDir, manifest.executable));
|
|
43
|
+
const relative = path.relative(engineDir, executable);
|
|
44
|
+
if (relative.startsWith('..' + path.sep) || path.isAbsolute(relative) ||
|
|
45
|
+
!relative.endsWith((isDevelopmentBuild ? '/open-browser-dev.app' : '/open-browser.app') + '/Contents/MacOS/open-browser')) throw new Error('invalid branded engine path');
|
|
46
|
+
const { stderr } = await run('/usr/bin/codesign', ['-dv', '--verbose=2', outer]);
|
|
47
|
+
const team = /^TeamIdentifier=([A-Z0-9]{10})$/m.exec(stderr)?.[1];
|
|
48
|
+
if (!team) throw new Error('Developer ID team required');
|
|
49
|
+
const requirement = 'identifier "local.open-browser' + (isDevelopmentBuild ? '-dev' : '') + '.chromium" and anchor apple generic and ' +
|
|
50
|
+
'certificate 1[field.1.2.840.113635.100.6.2.6] exists and ' +
|
|
51
|
+
'certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "' + team + '"';
|
|
52
|
+
await run('/usr/bin/codesign', ['--verify', '-R=' + requirement, path.resolve(executable, '../../..')]);
|
|
53
|
+
return executable;
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
throw new Error('macOS 持久浏览需要已用 Developer ID 签名的 open-browser v2 引擎。请在项目目录执行 npm run build,再重新启动。', { cause });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function copyLegacyBookmarks(destination) {
|
|
60
|
+
const legacy = path.join(stateDir, 'open-browser-profile');
|
|
61
|
+
const profile = path.join(legacy, 'Default');
|
|
62
|
+
const bookmarks = path.join(profile, 'Bookmarks');
|
|
63
|
+
try {
|
|
64
|
+
if (!(await lstat(legacy)).isDirectory() || !(await lstat(profile)).isDirectory() ||
|
|
65
|
+
!(await lstat(bookmarks)).isFile()) return;
|
|
66
|
+
await copyFile(bookmarks, path.join(destination, 'Default', 'Bookmarks'));
|
|
67
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function prepareProfile(profileDir) {
|
|
71
|
+
if (!mac || path.resolve(profileDir) !== defaultProfile) return seedProfile(profileDir);
|
|
72
|
+
// Publish a complete v2 directory at once, including the optional bookmark copy.
|
|
73
|
+
// Its existence is the migration record, even if the user later deletes all bookmarks.
|
|
74
|
+
await mkdir(stateDir, { recursive: true, mode: 0o700 });
|
|
75
|
+
try {
|
|
76
|
+
if (!(await lstat(profileDir)).isDirectory()) throw new Error('无效的 open-browser v2 资料目录。');
|
|
77
|
+
return;
|
|
78
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
79
|
+
const staging = await mkdtemp(path.join(stateDir, '.open-browser-profile-v2-'));
|
|
80
|
+
try {
|
|
81
|
+
await seedProfile(staging);
|
|
82
|
+
await copyLegacyBookmarks(staging);
|
|
83
|
+
try { await rename(staging, profileDir); }
|
|
84
|
+
catch (error) { if (!['EEXIST', 'ENOTEMPTY'].includes(error.code)) throw error; }
|
|
85
|
+
} finally { await rm(staging, { recursive: true, force: true }); }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function seedProfile(profileDir) {
|
|
89
|
+
const directory = path.join(profileDir, 'Default');
|
|
90
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
91
|
+
const temporary = path.join(directory, 'open-browser-preferences-' + randomUUID());
|
|
92
|
+
const defaults = {
|
|
93
|
+
// The cockpit is an intentional first-party new-tab surface. Mark the
|
|
94
|
+
// built-in override as acknowledged so a fresh open-browser profile does
|
|
95
|
+
// not show Chromium's "use this extension for new tabs" bubble.
|
|
96
|
+
ack_existing_ntp_extensions: true,
|
|
97
|
+
vertical_tabs: { enabled: true },
|
|
98
|
+
bookmark_bar: { show_tab_groups: false },
|
|
99
|
+
extensions: { pinned_extensions: [extensionId] },
|
|
100
|
+
autofill: { enabled: false, profile_enabled: false },
|
|
101
|
+
credentials_enable_service: false,
|
|
102
|
+
profile: { password_manager_enabled: false },
|
|
103
|
+
signin: { allowed: false },
|
|
104
|
+
sync: { disabled: true },
|
|
105
|
+
};
|
|
106
|
+
// Publish the initial preferences once. Chromium owns subsequent writes,
|
|
107
|
+
// including the user's choice to switch back to horizontal tabs.
|
|
108
|
+
await writeFile(temporary, JSON.stringify(defaults), { flag: 'wx', mode: 0o600 });
|
|
109
|
+
try { await link(temporary, path.join(directory, 'Preferences')); }
|
|
110
|
+
catch (error) { if (error.code !== 'EEXIST') throw error; }
|
|
111
|
+
finally { await rm(temporary, { force: true }); }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function launchChromiumShell({ profileDir = defaultProfile, headless = false, netLogPath } = {}) {
|
|
115
|
+
// A locally compiled Dev engine uses an ephemeral profile. It has a distinct
|
|
116
|
+
// executable identity and must never open an installed user's Keychain/profile.
|
|
117
|
+
const customEngine = isDevelopmentBuild && process.env.OPEN_BROWSER_DEV_CHROMIUM;
|
|
118
|
+
const executablePath = customEngine ? await realpath(customEngine)
|
|
119
|
+
: mac ? await macPersistentEngine() : await engineExecutable();
|
|
120
|
+
if (customEngine) profileDir = await mkdtemp(path.join(tmpdir(), 'open-browser-dev-input-'));
|
|
121
|
+
let context;
|
|
122
|
+
try {
|
|
123
|
+
await prepareProfile(profileDir);
|
|
124
|
+
const preferences = path.join(profileDir, 'Default', 'Preferences');
|
|
125
|
+
const raw = await readFile(preferences,'utf8').catch(error => {
|
|
126
|
+
if (error.code !== 'ENOENT') throw error;
|
|
127
|
+
return '{}';
|
|
128
|
+
});
|
|
129
|
+
let stored;
|
|
130
|
+
try { stored = JSON.parse(raw); } catch { /* Chromium recovers malformed preferences. */ }
|
|
131
|
+
context = await chromium.launchPersistentContext(profileDir, {
|
|
132
|
+
executablePath, headless, chromiumSandbox: true, viewport: null,
|
|
133
|
+
// Start with a local page so extensions and the profile initialize before
|
|
134
|
+
// the first visible tab is redirected to the open-browser cockpit.
|
|
135
|
+
ignoreDefaultArgs: ['--disable-extensions', '--disable-popup-blocking',
|
|
136
|
+
...(!customEngine ? ['--use-mock-keychain', '--password-store=basic'] : [])],
|
|
137
|
+
args: [...chromiumPrivacyArgs(), '--load-extension=' + extensionDir, '--window-size=1240,860',
|
|
138
|
+
...(process.platform === 'linux' ? ['--class=open-browser', '--name=open-browser'] : []),
|
|
139
|
+
...(netLogPath ? ['--log-net-log=' + netLogPath, '--net-log-capture-mode=Default'] : [])],
|
|
140
|
+
});
|
|
141
|
+
context.on('page', page => { void routeNewTab(page); });
|
|
142
|
+
if (stored?.bookmark_bar?.show_tab_groups !== false) {
|
|
143
|
+
// Let Chromium migrate its own live preference store; it also owns the
|
|
144
|
+
// user's bookmarks, toolbar visibility, and any concurrent profile writes.
|
|
145
|
+
const session = await context.browser().newBrowserCDPSession();
|
|
146
|
+
let targetId;
|
|
147
|
+
try {
|
|
148
|
+
const marker = 'about:blank#open-browser-settings-' + randomUUID();
|
|
149
|
+
const ready = context.waitForEvent('page', {predicate: page => page.url() === marker,timeout:10000});
|
|
150
|
+
const [page] = await Promise.all([ready, session.send('Target.createTarget',
|
|
151
|
+
{url:marker,background:true,focus:false}).then(target => { targetId = target.targetId; })]);
|
|
152
|
+
await page.goto('chrome://settings/appearance');
|
|
153
|
+
const applied = await page.evaluate(() => chrome.settingsPrivate.setPref('bookmark_bar.show_tab_groups',false,''));
|
|
154
|
+
if (!applied) throw new Error('无法设置书签栏的标签组显示方式。');
|
|
155
|
+
} catch (error) {
|
|
156
|
+
await context.close();
|
|
157
|
+
throw error;
|
|
158
|
+
} finally {
|
|
159
|
+
if (targetId) await session.send('Target.closeTarget',{targetId}).catch(() => {});
|
|
160
|
+
await session.detach().catch(() => {});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
// Chromium starts a persistent context with an ordinary blank document.
|
|
164
|
+
// The first visible tab should use the same cockpit as subsequent new tabs.
|
|
165
|
+
const initialPage = context.pages()[0];
|
|
166
|
+
if (initialPage?.url() === 'about:blank') {
|
|
167
|
+
await initialPage.goto('chrome://newtab/', { waitUntil: 'domcontentloaded' });
|
|
168
|
+
}
|
|
169
|
+
await routeNewTab(initialPage);
|
|
170
|
+
if (customEngine) context.once('close', () => {
|
|
171
|
+
void rm(profileDir, { recursive: true, force: true, maxRetries: 4 }).catch(() => {});
|
|
172
|
+
});
|
|
173
|
+
return context;
|
|
174
|
+
} catch (error) {
|
|
175
|
+
await context?.close().catch(() => {});
|
|
176
|
+
if (customEngine) await rm(profileDir, {recursive:true, force:true, maxRetries:4}).catch(() => {});
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
}
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { socketPath, adminTokenPath } from './paths.mjs';
|
|
5
|
+
import { localRequest, agentMethods, OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
|
|
6
|
+
|
|
7
|
+
const help = `open-browser <method> [< params.json]
|
|
8
|
+
|
|
9
|
+
每个命令从标准输入读取一个 JSON 对象,向本地服务发起调用,将结果写到标准输出。
|
|
10
|
+
可用方法:${agentMethods.join('、')}
|
|
11
|
+
|
|
12
|
+
最短路径:
|
|
13
|
+
printf '%s\\n' '{"url":"https://example.org","name":"页面检查"}' | open-browser open
|
|
14
|
+
printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","pageId":"PAGE_ID"}' | open-browser observe
|
|
15
|
+
printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","operationId":"finish-UNIQUE-ID","keepPageIds":[]}' | open-browser finishWorkspace
|
|
16
|
+
|
|
17
|
+
open-browser session # 每行读取 {"id":1,"method":"observe","params":{...}},直到 stdin 关闭
|
|
18
|
+
|
|
19
|
+
echo '{"name":"网页检查","agentName":"研究助手"}' | node cli.mjs createWorkspace
|
|
20
|
+
echo '{"url":"https://example.org","name":"网页检查"}' | node cli.mjs open
|
|
21
|
+
node cli.mjs listWorkspaces
|
|
22
|
+
echo '{"workspaceId":"WORKSPACE_ID","url":"https://example.org"}' | node cli.mjs openPage
|
|
23
|
+
echo '{"workspaceId":"WORKSPACE_ID","pageId":"PAGE_ID"}' | node cli.mjs observe
|
|
24
|
+
|
|
25
|
+
失败输出包含 code、message 和可用时的 nextAction。动作超时后优先使用同一 operationId 查询 getOperation。
|
|
26
|
+
需要完整参数契约时运行:node cli.mjs --schema
|
|
27
|
+
本机管理命令:admin.pair、admin.list、admin.grant、admin.revoke、admin.revokeClient、admin.clearHistory、admin.scheduler、admin.setPixelPermission。
|
|
28
|
+
凭据在可信的本地控制台设置;使用 fillCredential 和 credentialRef 填写登录字段。
|
|
29
|
+
open-browser skill # 输出与当前包版本匹配的 Skill 指南
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
async function printSkillGuide() {
|
|
33
|
+
const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'windows' : null;
|
|
34
|
+
const candidates = platform
|
|
35
|
+
? [`skills/open-browser/SKILL.${platform}.md`, 'skills/open-browser/SKILL.md']
|
|
36
|
+
: ['skills/open-browser/SKILL.md'];
|
|
37
|
+
for (const relative of candidates) {
|
|
38
|
+
try {
|
|
39
|
+
const guide = await readFile(new URL(relative, import.meta.url), 'utf8');
|
|
40
|
+
process.stdout.write(guide.endsWith('\n') ? guide : guide + '\n');
|
|
41
|
+
return;
|
|
42
|
+
} catch {}
|
|
43
|
+
}
|
|
44
|
+
throw new OpenBrowserError('SKILL_GUIDE_NOT_FOUND', `未找到 Skill 指南。已检查:${candidates.join('、')}`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async function readParams() {
|
|
48
|
+
const chunks = [];
|
|
49
|
+
let bytes = 0;
|
|
50
|
+
if (process.stdin.isTTY) return {};
|
|
51
|
+
for await (const chunk of process.stdin) {
|
|
52
|
+
bytes += chunk.length;
|
|
53
|
+
if (bytes > 1024 * 1024) throw new OpenBrowserError('REQUEST_TOO_LARGE', '标准输入超过 1 MiB。');
|
|
54
|
+
chunks.push(chunk);
|
|
55
|
+
}
|
|
56
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
57
|
+
if (!text.trim()) return {};
|
|
58
|
+
try { return JSON.parse(text); }
|
|
59
|
+
catch { throw new OpenBrowserError('INVALID_JSON', '标准输入必须是 JSON 对象。'); }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function sessionMain() {
|
|
63
|
+
const api = new OpenBrowserClient({ fallbackName: 'CLI session' });
|
|
64
|
+
const input = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
65
|
+
let tail = Promise.resolve();
|
|
66
|
+
const send = frame => process.stdout.write(JSON.stringify(frame) + '\n');
|
|
67
|
+
input.on('line', line => {
|
|
68
|
+
tail = tail.then(async () => {
|
|
69
|
+
let frame;
|
|
70
|
+
try { frame = JSON.parse(line); } catch { send({ id: null, error: { code: 'INVALID_JSON', message: '每行必须是 JSON 请求。' } }); return; }
|
|
71
|
+
const id = frame?.id;
|
|
72
|
+
if (!(typeof id === 'string' || Number.isSafeInteger(id)) || typeof frame?.method !== 'string' || !frame.method ||
|
|
73
|
+
(frame.params !== undefined && (!frame.params || typeof frame.params !== 'object' || Array.isArray(frame.params)))) {
|
|
74
|
+
send({ id: id ?? null, error: { code: 'INVALID_PARAMS', message: 'session 请求需要 id、method 和对象 params。' } });
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
const result = await api.call(frame.method, frame.params ?? {});
|
|
79
|
+
send({ id, result: result ?? null });
|
|
80
|
+
} catch (error) {
|
|
81
|
+
send({ id, error: { code: error.code ?? 'CLI_ERROR', message: error.message,
|
|
82
|
+
...(error.nextAction ? { nextAction: error.nextAction } : {}) } });
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
});
|
|
86
|
+
await new Promise(resolve => input.once('close', resolve));
|
|
87
|
+
await tail;
|
|
88
|
+
api.close();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function main() {
|
|
92
|
+
const [method, ...extra] = process.argv.slice(2);
|
|
93
|
+
if (method === 'session') {
|
|
94
|
+
if (extra.length) throw new OpenBrowserError('INVALID_PARAMS', 'session 不接受额外参数。');
|
|
95
|
+
await sessionMain();
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (method === '--schema') {
|
|
99
|
+
const { tools } = await import('./api-contract.mjs');
|
|
100
|
+
process.stdout.write(JSON.stringify(tools, null, 2) + '\n');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (method === 'skill') {
|
|
104
|
+
if (extra.length) throw new OpenBrowserError('INVALID_PARAMS', 'skill 不接受额外参数。');
|
|
105
|
+
await printSkillGuide();
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!method || method === '--help' || method === '-h') {
|
|
109
|
+
process.stdout.write(help);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (extra.length) throw new OpenBrowserError('INVALID_PARAMS', '请通过标准输入提供 JSON 参数。');
|
|
113
|
+
if (method.startsWith('admin.')) {
|
|
114
|
+
if (process.env.OPEN_BROWSER_CLIENT_TOKEN_FILE) throw new OpenBrowserError('forbidden', '请从本机管理会话运行。');
|
|
115
|
+
const params = await readParams();
|
|
116
|
+
const {tokenFile, ...args} = params;
|
|
117
|
+
const admin = (name, values) => localRequest(socketPath,adminTokenPath,'/v1/admin',name,values);
|
|
118
|
+
if (method === 'admin.pair' && (typeof tokenFile !== 'string' || !tokenFile)) throw new OpenBrowserError('INVALID_PARAMS','需要新令牌文件路径 tokenFile');
|
|
119
|
+
const result = await admin(method.slice(6),args);
|
|
120
|
+
if (method === 'admin.pair') {
|
|
121
|
+
try { await writeFile(tokenFile,result.token + '\n',{flag:'wx',mode:0o600}); }
|
|
122
|
+
catch (error) { await admin('revokeClient',{principalId:result.principalId}); throw error; }
|
|
123
|
+
delete result.token;
|
|
124
|
+
}
|
|
125
|
+
process.stdout.write(JSON.stringify(result) + '\n');
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (!agentMethods.includes(method)) throw new OpenBrowserError('UNKNOWN_METHOD', '未知的方法,请用 --help 查看命令。');
|
|
129
|
+
const api = new OpenBrowserClient({ fallbackName: 'CLI' });
|
|
130
|
+
const params = await readParams();
|
|
131
|
+
const result = method === 'capabilities' ? await api.capabilities() : await api.call(method, params);
|
|
132
|
+
process.stdout.write(JSON.stringify(result) + '\n');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
main().catch(error => {
|
|
136
|
+
process.stderr.write(JSON.stringify({ error: {
|
|
137
|
+
code: error.code ?? 'CLI_ERROR', message: error.message,
|
|
138
|
+
...(error.nextAction ? { nextAction: error.nextAction } : {}),
|
|
139
|
+
} }) + '\n');
|
|
140
|
+
process.exitCode = 1;
|
|
141
|
+
});
|
|
@@ -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
|
+
'pageAvailability','nextAction','scope','accountAlias','ownership','syncState','syncRevision','lastSyncedAt','security','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.2.0</string>
|
|
12
|
+
<key>NSHighResolutionCapable</key><true/>
|
|
13
|
+
</dict></plist>
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
#import <AppKit/AppKit.h>
|
|
2
|
+
#import <signal.h>
|
|
3
|
+
#import "OBControlBar.h"
|
|
4
|
+
|
|
5
|
+
// Chromium owns the window, menus and web input. The bundle launcher owns
|
|
6
|
+
// the local service lifetime and forwards Dock reopen events to its window.
|
|
7
|
+
@interface Launcher : NSObject <NSApplicationDelegate>
|
|
8
|
+
@property(strong) NSTask *service;
|
|
9
|
+
@property(strong) OBControlBar *bar;
|
|
10
|
+
@property(strong) NSFileHandle *input;
|
|
11
|
+
@property(strong) dispatch_queue_t writer;
|
|
12
|
+
@property BOOL ready;
|
|
13
|
+
@property BOOL quitting;
|
|
14
|
+
@end
|
|
15
|
+
|
|
16
|
+
@implementation Launcher
|
|
17
|
+
- (void)applicationDidFinishLaunching:(NSNotification *)note {
|
|
18
|
+
NSURL *resources = NSBundle.mainBundle.resourceURL;
|
|
19
|
+
NSURL *app = [resources URLByAppendingPathComponent:@"app"];
|
|
20
|
+
self.service = [NSTask new];
|
|
21
|
+
self.service.currentDirectoryURL = app;
|
|
22
|
+
self.service.executableURL = [resources URLByAppendingPathComponent:@"node/bin/node"];
|
|
23
|
+
self.service.arguments = @[[app URLByAppendingPathComponent:@"service.mjs"].path, @"--chromium", @"--desktop-bar"];
|
|
24
|
+
NSPipe *output = [NSPipe pipe];
|
|
25
|
+
self.service.standardOutput = output;
|
|
26
|
+
NSPipe *input = [NSPipe pipe];
|
|
27
|
+
self.service.standardInput = input;
|
|
28
|
+
self.input = input.fileHandleForWriting;
|
|
29
|
+
self.writer = dispatch_queue_create("open-browser.desktop.bar.write", DISPATCH_QUEUE_SERIAL);
|
|
30
|
+
signal(SIGPIPE, SIG_IGN);
|
|
31
|
+
__weak Launcher *owner = self;
|
|
32
|
+
self.service.terminationHandler = ^(NSTask *task) {
|
|
33
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
34
|
+
[owner.bar stop];
|
|
35
|
+
owner.ready = NO;
|
|
36
|
+
if (owner.quitting) { [NSApp replyToApplicationShouldTerminate:YES]; return; }
|
|
37
|
+
if (task.terminationStatus != 0) [owner showError:@"本机浏览器服务已退出。请检查是否已从源码启动同一服务。"];
|
|
38
|
+
[NSApp terminate:nil];
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
NSError *error = nil;
|
|
42
|
+
if (![self.service launchAndReturnError:&error]) {
|
|
43
|
+
[self showError:error.localizedDescription]; [NSApp terminate:nil]; return;
|
|
44
|
+
}
|
|
45
|
+
self.bar = [[OBControlBar alloc] initWithEngineRoot:[app URLByAppendingPathComponent:@".open-browser/engine"]
|
|
46
|
+
servicePID:self.service.processIdentifier send:^(NSDictionary *event) { [owner sendEvent:event]; }];
|
|
47
|
+
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
|
|
48
|
+
[owner readEvents:output.fileHandleForReading];
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
- (void)sendEvent:(NSDictionary *)event {
|
|
53
|
+
if (!self.ready || self.quitting || !self.service.running) return;
|
|
54
|
+
NSMutableData *line = [[NSJSONSerialization dataWithJSONObject:event options:0 error:NULL] mutableCopy];
|
|
55
|
+
if (!line) return;
|
|
56
|
+
[line appendBytes:"\n" length:1];
|
|
57
|
+
dispatch_async(self.writer, ^{ [self.input writeData:line error:NULL]; });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
- (void)readEvents:(NSFileHandle *)handle {
|
|
61
|
+
NSMutableData *line = [NSMutableData data];
|
|
62
|
+
BOOL skip = NO;
|
|
63
|
+
for (;;) @autoreleasepool {
|
|
64
|
+
NSData *chunk = handle.availableData;
|
|
65
|
+
if (!chunk.length) return;
|
|
66
|
+
const uint8_t *start = chunk.bytes, *end = start + chunk.length;
|
|
67
|
+
while (start < end) {
|
|
68
|
+
const uint8_t *newline = memchr(start, '\n', end - start);
|
|
69
|
+
NSUInteger count = (newline ?: end) - start;
|
|
70
|
+
if (!skip && line.length + count <= 65536) [line appendBytes:start length:count];
|
|
71
|
+
else skip = YES;
|
|
72
|
+
if (!newline) break;
|
|
73
|
+
if (!skip) {
|
|
74
|
+
id message = [NSJSONSerialization JSONObjectWithData:line options:0 error:NULL];
|
|
75
|
+
BOOL ready = [line isEqualToData:[@"open-browser ready" dataUsingEncoding:NSUTF8StringEncoding]];
|
|
76
|
+
dispatch_async(dispatch_get_main_queue(), ^{
|
|
77
|
+
if (!self.service.running || self.quitting) return;
|
|
78
|
+
NSDictionary *event = [message isKindOfClass:NSDictionary.class] ? message : nil;
|
|
79
|
+
if (ready || [event[@"ready"] isEqual:@YES]) self.ready = YES;
|
|
80
|
+
if ([event[@"event"] isEqual:@"desktop.bar"]) [self.bar update:event[@"bar"]];
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
[line setLength:0]; skip = NO;
|
|
84
|
+
start = newline + 1;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
- (void)showError:(NSString *)message {
|
|
89
|
+
NSAlert *alert = [NSAlert new];
|
|
90
|
+
alert.messageText = @"open-browser";
|
|
91
|
+
alert.informativeText = message;
|
|
92
|
+
[NSApp activateIgnoringOtherApps:YES];
|
|
93
|
+
[alert runModal];
|
|
94
|
+
}
|
|
95
|
+
- (BOOL)applicationShouldHandleReopen:(NSApplication *)app hasVisibleWindows:(BOOL)flag {
|
|
96
|
+
if (self.ready && self.service.running) kill(self.service.processIdentifier, SIGUSR2);
|
|
97
|
+
return YES;
|
|
98
|
+
}
|
|
99
|
+
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)app {
|
|
100
|
+
if (!self.service.running) return NSTerminateNow;
|
|
101
|
+
self.quitting = YES;
|
|
102
|
+
[self.bar stop];
|
|
103
|
+
[self.service terminate];
|
|
104
|
+
return NSTerminateLater;
|
|
105
|
+
}
|
|
106
|
+
@end
|
|
107
|
+
|
|
108
|
+
int main(int argc, const char *argv[]) {
|
|
109
|
+
@autoreleasepool {
|
|
110
|
+
NSApplication *app = [NSApplication sharedApplication];
|
|
111
|
+
[app setActivationPolicy:NSApplicationActivationPolicyAccessory];
|
|
112
|
+
__attribute__((objc_precise_lifetime)) Launcher *delegate = [Launcher new];
|
|
113
|
+
app.delegate = delegate;
|
|
114
|
+
[app run];
|
|
115
|
+
}
|
|
116
|
+
return 0;
|
|
117
|
+
}
|