@seekskyworld/open-browser 0.2.0 → 0.3.1
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/CONTRIBUTING.md +2 -0
- package/Docs/desktop-packages.md +45 -0
- 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 +11 -9
- package/README.zh-CN.md +6 -4
- package/access-registry.mjs +8 -3
- package/action-execution.mjs +30 -5
- package/api-contract.mjs +8 -7
- package/browser-extension/_locales/en/messages.json +8 -0
- package/browser-extension/_locales/zh_CN/messages.json +8 -0
- package/browser-extension/i18n.js +84 -0
- package/browser-extension/manifest.json +5 -4
- package/browser-extension/messages.js +266 -0
- package/browser-extension/newtab.css +4 -0
- package/browser-extension/newtab.html +9 -9
- package/browser-extension/newtab.js +38 -35
- package/browser-extension/page-locale.js +23 -0
- package/browser-extension/phase-labels.js +33 -6
- package/browser-extension/popup.css +2 -2
- package/browser-extension/popup.html +25 -25
- package/browser-extension/popup.js +102 -59
- package/browser-extension/tab-action.js +31 -25
- package/browser-extension/worker.js +31 -7
- package/browser-extension/workspace-title.js +2 -2
- package/build-profile.mjs +10 -2
- package/capability-matrix.mjs +1 -1
- package/chromium-host.mjs +26 -19
- package/chromium-shell.mjs +7 -5
- package/cli.mjs +51 -48
- package/contract-validation.mjs +1 -1
- package/control.mjs +9 -8
- package/desktop/Info.plist +4 -2
- package/desktop/Launcher.m +10 -2
- package/desktop/OBControlBar.m +12 -8
- package/desktop/OBLocalization.h +20 -0
- package/desktop/OBPageView.m +2 -1
- package/desktop/WorkspacePanel.m +85 -83
- package/desktop/archive-release.py +5 -1
- package/desktop/build-macos.mjs +17 -8
- package/desktop/build-managed-input.mjs +2 -1
- package/desktop/build-portable.mjs +5 -3
- package/desktop/build-profile.mjs +2 -1
- package/desktop/build.mjs +2 -1
- package/desktop/create-shortcut.ps1 +7 -1
- package/desktop/en.lproj/Localizable.strings +106 -0
- package/desktop/install-menu-entry.mjs +2 -0
- package/desktop/notarize-macos.mjs +70 -29
- package/desktop/package-macos.mjs +4 -3
- package/desktop/sign.mjs +22 -6
- package/desktop/start-profile.mjs +2 -1
- package/desktop/start.mjs +3 -1
- package/desktop/verify-macos-release.mjs +27 -18
- package/desktop/verify-version.mjs +22 -2
- package/desktop/zh-Hans.lproj/Localizable.strings +106 -0
- package/engine-service.mjs +86 -27
- package/hosted/cli.mjs +2 -1
- package/hosted/init.mjs +2 -1
- package/i18n.mjs +41 -0
- package/managed-input.mjs +22 -5
- package/mcp-http.mjs +12 -11
- package/mcp-server.mjs +27 -10
- package/mcp.mjs +1 -0
- package/messages.zh-CN.mjs +175 -0
- package/package.json +9 -5
- package/page-activity.mjs +10 -7
- package/page-observation.mjs +4 -1
- package/paths.mjs +2 -5
- package/receipt-store.mjs +17 -7
- package/runtime.mjs +5 -4
- package/sdk.mjs +57 -46
- package/service.mjs +38 -21
- package/skill-links.mjs +72 -18
- package/skills/open-browser/SKILL.md +10 -97
- package/skills/open-browser/SKILL.zh-CN.md +22 -0
- package/skills/open-browser/references/macos.en.md +3 -0
- package/skills/open-browser/references/macos.md +5 -0
- package/skills/open-browser/references/operations.en.md +54 -0
- package/skills/open-browser/{SKILL.windows.md → references/operations.md} +8 -59
- package/skills/open-browser/references/recovery.en.md +36 -0
- package/skills/open-browser/references/recovery.md +38 -0
- package/skills/open-browser/references/windows.en.md +3 -0
- package/skills/open-browser/references/windows.md +5 -0
- package/skills/open-browser/scripts/bootstrap.mjs +80 -90
- package/skills/open-browser/scripts/guide.mjs +20 -0
- package/skills/open-browser/scripts/open-browser +5 -1
- package/studio/demo-site.mjs +5 -4
- package/studio/index.html +37 -33
- package/studio/index.mjs +10 -3
- package/studio/native-demo.mjs +8 -7
- package/studio/studio.css +3 -0
- package/studio/studio.js +99 -69
- package/system-i18n.mjs +19 -0
- 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
|
}
|
|
@@ -134,7 +136,7 @@ export class BrowserService {
|
|
|
134
136
|
}
|
|
135
137
|
}
|
|
136
138
|
|
|
137
|
-
notifyTarget(ws, tab, el, documentId, controlGeneration, origin, actionKind = '
|
|
139
|
+
notifyTarget(ws, tab, el, documentId, controlGeneration, origin, actionKind = 'action') {
|
|
138
140
|
if (!this.onActionTarget) return;
|
|
139
141
|
const ticket = Symbol();
|
|
140
142
|
tab.latestTarget = ticket;
|
|
@@ -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/hosted/cli.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t } from "../i18n.mjs";
|
|
1
2
|
import path from 'node:path';
|
|
2
3
|
import { localRequest } from '../sdk.mjs';
|
|
3
4
|
|
|
@@ -5,7 +6,7 @@ try {
|
|
|
5
6
|
const method = process.argv[2];
|
|
6
7
|
const home = process.env.OPEN_BROWSER_HOSTED_DIR;
|
|
7
8
|
const token = process.env.OPEN_BROWSER_HOSTED_TOKEN_FILE;
|
|
8
|
-
if (!method || !home || !token) throw new Error(
|
|
9
|
+
if (!method || !home || !token) throw new Error(t("Set OPEN_BROWSER_HOSTED_DIR and OPEN_BROWSER_HOSTED_TOKEN_FILE, then specify a method."));
|
|
9
10
|
let input = '';
|
|
10
11
|
if (!process.stdin.isTTY) {
|
|
11
12
|
process.stdin.setEncoding('utf8');
|
package/hosted/init.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { t } from "../i18n.mjs";
|
|
1
2
|
import { randomBytes } from 'node:crypto';
|
|
2
3
|
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
4
|
import path from 'node:path';
|
|
@@ -6,7 +7,7 @@ import { pathToFileURL } from 'node:url';
|
|
|
6
7
|
export async function initialize(directory) {
|
|
7
8
|
const home = path.resolve(directory);
|
|
8
9
|
if (Buffer.byteLength(path.join(home, 'node-a/open-browser.sock')) >= 100)
|
|
9
|
-
throw new Error(
|
|
10
|
+
throw new Error(t("Choose a shorter hosted data directory for the Unix socket path."));
|
|
10
11
|
await mkdir(path.dirname(home), { recursive: true });
|
|
11
12
|
await mkdir(home, { mode: 0o700 });
|
|
12
13
|
const token = async name => {
|
package/i18n.mjs
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { profileStateDirectory } from './build-profile.mjs';
|
|
5
|
+
import { localeOverride, systemLocale, translate } from './system-i18n.mjs';
|
|
6
|
+
|
|
7
|
+
const choices = new Set(['system', 'en', 'zh-CN']);
|
|
8
|
+
const directory = profileStateDirectory();
|
|
9
|
+
const file = path.join(directory, 'interface-language');
|
|
10
|
+
function readPreference() {
|
|
11
|
+
try {
|
|
12
|
+
const value = readFileSync(file, 'utf8').trim();
|
|
13
|
+
if (choices.has(value)) return value;
|
|
14
|
+
} catch (error) {
|
|
15
|
+
if (error.code !== 'ENOENT' && error.code !== 'EACCES') throw error;
|
|
16
|
+
}
|
|
17
|
+
return 'system';
|
|
18
|
+
}
|
|
19
|
+
let preference = readPreference();
|
|
20
|
+
const effectiveLocale = () => localeOverride || (preference === 'system' ? systemLocale : preference);
|
|
21
|
+
export let locale = effectiveLocale();
|
|
22
|
+
|
|
23
|
+
export function interfaceLanguage() {
|
|
24
|
+
return { preference, locale, overridden: Boolean(localeOverride) };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function setInterfaceLanguage(value) {
|
|
28
|
+
if (!choices.has(value)) throw Object.assign(new Error('invalid_language'), {code:'invalid_language'});
|
|
29
|
+
if (localeOverride) throw Object.assign(new Error('language_overridden'), {code:'language_overridden'});
|
|
30
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
31
|
+
const temp = file + '.' + randomUUID();
|
|
32
|
+
try {
|
|
33
|
+
writeFileSync(temp, value + '\n', { flag: 'wx', mode: 0o600 });
|
|
34
|
+
renameSync(temp, file);
|
|
35
|
+
} finally { rmSync(temp, {force:true}); }
|
|
36
|
+
preference = value;
|
|
37
|
+
locale = effectiveLocale();
|
|
38
|
+
return interfaceLanguage();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function t(message, ...args) { return translate(locale, message, ...args); }
|
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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { t } from "./i18n.mjs";
|
|
2
3
|
import { createServer } from 'node:http';
|
|
3
4
|
import { randomUUID } from 'node:crypto';
|
|
4
5
|
import { readFile } from 'node:fs/promises';
|
|
@@ -9,8 +10,8 @@ import { tokenPath } from './paths.mjs';
|
|
|
9
10
|
|
|
10
11
|
const host = process.env.OPEN_BROWSER_MCP_HTTP_HOST || '127.0.0.1';
|
|
11
12
|
const port = Number(process.env.OPEN_BROWSER_MCP_HTTP_PORT || 9239);
|
|
12
|
-
if (!['127.0.0.1', '::1'].includes(host)) throw new Error(
|
|
13
|
-
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(
|
|
13
|
+
if (!['127.0.0.1', '::1'].includes(host)) throw new Error(t("The MCP HTTP server must bind to a loopback address."));
|
|
14
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(t("Invalid OPEN_BROWSER_MCP_HTTP_PORT."));
|
|
14
15
|
|
|
15
16
|
async function readToken() {
|
|
16
17
|
const configured = process.env.OPEN_BROWSER_MCP_HTTP_TOKEN?.trim();
|
|
@@ -26,8 +27,8 @@ async function readBody(req) {
|
|
|
26
27
|
if (bytes > 1024 * 1024) throw new Error('request_too_large');
|
|
27
28
|
chunks.push(chunk);
|
|
28
29
|
}
|
|
29
|
-
if (!
|
|
30
|
-
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
30
|
+
if (!bytes) return undefined;
|
|
31
|
+
return JSON.parse(Buffer.concat(chunks, bytes).toString('utf8'));
|
|
31
32
|
}
|
|
32
33
|
|
|
33
34
|
const sessions = new Map();
|
|
@@ -44,7 +45,6 @@ const server = createServer(async (req, res) => {
|
|
|
44
45
|
const session = sessions.get(sessionId);
|
|
45
46
|
if (!session) { res.writeHead(404).end(); return; }
|
|
46
47
|
sessions.delete(sessionId);
|
|
47
|
-
await session.transport.close().catch(() => {});
|
|
48
48
|
await session.mcp.close().catch(() => {});
|
|
49
49
|
res.writeHead(204).end();
|
|
50
50
|
return;
|
|
@@ -62,14 +62,16 @@ const server = createServer(async (req, res) => {
|
|
|
62
62
|
return;
|
|
63
63
|
}
|
|
64
64
|
const mcp = createMcpServer();
|
|
65
|
-
const transport = new StreamableHTTPServerTransport({
|
|
65
|
+
const transport = new StreamableHTTPServerTransport({
|
|
66
|
+
sessionIdGenerator: () => randomUUID(),
|
|
67
|
+
onsessioninitialized: id => { sessions.set(id, session); },
|
|
68
|
+
});
|
|
66
69
|
session = { mcp, transport };
|
|
67
70
|
transport.onclose = () => { if (transport.sessionId) sessions.delete(transport.sessionId); };
|
|
68
71
|
await mcp.connect(transport);
|
|
69
72
|
}
|
|
70
73
|
try {
|
|
71
74
|
await session.transport.handleRequest(req, res, body);
|
|
72
|
-
if (session.transport.sessionId) sessions.set(session.transport.sessionId, session);
|
|
73
75
|
} catch (error) {
|
|
74
76
|
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: 'mcp_server_error' }));
|
|
75
77
|
}
|
|
@@ -77,8 +79,7 @@ const server = createServer(async (req, res) => {
|
|
|
77
79
|
|
|
78
80
|
server.listen(port, host, () => console.error(`open-browser MCP HTTP listening on http://${host}:${port}/mcp`));
|
|
79
81
|
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => {
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
})).finally(() => server.close(() => process.exit(0)));
|
|
82
|
+
server.close();
|
|
83
|
+
void Promise.allSettled([...sessions.values()].map(session => session.mcp.close()))
|
|
84
|
+
.finally(() => { server.closeAllConnections(); });
|
|
84
85
|
});
|
package/mcp-server.mjs
CHANGED
|
@@ -1,30 +1,47 @@
|
|
|
1
|
+
import { t } from "./i18n.mjs";
|
|
2
|
+
import { Agent } from 'node:http';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
1
4
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
5
|
import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } from '@modelcontextprotocol/sdk/types.js';
|
|
3
6
|
import { checkAgentRequest } from './contract-validation.mjs';
|
|
4
7
|
import { OpenBrowserClient, OpenBrowserError } from './sdk.mjs';
|
|
5
8
|
import { tools } from './api-contract.mjs';
|
|
6
9
|
|
|
10
|
+
const {version} = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8'));
|
|
11
|
+
|
|
7
12
|
export function createMcpServer() {
|
|
8
|
-
const server = new Server({ name: 'open-browser', version
|
|
13
|
+
const server = new Server({ name: 'open-browser', version }, { capabilities: { tools: {} } });
|
|
14
|
+
let api;
|
|
15
|
+
server.onclose = () => {
|
|
16
|
+
api?.close();
|
|
17
|
+
api = undefined;
|
|
18
|
+
};
|
|
9
19
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
10
|
-
server.setRequestHandler(CallToolRequestSchema, async ({ params }) => {
|
|
20
|
+
server.setRequestHandler(CallToolRequestSchema, async ({ params }, { signal }) => {
|
|
11
21
|
let args;
|
|
12
22
|
try {
|
|
13
23
|
const arguments_ = params.arguments ?? {};
|
|
14
24
|
if (['createWorkspace', 'open'].includes(params.name) &&
|
|
15
25
|
(typeof arguments_.name !== 'string' || !arguments_.name.trim()))
|
|
16
|
-
throw new McpError(ErrorCode.InvalidParams,
|
|
26
|
+
throw new McpError(ErrorCode.InvalidParams, t("Supply a non-empty task name when creating an agent workspace."));
|
|
17
27
|
args = checkAgentRequest(params.name, arguments_);
|
|
18
28
|
} catch (error) {
|
|
19
29
|
if (error instanceof McpError) throw error;
|
|
20
|
-
throw new McpError(ErrorCode.InvalidParams,
|
|
30
|
+
throw new McpError(ErrorCode.InvalidParams, t("Invalid open-browser tool name or arguments."));
|
|
21
31
|
}
|
|
22
32
|
try {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
33
|
+
if (!api) {
|
|
34
|
+
const client = server.getClientVersion();
|
|
35
|
+
const clientName = client?.title?.trim() || client?.name?.trim() || 'MCP';
|
|
36
|
+
// Bound idle sockets only. A query or cancellation must be able to
|
|
37
|
+
// reach the service while long-running calls hold their connections.
|
|
38
|
+
api = new OpenBrowserClient({
|
|
39
|
+
agent: new Agent({ keepAlive:true, maxFreeSockets:4 }),
|
|
40
|
+
agentName: process.env.OPEN_BROWSER_AGENT_NAME?.trim() || Array.from(clientName).slice(0, 80).join(''),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
const result = params.name === 'capabilities'
|
|
44
|
+
? await api.capabilities({signal}) : await api.call(params.name, args, {signal});
|
|
28
45
|
if (params.name === 'captureVisual') {
|
|
29
46
|
const { data, mimeType, ...geometry } = result;
|
|
30
47
|
return { content: [{ type: 'image', mimeType, data }, { type: 'text', text: JSON.stringify(geometry) }] };
|
|
@@ -33,7 +50,7 @@ export function createMcpServer() {
|
|
|
33
50
|
} catch (error) {
|
|
34
51
|
const detail = error instanceof OpenBrowserError
|
|
35
52
|
? { code: error.code, message: error.message, ...(error.nextAction ? { nextAction: error.nextAction } : {}) }
|
|
36
|
-
: { code: 'CLIENT_ERROR', message:
|
|
53
|
+
: { code: 'CLIENT_ERROR', message: t("The local service call failed.") };
|
|
37
54
|
return { isError: true, content: [{ type: 'text', text: JSON.stringify(detail) }] };
|
|
38
55
|
}
|
|
39
56
|
});
|
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(); });
|