@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
@@ -0,0 +1,61 @@
1
+ import { execFileSync, spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { access, readFile } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const root = fileURLToPath(new URL('../', import.meta.url));
8
+ const defaultApp = path.join(root, 'dist', 'open-browser.app');
9
+
10
+ function commandPath(name, fallback) {
11
+ try {
12
+ return execFileSync('/usr/bin/xcrun', ['--find', name], { encoding: 'utf8' }).trim();
13
+ } catch {
14
+ return fallback;
15
+ }
16
+ }
17
+
18
+ function run(command, args) {
19
+ execFileSync(command, args, { stdio: 'inherit' });
20
+ }
21
+
22
+ async function main() {
23
+ if (process.argv.includes('--help') || process.argv.includes('-h')) {
24
+ console.log('用法:node desktop/verify-macos-release.mjs [app-path]');
25
+ return;
26
+ }
27
+ if (process.platform !== 'darwin') throw new Error('macOS 发行验收只能在 macOS 执行。');
28
+ const app = path.resolve(process.argv[2] || process.env.OPEN_BROWSER_APP_PATH || defaultApp);
29
+ await access(app);
30
+ if (!app.endsWith('.app')) throw new Error('验收输入必须是 .app 应用包。');
31
+ run('/usr/bin/codesign', ['--verify', '--strict', '--deep', '--verbose=2', app]);
32
+ const details = spawnSync('/usr/bin/codesign', ['-d', '--verbose=4', app], { encoding: 'utf8' });
33
+ if (details.status !== 0) throw new Error(details.stderr || '无法读取应用签名详情。');
34
+ const signatureDetails = details.stdout + details.stderr;
35
+ if (!/CodeDirectory.*\bruntime\b/.test(signatureDetails))
36
+ throw new Error('应用没有启用 Hardened Runtime。');
37
+ const stapler = commandPath('stapler', '/usr/bin/xcrun');
38
+ run(stapler, stapler === '/usr/bin/xcrun' ? ['stapler', 'validate', app] : ['validate', app]);
39
+ run(commandPath('spctl', '/usr/sbin/spctl'), ['--assess', '--type', 'execute', '--verbose=4', app]);
40
+
41
+ const appArch = app.endsWith('-x64.app') ? 'x64' : app.endsWith('-arm64.app') ? 'arm64' : process.env.OPEN_BROWSER_TARGET_ARCH || process.arch;
42
+ const zip = process.env.OPEN_BROWSER_NOTARY_ZIP || path.join(path.dirname(app), `open-browser-macos-${appArch}.zip`);
43
+ try {
44
+ await access(zip);
45
+ const checksumFile = zip + '.sha256';
46
+ await access(checksumFile);
47
+ const expected = (await readFile(checksumFile, 'utf8')).trim().split(/\s+/)[0];
48
+ const actual = createHash('sha256').update(await readFile(zip)).digest('hex');
49
+ if (expected !== actual) throw new Error(`ZIP SHA-256 不匹配:${zip}`);
50
+ console.log(`${zip}\nSHA-256 ${actual}`);
51
+ } catch (error) {
52
+ if (error?.code === 'ENOENT') throw new Error(`缺少已固化票据的 ZIP 或校验和:${zip}`);
53
+ throw error;
54
+ }
55
+ console.log(`macOS 发行验收通过:${app}`);
56
+ }
57
+
58
+ main().catch(error => {
59
+ console.error(error instanceof Error ? error.message : error);
60
+ process.exitCode = 1;
61
+ });
package/diagnostics.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // Export only categories from this table. IDs, URLs, page text and errors can contain user input.
2
2
  const advice = new Map([
3
+ ['human_verification_required',['verification','take_control_and_complete_verification']],
3
4
  ['target_obscured',['obscured','observe_foreground']],
4
5
  ['timeout',['timeout','check_site_result']],
5
6
  ['wait_timeout',['timeout','check_site_result']],
@@ -11,6 +12,14 @@ const advice = new Map([
11
12
  ['run_timeout',['budget','inspect_progress']],
12
13
  ['stale_ref',['stale_target','observe_again']],
13
14
  ['stale_document',['navigation','observe_again']],
15
+ ['target_missing',['target','observe_again']],
16
+ ['target_ambiguous',['target','narrow_locator']],
17
+ ['origin_denied',['permission','grant_origin']],
18
+ ['invalid_actions',['input','read_schema']],
19
+ ['invalid_params',['input','read_schema']],
20
+ ['browser_action_failed',['browser','observe_again']],
21
+ ['page_not_found',['page','list_workspaces']],
22
+ ['service_restarted',['recovery','inspect_progress']],
14
23
  ]);
15
24
  const states = new Set(['queued','running','failed','completed','cancelled','outcome_unknown']);
16
25
  export function operationDiagnostic(receipt, dispatched) {
@@ -1,6 +1,7 @@
1
- import { close as closeWorkspace, finish, finishDigest, handOff, returnToAgent } from './workspace-lifecycle.mjs';
1
+ import { adoptTab, offerTab } from './tab-adoption.mjs';
2
+ import { close as closeWorkspace, finish, finishDigest, previewFinish, handOff, returnToAgent } from './workspace-lifecycle.mjs';
2
3
  import { perform } from './action-execution.mjs';
3
- import { allowedPageOrigin, clearFrameRefs, clearRefs, fail, publicError, redact, requirePageOrigin, stringParam, webOrigin, workspaceView } from './workspace-state.mjs';
4
+ import { ServiceError, allowedPageOrigin, clearFrameRefs, clearRefs, fail, publicError, redact, requirePageOrigin, stringParam, webOrigin, workspaceView } from './workspace-state.mjs';
4
5
  import {workflowRequest,workflowOrigin,performWorkflow} from './site-workflow.mjs';
5
6
  import { agentMethods, capabilityProfiles, limits } from './api-contract.mjs';
6
7
  import {UploadGrants} from './uploads.mjs';
@@ -17,6 +18,7 @@ import { AsyncLocalStorage } from 'node:async_hooks';
17
18
  import { ReceiptStore } from './receipt-store.mjs';
18
19
  import { DesktopFrames, enqueueHuman, navigatePage, pageInput, pageLocation, refreshTitle, releaseInput } from './desktop-page.mjs';
19
20
  import { privacyCapabilities } from './privacy-config.mjs';
21
+ import { buildProfile } from './build-profile.mjs';
20
22
  import path from 'node:path';
21
23
  import { stateDir } from './paths.mjs';
22
24
  import { OutputStore } from './output-store.mjs';
@@ -57,13 +59,20 @@ const statusQueries = new Set(['getWorkspace', 'visualStatus', 'listDownloads',
57
59
 
58
60
  export class BrowserService {
59
61
  constructor(browser, { concurrency = 4, lowMemoryMiB = Number(process.env.OPEN_BROWSER_LOW_MEMORY_MIB || 0), idleTimeoutMs = 30 * 60_000, sharedContext, groupTab, onActivity, onActionTarget,
60
- journalPath, releaseTab, readOnlyObserver = readDocumentSummary } = {}) {
62
+ journalPath, releaseTab, setInputGuard, withAgentInput, inputGuardMode, readOnlyObserver = readDocumentSummary } = {}) {
61
63
  if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16) fail('invalid_concurrency');
62
64
  if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs <= 0) fail('invalid_idle_timeout');
63
65
  this.browser = browser;
64
66
  this.sharedContext = sharedContext;
65
67
  this.groupTab = groupTab;
66
68
  this.releaseTab = releaseTab;
69
+ this.withAgentInput = withAgentInput;
70
+ this.inputGuardMode = inputGuardMode;
71
+ if (setInputGuard) this.setInputGuard = (ws, tab, enabled) => setInputGuard(tab, enabled, () => {
72
+ ws.guardLost = true;
73
+ if (ws.mode === 'agent' && !ws.finishing && !this.stopped)
74
+ void this.handOff(ws, undefined, false).catch(() => {});
75
+ });
67
76
  this.readOnlyObserver = readOnlyObserver;
68
77
  this.actors = new AsyncLocalStorage();
69
78
  this.store = new ReceiptStore(journalPath, () => this.actors.getStore());
@@ -91,10 +100,41 @@ export class BrowserService {
91
100
  }
92
101
 
93
102
  notify(ws) {
103
+ if (ws.mode === 'agent' || ws.mode === 'closed' || ws.finishing) {
104
+ for (const resume of ws.controlWaiters || []) resume();
105
+ }
94
106
  this.notifier.notify(ws);
95
107
  }
96
108
 
97
- notifyTarget(ws, tab, el, documentId, controlGeneration, origin) {
109
+ invalidateObservation(tab) {
110
+ if (tab) tab.observationCache = undefined;
111
+ }
112
+
113
+ async observationRevision(tab) {
114
+ try {
115
+ return await tab.page.evaluate(() => {
116
+ const key = '__openBrowserObservationRevision';
117
+ if (!Number.isSafeInteger(window[key])) {
118
+ window[key] = 1;
119
+ const ignored = node => node?.closest?.('[data-open-browser-activity],[data-open-browser-target],[data-open-browser-agent-cursor],[data-open-browser-label]');
120
+ const observer = new MutationObserver(records => {
121
+ if (records.some(record => {
122
+ if (record.type === 'attributes' && ignored(record.target)) return false;
123
+ if (record.type === 'childList' && [...record.addedNodes, ...record.removedNodes].every(ignored)) return false;
124
+ return true;
125
+ })) window[key]++;
126
+ });
127
+ observer.observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
128
+ Object.defineProperty(window, '__openBrowserObservationObserver', { value: observer, configurable: true });
129
+ }
130
+ return window[key];
131
+ });
132
+ } catch {
133
+ return null;
134
+ }
135
+ }
136
+
137
+ notifyTarget(ws, tab, el, documentId, controlGeneration, origin, actionKind = '操作') {
98
138
  if (!this.onActionTarget) return;
99
139
  const ticket = Symbol();
100
140
  tab.latestTarget = ticket;
@@ -109,8 +149,12 @@ export class BrowserService {
109
149
  const left = Math.max(0, box.x), right = Math.min(size.width, box.x + box.width);
110
150
  const top = Math.max(0, box.y), bottom = Math.min(size.height, box.y + box.height);
111
151
  if (!(right > left && bottom > top)) return;
112
- return this.onActionTarget({ workspaceId: ws.id, pageId: tab.id, documentId, controlGeneration,
113
- x: (left + right) / 2, y: (top + bottom) / 2, origin });
152
+ const target = { workspaceId: ws.id, pageId: tab.id, documentId, controlGeneration,
153
+ x: (left + right) / 2, y: (top + bottom) / 2, origin };
154
+ Object.defineProperty(target, 'actionKind', { value: actionKind, enumerable: false });
155
+ this.store.event(ws.owner, ws.id, 'action', 'running', null, null,
156
+ { pageId: tab.id, resourceId: String(actionKind).slice(0, 64) });
157
+ return this.onActionTarget(target);
114
158
  }).catch(() => {});
115
159
  }
116
160
 
@@ -122,7 +166,7 @@ export class BrowserService {
122
166
  if (this.stopped) fail('service_stopped');
123
167
  if (typeof clientId !== 'string' || !clientId) fail('unauthorized');
124
168
  if (!params || typeof params !== 'object' || Array.isArray(params)) fail('invalid_params');
125
- if (method === 'capabilities') return {version:1,contractVersion:2,methods:agentMethods,capabilities:capabilityProfiles,limits,privacy:privacyCapabilities(),visual:{enabled:this.visual.enabled,actions:this.visual.enabled ? visualActions : []}};
169
+ if (method === 'capabilities') return {version:1,contractVersion:2,buildProfile,methods:agentMethods,capabilities:capabilityProfiles,limits,privacy:privacyCapabilities(),visual:{enabled:this.visual.enabled,actions:this.visual.enabled ? visualActions : []}};
126
170
  if(method==='runWorkflow') {
127
171
  params=workflowRequest(params);
128
172
  method='act';
@@ -141,8 +185,10 @@ export class BrowserService {
141
185
  const {records, nextObjectCursor} = this.store.recoveryObjects(clientId, params.workspaceId, params.objectsAfter, params.limit);
142
186
  if (!ws && !records.length && !operations.length && !this.store.events(clientId,params.workspaceId,0,1).events.length)
143
187
  fail('workspace_not_found');
144
- const pages = records.filter(row => row.kind === 'page').map(({id}) => ({
145
- pageId:id, next: ws?.pages.has(id) ? 'observe' : 'handle_unavailable'
188
+ const pages = records.filter(row => row.kind === 'page').map(({id, disposition}) => ({
189
+ pageId:id, ...(disposition && {lastDisposition:disposition}), next: ws?.pages.has(id) ? 'observe' : 'handle_unavailable',
190
+ pageAvailability:ws ? (ws.pages.has(id) ? 'managed' : 'closed') : 'unregistered',
191
+ nextAction:ws?.pages.has(id) ? (ws.mode === 'agent' ? 'reattachPage' : 'wait_for_agent_control') : 'request_tab_selection'
146
192
  }));
147
193
  return {
148
194
  workspaceId:params.workspaceId, mode:ws?.mode ?? 'unavailable', pages,
@@ -158,6 +204,8 @@ export class BrowserService {
158
204
  if (method === 'diagnoseOperation') return this.store.diagnose(clientId, params.workspaceId, params.operationId);
159
205
  if (method === 'listOperations')
160
206
  return this.store.list(clientId, params.workspaceId, params.after, params.limit);
207
+ if (method === 'getWorkspace' && params.profileId !== undefined && params.profileId !== serviceProfileId)
208
+ fail('profile_mismatch');
161
209
  const ws = this.workspaces.get(params.workspaceId);
162
210
  if (!ws || ws.owner !== clientId) {
163
211
  if (['listOutputs', 'readOutput'].includes(method)) {
@@ -182,6 +230,39 @@ export class BrowserService {
182
230
  if (!statusQueries.has(method)) ws.lastActiveAt = Date.now();
183
231
  switch (method) {
184
232
  case 'getWorkspace': return workspaceView(ws, true);
233
+ case 'offerCurrentTab': return offerTab(this, ws, params);
234
+ case 'adoptCurrentTab': return adoptTab(this, ws, params);
235
+ case 'canvasSnapshot': return this.enqueue(ws, async () => {
236
+ const tab = this.tab(ws, params.pageId);
237
+ const origin = requirePageOrigin(ws, tab), documentId = tab.documentId, controlGeneration = ws.generation;
238
+ const data = await tab.page.evaluate(inspectDocument, {canvas:true, origins:[origin]});
239
+ this.requireControl(ws, controlGeneration);
240
+ if (!data || ws.pages.get(tab.id) !== tab || tab.documentId !== documentId || requirePageOrigin(ws, tab) !== origin)
241
+ fail('stale_observation');
242
+ for (const row of [...data.nodes, ...data.edges, ...data.messages, ...data.attachments]) {
243
+ for (const field of ['id','label','text','source','target']) if (field in row) row[field] = redact(ws, row[field]);
244
+ }
245
+ const snapshotVersion = createHash('sha256').update(JSON.stringify([documentId,controlGeneration,data])).digest('hex');
246
+ return {workspaceId:ws.id,pageId:tab.id,documentId,controlGeneration,snapshotVersion,...data};
247
+ }, {kind:'canvasSnapshot', pageId:params.pageId});
248
+ case 'previewFinish': return previewFinish(this, ws, params.keepPageIds);
249
+ case 'reattachPage': {
250
+ this.tab(ws, params.pageId);
251
+ if (params.waitMs && ws.mode !== 'agent') {
252
+ ws.controlWaiters ??= new Set();
253
+ if (ws.controlWaiters.size >= 32) fail('queue_full');
254
+ await new Promise((resolve, reject) => {
255
+ const resume = () => { clearTimeout(timer); ws.controlWaiters.delete(resume); resolve(); };
256
+ const timer = setTimeout(() => { ws.controlWaiters.delete(resume); reject(new ServiceError('workspace_under_user_control')); }, params.waitMs);
257
+ ws.controlWaiters.add(resume);
258
+ });
259
+ }
260
+ return this.enqueue(ws, async () => {
261
+ const tab = this.tab(ws, params.pageId);
262
+ if (this.groupTab && tab.syncedGeneration !== ws.generation) await this.syncTab(ws, tab);
263
+ return this.observe(ws, tab);
264
+ }, {kind:'observe', pageId:params.pageId});
265
+ }
185
266
  case 'listUploads': return ws.uploads.list();
186
267
  case 'grantUpload': {
187
268
  if (this.actors.getStore() !== 'desktop') fail('forbidden');
@@ -212,6 +293,7 @@ export class BrowserService {
212
293
  }
213
294
  case 'visualStatus': return {lastCapture:ws.lastVisualCapture || null};
214
295
  case 'grantOrigin': {
296
+ if (ws.singleTab) fail('single_tab_scope');
215
297
  if (params.controlGeneration !== ws.generation || !['agent', 'human'].includes(ws.mode)) fail('stale_control');
216
298
  const origin = webOrigin(params.origin);
217
299
  if (origin !== params.origin || !['navigation', 'resource'].includes(params.scope)) fail('invalid_params');
@@ -244,6 +326,7 @@ export class BrowserService {
244
326
  case 'pageNavigate': return this.desktopNavigate(ws, params, false);
245
327
  case 'closePage': {
246
328
  const tab = this.tab(ws, params.pageId);
329
+ if (ws.singleTab) fail('user_owned_page');
247
330
  await tab.page.close();
248
331
  return { workspaceId: ws.id, pageId: tab.id, closed: true };
249
332
  }
@@ -257,6 +340,7 @@ export class BrowserService {
257
340
  case 'openPage': return this.enqueue(ws, job => this.open(ws, params.url, job), { kind: 'openPage' });
258
341
  case 'observe': return this.enqueue(ws, () => this.observe(ws, this.tab(ws, params.pageId), params),
259
342
  { kind: 'observe', pageId: params.pageId });
343
+ case 'observeAndAct': return this.observeAndAct(ws, params);
260
344
  case 'act': return this.act(ws, params);
261
345
  case 'setCredential': return this.setCredential(ws, params);
262
346
  case 'resolveCredential': {
@@ -294,7 +378,9 @@ export class BrowserService {
294
378
  }
295
379
  case 'handOff':
296
380
  case 'takeControl': return this.handOff(ws, params.pageId, true, params.controlGeneration);
297
- case 'returnToAgent': return this.returnToAgent(ws, params.controlGeneration);
381
+ case 'returnToAgent':
382
+ if (params.pageId !== undefined) this.tab(ws, params.pageId);
383
+ return this.returnToAgent(ws, params.controlGeneration);
298
384
  case 'closeWorkspace':
299
385
  if (ws.mode !== 'agent') fail('workspace_under_user_control');
300
386
  await closeWorkspace(this, ws);
@@ -320,7 +406,7 @@ export class BrowserService {
320
406
  ? { context: this.sharedContext } : await this.allocateContext();
321
407
  try {
322
408
  const ws = { id: randomUUID(), owner, name, agentName: displayName, context, browserContextId, origins, networkMode, mode: 'agent',
323
- resourceOrigins: resources, blockedOrigins: new Map(), generation: randomUUID(), control: new AbortController(), pages: new Map(), operations: new Map(), credentials: new Map(),
409
+ resourceOrigins: resources, blockedOrigins: new Map(), inputGuardMode: this.inputGuardMode || (this.sharedContext ? 'unavailable' : 'not_required'), generation: randomUUID(), control: new AbortController(), pages: new Map(), operations: new Map(), credentials: new Map(),
324
410
  tail: Promise.resolve(), lanes: new Map(), pending: 0, handoff: null, lastActiveAt: Date.now(),
325
411
  inputTail: Promise.resolve(), inputPending: 0,
326
412
  popupTasks: new Set(), jobs: new Set(), recent: null, credentialRequests: new Map() };
@@ -351,9 +437,11 @@ export class BrowserService {
351
437
  const ws = this.workspaces.get(created.workspaceId);
352
438
  if (!ws) fail('workspace_unavailable');
353
439
  try {
354
- return await this.open(ws, url);
440
+ return await this.enqueue(ws, job => this.open(ws, url, job), {kind:'openPage'});
355
441
  } catch (error) {
356
- await closeWorkspace(this, ws).catch(() => {});
442
+ // A takeover can happen while the first page is being opened. The
443
+ // workspace and any opened tab then belong to the person taking control.
444
+ if (ws.mode === 'agent' && !ws.finishing) await closeWorkspace(this, ws).catch(() => {});
357
445
  throw error;
358
446
  }
359
447
  }
@@ -381,11 +469,27 @@ export class BrowserService {
381
469
 
382
470
  routeWorkspace(target, ws) { return routeWorkspace(target, ws, !!this.sharedContext); }
383
471
 
472
+ async syncTab(ws, tab) {
473
+ if (!this.groupTab) return;
474
+ const generation = ws.generation;
475
+ try { await this.groupTab(tab.page, ws.id, ws.name, ws.mode, ws.agentName, tab.id, generation, !!ws.singleTab); }
476
+ catch { fail('sync_pending'); }
477
+ if (ws.pages.get(tab.id) === tab && ws.generation === generation) {
478
+ tab.syncedGeneration = generation;
479
+ tab.syncRevision = (tab.syncRevision || 0) + 1;
480
+ tab.lastSyncedAt = Date.now();
481
+ this.notify(ws);
482
+ }
483
+ }
484
+
384
485
  register(ws, page) {
486
+ ws.everRegistered = true;
385
487
  const existing = [...ws.pages.values()].find(tab => tab.page === page);
386
488
  if (existing) return existing;
387
489
  const tab = { id: randomUUID(), page, documentId: randomUUID(), refs:new Map(), frameRefs:new Map(), frameDocuments:new WeakMap(), frameIds:new WeakMap(), cursors:new Map(), frameRevision:0, title: '',
388
490
  heldKeys: new Set(), heldButtons: new Set() };
491
+ tab.extensionSync = !!this.groupTab;
492
+ ws.securityChallenge = null;
389
493
  this.store.remember(ws.owner, ws.id, 'page', tab.id);
390
494
  ws.pages.set(tab.id, tab);
391
495
  const releaseDialogs = attachDialogs(ws,tab,()=>{
@@ -403,7 +507,9 @@ export class BrowserService {
403
507
  }
404
508
  ws.credentialRequests.delete(tab.id);
405
509
  tab.title = '';
510
+ ws.securityChallenge = null;
406
511
  tab.documentId = randomUUID();
512
+ this.invalidateObservation(tab);
407
513
  clearRefs(tab);
408
514
  this.notify(ws);
409
515
  if (tab.heldKeys.size || tab.heldButtons.size)
@@ -411,7 +517,24 @@ export class BrowserService {
411
517
  void refreshTitle(ws, tab);
412
518
  };
413
519
  const loaded = () => { void refreshTitle(ws, tab); };
520
+ const response = async response => {
521
+ try {
522
+ if (response.request().resourceType() !== 'document') return;
523
+ const headers = await response.allHeaders();
524
+ const mitigated = headers['cf-mitigated']?.toLowerCase() === 'challenge';
525
+ const cloudflare = headers.server?.toLowerCase().includes('cloudflare');
526
+ if (!mitigated && !(cloudflare && response.status() >= 403)) return;
527
+ const url = URL.parse(response.url());
528
+ if (!url || !['http:', 'https:'].includes(url.protocol)) return;
529
+ ws.securityChallenge = { provider: 'cloudflare', origin: url.origin,
530
+ status: response.status(), detectedAt: Date.now() };
531
+ this.store.event(ws.owner, ws.id, 'security', 'human_verification_required', null,
532
+ { pageId: tab.id, origin: url.origin, status: response.status() });
533
+ this.notify(ws);
534
+ } catch { /* A closing page cannot change the workspace state. */ }
535
+ };
414
536
  const closed = () => {
537
+ this.store.pageDisposition(ws.owner, ws.id, tab.id, page.isClosed() ? 'closed' : 'released');
415
538
  releaseDialogs();
416
539
  void tab.summarySession?.detach().catch(() => {});
417
540
  clearRefs(tab);
@@ -429,12 +552,14 @@ export class BrowserService {
429
552
  page.on('framenavigated', navigated);
430
553
  page.on('framedetached', navigated);
431
554
  page.on('domcontentloaded', loaded);
555
+ page.on('response', response);
432
556
  page.on('close', closed);
433
557
  tab.unregister = () => {
434
558
  page.off('download', downloaded);
435
559
  page.off('framenavigated', navigated);
436
560
  page.off('framedetached', navigated);
437
561
  page.off('domcontentloaded', loaded);
562
+ page.off('response', response);
438
563
  page.off('close', closed);
439
564
  closed();
440
565
  };
@@ -449,6 +574,7 @@ export class BrowserService {
449
574
 
450
575
  requireControl(ws, generation) {
451
576
  if (ws.finishing) fail('workspace_finishing');
577
+ if (ws.securityChallenge) fail('human_verification_required');
452
578
  if (ws.mode !== 'agent') fail('workspace_under_user_control');
453
579
  if (ws.generation !== generation) fail('stale_control');
454
580
  }
@@ -539,6 +665,7 @@ export class BrowserService {
539
665
  }
540
666
 
541
667
  async open(ws, url, job, popup) {
668
+ if (ws.singleTab) fail('single_tab_scope');
542
669
  const origin = webOrigin(url);
543
670
  if (!ws.origins.size && !ws.resourceOrigins.has(origin)) ws.origins.add(origin);
544
671
  if (!ws.origins.has(origin)) {
@@ -613,7 +740,10 @@ export class BrowserService {
613
740
  });
614
741
  if (job) job.pageId = tab.id;
615
742
  this.notify(ws);
616
- if (this.sharedContext) await this.groupTab?.(page, ws.id, ws.name, ws.mode, ws.agentName, tab.id);
743
+ if (this.sharedContext) await this.syncTab(ws, tab);
744
+ // Register the tab with the extension before attaching the fallback
745
+ // capture layer so its debugger state is established first.
746
+ if (ws.mode === 'agent') await this.setInputGuard?.(ws, tab, true);
617
747
  let firstRequest;
618
748
  if (popup) {
619
749
  // Recheck in the actual request handler as well as before goto. A handoff
@@ -649,6 +779,7 @@ export class BrowserService {
649
779
  const key = target + '\n' + credentialRef;
650
780
  if (ws.credentials.size >= 128 && !ws.credentials.has(key)) fail('credential_limit');
651
781
  ws.credentials.set(key, value);
782
+ for (const tab of ws.pages.values()) this.invalidateObservation(tab);
652
783
  for (const [pageId, request] of ws.credentialRequests) {
653
784
  if (request.origin === target && request.credentialRef === credentialRef)
654
785
  ws.credentialRequests.delete(pageId);
@@ -666,7 +797,7 @@ export class BrowserService {
666
797
  this.requireControl(ws, generation);
667
798
  if (documentId !== tab.documentId) fail('stale_observation');
668
799
  requirePageOrigin(ws, tab);
669
- return { workspaceId: ws.id, pageId: tab.id, documentId, controlGeneration: generation,
800
+ return { workspaceId: ws.id, pageId: tab.id, observationId: randomUUID(), documentId, controlGeneration: generation,
670
801
  text: redact(ws, text) };
671
802
  }
672
803
 
@@ -791,6 +922,13 @@ export class BrowserService {
791
922
  options.padding=Math.max(0,...Array.from(ws.credentials.values(),v=>v.length-1));
792
923
  requirePageOrigin(ws,tab);
793
924
  const documentId=tab.documentId,controlGeneration=ws.generation,frameRevision=tab.frameRevision;
925
+ const cacheable = !readOnly && !request.cursor && !request.name && !request.region && !request.locator &&
926
+ !request.includeFrames && !request.frameControls && request.limit === 180;
927
+ const revision = cacheable ? await this.observationRevision(tab) : null;
928
+ if (cacheable && revision !== null && tab.observationCache?.documentId === documentId &&
929
+ tab.observationCache.controlGeneration === controlGeneration && tab.observationCache.revision === revision) {
930
+ return { ...tab.observationCache.payload, observationId: randomUUID(), blockedRequests: blockedRequests(tab.page) };
931
+ }
794
932
  const check=()=>{
795
933
  this.requireControl(ws,controlGeneration);
796
934
  requirePageOrigin(ws,tab);
@@ -805,7 +943,7 @@ export class BrowserService {
805
943
  this.requireControl(ws, controlGeneration);
806
944
  requirePageOrigin(ws, tab);
807
945
  if (tab.documentId !== documentId || ws.pages.get(tab.id) !== tab || tab.page.isClosed()) fail('stale_observation');
808
- return { workspaceId: ws.id, pageId: tab.id, documentId, controlGeneration, text:observationText(ws,text,textWindowInfo),
946
+ return { workspaceId: ws.id, pageId: tab.id, observationId: randomUUID(), documentId, controlGeneration, text:observationText(ws,text,textWindowInfo),
809
947
  elements:details.map(({role,name,options,...state})=>({role,name:redact(ws,name),...state})),
810
948
  ...(foreground && {foreground:{...foreground,name:redact(ws,foreground.name)}}), ...observationMatch(ws,match), ...this.continuation(tab,ws,true,request,next,frameResult?.next),
811
949
  ...(frames && {frames}), blockedRequests: blockedRequests(tab.page) };
@@ -848,10 +986,13 @@ export class BrowserService {
848
986
  nodes = undefined;
849
987
  handles = undefined;
850
988
  void previousNodes?.dispose().catch(() => {});
851
- tab.lastObservation={documentId,controlGeneration,text:observationText(ws,text,textWindowInfo),elements};
852
- return {workspaceId:ws.id,pageId:tab.id,...tab.lastObservation,
989
+ tab.lastObservation={observationId: randomUUID(), documentId,controlGeneration,text:observationText(ws,text,textWindowInfo),elements};
990
+ const result = {workspaceId:ws.id,pageId:tab.id,...tab.lastObservation,
853
991
  ...(foreground && {foreground:{...foreground,name:redact(ws,foreground.name)}}), ...observationMatch(ws,match), ...this.continuation(tab,ws,false,request,next,frameResult?.next),
854
992
  ...(frames && { frames }), blockedRequests: blockedRequests(tab.page) };
993
+ if (cacheable && revision !== null)
994
+ tab.observationCache = { documentId, controlGeneration, revision, payload: result };
995
+ return result;
855
996
  } finally {
856
997
  if(!published && frameResult) for(const {handle} of frameResult.refs.values()) void handle.dispose().catch(()=>{});
857
998
  const release = [snapshot, nodes, freshNodes, ...(handles?.values() ?? [])].filter(Boolean);
@@ -859,6 +1000,20 @@ export class BrowserService {
859
1000
  }
860
1001
  }
861
1002
 
1003
+ async observeAndAct(ws, params) {
1004
+ const tab = this.tab(ws, params.pageId);
1005
+ const { workspaceId, pageId, operationId, actions, timeoutMs, observeAfter,
1006
+ documentId, controlGeneration, ...observeParams } = params;
1007
+ if (workspaceId !== ws.id || documentId !== undefined || controlGeneration !== undefined)
1008
+ fail('invalid_params');
1009
+ const observation = await this.enqueue(ws, () => this.observe(ws, tab, observeParams),
1010
+ { kind: 'observe', pageId: tab.id });
1011
+ const receipt = this.act(ws, { workspaceId: ws.id, pageId: tab.id, operationId,
1012
+ documentId: observation.documentId, controlGeneration: observation.controlGeneration,
1013
+ actions, timeoutMs, observeAfter });
1014
+ return { observation, receipt };
1015
+ }
1016
+
862
1017
  actionDigest(params) {
863
1018
  const {pageId,documentId,controlGeneration,actions,observeAfter,timeoutMs}=params;
864
1019
  if(params[workflowOrigin]) return createHash('sha256').update(JSON.stringify(
@@ -960,6 +1115,7 @@ export class BrowserService {
960
1115
  }
961
1116
 
962
1117
  async desktopNavigate(ws, { pageId, action, url }, newTab) {
1118
+ if (ws.singleTab && (newTab || (url && !ws.origins.has(webOrigin(url))))) fail('single_tab_scope');
963
1119
  const tab = newTab ? null : this.tab(ws, pageId);
964
1120
  if (newTab) action = 'go';
965
1121
  if (!['go', 'back', 'forward', 'reload'].includes(action) ||
@@ -0,0 +1,138 @@
1
+ import { ServiceError } from './workspace-state.mjs';
2
+
3
+ // The preferred guard is implemented inside Chromium. A stock Chromium build
4
+ // uses a page-level capture fallback, which blocks page input while allowing
5
+ // the service to open a short dispatch window for one Agent action. The
6
+ // fallback avoids keeping a CDP session attached after native support has been
7
+ // ruled out because the extension also uses chrome.debugger.
8
+ const fallbackSource = `(() => {
9
+ const key = '__openBrowserInputGuard';
10
+ const current = globalThis[key];
11
+ if (current) { current.enabled = true; return; }
12
+ const state = { enabled: true };
13
+ const block = event => {
14
+ if (!state.enabled) return;
15
+ event.preventDefault();
16
+ event.stopImmediatePropagation();
17
+ };
18
+ for (const type of ['click','dblclick','mousedown','mouseup','mousemove','mouseenter','mouseleave',
19
+ 'pointerdown','pointerup','pointermove','pointercancel','wheel','touchstart','touchmove','touchend',
20
+ 'contextmenu','keydown','keypress','keyup','beforeinput','input','change'])
21
+ document.addEventListener(type, block, true);
22
+ globalThis[key] = state;
23
+ })();`;
24
+
25
+ function fallbackExpression(enabled) {
26
+ return `globalThis.__openBrowserInputGuard && (globalThis.__openBrowserInputGuard.enabled = ${enabled ? 'true' : 'false'})`;
27
+ }
28
+
29
+ async function setFallbackState(page, enabled) {
30
+ await page.evaluate(fallbackExpression(enabled)).catch(() => {});
31
+ // Init scripts cannot be removed from a Playwright page. Append a small
32
+ // state update so a later navigation preserves the handoff decision.
33
+ await page.addInitScript({ content: fallbackExpression(enabled) }).catch(() => {});
34
+ }
35
+
36
+ export function managedInput(context, onBlocked, { allowFallback = false, forceFallback = false } = {}) {
37
+ const sessions = new WeakMap();
38
+ const disconnectedSessions = new WeakSet();
39
+
40
+ async function setGuard(tab, enabled, onLost) {
41
+ const { page } = tab;
42
+ let entry = sessions.get(page);
43
+ if (page.isClosed()) return;
44
+ if (!enabled) {
45
+ if (!entry) return;
46
+ if (entry.mode === 'fallback') {
47
+ await setFallbackState(page, false);
48
+ sessions.delete(page);
49
+ return;
50
+ }
51
+ try { await entry.session.send('Input.setOpenBrowserInputGuard', { enabled: false }); }
52
+ catch (error) {
53
+ if (!page.isClosed() && !disconnectedSessions.has(entry.session)) throw error;
54
+ }
55
+ sessions.delete(page);
56
+ try { await entry.session.detach(); }
57
+ catch (error) {
58
+ if (!page.isClosed() && !disconnectedSessions.has(entry.session)) {
59
+ sessions.set(page, entry);
60
+ throw error;
61
+ }
62
+ }
63
+ return;
64
+ }
65
+ if (entry) return;
66
+ if (forceFallback && allowFallback) {
67
+ try {
68
+ await page.addInitScript({ content: fallbackSource });
69
+ await page.evaluate(fallbackSource);
70
+ entry = { mode: 'fallback', depth: 0, transition: Promise.resolve() };
71
+ sessions.set(page, entry);
72
+ } catch (cause) {
73
+ if (!page.isClosed()) throw Object.assign(new ServiceError('input_guard_unavailable'), { cause });
74
+ }
75
+ return;
76
+ }
77
+ const session = await context.newCDPSession(page);
78
+ entry = { session, mode: 'native', depth: 0, transition: Promise.resolve() };
79
+ try {
80
+ session.once('close', () => {
81
+ disconnectedSessions.add(session);
82
+ if (sessions.get(page) !== entry) return;
83
+ sessions.delete(page);
84
+ if (!page.isClosed()) onLost?.();
85
+ });
86
+ session.on('Input.openBrowserInputBlocked', () => {
87
+ if (sessions.get(page) === entry) onBlocked(tab);
88
+ });
89
+ let timer;
90
+ try {
91
+ await Promise.race([
92
+ session.send('Input.setOpenBrowserInputGuard', { enabled: true }),
93
+ new Promise((_, reject) => {
94
+ timer = setTimeout(() => reject(Error('Input guard acknowledgement timed out')), 5000);
95
+ }),
96
+ ]);
97
+ } finally { clearTimeout(timer); }
98
+ if (disconnectedSessions.has(session)) throw Error('input guard session closed');
99
+ sessions.set(page, entry);
100
+ } catch (cause) {
101
+ const unsupported = /wasn.t found|not found|unknown command/i.test(String(cause?.message));
102
+ await session.detach().catch(() => {});
103
+ if (!allowFallback || !unsupported) {
104
+ if (!page.isClosed()) throw Object.assign(new ServiceError('input_guard_unavailable'), { cause });
105
+ return;
106
+ }
107
+ try {
108
+ await page.addInitScript({ content: fallbackSource });
109
+ await page.evaluate(fallbackSource);
110
+ entry = { mode: 'fallback', depth: 0, transition: Promise.resolve() };
111
+ sessions.set(page, entry);
112
+ } catch (fallbackCause) {
113
+ if (!page.isClosed()) throw Object.assign(new ServiceError('input_guard_unavailable'), { cause: fallbackCause });
114
+ }
115
+ }
116
+ }
117
+
118
+ setGuard.withAgentInput = async (tab, work) => {
119
+ const entry = sessions.get(tab.page);
120
+ if (!entry || entry.mode !== 'fallback') return work();
121
+ entry.depth++;
122
+ if (entry.depth === 1) {
123
+ entry.transition = entry.transition.then(() => setFallbackState(tab.page, false));
124
+ await entry.transition;
125
+ }
126
+ try { return await work(); }
127
+ finally {
128
+ entry.depth--;
129
+ if (entry.depth === 0) {
130
+ entry.transition = entry.transition.then(() => setFallbackState(tab.page, true));
131
+ await entry.transition.catch(() => {});
132
+ }
133
+ }
134
+ };
135
+
136
+ setGuard.mode = tab => sessions.get(tab.page)?.mode || null;
137
+ return setGuard;
138
+ }