@seekskyworld/open-browser 0.2.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 (53) hide show
  1. package/Docs/open-browser-api.d.ts +13 -9
  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 +6 -6
  3. package/README.md +4 -4
  4. package/README.zh-CN.md +4 -4
  5. package/access-registry.mjs +8 -3
  6. package/action-execution.mjs +30 -5
  7. package/api-contract.mjs +6 -6
  8. package/browser-extension/manifest.json +1 -1
  9. package/browser-extension/newtab.js +1 -0
  10. package/browser-extension/phase-labels.js +1 -1
  11. package/browser-extension/popup.html +3 -1
  12. package/browser-extension/popup.js +33 -13
  13. package/browser-extension/tab-action.js +3 -2
  14. package/browser-extension/worker.js +3 -3
  15. package/capability-matrix.mjs +1 -1
  16. package/chromium-host.mjs +6 -10
  17. package/chromium-shell.mjs +2 -2
  18. package/cli.mjs +22 -22
  19. package/contract-validation.mjs +1 -1
  20. package/desktop/Info.plist +2 -2
  21. package/desktop/WorkspacePanel.m +3 -2
  22. package/desktop/build-macos.mjs +6 -3
  23. package/desktop/notarize-macos.mjs +54 -10
  24. package/desktop/sign.mjs +17 -2
  25. package/desktop/verify-macos-release.mjs +21 -13
  26. package/desktop/verify-version.mjs +22 -2
  27. package/engine-service.mjs +85 -26
  28. package/managed-input.mjs +22 -5
  29. package/mcp-http.mjs +9 -9
  30. package/mcp-server.mjs +23 -7
  31. package/mcp.mjs +1 -0
  32. package/package.json +6 -5
  33. package/page-activity.mjs +2 -1
  34. package/page-observation.mjs +4 -1
  35. package/receipt-store.mjs +17 -7
  36. package/runtime.mjs +2 -2
  37. package/sdk.mjs +24 -14
  38. package/service.mjs +36 -20
  39. package/skill-links.mjs +72 -18
  40. package/skills/open-browser/SKILL.md +8 -97
  41. package/skills/open-browser/references/macos.md +3 -0
  42. package/skills/open-browser/{SKILL.windows.md → references/operations.md} +7 -60
  43. package/skills/open-browser/references/recovery.md +36 -0
  44. package/skills/open-browser/references/windows.md +3 -0
  45. package/skills/open-browser/scripts/bootstrap.mjs +77 -89
  46. package/skills/open-browser/scripts/guide.mjs +17 -0
  47. package/studio/studio.js +2 -2
  48. package/tab-adoption.mjs +9 -3
  49. package/tab-recovery.mjs +100 -0
  50. package/visual-page.mjs +17 -7
  51. package/workspace-lifecycle.mjs +18 -2
  52. package/workspace-state.mjs +57 -16
  53. package/skills/open-browser/SKILL.macos.md +0 -112
@@ -0,0 +1,36 @@
1
+ # 恢复页面与读取错误
2
+
3
+ | 返回 | 下一步 |
4
+ | --- | --- |
5
+ | `mode:agent` 且 `pages:[]` | 查看 `pageAvailability`。首次绑定时等待 `page_bound`,已关闭的页需要重新选择。 |
6
+ | `sync_pending` | 用原工作区和页面调用 `reattachPage` 重试同步。 |
7
+ | `workspace_not_found` | 核对 profile 和调用方,用原工作区 ID 调用 `getRecoverySummary`。读取 `closeReason`、页面处置和动作回执。历史记录没有可用绑定时,按 `nextAction:request_tab_selection` 请用户重新选页。旧记录可能返回 `unknown`。 |
8
+ | `service_shutdown` | 用户交付标签时可勾选重启恢复。服务在授权时记录浏览器生成的页面身份。正常退出或服务进程被强制终止后,原资料中的有效记录可在 24 小时内重新绑定 Chromium 恢复的同一标签。用原工作区和页面调用 `reattachPage` 取得新观察。人工接管、原标签未恢复、页面身份变化或提交仍待核实时,请按恢复摘要重新选页。 |
9
+ | `page_not_found`、`origin_denied` | 核对用户实际选中的标签和站点。恢复时按用户选择绑定,同一地址可能有多个标签。 |
10
+ | `stale_document`、`stale_control`、`stale_ref` | 对原页重新观察,核对控件再提交。 |
11
+ | `outcome_unknown`、请求超时 | 保留原 operationId,查询动作回执,核对站点结果后再决定是否重试。 |
12
+ | `RESPONSE_LOST` | 请求已发出,服务可能已执行。创建任务后用 `listWorkspaces` 核对名称和页面。有 operationId 时用 `getOperation` 核对回执。 |
13
+ | `target_obscured` | 查看回执的 obstruction 和观察中的前景弹窗,核对后再处理遮挡。 |
14
+ | `human_verification_required` | 用 `handOff` 请用户处理站点验证,用 `reattachPage` 等待交回。 |
15
+
16
+ 宿主进程关闭会结束当前 Chromium 上下文。恢复标签会得到新文档,旧控件引用和一次性视觉帧随之失效。备用授权流程由用户点击「生成备用授权码」,然后调用 `adoptCurrentTab` 兑换,一次有效,期限两分钟。
17
+
18
+ ## CLI 错误
19
+
20
+ 连续调用使用 `session`,每行 stdout 按请求 id 返回 `{id,result}` 或 `{id,error}`。单次脚本调用可用 `--json <方法>`,统一从 stdout 读取 `{result}` 或 `{error}` 并检查退出码。兼容旧版时,单次 CLI 成功时在 stdout 返回结果,失败时以非零状态退出,并在 stderr 返回错误。下面的 Python 函数接收 Skill 启动器的绝对路径,保留错误码和原始启动错误。
21
+
22
+ ```python
23
+ import json
24
+ import subprocess
25
+
26
+ def call(launcher, method, params):
27
+ proc = subprocess.run([launcher, method], input=json.dumps(params),
28
+ text=True, capture_output=True)
29
+ if proc.returncode == 0:
30
+ return json.loads(proc.stdout)
31
+ try:
32
+ detail = json.loads(proc.stderr)["error"]
33
+ except (ValueError, KeyError, TypeError):
34
+ detail = {"code": "CLI_EXIT", "message": proc.stderr.strip()}
35
+ raise RuntimeError(proc.returncode, detail)
36
+ ```
@@ -0,0 +1,3 @@
1
+ ### Windows
2
+
3
+ 在 Windows 便携版中,Skill 会使用 `scripts/open-browser.cmd` 和包内 Node。需要打开浏览器窗口时运行便携包中的 `open-browser.cmd`。
@@ -1,17 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { access, readFile } from 'node:fs/promises';
2
+ import { readFile, realpath, stat } from 'node:fs/promises';
3
3
  import { spawn } from 'node:child_process';
4
+ import { once } from 'node:events';
4
5
  import net from 'node:net';
6
+ import { setTimeout as delay } from 'node:timers/promises';
5
7
  import path from 'node:path';
6
- import { pathToFileURL } from 'node:url';
8
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
9
 
8
10
  const defaultWaitMs = 10_000;
9
11
  const retryDelayMs = 150;
10
12
 
11
- function sleep(ms) {
12
- return new Promise(resolve => setTimeout(resolve, ms));
13
- }
14
-
15
13
  function parseErrorCode(stderr) {
16
14
  try {
17
15
  const response = JSON.parse(stderr.trim());
@@ -21,17 +19,13 @@ function parseErrorCode(stderr) {
21
19
  }
22
20
  }
23
21
 
24
- async function executable(file) {
25
- try {
26
- await access(file);
27
- return true;
28
- } catch {
29
- return false;
30
- }
22
+ async function isFile(file) {
23
+ return stat(file).then(entry => entry.isFile(), () => false);
31
24
  }
32
25
 
33
- function detached(command, args, options = {}) {
26
+ async function detached(command, args, options = {}) {
34
27
  const child = spawn(command, args, { ...options, detached: true, stdio: 'ignore' });
28
+ await once(child, 'spawn');
35
29
  child.unref();
36
30
  }
37
31
 
@@ -43,6 +37,7 @@ async function wakeExisting(root) {
43
37
  process.kill(pid, 0);
44
38
  const active = await new Promise(resolve => {
45
39
  const probe = net.connect(socketPath);
40
+ probe.setTimeout(1000, () => { probe.destroy(); resolve(false); });
46
41
  probe.once('connect', () => { probe.destroy(); resolve(true); });
47
42
  probe.once('error', () => resolve(false));
48
43
  });
@@ -58,35 +53,35 @@ async function startLocalBrowser(root) {
58
53
  ? path.resolve(root, '../../../')
59
54
  : undefined;
60
55
  if (appBundle?.endsWith('.app')) {
61
- detached('open', ['-g', appBundle]);
62
- return;
56
+ return detached('open', ['-g', appBundle]);
63
57
  }
64
58
 
65
59
  const portableRoot = path.resolve(root, '..');
66
60
  const portableLauncher = process.platform === 'win32'
67
61
  ? path.join(portableRoot, 'open-browser.cmd')
68
62
  : path.join(portableRoot, 'open-browser');
69
- if (await executable(portableLauncher)) {
63
+ if (await isFile(portableLauncher)) {
70
64
  if (process.platform === 'win32') {
71
- detached(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${portableLauncher}"`], { cwd: portableRoot });
72
- } else {
73
- detached(portableLauncher, [], { cwd: portableRoot });
65
+ return detached(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${portableLauncher}"`], { cwd: portableRoot });
74
66
  }
75
- return;
67
+ return detached(portableLauncher, [], { cwd: portableRoot });
76
68
  }
77
69
 
78
- const service = path.join(root, 'service.mjs');
79
- if (await access(service).then(() => true, () => false)) {
80
- detached(process.execPath, [service, '--chromium'], { cwd: root });
81
- return;
70
+ if (process.platform === 'darwin' && process.env.OPEN_BROWSER_USE_SOURCE !== '1' &&
71
+ process.env.OPEN_BROWSER_BUILD_PROFILE !== 'dev') {
72
+ for (const app of [path.join(root, 'dist/open-browser.app'), '/Applications/open-browser.app']) {
73
+ if (await isFile(path.join(app, 'Contents/MacOS/open-browser'))) return detached('open', ['-g', app]);
74
+ }
82
75
  }
76
+ const service = path.join(root, 'service.mjs');
77
+ if (await isFile(service)) return detached(process.execPath, [service, '--chromium'], { cwd: root });
83
78
 
84
79
  throw new Error('OPEN_BROWSER_APP_NOT_FOUND');
85
80
  }
86
81
 
87
82
  function waitLimit() {
88
83
  const value = Number(process.env.OPEN_BROWSER_AUTOSTART_TIMEOUT_MS ?? defaultWaitMs);
89
- return Number.isFinite(value) ? Math.max(1_000, Math.min(30_000, value)) : defaultWaitMs;
84
+ return Number.isFinite(value) ? Math.max(1_000, Math.min(30_000, Math.trunc(value))) : defaultWaitMs;
90
85
  }
91
86
 
92
87
  async function run(node, root, args, input) {
@@ -110,89 +105,82 @@ async function run(node, root, args, input) {
110
105
  });
111
106
  }
112
107
 
113
- async function waitForService(node, root) {
114
- const deadline = Date.now() + waitLimit();
115
- while (Date.now() < deadline) {
116
- const probe = await run(node, root, ['capabilities'], '{}\n');
117
- const code = parseErrorCode(probe.stderr);
118
- if (probe.code === 0) return true;
119
- if (!['SERVICE_UNAVAILABLE', 'not_ready'].includes(code)) return false;
120
- await sleep(retryDelayMs);
108
+ // Only readiness is polled. One SDK client and one deadline cover every probe.
109
+ async function ensureService(root, start = startLocalBrowser, initialError) {
110
+ const { OpenBrowserClient, OpenBrowserError } = await import(pathToFileURL(path.join(root, 'sdk.mjs')).href);
111
+ const api = new OpenBrowserClient();
112
+ const signal = AbortSignal.timeout(waitLimit());
113
+ let error = initialError;
114
+ let launched = false;
115
+ try {
116
+ for (;;) {
117
+ if (error) {
118
+ if (process.env.OPEN_BROWSER_AUTOSTART === '0' ||
119
+ !['SERVICE_UNAVAILABLE', 'not_ready', 'RESPONSE_LOST'].includes(error.code)) throw error;
120
+ if (error.code === 'SERVICE_UNAVAILABLE' && !launched) {
121
+ await start(root);
122
+ launched = true;
123
+ } else {
124
+ await delay(retryDelayMs, undefined, { signal });
125
+ }
126
+ }
127
+ try {
128
+ await api.capabilities({ signal });
129
+ return;
130
+ } catch (cause) {
131
+ signal.throwIfAborted();
132
+ error = cause;
133
+ }
134
+ }
135
+ } catch (cause) {
136
+ if (signal.aborted) throw new OpenBrowserError('REQUEST_TIMEOUT', '等待本机服务就绪超时。');
137
+ throw cause;
138
+ } finally {
139
+ api.close();
121
140
  }
122
- return false;
123
141
  }
124
142
 
125
143
  async function runSession(node, root, args) {
126
- let probe = await run(node, root, ['capabilities'], '{}\n');
127
- const errorCode = parseErrorCode(probe.stderr);
128
- if (probe.code !== 0 && ['SERVICE_UNAVAILABLE', 'not_ready'].includes(errorCode) && process.env.OPEN_BROWSER_AUTOSTART !== '0') {
129
- if (errorCode === 'SERVICE_UNAVAILABLE') {
130
- try { await startLocalBrowser(root); } catch { /* return the original service error below */ }
131
- }
132
- if (await waitForService(node, root)) probe = { code: 0 };
133
- }
134
- if (probe.code !== 0) {
135
- if (probe.stdout) process.stdout.write(probe.stdout);
136
- if (probe.stderr) process.stderr.write(probe.stderr);
137
- return probe.code;
138
- }
144
+ await ensureService(root);
139
145
  const child = spawn(node, [path.join(root, 'cli.mjs'), ...args], {
140
146
  cwd: root,
141
147
  env: process.env,
142
148
  stdio: 'inherit',
143
149
  });
144
- return new Promise(resolve => child.once('close', code => resolve(code ?? 1)));
145
- }
146
-
147
- async function installSkillLinks(root) {
148
- if (process.env.OPEN_BROWSER_AUTO_INSTALL_SKILLS === '0') return;
149
- const installer = path.join(root, 'skill-links.mjs');
150
- if (!await executable(installer)) return;
151
- try {
152
- const { installAgentSkillLinks } = await import(pathToFileURL(installer).href);
153
- const result = await installAgentSkillLinks({ source: path.join(root, 'skills', 'open-browser') });
154
- if (process.env.OPEN_BROWSER_SKILLS_VERBOSE === '1') process.stderr.write(JSON.stringify({ skillLinks: result }) + '\n');
155
- } catch (error) {
156
- if (process.env.OPEN_BROWSER_SKILLS_VERBOSE === '1') process.stderr.write(JSON.stringify({ skillLinksError: error.message }) + '\n');
157
- }
158
- }
159
-
160
- async function printSkillGuide(root) {
161
- const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'win32' ? 'windows' : null;
162
- const candidates = platform
163
- ? [path.join(root, 'skills', 'open-browser', `SKILL.${platform}.md`), path.join(root, 'skills', 'open-browser', 'SKILL.md')]
164
- : [path.join(root, 'skills', 'open-browser', 'SKILL.md')];
165
- for (const guide of candidates) {
166
- try {
167
- const { readFile } = await import('node:fs/promises');
168
- process.stdout.write(await readFile(guide, 'utf8'));
169
- return;
170
- } catch {}
171
- }
172
- throw Object.assign(new Error(`未找到 Skill 指南。已检查:${candidates.join('、')}`), { code: 'SKILL_GUIDE_NOT_FOUND' });
150
+ const [code] = await once(child, 'close');
151
+ return code ?? 1;
173
152
  }
174
153
 
175
154
  export async function invoke({ node, root, args, input, start = startLocalBrowser }) {
176
155
  const first = await run(node, root, args, input);
177
156
  if (first.code === 0) return first;
178
- const errorCode = parseErrorCode(first.stderr);
179
- if (!['SERVICE_UNAVAILABLE', 'not_ready'].includes(errorCode) || process.env.OPEN_BROWSER_AUTOSTART === '0') return first;
180
- if (errorCode === 'SERVICE_UNAVAILABLE') {
181
- try { await start(root); } catch { return first; }
182
- }
183
- if (!await waitForService(node, root)) return first;
157
+ const errorCode = parseErrorCode(args[0] === '--json' ? first.stdout : first.stderr);
158
+ if (process.env.OPEN_BROWSER_AUTOSTART === '0') return first;
159
+ if (errorCode === 'RESPONSE_LOST') {
160
+ const method = args[0] === '--json' ? args[1] : args[0];
161
+ const { readCapabilities } = await import(pathToFileURL(path.join(root, 'capability-matrix.mjs')).href);
162
+ // Capturing a frame issues a new one-time ticket. Retry only repeatable reads.
163
+ if (method === 'captureVisual' || !(readCapabilities.includes(method) ||
164
+ ['capabilities', 'listWorkspaces', 'listUploads', 'canvasSnapshot', 'admin.list', 'admin.scheduler'].includes(method))) return first;
165
+ } else if (!['SERVICE_UNAVAILABLE', 'not_ready'].includes(errorCode)) return first;
166
+ try { await ensureService(root, start, { code: errorCode }); }
167
+ catch { return first; }
184
168
  return run(node, root, args, input);
185
169
  }
186
170
 
187
171
  async function main() {
188
- const [root, ...args] = process.argv.slice(2);
189
- if (!root) throw new Error('OPEN_BROWSER_CLI_ROOT_REQUIRED');
172
+ const root = fileURLToPath(new URL('../../..', import.meta.url));
173
+ const args = process.argv.slice(2);
174
+ // Older desktop launchers provide their own package directory as argv[2].
175
+ if (args[0] && path.isAbsolute(args[0]) && await realpath(args[0]).catch(() => null) === path.resolve(root)) args.shift();
190
176
  if (args[0] === 'skill') {
191
177
  if (args.length > 1) throw Object.assign(new Error('skill 不接受额外参数。'), { code: 'INVALID_PARAMS' });
192
- await printSkillGuide(root);
178
+ const { readSkillGuide } = await import('./guide.mjs');
179
+ process.stdout.write(await readSkillGuide());
193
180
  return;
194
181
  }
195
- await installSkillLinks(root);
182
+ const { autoInstallSkillLinks } = await import('../../../skill-links.mjs');
183
+ await autoInstallSkillLinks({ useCache: true });
196
184
  if (args[0] === 'session') {
197
185
  process.exitCode = await runSession(process.execPath, root, args);
198
186
  return;
@@ -205,9 +193,9 @@ async function main() {
205
193
  process.exitCode = result.code;
206
194
  }
207
195
 
208
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
196
+ if (import.meta.main ?? (process.argv[1] && await realpath(process.argv[1]).catch(() => null) === fileURLToPath(import.meta.url))) {
209
197
  main().catch(error => {
210
- process.stderr.write(JSON.stringify({ error: { code: error.code ?? 'CLI_BOOTSTRAP_FAILED', message: error.message } }) + '\n');
198
+ process.stderr.write(JSON.stringify({ error: { code: error.code ?? 'CLI_BOOTSTRAP_FAILED', message: error.message, nextAction: error.nextAction } }) + '\n');
211
199
  process.exitCode = 1;
212
200
  });
213
201
  }
@@ -0,0 +1,17 @@
1
+ import { readFile } from 'node:fs/promises';
2
+
3
+ export async function readSkillGuide(platform = process.platform) {
4
+ let body;
5
+ try {
6
+ body = await readFile(new URL('../SKILL.md', import.meta.url), 'utf8');
7
+ } catch (cause) {
8
+ throw Object.assign(new Error('未找到 skills/open-browser/SKILL.md。', {cause}), {code:'SKILL_GUIDE_NOT_FOUND'});
9
+ }
10
+ if (!body.endsWith('\n')) body += '\n';
11
+ const label = {darwin:'macOS', win32:'Windows'}[platform];
12
+ if (!label) return body;
13
+ const supplement = await readFile(new URL(`../references/${label.toLowerCase()}.md`, import.meta.url), 'utf8')
14
+ .catch(error => { if (error.code !== 'ENOENT') throw error; });
15
+ if (!supplement) return body;
16
+ return `[open-browser:skill] open-browser usage guide (${label})\n\n${body}\n${supplement}`;
17
+ }
package/studio/studio.js CHANGED
@@ -10,7 +10,7 @@ const groups = [
10
10
  { id: 'human', title: '人工接管' }, { id: 'idle', title: '待命' },
11
11
  ];
12
12
  const phases = { idle: '等待指令', queued: '已排队', running: '执行中', needs_credential: '等待凭据',
13
- completed: '已完成', failed: '执行失败', cancelled: '已取消', outcome_unknown: '结果待核对' };
13
+ completed: '已完成', failed: '执行失败', needs_visual_permission: '需要授权截图', cancelled: '已取消', outcome_unknown: '结果待核对' };
14
14
  const kinds = { openPage: '打开页面', observe: '观察页面', act: '页面操作' };
15
15
  const stepKinds = { click: '点击', fill: '填写', fillCredential: '填写凭据' };
16
16
  const errorText = {
@@ -75,7 +75,7 @@ function clearSensitiveInputs() {
75
75
  function groupOf(w) {
76
76
  if (w.mode === 'human' || w.mode === 'transferring') return 'human';
77
77
  const a = w.activity || {};
78
- if (a.needsCredential || a.phase === 'failed' || a.phase === 'outcome_unknown') return 'attention';
78
+ if (a.needsCredential || a.needsVisualPermission || a.phase === 'failed' || a.phase === 'outcome_unknown') return 'attention';
79
79
  if (a.current || a.queued || a.phase === 'running' || a.phase === 'queued') return 'running';
80
80
  return 'idle';
81
81
  }
package/tab-adoption.mjs CHANGED
@@ -4,7 +4,7 @@ import { refreshTitle } from './desktop-page.mjs';
4
4
 
5
5
  // Only the packaged extension supplies a target ID. Agent clients receive an
6
6
  // expiring capability scoped to one workspace and never enumerate ordinary tabs.
7
- export async function offerTab(service, ws, {targetId, origin, accountAlias}) {
7
+ export async function offerTab(service, ws, {targetId, origin, accountAlias, resumeOnRestart = false}) {
8
8
  if (!service.sharedContext || service.actors.getStore() !== 'desktop') fail('forbidden');
9
9
  if (ws.everRegistered || ws.pending || ws.mode !== 'agent') fail('adoption_requires_empty_workspace');
10
10
  if (webOrigin(origin) !== origin || typeof targetId !== 'string' ||
@@ -37,7 +37,7 @@ export async function offerTab(service, ws, {targetId, origin, accountAlias}) {
37
37
  const timer = setTimeout(revoke, 120_000).unref();
38
38
  candidate.on('framenavigated', navigated);
39
39
  candidate.once('close', revoke);
40
- ws.offer = {revoke, page:candidate, origin, token, targetId, accountAlias, expiresAt:Date.now() + 120_000};
40
+ ws.offer = {revoke, resumeOnRestart, page:candidate, origin, token, targetId, accountAlias, expiresAt:Date.now() + 120_000};
41
41
  return {adoptionToken:token, workspaceId:ws.id, expiresAt:ws.offer.expiresAt};
42
42
  }
43
43
  fail('adoption_page_changed');
@@ -55,7 +55,7 @@ export async function adoptTab(service, ws, params) {
55
55
  ws.origins = new Set([offer.origin]);
56
56
  ws.resourceOrigins.clear();
57
57
  ws.accountAlias = offer.accountAlias;
58
- const tab = service.register(ws, offer.page);
58
+ const tab = service.register(ws, offer.page, offer.restoredPageId);
59
59
  tab.targetId = offer.targetId;
60
60
  tab.createdByAgent = false;
61
61
  // Bind before yielding so a concurrent redemption cannot claim this page.
@@ -68,6 +68,12 @@ export async function adoptTab(service, ws, params) {
68
68
  await refreshTitle(ws, tab);
69
69
  service.requireControl(ws, ws.generation);
70
70
  if (offer.page.isClosed() || URL.parse(offer.page.url())?.origin !== offer.origin) fail('adoption_page_changed');
71
+ const generation = ws.generation;
72
+ ws.resumeOnRestart = offer.resumeOnRestart === true;
73
+ await service.tabRecovery?.refresh(ws);
74
+ service.requireControl(ws, generation);
75
+ if (ws.pages.get(tab.id) !== tab || URL.parse(offer.page.url())?.origin !== offer.origin) fail('adoption_page_changed');
76
+ service.store.event(ws.owner, ws.id, 'page_bound', 'managed', null, null, {pageId:tab.id, resourceId:tab.id});
71
77
  return {workspaceId:ws.id, pageId:tab.id};
72
78
  }, {kind:'adoptCurrentTab', pageId:tab.id}).catch(async error => {
73
79
  // A concurrent takeover/close owns the release sequence.
@@ -0,0 +1,100 @@
1
+ import {createHash} from 'node:crypto';
2
+
3
+ // Read the browser-generated navigation entry in a fresh isolated world.
4
+ // Page scripts cannot substitute a value for this getter.
5
+ async function identify(page) {
6
+ const cdp = await page.context().newCDPSession(page);
7
+ try {
8
+ const {frameTree} = await cdp.send('Page.getFrameTree');
9
+ const {executionContextId} = await cdp.send('Page.createIsolatedWorld',{frameId:frameTree.frame.id,worldName:'open-browser-resume'});
10
+ const {result} = await cdp.send('Runtime.evaluate',{contextId:executionContextId,
11
+ expression:'window.navigation?.currentEntry?.key'});
12
+ if (typeof result.value !== 'string' || !/^[a-f0-9-]{36}$/i.test(result.value)) return null;
13
+ const {targetInfo} = await cdp.send('Target.getTargetInfo');
14
+ return {page, targetId:targetInfo.targetId, origin:URL.parse(targetInfo.url)?.origin,
15
+ entry:createHash('sha256').update(result.value).digest('hex')};
16
+ } finally { await cdp.detach().catch(() => {}); }
17
+ }
18
+
19
+ // Only the hash of the browser's own history entry is durable. Keep the
20
+ // checkpoint in step with ownership and pending writes, before input dispatch.
21
+ export class TabRecovery {
22
+ constructor(registry) {
23
+ this.save = registry.db.prepare('INSERT OR REPLACE INTO resumable_tabs(task,page,origin,entry,expires) VALUES(?,?,?,?,?)');
24
+ this.remove = registry.db.prepare('DELETE FROM resumable_tabs WHERE task=?');
25
+ this.entries = new WeakMap();
26
+ }
27
+
28
+ refresh(ws) {
29
+ if (this.closed || !ws.resumeOnRestart) return;
30
+ let state = this.entries.get(ws);
31
+ if (!state) {
32
+ state = {};
33
+ this.entries.set(ws,state);
34
+ }
35
+ const [tab] = ws.pages.values();
36
+ const eligible = ws.mode === 'agent' && !ws.finishing && !ws.securityChallenge && !ws.guardLost &&
37
+ tab && !tab.dialog && !tab.needsSubmissionReview && !tab.page.isClosed() &&
38
+ ws.origins.has(URL.parse(tab.page.url())?.origin) && ![...ws.jobs].some(job => job.kind === 'act');
39
+ if (state.saved && (!eligible || state.documentId !== tab.documentId)) {
40
+ this.remove.run(ws.id);
41
+ state.saved = false;
42
+ }
43
+ if (!eligible) return;
44
+ if (state.documentId !== tab.documentId || !state.identity) {
45
+ if (state.documentId === tab.documentId && state.pending) return state.pending;
46
+ const documentId = tab.documentId;
47
+ state.documentId = documentId;
48
+ state.identity = null;
49
+ state.pending = identify(tab.page).catch(() => null).then(identity => {
50
+ if (state.documentId !== documentId) return;
51
+ state.pending = null;
52
+ if (!this.closed && identity && tab.documentId === documentId && ws.pages.get(tab.id) === tab &&
53
+ identity.origin === URL.parse(tab.page.url())?.origin && ws.origins.has(identity.origin)) {
54
+ state.identity = identity;
55
+ this.refresh(ws);
56
+ }
57
+ });
58
+ return state.pending;
59
+ }
60
+ if (!state.saved || Date.now() >= state.renewAt) {
61
+ const now = Date.now();
62
+ this.save.run(ws.id,tab.id,state.identity.origin,state.identity.entry,now+86400000);
63
+ state.saved = true;
64
+ state.renewAt = now + 60000;
65
+ }
66
+ }
67
+ }
68
+
69
+ export async function restoreApprovedTabs(engine, registry) {
70
+ const rows = registry.db.prepare(`SELECT r.*, t.name, t.owner, t.agentName FROM resumable_tabs r
71
+ JOIN tasks t ON r.task=t.id WHERE r.expires>? AND (t.owner='local' OR t.owner IN (SELECT id FROM clients))`).all(Date.now());
72
+ registry.db.prepare(`DELETE FROM resumable_tabs WHERE expires<=? OR task IN
73
+ (SELECT id FROM tasks WHERE owner!='local' AND owner NOT IN (SELECT id FROM clients))`).run(Date.now());
74
+ const consume = registry.db.prepare('DELETE FROM resumable_tabs WHERE task=?');
75
+ if (!rows.length) return;
76
+ const origins = new Set(rows.map(row => row.origin));
77
+ const candidates = await Promise.all(engine.sharedContext.pages()
78
+ .filter(page => origins.has(URL.parse(page.url())?.origin)).map(page => identify(page).catch(() => null)));
79
+ for (const row of rows) {
80
+ const matches = candidates.filter(item => item?.origin === row.origin && item.entry === row.entry);
81
+ if (matches.length !== 1 || registry.hasDelegates(row.task)) {
82
+ consume.run(row.task);
83
+ continue;
84
+ }
85
+ const [match] = matches;
86
+ let ws;
87
+ try {
88
+ await engine.create({name:row.name,agentName:row.agentName},row.owner,row.task);
89
+ ws = engine.workspaces.get(row.task);
90
+ const offer = await engine.call('offerCurrentTab',{workspaceId:row.task,targetId:match.targetId,
91
+ origin:row.origin,resumeOnRestart:true},row.owner,'desktop');
92
+ if ((await identify(match.page))?.entry !== row.entry || !ws.offer) throw Error('navigation_changed');
93
+ ws.offer.restoredPageId = row.page;
94
+ await registry.call(engine,row.owner,'adoptCurrentTab',{workspaceId:row.task,adoptionToken:offer.adoptionToken});
95
+ } catch {
96
+ consume.run(row.task);
97
+ if (ws) await engine.call('closeWorkspace',{workspaceId:row.task},row.owner);
98
+ }
99
+ }
100
+ }
package/visual-page.mjs CHANGED
@@ -51,12 +51,15 @@ async function measure(session, contextId, guarded=false) {
51
51
  }
52
52
  if(privateNode || sensitive.has(doc.nodes.parentIndex[i])) sensitive.add(i);
53
53
  }
54
- const masks=[],layout=[],hiddenNodes=new Set();
54
+ const masks=[],layout=[],hiddenNodes=new Set(), canvases=[];
55
55
  let complexPaint=false;
56
56
  for(let j=0;j<doc.layout.nodeIndex.length;j++) {
57
57
  const node = doc.layout.nodeIndex[j], b = doc.layout.bounds[j];
58
58
  const [visibility,filter,reflection,backdrop,opacity] = doc.layout.styles[j].map(k=>strings[k]);
59
59
  if(opacity==='0') hiddenNodes.add(node);
60
+ if (strings[doc.nodes.nodeName[node]] === 'CANVAS' && b[2] > 0 && b[3] > 0 &&
61
+ visibility === 'visible' && opacity !== '0' && !sensitive.has(node))
62
+ canvases.push(doc.nodes.backendNodeId[node]);
60
63
  layout.push([doc.nodes.backendNodeId[node],b,doc.layout.paintOrders[j],visibility]);
61
64
  if ([filter,reflection,backdrop].some(v=>v && v!=='none')) complexPaint=true;
62
65
  if(sensitive.has(node)) masks.push({x:b[0]/viewport.zoom-viewport.scrollX-2,y:b[1]/viewport.zoom-viewport.scrollY-2,
@@ -73,7 +76,7 @@ async function measure(session, contextId, guarded=false) {
73
76
  if(masks.length && complexPaint) fail('visual_redaction_unavailable');
74
77
  const protectedNodes=new Set([...sensitive].map(i=>doc.nodes.backendNodeId[i]));
75
78
  const hosts=[...new Set([...shadowHosts].map(i=>strings[doc.nodes.nodeName[i]].toLowerCase()))];
76
- return {viewport,masks,protectedNodes,hosts,signature:hash(JSON.stringify([viewport,layout,masks]))};
79
+ return {viewport,masks,protectedNodes,hosts,canvases,signature:hash(JSON.stringify([viewport,layout,masks]))};
77
80
  }
78
81
 
79
82
  // Read the current compositor surface. CDP's screenshot clip can temporarily
@@ -182,6 +185,10 @@ export class VisualPages {
182
185
  return {principalId,origin,allow};
183
186
  }
184
187
 
188
+ hasPermission(ws, principalId, origin) {
189
+ return this.permissions.get(ws)?.has(JSON.stringify([principalId,origin])) ?? false;
190
+ }
191
+
185
192
  authority(ws,tab,actor,mode) {
186
193
  if(!this.enabled) fail('visual_disabled');
187
194
  if(ws.mode!==mode || ws.finishing) fail('stale_control');
@@ -204,6 +211,7 @@ export class VisualPages {
204
211
  const contextId=await isolatedContext(session);
205
212
  const initial=await measure(session,contextId);
206
213
  const v=initial.viewport;
214
+ if (params.liveCanvas && initial.canvases.length !== 1) fail('visual_canvas_ambiguous');
207
215
  let region=params.region;
208
216
  if(params.ref!==undefined) {
209
217
  const handle=tab.refs.get(params.ref);
@@ -222,7 +230,7 @@ export class VisualPages {
222
230
  const frameId=randomUUID();
223
231
  this.frames.set(tab,{...auth,actor,mode,clip,frameId,expires:Date.now()+frameLifetime,signature:initial.signature,
224
232
  // Retain only a digest, so changed paint on canvas is detected without saving its pixels.
225
- pixelDigest:hash(pixels)});
233
+ pixelDigest:hash(pixels), canvasId:params.liveCanvas ? initial.canvases[0] : null});
226
234
  return {workspaceId:ws.id,pageId:tab.id,frameId,documentId:auth.documentId,controlGeneration:auth.controlGeneration,
227
235
  origin:auth.origin,mimeType:'image/png',data:pixels.toString('base64'),clip,viewport:{width:v.width,height:v.height},
228
236
  pixelWidth:clip.width,pixelHeight:clip.height,scale:v.scale,zoom:v.zoom,deviceScaleFactor:v.deviceScaleFactor};
@@ -252,9 +260,11 @@ export class VisualPages {
252
260
  const executionContextId=await isolatedContext(session);
253
261
  const layout=await measure(session,executionContextId);
254
262
  if(layout.signature!==frame.signature) fail('stale_visual_frame');
255
- const pixels=await maskedCapture(session,executionContextId,frame.clip,layout);
256
- if(hash(pixels)!==frame.pixelDigest || (await measure(session,executionContextId)).signature!==layout.signature)
257
- fail('stale_visual_frame');
263
+ if (!frame.canvasId) {
264
+ const pixels=await maskedCapture(session,executionContextId,frame.clip,layout);
265
+ if(hash(pixels)!==frame.pixelDigest || (await measure(session,executionContextId)).signature!==layout.signature)
266
+ fail('stale_visual_frame');
267
+ }
258
268
  async function point(x,y,verifyFocus=false) {
259
269
  check();
260
270
  if(!inRect(x,y,frame.clip) || layout.masks.some(m=>inRect(x,y,m))) fail('visual_target_denied');
@@ -269,7 +279,7 @@ export class VisualPages {
269
279
  const {result}=await session.send('Runtime.evaluate',{expression,contextId:executionContextId});
270
280
  if(!result.objectId) fail('visual_target_denied');
271
281
  const {node}=await session.send('DOM.describeNode',{objectId:result.objectId});
272
- if(!node.backendNodeId || layout.protectedNodes.has(node.backendNodeId)) fail('visual_target_denied');
282
+ if(!node.backendNodeId || (frame.canvasId && frame.canvasId !== node.backendNodeId) || layout.protectedNodes.has(node.backendNodeId)) fail('visual_target_denied');
273
283
  check();
274
284
  }
275
285
  await point(action.x,action.y,['key','text'].includes(action.type));
@@ -49,6 +49,7 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
49
49
  service.store.save(ws.owner, ws.id, digest, receipt);
50
50
  const pending = { operationId };
51
51
  ws.finishing = pending;
52
+ service.notify(ws);
52
53
  for (const tab of ws.pages.values()) discardDialog(tab);
53
54
  ws.generation = randomUUID();
54
55
  stopOperations(ws);
@@ -83,6 +84,7 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
83
84
  service.store.save(ws.owner, ws.id, digest, receipt);
84
85
  }
85
86
  if (!service.sharedContext && !receipt.keptPageIds.length) await ws.context.close();
87
+ service.store.event(ws.owner, ws.id, 'workspace_end', 'finished');
86
88
  ws.mode = 'closed';
87
89
  ws.credentials.clear();
88
90
  ws.credentialRequests.clear();
@@ -118,7 +120,8 @@ export async function finish(service, ws, {operationId, keepPageIds, controlGene
118
120
  export async function handOff(service, ws, pageId, focus = true, expectedGeneration) {
119
121
  if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
120
122
  if (ws.returning) fail('control_transition');
121
- if (ws.handoff) return ws.handoff;
123
+ const hasDialog = () => [...ws.pages.values()].some(page => page.dialog);
124
+ if (ws.handoff) return hasDialog() ? workspaceView(ws) : ws.handoff;
122
125
  if (ws.mode === 'human') return workspaceView(ws);
123
126
  const tab = pageId ? service.tab(ws, pageId) : [...ws.pages.values()].at(-1);
124
127
  ws.mode = 'transferring';
@@ -147,6 +150,12 @@ export async function handOff(service, ws, pageId, focus = true, expectedGenerat
147
150
  await refreshControlGroups(service, ws);
148
151
  return workspaceView(ws);
149
152
  })().finally(() => { ws.handoff = null; });
153
+ // A native dialog suspends the dispatched action. Let the desktop answer it
154
+ // while ownership is transferring, then finish draining before enabling input.
155
+ if (hasDialog()) {
156
+ ws.handoff.catch(() => {});
157
+ return workspaceView(ws);
158
+ }
150
159
  return ws.handoff;
151
160
  }
152
161
 
@@ -169,6 +178,12 @@ async function refreshControlGroups(service, ws) {
169
178
  export async function returnToAgent(service, ws, expectedGeneration) {
170
179
  if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
171
180
  if (ws.returning) return ws.returning;
181
+ if (ws.handoff && ws.mode === 'transferring') {
182
+ if ([...ws.pages.values()].some(tab => tab.dialog)) fail('control_transition');
183
+ await ws.handoff;
184
+ if (expectedGeneration !== undefined && expectedGeneration !== ws.generation) fail('stale_control');
185
+ if (ws.returning) return ws.returning;
186
+ }
172
187
  if (ws.mode !== 'human') fail('not_in_human_control');
173
188
  ws.mode = 'transferring';
174
189
  service.store.event(ws.owner, ws.id, 'control', ws.mode);
@@ -209,7 +224,8 @@ export async function returnToAgent(service, ws, expectedGeneration) {
209
224
  return ws.returning;
210
225
  }
211
226
 
212
- export async function close(service, ws) {
227
+ export async function close(service, ws, reason = 'explicit_close') {
228
+ service.store.event(ws.owner, ws.id, 'workspace_end', reason);
213
229
  ws.offer?.revoke();
214
230
  for (const tab of ws.pages.values()) discardDialog(tab);
215
231
  ws.mode = 'closed';