@seekskyworld/open-browser 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/Docs/open-browser-api.d.ts +23 -5
  2. package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +51 -3
  3. package/README.md +14 -5
  4. package/README.zh-CN.md +16 -5
  5. package/access-registry.mjs +5 -0
  6. package/action-execution.mjs +32 -21
  7. package/api-contract.mjs +14 -2
  8. package/browser-extension/manifest.json +1 -4
  9. package/browser-extension/newtab.css +6 -0
  10. package/browser-extension/newtab.js +53 -2
  11. package/browser-extension/phase-labels.js +1 -1
  12. package/browser-extension/popup.css +1 -1
  13. package/browser-extension/popup.html +14 -4
  14. package/browser-extension/popup.js +101 -20
  15. package/browser-extension/tab-action.js +3 -2
  16. package/browser-extension/worker.js +102 -9
  17. package/build-profile.mjs +23 -0
  18. package/capability-matrix.mjs +3 -3
  19. package/chromium-host.mjs +78 -18
  20. package/chromium-shell.mjs +77 -48
  21. package/cli.mjs +59 -1
  22. package/contract-validation.mjs +1 -1
  23. package/desktop/Info.plist +1 -1
  24. package/desktop/OBControlBar.m +7 -3
  25. package/desktop/WorkspacePanel.m +2 -1
  26. package/desktop/brand-keychain.py +20 -4
  27. package/desktop/build-macos.mjs +26 -10
  28. package/desktop/build-managed-input.mjs +37 -0
  29. package/desktop/build-profile.mjs +6 -0
  30. package/desktop/build.mjs +8 -0
  31. package/desktop/macos-entitlements.plist +12 -0
  32. package/desktop/notarize-macos.mjs +145 -0
  33. package/desktop/package-macos.mjs +54 -0
  34. package/desktop/patches/chromium-managed-input.patch +144 -0
  35. package/desktop/sign.mjs +48 -4
  36. package/desktop/start-profile.mjs +5 -0
  37. package/desktop/start.mjs +25 -3
  38. package/desktop/verify-macos-release.mjs +61 -0
  39. package/diagnostics.mjs +9 -0
  40. package/engine-service.mjs +174 -18
  41. package/managed-input.mjs +138 -0
  42. package/mcp-http.mjs +84 -0
  43. package/mcp-server.mjs +41 -0
  44. package/mcp.mjs +2 -40
  45. package/package.json +22 -2
  46. package/page-activity.mjs +95 -28
  47. package/page-observation.mjs +41 -3
  48. package/paths.mjs +5 -3
  49. package/receipt-store.mjs +9 -2
  50. package/runtime.mjs +10 -1
  51. package/sdk.mjs +32 -15
  52. package/service.mjs +21 -2
  53. package/skill-links.mjs +90 -0
  54. package/skills/open-browser/SKILL.macos.md +112 -0
  55. package/skills/open-browser/SKILL.md +24 -3
  56. package/skills/open-browser/SKILL.windows.md +112 -0
  57. package/skills/open-browser/scripts/bootstrap.mjs +80 -1
  58. package/tab-adoption.mjs +77 -0
  59. package/uploads.mjs +4 -4
  60. package/workspace-lifecycle.mjs +74 -6
  61. package/workspace-state.mjs +14 -2
package/chromium-host.mjs CHANGED
@@ -1,36 +1,86 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { randomUUID } from 'node:crypto';
3
3
 
4
+ import { managedInput } from './managed-input.mjs';
4
5
  import { pageActivity } from './page-activity.mjs';
5
6
  import { desktopCapabilities } from './capability-matrix.mjs';
6
7
 
7
8
  export const extensionId = 'ehmdmliolflappfnmopemgojhbiilmpl';
8
9
  const workerUrl = 'chrome-extension://' + extensionId + '/worker.js';
9
10
  const isHost = worker => worker.url() === workerUrl;
11
+ const WORKER_EVAL_TIMEOUT_MS = 5000;
12
+
13
+ export function classifyExtensionFailure({ dispatched = false } = {}) {
14
+ return dispatched
15
+ ? { code: 'host_timeout', message: 'open-browser 扩展已收到请求,但本机服务未在时限内返回。请检查服务状态后重试。' }
16
+ : { code: 'host_unavailable', message: 'open-browser 扩展未连接到本机服务,请先启动应用后重试。' };
17
+ }
18
+
19
+ function extensionError(code, message, cause) {
20
+ return Object.assign(new Error(message, cause ? { cause } : undefined), { code });
21
+ }
22
+
23
+ async function evaluateWorker(host, pageFunction, arg) {
24
+ let timer;
25
+ try {
26
+ return await Promise.race([
27
+ host.evaluate(pageFunction, arg),
28
+ new Promise((_, reject) => {
29
+ timer = setTimeout(() => reject(extensionError(
30
+ 'extension_worker_timeout',
31
+ 'open-browser 扩展 service worker 响应超时,请检查扩展状态后重试.',
32
+ )), WORKER_EVAL_TIMEOUT_MS);
33
+ }),
34
+ ]);
35
+ } finally {
36
+ clearTimeout(timer);
37
+ }
38
+ }
10
39
 
11
40
  // No page bindings, shared secret or loopback listener. Only our packaged
12
41
  // extension's service worker can submit desktop control requests.
13
42
  export async function chromiumHost(context) {
14
43
  const findWorker = () => context.serviceWorkers().find(isHost);
15
- const worker = async () => findWorker() || context.waitForEvent('serviceworker', { predicate: isHost, timeout: 10000 });
44
+ const worker = async () => {
45
+ const current = findWorker();
46
+ if (current) return current;
47
+ try {
48
+ return await context.waitForEvent('serviceworker', { predicate: isHost, timeout: 10000 });
49
+ } catch (cause) {
50
+ throw extensionError('extension_unavailable', 'open-browser 工作区扩展未运行,请重新启动应用或重新加载扩展.', cause);
51
+ }
52
+ };
16
53
  let initial = await worker();
17
- const currentVersion = host => host.evaluate(() => globalThis.openBrowserGroupVersion);
18
- if (await currentVersion(initial) !== 10) {
54
+ const currentVersion = host => evaluateWorker(host, () => globalThis.openBrowserGroupVersion);
55
+ if (await currentVersion(initial) !== 12) {
19
56
  // A persistent Chromium profile can start the previous cached MV3 worker.
20
57
  const replacement = context.waitForEvent('serviceworker', { predicate: isHost, timeout: 10000 });
21
58
  try {
22
- [initial] = await Promise.all([replacement, initial.evaluate(() => {
59
+ [initial] = await Promise.all([replacement, evaluateWorker(initial, () => {
23
60
  setTimeout(() => chrome.runtime.reload(), 0);
24
61
  })]);
25
62
  } catch (cause) {
26
63
  // Chromium can defer the replacement worker until its next profile launch.
27
64
  throw Object.assign(new Error('工作区扩展已请求更新', { cause }), { code: 'extension_reload' });
28
65
  }
29
- if (await currentVersion(initial) !== 10) throw new Error('请重新构建 open-browser 工作区扩展。');
66
+ if (await currentVersion(initial) !== 12) throw new Error('请重新构建 open-browser 工作区扩展。');
30
67
  }
31
68
  let stopped = false;
32
69
  let lastState;
33
70
  const effects = pageActivity();
71
+ const configuredGuard = process.env.OPEN_BROWSER_INPUT_GUARD?.trim().toLowerCase();
72
+ // All packaged profiles use the page-level fallback unless a Chromium build
73
+ // provides the native event-aware guard. `off` remains an explicit
74
+ // diagnostics override.
75
+ const guardMode = configuredGuard || 'fallback';
76
+ if (!['off', 'fallback', 'native'].includes(guardMode))
77
+ throw extensionError('invalid_input_guard_mode', 'OPEN_BROWSER_INPUT_GUARD 必须是 off、fallback 或 native。');
78
+ const guarded = guardMode !== 'off';
79
+ const setInputGuard = guarded ? managedInput(context, tab => {
80
+ void worker().then(host => globalThis.openBrowserInputHint
81
+ ? evaluateWorker(host, pageId => globalThis.openBrowserInputHint(pageId), tab.id)
82
+ : undefined).catch(() => {});
83
+ }, { allowFallback: guardMode === 'fallback', forceFallback: guardMode === 'fallback' }) : undefined;
34
84
  let revision = 0, wakeSync;
35
85
  function changed() { revision++; wakeSync?.(); }
36
86
  const allowed = new Set(desktopCapabilities);
@@ -43,13 +93,13 @@ export async function chromiumHost(context) {
43
93
  } catch (error) {
44
94
  response = { id: request.id, error: error.code || 'operation_failed' };
45
95
  }
46
- await host.evaluate(value => globalThis.openBrowserReply(value), response);
96
+ await evaluateWorker(host, value => globalThis.openBrowserReply(value), response);
47
97
  }
48
98
  async function requests(call) {
49
99
  while (!stopped) {
50
100
  try {
51
101
  const host = await worker();
52
- const request = await host.evaluate(() => globalThis.openBrowserNext());
102
+ const request = await evaluateWorker(host, () => globalThis.openBrowserNext());
53
103
  if (!request || stopped) continue;
54
104
  // Accept takeover while a longer popup operation (such as login) is in flight.
55
105
  void respond(host, request, call).catch(() => {});
@@ -66,10 +116,11 @@ export async function chromiumHost(context) {
66
116
  workspaceId, agentName, name, mode, controlGeneration, pages: pages.map(({pageId}) => ({pageId})),
67
117
  running: activity.running, currentPageId: activity.current?.pageId, stepKind: activity.current?.stepKind,
68
118
  dispatchState: activity.current?.dispatchState, phase: activity.phase, needsCredential: activity.needsCredential,
119
+ needsHumanVerification: activity.needsHumanVerification,
69
120
  }));
70
121
  const signature = JSON.stringify(state);
71
122
  if (signature !== lastState) {
72
- await (await worker()).evaluate(items => globalThis.openBrowserSync(items), state);
123
+ await evaluateWorker(await worker(), items => globalThis.openBrowserSync(items), state);
73
124
  lastState = signature;
74
125
  }
75
126
  } catch { lastState = undefined; }
@@ -80,19 +131,25 @@ export async function chromiumHost(context) {
80
131
  wakeSync = undefined;
81
132
  }
82
133
  }
83
- const frontTab = async () => (await worker()).evaluate(() => globalThis.openBrowserFrontTab());
134
+ const frontTab = async () => evaluateWorker(await worker(), () => globalThis.openBrowserFrontTab());
84
135
  let lastBar;
85
136
  async function watchFrontTab(send) {
137
+ let frontRevision = 0;
86
138
  while (!stopped) {
87
- const bar = await frontTab().catch(() => null);
139
+ const bar = await frontTab().catch(() => null);
88
140
  const signature = JSON.stringify(bar);
89
141
  if (!stopped && signature !== lastBar) {
90
142
  lastBar = signature;
91
143
  send(bar);
92
144
  }
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);
145
+ const host = await worker().catch(() => null);
146
+ if (!host) { await delay(300); continue; }
147
+ const next = await evaluateWorker(host, ({ after }) => {
148
+ if (typeof globalThis.openBrowserWaitFrontTabChange !== 'function') return null;
149
+ return globalThis.openBrowserWaitFrontTabChange(after);
150
+ }, { after: frontRevision }).catch(() => null);
151
+ if (next === null) { await delay(300); continue; }
152
+ frontRevision = await next;
96
153
  }
97
154
  }
98
155
  async function clickBar(frame, call) {
@@ -114,15 +171,18 @@ export async function chromiumHost(context) {
114
171
  await call(front.mode === 'agent' ? 'takeControl' : 'returnToAgent', { workspaceId, pageId, controlGeneration });
115
172
  }
116
173
  return {
174
+ setInputGuard,
175
+ withAgentInput: setInputGuard?.withAgentInput,
176
+ inputGuardMode: guarded ? guardMode : 'off',
117
177
  onActionTarget(event) { if (!stopped) effects.target(event); },
118
178
  onActivity(view) { if (!stopped) { effects.update(view); changed(); } },
119
- async groupTab(page, workspaceId, name, mode, agentName, pageId) {
179
+ async groupTab(page, workspaceId, name, mode, agentName, pageId, controlGeneration, preserveGroup) {
120
180
  const session = await context.newCDPSession(page);
121
181
  let retained = false;
122
182
  try {
123
183
  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);
184
+ const args = { targetId: targetInfo.targetId, workspaceId, name, mode, agentName, pageId, controlGeneration, preserveGroup };
185
+ await evaluateWorker(await worker(), info => globalThis.openBrowserGroup(info), args);
126
186
  if (pageId && !effects.has(pageId)) {
127
187
  effects.track(page, session, workspaceId, pageId);
128
188
  retained = true;
@@ -132,12 +192,12 @@ export async function chromiumHost(context) {
132
192
  } finally { if (!retained) await session.detach().catch(() => {}); }
133
193
  },
134
194
  async releaseTab(page, workspaceId, pageId) {
135
- if (!page.isClosed()) await (await worker()).evaluate(params => globalThis.openBrowserRelease(params), {workspaceId,pageId});
195
+ if (!page.isClosed()) await evaluateWorker(await worker(), params => globalThis.openBrowserRelease(params), {workspaceId,pageId});
136
196
  await effects.release(pageId);
137
197
  lastState = undefined;
138
198
  changed();
139
199
  },
140
- async show() { await (await worker()).evaluate(() => globalThis.openBrowserShow()); },
200
+ async show() { await evaluateWorker(await worker(), () => globalThis.openBrowserShow()); },
141
201
  clickBar,
142
202
  start(call, onBar) {
143
203
  void requests(call);
@@ -6,9 +6,11 @@ import path from 'node:path';
6
6
  import { promisify } from 'node:util';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import { chromium } from 'playwright-core';
9
+ import { tmpdir } from 'node:os';
9
10
  import { stateDir } from './paths.mjs';
10
11
  import { engineExecutable } from './runtime.mjs';
11
12
  import { chromiumPrivacyArgs } from './privacy-config.mjs';
13
+ import { isDevelopmentBuild } from './build-profile.mjs';
12
14
 
13
15
  const extensionDir = fileURLToPath(new URL('./browser-extension', import.meta.url));
14
16
  const extensionId = 'ehmdmliolflappfnmopemgojhbiilmpl';
@@ -16,12 +18,22 @@ const extensionId = 'ehmdmliolflappfnmopemgojhbiilmpl';
16
18
  const mac = process.platform === 'darwin';
17
19
  const defaultProfile = path.join(stateDir, mac ? 'open-browser-profile-v2' : 'open-browser-profile');
18
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
+ }
19
31
 
20
32
  async function macPersistentEngine() {
21
33
  const here = fileURLToPath(new URL('.', import.meta.url));
22
34
  const appCode = path.join('Contents', 'Resources', 'app');
23
35
  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');
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');
25
37
  try {
26
38
  const engineDir = await realpath(path.join(outer, appCode, '.open-browser', 'engine'));
27
39
  const { version } = createRequire(import.meta.url)('playwright-core/package.json');
@@ -30,11 +42,11 @@ async function macPersistentEngine() {
30
42
  const executable = await realpath(path.resolve(engineDir, manifest.executable));
31
43
  const relative = path.relative(engineDir, executable);
32
44
  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');
45
+ !relative.endsWith((isDevelopmentBuild ? '/open-browser-dev.app' : '/open-browser.app') + '/Contents/MacOS/open-browser')) throw new Error('invalid branded engine path');
34
46
  const { stderr } = await run('/usr/bin/codesign', ['-dv', '--verbose=2', outer]);
35
47
  const team = /^TeamIdentifier=([A-Z0-9]{10})$/m.exec(stderr)?.[1];
36
48
  if (!team) throw new Error('Developer ID team required');
37
- const requirement = 'identifier "local.open-browser.chromium" and anchor apple generic and ' +
49
+ const requirement = 'identifier "local.open-browser' + (isDevelopmentBuild ? '-dev' : '') + '.chromium" and anchor apple generic and ' +
38
50
  'certificate 1[field.1.2.840.113635.100.6.2.6] exists and ' +
39
51
  'certificate leaf[field.1.2.840.113635.100.6.1.13] exists and certificate leaf[subject.OU] = "' + team + '"';
40
52
  await run('/usr/bin/codesign', ['--verify', '-R=' + requirement, path.resolve(executable, '../../..')]);
@@ -100,51 +112,68 @@ async function seedProfile(profileDir) {
100
112
  }
101
113
 
102
114
  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(() => {});
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
+ }
141
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;
142
178
  }
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
179
  }
package/cli.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { writeFile } from 'node:fs/promises';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { createInterface } from 'node:readline';
3
4
  import { socketPath, adminTokenPath } from './paths.mjs';
4
5
  import { localRequest, agentMethods, OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
5
6
 
@@ -13,6 +14,8 @@ const help = `open-browser <method> [< params.json]
13
14
  printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","pageId":"PAGE_ID"}' | open-browser observe
14
15
  printf '%s\\n' '{"workspaceId":"WORKSPACE_ID","operationId":"finish-UNIQUE-ID","keepPageIds":[]}' | open-browser finishWorkspace
15
16
 
17
+ open-browser session # 每行读取 {"id":1,"method":"observe","params":{...}},直到 stdin 关闭
18
+
16
19
  echo '{"name":"网页检查","agentName":"研究助手"}' | node cli.mjs createWorkspace
17
20
  echo '{"url":"https://example.org","name":"网页检查"}' | node cli.mjs open
18
21
  node cli.mjs listWorkspaces
@@ -23,8 +26,24 @@ const help = `open-browser <method> [< params.json]
23
26
  需要完整参数契约时运行:node cli.mjs --schema
24
27
  本机管理命令:admin.pair、admin.list、admin.grant、admin.revoke、admin.revokeClient、admin.clearHistory、admin.scheduler、admin.setPixelPermission。
25
28
  凭据在可信的本地控制台设置;使用 fillCredential 和 credentialRef 填写登录字段。
29
+ open-browser skill # 输出与当前包版本匹配的 Skill 指南
26
30
  `;
27
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
+
28
47
  async function readParams() {
29
48
  const chunks = [];
30
49
  let bytes = 0;
@@ -40,13 +59,52 @@ async function readParams() {
40
59
  catch { throw new OpenBrowserError('INVALID_JSON', '标准输入必须是 JSON 对象。'); }
41
60
  }
42
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
+
43
91
  async function main() {
44
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
+ }
45
98
  if (method === '--schema') {
46
99
  const { tools } = await import('./api-contract.mjs');
47
100
  process.stdout.write(JSON.stringify(tools, null, 2) + '\n');
48
101
  return;
49
102
  }
103
+ if (method === 'skill') {
104
+ if (extra.length) throw new OpenBrowserError('INVALID_PARAMS', 'skill 不接受额外参数。');
105
+ await printSkillGuide();
106
+ return;
107
+ }
50
108
  if (!method || method === '--help' || method === '-h') {
51
109
  process.stdout.write(help);
52
110
  return;
@@ -7,7 +7,7 @@ const schemas = new Map(tools.map(tool => [tool.name,tool.inputSchema]));
7
7
  // Older callers spread a returned page or workspace handle into a subsequent request.
8
8
  // Strip only the known read-only handle fields before checking that request.
9
9
  const viewFields = new Set(['agentName','name','mode','pages','controlGeneration','activity','blockedOrigins','pageId','origin','title','profile','profileId','profileAlias',
10
- 'openedByOperationId','openerPageId','documentId','pendingDialogs']);
10
+ 'pageAvailability','nextAction','scope','accountAlias','ownership','syncState','syncRevision','lastSyncedAt','security','openedByOperationId','openerPageId','documentId','pendingDialogs']);
11
11
 
12
12
  export function checkAgentRequest(method, params) {
13
13
  const schema = schemas.get(method);
@@ -8,6 +8,6 @@
8
8
  <key>CFBundlePackageType</key><string>APPL</string>
9
9
  <key>CFBundleIconFile</key><string>open-browser.icns</string>
10
10
  <key>CFBundleVersion</key><string>1</string>
11
- <key>CFBundleShortVersionString</key><string>0.1.0</string>
11
+ <key>CFBundleShortVersionString</key><string>0.2.0</string>
12
12
  <key>NSHighResolutionCapable</key><true/>
13
13
  </dict></plist>
@@ -130,9 +130,12 @@ static NSString *Text(id value) { return [value isKindOfClass:NSString.class] ?
130
130
 
131
131
  - (BOOL)frontMatches:(CGRect)bounds {
132
132
  NSRunningApplication *front = NSWorkspace.sharedWorkspace.frontmostApplication;
133
- if (![front.bundleIdentifier isEqual:@"local.open-browser.chromium"] || front.hidden) return NO;
133
+ BOOL dev = [NSBundle.mainBundle.bundleIdentifier isEqual:@"local.open-browser.desktop-dev"];
134
+ NSString *engineID = dev ? @"local.open-browser-dev.chromium" : @"local.open-browser.chromium";
135
+ if (![front.bundleIdentifier isEqual:engineID] || front.hidden) return NO;
134
136
  NSString *path = front.executableURL.URLByResolvingSymlinksInPath.path;
135
- return [path hasPrefix:self.rootPrefix] && [path hasSuffix:@"/open-browser.app/Contents/MacOS/open-browser"] &&
137
+ NSString *suffix = dev ? @"/open-browser-dev.app/Contents/MacOS/open-browser" : @"/open-browser.app/Contents/MacOS/open-browser";
138
+ return [path hasPrefix:self.rootPrefix] && [path hasSuffix:suffix] &&
136
139
  IsChildOfService(front.processIdentifier, self.servicePID) && FrontWindowMatches(front.processIdentifier, bounds);
137
140
  }
138
141
 
@@ -177,10 +180,11 @@ static NSString *Text(id value) { return [value isKindOfClass:NSString.class] ?
177
180
  if (![self.pending isEqual:binding]) self.pending = nil;
178
181
  BOOL human = [bar[@"mode"] isEqual:@"human"], transferring = [bar[@"mode"] isEqual:@"transferring"];
179
182
  NSDictionary *states = @{@"actionability":@"检查目标", @"dispatching":@"正在派发", @"waiting":@"等待页面", @"verifying":@"核对结果", @"dispatched":@"已派发", @"running":@"执行中", @"queued":@"已排队", @"idle":@"待命", @"completed":@"已完成",
180
- @"needs_credential":@"等待凭据", @"failed":@"失败", @"cancelled":@"已取消", @"outcome_unknown":@"待核实"};
183
+ @"needs_credential":@"等待凭据", @"needs_human_verification":@"需要人工验证", @"failed":@"失败", @"cancelled":@"已取消", @"outcome_unknown":@"待核实"};
181
184
  self.agent.stringValue = Text(bar[@"agentName"]).length ? bar[@"agentName"] : @"Agent";
182
185
  self.agent.toolTip = self.agent.stringValue;
183
186
  self.status.stringValue = transferring ? @"交接中" : human ? @"人工控制" : states[Text(bar[@"phase"])] ?: @"待命";
187
+ self.button.bezelColor = !human && !transferring && [bar[@"inputBlocked"] boolValue] ? NSColor.systemOrangeColor : nil;
184
188
  self.button.title = human ? @"交回 Agent" : @"人工接管";
185
189
  self.delivery.enabled = !transferring;
186
190
  self.button.enabled = !transferring && !self.pending;
@@ -58,12 +58,13 @@ static NSString *Status(NSDictionary *workspace) {
58
58
  if ([workspace[@"mode"] isEqual:@"human"]) return @"用户控制 · Agent 已暂停";
59
59
  if ([workspace[@"mode"] isEqual:@"transferring"]) return @"正在交接控制权";
60
60
  NSDictionary *activity = workspace[@"activity"];
61
+ if ([activity[@"needsHumanVerification"] boolValue]) return @"需要人工验证";
61
62
  if ([activity[@"needsCredential"] boolValue]) return @"等待补充凭据";
62
63
  NSString *current = Operation(Map(activity[@"current"]));
63
64
  if (current.length) return current;
64
65
  NSDictionary *phase = @{@"running":@"执行中", @"actionability":@"检查目标", @"dispatching":@"正在派发",
65
66
  @"waiting":@"等待页面", @"verifying":@"核对结果", @"queued":@"排队中", @"completed":@"已完成", @"failed":@"执行失败",
66
- @"outcome_unknown":@"结果待核对", @"cancelled":@"已取消", @"needs_credential":@"等待补充凭据"};
67
+ @"outcome_unknown":@"结果待核对", @"cancelled":@"已取消", @"needs_credential":@"等待补充凭据", @"needs_human_verification":@"需要人工验证"};
67
68
  return phase[String(activity[@"phase"])] ?: @"等待指令";
68
69
  }
69
70
 
@@ -19,7 +19,10 @@ VERSION = '159.0.8154.6'
19
19
  REVISION = '98a2592026af8d673b9fa83b626ac68bdf4ae78a'
20
20
  FRAMEWORK = 'Google Chrome for Testing Framework'
21
21
  SOURCE = b'Chromium Safe Storage'
22
- PRODUCT = b'open-browser Keychain'
22
+ DEV = os.environ.get('OPEN_BROWSER_BUILD_PROFILE', '').strip().lower() == 'dev'
23
+ STABLE_PRODUCT = b'open-browser Keychain'
24
+ PRODUCT = b'open-browser Dev Safe' if DEV else STABLE_PRODUCT
25
+ EXPECTED_BUNDLE = 'local.open-browser-dev.chromium' if DEV else 'local.open-browser.chromium'
23
26
  # Mach CPU type -> offset in __TEXT,__const, input hash, branded hash.
24
27
  RELEASE = {
25
28
  0x0100000C: (225772584, 'a0a2e8854ce90268f5d9b32210cf53fc0709f4b798b3c3a96964ba3ebce4bc4b',
@@ -47,11 +50,24 @@ def in_readonly_constants(data, offset):
47
50
  return False
48
51
 
49
52
 
53
+ def matches_branded_digest(data, offset, stable_digest):
54
+ # Dev differs from the pinned Stable output at exactly this constant.
55
+ end = offset + len(PRODUCT)
56
+ if data[offset:end] != PRODUCT:
57
+ return False
58
+ view = memoryview(data)
59
+ digest = hashlib.sha256(view[:offset])
60
+ digest.update(STABLE_PRODUCT)
61
+ digest.update(view[end:])
62
+ return digest.hexdigest() == stable_digest
63
+
64
+
50
65
  def brand(bundle):
51
66
  bundle = bundle.resolve(strict=True)
52
67
  with (bundle / 'Contents/Info.plist').open('rb') as stream:
53
68
  info = plistlib.load(stream)
54
- if (bundle.name != 'open-browser.app' or info.get('CFBundleIdentifier') != 'local.open-browser.chromium'
69
+ expected_name = 'open-browser-dev.app' if DEV else 'open-browser.app'
70
+ if (bundle.name != expected_name or info.get('CFBundleIdentifier') != EXPECTED_BUNDLE
55
71
  or info.get('CFBundleShortVersionString') != VERSION
56
72
  or info.get('SCMRevision', '').split('-')[0] != REVISION):
57
73
  raise ValueError('Expected the staged open-browser Chromium bundle at the pinned upstream revision')
@@ -64,7 +80,7 @@ def brand(bundle):
64
80
  raise ValueError('Unrecognized framework architecture')
65
81
  offset, before, after = RELEASE[cpu]
66
82
  digest = hashlib.sha256(data).hexdigest()
67
- if digest == after:
83
+ if matches_branded_digest(data, offset, after):
68
84
  return
69
85
  if digest != before:
70
86
  raise ValueError('Framework SHA-256 differs from the reviewed official release')
@@ -73,7 +89,7 @@ def brand(bundle):
73
89
  or data.find(SOURCE) != offset or data.find(SOURCE, offset + 1) != -1):
74
90
  raise ValueError('Unexpected keychain service constant layout')
75
91
  data[offset:offset+len(SOURCE)] = PRODUCT
76
- if hashlib.sha256(data).hexdigest() != after:
92
+ if not matches_branded_digest(data, offset, after):
77
93
  raise ValueError('Unexpected branded framework digest')
78
94
  # Publish a fully verified copy atomically, even for hardlinked input.
79
95
  with NamedTemporaryFile(dir=binary.parent, prefix='.open-browser-keychain-', delete=False) as temp: