@seekskyworld/open-browser 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Docs/open-browser-api.d.ts +32 -10
- 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
- package/README.md +14 -5
- package/README.zh-CN.md +16 -5
- package/access-registry.mjs +13 -3
- package/action-execution.mjs +60 -24
- package/api-contract.mjs +19 -7
- package/browser-extension/manifest.json +1 -4
- package/browser-extension/newtab.css +6 -0
- package/browser-extension/newtab.js +54 -2
- package/browser-extension/phase-labels.js +1 -1
- package/browser-extension/popup.css +1 -1
- package/browser-extension/popup.html +16 -4
- package/browser-extension/popup.js +122 -21
- package/browser-extension/tab-action.js +4 -2
- package/browser-extension/worker.js +102 -9
- package/build-profile.mjs +23 -0
- package/capability-matrix.mjs +4 -4
- package/chromium-host.mjs +81 -25
- package/chromium-shell.mjs +78 -49
- package/cli.mjs +63 -5
- package/contract-validation.mjs +1 -1
- package/desktop/Info.plist +2 -2
- package/desktop/OBControlBar.m +7 -3
- package/desktop/WorkspacePanel.m +4 -2
- package/desktop/brand-keychain.py +20 -4
- package/desktop/build-macos.mjs +31 -12
- package/desktop/build-managed-input.mjs +37 -0
- package/desktop/build-profile.mjs +6 -0
- package/desktop/build.mjs +8 -0
- package/desktop/macos-entitlements.plist +12 -0
- package/desktop/notarize-macos.mjs +189 -0
- package/desktop/package-macos.mjs +54 -0
- package/desktop/patches/chromium-managed-input.patch +144 -0
- package/desktop/sign.mjs +63 -4
- package/desktop/start-profile.mjs +5 -0
- package/desktop/start.mjs +25 -3
- package/desktop/verify-macos-release.mjs +69 -0
- package/desktop/verify-version.mjs +22 -2
- package/diagnostics.mjs +9 -0
- package/engine-service.mjs +244 -29
- package/managed-input.mjs +155 -0
- package/mcp-http.mjs +84 -0
- package/mcp-server.mjs +57 -0
- package/mcp.mjs +3 -40
- package/package.json +24 -3
- package/page-activity.mjs +97 -29
- package/page-observation.mjs +44 -3
- package/paths.mjs +5 -3
- package/receipt-store.mjs +24 -7
- package/runtime.mjs +10 -1
- package/sdk.mjs +53 -26
- package/service.mjs +45 -10
- package/skill-links.mjs +144 -0
- package/skills/open-browser/SKILL.md +8 -76
- package/skills/open-browser/references/macos.md +3 -0
- package/skills/open-browser/references/operations.md +59 -0
- package/skills/open-browser/references/recovery.md +36 -0
- package/skills/open-browser/references/windows.md +3 -0
- package/skills/open-browser/scripts/bootstrap.mjs +112 -45
- package/skills/open-browser/scripts/guide.mjs +17 -0
- package/studio/studio.js +2 -2
- package/tab-adoption.mjs +83 -0
- package/tab-recovery.mjs +100 -0
- package/uploads.mjs +4 -4
- package/visual-page.mjs +17 -7
- package/workspace-lifecycle.mjs +92 -8
- package/workspace-state.mjs +65 -12
package/engine-service.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
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,21 @@ 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, tabRecovery, 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');
|
|
65
|
+
this.tabRecovery = tabRecovery;
|
|
63
66
|
this.browser = browser;
|
|
64
67
|
this.sharedContext = sharedContext;
|
|
65
68
|
this.groupTab = groupTab;
|
|
66
69
|
this.releaseTab = releaseTab;
|
|
70
|
+
this.withAgentInput = withAgentInput;
|
|
71
|
+
this.inputGuardMode = inputGuardMode;
|
|
72
|
+
if (setInputGuard) this.setInputGuard = (ws, tab, enabled) => setInputGuard(tab, enabled, () => {
|
|
73
|
+
ws.guardLost = true;
|
|
74
|
+
if (ws.mode === 'agent' && !ws.finishing && !this.stopped)
|
|
75
|
+
void this.handOff(ws, undefined, false).catch(() => {});
|
|
76
|
+
});
|
|
67
77
|
this.readOnlyObserver = readOnlyObserver;
|
|
68
78
|
this.actors = new AsyncLocalStorage();
|
|
69
79
|
this.store = new ReceiptStore(journalPath, () => this.actors.getStore());
|
|
@@ -85,16 +95,48 @@ export class BrowserService {
|
|
|
85
95
|
for (const ws of this.workspaces.values()) {
|
|
86
96
|
if (ws.mode === 'agent' && !ws.pending && !ws.finishing && ws.lastActiveAt <= cutoff &&
|
|
87
97
|
!ws.credentialRequests.size && ![...ws.pages.values()].some(tab => tab.needsSubmissionReview))
|
|
88
|
-
void closeWorkspace(this, ws).catch(() => {});
|
|
98
|
+
void closeWorkspace(this, ws, 'idle_timeout').catch(() => {});
|
|
89
99
|
}
|
|
90
100
|
}, Math.min(60_000, idleTimeoutMs)).unref();
|
|
91
101
|
}
|
|
92
102
|
|
|
93
103
|
notify(ws) {
|
|
104
|
+
if (!this.stopped) this.tabRecovery?.refresh(ws);
|
|
105
|
+
if (ws.mode === 'agent' || ws.mode === 'closed' || ws.finishing) {
|
|
106
|
+
for (const resume of ws.controlWaiters || []) resume();
|
|
107
|
+
}
|
|
94
108
|
this.notifier.notify(ws);
|
|
95
109
|
}
|
|
96
110
|
|
|
97
|
-
|
|
111
|
+
invalidateObservation(tab) {
|
|
112
|
+
if (tab) tab.observationCache = undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async observationRevision(tab) {
|
|
116
|
+
try {
|
|
117
|
+
return await tab.page.evaluate(() => {
|
|
118
|
+
const key = '__openBrowserObservationRevision';
|
|
119
|
+
if (!Number.isSafeInteger(window[key])) {
|
|
120
|
+
window[key] = 1;
|
|
121
|
+
const ignored = node => node?.closest?.('[data-open-browser-activity],[data-open-browser-target],[data-open-browser-agent-cursor],[data-open-browser-label]');
|
|
122
|
+
const observer = new MutationObserver(records => {
|
|
123
|
+
if (records.some(record => {
|
|
124
|
+
if (record.type === 'attributes' && ignored(record.target)) return false;
|
|
125
|
+
if (record.type === 'childList' && [...record.addedNodes, ...record.removedNodes].every(ignored)) return false;
|
|
126
|
+
return true;
|
|
127
|
+
})) window[key]++;
|
|
128
|
+
});
|
|
129
|
+
observer.observe(document, { subtree: true, childList: true, attributes: true, characterData: true });
|
|
130
|
+
Object.defineProperty(window, '__openBrowserObservationObserver', { value: observer, configurable: true });
|
|
131
|
+
}
|
|
132
|
+
return window[key];
|
|
133
|
+
});
|
|
134
|
+
} catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
notifyTarget(ws, tab, el, documentId, controlGeneration, origin, actionKind = '操作') {
|
|
98
140
|
if (!this.onActionTarget) return;
|
|
99
141
|
const ticket = Symbol();
|
|
100
142
|
tab.latestTarget = ticket;
|
|
@@ -109,8 +151,12 @@ export class BrowserService {
|
|
|
109
151
|
const left = Math.max(0, box.x), right = Math.min(size.width, box.x + box.width);
|
|
110
152
|
const top = Math.max(0, box.y), bottom = Math.min(size.height, box.y + box.height);
|
|
111
153
|
if (!(right > left && bottom > top)) return;
|
|
112
|
-
|
|
113
|
-
x: (left + right) / 2, y: (top + bottom) / 2, origin }
|
|
154
|
+
const target = { workspaceId: ws.id, pageId: tab.id, documentId, controlGeneration,
|
|
155
|
+
x: (left + right) / 2, y: (top + bottom) / 2, origin };
|
|
156
|
+
Object.defineProperty(target, 'actionKind', { value: actionKind, enumerable: false });
|
|
157
|
+
this.store.event(ws.owner, ws.id, 'action', 'running', null, null,
|
|
158
|
+
{ pageId: tab.id, resourceId: String(actionKind).slice(0, 64) });
|
|
159
|
+
return this.onActionTarget(target);
|
|
114
160
|
}).catch(() => {});
|
|
115
161
|
}
|
|
116
162
|
|
|
@@ -122,7 +168,7 @@ export class BrowserService {
|
|
|
122
168
|
if (this.stopped) fail('service_stopped');
|
|
123
169
|
if (typeof clientId !== 'string' || !clientId) fail('unauthorized');
|
|
124
170
|
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 : []}};
|
|
171
|
+
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
172
|
if(method==='runWorkflow') {
|
|
127
173
|
params=workflowRequest(params);
|
|
128
174
|
method='act';
|
|
@@ -141,11 +187,18 @@ export class BrowserService {
|
|
|
141
187
|
const {records, nextObjectCursor} = this.store.recoveryObjects(clientId, params.workspaceId, params.objectsAfter, params.limit);
|
|
142
188
|
if (!ws && !records.length && !operations.length && !this.store.events(clientId,params.workspaceId,0,1).events.length)
|
|
143
189
|
fail('workspace_not_found');
|
|
144
|
-
const
|
|
145
|
-
|
|
146
|
-
|
|
190
|
+
const closeReason = !ws ? this.store.closeReason(clientId, params.workspaceId) : undefined;
|
|
191
|
+
const pages = records.filter(row => row.kind === 'page').map(({id, disposition, origin}) => {
|
|
192
|
+
const managed = ws?.pages.has(id);
|
|
193
|
+
return {pageId:id, ...(origin && {origin}), ...(disposition && {lastDisposition:disposition}),
|
|
194
|
+
next:managed ? 'observe' : 'handle_unavailable',
|
|
195
|
+
pageAvailability:ws ? (managed ? 'managed' : 'closed') : disposition === 'closed' ? 'closed' : 'unregistered',
|
|
196
|
+
nextAction:managed ? (ws.mode === 'agent' ? 'reattachPage' : 'wait_for_agent_control') : 'request_tab_selection'
|
|
197
|
+
};
|
|
198
|
+
});
|
|
147
199
|
return {
|
|
148
200
|
workspaceId:params.workspaceId, mode:ws?.mode ?? 'unavailable', pages,
|
|
201
|
+
...(!ws && {closeReason}),
|
|
149
202
|
deliveries:records.filter(row => row.kind === 'download').map(row => ({downloadId:row.id})),
|
|
150
203
|
outputs:records.filter(row => row.kind === 'output').map(row => ({outputId:row.id})),
|
|
151
204
|
operations:operations.map(receipt => ({...receipt, next:
|
|
@@ -158,6 +211,8 @@ export class BrowserService {
|
|
|
158
211
|
if (method === 'diagnoseOperation') return this.store.diagnose(clientId, params.workspaceId, params.operationId);
|
|
159
212
|
if (method === 'listOperations')
|
|
160
213
|
return this.store.list(clientId, params.workspaceId, params.after, params.limit);
|
|
214
|
+
if (method === 'getWorkspace' && params.profileId !== undefined && params.profileId !== serviceProfileId)
|
|
215
|
+
fail('profile_mismatch');
|
|
161
216
|
const ws = this.workspaces.get(params.workspaceId);
|
|
162
217
|
if (!ws || ws.owner !== clientId) {
|
|
163
218
|
if (['listOutputs', 'readOutput'].includes(method)) {
|
|
@@ -182,6 +237,43 @@ export class BrowserService {
|
|
|
182
237
|
if (!statusQueries.has(method)) ws.lastActiveAt = Date.now();
|
|
183
238
|
switch (method) {
|
|
184
239
|
case 'getWorkspace': return workspaceView(ws, true);
|
|
240
|
+
case 'offerCurrentTab': return offerTab(this, ws, params);
|
|
241
|
+
case 'adoptCurrentTab': return adoptTab(this, ws, params);
|
|
242
|
+
case 'canvasSnapshot': return this.enqueue(ws, async () => {
|
|
243
|
+
const tab = this.tab(ws, params.pageId);
|
|
244
|
+
const origin = requirePageOrigin(ws, tab), documentId = tab.documentId, controlGeneration = ws.generation;
|
|
245
|
+
const data = await tab.page.evaluate(inspectDocument, {canvas:true, origins:[origin]});
|
|
246
|
+
this.requireControl(ws, controlGeneration);
|
|
247
|
+
if (!data || ws.pages.get(tab.id) !== tab || tab.documentId !== documentId || requirePageOrigin(ws, tab) !== origin)
|
|
248
|
+
fail('stale_observation');
|
|
249
|
+
for (const row of [...data.nodes, ...data.edges, ...data.messages, ...data.attachments]) {
|
|
250
|
+
for (const field of ['id','label','text','source','target']) if (field in row) row[field] = redact(ws, row[field]);
|
|
251
|
+
}
|
|
252
|
+
if (data.adapter === 'unsupported') {
|
|
253
|
+
let visualStatus = 'available';
|
|
254
|
+
try { this.visual.authority(ws, tab, this.actors.getStore(), 'agent'); }
|
|
255
|
+
catch (error) { visualStatus = error.code; }
|
|
256
|
+
data.fallback = {dom:'observe', visualStatus, ...(visualStatus === 'available' && {visual:'captureVisual'}),
|
|
257
|
+
...(visualStatus === 'pixel_permission_required' && {grant:this.sharedContext && ws.owner === this.actors.getStore()
|
|
258
|
+
? 'extension_pixel_permission' : 'admin.setPixelPermission', origin})};
|
|
259
|
+
}
|
|
260
|
+
const snapshotVersion = createHash('sha256').update(JSON.stringify([documentId,controlGeneration,data])).digest('hex');
|
|
261
|
+
return {workspaceId:ws.id,pageId:tab.id,documentId,controlGeneration,snapshotVersion,...data};
|
|
262
|
+
}, {kind:'canvasSnapshot', pageId:params.pageId});
|
|
263
|
+
case 'previewFinish': return previewFinish(this, ws, params.keepPageIds);
|
|
264
|
+
case 'reattachPage': {
|
|
265
|
+
this.tab(ws, params.pageId);
|
|
266
|
+
if (params.waitMs && ws.mode !== 'agent') {
|
|
267
|
+
ws.controlWaiters ??= new Set();
|
|
268
|
+
if (ws.controlWaiters.size >= 32) fail('queue_full');
|
|
269
|
+
await new Promise((resolve, reject) => {
|
|
270
|
+
const resume = () => { clearTimeout(timer); ws.controlWaiters.delete(resume); resolve(); };
|
|
271
|
+
const timer = setTimeout(() => { ws.controlWaiters.delete(resume); reject(new ServiceError('workspace_under_user_control')); }, params.waitMs);
|
|
272
|
+
ws.controlWaiters.add(resume);
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
return this.refreshBoundPage(ws, params.pageId);
|
|
276
|
+
}
|
|
185
277
|
case 'listUploads': return ws.uploads.list();
|
|
186
278
|
case 'grantUpload': {
|
|
187
279
|
if (this.actors.getStore() !== 'desktop') fail('forbidden');
|
|
@@ -210,8 +302,23 @@ export class BrowserService {
|
|
|
210
302
|
this.store.remember(ws.owner, ws.id, 'output', result.output.id);
|
|
211
303
|
return result;
|
|
212
304
|
}
|
|
213
|
-
case 'visualStatus':
|
|
305
|
+
case 'visualStatus': {
|
|
306
|
+
const tab = ws.pages.get(params.pageId);
|
|
307
|
+
const origin = tab && allowedPageOrigin(ws, tab);
|
|
308
|
+
return {lastCapture:ws.lastVisualCapture || null, ...(origin && this.visual.enabled && {
|
|
309
|
+
pagePermission:{origin, allow:this.visual.hasPermission(ws, ws.owner, origin), documentId:tab.documentId}
|
|
310
|
+
})};
|
|
311
|
+
}
|
|
312
|
+
case 'setPagePixelPermission': {
|
|
313
|
+
if (this.actors.getStore() !== 'desktop') fail('forbidden');
|
|
314
|
+
const tab = this.tab(ws, params.pageId);
|
|
315
|
+
if (ws.generation !== params.controlGeneration) fail('stale_control');
|
|
316
|
+
if (tab.documentId !== params.documentId) fail('stale_document');
|
|
317
|
+
if (requirePageOrigin(ws, tab) !== params.origin) fail('origin_denied');
|
|
318
|
+
return this.visual.permission(ws, {principalId:ws.owner, origin:params.origin, allow:params.allow});
|
|
319
|
+
}
|
|
214
320
|
case 'grantOrigin': {
|
|
321
|
+
if (ws.singleTab) fail('single_tab_scope');
|
|
215
322
|
if (params.controlGeneration !== ws.generation || !['agent', 'human'].includes(ws.mode)) fail('stale_control');
|
|
216
323
|
const origin = webOrigin(params.origin);
|
|
217
324
|
if (origin !== params.origin || !['navigation', 'resource'].includes(params.scope)) fail('invalid_params');
|
|
@@ -244,6 +351,7 @@ export class BrowserService {
|
|
|
244
351
|
case 'pageNavigate': return this.desktopNavigate(ws, params, false);
|
|
245
352
|
case 'closePage': {
|
|
246
353
|
const tab = this.tab(ws, params.pageId);
|
|
354
|
+
if (ws.singleTab) fail('user_owned_page');
|
|
247
355
|
await tab.page.close();
|
|
248
356
|
return { workspaceId: ws.id, pageId: tab.id, closed: true };
|
|
249
357
|
}
|
|
@@ -257,6 +365,7 @@ export class BrowserService {
|
|
|
257
365
|
case 'openPage': return this.enqueue(ws, job => this.open(ws, params.url, job), { kind: 'openPage' });
|
|
258
366
|
case 'observe': return this.enqueue(ws, () => this.observe(ws, this.tab(ws, params.pageId), params),
|
|
259
367
|
{ kind: 'observe', pageId: params.pageId });
|
|
368
|
+
case 'observeAndAct': return this.observeAndAct(ws, params);
|
|
260
369
|
case 'act': return this.act(ws, params);
|
|
261
370
|
case 'setCredential': return this.setCredential(ws, params);
|
|
262
371
|
case 'resolveCredential': {
|
|
@@ -290,11 +399,23 @@ export class BrowserService {
|
|
|
290
399
|
if (op.receipt.state === 'queued') op.receipt.state = 'cancelled';
|
|
291
400
|
this.notify(ws);
|
|
292
401
|
}
|
|
293
|
-
return this.
|
|
402
|
+
return this.waitReceipt(ws, op, params.waitMs);
|
|
294
403
|
}
|
|
295
404
|
case 'handOff':
|
|
296
405
|
case 'takeControl': return this.handOff(ws, params.pageId, true, params.controlGeneration);
|
|
297
|
-
case 'returnToAgent':
|
|
406
|
+
case 'returnToAgent': {
|
|
407
|
+
if (params.pageId !== undefined) this.tab(ws, params.pageId);
|
|
408
|
+
const state = await this.returnToAgent(ws, params.controlGeneration);
|
|
409
|
+
if (params.pageId === undefined) return state;
|
|
410
|
+
try {
|
|
411
|
+
const observation = await this.refreshBoundPage(ws, params.pageId);
|
|
412
|
+
return {...workspaceView(ws), observation};
|
|
413
|
+
} catch (error) {
|
|
414
|
+
// Control already changed. Report a page-specific failure separately
|
|
415
|
+
// so the caller can recover without replaying the handoff.
|
|
416
|
+
return {...workspaceView(ws), pageError:{pageId:params.pageId,code:publicError(error)}};
|
|
417
|
+
}
|
|
418
|
+
}
|
|
298
419
|
case 'closeWorkspace':
|
|
299
420
|
if (ws.mode !== 'agent') fail('workspace_under_user_control');
|
|
300
421
|
await closeWorkspace(this, ws);
|
|
@@ -303,7 +424,7 @@ export class BrowserService {
|
|
|
303
424
|
}
|
|
304
425
|
}
|
|
305
426
|
|
|
306
|
-
async create({ profileId, name = '', agentName = 'Agent', allowedOrigins = [], resourceOrigins = [], networkMode = 'strict' }, owner) {
|
|
427
|
+
async create({ profileId, name = '', agentName = 'Agent', allowedOrigins = [], resourceOrigins = [], networkMode = 'strict' }, owner, workspaceId = randomUUID()) {
|
|
307
428
|
if (profileId !== undefined && profileId !== serviceProfileId) fail('profile_mismatch');
|
|
308
429
|
if (typeof name !== 'string' || !name.trim()) fail('task_name_required');
|
|
309
430
|
if (name.length > 120 || !Array.isArray(allowedOrigins)
|
|
@@ -319,8 +440,8 @@ export class BrowserService {
|
|
|
319
440
|
const { context, browserContextId } = this.sharedContext
|
|
320
441
|
? { context: this.sharedContext } : await this.allocateContext();
|
|
321
442
|
try {
|
|
322
|
-
const ws = { id:
|
|
323
|
-
resourceOrigins: resources, blockedOrigins: new Map(), generation: randomUUID(), control: new AbortController(), pages: new Map(), operations: new Map(), credentials: new Map(),
|
|
443
|
+
const ws = { id: workspaceId, owner, name, agentName: displayName, context, browserContextId, origins, networkMode, mode: 'agent',
|
|
444
|
+
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
445
|
tail: Promise.resolve(), lanes: new Map(), pending: 0, handoff: null, lastActiveAt: Date.now(),
|
|
325
446
|
inputTail: Promise.resolve(), inputPending: 0,
|
|
326
447
|
popupTasks: new Set(), jobs: new Set(), recent: null, credentialRequests: new Map() };
|
|
@@ -351,9 +472,11 @@ export class BrowserService {
|
|
|
351
472
|
const ws = this.workspaces.get(created.workspaceId);
|
|
352
473
|
if (!ws) fail('workspace_unavailable');
|
|
353
474
|
try {
|
|
354
|
-
return await this.open(ws, url);
|
|
475
|
+
return await this.enqueue(ws, job => this.open(ws, url, job), {kind:'openPage'});
|
|
355
476
|
} catch (error) {
|
|
356
|
-
|
|
477
|
+
// A takeover can happen while the first page is being opened. The
|
|
478
|
+
// workspace and any opened tab then belong to the person taking control.
|
|
479
|
+
if (ws.mode === 'agent' && !ws.finishing) await closeWorkspace(this, ws, 'open_failed').catch(() => {});
|
|
357
480
|
throw error;
|
|
358
481
|
}
|
|
359
482
|
}
|
|
@@ -381,12 +504,37 @@ export class BrowserService {
|
|
|
381
504
|
|
|
382
505
|
routeWorkspace(target, ws) { return routeWorkspace(target, ws, !!this.sharedContext); }
|
|
383
506
|
|
|
384
|
-
|
|
507
|
+
refreshBoundPage(ws, pageId) {
|
|
508
|
+
return this.enqueue(ws, async () => {
|
|
509
|
+
const tab = this.tab(ws, pageId);
|
|
510
|
+
if (this.groupTab && tab.syncedGeneration !== ws.generation) await this.syncTab(ws, tab);
|
|
511
|
+
if (tab.dialog) fail('dialog_pending');
|
|
512
|
+
return this.observe(ws, tab);
|
|
513
|
+
}, {kind:'observe', pageId});
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
async syncTab(ws, tab) {
|
|
517
|
+
if (!this.groupTab) return;
|
|
518
|
+
const generation = ws.generation;
|
|
519
|
+
try { await this.groupTab(tab.page, ws.id, ws.name, ws.mode, ws.agentName, tab.id, generation, !!ws.singleTab); }
|
|
520
|
+
catch { fail('sync_pending'); }
|
|
521
|
+
if (ws.pages.get(tab.id) === tab && ws.generation === generation) {
|
|
522
|
+
tab.syncedGeneration = generation;
|
|
523
|
+
tab.syncRevision = (tab.syncRevision || 0) + 1;
|
|
524
|
+
tab.lastSyncedAt = Date.now();
|
|
525
|
+
this.notify(ws);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
register(ws, page, pageId = randomUUID()) {
|
|
530
|
+
ws.everRegistered = true;
|
|
385
531
|
const existing = [...ws.pages.values()].find(tab => tab.page === page);
|
|
386
532
|
if (existing) return existing;
|
|
387
|
-
const tab = { id:
|
|
533
|
+
const tab = { id: pageId, page, documentId: randomUUID(), refs:new Map(), frameRefs:new Map(), frameDocuments:new WeakMap(), frameIds:new WeakMap(), cursors:new Map(), frameRevision:0, title: '',
|
|
388
534
|
heldKeys: new Set(), heldButtons: new Set() };
|
|
389
|
-
|
|
535
|
+
tab.extensionSync = !!this.groupTab;
|
|
536
|
+
ws.securityChallenge = null;
|
|
537
|
+
this.store.remember(ws.owner, ws.id, 'page', tab.id, {origin: ws.singleTab ? allowedPageOrigin(ws, tab) : null});
|
|
390
538
|
ws.pages.set(tab.id, tab);
|
|
391
539
|
const releaseDialogs = attachDialogs(ws,tab,()=>{
|
|
392
540
|
const info=tab.dialog.info;
|
|
@@ -403,7 +551,9 @@ export class BrowserService {
|
|
|
403
551
|
}
|
|
404
552
|
ws.credentialRequests.delete(tab.id);
|
|
405
553
|
tab.title = '';
|
|
554
|
+
ws.securityChallenge = null;
|
|
406
555
|
tab.documentId = randomUUID();
|
|
556
|
+
this.invalidateObservation(tab);
|
|
407
557
|
clearRefs(tab);
|
|
408
558
|
this.notify(ws);
|
|
409
559
|
if (tab.heldKeys.size || tab.heldButtons.size)
|
|
@@ -411,7 +561,24 @@ export class BrowserService {
|
|
|
411
561
|
void refreshTitle(ws, tab);
|
|
412
562
|
};
|
|
413
563
|
const loaded = () => { void refreshTitle(ws, tab); };
|
|
564
|
+
const response = async response => {
|
|
565
|
+
try {
|
|
566
|
+
if (response.request().resourceType() !== 'document') return;
|
|
567
|
+
const headers = await response.allHeaders();
|
|
568
|
+
const mitigated = headers['cf-mitigated']?.toLowerCase() === 'challenge';
|
|
569
|
+
const cloudflare = headers.server?.toLowerCase().includes('cloudflare');
|
|
570
|
+
if (!mitigated && !(cloudflare && response.status() >= 403)) return;
|
|
571
|
+
const url = URL.parse(response.url());
|
|
572
|
+
if (!url || !['http:', 'https:'].includes(url.protocol)) return;
|
|
573
|
+
ws.securityChallenge = { provider: 'cloudflare', origin: url.origin,
|
|
574
|
+
status: response.status(), detectedAt: Date.now() };
|
|
575
|
+
this.store.event(ws.owner, ws.id, 'security', 'human_verification_required', null,
|
|
576
|
+
{ pageId: tab.id, origin: url.origin, status: response.status() });
|
|
577
|
+
this.notify(ws);
|
|
578
|
+
} catch { /* A closing page cannot change the workspace state. */ }
|
|
579
|
+
};
|
|
414
580
|
const closed = () => {
|
|
581
|
+
this.store.pageDisposition(ws.owner, ws.id, tab.id, page.isClosed() ? 'closed' : 'released');
|
|
415
582
|
releaseDialogs();
|
|
416
583
|
void tab.summarySession?.detach().catch(() => {});
|
|
417
584
|
clearRefs(tab);
|
|
@@ -429,12 +596,14 @@ export class BrowserService {
|
|
|
429
596
|
page.on('framenavigated', navigated);
|
|
430
597
|
page.on('framedetached', navigated);
|
|
431
598
|
page.on('domcontentloaded', loaded);
|
|
599
|
+
page.on('response', response);
|
|
432
600
|
page.on('close', closed);
|
|
433
601
|
tab.unregister = () => {
|
|
434
602
|
page.off('download', downloaded);
|
|
435
603
|
page.off('framenavigated', navigated);
|
|
436
604
|
page.off('framedetached', navigated);
|
|
437
605
|
page.off('domcontentloaded', loaded);
|
|
606
|
+
page.off('response', response);
|
|
438
607
|
page.off('close', closed);
|
|
439
608
|
closed();
|
|
440
609
|
};
|
|
@@ -449,6 +618,7 @@ export class BrowserService {
|
|
|
449
618
|
|
|
450
619
|
requireControl(ws, generation) {
|
|
451
620
|
if (ws.finishing) fail('workspace_finishing');
|
|
621
|
+
if (ws.securityChallenge) fail('human_verification_required');
|
|
452
622
|
if (ws.mode !== 'agent') fail('workspace_under_user_control');
|
|
453
623
|
if (ws.generation !== generation) fail('stale_control');
|
|
454
624
|
}
|
|
@@ -539,6 +709,7 @@ export class BrowserService {
|
|
|
539
709
|
}
|
|
540
710
|
|
|
541
711
|
async open(ws, url, job, popup) {
|
|
712
|
+
if (ws.singleTab) fail('single_tab_scope');
|
|
542
713
|
const origin = webOrigin(url);
|
|
543
714
|
if (!ws.origins.size && !ws.resourceOrigins.has(origin)) ws.origins.add(origin);
|
|
544
715
|
if (!ws.origins.has(origin)) {
|
|
@@ -613,7 +784,10 @@ export class BrowserService {
|
|
|
613
784
|
});
|
|
614
785
|
if (job) job.pageId = tab.id;
|
|
615
786
|
this.notify(ws);
|
|
616
|
-
if (this.sharedContext) await this.
|
|
787
|
+
if (this.sharedContext) await this.syncTab(ws, tab);
|
|
788
|
+
// Register the tab with the extension before attaching the fallback
|
|
789
|
+
// capture layer so its debugger state is established first.
|
|
790
|
+
if (ws.mode === 'agent') await this.setInputGuard?.(ws, tab, true);
|
|
617
791
|
let firstRequest;
|
|
618
792
|
if (popup) {
|
|
619
793
|
// Recheck in the actual request handler as well as before goto. A handoff
|
|
@@ -649,6 +823,7 @@ export class BrowserService {
|
|
|
649
823
|
const key = target + '\n' + credentialRef;
|
|
650
824
|
if (ws.credentials.size >= 128 && !ws.credentials.has(key)) fail('credential_limit');
|
|
651
825
|
ws.credentials.set(key, value);
|
|
826
|
+
for (const tab of ws.pages.values()) this.invalidateObservation(tab);
|
|
652
827
|
for (const [pageId, request] of ws.credentialRequests) {
|
|
653
828
|
if (request.origin === target && request.credentialRef === credentialRef)
|
|
654
829
|
ws.credentialRequests.delete(pageId);
|
|
@@ -666,7 +841,7 @@ export class BrowserService {
|
|
|
666
841
|
this.requireControl(ws, generation);
|
|
667
842
|
if (documentId !== tab.documentId) fail('stale_observation');
|
|
668
843
|
requirePageOrigin(ws, tab);
|
|
669
|
-
return { workspaceId: ws.id, pageId: tab.id, documentId, controlGeneration: generation,
|
|
844
|
+
return { workspaceId: ws.id, pageId: tab.id, observationId: randomUUID(), documentId, controlGeneration: generation,
|
|
670
845
|
text: redact(ws, text) };
|
|
671
846
|
}
|
|
672
847
|
|
|
@@ -791,6 +966,13 @@ export class BrowserService {
|
|
|
791
966
|
options.padding=Math.max(0,...Array.from(ws.credentials.values(),v=>v.length-1));
|
|
792
967
|
requirePageOrigin(ws,tab);
|
|
793
968
|
const documentId=tab.documentId,controlGeneration=ws.generation,frameRevision=tab.frameRevision;
|
|
969
|
+
const cacheable = !readOnly && !request.cursor && !request.name && !request.region && !request.locator &&
|
|
970
|
+
!request.includeFrames && !request.frameControls && request.limit === 180;
|
|
971
|
+
const revision = cacheable ? await this.observationRevision(tab) : null;
|
|
972
|
+
if (cacheable && revision !== null && tab.observationCache?.documentId === documentId &&
|
|
973
|
+
tab.observationCache.controlGeneration === controlGeneration && tab.observationCache.revision === revision) {
|
|
974
|
+
return { ...tab.observationCache.payload, observationId: randomUUID(), blockedRequests: blockedRequests(tab.page) };
|
|
975
|
+
}
|
|
794
976
|
const check=()=>{
|
|
795
977
|
this.requireControl(ws,controlGeneration);
|
|
796
978
|
requirePageOrigin(ws,tab);
|
|
@@ -805,7 +987,7 @@ export class BrowserService {
|
|
|
805
987
|
this.requireControl(ws, controlGeneration);
|
|
806
988
|
requirePageOrigin(ws, tab);
|
|
807
989
|
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),
|
|
990
|
+
return { workspaceId: ws.id, pageId: tab.id, observationId: randomUUID(), documentId, controlGeneration, text:observationText(ws,text,textWindowInfo),
|
|
809
991
|
elements:details.map(({role,name,options,...state})=>({role,name:redact(ws,name),...state})),
|
|
810
992
|
...(foreground && {foreground:{...foreground,name:redact(ws,foreground.name)}}), ...observationMatch(ws,match), ...this.continuation(tab,ws,true,request,next,frameResult?.next),
|
|
811
993
|
...(frames && {frames}), blockedRequests: blockedRequests(tab.page) };
|
|
@@ -848,10 +1030,13 @@ export class BrowserService {
|
|
|
848
1030
|
nodes = undefined;
|
|
849
1031
|
handles = undefined;
|
|
850
1032
|
void previousNodes?.dispose().catch(() => {});
|
|
851
|
-
tab.lastObservation={documentId,controlGeneration,text:observationText(ws,text,textWindowInfo),elements};
|
|
852
|
-
|
|
1033
|
+
tab.lastObservation={observationId: randomUUID(), documentId,controlGeneration,text:observationText(ws,text,textWindowInfo),elements};
|
|
1034
|
+
const result = {workspaceId:ws.id,pageId:tab.id,...tab.lastObservation,
|
|
853
1035
|
...(foreground && {foreground:{...foreground,name:redact(ws,foreground.name)}}), ...observationMatch(ws,match), ...this.continuation(tab,ws,false,request,next,frameResult?.next),
|
|
854
1036
|
...(frames && { frames }), blockedRequests: blockedRequests(tab.page) };
|
|
1037
|
+
if (cacheable && revision !== null)
|
|
1038
|
+
tab.observationCache = { documentId, controlGeneration, revision, payload: result };
|
|
1039
|
+
return result;
|
|
855
1040
|
} finally {
|
|
856
1041
|
if(!published && frameResult) for(const {handle} of frameResult.refs.values()) void handle.dispose().catch(()=>{});
|
|
857
1042
|
const release = [snapshot, nodes, freshNodes, ...(handles?.values() ?? [])].filter(Boolean);
|
|
@@ -859,6 +1044,21 @@ export class BrowserService {
|
|
|
859
1044
|
}
|
|
860
1045
|
}
|
|
861
1046
|
|
|
1047
|
+
async observeAndAct(ws, params) {
|
|
1048
|
+
const tab = this.tab(ws, params.pageId);
|
|
1049
|
+
const { workspaceId, pageId, operationId, actions, timeoutMs, observeAfter, waitMs,
|
|
1050
|
+
documentId, controlGeneration, ...observeParams } = params;
|
|
1051
|
+
if (workspaceId !== ws.id || documentId !== undefined || controlGeneration !== undefined)
|
|
1052
|
+
fail('invalid_params');
|
|
1053
|
+
const observation = await this.enqueue(ws, () => this.observe(ws, tab, observeParams),
|
|
1054
|
+
{ kind: 'observe', pageId: tab.id });
|
|
1055
|
+
const receipt = this.act(ws, { workspaceId: ws.id, pageId: tab.id, operationId,
|
|
1056
|
+
documentId: observation.documentId, controlGeneration: observation.controlGeneration,
|
|
1057
|
+
actions, timeoutMs, observeAfter });
|
|
1058
|
+
const op = ws.operations.get(operationId);
|
|
1059
|
+
return { observation, receipt:waitMs && op ? await this.waitReceipt(ws, op, waitMs) : receipt };
|
|
1060
|
+
}
|
|
1061
|
+
|
|
862
1062
|
actionDigest(params) {
|
|
863
1063
|
const {pageId,documentId,controlGeneration,actions,observeAfter,timeoutMs}=params;
|
|
864
1064
|
if(params[workflowOrigin]) return createHash('sha256').update(JSON.stringify(
|
|
@@ -939,7 +1139,7 @@ export class BrowserService {
|
|
|
939
1139
|
const run = this.enqueue(ws, () => params[workflowOrigin] ? performWorkflow(this,ws,tab,params,op,fail) :
|
|
940
1140
|
perform(this,ws,tab,params,op), op);
|
|
941
1141
|
ws.operations.set(operationId, op);
|
|
942
|
-
run.catch(error => {
|
|
1142
|
+
op.settled = run.catch(error => {
|
|
943
1143
|
if (['queued','running'].includes(receipt.state)) {
|
|
944
1144
|
receipt.state = op.cancel ? 'cancelled' : 'failed';
|
|
945
1145
|
receipt.phase = receipt.state;
|
|
@@ -949,9 +1149,23 @@ export class BrowserService {
|
|
|
949
1149
|
return { ...receipt };
|
|
950
1150
|
}
|
|
951
1151
|
|
|
1152
|
+
async waitReceipt(ws, op, waitMs) {
|
|
1153
|
+
if (waitMs && op.settled && ['queued','running'].includes(op.receipt.state)) {
|
|
1154
|
+
let timer;
|
|
1155
|
+
try {
|
|
1156
|
+
await Promise.race([op.settled, new Promise(resolve => { timer = setTimeout(resolve, waitMs); })]);
|
|
1157
|
+
} finally { clearTimeout(timer); }
|
|
1158
|
+
}
|
|
1159
|
+
return this.receiptView(ws, op);
|
|
1160
|
+
}
|
|
1161
|
+
|
|
952
1162
|
receiptView(ws, op) {
|
|
953
1163
|
const result = { ...op.receipt };
|
|
954
1164
|
const tab = ws.pages.get(op.pageId);
|
|
1165
|
+
const detail = tab?.actionObstruction;
|
|
1166
|
+
if (result.error === 'target_obscured' && detail?.operationId === result.operationId && ws.mode === 'agent' &&
|
|
1167
|
+
detail.controlGeneration === ws.generation && detail.documentId === tab.documentId &&
|
|
1168
|
+
detail.origin === allowedPageOrigin(ws,tab)) result.obstruction = detail.obstruction;
|
|
955
1169
|
const recent = tab?.actionObservation;
|
|
956
1170
|
if (recent?.operationId === op.receipt.operationId && ws.mode === 'agent' &&
|
|
957
1171
|
recent.generation === ws.generation && recent.documentId === tab.documentId && allowedPageOrigin(ws, tab))
|
|
@@ -960,6 +1174,7 @@ export class BrowserService {
|
|
|
960
1174
|
}
|
|
961
1175
|
|
|
962
1176
|
async desktopNavigate(ws, { pageId, action, url }, newTab) {
|
|
1177
|
+
if (ws.singleTab && (newTab || (url && !ws.origins.has(webOrigin(url))))) fail('single_tab_scope');
|
|
963
1178
|
const tab = newTab ? null : this.tab(ws, pageId);
|
|
964
1179
|
if (newTab) action = 'go';
|
|
965
1180
|
if (!['go', 'back', 'forward', 'reload'].includes(action) ||
|
|
@@ -994,7 +1209,7 @@ export class BrowserService {
|
|
|
994
1209
|
clearInterval(this.sweep);
|
|
995
1210
|
await Promise.all([...this.workspaces.values()].map(async ws => {
|
|
996
1211
|
await ws.finishing?.promise;
|
|
997
|
-
if (this.workspaces.has(ws.id)) await closeWorkspace(this, ws);
|
|
1212
|
+
if (this.workspaces.has(ws.id)) await closeWorkspace(this, ws, 'service_shutdown');
|
|
998
1213
|
}));
|
|
999
1214
|
if (this.protocol) await this.protocol.then(session => session.detach()).catch(() => {});
|
|
1000
1215
|
this.store.close();
|