@seekskyworld/open-browser 0.0.0-stage → 0.1.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 (109) hide show
  1. package/CONTRIBUTING.md +15 -0
  2. package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
  3. package/Docs/THIRD-PARTY-NOTICES.md +12 -0
  4. package/Docs/open-browser-api.d.ts +273 -0
  5. package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
  6. package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
  7. package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
  8. 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 +36 -0
  9. package/LICENSE +200 -0
  10. package/README.md +150 -2
  11. package/README.zh-CN.md +155 -0
  12. package/SECURITY.md +9 -0
  13. package/access-registry.mjs +151 -0
  14. package/action-execution.mjs +374 -0
  15. package/activity-notifier.mjs +34 -0
  16. package/api-contract.mjs +122 -0
  17. package/browser-extension/icons/open-browser-128.png +0 -0
  18. package/browser-extension/icons/open-browser-16.png +0 -0
  19. package/browser-extension/icons/open-browser-32.png +0 -0
  20. package/browser-extension/icons/open-browser-48.png +0 -0
  21. package/browser-extension/icons/open-browser-wordmark.png +0 -0
  22. package/browser-extension/manifest.json +38 -0
  23. package/browser-extension/newtab.css +20 -0
  24. package/browser-extension/newtab.html +19 -0
  25. package/browser-extension/newtab.js +123 -0
  26. package/browser-extension/phase-labels.js +9 -0
  27. package/browser-extension/popup.css +19 -0
  28. package/browser-extension/popup.html +46 -0
  29. package/browser-extension/popup.js +324 -0
  30. package/browser-extension/tab-action.js +137 -0
  31. package/browser-extension/worker.js +188 -0
  32. package/browser-extension/workspace-title.js +15 -0
  33. package/capability-matrix.mjs +21 -0
  34. package/chromium-host.mjs +149 -0
  35. package/chromium-shell.mjs +150 -0
  36. package/cli.mjs +83 -0
  37. package/contract-validation.mjs +27 -0
  38. package/control.mjs +107 -0
  39. package/desktop/Info.plist +13 -0
  40. package/desktop/Launcher.m +117 -0
  41. package/desktop/OBControlBar.h +7 -0
  42. package/desktop/OBControlBar.m +213 -0
  43. package/desktop/OBPageView.h +6 -0
  44. package/desktop/OBPageView.m +348 -0
  45. package/desktop/WorkspacePanel.h +16 -0
  46. package/desktop/WorkspacePanel.m +915 -0
  47. package/desktop/archive-release.py +129 -0
  48. package/desktop/brand-keychain.py +95 -0
  49. package/desktop/brand-locales.py +93 -0
  50. package/desktop/brand-macos-icons.py +24 -0
  51. package/desktop/brand-windows-icons.mjs +48 -0
  52. package/desktop/build-macos.mjs +96 -0
  53. package/desktop/build-portable.mjs +95 -0
  54. package/desktop/build.mjs +5 -0
  55. package/desktop/create-shortcut.ps1 +9 -0
  56. package/desktop/generate-icons.py +39 -0
  57. package/desktop/icons/open-browser.icns +0 -0
  58. package/desktop/icons/open-browser.ico +0 -0
  59. package/desktop/install-menu-entry.mjs +24 -0
  60. package/desktop/package-assets.mjs +34 -0
  61. package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
  62. package/desktop/portable-archive.py +22 -0
  63. package/desktop/sign.mjs +33 -0
  64. package/desktop/smoke-portable.mjs +65 -0
  65. package/desktop/start.mjs +12 -0
  66. package/desktop/verify-upgrade.mjs +74 -0
  67. package/desktop/verify-version.mjs +12 -0
  68. package/desktop-page.mjs +211 -0
  69. package/diagnostics.mjs +28 -0
  70. package/downloads.mjs +110 -0
  71. package/engine-service.mjs +1002 -0
  72. package/hosted/README.md +74 -0
  73. package/hosted/cli.mjs +17 -0
  74. package/hosted/directory.mjs +261 -0
  75. package/hosted/init.mjs +37 -0
  76. package/hosted/server.mjs +129 -0
  77. package/managed-popup.mjs +54 -0
  78. package/mcp.mjs +43 -0
  79. package/network-policy.mjs +107 -0
  80. package/output-store.mjs +96 -0
  81. package/package.json +57 -4
  82. package/page-activity.mjs +121 -0
  83. package/page-dialogs.mjs +53 -0
  84. package/page-observation.mjs +280 -0
  85. package/paths.mjs +20 -0
  86. package/privacy-config.mjs +95 -0
  87. package/receipt-store.mjs +191 -0
  88. package/runtime.mjs +44 -0
  89. package/scheduler.mjs +70 -0
  90. package/sdk.mjs +176 -0
  91. package/service.mjs +271 -0
  92. package/site-workflow.mjs +115 -0
  93. package/skills/open-browser/SKILL.md +86 -0
  94. package/skills/open-browser/scripts/bootstrap.mjs +134 -0
  95. package/skills/open-browser/scripts/open-browser +21 -0
  96. package/skills/open-browser/scripts/open-browser.cmd +9 -0
  97. package/skills/open-browser/workflows/login-export.json +10 -0
  98. package/skills/open-browser/workflows/upload-verify.json +8 -0
  99. package/studio/demo-site.mjs +111 -0
  100. package/studio/demo.css +1 -0
  101. package/studio/index.html +66 -0
  102. package/studio/index.mjs +57 -0
  103. package/studio/native-demo.mjs +124 -0
  104. package/studio/studio.css +119 -0
  105. package/studio/studio.js +438 -0
  106. package/uploads.mjs +63 -0
  107. package/visual-page.mjs +306 -0
  108. package/workspace-lifecycle.mjs +170 -0
  109. package/workspace-state.mjs +95 -0
@@ -0,0 +1,1002 @@
1
+ import { close as closeWorkspace, finish, finishDigest, handOff, returnToAgent } from './workspace-lifecycle.mjs';
2
+ import { perform } from './action-execution.mjs';
3
+ import { allowedPageOrigin, clearFrameRefs, clearRefs, fail, publicError, redact, requirePageOrigin, stringParam, webOrigin, workspaceView } from './workspace-state.mjs';
4
+ import {workflowRequest,workflowOrigin,performWorkflow} from './site-workflow.mjs';
5
+ import { agentMethods, capabilityProfiles, limits } from './api-contract.mjs';
6
+ import {UploadGrants} from './uploads.mjs';
7
+ import {attachDialogs, discardDialog, respondDialog} from './page-dialogs.mjs';
8
+ import { installPopupBridge } from './managed-popup.mjs';
9
+ import { VisualPages, visualActions, validateVisualAction } from './visual-page.mjs';
10
+ import { profileId as serviceProfileId } from './paths.mjs';
11
+ import { WorkspaceDownloads } from './downloads.mjs';
12
+ import { WorkspaceScheduler } from './scheduler.mjs';
13
+ import { inspectDocument, readDocumentSummary, frameAllowed, observeFrames } from './page-observation.mjs';
14
+ import { blockedRequests, rememberBlock, routeWorkspace } from './network-policy.mjs';
15
+ import { createHash, randomUUID } from 'node:crypto';
16
+ import { AsyncLocalStorage } from 'node:async_hooks';
17
+ import { ReceiptStore } from './receipt-store.mjs';
18
+ import { DesktopFrames, enqueueHuman, navigatePage, pageInput, pageLocation, refreshTitle, releaseInput } from './desktop-page.mjs';
19
+ import { privacyCapabilities } from './privacy-config.mjs';
20
+ import path from 'node:path';
21
+ import { stateDir } from './paths.mjs';
22
+ import { OutputStore } from './output-store.mjs';
23
+ import { ActivityNotifier } from './activity-notifier.mjs';
24
+
25
+ function observationMatch(ws, match) {
26
+ if (!match) return {};
27
+ return {match:{...match,candidates:match.candidates.map(({role,name,within})=>({
28
+ role,name:redact(ws,name),...(within && {within:{role:within.role,name:redact(ws,within.name)}})
29
+ }))}};
30
+ }
31
+
32
+ // The renderer receives only the overlap length. Locate complete secrets on
33
+ // the service side, then redact their intersection with the returned slice.
34
+ function observationText(ws,text,window) {
35
+ if(!window) return redact(ws,text);
36
+ const {padded,skip,length}=window;
37
+ const hidden=new Uint8Array(length);
38
+ for(const secret of ws.credentials.values()) {
39
+ let start=padded.indexOf(secret);
40
+ while(start>=0) {
41
+ const end=Math.min(length,start+secret.length-skip);
42
+ if(end>0 && start<skip+length) hidden.fill(1,Math.max(0,start-skip),end);
43
+ start=padded.indexOf(secret,start+1);
44
+ }
45
+ }
46
+ let clean='';
47
+ for(let i=0;i<length;i++) {
48
+ if(!hidden[i]) clean+=text[i];
49
+ else if(!i || !hidden[i-1]) clean+='[redacted]';
50
+ }
51
+ return clean;
52
+ }
53
+
54
+ const statusQueries = new Set(['getWorkspace', 'visualStatus', 'listDownloads', 'listOutputs', 'readOutput',
55
+ 'listUploads', 'getOperation', 'diagnoseOperation', 'listOperations', 'listEvents', 'eventCursor',
56
+ 'waitForEvent', 'getRecoverySummary']);
57
+
58
+ export class BrowserService {
59
+ 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 } = {}) {
61
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16) fail('invalid_concurrency');
62
+ if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs <= 0) fail('invalid_idle_timeout');
63
+ this.browser = browser;
64
+ this.sharedContext = sharedContext;
65
+ this.groupTab = groupTab;
66
+ this.releaseTab = releaseTab;
67
+ this.readOnlyObserver = readOnlyObserver;
68
+ this.actors = new AsyncLocalStorage();
69
+ this.store = new ReceiptStore(journalPath, () => this.actors.getStore());
70
+ this.outputs = new OutputStore(path.join(stateDir, 'open-browser-deliveries'));
71
+ this.onActivity = onActivity;
72
+ this.onActionTarget = onActionTarget;
73
+ this.frames = new DesktopFrames();
74
+ this.visual = new VisualPages();
75
+ this.workspaces = new Map();
76
+ this.slots = new WorkspaceScheduler(concurrency, { lowMemoryMiB });
77
+ this.pending = 0;
78
+ this.creatingContext = Promise.resolve();
79
+ this.protocol = null;
80
+ this.stopped = false;
81
+ this.idleTimeoutMs = idleTimeoutMs;
82
+ this.notifier = new ActivityNotifier(onActivity, workspaceId => this.workspaces.has(workspaceId));
83
+ this.sweep = setInterval(() => {
84
+ const cutoff = Date.now() - idleTimeoutMs;
85
+ for (const ws of this.workspaces.values()) {
86
+ if (ws.mode === 'agent' && !ws.pending && !ws.finishing && ws.lastActiveAt <= cutoff &&
87
+ !ws.credentialRequests.size && ![...ws.pages.values()].some(tab => tab.needsSubmissionReview))
88
+ void closeWorkspace(this, ws).catch(() => {});
89
+ }
90
+ }, Math.min(60_000, idleTimeoutMs)).unref();
91
+ }
92
+
93
+ notify(ws) {
94
+ this.notifier.notify(ws);
95
+ }
96
+
97
+ notifyTarget(ws, tab, el, documentId, controlGeneration, origin) {
98
+ if (!this.onActionTarget) return;
99
+ const ticket = Symbol();
100
+ tab.latestTarget = ticket;
101
+ // Coordinates are advisory. Capture geometry alongside the real action,
102
+ // without scrolling the page or delaying dispatch for a desktop effect.
103
+ const viewport = tab.page.viewportSize() ||
104
+ tab.page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
105
+ void Promise.all([el.boundingBox(), viewport]).then(([box, size]) => {
106
+ if (!box || tab.latestTarget !== ticket || ws.pages.get(tab.id) !== tab || tab.page.isClosed() ||
107
+ ws.mode !== 'agent' || ws.generation !== controlGeneration || tab.documentId !== documentId ||
108
+ allowedPageOrigin(ws, tab) !== origin) return;
109
+ const left = Math.max(0, box.x), right = Math.min(size.width, box.x + box.width);
110
+ const top = Math.max(0, box.y), bottom = Math.min(size.height, box.y + box.height);
111
+ 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 });
114
+ }).catch(() => {});
115
+ }
116
+
117
+ call(method, params = {}, clientId, actorId = clientId) {
118
+ return this.actors.run(actorId, () => this.execute(method, params, clientId));
119
+ }
120
+
121
+ async execute(method, params, clientId) {
122
+ if (this.stopped) fail('service_stopped');
123
+ if (typeof clientId !== 'string' || !clientId) fail('unauthorized');
124
+ 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 : []}};
126
+ if(method==='runWorkflow') {
127
+ params=workflowRequest(params);
128
+ method='act';
129
+ }
130
+ if (method === 'createWorkspace') return this.create(params, clientId);
131
+ if (method === 'open') return this.openWorkspace(params, clientId);
132
+ if (method === 'listWorkspaces')
133
+ return [...this.workspaces.values()].filter(ws => ws.owner === clientId).map(ws => workspaceView(ws));
134
+ if (method === 'eventCursor') return this.store.cursor(clientId,params.workspaceId);
135
+ if (method === 'waitForEvent') return this.store.waitForEvent(clientId,params);
136
+ if (method === 'listEvents') return this.store.events(clientId, params.workspaceId, params.after, params.limit);
137
+ if (method === 'getRecoverySummary') {
138
+ const live = this.workspaces.get(params.workspaceId);
139
+ const ws = live?.owner === clientId ? live : undefined;
140
+ const {operations, nextCursor} = this.store.list(clientId, params.workspaceId, params.after, params.limit);
141
+ const {records, nextObjectCursor} = this.store.recoveryObjects(clientId, params.workspaceId, params.objectsAfter, params.limit);
142
+ if (!ws && !records.length && !operations.length && !this.store.events(clientId,params.workspaceId,0,1).events.length)
143
+ 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'
146
+ }));
147
+ return {
148
+ workspaceId:params.workspaceId, mode:ws?.mode ?? 'unavailable', pages,
149
+ deliveries:records.filter(row => row.kind === 'download').map(row => ({downloadId:row.id})),
150
+ outputs:records.filter(row => row.kind === 'output').map(row => ({outputId:row.id})),
151
+ operations:operations.map(receipt => ({...receipt, next:
152
+ receipt.state === 'outcome_unknown' ? 'verify_site' :
153
+ ['running','queued'].includes(receipt.state) ? 'poll' :
154
+ receipt.state === 'completed' ? 'already_completed' : 'inspect_receipt'})),
155
+ nextCursor, nextObjectCursor
156
+ };
157
+ }
158
+ if (method === 'diagnoseOperation') return this.store.diagnose(clientId, params.workspaceId, params.operationId);
159
+ if (method === 'listOperations')
160
+ return this.store.list(clientId, params.workspaceId, params.after, params.limit);
161
+ const ws = this.workspaces.get(params.workspaceId);
162
+ if (!ws || ws.owner !== clientId) {
163
+ if (['listOutputs', 'readOutput'].includes(method)) {
164
+ const {records} = this.store.recoveryObjects(clientId, params.workspaceId, 0, 100);
165
+ const known = records.some(record => record.kind === 'output' &&
166
+ (method === 'listOutputs' || record.id === params.outputId));
167
+ if (known) {
168
+ return method === 'listOutputs' ? this.outputs.list(params.workspaceId) :
169
+ this.outputs.read(params.workspaceId, params.outputId, params);
170
+ }
171
+ }
172
+ const past = this.store.get(clientId, params.workspaceId, params.operationId);
173
+ if (past && method === 'getOperation') return past.receipt;
174
+ if (past && ['act','finishWorkspace','hostFinishWorkspace'].includes(method)) {
175
+ const digest = method === 'act' ? this.actionDigest(params) : finishDigest(params.keepPageIds);
176
+ if (past.digest !== digest) fail('operation_id_conflict');
177
+ return past.receipt;
178
+ }
179
+ fail('workspace_not_found');
180
+ }
181
+ if (ws.finishing && !['getOperation','getWorkspace','finishWorkspace','hostFinishWorkspace'].includes(method)) fail('workspace_finishing');
182
+ if (!statusQueries.has(method)) ws.lastActiveAt = Date.now();
183
+ switch (method) {
184
+ case 'getWorkspace': return workspaceView(ws, true);
185
+ case 'listUploads': return ws.uploads.list();
186
+ case 'grantUpload': {
187
+ if (this.actors.getStore() !== 'desktop') fail('forbidden');
188
+ return ws.uploads.grant(ws,this.tab(ws,params.pageId),params);
189
+ }
190
+ case 'revokeUpload':
191
+ if (this.actors.getStore() !== 'desktop') fail('forbidden');
192
+ ws.uploads.remove(params.fileId);
193
+ return {revoked:true};
194
+ case 'respondDialog': {
195
+ const result = await respondDialog(ws,this.tab(ws,params.pageId),params,this.actors.getStore()==='desktop');
196
+ this.notify(ws);
197
+ return result;
198
+ }
199
+ case 'listDownloads': return ws.downloads.list();
200
+ case 'listOutputs': return ws.downloads.listOutputs();
201
+ case 'readOutput': return ws.downloads.readOutput(params.outputId, params);
202
+ case 'cancelDownload':
203
+ if (this.actors.getStore() !== 'desktop') this.requireControl(ws, ws.generation);
204
+ return ws.downloads.cancel(params.downloadId);
205
+ case 'keepDownload':
206
+ if (this.actors.getStore() !== 'desktop') fail('forbidden');
207
+ {
208
+ const result = await ws.downloads.keep(params.downloadId);
209
+ this.store.remember(ws.owner, ws.id, 'download', params.downloadId);
210
+ this.store.remember(ws.owner, ws.id, 'output', result.output.id);
211
+ return result;
212
+ }
213
+ case 'visualStatus': return {lastCapture:ws.lastVisualCapture || null};
214
+ case 'grantOrigin': {
215
+ if (params.controlGeneration !== ws.generation || !['agent', 'human'].includes(ws.mode)) fail('stale_control');
216
+ const origin = webOrigin(params.origin);
217
+ if (origin !== params.origin || !['navigation', 'resource'].includes(params.scope)) fail('invalid_params');
218
+ const key = params.scope + '\n' + origin;
219
+ if (!ws.blockedOrigins.has(key)) fail('origin_not_requested');
220
+ const origins = params.scope === 'resource' ? ws.resourceOrigins : ws.origins;
221
+ if (origins.size >= 32 && !origins.has(origin)) fail('origin_limit');
222
+ origins.add(origin);
223
+ ws.blockedOrigins.delete(key);
224
+ this.notify(ws);
225
+ return { origin, scope: params.scope, granted: true };
226
+ }
227
+ case 'setPixelPermission': return this.visual.permission(ws,params);
228
+ case 'captureVisual': return this.enqueue(ws, async () => {
229
+ const frame=await this.visual.capture(ws,this.tab(ws,params.pageId),this.actors.getStore(),params,'agent');
230
+ this.store.event(ws.owner,ws.id,'visual_capture','completed',null,null,frame);
231
+ return frame;
232
+ }, {kind:'captureVisual',pageId:params.pageId});
233
+ case 'captureRemoteVisual': return this.visual.capture(ws,this.tab(ws,params.pageId),this.actors.getStore(),params,'human');
234
+ case 'remoteVisualInput': return enqueueHuman(ws,params.controlGeneration,() =>
235
+ this.visual.input(ws,this.tab(ws,params.pageId),this.actors.getStore(),params,'human'));
236
+ case 'pageFrame': {
237
+ const frame = await this.frames.capture(ws, this.tab(ws, params.pageId), params);
238
+ frame.title = redact(ws, frame.title);
239
+ return frame;
240
+ }
241
+ case 'pageInput': return pageInput(ws, this.tab(ws, params.pageId), params);
242
+ case 'pageLocation': return pageLocation(ws, this.tab(ws, params.pageId));
243
+ case 'pageNew': return this.desktopNavigate(ws, params, true);
244
+ case 'pageNavigate': return this.desktopNavigate(ws, params, false);
245
+ case 'closePage': {
246
+ const tab = this.tab(ws, params.pageId);
247
+ await tab.page.close();
248
+ return { workspaceId: ws.id, pageId: tab.id, closed: true };
249
+ }
250
+ case 'previewPage': return this.previewPage(ws, this.tab(ws, params.pageId));
251
+ case 'observeReadOnly': return this.enqueue(ws, () => this.observe(ws, this.tab(ws, params.pageId), params, true),
252
+ { kind:'observe', pageId:params.pageId });
253
+ case 'showPage':
254
+ if (ws.mode !== 'human') fail('not_in_human_control');
255
+ await this.tab(ws, params.pageId).page.bringToFront();
256
+ return { workspaceId: ws.id, pageId: params.pageId };
257
+ case 'openPage': return this.enqueue(ws, job => this.open(ws, params.url, job), { kind: 'openPage' });
258
+ case 'observe': return this.enqueue(ws, () => this.observe(ws, this.tab(ws, params.pageId), params),
259
+ { kind: 'observe', pageId: params.pageId });
260
+ case 'act': return this.act(ws, params);
261
+ case 'setCredential': return this.setCredential(ws, params);
262
+ case 'resolveCredential': {
263
+ const request = ws.credentialRequests.get(params.pageId);
264
+ if (!request || ws.mode !== 'agent' || ws.generation !== params.controlGeneration ||
265
+ this.tab(ws, params.pageId).documentId !== params.documentId ||
266
+ !['documentId','controlGeneration','operationId','origin','credentialRef'].every(k => request[k] === params[k]) ||
267
+ !allowedPageOrigin(ws,this.tab(ws,params.pageId))) fail('stale_credential_request');
268
+ if(request.frameId) {
269
+ const tab=this.tab(ws,params.pageId);
270
+ const frame=tab.page.frames().find(frame=>tab.frameDocuments.get(frame)?.frameId===request.frameId);
271
+ if(!frame || URL.parse(frame.url())?.origin!==params.origin || !await frameAllowed(frame,ws.origins)) fail('stale_credential_request');
272
+ } else if(allowedPageOrigin(ws,this.tab(ws,params.pageId))!==params.origin) fail('stale_credential_request');
273
+ return this.setCredential(ws, params);
274
+ }
275
+ case 'finishWorkspace': return finish(this, ws, params);
276
+ case 'hostFinishWorkspace': return finish(this, ws, params, true);
277
+ case 'getOperation':
278
+ case 'cancelOperation': {
279
+ const op = ws.operations.get(params.operationId);
280
+ if (!op) {
281
+ const saved = this.store.get(clientId, ws.id, params.operationId);
282
+ if (saved && method === 'getOperation') return saved.receipt;
283
+ fail('operation_not_found');
284
+ }
285
+ if (method === 'cancelOperation') {
286
+ const tab = ws.pages.get(op.pageId);
287
+ if (ws.mode === 'agent' && tab?.dialog?.info.operationId === op.receipt.operationId) discardDialog(tab);
288
+ op.cancel = true;
289
+ op.controller?.abort();
290
+ if (op.receipt.state === 'queued') op.receipt.state = 'cancelled';
291
+ this.notify(ws);
292
+ }
293
+ return this.receiptView(ws, op);
294
+ }
295
+ case 'handOff':
296
+ case 'takeControl': return this.handOff(ws, params.pageId, true, params.controlGeneration);
297
+ case 'returnToAgent': return this.returnToAgent(ws, params.controlGeneration);
298
+ case 'closeWorkspace':
299
+ if (ws.mode !== 'agent') fail('workspace_under_user_control');
300
+ await closeWorkspace(this, ws);
301
+ return { workspaceId: ws.id, closed: true };
302
+ default: fail('unknown_method');
303
+ }
304
+ }
305
+
306
+ async create({ profileId, name = '', agentName = 'Agent', allowedOrigins = [], resourceOrigins = [], networkMode = 'strict' }, owner) {
307
+ if (profileId !== undefined && profileId !== serviceProfileId) fail('profile_mismatch');
308
+ if (typeof name !== 'string' || !name.trim()) fail('task_name_required');
309
+ if (name.length > 120 || !Array.isArray(allowedOrigins)
310
+ || allowedOrigins.length > 32) fail('invalid_params');
311
+ if (typeof agentName !== 'string' || [...agentName].length > 80) fail('invalid_params');
312
+ if (!['strict','browser'].includes(networkMode)) fail('invalid_params');
313
+ const displayName = agentName.replace(/[\p{Cc}\p{Bidi_Control}\u2028\u2029]+/gu, ' ').trim() || 'Agent';
314
+ const origins = new Set(allowedOrigins.map(webOrigin));
315
+ if (!Array.isArray(resourceOrigins) || resourceOrigins.length > 32) fail('invalid_params');
316
+ const resources = new Set(resourceOrigins.map(webOrigin));
317
+ if (this.workspaces.size >= 64) fail('workspace_limit');
318
+ this.protocol ??= this.browser.newBrowserCDPSession();
319
+ const { context, browserContextId } = this.sharedContext
320
+ ? { context: this.sharedContext } : await this.allocateContext();
321
+ try {
322
+ 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(),
324
+ tail: Promise.resolve(), lanes: new Map(), pending: 0, handoff: null, lastActiveAt: Date.now(),
325
+ inputTail: Promise.resolve(), inputPending: 0,
326
+ popupTasks: new Set(), jobs: new Set(), recent: null, credentialRequests: new Map() };
327
+ ws.uploads = new UploadGrants();
328
+ ws.downloads = new WorkspaceDownloads(ws, this.outputs);
329
+ if (!this.sharedContext) {
330
+ context.setDefaultTimeout(5000);
331
+ ws.networkRelease = await this.routeWorkspace(context, ws);
332
+ ws.onPage = page => this.register(ws, page);
333
+ context.on('page', ws.onPage);
334
+ }
335
+ if (this.stopped || this.workspaces.size >= 64) fail('workspace_unavailable');
336
+ this.workspaces.set(ws.id, ws);
337
+ this.store.event(owner, ws.id, 'control', 'agent');
338
+ this.notify(ws);
339
+ return workspaceView(ws);
340
+ } catch (error) {
341
+ if (!this.sharedContext) await context.close().catch(() => {});
342
+ throw error;
343
+ }
344
+ }
345
+
346
+ async openWorkspace({ url, allowedOrigins = [], ...params }, owner) {
347
+ const targetOrigin = webOrigin(url);
348
+ if (!Array.isArray(allowedOrigins) || allowedOrigins.length > 32) fail('invalid_params');
349
+ const origins = [...new Set([targetOrigin, ...allowedOrigins])];
350
+ const created = await this.create({ ...params, allowedOrigins: origins, networkMode: 'browser' }, owner);
351
+ const ws = this.workspaces.get(created.workspaceId);
352
+ if (!ws) fail('workspace_unavailable');
353
+ try {
354
+ return await this.open(ws, url);
355
+ } catch (error) {
356
+ await closeWorkspace(this, ws).catch(() => {});
357
+ throw error;
358
+ }
359
+ }
360
+
361
+ async allocateContext() {
362
+ // Playwright does not expose the Chromium context ID. Serialize only
363
+ // context allocation; never guess if another component creates one too.
364
+ const protocol = await this.protocol;
365
+ const allocation = this.creatingContext.then(async () => {
366
+ const before = new Set((await protocol.send('Target.getBrowserContexts')).browserContextIds);
367
+ const context = await this.browser.newContext({ acceptDownloads: true, serviceWorkers: 'block' });
368
+ try {
369
+ const { browserContextIds } = await protocol.send('Target.getBrowserContexts');
370
+ const added = browserContextIds.filter(id => !before.has(id));
371
+ if (added.length !== 1) fail('workspace_context_ambiguous');
372
+ return { context, browserContextId: added[0] };
373
+ } catch (error) {
374
+ await context.close().catch(() => {});
375
+ throw error;
376
+ }
377
+ });
378
+ this.creatingContext = allocation.then(() => {}, () => {});
379
+ return allocation;
380
+ }
381
+
382
+ routeWorkspace(target, ws) { return routeWorkspace(target, ws, !!this.sharedContext); }
383
+
384
+ register(ws, page) {
385
+ const existing = [...ws.pages.values()].find(tab => tab.page === page);
386
+ if (existing) return existing;
387
+ 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
+ heldKeys: new Set(), heldButtons: new Set() };
389
+ this.store.remember(ws.owner, ws.id, 'page', tab.id);
390
+ ws.pages.set(tab.id, tab);
391
+ const releaseDialogs = attachDialogs(ws,tab,()=>{
392
+ const info=tab.dialog.info;
393
+ this.store.event(ws.owner,ws.id,'dialog','opened',info.operationId,null,{pageId:tab.id,resourceId:info.dialogId});
394
+ this.notify(ws);
395
+ });
396
+ const navigated = frame => {
397
+ if (frame !== page.mainFrame()) {
398
+ tab.frameRevision++;
399
+ tab.frameDocuments.delete(frame);
400
+ clearFrameRefs(tab);
401
+ if(ws.credentialRequests.get(tab.id)?.frameId) ws.credentialRequests.delete(tab.id);
402
+ return;
403
+ }
404
+ ws.credentialRequests.delete(tab.id);
405
+ tab.title = '';
406
+ tab.documentId = randomUUID();
407
+ clearRefs(tab);
408
+ this.notify(ws);
409
+ if (tab.heldKeys.size || tab.heldButtons.size)
410
+ ws.inputTail = ws.inputTail.then(() => releaseInput(tab));
411
+ void refreshTitle(ws, tab);
412
+ };
413
+ const loaded = () => { void refreshTitle(ws, tab); };
414
+ const closed = () => {
415
+ releaseDialogs();
416
+ void tab.summarySession?.detach().catch(() => {});
417
+ clearRefs(tab);
418
+ ws.pages.delete(tab.id);
419
+ ws.credentialRequests.delete(tab.id);
420
+ this.notify(ws);
421
+ };
422
+ const downloaded = artifact => {
423
+ const resourceId=ws.downloads.receive(tab.id,artifact);
424
+ if (!resourceId) return;
425
+ const op=[...ws.jobs].find(job=>job.pageId===tab.id && job.dispatched);
426
+ this.store.event(ws.owner,ws.id,'download','receiving',op?.receipt.operationId,null,{pageId:tab.id,resourceId});
427
+ };
428
+ page.on('download', downloaded);
429
+ page.on('framenavigated', navigated);
430
+ page.on('framedetached', navigated);
431
+ page.on('domcontentloaded', loaded);
432
+ page.on('close', closed);
433
+ tab.unregister = () => {
434
+ page.off('download', downloaded);
435
+ page.off('framenavigated', navigated);
436
+ page.off('framedetached', navigated);
437
+ page.off('domcontentloaded', loaded);
438
+ page.off('close', closed);
439
+ closed();
440
+ };
441
+ return tab;
442
+ }
443
+
444
+ tab(ws, id) {
445
+ const tab = ws.pages.get(id);
446
+ if (!tab || tab.page.isClosed()) fail('page_not_found');
447
+ return tab;
448
+ }
449
+
450
+ requireControl(ws, generation) {
451
+ if (ws.finishing) fail('workspace_finishing');
452
+ if (ws.mode !== 'agent') fail('workspace_under_user_control');
453
+ if (ws.generation !== generation) fail('stale_control');
454
+ }
455
+
456
+ enqueue(ws, work, job) {
457
+ this.requireControl(ws, ws.generation);
458
+ if (ws.pending >= 128 || this.pending >= 512) fail('queue_full');
459
+ const generation = ws.generation;
460
+ if (job) {
461
+ job.receipt ??= { state: 'queued', completedSteps: 0 };
462
+ job.totalSteps ??= 1;
463
+ job.receipt.totalSteps ??= job.totalSteps;
464
+ job.receipt.phase ??= 'queued';
465
+ job.receipt.stepKind ??= job.stepKind;
466
+ ws.jobs.add(job);
467
+ }
468
+ const enqueuedAt = performance.now();
469
+ this.pending++;
470
+ ws.pending++;
471
+ this.notify(ws);
472
+ const signal = ws.control.signal;
473
+ // Only operations targeting the same page depend on each other. Ownership
474
+ // changes still drain the aggregate of all lanes before enabling input.
475
+ const lane = job?.pageId || (job?.kind === 'openPage' ? Symbol() : 'workspace');
476
+ const previous = ws.lanes.get(lane) || Promise.resolve();
477
+ const result = previous.then(() => this.slots.run(ws.id, async () => {
478
+ this.requireControl(ws, generation);
479
+ if (job?.deadline !== undefined && Date.now() >= job.deadline) fail('run_timeout');
480
+ if (job?.receipt.state === 'queued') {
481
+ job.receipt.state = 'running';
482
+ job.receipt.phase = 'running';
483
+ if (job.digest) this.store.save(ws.owner, ws.id, job.digest, job.receipt);
484
+ }
485
+ this.notify(ws);
486
+ const value = await work(job);
487
+ if (job?.deadline !== undefined && Date.now() >= job.deadline) fail('run_timeout');
488
+ this.requireControl(ws, generation);
489
+ if (job?.receipt.state === 'running') {
490
+ job.receipt.state = 'completed';
491
+ job.receipt.phase = 'completed';
492
+ job.receipt.completedSteps = job.totalSteps;
493
+ }
494
+ return value;
495
+ }, signal, enqueuedAt)).catch(error => {
496
+ if (job && ['queued','running'].includes(job.receipt.state)) {
497
+ job.receipt.state = job.dispatched ? 'outcome_unknown' : job.cancel ? 'cancelled' : 'failed';
498
+ job.receipt.phase = job.receipt.state;
499
+ job.receipt.error = publicError(error);
500
+ }
501
+ throw error;
502
+ }).finally(() => {
503
+ this.pending--;
504
+ ws.pending--;
505
+ ws.lastActiveAt = Date.now();
506
+ if (job) {
507
+ if (job.receipt.state === 'cancelled' && job.controlTransferred)
508
+ job.receipt.error = 'workspace_under_user_control';
509
+ ws.jobs.delete(job);
510
+ ws.recent = job;
511
+ if (job.digest) this.store.save(ws.owner, ws.id, job.digest, job.receipt);
512
+ if (ws.operations.size > 128) {
513
+ for (const [id, entry] of ws.operations) {
514
+ if (!ws.jobs.has(entry)) ws.operations.delete(id);
515
+ if (ws.operations.size <= 128) break;
516
+ }
517
+ }
518
+ }
519
+ this.notify(ws);
520
+ });
521
+ const settled = result.catch(() => {});
522
+ ws.lanes.set(lane, settled);
523
+ ws.tail = Promise.all(ws.lanes.values()).then(() => {});
524
+ void settled.then(() => { if (ws.lanes.get(lane) === settled) ws.lanes.delete(lane); });
525
+ return result;
526
+ }
527
+
528
+ async openPopup(ws, opener, lease, url) {
529
+ const check = () => {
530
+ this.requireControl(ws,lease.generation);
531
+ if (lease.op.cancel || ws.pages.get(opener.id)!==opener || opener.documentId!==lease.documentId ||
532
+ allowedPageOrigin(ws,opener)!==lease.origin) fail('stale_document');
533
+ };
534
+ check();
535
+ const child=await this.open(ws,url,undefined,{opener,lease,check});
536
+ (lease.op.receipt.openedPageIds ??= []).push(child.pageId);
537
+ this.store.event(ws.owner,ws.id,'popup','opened',lease.op.receipt.operationId,null,{pageId:opener.id,resourceId:child.pageId});
538
+ return child;
539
+ }
540
+
541
+ async open(ws, url, job, popup) {
542
+ const origin = webOrigin(url);
543
+ if (!ws.origins.size && !ws.resourceOrigins.has(origin)) ws.origins.add(origin);
544
+ if (!ws.origins.has(origin)) {
545
+ rememberBlock(ws, origin, 'navigation', 'document', 'origin_denied');
546
+ fail('origin_denied');
547
+ }
548
+ // Chromium can activate the first window in a new context even if
549
+ // Playwright sends only page-local input later. Request background at
550
+ // creation; the marker selects our exact target among concurrent popups.
551
+ const marker = 'about:blank#open-browser-' + randomUUID();
552
+ const protocol = await this.protocol;
553
+ let targetId;
554
+ let page;
555
+ try {
556
+ [page] = await Promise.all([
557
+ ws.context.waitForEvent('page', { predicate: candidate => candidate.url() === marker, timeout: 5000 }),
558
+ protocol.send('Target.createTarget', {
559
+ url: marker, browserContextId: ws.browserContextId, background: true, focus: false,
560
+ }).then(target => { targetId = target.targetId; }),
561
+ ]);
562
+ } catch {
563
+ if (targetId) await protocol.send('Target.closeTarget', { targetId }).catch(() => {});
564
+ fail('background_page_unavailable');
565
+ }
566
+ try {
567
+ let networkRelease, networkSession;
568
+ if (this.sharedContext) {
569
+ if (ws.mode === 'closed') fail('workspace_closed');
570
+ page.setDefaultTimeout(5000);
571
+ const session = await ws.context.newCDPSession(page);
572
+ const { targetInfo } = await session.send('Target.getTargetInfo');
573
+ if (targetInfo.targetId !== targetId) {
574
+ await session.detach().catch(() => {});
575
+ fail('background_page_unavailable');
576
+ }
577
+ // An already-installed worker may serve an ordinary profile tab. This
578
+ // override applies only to the workspace target and its navigation.
579
+ await session.send('Network.setBypassServiceWorker', { bypass: true });
580
+ networkSession = session;
581
+ networkRelease = await this.routeWorkspace(page, ws);
582
+ }
583
+ if (ws.mode === 'closed') fail('workspace_closed');
584
+ const tab = this.register(ws, page);
585
+ tab.targetId = targetId;
586
+ tab.createdByAgent = true;
587
+ if (popup) {
588
+ popup.check();
589
+ tab.openerPageId=popup.opener.id;
590
+ tab.openedByOperationId=popup.lease.op.receipt.operationId;
591
+ }
592
+ tab.networkRelease = networkRelease;
593
+ tab.networkSession = networkSession;
594
+ tab.releasePopups=await installPopupBridge(page, (token,href) => {
595
+ const lease=tab.popupLease;
596
+ if (!lease || token!==lease.token || Date.now()>lease.armDeadline) return;
597
+ if (!href) {
598
+ lease.until ??= Date.now()+2000;
599
+ return;
600
+ }
601
+ if (!lease.until || Date.now()>lease.until) return;
602
+ tab.popupLease=undefined;
603
+ const task=this.openPopup(ws,tab,lease,href);
604
+ // Drain already-started opens before local takeover or finishing releases pages.
605
+ ws.popupTasks.add(task);
606
+ task.then(()=>ws.popupTasks.delete(task),()=>ws.popupTasks.delete(task));
607
+ lease.opening=task.catch(error=>{
608
+ // A denied popup has a recorded origin; the originating click was still dispatched.
609
+ if (error.code==='origin_denied') return;
610
+ throw error;
611
+ });
612
+ return lease.opening.then(()=>{},()=>{});
613
+ });
614
+ if (job) job.pageId = tab.id;
615
+ this.notify(ws);
616
+ if (this.sharedContext) await this.groupTab?.(page, ws.id, ws.name, ws.mode, ws.agentName, tab.id);
617
+ let firstRequest;
618
+ if (popup) {
619
+ // Recheck in the actual request handler as well as before goto. A handoff
620
+ // may arrive after Chromium schedules navigation but before routing.
621
+ popup.check();
622
+ firstRequest=async route=>{
623
+ try { popup.check(); } catch { return route.abort('blockedbyclient'); }
624
+ return route.fallback();
625
+ };
626
+ await page.route('**/*',firstRequest);
627
+ }
628
+ try {
629
+ popup?.check();
630
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 15000 });
631
+ popup?.check();
632
+ } finally {
633
+ if (firstRequest) await page.unroute('**/*',firstRequest).catch(()=>{});
634
+ }
635
+ await refreshTitle(ws, tab);
636
+ return { workspaceId: ws.id, pageId: tab.id };
637
+ } catch (error) {
638
+ await protocol.send('Target.closeTarget', { targetId }).catch(() => {});
639
+ if (error.code) throw error;
640
+ fail('navigation_failed');
641
+ }
642
+ }
643
+
644
+ setCredential(ws, { origin, credentialRef, value }) {
645
+ const target = webOrigin(origin);
646
+ if ((ws.origins.size || ws.resourceOrigins.has(target)) && !ws.origins.has(target)) fail('origin_denied');
647
+ stringParam(credentialRef, 160);
648
+ stringParam(value, 8192);
649
+ const key = target + '\n' + credentialRef;
650
+ if (ws.credentials.size >= 128 && !ws.credentials.has(key)) fail('credential_limit');
651
+ ws.credentials.set(key, value);
652
+ for (const [pageId, request] of ws.credentialRequests) {
653
+ if (request.origin === target && request.credentialRef === credentialRef)
654
+ ws.credentialRequests.delete(pageId);
655
+ }
656
+ this.notify(ws);
657
+ return { credentialRef, saved: true };
658
+ }
659
+
660
+ async previewPage(ws, tab) {
661
+ const { documentId } = tab;
662
+ const generation = ws.generation;
663
+ this.requireControl(ws, generation);
664
+ requirePageOrigin(ws, tab);
665
+ const text = await tab.page.evaluate(inspectDocument, true);
666
+ this.requireControl(ws, generation);
667
+ if (documentId !== tab.documentId) fail('stale_observation');
668
+ requirePageOrigin(ws, tab);
669
+ return { workspaceId: ws.id, pageId: tab.id, documentId, controlGeneration: generation,
670
+ text: redact(ws, text) };
671
+ }
672
+
673
+ async observeFrameControls(ws,tab,options,offsets,readOnly,check) {
674
+ const refs=new Map(), next=new Map(), frames=[];
675
+ let remaining=options.limit,remainingText=8000;
676
+ try {
677
+ for(const frame of tab.page.frames().filter(frame=>frame.parentFrame())) {
678
+ if(offsets && !offsets.has(frame)) continue;
679
+ if(!await frameAllowed(frame,ws.origins)) continue;
680
+ if(frames.length>=16 || (!remaining && !remainingText)) {next.set(frame,offsets?.get(frame) ?? {});continue;}
681
+ let document=tab.frameDocuments.get(frame);
682
+ if(!document) {
683
+ const frameId=tab.frameIds.get(frame) ?? randomUUID();
684
+ tab.frameIds.set(frame,frameId);
685
+ document={frameId,documentId:randomUUID(),origin:webOrigin(frame.url())};
686
+ tab.frameDocuments.set(frame,document);
687
+ }
688
+ const settings={name:options.name,region:options.region,padding:options.padding,limit:remaining,textLimit:remainingText,
689
+ ...offsets?.get(frame),origins:[...ws.origins]};
690
+ let snapshot,nodes,handles;
691
+ try {
692
+ snapshot=await frame.evaluateHandle(inspectDocument,settings);
693
+ const summary=await snapshot.evaluate(result=>result?.summary);
694
+ if(!summary || summary.origin!==document.origin || !ws.origins.has(summary.origin)) continue;
695
+ if(!readOnly) {
696
+ nodes=await snapshot.getProperty('nodes');
697
+ handles=await nodes.getProperties();
698
+ }
699
+ if(!await frameAllowed(frame,ws.origins) || tab.frameDocuments.get(frame)!==document) fail('stale_observation');
700
+ const elements=summary.details.map(({role,name,options,...state},i)=>{
701
+ const info={role,name:redact(ws,name),...state};
702
+ if(readOnly) return info;
703
+ const handle=handles.get(String(i))?.asElement();
704
+ if(!handle) fail('stale_observation');
705
+ const ref=randomUUID();
706
+ refs.set(ref,{frame,document,handle,actor:this.actors.getStore()});
707
+ handles.delete(String(i));
708
+ const choices=options?.map(({label,value})=>({label:redact(ws,label),value:redact(ws,value)}));
709
+ return {...info,ref,...(choices && {options:choices})};
710
+ });
711
+ frames.push({...document,text:observationText(ws,summary.text,summary.textWindowInfo),elements});
712
+ remaining-=elements.length;remainingText-=summary.text.length;
713
+ if(summary.next) next.set(frame,summary.next);
714
+ } finally {
715
+ await Promise.all([snapshot,nodes,...(handles?.values() ?? [])].filter(Boolean).map(h=>h.dispose().catch(()=>{})));
716
+ }
717
+ check();
718
+ }
719
+ return {refs,next,frames};
720
+ } catch(error) {
721
+ for(const {handle} of refs.values()) await handle.dispose().catch(()=>{});
722
+ throw error;
723
+ }
724
+ }
725
+
726
+ async checkFrameRef(ws,tab,ref,entry) {
727
+ if(!entry) return;
728
+ if(tab.frameRefs.get(ref)!==entry || tab.frameDocuments.get(entry.frame)!==entry.document ||
729
+ entry.actor!==this.actors.getStore() || !ws.origins.has(entry.document.origin) ||
730
+ URL.parse(entry.frame.url())?.origin!==entry.document.origin || !await frameAllowed(entry.frame,ws.origins))
731
+ fail('stale_ref');
732
+ }
733
+
734
+ async checkSemanticTarget(ws,tab,ref,entry,handle,kind) {
735
+ await this.checkFrameRef(ws,tab,ref,entry);
736
+ if(await handle.ownerFrame()!==(entry?.frame ?? tab.page.mainFrame())) fail('stale_ref');
737
+ const targetFrame=entry?.frame ?? tab.page.mainFrame();
738
+ if(!await targetFrame.evaluate(inspectDocument,{foregroundTarget:handle})) fail('target_obscured');
739
+ if(tab.strictLocator && !entry &&
740
+ !await targetFrame.evaluate(inspectDocument,{locator:tab.strictLocator,expectedNode:handle,origins:[...ws.origins]}))
741
+ fail('stale_ref');
742
+ const error=await handle.evaluate((node,kind)=>{
743
+ if(!node.isConnected) return 'stale_ref';
744
+ for(let el=node;el;el=el.assignedSlot || el.parentElement || el.getRootNode().host) {
745
+ if(el.matches('[inert],[aria-hidden="true" i],[data-open-browser-private]')) return 'stale_ref';
746
+ }
747
+ if(kind==='setChecked' && !(node.control ?? node).matches('input[type="checkbox"],input[type="radio"],[role="checkbox"],[role="switch"],[role="radio"]')) return 'invalid_actions';
748
+ if(node.localName==='label' && !['click','setChecked'].includes(kind)) return 'invalid_actions';
749
+ if(kind==='fill' && node.matches('input[type="password"]')) return 'credential_ref_required';
750
+ },kind);
751
+ if(error) fail(error);
752
+ }
753
+
754
+ observationRequest(tab,ws,params,readOnly) {
755
+ const actor=this.actors.getStore();
756
+ if(params.cursor!==undefined) {
757
+ if(typeof params.cursor!=='string' || Object.keys(params).some(k=>!['workspaceId','pageId','cursor'].includes(k))) fail('invalid_params');
758
+ const entry=tab.cursors.get(params.cursor);
759
+ if(!entry || entry.actor!==actor || entry.readOnly!==readOnly || entry.expires<Date.now() ||
760
+ entry.generation!==ws.generation || entry.documentId!==tab.documentId ||
761
+ (entry.request.frameControls && entry.frameRevision!==tab.frameRevision)) fail('stale_cursor');
762
+ return entry.request;
763
+ }
764
+ const {name,region,locator,limit=180,frameControls=false,includeFrames=false}=params;
765
+ if(locator !== undefined) {
766
+ const valid = obj => obj && typeof obj.role==='string' && obj.role.trim() && obj.role.length<=80 &&
767
+ typeof obj.name==='string' && obj.name.trim() && obj.name.length<=160;
768
+ if(!valid(locator) || (locator.within!==undefined && !valid(locator.within)) ||
769
+ name!==undefined || region!==undefined || includeFrames || frameControls) fail('invalid_params');
770
+ }
771
+ if(!Number.isInteger(limit) || limit<1 || limit>180 || typeof frameControls!=='boolean' || typeof includeFrames!=='boolean' ||
772
+ (name!==undefined && (typeof name!=='string' || !name.trim() || name.length>160)) ||
773
+ (region!==undefined && (!region || !['x','y','width','height'].every(k=>Number.isSafeInteger(region[k])) ||
774
+ region.x<0 || region.y<0 || region.width<=0 || region.height<=0))) fail('invalid_params');
775
+ return {name,region,locator,limit,frameControls,includeFrames};
776
+ }
777
+
778
+ continuation(tab,ws,readOnly,request,mainNext,frameNext) {
779
+ if(!mainNext && !frameNext?.size) return {truncated:false};
780
+ const nextCursor=randomUUID();
781
+ for(const [key,entry] of tab.cursors) if(entry.expires<Date.now()) tab.cursors.delete(key);
782
+ if(tab.cursors.size>=64) tab.cursors.delete(tab.cursors.keys().next().value);
783
+ tab.cursors.set(nextCursor,{actor:this.actors.getStore(),readOnly,generation:ws.generation,documentId:tab.documentId,
784
+ frameRevision:tab.frameRevision,expires:Date.now()+60_000,request:{...request,...(mainNext ?? {elementOffset:null,textOffset:null}),frameOffsets:frameNext}});
785
+ return {truncated:true,nextCursor};
786
+ }
787
+
788
+ async observe(ws, tab, params = {}, readOnly = false) {
789
+ const request=this.observationRequest(tab,ws,params,readOnly);
790
+ const {includeFrames,frameControls,frameOffsets,...options}=request;
791
+ options.padding=Math.max(0,...Array.from(ws.credentials.values(),v=>v.length-1));
792
+ requirePageOrigin(ws,tab);
793
+ const documentId=tab.documentId,controlGeneration=ws.generation,frameRevision=tab.frameRevision;
794
+ const check=()=>{
795
+ this.requireControl(ws,controlGeneration);
796
+ requirePageOrigin(ws,tab);
797
+ if(tab.documentId!==documentId || ws.pages.get(tab.id)!==tab || tab.page.isClosed() ||
798
+ (frameControls && tab.frameRevision!==frameRevision)) fail('stale_observation');
799
+ };
800
+ const frameResult=frameControls ? await this.observeFrameControls(ws,tab,options,frameOffsets,readOnly,check) : null;
801
+ const frames=frameResult?.frames ?? (includeFrames ? await observeFrames(tab.page,ws.origins,(value,window)=>observationText(ws,value,window),options.padding) : undefined);
802
+ if (readOnly) {
803
+ const {text,details,match,foreground,next,textWindowInfo}=await this.readOnlyObserver(tab,[...ws.origins],options);
804
+ check();
805
+ this.requireControl(ws, controlGeneration);
806
+ requirePageOrigin(ws, tab);
807
+ 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),
809
+ elements:details.map(({role,name,options,...state})=>({role,name:redact(ws,name),...state})),
810
+ ...(foreground && {foreground:{...foreground,name:redact(ws,foreground.name)}}), ...observationMatch(ws,match), ...this.continuation(tab,ws,true,request,next,frameResult?.next),
811
+ ...(frames && {frames}), blockedRequests: blockedRequests(tab.page) };
812
+ }
813
+ let published=false;
814
+ const priorRefs = [...tab.refs.keys()];
815
+ const previousNodes = tab.observedNodes;
816
+ let snapshot,nodes,freshNodes,handles;
817
+ try {
818
+ snapshot=await tab.page.evaluateHandle(inspectDocument,{...options,previousNodes});
819
+ const {text,details,match,foreground,previousIndices,next,textWindowInfo}=await snapshot.evaluate(result=>result.summary);
820
+ nodes = await snapshot.getProperty('nodes');
821
+ if (previousNodes) freshNodes = await snapshot.getProperty('freshNodes');
822
+ handles = await (freshNodes ?? nodes).getProperties();
823
+ requirePageOrigin(ws, tab);
824
+ if (tab.documentId !== documentId || ws.mode !== 'agent' || ws.generation !== controlGeneration ||
825
+ ws.pages.get(tab.id) !== tab || tab.page.isClosed() || previousNodes !== tab.observedNodes) fail('stale_observation');
826
+
827
+ check();
828
+ const nextRefs = new Map();
829
+ const elements = details.map(({role, name, options,...state}, index) => {
830
+ const existing = priorRefs[previousIndices?.[index]];
831
+ const ref = existing ?? randomUUID();
832
+ const element = existing ? tab.refs.get(existing) : handles.get(String(index))?.asElement();
833
+ if (!element || nextRefs.has(ref)) fail('stale_observation');
834
+ nextRefs.set(ref, element);
835
+ const choices = options?.map(option => ({value: redact(ws, option.value), label: redact(ws, option.label)}));
836
+ return { ref, role, name: redact(ws, name), ...state, ...(choices && { options: choices }) };
837
+ });
838
+ // Publish only after every target and the control generation are verified.
839
+ for (const [ref, handle] of tab.refs) {
840
+ if (!nextRefs.has(ref)) void handle.dispose().catch(() => {});
841
+ }
842
+ tab.refs=nextRefs;
843
+ tab.strictLocator=options.locator;
844
+ clearFrameRefs(tab);
845
+ if(frameResult) tab.frameRefs=frameResult.refs;
846
+ published=true;
847
+ tab.observedNodes = nodes;
848
+ nodes = undefined;
849
+ handles = undefined;
850
+ 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,
853
+ ...(foreground && {foreground:{...foreground,name:redact(ws,foreground.name)}}), ...observationMatch(ws,match), ...this.continuation(tab,ws,false,request,next,frameResult?.next),
854
+ ...(frames && { frames }), blockedRequests: blockedRequests(tab.page) };
855
+ } finally {
856
+ if(!published && frameResult) for(const {handle} of frameResult.refs.values()) void handle.dispose().catch(()=>{});
857
+ const release = [snapshot, nodes, freshNodes, ...(handles?.values() ?? [])].filter(Boolean);
858
+ await Promise.all(release.map(handle => handle.dispose().catch(() => {})));
859
+ }
860
+ }
861
+
862
+ actionDigest(params) {
863
+ const {pageId,documentId,controlGeneration,actions,observeAfter,timeoutMs}=params;
864
+ if(params[workflowOrigin]) return createHash('sha256').update(JSON.stringify(
865
+ ['runWorkflow',pageId,documentId,controlGeneration,params[workflowOrigin],actions,timeoutMs])).digest('hex');
866
+ return createHash('sha256').update(JSON.stringify(['act',pageId,documentId,controlGeneration,actions,observeAfter,timeoutMs])).digest('hex');
867
+ }
868
+
869
+ act(ws, params) {
870
+ const { operationId, pageId, documentId, controlGeneration, actions, timeoutMs } = params;
871
+ stringParam(operationId, 160);
872
+ if (timeoutMs !== undefined && (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > limits.runTimeoutMs)) fail('invalid_params');
873
+ if (params.observeAfter !== undefined && !['full', 'delta'].includes(params.observeAfter)) fail('invalid_params');
874
+ if (!Array.isArray(actions) || !actions.length || actions.length > 32) fail('invalid_actions');
875
+ for (const action of params[workflowOrigin] ? [] : actions) {
876
+ if (action?.kind === 'upload') {
877
+ stringParam(action.fileId,160);
878
+ stringParam(action.ref,160);
879
+ continue;
880
+ }
881
+ if (action?.kind === 'spatial') {
882
+ stringParam(action.frameId,160);
883
+ validateVisualAction(action.action);
884
+ continue;
885
+ }
886
+ if (action?.kind === 'wait') {
887
+ if ([action.text, action.url, action.element, action.absent, action.navigation].filter(value => value !== undefined).length !== 1) fail('invalid_actions');
888
+ if (action.text !== undefined) stringParam(action.text, 256);
889
+ if (action.url !== undefined) webOrigin(stringParam(action.url, 65536));
890
+ if (action.navigation !== undefined && action.navigation !== 'commit') fail('invalid_actions');
891
+ if (action.element !== undefined || action.absent !== undefined) {
892
+ const target=action.element ?? action.absent;
893
+ stringParam(target?.role, 80);
894
+ stringParam(target?.name, 160);
895
+ const stateKeys=['checked','pressed','expanded','selected'];
896
+ for(const [key,val] of Object.entries(target)) {
897
+ if(key==='role' || key==='name') continue;
898
+ if(action.absent || !stateKeys.includes(key) || (typeof val!=='boolean' &&
899
+ !(['pressed','checked'].includes(key) && val==='mixed'))) fail('invalid_actions');
900
+ }
901
+ }
902
+ if (action.timeoutMs !== undefined && (!Number.isInteger(action.timeoutMs) ||
903
+ action.timeoutMs < 1 || action.timeoutMs > 10000)) fail('invalid_actions');
904
+ continue;
905
+ }
906
+ if (!action || typeof action.ref !== 'string' || !['click', 'doubleClick', 'hover', 'press', 'scroll', 'drag', 'fill', 'fillCredential', 'select','setChecked'].includes(action.kind))
907
+ fail('invalid_actions');
908
+ if (action.kind === 'setChecked' && typeof action.checked !== 'boolean') fail('invalid_actions');
909
+ if (action.kind === 'select' && (typeof action.value !== 'string' || action.value.length > 256)) fail('invalid_actions');
910
+ if (action.kind === 'fill' && (typeof action.value !== 'string' || action.value.length > 8192))
911
+ fail('invalid_actions');
912
+ if (action.kind === 'press' && (typeof action.key !== 'string' || action.key.length > 80)) fail('invalid_actions');
913
+ if (action.kind === 'scroll' && (!Number.isFinite(action.deltaY) || !Number.isFinite(action.deltaX ?? 0))) fail('invalid_actions');
914
+ if (action.kind === 'drag' && (typeof action.toRef !== 'string' || action.toRef.length > 160)) fail('invalid_actions');
915
+ if (action.kind === 'fillCredential') stringParam(action.credentialRef, 160);
916
+ }
917
+ const digest = this.actionDigest(params);
918
+ const past = ws.operations.get(operationId);
919
+ if (past) {
920
+ if (digest !== past.digest) fail('operation_id_conflict');
921
+ return this.receiptView(ws, past);
922
+ }
923
+ const prior = this.store.get(ws.owner, ws.id, operationId);
924
+ if (prior) {
925
+ if (prior.digest !== digest) fail('operation_id_conflict');
926
+ return prior.receipt;
927
+ }
928
+ const tab = this.tab(ws, pageId);
929
+ this.requireControl(ws, controlGeneration);
930
+ requirePageOrigin(ws, tab);
931
+ if (tab.documentId !== documentId) fail('stale_document');
932
+ if (ws.operations.size >= 2048) fail('operation_limit');
933
+ const receipt = { operationId, pageId, state: 'queued', phase: 'queued', totalSteps: actions.length, completedSteps: 0 };
934
+ if (ws.pending >= 128 || this.pending >= 512) fail('queue_full');
935
+ this.store.save(ws.owner, ws.id, digest, receipt);
936
+ const budgetMs = timeoutMs ?? limits.runTimeoutMs;
937
+ const op = { digest, receipt, cancel: false, controller: new AbortController(), kind: 'act', pageId, totalSteps: actions.length,
938
+ deadline: Date.now() + budgetMs, budgetMs };
939
+ const run = this.enqueue(ws, () => params[workflowOrigin] ? performWorkflow(this,ws,tab,params,op,fail) :
940
+ perform(this,ws,tab,params,op), op);
941
+ ws.operations.set(operationId, op);
942
+ run.catch(error => {
943
+ if (['queued','running'].includes(receipt.state)) {
944
+ receipt.state = op.cancel ? 'cancelled' : 'failed';
945
+ receipt.phase = receipt.state;
946
+ receipt.error = publicError(error);
947
+ }
948
+ });
949
+ return { ...receipt };
950
+ }
951
+
952
+ receiptView(ws, op) {
953
+ const result = { ...op.receipt };
954
+ const tab = ws.pages.get(op.pageId);
955
+ const recent = tab?.actionObservation;
956
+ if (recent?.operationId === op.receipt.operationId && ws.mode === 'agent' &&
957
+ recent.generation === ws.generation && recent.documentId === tab.documentId && allowedPageOrigin(ws, tab))
958
+ Object.assign(result, recent.payload);
959
+ return result;
960
+ }
961
+
962
+ async desktopNavigate(ws, { pageId, action, url }, newTab) {
963
+ const tab = newTab ? null : this.tab(ws, pageId);
964
+ if (newTab) action = 'go';
965
+ if (!['go', 'back', 'forward', 'reload'].includes(action) ||
966
+ (action !== 'go' && url !== undefined)) fail('invalid_params');
967
+ const origin = action === 'go' ? webOrigin(stringParam(url, 65536)) : null;
968
+ const { controlGeneration } = await this.handOff(ws, pageId, false);
969
+ return enqueueHuman(ws, controlGeneration, async check => {
970
+ if (tab) this.tab(ws, tab.id);
971
+ // Only an explicitly typed address grants a new origin. Redirects and
972
+ // subresources still pass through the existing workspace network rules.
973
+ if (origin) ws.origins.add(origin);
974
+ if (newTab) return this.open(ws, url);
975
+ try { return await navigatePage(ws, tab, action, url, check); }
976
+ catch (error) {
977
+ if (error.code) throw error;
978
+ fail('navigation_failed');
979
+ }
980
+ });
981
+ }
982
+
983
+ handOff(ws, pageId, focus, expectedGeneration) {
984
+ return handOff(this, ws, pageId, focus, expectedGeneration);
985
+ }
986
+
987
+ returnToAgent(ws, expectedGeneration) {
988
+ return returnToAgent(this, ws, expectedGeneration);
989
+ }
990
+
991
+ async shutdown() {
992
+ if (this.stopped) return;
993
+ this.stopped = true;
994
+ clearInterval(this.sweep);
995
+ await Promise.all([...this.workspaces.values()].map(async ws => {
996
+ await ws.finishing?.promise;
997
+ if (this.workspaces.has(ws.id)) await closeWorkspace(this, ws);
998
+ }));
999
+ if (this.protocol) await this.protocol.then(session => session.detach()).catch(() => {});
1000
+ this.store.close();
1001
+ }
1002
+ }