@seekskyworld/open-browser 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Docs/open-browser-api.d.ts +13 -9
- package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +6 -6
- package/README.md +4 -4
- package/README.zh-CN.md +4 -4
- package/access-registry.mjs +8 -3
- package/action-execution.mjs +30 -5
- package/api-contract.mjs +6 -6
- package/browser-extension/manifest.json +1 -1
- package/browser-extension/newtab.js +1 -0
- package/browser-extension/phase-labels.js +1 -1
- package/browser-extension/popup.html +3 -1
- package/browser-extension/popup.js +33 -13
- package/browser-extension/tab-action.js +3 -2
- package/browser-extension/worker.js +3 -3
- package/capability-matrix.mjs +1 -1
- package/chromium-host.mjs +6 -10
- package/chromium-shell.mjs +2 -2
- package/cli.mjs +22 -22
- package/contract-validation.mjs +1 -1
- package/desktop/Info.plist +2 -2
- package/desktop/WorkspacePanel.m +3 -2
- package/desktop/build-macos.mjs +6 -3
- package/desktop/notarize-macos.mjs +54 -10
- package/desktop/sign.mjs +17 -2
- package/desktop/verify-macos-release.mjs +21 -13
- package/desktop/verify-version.mjs +22 -2
- package/engine-service.mjs +85 -26
- package/managed-input.mjs +22 -5
- package/mcp-http.mjs +9 -9
- package/mcp-server.mjs +23 -7
- package/mcp.mjs +1 -0
- package/package.json +6 -5
- package/page-activity.mjs +2 -1
- package/page-observation.mjs +4 -1
- package/receipt-store.mjs +17 -7
- package/runtime.mjs +2 -2
- package/sdk.mjs +24 -14
- package/service.mjs +36 -20
- package/skill-links.mjs +72 -18
- package/skills/open-browser/SKILL.md +8 -97
- package/skills/open-browser/references/macos.md +3 -0
- package/skills/open-browser/{SKILL.windows.md → references/operations.md} +7 -60
- 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 +77 -89
- package/skills/open-browser/scripts/guide.mjs +17 -0
- package/studio/studio.js +2 -2
- package/tab-adoption.mjs +9 -3
- package/tab-recovery.mjs +100 -0
- package/visual-page.mjs +17 -7
- package/workspace-lifecycle.mjs +18 -2
- package/workspace-state.mjs +57 -16
- package/skills/open-browser/SKILL.macos.md +0 -112
package/engine-service.mjs
CHANGED
|
@@ -59,9 +59,10 @@ const statusQueries = new Set(['getWorkspace', 'visualStatus', 'listDownloads',
|
|
|
59
59
|
|
|
60
60
|
export class BrowserService {
|
|
61
61
|
constructor(browser, { concurrency = 4, lowMemoryMiB = Number(process.env.OPEN_BROWSER_LOW_MEMORY_MIB || 0), idleTimeoutMs = 30 * 60_000, sharedContext, groupTab, onActivity, onActionTarget,
|
|
62
|
-
journalPath, releaseTab, setInputGuard, withAgentInput, inputGuardMode, readOnlyObserver = readDocumentSummary } = {}) {
|
|
62
|
+
journalPath, tabRecovery, releaseTab, setInputGuard, withAgentInput, inputGuardMode, readOnlyObserver = readDocumentSummary } = {}) {
|
|
63
63
|
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 16) fail('invalid_concurrency');
|
|
64
64
|
if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs <= 0) fail('invalid_idle_timeout');
|
|
65
|
+
this.tabRecovery = tabRecovery;
|
|
65
66
|
this.browser = browser;
|
|
66
67
|
this.sharedContext = sharedContext;
|
|
67
68
|
this.groupTab = groupTab;
|
|
@@ -94,12 +95,13 @@ export class BrowserService {
|
|
|
94
95
|
for (const ws of this.workspaces.values()) {
|
|
95
96
|
if (ws.mode === 'agent' && !ws.pending && !ws.finishing && ws.lastActiveAt <= cutoff &&
|
|
96
97
|
!ws.credentialRequests.size && ![...ws.pages.values()].some(tab => tab.needsSubmissionReview))
|
|
97
|
-
void closeWorkspace(this, ws).catch(() => {});
|
|
98
|
+
void closeWorkspace(this, ws, 'idle_timeout').catch(() => {});
|
|
98
99
|
}
|
|
99
100
|
}, Math.min(60_000, idleTimeoutMs)).unref();
|
|
100
101
|
}
|
|
101
102
|
|
|
102
103
|
notify(ws) {
|
|
104
|
+
if (!this.stopped) this.tabRecovery?.refresh(ws);
|
|
103
105
|
if (ws.mode === 'agent' || ws.mode === 'closed' || ws.finishing) {
|
|
104
106
|
for (const resume of ws.controlWaiters || []) resume();
|
|
105
107
|
}
|
|
@@ -185,13 +187,18 @@ export class BrowserService {
|
|
|
185
187
|
const {records, nextObjectCursor} = this.store.recoveryObjects(clientId, params.workspaceId, params.objectsAfter, params.limit);
|
|
186
188
|
if (!ws && !records.length && !operations.length && !this.store.events(clientId,params.workspaceId,0,1).events.length)
|
|
187
189
|
fail('workspace_not_found');
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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
|
+
});
|
|
193
199
|
return {
|
|
194
200
|
workspaceId:params.workspaceId, mode:ws?.mode ?? 'unavailable', pages,
|
|
201
|
+
...(!ws && {closeReason}),
|
|
195
202
|
deliveries:records.filter(row => row.kind === 'download').map(row => ({downloadId:row.id})),
|
|
196
203
|
outputs:records.filter(row => row.kind === 'output').map(row => ({outputId:row.id})),
|
|
197
204
|
operations:operations.map(receipt => ({...receipt, next:
|
|
@@ -242,6 +249,14 @@ export class BrowserService {
|
|
|
242
249
|
for (const row of [...data.nodes, ...data.edges, ...data.messages, ...data.attachments]) {
|
|
243
250
|
for (const field of ['id','label','text','source','target']) if (field in row) row[field] = redact(ws, row[field]);
|
|
244
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
|
+
}
|
|
245
260
|
const snapshotVersion = createHash('sha256').update(JSON.stringify([documentId,controlGeneration,data])).digest('hex');
|
|
246
261
|
return {workspaceId:ws.id,pageId:tab.id,documentId,controlGeneration,snapshotVersion,...data};
|
|
247
262
|
}, {kind:'canvasSnapshot', pageId:params.pageId});
|
|
@@ -257,11 +272,7 @@ export class BrowserService {
|
|
|
257
272
|
ws.controlWaiters.add(resume);
|
|
258
273
|
});
|
|
259
274
|
}
|
|
260
|
-
return this.
|
|
261
|
-
const tab = this.tab(ws, params.pageId);
|
|
262
|
-
if (this.groupTab && tab.syncedGeneration !== ws.generation) await this.syncTab(ws, tab);
|
|
263
|
-
return this.observe(ws, tab);
|
|
264
|
-
}, {kind:'observe', pageId:params.pageId});
|
|
275
|
+
return this.refreshBoundPage(ws, params.pageId);
|
|
265
276
|
}
|
|
266
277
|
case 'listUploads': return ws.uploads.list();
|
|
267
278
|
case 'grantUpload': {
|
|
@@ -291,7 +302,21 @@ export class BrowserService {
|
|
|
291
302
|
this.store.remember(ws.owner, ws.id, 'output', result.output.id);
|
|
292
303
|
return result;
|
|
293
304
|
}
|
|
294
|
-
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
|
+
}
|
|
295
320
|
case 'grantOrigin': {
|
|
296
321
|
if (ws.singleTab) fail('single_tab_scope');
|
|
297
322
|
if (params.controlGeneration !== ws.generation || !['agent', 'human'].includes(ws.mode)) fail('stale_control');
|
|
@@ -374,13 +399,23 @@ export class BrowserService {
|
|
|
374
399
|
if (op.receipt.state === 'queued') op.receipt.state = 'cancelled';
|
|
375
400
|
this.notify(ws);
|
|
376
401
|
}
|
|
377
|
-
return this.
|
|
402
|
+
return this.waitReceipt(ws, op, params.waitMs);
|
|
378
403
|
}
|
|
379
404
|
case 'handOff':
|
|
380
405
|
case 'takeControl': return this.handOff(ws, params.pageId, true, params.controlGeneration);
|
|
381
|
-
case 'returnToAgent':
|
|
406
|
+
case 'returnToAgent': {
|
|
382
407
|
if (params.pageId !== undefined) this.tab(ws, params.pageId);
|
|
383
|
-
|
|
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
|
+
}
|
|
384
419
|
case 'closeWorkspace':
|
|
385
420
|
if (ws.mode !== 'agent') fail('workspace_under_user_control');
|
|
386
421
|
await closeWorkspace(this, ws);
|
|
@@ -389,7 +424,7 @@ export class BrowserService {
|
|
|
389
424
|
}
|
|
390
425
|
}
|
|
391
426
|
|
|
392
|
-
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()) {
|
|
393
428
|
if (profileId !== undefined && profileId !== serviceProfileId) fail('profile_mismatch');
|
|
394
429
|
if (typeof name !== 'string' || !name.trim()) fail('task_name_required');
|
|
395
430
|
if (name.length > 120 || !Array.isArray(allowedOrigins)
|
|
@@ -405,7 +440,7 @@ export class BrowserService {
|
|
|
405
440
|
const { context, browserContextId } = this.sharedContext
|
|
406
441
|
? { context: this.sharedContext } : await this.allocateContext();
|
|
407
442
|
try {
|
|
408
|
-
const ws = { id:
|
|
443
|
+
const ws = { id: workspaceId, owner, name, agentName: displayName, context, browserContextId, origins, networkMode, mode: 'agent',
|
|
409
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(),
|
|
410
445
|
tail: Promise.resolve(), lanes: new Map(), pending: 0, handoff: null, lastActiveAt: Date.now(),
|
|
411
446
|
inputTail: Promise.resolve(), inputPending: 0,
|
|
@@ -441,7 +476,7 @@ export class BrowserService {
|
|
|
441
476
|
} catch (error) {
|
|
442
477
|
// A takeover can happen while the first page is being opened. The
|
|
443
478
|
// workspace and any opened tab then belong to the person taking control.
|
|
444
|
-
if (ws.mode === 'agent' && !ws.finishing) await closeWorkspace(this, ws).catch(() => {});
|
|
479
|
+
if (ws.mode === 'agent' && !ws.finishing) await closeWorkspace(this, ws, 'open_failed').catch(() => {});
|
|
445
480
|
throw error;
|
|
446
481
|
}
|
|
447
482
|
}
|
|
@@ -469,6 +504,15 @@ export class BrowserService {
|
|
|
469
504
|
|
|
470
505
|
routeWorkspace(target, ws) { return routeWorkspace(target, ws, !!this.sharedContext); }
|
|
471
506
|
|
|
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
|
+
|
|
472
516
|
async syncTab(ws, tab) {
|
|
473
517
|
if (!this.groupTab) return;
|
|
474
518
|
const generation = ws.generation;
|
|
@@ -482,15 +526,15 @@ export class BrowserService {
|
|
|
482
526
|
}
|
|
483
527
|
}
|
|
484
528
|
|
|
485
|
-
register(ws, page) {
|
|
529
|
+
register(ws, page, pageId = randomUUID()) {
|
|
486
530
|
ws.everRegistered = true;
|
|
487
531
|
const existing = [...ws.pages.values()].find(tab => tab.page === page);
|
|
488
532
|
if (existing) return existing;
|
|
489
|
-
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: '',
|
|
490
534
|
heldKeys: new Set(), heldButtons: new Set() };
|
|
491
535
|
tab.extensionSync = !!this.groupTab;
|
|
492
536
|
ws.securityChallenge = null;
|
|
493
|
-
this.store.remember(ws.owner, ws.id, 'page', tab.id);
|
|
537
|
+
this.store.remember(ws.owner, ws.id, 'page', tab.id, {origin: ws.singleTab ? allowedPageOrigin(ws, tab) : null});
|
|
494
538
|
ws.pages.set(tab.id, tab);
|
|
495
539
|
const releaseDialogs = attachDialogs(ws,tab,()=>{
|
|
496
540
|
const info=tab.dialog.info;
|
|
@@ -1002,7 +1046,7 @@ export class BrowserService {
|
|
|
1002
1046
|
|
|
1003
1047
|
async observeAndAct(ws, params) {
|
|
1004
1048
|
const tab = this.tab(ws, params.pageId);
|
|
1005
|
-
const { workspaceId, pageId, operationId, actions, timeoutMs, observeAfter,
|
|
1049
|
+
const { workspaceId, pageId, operationId, actions, timeoutMs, observeAfter, waitMs,
|
|
1006
1050
|
documentId, controlGeneration, ...observeParams } = params;
|
|
1007
1051
|
if (workspaceId !== ws.id || documentId !== undefined || controlGeneration !== undefined)
|
|
1008
1052
|
fail('invalid_params');
|
|
@@ -1011,7 +1055,8 @@ export class BrowserService {
|
|
|
1011
1055
|
const receipt = this.act(ws, { workspaceId: ws.id, pageId: tab.id, operationId,
|
|
1012
1056
|
documentId: observation.documentId, controlGeneration: observation.controlGeneration,
|
|
1013
1057
|
actions, timeoutMs, observeAfter });
|
|
1014
|
-
|
|
1058
|
+
const op = ws.operations.get(operationId);
|
|
1059
|
+
return { observation, receipt:waitMs && op ? await this.waitReceipt(ws, op, waitMs) : receipt };
|
|
1015
1060
|
}
|
|
1016
1061
|
|
|
1017
1062
|
actionDigest(params) {
|
|
@@ -1094,7 +1139,7 @@ export class BrowserService {
|
|
|
1094
1139
|
const run = this.enqueue(ws, () => params[workflowOrigin] ? performWorkflow(this,ws,tab,params,op,fail) :
|
|
1095
1140
|
perform(this,ws,tab,params,op), op);
|
|
1096
1141
|
ws.operations.set(operationId, op);
|
|
1097
|
-
run.catch(error => {
|
|
1142
|
+
op.settled = run.catch(error => {
|
|
1098
1143
|
if (['queued','running'].includes(receipt.state)) {
|
|
1099
1144
|
receipt.state = op.cancel ? 'cancelled' : 'failed';
|
|
1100
1145
|
receipt.phase = receipt.state;
|
|
@@ -1104,9 +1149,23 @@ export class BrowserService {
|
|
|
1104
1149
|
return { ...receipt };
|
|
1105
1150
|
}
|
|
1106
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
|
+
|
|
1107
1162
|
receiptView(ws, op) {
|
|
1108
1163
|
const result = { ...op.receipt };
|
|
1109
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;
|
|
1110
1169
|
const recent = tab?.actionObservation;
|
|
1111
1170
|
if (recent?.operationId === op.receipt.operationId && ws.mode === 'agent' &&
|
|
1112
1171
|
recent.generation === ws.generation && recent.documentId === tab.documentId && allowedPageOrigin(ws, tab))
|
|
@@ -1150,7 +1209,7 @@ export class BrowserService {
|
|
|
1150
1209
|
clearInterval(this.sweep);
|
|
1151
1210
|
await Promise.all([...this.workspaces.values()].map(async ws => {
|
|
1152
1211
|
await ws.finishing?.promise;
|
|
1153
|
-
if (this.workspaces.has(ws.id)) await closeWorkspace(this, ws);
|
|
1212
|
+
if (this.workspaces.has(ws.id)) await closeWorkspace(this, ws, 'service_shutdown');
|
|
1154
1213
|
}));
|
|
1155
1214
|
if (this.protocol) await this.protocol.then(session => session.detach()).catch(() => {});
|
|
1156
1215
|
this.store.close();
|
package/managed-input.mjs
CHANGED
|
@@ -11,7 +11,7 @@ const fallbackSource = `(() => {
|
|
|
11
11
|
if (current) { current.enabled = true; return; }
|
|
12
12
|
const state = { enabled: true };
|
|
13
13
|
const block = event => {
|
|
14
|
-
if (!state.enabled) return;
|
|
14
|
+
if (!state.enabled || !event.isTrusted) return;
|
|
15
15
|
event.preventDefault();
|
|
16
16
|
event.stopImmediatePropagation();
|
|
17
17
|
};
|
|
@@ -27,10 +27,27 @@ function fallbackExpression(enabled) {
|
|
|
27
27
|
}
|
|
28
28
|
|
|
29
29
|
async function setFallbackState(page, enabled) {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
//
|
|
33
|
-
|
|
30
|
+
if (page.isClosed()) return;
|
|
31
|
+
let lastError;
|
|
32
|
+
// A handoff can coincide with a renderer navigation. Do not silently report
|
|
33
|
+
// human control before the page-level listener has actually been disabled.
|
|
34
|
+
// Retry the current execution context briefly, then let the lifecycle roll
|
|
35
|
+
// back to a safe state if the page remains unavailable.
|
|
36
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
37
|
+
try {
|
|
38
|
+
// Init scripts cannot be removed from a Playwright page. Append a small
|
|
39
|
+
// state update so a later navigation preserves the handoff decision.
|
|
40
|
+
await page.addInitScript({ content: fallbackExpression(enabled) });
|
|
41
|
+
await page.evaluate(fallbackExpression(enabled));
|
|
42
|
+
const state = await page.evaluate(() => globalThis.__openBrowserInputGuard?.enabled);
|
|
43
|
+
if (state === enabled) return;
|
|
44
|
+
lastError = Error('Input guard state was not applied');
|
|
45
|
+
} catch (error) {
|
|
46
|
+
lastError = error;
|
|
47
|
+
}
|
|
48
|
+
if (!page.isClosed()) await new Promise(resolve => setTimeout(resolve, 25 * (attempt + 1)));
|
|
49
|
+
}
|
|
50
|
+
if (!page.isClosed()) throw lastError || Error('Input guard state was not applied');
|
|
34
51
|
}
|
|
35
52
|
|
|
36
53
|
export function managedInput(context, onBlocked, { allowFallback = false, forceFallback = false } = {}) {
|
package/mcp-http.mjs
CHANGED
|
@@ -26,8 +26,8 @@ async function readBody(req) {
|
|
|
26
26
|
if (bytes > 1024 * 1024) throw new Error('request_too_large');
|
|
27
27
|
chunks.push(chunk);
|
|
28
28
|
}
|
|
29
|
-
if (!
|
|
30
|
-
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
29
|
+
if (!bytes) return undefined;
|
|
30
|
+
return JSON.parse(Buffer.concat(chunks, bytes).toString('utf8'));
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
const sessions = new Map();
|
|
@@ -44,7 +44,6 @@ const server = createServer(async (req, res) => {
|
|
|
44
44
|
const session = sessions.get(sessionId);
|
|
45
45
|
if (!session) { res.writeHead(404).end(); return; }
|
|
46
46
|
sessions.delete(sessionId);
|
|
47
|
-
await session.transport.close().catch(() => {});
|
|
48
47
|
await session.mcp.close().catch(() => {});
|
|
49
48
|
res.writeHead(204).end();
|
|
50
49
|
return;
|
|
@@ -62,14 +61,16 @@ const server = createServer(async (req, res) => {
|
|
|
62
61
|
return;
|
|
63
62
|
}
|
|
64
63
|
const mcp = createMcpServer();
|
|
65
|
-
const transport = new StreamableHTTPServerTransport({
|
|
64
|
+
const transport = new StreamableHTTPServerTransport({
|
|
65
|
+
sessionIdGenerator: () => randomUUID(),
|
|
66
|
+
onsessioninitialized: id => { sessions.set(id, session); },
|
|
67
|
+
});
|
|
66
68
|
session = { mcp, transport };
|
|
67
69
|
transport.onclose = () => { if (transport.sessionId) sessions.delete(transport.sessionId); };
|
|
68
70
|
await mcp.connect(transport);
|
|
69
71
|
}
|
|
70
72
|
try {
|
|
71
73
|
await session.transport.handleRequest(req, res, body);
|
|
72
|
-
if (session.transport.sessionId) sessions.set(session.transport.sessionId, session);
|
|
73
74
|
} catch (error) {
|
|
74
75
|
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'mcp_server_error' }));
|
|
75
76
|
}
|
|
@@ -77,8 +78,7 @@ const server = createServer(async (req, res) => {
|
|
|
77
78
|
|
|
78
79
|
server.listen(port, host, () => console.error(`open-browser MCP HTTP listening on http://${host}:${port}/mcp`));
|
|
79
80
|
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
})).finally(() => server.close(() => process.exit(0)));
|
|
81
|
+
server.close();
|
|
82
|
+
void Promise.allSettled([...sessions.values()].map(session => session.mcp.close()))
|
|
83
|
+
.finally(() => { server.closeAllConnections(); });
|
|
84
84
|
});
|
package/mcp-server.mjs
CHANGED
|
@@ -1,13 +1,22 @@
|
|
|
1
|
+
import { Agent } from 'node:http';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
1
3
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
4
|
import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
3
5
|
import { checkAgentRequest } from './contract-validation.mjs';
|
|
4
6
|
import { OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
|
|
5
7
|
import { tools } from './api-contract.mjs';
|
|
6
8
|
|
|
9
|
+
const {version} = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
|
|
10
|
+
|
|
7
11
|
export function createMcpServer() {
|
|
8
|
-
const server = new Server({ name: 'open-browser', version
|
|
12
|
+
const server = new Server({ name: 'open-browser', version }, { capabilities: { tools: {} } });
|
|
13
|
+
let api;
|
|
14
|
+
server.onclose = () => {
|
|
15
|
+
api?.close();
|
|
16
|
+
api = undefined;
|
|
17
|
+
};
|
|
9
18
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
10
|
-
server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
|
|
19
|
+
server.setRequestHandler(CallToolRequestSchema, async ({ params }, { signal }) => {
|
|
11
20
|
let args;
|
|
12
21
|
try {
|
|
13
22
|
const arguments_ = params.arguments ?? {};
|
|
@@ -20,11 +29,18 @@ export function createMcpServer() {
|
|
|
20
29
|
throw new McpError(ErrorCode.InvalidParams, 'Invalid open-browser tool name or arguments');
|
|
21
30
|
}
|
|
22
31
|
try {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
32
|
+
if (!api) {
|
|
33
|
+
const client = server.getClientVersion();
|
|
34
|
+
const clientName = client?.title?.trim() || client?.name?.trim() || 'MCP';
|
|
35
|
+
// Bound idle sockets only. A query or cancellation must be able to
|
|
36
|
+
// reach the service while long-running calls hold their connections.
|
|
37
|
+
api = new OpenBrowserClient({
|
|
38
|
+
agent: new Agent({ keepAlive:true, maxFreeSockets:4 }),
|
|
39
|
+
agentName: process.env.OPEN_BROWSER_AGENT_NAME?.trim() || Array.from(clientName).slice(0, 80).join(''),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const result = params.name === 'capabilities'
|
|
43
|
+
? await api.capabilities({signal}) : await api.call(params.name, args, {signal});
|
|
28
44
|
if (params.name === 'captureVisual') {
|
|
29
45
|
const { data, mimeType, ...geometry } = result;
|
|
30
46
|
return { content: [{ type: 'image', mimeType, data }, { type: 'text', text: JSON.stringify(geometry) }] };
|
package/mcp.mjs
CHANGED
|
@@ -3,3 +3,4 @@ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
|
3
3
|
import { createMcpServer } from './mcp-server.mjs';
|
|
4
4
|
const server = createMcpServer();
|
|
5
5
|
await server.connect(new StdioServerTransport());
|
|
6
|
+
process.stdin.once('end', () => { void server.close(); });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seekskyworld/open-browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
"open-browser": "cli.mjs",
|
|
20
20
|
"open-browser-mcp": "mcp.mjs",
|
|
21
21
|
"open-browser-mcp-http": "mcp-http.mjs",
|
|
22
|
-
"open-browser-skill": "skills/open-browser/scripts/
|
|
22
|
+
"open-browser-skill": "skills/open-browser/scripts/bootstrap.mjs"
|
|
23
23
|
},
|
|
24
24
|
"exports": {
|
|
25
25
|
".": "./sdk.mjs",
|
|
@@ -42,14 +42,15 @@
|
|
|
42
42
|
"build:stable": "node desktop/build-profile.mjs stable",
|
|
43
43
|
"build:macos:x64": "node desktop/build-macos.mjs --arch x64",
|
|
44
44
|
"build:macos:arm64": "node desktop/build-macos.mjs --arch arm64",
|
|
45
|
-
"build:release-macos": "npm run build:stable && node desktop/notarize-macos.mjs",
|
|
46
|
-
"build:release-macos:x64": "npm run build:macos:x64 && node desktop/notarize-macos.mjs dist/open-browser-x64.app --zip dist/open-browser-macos-x64.zip",
|
|
47
|
-
"build:release-macos:arm64": "npm run build:macos:arm64 && node desktop/notarize-macos.mjs dist/open-browser.app --zip dist/open-browser-macos-arm64.zip",
|
|
45
|
+
"build:release-macos": "npm run build:stable && node desktop/notarize-macos.mjs --zip dist/open-browser-macos-arm64.zip --dmg dist/open-browser-macos-arm64.dmg",
|
|
46
|
+
"build:release-macos:x64": "npm run build:macos:x64 && node desktop/notarize-macos.mjs dist/open-browser-x64.app --zip dist/open-browser-macos-x64.zip --dmg dist/open-browser-macos-x64.dmg",
|
|
47
|
+
"build:release-macos:arm64": "npm run build:macos:arm64 && node desktop/notarize-macos.mjs dist/open-browser.app --zip dist/open-browser-macos-arm64.zip --dmg dist/open-browser-macos-arm64.dmg",
|
|
48
48
|
"release:verify-macos": "node desktop/verify-macos-release.mjs",
|
|
49
49
|
"cli": "node cli.mjs",
|
|
50
50
|
"mcp": "node mcp.mjs",
|
|
51
51
|
"mcp:http": "node mcp-http.mjs",
|
|
52
52
|
"package:check": "npm pack --dry-run",
|
|
53
|
+
"prepack": "node desktop/verify-version.mjs",
|
|
53
54
|
"browser:install": "node runtime.mjs",
|
|
54
55
|
"control": "node control.mjs",
|
|
55
56
|
"test": "npm run test:unit",
|
package/page-activity.mjs
CHANGED
|
@@ -159,7 +159,8 @@ export function pageActivity() {
|
|
|
159
159
|
} finally { await tab.session.detach().catch(() => {}); }
|
|
160
160
|
},
|
|
161
161
|
update({ workspaceId, pages, mode, activity, controlGeneration }) {
|
|
162
|
-
const running = new Set((activity.running || [activity.current]).filter(job => mode === 'agent' && job?.state === 'running'
|
|
162
|
+
const running = new Set((activity.running || [activity.current]).filter(job => mode === 'agent' && job?.state === 'running' &&
|
|
163
|
+
job.kind !== 'captureVisual' && (job.kind !== 'act' || (job.stepKind && job.stepKind !== 'spatial'))).map(job => job.pageId));
|
|
163
164
|
for (const [id, tab] of tabs) {
|
|
164
165
|
if (tab.workspaceId !== workspaceId) continue;
|
|
165
166
|
const previous = tab.generation;
|
package/page-observation.mjs
CHANGED
|
@@ -101,7 +101,10 @@ export function inspectDocument(options = {}) {
|
|
|
101
101
|
text:label(el)
|
|
102
102
|
}));
|
|
103
103
|
const attachments = rows('a[download]', el => ({label:label(el)}));
|
|
104
|
-
|
|
104
|
+
const adapter = root.querySelector('.react-flow') ? 'react-flow' : messages.length ? 'chat' : 'unsupported';
|
|
105
|
+
const reason = adapter === 'unsupported' && ([...root.querySelectorAll('canvas')].some(visible)
|
|
106
|
+
? 'canvas_without_semantic_adapter' : 'no_supported_markup');
|
|
107
|
+
return {adapter, ...(reason && {reason}),
|
|
105
108
|
nodes:nodeRows, edges, messages, attachments, truncated};
|
|
106
109
|
}
|
|
107
110
|
const nodes=[],details=[];
|
package/receipt-store.mjs
CHANGED
|
@@ -28,6 +28,7 @@ export class ReceiptStore {
|
|
|
28
28
|
inflight INTEGER NOT NULL, expires INTEGER NOT NULL, PRIMARY KEY(owner,workspace,operation));
|
|
29
29
|
CREATE TABLE IF NOT EXISTS recovery_objects (
|
|
30
30
|
owner TEXT NOT NULL, workspace TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, expires INTEGER NOT NULL,
|
|
31
|
+
origin TEXT,
|
|
31
32
|
PRIMARY KEY(owner,workspace,kind,id));
|
|
32
33
|
CREATE INDEX IF NOT EXISTS recovery_expiry ON recovery_objects(expires);
|
|
33
34
|
CREATE INDEX IF NOT EXISTS receipt_expiry ON receipts(expires);
|
|
@@ -38,6 +39,8 @@ export class ReceiptStore {
|
|
|
38
39
|
CREATE INDEX IF NOT EXISTS event_expiry ON events(expires);`);
|
|
39
40
|
if (!this.db.prepare('PRAGMA table_info(recovery_objects)').all().some(field => field.name === 'disposition'))
|
|
40
41
|
this.db.exec('ALTER TABLE recovery_objects ADD COLUMN disposition TEXT');
|
|
42
|
+
if (!this.db.prepare('PRAGMA table_info(recovery_objects)').all().some(field => field.name === 'origin'))
|
|
43
|
+
this.db.exec('ALTER TABLE recovery_objects ADD COLUMN origin TEXT');
|
|
41
44
|
this.sweep = this.db.prepare('DELETE FROM receipts WHERE expires <= ?');
|
|
42
45
|
this.sweepRecovery = this.db.prepare('DELETE FROM recovery_objects WHERE expires<=?');
|
|
43
46
|
this.sweepRecovery.run(Date.now());
|
|
@@ -62,9 +65,9 @@ export class ReceiptStore {
|
|
|
62
65
|
}
|
|
63
66
|
}
|
|
64
67
|
|
|
65
|
-
remember(owner, workspace, kind, id) {
|
|
66
|
-
this.db.prepare('INSERT OR REPLACE INTO recovery_objects(owner,workspace,kind,id,expires) VALUES (
|
|
67
|
-
.run(owner, workspace, kind, id, Date.now() + retentionMs);
|
|
68
|
+
remember(owner, workspace, kind, id, {origin = null} = {}) {
|
|
69
|
+
this.db.prepare('INSERT OR REPLACE INTO recovery_objects(owner,workspace,kind,id,expires,origin) VALUES (?,?,?,?,?,?)')
|
|
70
|
+
.run(owner, workspace, kind, id, Date.now() + retentionMs, origin);
|
|
68
71
|
}
|
|
69
72
|
|
|
70
73
|
pageDisposition(owner, workspace, id, disposition) {
|
|
@@ -72,10 +75,16 @@ export class ReceiptStore {
|
|
|
72
75
|
.run(disposition, owner, workspace, id);
|
|
73
76
|
}
|
|
74
77
|
|
|
78
|
+
closeReason(owner, workspace) {
|
|
79
|
+
const row = this.db.prepare("SELECT state FROM events WHERE owner=? AND workspace=? AND kind='workspace_end' AND expires>? ORDER BY sequence DESC LIMIT 1")
|
|
80
|
+
.get(owner, workspace, Date.now());
|
|
81
|
+
return row?.state ?? 'unknown';
|
|
82
|
+
}
|
|
83
|
+
|
|
75
84
|
recoveryObjects(owner, workspace, after = 0, limit = 50) {
|
|
76
85
|
if (!Number.isSafeInteger(after) || after < 0) throw Object.assign(new Error('invalid_params'), {code:'invalid_params'});
|
|
77
86
|
// ReceiptStore.list has already validated the common limit.
|
|
78
|
-
const rows = this.db.prepare('SELECT rowid,kind,id,disposition FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
|
|
87
|
+
const rows = this.db.prepare('SELECT rowid,kind,id,disposition,origin FROM recovery_objects WHERE owner=? AND workspace=? AND expires>? AND rowid>? ORDER BY rowid LIMIT ?')
|
|
79
88
|
.all(owner, workspace, Date.now(), after, limit + 1);
|
|
80
89
|
return {records:rows.slice(0,limit), nextObjectCursor:rows.length > limit ? rows[limit-1].rowid : null};
|
|
81
90
|
}
|
|
@@ -138,15 +147,16 @@ export class ReceiptStore {
|
|
|
138
147
|
|
|
139
148
|
waitForEvent(owner,{workspaceId,pageId,operationId,kind,after,timeoutMs=5000}) {
|
|
140
149
|
if (!Number.isSafeInteger(after) || after<0 || !Number.isSafeInteger(timeoutMs) || timeoutMs<1 || timeoutMs>10000 ||
|
|
141
|
-
!['dialog','popup','download'].includes(kind) ||
|
|
150
|
+
(!['dialog','popup','download','page_bound'].includes(kind)) ||
|
|
151
|
+
(typeof pageId!=='string' && !(kind==='page_bound' && pageId===undefined)) ||
|
|
142
152
|
(operationId!==undefined && typeof operationId!=='string'))
|
|
143
153
|
throw Object.assign(new Error('invalid_params'),{code:'invalid_params'});
|
|
144
154
|
const sql=`SELECT sequence,kind,state,pageId,resourceId,operationId FROM events
|
|
145
|
-
WHERE owner=? AND workspace=? AND pageId=? AND kind=? AND sequence>? AND expires>?
|
|
155
|
+
WHERE owner=? AND workspace=? AND (? IS NULL OR pageId=?) AND kind=? AND sequence>? AND expires>?
|
|
146
156
|
AND (? IS NULL OR operationId=?) ORDER BY sequence LIMIT 1`;
|
|
147
157
|
const query=this.db.prepare(sql);
|
|
148
158
|
const read=()=>{
|
|
149
|
-
const row=query.get(owner,workspaceId,pageId,kind,after,Date.now(),operationId??null,operationId??null);
|
|
159
|
+
const row=query.get(owner,workspaceId,pageId??null,pageId??null,kind,after,Date.now(),operationId??null,operationId??null);
|
|
150
160
|
if (row?.operationId===null) delete row.operationId;
|
|
151
161
|
return row && {event:row,nextCursor:row.sequence};
|
|
152
162
|
};
|
package/runtime.mjs
CHANGED
|
@@ -30,8 +30,8 @@ export async function engineExecutable() {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
async function install() {
|
|
33
|
-
if (process.platform === 'darwin' && targetArch !== process.arch)
|
|
34
|
-
throw new Error(`当前 Node 是 ${process.arch},不能下载并登记 ${targetArch} 引擎。请在对应架构的 macOS 或 Rosetta x64 Node 下运行。`);
|
|
33
|
+
if (process.platform === 'darwin' && targetArch() !== process.arch)
|
|
34
|
+
throw new Error(`当前 Node 是 ${process.arch},不能下载并登记 ${targetArch()} 引擎。请在对应架构的 macOS 或 Rosetta x64 Node 下运行。`);
|
|
35
35
|
process.env.PLAYWRIGHT_BROWSERS_PATH = engineDir;
|
|
36
36
|
const cli = path.join(path.dirname(require.resolve('playwright-core/package.json')), 'cli.js');
|
|
37
37
|
execFileSync(process.execPath, [cli, 'install', 'chromium', '--no-shell'], { stdio: 'inherit' });
|