@seekskyworld/open-browser 0.1.0 → 0.3.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 (68) hide show
  1. package/Docs/open-browser-api.d.ts +32 -10
  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 +13 -3
  6. package/action-execution.mjs +60 -24
  7. package/api-contract.mjs +19 -7
  8. package/browser-extension/manifest.json +1 -4
  9. package/browser-extension/newtab.css +6 -0
  10. package/browser-extension/newtab.js +54 -2
  11. package/browser-extension/phase-labels.js +1 -1
  12. package/browser-extension/popup.css +1 -1
  13. package/browser-extension/popup.html +16 -4
  14. package/browser-extension/popup.js +122 -21
  15. package/browser-extension/tab-action.js +4 -2
  16. package/browser-extension/worker.js +102 -9
  17. package/build-profile.mjs +23 -0
  18. package/capability-matrix.mjs +4 -4
  19. package/chromium-host.mjs +81 -25
  20. package/chromium-shell.mjs +78 -49
  21. package/cli.mjs +63 -5
  22. package/contract-validation.mjs +1 -1
  23. package/desktop/Info.plist +2 -2
  24. package/desktop/OBControlBar.m +7 -3
  25. package/desktop/WorkspacePanel.m +4 -2
  26. package/desktop/brand-keychain.py +20 -4
  27. package/desktop/build-macos.mjs +31 -12
  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 +189 -0
  33. package/desktop/package-macos.mjs +54 -0
  34. package/desktop/patches/chromium-managed-input.patch +144 -0
  35. package/desktop/sign.mjs +63 -4
  36. package/desktop/start-profile.mjs +5 -0
  37. package/desktop/start.mjs +25 -3
  38. package/desktop/verify-macos-release.mjs +69 -0
  39. package/desktop/verify-version.mjs +22 -2
  40. package/diagnostics.mjs +9 -0
  41. package/engine-service.mjs +244 -29
  42. package/managed-input.mjs +155 -0
  43. package/mcp-http.mjs +84 -0
  44. package/mcp-server.mjs +57 -0
  45. package/mcp.mjs +3 -40
  46. package/package.json +24 -3
  47. package/page-activity.mjs +97 -29
  48. package/page-observation.mjs +44 -3
  49. package/paths.mjs +5 -3
  50. package/receipt-store.mjs +24 -7
  51. package/runtime.mjs +10 -1
  52. package/sdk.mjs +53 -26
  53. package/service.mjs +45 -10
  54. package/skill-links.mjs +144 -0
  55. package/skills/open-browser/SKILL.md +8 -76
  56. package/skills/open-browser/references/macos.md +3 -0
  57. package/skills/open-browser/references/operations.md +59 -0
  58. package/skills/open-browser/references/recovery.md +36 -0
  59. package/skills/open-browser/references/windows.md +3 -0
  60. package/skills/open-browser/scripts/bootstrap.mjs +112 -45
  61. package/skills/open-browser/scripts/guide.mjs +17 -0
  62. package/studio/studio.js +2 -2
  63. package/tab-adoption.mjs +83 -0
  64. package/tab-recovery.mjs +100 -0
  65. package/uploads.mjs +4 -4
  66. package/visual-page.mjs +17 -7
  67. package/workspace-lifecycle.mjs +92 -8
  68. package/workspace-state.mjs +65 -12
@@ -74,6 +74,39 @@ export function inspectDocument(options = {}) {
74
74
  foreground={role:front.getAttribute('role') || 'dialog',name:(label || front.getAttribute('aria-label') || '').slice(0,160),
75
75
  bounds:{x,y,width,height}};
76
76
  }
77
+ if (options.canvas) {
78
+ const root = front || document;
79
+ let truncated = false;
80
+ const rows = (selector, describe) => {
81
+ const result = [];
82
+ for (const el of root.querySelectorAll(selector)) {
83
+ if (!visible(el) || composedMatch(el, 'input,textarea,select,[contenteditable]')) continue;
84
+ if (result.length >= 100) { truncated = true; break; }
85
+ result.push(describe(el));
86
+ }
87
+ return result;
88
+ };
89
+ const label = el => visibleText(el, 512) || (el.getAttribute('aria-label') || '').slice(0, 512);
90
+ const nodeRows = rows('.react-flow__node', el => ({
91
+ id:(el.getAttribute('data-id') || '').slice(0,128), label:label(el), selected:el.classList.contains('selected')
92
+ }));
93
+ const edges = rows('.react-flow__edge', el => {
94
+ const accessibleLabel = (el.getAttribute('aria-label') || '').slice(0,512);
95
+ const endpoints = /^Edge from (\S+) to (\S+)$/.exec(accessibleLabel);
96
+ return {id:(el.getAttribute('data-id') || '').slice(0,128), label:accessibleLabel || label(el),
97
+ selected:el.classList.contains('selected'), ...(endpoints && {source:endpoints[1],target:endpoints[2]})};
98
+ });
99
+ const messages = rows('[data-message-author-role], [role="log"] > [role="article"]', el => ({
100
+ role:['user','assistant','system','tool'].includes(el.dataset.messageAuthorRole) ? el.dataset.messageAuthorRole : 'message',
101
+ text:label(el)
102
+ }));
103
+ const attachments = rows('a[download]', el => ({label:label(el)}));
104
+ const adapter = root.querySelector('.react-flow') ? 'react-flow' : messages.length ? 'chat' : 'unsupported';
105
+ const reason = adapter === 'unsupported' && ([...root.querySelectorAll('canvas')].some(visible)
106
+ ? 'canvas_without_semantic_adapter' : 'no_supported_markup');
107
+ return {adapter, ...(reason && {reason}),
108
+ nodes:nodeRows, edges, messages, attachments, truncated};
109
+ }
77
110
  const nodes=[],details=[];
78
111
  function stateOf(el) {
79
112
  const state = {};
@@ -245,10 +278,18 @@ export async function observeFrames(page, origins, redact, padding=0) {
245
278
  let remaining = 8000;
246
279
  // Direct visible child frames only. A blank or opaque sandbox has no
247
280
  // explicit HTTP(S) origin. No cross-frame action handles leave this helper.
248
- for (const frame of page.mainFrame().childFrames().slice(0, 16)) {
249
- if (!remaining || !origins.has(URL.parse(frame.url())?.origin)) continue;
281
+ const candidates = page.mainFrame().childFrames().slice(0, 16)
282
+ .filter(frame => origins.has(URL.parse(frame.url())?.origin));
283
+ const allowed = (await Promise.all(candidates.map(async frame => {
284
+ try { return await frameAllowed(frame, origins) ? frame : null; }
285
+ catch (error) {
286
+ if (!frame.isDetached() && !/context was destroyed|navigat/i.test(error.message)) throw error;
287
+ return null;
288
+ }
289
+ }))).filter(Boolean);
290
+ for (const frame of allowed) {
291
+ if (!remaining) break;
250
292
  try {
251
- if (!(await frameAllowed(frame,origins))) continue;
252
293
  const data=await frame.evaluate(inspectDocument,{textOnly:true,origins:[...origins],textLimit:remaining,padding});
253
294
  if (data && origins.has(data.origin) && URL.parse(frame.url())?.origin === data.origin) {
254
295
  const text = redact(data.text,data.textWindowInfo);
package/paths.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { homedir } from 'node:os';
3
3
  import path from 'node:path';
4
+ import { buildProfile, scopedBuildRoot } from './build-profile.mjs';
4
5
 
5
6
  export const profileId = process.env.OPEN_BROWSER_PROFILE || 'default';
6
- const base = path.resolve(process.env.OPEN_BROWSER_STATE_DIR || path.join(homedir(), '.open-browser'));
7
+ const base = scopedBuildRoot(path.resolve(process.env.OPEN_BROWSER_STATE_DIR || path.join(homedir(), '.open-browser')));
7
8
 
8
9
  export function pathsForProfile(id) {
9
10
  if (typeof id !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,47}$/.test(id)) throw new Error('invalid_profile');
@@ -13,8 +14,9 @@ export function pathsForProfile(id) {
13
14
  const socketPath = process.platform === 'win32'
14
15
  ? '\\\\.\\pipe\\open-browser-' + instance
15
16
  : Buffer.byteLength(socketFile) < 100 ? socketFile : path.join('/tmp', 'open-browser-' + process.getuid() + '-' + instance + '.sock');
16
- return {stateDir, socketPath, tokenPath:path.join(stateDir, 'open-browser.token')};
17
+ return {stateDir, socketPath, tokenPath:path.join(stateDir, 'open-browser.token'), pidPath:path.join(stateDir, 'open-browser.pid')};
17
18
  }
18
19
 
19
- export const {stateDir, socketPath, tokenPath} = pathsForProfile(profileId);
20
+ export { buildProfile };
21
+ export const {stateDir, socketPath, tokenPath, pidPath} = pathsForProfile(profileId);
20
22
  export const adminTokenPath = path.join(stateDir, 'open-browser-admin.token');
package/receipt-store.mjs CHANGED
@@ -28,6 +28,7 @@ export class ReceiptStore {
28
28
  inflight INTEGER NOT NULL, expires INTEGER NOT NULL, PRIMARY KEY(owner,workspace,operation));
29
29
  CREATE TABLE IF NOT EXISTS recovery_objects (
30
30
  owner TEXT NOT NULL, workspace TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, expires INTEGER NOT NULL,
31
+ origin TEXT,
31
32
  PRIMARY KEY(owner,workspace,kind,id));
32
33
  CREATE INDEX IF NOT EXISTS recovery_expiry ON recovery_objects(expires);
33
34
  CREATE INDEX IF NOT EXISTS receipt_expiry ON receipts(expires);
@@ -36,6 +37,10 @@ export class ReceiptStore {
36
37
  operationId TEXT, completedSteps INTEGER, expires INTEGER, actorId TEXT, pixelWidth INTEGER, pixelHeight INTEGER);
37
38
  CREATE INDEX IF NOT EXISTS event_feed ON events(owner,workspace,sequence);
38
39
  CREATE INDEX IF NOT EXISTS event_expiry ON events(expires);`);
40
+ if (!this.db.prepare('PRAGMA table_info(recovery_objects)').all().some(field => field.name === 'disposition'))
41
+ this.db.exec('ALTER TABLE recovery_objects ADD COLUMN disposition TEXT');
42
+ if (!this.db.prepare('PRAGMA table_info(recovery_objects)').all().some(field => field.name === 'origin'))
43
+ this.db.exec('ALTER TABLE recovery_objects ADD COLUMN origin TEXT');
39
44
  this.sweep = this.db.prepare('DELETE FROM receipts WHERE expires <= ?');
40
45
  this.sweepRecovery = this.db.prepare('DELETE FROM recovery_objects WHERE expires<=?');
41
46
  this.sweepRecovery.run(Date.now());
@@ -60,15 +65,26 @@ export class ReceiptStore {
60
65
  }
61
66
  }
62
67
 
63
- remember(owner, workspace, kind, id) {
64
- this.db.prepare('INSERT OR REPLACE INTO recovery_objects VALUES (?,?,?,?,?)')
65
- .run(owner, workspace, kind, id, Date.now() + retentionMs);
68
+ remember(owner, workspace, kind, id, {origin = null} = {}) {
69
+ this.db.prepare('INSERT OR REPLACE INTO recovery_objects(owner,workspace,kind,id,expires,origin) VALUES (?,?,?,?,?,?)')
70
+ .run(owner, workspace, kind, id, Date.now() + retentionMs, origin);
71
+ }
72
+
73
+ pageDisposition(owner, workspace, id, disposition) {
74
+ this.db.prepare("UPDATE recovery_objects SET disposition=? WHERE owner=? AND workspace=? AND kind='page' AND id=?")
75
+ .run(disposition, owner, workspace, id);
76
+ }
77
+
78
+ closeReason(owner, workspace) {
79
+ const row = this.db.prepare("SELECT state FROM events WHERE owner=? AND workspace=? AND kind='workspace_end' AND expires>? ORDER BY sequence DESC LIMIT 1")
80
+ .get(owner, workspace, Date.now());
81
+ return row?.state ?? 'unknown';
66
82
  }
67
83
 
68
84
  recoveryObjects(owner, workspace, after = 0, limit = 50) {
69
85
  if (!Number.isSafeInteger(after) || after < 0) throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
70
86
  // ReceiptStore.list has already validated the common limit.
71
- const rows = this.db.prepare('SELECT rowid,kind,id FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
87
+ const rows = this.db.prepare('SELECT rowid,kind,id,disposition,origin FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
72
88
  .all(owner, workspace, Date.now(), after, limit + 1);
73
89
  return {records:rows.slice(0,limit), nextObjectCursor:rows.length > limit ? rows[limit-1].rowid : null};
74
90
  }
@@ -131,15 +147,16 @@ export class ReceiptStore {
131
147
 
132
148
  waitForEvent(owner,{workspaceId,pageId,operationId,kind,after,timeoutMs=5000}) {
133
149
  if (!Number.isSafeInteger(after) || after<0 || !Number.isSafeInteger(timeoutMs) || timeoutMs<1 || timeoutMs>10000 ||
134
- !['dialog','popup','download'].includes(kind) || typeof pageId!=='string' ||
150
+ (!['dialog','popup','download','page_bound'].includes(kind)) ||
151
+ (typeof pageId!=='string' && !(kind==='page_bound' && pageId===undefined)) ||
135
152
  (operationId!==undefined && typeof operationId!=='string'))
136
153
  throw Object.assign(new Error('invalid_params'),{code:'invalid_params'});
137
154
  const sql=`SELECT sequence,kind,state,pageId,resourceId,operationId FROM events
138
- WHERE owner=? AND workspace=? AND pageId=? AND kind=? AND sequence>? AND expires>?
155
+ WHERE owner=? AND workspace=? AND (? IS NULL OR pageId=?) AND kind=? AND sequence>? AND expires>?
139
156
  AND (? IS NULL OR operationId=?) ORDER BY sequence LIMIT 1`;
140
157
  const query=this.db.prepare(sql);
141
158
  const read=()=>{
142
- const row=query.get(owner,workspaceId,pageId,kind,after,Date.now(),operationId??null,operationId??null);
159
+ const row=query.get(owner,workspaceId,pageId??null,pageId??null,kind,after,Date.now(),operationId??null,operationId??null);
143
160
  if (row?.operationId===null) delete row.operationId;
144
161
  return row && {event:row,nextCursor:row.sequence};
145
162
  };
package/runtime.mjs CHANGED
@@ -8,9 +8,15 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
8
8
  const require = createRequire(import.meta.url);
9
9
  const version = require('playwright-core/package.json').version;
10
10
  const engineDir = fileURLToPath(new URL('./.open-browser/engine/', import.meta.url));
11
- const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${process.arch}.json`);
11
+ function targetArch() {
12
+ return process.env.OPEN_BROWSER_TARGET_ARCH?.trim() || process.arch;
13
+ }
12
14
 
13
15
  export async function engineExecutable() {
16
+ const arch = targetArch();
17
+ const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${arch}.json`);
18
+ if (process.platform === 'darwin' && !['arm64', 'x64'].includes(arch))
19
+ throw new Error('macOS 引擎目标架构必须是 arm64 或 x64。');
14
20
  try {
15
21
  const entry = JSON.parse(await readFile(manifest, 'utf8'));
16
22
  const executable = await realpath(path.join(engineDir, entry.executable));
@@ -24,6 +30,8 @@ export async function engineExecutable() {
24
30
  }
25
31
 
26
32
  async function install() {
33
+ if (process.platform === 'darwin' && targetArch() !== process.arch)
34
+ throw new Error(`当前 Node 是 ${process.arch},不能下载并登记 ${targetArch()} 引擎。请在对应架构的 macOS 或 Rosetta x64 Node 下运行。`);
27
35
  process.env.PLAYWRIGHT_BROWSERS_PATH = engineDir;
28
36
  const cli = path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js');
29
37
  execFileSync(process.execPath, [cli, 'install', 'chromium', '--no-shell'], { stdio: 'inherit' });
@@ -34,6 +42,7 @@ async function install() {
34
42
  binary = await installWindowsIcons(binary);
35
43
  }
36
44
  const executable = path.relative(engineDir, binary);
45
+ const manifest = path.join(engineDir, `engine-${version}-${process.platform}-${targetArch()}.json`);
37
46
  const temp = manifest + '.' + randomUUID();
38
47
  await writeFile(temp, JSON.stringify({ executable }) + '\n', { flag: 'wx' });
39
48
  await rename(temp, manifest);
package/sdk.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { request } from 'node:http';
2
+ import { Agent, request } from 'node:http';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { pathsForProfile, profileId } from './paths.mjs';
5
5
 
@@ -11,19 +11,33 @@ export { agentMethods };
11
11
  * service error. The hint never replaces the server error message.
12
12
  */
13
13
  export const recoveryHints = Object.freeze({
14
- SERVICE_UNAVAILABLE: '启动 open-browser 后重试同一只读请求。',
14
+ SERVICE_UNAVAILABLE: '请求尚未送达。启动 open-browser 并确认本机连接凭据可用后重试。',
15
+ RESPONSE_LOST: '创建任务后用 listWorkspaces 核对任务。已有工作区用 getWorkspace 核对页面。有 operationId 时用 getOperation 核对回执。只读查询可重新执行。',
15
16
  TASK_NAME_REQUIRED: '为 createWorkspace 或 open 提供清晰的非空 name,再重新创建任务。',
16
17
  REQUEST_TIMEOUT: '用同一 operationId 查询 getOperation 或 diagnoseOperation,再决定是否继续。',
17
18
  stale_ref: '重新 observe 当前页面并用新 ref 构造动作。',
18
19
  stale_document: '重新 observe 当前页面后再执行动作。',
19
20
  stale_control: '重新 observe 获取最新 controlGeneration。',
20
21
  stale_observation: '重新 observe 当前页面,不要复用旧文档标识。',
21
- target_obscured: '重新 observe 并等待遮罩消失,再用新的 operationId 重试。',
22
+ target_obscured: '查看回执的 obstruction 和当前观察中的前景弹窗,确认遮罩消失后再操作。',
23
+ pixel_permission_required: '请用户在当前标签的扩展内为任务所有者授权截图。委托客户端需由管理员按 principalId 和 origin 授权。',
24
+ stale_visual_frame: '重新截取目标所在的稳定区域,并在该帧有效期内操作。',
22
25
  target_ambiguous: '用 observe 的 locator 或 within 缩小目标范围。',
23
26
  target_missing: '重新 observe 并核对页面状态或目标名称。',
24
27
  navigation_failed: '先 observe 当前页面和地址,再决定是否重试导航。',
25
28
  origin_denied: '核对 blockedOrigins,取得控制权后用 grantOrigin 授权所需来源。',
26
- workspace_under_user_control: '等待用户交回 Agent 控制权后重新 observe。',
29
+ profile_mismatch: '请切换至该标签页所在的 open-browser profile。',
30
+ adoption_expired: '请用户在原标签页重新签发授权,使用所选任务的 workspaceId 兑换。',
31
+ adoption_page_changed: '请用户核对当前标签和站点,再授权此页。',
32
+ adoption_requires_empty_workspace: '创建新的命名工作区,再让用户选择该任务。',
33
+ adoption_requires_private_workspace: '创建一个仅当前 Agent 使用的新任务后重新授权。',
34
+ sync_pending: '扩展尚未确认该页。请读取 getWorkspace 后重试 reattachPage。',
35
+ single_tab_scope: '此授权覆盖用户所选的一页及其站点。其他页需要单独授权。',
36
+ page_not_found: '用 getRecoverySummary 核对原页状态,需要时请用户重新选择标签。',
37
+ workspace_not_found: '核对 profileId。服务重启后用 getRecoverySummary 查历史,并请用户重新授权原页。',
38
+ finish_preview_changed: '等待当前操作完成,重新调用 previewFinish 核对页面清单。',
39
+ input_guard_unavailable: '请检查 Dev Chromium 是否包含受管页面输入保护补丁。',
40
+ workspace_under_user_control: '用原页面句柄调用 reattachPage 并传 waitMs 等待交回和新观察。',
27
41
  outcome_unknown: '先用 getOperation 或 diagnoseOperation,并核对站点结果后再重试。',
28
42
  inspect_before_retry: '先核对站点是否已生效,再决定是否提交新的 operationId。',
29
43
  run_timeout: '运行预算已耗尽。用同一 operationId 查询回执,并核对站点结果后再决定是否继续。',
@@ -40,18 +54,20 @@ export class OpenBrowserError extends Error {
40
54
  }
41
55
 
42
56
  const unavailable = () => new OpenBrowserError('SERVICE_UNAVAILABLE', '请先启动 open-browser 本地服务。');
57
+ const responseLost = () => new OpenBrowserError('RESPONSE_LOST', '本机服务的回包中断,请先核对请求结果。');
43
58
 
44
59
  export class OpenBrowserClient {
45
60
  constructor(options = {}) {
46
61
  const selected = pathsForProfile(options.profileId ?? profileId);
47
62
  this.socketPath = options.socketPath ?? selected.socketPath;
48
63
  this.tokenPath = options.tokenPath ?? process.env.OPEN_BROWSER_CLIENT_TOKEN_FILE ?? selected.tokenPath;
64
+ this.agent = options.agent ?? new Agent({ keepAlive: true, maxSockets: 4 });
49
65
  const codex = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID;
50
66
  this.agentName = options.agentName ?? (process.env.OPEN_BROWSER_AGENT_NAME?.trim() ||
51
67
  (codex ? 'Codex' : options.fallbackName ?? 'SDK'));
52
68
  }
53
69
 
54
- async call(method, params = {}) {
70
+ async call(method, params = {}, {signal} = {}) {
55
71
  if (!agentMethods.includes(method))
56
72
  throw new OpenBrowserError('UNKNOWN_METHOD', '未知的 Agent API 方法。');
57
73
  if (!params || typeof params !== 'object' || Array.isArray(params))
@@ -61,10 +77,10 @@ export class OpenBrowserClient {
61
77
  throw new OpenBrowserError('TASK_NAME_REQUIRED', '创建 Agent 任务时必须提供非空任务名称 name。');
62
78
  if (['createWorkspace','open'].includes(method) && params.agentName === undefined)
63
79
  params = { ...params, agentName: this.agentName };
64
- return localRequest(this.socketPath,this.tokenPath,'/v1/call',method,params);
80
+ return localRequest(this.socketPath,this.tokenPath,'/v1/call',method,params,this.agent,signal);
65
81
  }
66
- async capabilities() {
67
- try { return await this.call('capabilities'); }
82
+ async capabilities(options) {
83
+ try { return await this.call('capabilities', {}, options); }
68
84
  catch(error) {
69
85
  if (['UNKNOWN_METHOD','unknown_method','forbidden'].includes(error.code)) return {version:0,visual:{enabled:false,actions:[]}};
70
86
  throw error;
@@ -82,8 +98,8 @@ export class OpenBrowserClient {
82
98
  listEvents(workspaceId, options = {}) { return this.call('listEvents', { ...options, workspaceId }); }
83
99
  getRecoverySummary(workspaceId, options = {}) { return this.call('getRecoverySummary', { ...options, workspaceId }); }
84
100
  listOperations(workspaceId, options = {}) { return this.call('listOperations', { ...options, workspaceId }); }
85
- finishWorkspace(workspaceId, keepPageIds, operationId) {
86
- return this.call('finishWorkspace', {workspaceId, keepPageIds, operationId});
101
+ finishWorkspace(workspaceId, keepPageIds, operationId, previewId) {
102
+ return this.call('finishWorkspace', {workspaceId, keepPageIds, operationId, previewId});
87
103
  }
88
104
 
89
105
  /** Finish a workspace with a fresh idempotency key generated by the SDK. */
@@ -97,7 +113,19 @@ export class OpenBrowserClient {
97
113
  listWorkspaces() { return this.call('listWorkspaces'); }
98
114
  getWorkspace(workspaceId) { return this.call('getWorkspace', { workspaceId }); }
99
115
  openPage(workspaceId, url) { return this.call('openPage', { workspaceId, url }); }
116
+ canvasSnapshot(page) { return this.call('canvasSnapshot', page); }
117
+ adoptCurrentTab(workspaceId, adoptionToken) { return this.call('adoptCurrentTab', {workspaceId, adoptionToken}); }
118
+ reattachPage(page, options = {}) { return this.call('reattachPage', {...options, ...page}); }
119
+ previewFinish(workspaceId, keepPageIds = []) { return this.call('previewFinish', {workspaceId, keepPageIds}); }
100
120
  observe(page) { return this.call('observe', page); }
121
+ observeAndAct(page, request = {}) {
122
+ const { actions, observeAfter, timeoutMs, operationId = randomUUID(), ...observeOptions } = request;
123
+ if (!Array.isArray(actions) || actions.length === 0)
124
+ return Promise.reject(new OpenBrowserError('INVALID_PARAMS', 'observeAndAct 需要至少一个 action。'));
125
+ return this.call('observeAndAct', {
126
+ ...page, ...observeOptions, actions, observeAfter, timeoutMs, operationId,
127
+ });
128
+ }
101
129
  /** Open one URL and immediately return its first observation. */
102
130
  async openAndObserve(options = {}, observeOptions = {}) {
103
131
  const page = await this.open(options);
@@ -106,36 +134,29 @@ export class OpenBrowserClient {
106
134
  }
107
135
  /** Observe immediately before acting, while preserving document and control checks. */
108
136
  async actAfterObserve(page, request = {}) {
109
- const { actions, observeAfter, timeoutMs, operationId = randomUUID() } = request;
110
- if (!Array.isArray(actions) || actions.length === 0)
111
- throw new OpenBrowserError('INVALID_PARAMS', 'actAfterObserve 需要至少一个 action。');
112
- const observation = await this.observe(page);
113
- const receipt = await this.act({
114
- ...page,
115
- documentId: observation.documentId,
116
- controlGeneration: observation.controlGeneration,
117
- }, { actions, observeAfter, timeoutMs, operationId });
118
- return { observation, receipt };
137
+ return this.observeAndAct(page, request).then(({ observation, receipt }) => ({ observation, receipt }));
119
138
  }
120
139
  runWorkflow(page, request) { return this.call('runWorkflow',{...request,...page}); }
121
140
  act(page, operation) { return this.call('act', { ...operation, ...page }); }
122
141
  diagnoseOperation(workspaceId, operationId) { return this.call('diagnoseOperation', {workspaceId, operationId}); }
123
- getOperation(workspaceId, operationId) {
124
- return this.call('getOperation', { workspaceId, operationId });
142
+ getOperation(workspaceId, operationId, {waitMs} = {}) {
143
+ return this.call('getOperation', { workspaceId, operationId, ...(waitMs !== undefined && {waitMs}) });
125
144
  }
126
145
  cancelOperation(workspaceId, operationId) {
127
146
  return this.call('cancelOperation', { workspaceId, operationId });
128
147
  }
129
148
  handOff(workspaceId) { return this.call('handOff', { workspaceId }); }
130
149
  closeWorkspace(workspaceId) { return this.call('closeWorkspace', { workspaceId }); }
150
+ close() { this.agent.destroy(); }
131
151
  }
132
152
 
133
- export async function localRequest(socket, credentials, endpoint, method, params) {
153
+ export async function localRequest(socket, credentials, endpoint, method, params, agent, signal) {
134
154
  const body = JSON.stringify({ method, params });
135
155
  let token;
136
156
  try {
137
- token = (await readFile(credentials, 'utf8')).trim();
157
+ token = (await readFile(credentials, {encoding:'utf8', signal})).trim();
138
158
  } catch {
159
+ signal?.throwIfAborted();
139
160
  throw unavailable();
140
161
  }
141
162
  if (!token) throw unavailable();
@@ -149,11 +170,12 @@ export async function localRequest(socket, credentials, endpoint, method, params
149
170
  'content-type': 'application/json',
150
171
  'content-length': Buffer.byteLength(body),
151
172
  },
173
+ agent, signal,
152
174
  }, res => {
153
175
  let data = '';
154
176
  res.setEncoding('utf8');
155
177
  res.on('data', chunk => { data += chunk; });
156
- res.on('error', () => reject(unavailable()));
178
+ res.once('error', () => reject(signal?.aborted ? signal.reason : responseLost()));
157
179
  res.on('end', () => {
158
180
  let reply;
159
181
  try { reply = JSON.parse(data); } catch {}
@@ -166,7 +188,12 @@ export async function localRequest(socket, credentials, endpoint, method, params
166
188
  }
167
189
  });
168
190
  });
169
- req.once('error', () => reject(unavailable()));
191
+ // A failed connect cannot have delivered the request. A reset on an
192
+ // established (including reused) socket can follow a committed write.
193
+ req.once('error', error => {
194
+ if (signal?.aborted) reject(signal.reason);
195
+ else reject(error.syscall === 'connect' ? unavailable() : responseLost());
196
+ });
170
197
  req.setTimeout(limits.clientTimeoutMs, () => {
171
198
  reject(new OpenBrowserError('REQUEST_TIMEOUT', '等待服务响应超时。对于已派发的动作,请按 operationId 查询回执。'));
172
199
  req.destroy();
package/service.mjs CHANGED
@@ -1,16 +1,20 @@
1
1
  import { limits } from './api-contract.mjs';
2
2
  import path from 'node:path';
3
+ import { TabRecovery, restoreApprovedTabs } from './tab-recovery.mjs';
3
4
  import { AccessRegistry } from './access-registry.mjs';
4
5
  import http from 'node:http';
5
6
  import net from 'node:net';
6
7
  import { createInterface } from 'node:readline';
8
+ import { setTimeout as delay } from 'node:timers/promises';
7
9
  import { randomBytes, timingSafeEqual } from 'node:crypto';
8
10
  import { chmod, lstat, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
9
11
  import { pathToFileURL } from 'node:url';
10
12
  import { launchBrowser } from './control.mjs';
11
13
  import { agentMethods } from './sdk.mjs';
12
14
  import { BrowserService } from './engine-service.mjs';
13
- import { socketPath, stateDir, tokenPath, adminTokenPath } from './paths.mjs';
15
+ import { desktopWorkspaces, workspaceSyncView } from './workspace-state.mjs';
16
+ import { autoInstallSkillLinks } from './skill-links.mjs';
17
+ import { socketPath, stateDir, tokenPath, adminTokenPath, pidPath } from './paths.mjs';
14
18
 
15
19
  function listen(server) {
16
20
  return new Promise((resolve, reject) => {
@@ -71,6 +75,7 @@ function errorCode(error) {
71
75
  export async function startApplication({ headless = false, mode = 'service', onShow, onBar,
72
76
  launchServiceBrowser = launchBrowser, readOnlyObserver, chromiumNetLog } = {}) {
73
77
  if (!['web', 'native', 'service', 'chromium'].includes(mode)) throw new Error('invalid_mode');
78
+ await autoInstallSkillLinks();
74
79
  await mkdir(stateDir, { mode: 0o700, recursive: true });
75
80
  if (process.platform !== 'win32') await chmod(stateDir, 0o700);
76
81
  const token = randomBytes(32).toString('hex');
@@ -81,6 +86,7 @@ export async function startApplication({ headless = false, mode = 'service', onS
81
86
  let ready = false;
82
87
  let closing;
83
88
  let showing;
89
+ let pidWritten = false;
84
90
 
85
91
  async function openControlWindow() {
86
92
  if (shell) return shell.show();
@@ -143,11 +149,16 @@ export async function startApplication({ headless = false, mode = 'service', onS
143
149
  if ((await readFile(tokenPath, 'utf8').catch(() => '')).trim() === token)
144
150
  await unlink(tokenPath).catch(() => {});
145
151
  if ((await readFile(adminTokenPath, 'utf8').catch(() => '')).trim() === adminToken) await unlink(adminTokenPath).catch(() => {});
152
+ if (pidWritten && (await readFile(pidPath, 'utf8').catch(() => '')).trim() === String(process.pid))
153
+ await unlink(pidPath).catch(() => {});
146
154
  const serverClosed = new Promise(resolve => server.close(resolve));
147
155
  server.closeAllConnections();
148
156
  try {
149
157
  if (studio) await studio.close();
150
- if (engine) await engine.shutdown();
158
+ if (engine) {
159
+ if (engine.tabRecovery) engine.tabRecovery.closed = true;
160
+ await engine.shutdown();
161
+ }
151
162
  } finally {
152
163
  await sharedContext?.close().catch(() => {});
153
164
  await browser?.close().catch(() => {});
@@ -163,26 +174,36 @@ export async function startApplication({ headless = false, mode = 'service', onS
163
174
  if (mode === 'chromium') {
164
175
  const { launchChromiumShell } = await import('./chromium-shell.mjs');
165
176
  const { chromiumHost } = await import('./chromium-host.mjs');
166
- sharedContext = await launchChromiumShell({ headless, netLogPath:chromiumNetLog });
177
+ const restoreSession = !!registry.db.prepare('SELECT 1 FROM resumable_tabs WHERE expires>? LIMIT 1').get(Date.now());
178
+ const launch = async () => {
179
+ // After SIGKILL the old browser can still be closing its profile.
180
+ const deadline = Date.now() + 5000;
181
+ for (;;) {
182
+ try { return await launchChromiumShell({headless,netLogPath:chromiumNetLog,restoreSession}); }
183
+ catch (error) {
184
+ if (Date.now() >= deadline || !/ProcessSingleton|SingletonLock|user data directory is already in use/i.test(error.message)) throw error;
185
+ await delay(200);
186
+ }
187
+ }
188
+ };
189
+ sharedContext = await launch();
167
190
  try { shell = await chromiumHost(sharedContext); }
168
191
  catch (error) {
169
192
  if (error.code !== 'extension_reload') throw error;
170
193
  await sharedContext.close();
171
- sharedContext = await launchChromiumShell({ headless, netLogPath:chromiumNetLog });
194
+ sharedContext = await launch();
172
195
  shell = await chromiumHost(sharedContext);
173
196
  }
174
197
  browser = sharedContext.browser();
175
198
  } else {
176
199
  browser = await launchServiceBrowser({ headless: mode === 'native' || headless });
177
200
  }
178
- engine = new BrowserService(browser, { concurrency: 4, sharedContext, readOnlyObserver, journalPath: path.join(stateDir, 'open-browser-receipts.sqlite'), releaseTab: shell?.releaseTab, groupTab: shell?.groupTab, onActivity: shell?.onActivity,
201
+ engine = new BrowserService(browser, { concurrency: 4, sharedContext, tabRecovery:sharedContext && new TabRecovery(registry), readOnlyObserver, journalPath: path.join(stateDir, 'open-browser-receipts.sqlite'), releaseTab: shell?.releaseTab, setInputGuard: shell?.setInputGuard, withAgentInput: shell?.withAgentInput, inputGuardMode: shell?.inputGuardMode, groupTab: shell?.groupTab, onActivity: shell?.onActivity,
179
202
  onActionTarget: shell?.onActionTarget });
203
+ if (sharedContext) await restoreApprovedTabs(engine, registry);
180
204
  const call = async (method, params = {}) => {
181
205
  if (method === 'createWorkspace') return registry.call(engine, 'local', method, params);
182
- if (method === 'listWorkspaces') {
183
- const owners = new Set([...engine.workspaces.values()].map(ws => ws.owner));
184
- return (await Promise.all([...owners].map(owner => engine.call(method, params, owner)))).flat();
185
- }
206
+ if (method === 'listWorkspaces') return desktopWorkspaces(engine.workspaces);
186
207
  return engine.call(method === 'finishWorkspace' ? 'hostFinishWorkspace' : method, params, registry.owner(params.workspaceId) || 'local', 'desktop');
187
208
  };
188
209
  if (mode === 'web') {
@@ -199,6 +220,16 @@ export async function startApplication({ headless = false, mode = 'service', onS
199
220
  if (!ready) throw Object.assign(new Error('not_ready'), { code: 'not_ready' });
200
221
  switch (method) {
201
222
  case 'listWorkspaces': return call(method, params);
223
+ case 'offerCurrentTab': {
224
+ if (registry.hasDelegates(params.workspaceId)) throw Object.assign(new Error(), {code:'adoption_requires_private_workspace'});
225
+ const offer = await call(method, params);
226
+ if (params.bindOnApproval !== true) return offer;
227
+ const owner = registry.owner(offer.workspaceId);
228
+ if (!owner) throw Object.assign(new Error(), {code:'workspace_not_found'});
229
+ return registry.call(engine, owner, 'adoptCurrentTab', {
230
+ workspaceId:offer.workspaceId, adoptionToken:offer.adoptionToken
231
+ });
232
+ }
202
233
  case 'listAgentHistory': return registry.listHistory(engine, 'local', params);
203
234
  case 'getWorkspace': return call(method, params);
204
235
  default: return call(method, params);
@@ -209,8 +240,12 @@ export async function startApplication({ headless = false, mode = 'service', onS
209
240
  await writeFile(temporary, value + '\n', { mode: 0o600, flag: 'wx' });
210
241
  await rename(temporary, file);
211
242
  }
243
+ const temporaryPid = pidPath + '.' + process.pid;
244
+ await writeFile(temporaryPid, String(process.pid) + '\n', { mode: 0o600, flag: 'wx' });
245
+ await rename(temporaryPid, pidPath);
246
+ pidWritten = true;
212
247
  ready = true;
213
- shell?.start(hostCall, onBar);
248
+ shell?.start(hostCall, onBar, () => desktopWorkspaces(engine.workspaces, workspaceSyncView));
214
249
  browser.once('disconnected', () => { void close(); });
215
250
  return { close, closed, openControlWindow, studio, page, hostCall, sharedContext,
216
251
  clickBar: frame => shell?.clickBar(frame, hostCall) };
@@ -0,0 +1,144 @@
1
+ import { lstat, mkdir, readFile, realpath, rename, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';
2
+ import { randomUUID } from 'node:crypto';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath, pathToFileURL } from 'node:url';
6
+ import { stateDir } from './paths.mjs';
7
+
8
+ const sourceRoot = path.dirname(fileURLToPath(import.meta.url));
9
+ const defaultSkillSource = path.join(sourceRoot, 'skills', 'open-browser');
10
+
11
+ const agentRoots = [
12
+ ['codex', '.codex'],
13
+ ['claude-code', '.claude'],
14
+ ['cursor', '.cursor'],
15
+ ['windsurf', path.join('.codeium', 'windsurf')],
16
+ ['windsurf-legacy', '.windsurf'],
17
+ ['gemini-cli', '.gemini'],
18
+ ['cline', '.cline'],
19
+ ['roo-code', '.roo'],
20
+ ['opencode', path.join('.config', 'opencode')],
21
+ ].map(([name, relative]) => ({
22
+ name,
23
+ detect: path.join(os.homedir(), relative),
24
+ root: path.join(os.homedir(), relative, 'skills'),
25
+ }));
26
+
27
+ function configuredRoots() {
28
+ const extra = (process.env.OPEN_BROWSER_AGENT_SKILL_DIRS || '')
29
+ .split(path.delimiter)
30
+ .map(value => value.trim())
31
+ .filter(Boolean)
32
+ .map(value => path.resolve(value));
33
+ return [...agentRoots, ...extra.map(root => ({ name: 'configured', root, configured: true }))];
34
+ }
35
+
36
+ async function isDirectory(pathname) {
37
+ try {
38
+ return (await stat(pathname)).isDirectory();
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ async function createDirectoryLink(source, relativeSource, link) {
45
+ try {
46
+ await symlink(relativeSource, link, 'dir');
47
+ } catch (error) {
48
+ if (process.platform !== 'win32' || error.code !== 'EPERM') throw error;
49
+ await symlink(source, link, 'junction');
50
+ }
51
+ }
52
+
53
+ async function linkSkill(root, source) {
54
+ const link = path.join(root, 'open-browser');
55
+ await mkdir(root, { recursive: true });
56
+ const relativeSource = path.relative(await realpath(root), source) || '.';
57
+ try {
58
+ await createDirectoryLink(source, relativeSource, link);
59
+ return { status: 'linked', path: link };
60
+ } catch (error) {
61
+ if (error.code !== 'EEXIST') throw error;
62
+ }
63
+ if (!(await lstat(link)).isSymbolicLink()) return { status: 'skipped_conflict', path: link };
64
+ const current = await realpath(link).catch(error => {
65
+ if (error.code !== 'ENOENT') throw error;
66
+ });
67
+ if (current === source) return { status: 'existing', path: link };
68
+ if (current) {
69
+ const manifest = await readFile(path.resolve(current, '../../package.json'), 'utf8').then(JSON.parse).catch(() => null);
70
+ if (path.basename(current) !== 'open-browser' || path.basename(path.dirname(current)) !== 'skills' ||
71
+ manifest?.name !== '@seekskyworld/open-browser') return { status: 'skipped_conflict', path: link };
72
+ }
73
+ const temporary = link + '.' + randomUUID();
74
+ await createDirectoryLink(source, relativeSource, temporary);
75
+ try {
76
+ // Windows cannot replace a directory symlink with a rename. Prepare the
77
+ // replacement first and accept a concurrent scan that installed it.
78
+ if (process.platform === 'win32') await unlink(link).catch(error => { if (error.code !== 'ENOENT') throw error; });
79
+ try { await rename(temporary, link); }
80
+ catch (error) {
81
+ if (await realpath(link).catch(() => null) !== source) throw error;
82
+ }
83
+ } finally {
84
+ await rm(temporary, { force: true });
85
+ }
86
+ return { status: 'linked', path: link };
87
+ }
88
+
89
+ export async function installAgentSkillLinks({ source = defaultSkillSource } = {}) {
90
+ if (process.env.NODE_TEST_CONTEXT || process.env.OPEN_BROWSER_AUTO_INSTALL_SKILLS === '0') return { disabled: true, links: [] };
91
+ if (!(await isDirectory(source))) return { disabled: false, links: [], sourceMissing: true };
92
+ source = await realpath(source);
93
+ const links = [];
94
+ const seen = new Set();
95
+ for (const agent of configuredRoots()) {
96
+ if (!agent.configured && !(await isDirectory(agent.detect))) continue;
97
+ const root = path.resolve(agent.root);
98
+ if (seen.has(root)) continue;
99
+ seen.add(root);
100
+ const result = await linkSkill(root, source).catch(error => ({
101
+ status: 'skipped_error', path: path.join(root, 'open-browser'), code: error.code || 'unknown',
102
+ }));
103
+ links.push({ agent: agent.name, ...result });
104
+ }
105
+ return { disabled: false, links, source: path.resolve(source) };
106
+ }
107
+
108
+ // Desktop starts always discover new agents. Short-lived Skill commands
109
+ // share a recent successful scan across processes using this profile.
110
+ export async function autoInstallSkillLinks({ useCache = false } = {}) {
111
+ if (process.env.NODE_TEST_CONTEXT || process.env.OPEN_BROWSER_AUTO_INSTALL_SKILLS === '0') return;
112
+ const verbose = process.env.OPEN_BROWSER_SKILLS_VERBOSE === '1';
113
+ try {
114
+ const marker = path.join(stateDir, 'skill-links.json');
115
+ const key = JSON.stringify([defaultSkillSource, ...configuredRoots().map(agent => agent.root)]);
116
+ if (useCache) {
117
+ const saved = await readFile(marker, 'utf8').then(JSON.parse).catch(() => null);
118
+ const age = Date.now() - saved?.checkedAt;
119
+ if (saved?.key === key && age >= 0 && age < 10 * 60_000) return;
120
+ }
121
+ const result = await installAgentSkillLinks();
122
+ if (verbose) console.error(JSON.stringify({ skillLinks: result }));
123
+ if (result.sourceMissing || result.links.some(link => link.status === 'skipped_error')) return;
124
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
125
+ const temporary = marker + '.' + randomUUID();
126
+ try {
127
+ await writeFile(temporary, JSON.stringify({ key, checkedAt: Date.now() }), { mode: 0o600, flag: 'wx' });
128
+ await rename(temporary, marker);
129
+ } finally {
130
+ await rm(temporary, { force: true });
131
+ }
132
+ } catch (error) {
133
+ if (verbose) console.error(JSON.stringify({ skillLinksError: error.message }));
134
+ }
135
+ }
136
+
137
+ if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
138
+ installAgentSkillLinks().then(result => {
139
+ process.stdout.write(JSON.stringify(result) + '\n');
140
+ }).catch(error => {
141
+ process.stderr.write(JSON.stringify({ error: error.message }) + '\n');
142
+ process.exitCode = 1;
143
+ });
144
+ }