@seekskyworld/open-browser 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONTRIBUTING.md +15 -0
- package/Docs/Agent/346/265/217/350/247/210/345/231/250/346/200/273/344/275/223/346/236/266/346/236/204.md +58 -0
- package/Docs/THIRD-PARTY-NOTICES.md +12 -0
- package/Docs/open-browser-api.d.ts +273 -0
- package/Docs/open-browser/344/273/273/345/212/241/350/257/204/346/265/213/346/214/207/345/215/227.md +59 -0
- package/Docs/open-browser/351/232/220/347/247/201/344/270/216/345/274/200/346/272/220/345/256/241/350/256/241.md +37 -0
- package/Docs//346/216/247/345/210/266/345/217/260/345/210/206/347/273/204/344/270/216/346/216/245/347/256/241/346/226/271/346/241/210.md +31 -0
- package/Docs//350/267/250/345/271/263/345/217/260/350/257/225/347/224/250/344/270/216/345/217/221/350/241/214.md +36 -0
- package/LICENSE +200 -0
- package/README.md +150 -2
- package/README.zh-CN.md +155 -0
- package/SECURITY.md +9 -0
- package/access-registry.mjs +151 -0
- package/action-execution.mjs +374 -0
- package/activity-notifier.mjs +34 -0
- package/api-contract.mjs +122 -0
- package/browser-extension/icons/open-browser-128.png +0 -0
- package/browser-extension/icons/open-browser-16.png +0 -0
- package/browser-extension/icons/open-browser-32.png +0 -0
- package/browser-extension/icons/open-browser-48.png +0 -0
- package/browser-extension/icons/open-browser-wordmark.png +0 -0
- package/browser-extension/manifest.json +38 -0
- package/browser-extension/newtab.css +20 -0
- package/browser-extension/newtab.html +19 -0
- package/browser-extension/newtab.js +123 -0
- package/browser-extension/phase-labels.js +9 -0
- package/browser-extension/popup.css +19 -0
- package/browser-extension/popup.html +46 -0
- package/browser-extension/popup.js +324 -0
- package/browser-extension/tab-action.js +137 -0
- package/browser-extension/worker.js +188 -0
- package/browser-extension/workspace-title.js +15 -0
- package/capability-matrix.mjs +21 -0
- package/chromium-host.mjs +149 -0
- package/chromium-shell.mjs +150 -0
- package/cli.mjs +83 -0
- package/contract-validation.mjs +27 -0
- package/control.mjs +107 -0
- package/desktop/Info.plist +13 -0
- package/desktop/Launcher.m +117 -0
- package/desktop/OBControlBar.h +7 -0
- package/desktop/OBControlBar.m +213 -0
- package/desktop/OBPageView.h +6 -0
- package/desktop/OBPageView.m +348 -0
- package/desktop/WorkspacePanel.h +16 -0
- package/desktop/WorkspacePanel.m +915 -0
- package/desktop/archive-release.py +129 -0
- package/desktop/brand-keychain.py +95 -0
- package/desktop/brand-locales.py +93 -0
- package/desktop/brand-macos-icons.py +24 -0
- package/desktop/brand-windows-icons.mjs +48 -0
- package/desktop/build-macos.mjs +96 -0
- package/desktop/build-portable.mjs +95 -0
- package/desktop/build.mjs +5 -0
- package/desktop/create-shortcut.ps1 +9 -0
- package/desktop/generate-icons.py +39 -0
- package/desktop/icons/open-browser.icns +0 -0
- package/desktop/icons/open-browser.ico +0 -0
- package/desktop/install-menu-entry.mjs +24 -0
- package/desktop/package-assets.mjs +34 -0
- package/desktop/patches/chromium-macos-keychain-service.patch +18 -0
- package/desktop/portable-archive.py +22 -0
- package/desktop/sign.mjs +33 -0
- package/desktop/smoke-portable.mjs +65 -0
- package/desktop/start.mjs +12 -0
- package/desktop/verify-upgrade.mjs +74 -0
- package/desktop/verify-version.mjs +12 -0
- package/desktop-page.mjs +211 -0
- package/diagnostics.mjs +28 -0
- package/downloads.mjs +110 -0
- package/engine-service.mjs +1002 -0
- package/hosted/README.md +74 -0
- package/hosted/cli.mjs +17 -0
- package/hosted/directory.mjs +261 -0
- package/hosted/init.mjs +37 -0
- package/hosted/server.mjs +129 -0
- package/managed-popup.mjs +54 -0
- package/mcp.mjs +43 -0
- package/network-policy.mjs +107 -0
- package/output-store.mjs +96 -0
- package/package.json +57 -4
- package/page-activity.mjs +121 -0
- package/page-dialogs.mjs +53 -0
- package/page-observation.mjs +280 -0
- package/paths.mjs +20 -0
- package/privacy-config.mjs +95 -0
- package/receipt-store.mjs +191 -0
- package/runtime.mjs +44 -0
- package/scheduler.mjs +70 -0
- package/sdk.mjs +176 -0
- package/service.mjs +271 -0
- package/site-workflow.mjs +115 -0
- package/skills/open-browser/SKILL.md +86 -0
- package/skills/open-browser/scripts/bootstrap.mjs +134 -0
- package/skills/open-browser/scripts/open-browser +21 -0
- package/skills/open-browser/scripts/open-browser.cmd +9 -0
- package/skills/open-browser/workflows/login-export.json +10 -0
- package/skills/open-browser/workflows/upload-verify.json +8 -0
- package/studio/demo-site.mjs +111 -0
- package/studio/demo.css +1 -0
- package/studio/index.html +66 -0
- package/studio/index.mjs +57 -0
- package/studio/native-demo.mjs +124 -0
- package/studio/studio.css +119 -0
- package/studio/studio.js +438 -0
- package/uploads.mjs +63 -0
- package/visual-page.mjs +306 -0
- package/workspace-lifecycle.mjs +170 -0
- package/workspace-state.mjs +95 -0
package/scheduler.mjs
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Requests in a page lane enter this scheduler only when the preceding operation settles.
|
|
2
|
+
export class WorkspaceScheduler {
|
|
3
|
+
constructor(maximum, { lowMemoryMiB = 0, availableBytes = () => process.availableMemory() } = {}) {
|
|
4
|
+
if (!Number.isSafeInteger(lowMemoryMiB) || lowMemoryMiB < 0) throw new Error('invalid_memory_watermark');
|
|
5
|
+
this.maximum = maximum;
|
|
6
|
+
this.limit = maximum;
|
|
7
|
+
this.active = 0;
|
|
8
|
+
this.queues = new Map();
|
|
9
|
+
this.lowBytes = lowMemoryMiB * 1024 * 1024;
|
|
10
|
+
this.availableBytes = availableBytes;
|
|
11
|
+
this.sampledAt = -Infinity;
|
|
12
|
+
this.completed = 0;
|
|
13
|
+
this.waitMs = 0;
|
|
14
|
+
this.executionMs = 0;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
refreshLimit(now) {
|
|
18
|
+
if (!this.lowBytes || now - this.sampledAt < 1000) return;
|
|
19
|
+
this.sampledAt = now;
|
|
20
|
+
const available = this.availableBytes();
|
|
21
|
+
// Unknown readings keep the previous limit. Separate watermarks avoid rapid oscillation.
|
|
22
|
+
if (available > 0 && available < this.lowBytes) this.limit = Math.max(1, Math.floor(this.maximum / 2));
|
|
23
|
+
if (available > this.lowBytes * 1.5) this.limit = this.maximum;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
drain() {
|
|
27
|
+
this.refreshLimit(performance.now());
|
|
28
|
+
while (this.active < this.limit && this.queues.size) {
|
|
29
|
+
const [workspace, queue] = this.queues.entries().next().value;
|
|
30
|
+
this.queues.delete(workspace);
|
|
31
|
+
const item = queue.shift();
|
|
32
|
+
if (queue.length) this.queues.set(workspace, queue);
|
|
33
|
+
this.active++;
|
|
34
|
+
item.start();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async run(workspace, work, signal, enqueuedAt) {
|
|
39
|
+
if (signal.aborted) throw Object.assign(new Error('operation_cancelled'), {code:'operation_cancelled'});
|
|
40
|
+
await new Promise((resolve, reject) => {
|
|
41
|
+
const queue = this.queues.get(workspace) || [];
|
|
42
|
+
const item = { start: () => { signal.removeEventListener('abort', abort); resolve(); } };
|
|
43
|
+
const abort = () => {
|
|
44
|
+
const index = queue.indexOf(item);
|
|
45
|
+
if (index >= 0) queue.splice(index, 1);
|
|
46
|
+
if (!queue.length && this.queues.get(workspace) === queue) this.queues.delete(workspace);
|
|
47
|
+
reject(Object.assign(new Error('operation_cancelled'), {code:'operation_cancelled'}));
|
|
48
|
+
};
|
|
49
|
+
signal.addEventListener('abort', abort, {once:true});
|
|
50
|
+
queue.push(item);
|
|
51
|
+
this.queues.set(workspace, queue);
|
|
52
|
+
this.drain();
|
|
53
|
+
});
|
|
54
|
+
const started = performance.now();
|
|
55
|
+
this.waitMs += started - enqueuedAt;
|
|
56
|
+
try { return await work(); }
|
|
57
|
+
finally {
|
|
58
|
+
this.executionMs += performance.now() - started;
|
|
59
|
+
this.completed++;
|
|
60
|
+
this.active--;
|
|
61
|
+
this.drain();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
snapshot(pending) {
|
|
66
|
+
return { maximum:this.maximum, limit:this.limit, active:this.active, pending,
|
|
67
|
+
lowMemoryMiB:this.lowBytes / 1048576, completed:this.completed,
|
|
68
|
+
cumulativeWaitMs:Math.round(this.waitMs), cumulativeExecutionMs:Math.round(this.executionMs) };
|
|
69
|
+
}
|
|
70
|
+
}
|
package/sdk.mjs
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { request } from 'node:http';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { pathsForProfile, profileId } from './paths.mjs';
|
|
5
|
+
|
|
6
|
+
import { agentMethods, limits } from './api-contract.mjs';
|
|
7
|
+
export { agentMethods };
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A short, machine-readable hint for the next safe operation after a common
|
|
11
|
+
* service error. The hint never replaces the server error message.
|
|
12
|
+
*/
|
|
13
|
+
export const recoveryHints = Object.freeze({
|
|
14
|
+
SERVICE_UNAVAILABLE: '启动 open-browser 后重试同一只读请求。',
|
|
15
|
+
TASK_NAME_REQUIRED: '为 createWorkspace 或 open 提供清晰的非空 name,再重新创建任务。',
|
|
16
|
+
REQUEST_TIMEOUT: '用同一 operationId 查询 getOperation 或 diagnoseOperation,再决定是否继续。',
|
|
17
|
+
stale_ref: '重新 observe 当前页面并用新 ref 构造动作。',
|
|
18
|
+
stale_document: '重新 observe 当前页面后再执行动作。',
|
|
19
|
+
stale_control: '重新 observe 获取最新 controlGeneration。',
|
|
20
|
+
stale_observation: '重新 observe 当前页面,不要复用旧文档标识。',
|
|
21
|
+
target_obscured: '重新 observe 并等待遮罩消失,再用新的 operationId 重试。',
|
|
22
|
+
target_ambiguous: '用 observe 的 locator 或 within 缩小目标范围。',
|
|
23
|
+
target_missing: '重新 observe 并核对页面状态或目标名称。',
|
|
24
|
+
navigation_failed: '先 observe 当前页面和地址,再决定是否重试导航。',
|
|
25
|
+
origin_denied: '核对 blockedOrigins,取得控制权后用 grantOrigin 授权所需来源。',
|
|
26
|
+
workspace_under_user_control: '等待用户交回 Agent 控制权后重新 observe。',
|
|
27
|
+
outcome_unknown: '先用 getOperation 或 diagnoseOperation,并核对站点结果后再重试。',
|
|
28
|
+
inspect_before_retry: '先核对站点是否已生效,再决定是否提交新的 operationId。',
|
|
29
|
+
run_timeout: '运行预算已耗尽。用同一 operationId 查询回执,并核对站点结果后再决定是否继续。',
|
|
30
|
+
invalid_params: '运行 --schema 或读取 capabilities,按当前契约修正参数。',
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
export class OpenBrowserError extends Error {
|
|
34
|
+
constructor(code, message) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = 'OpenBrowserError';
|
|
37
|
+
this.code = code;
|
|
38
|
+
this.nextAction = recoveryHints[code];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const unavailable = () => new OpenBrowserError('SERVICE_UNAVAILABLE', '请先启动 open-browser 本地服务。');
|
|
43
|
+
|
|
44
|
+
export class OpenBrowserClient {
|
|
45
|
+
constructor(options = {}) {
|
|
46
|
+
const selected = pathsForProfile(options.profileId ?? profileId);
|
|
47
|
+
this.socketPath = options.socketPath ?? selected.socketPath;
|
|
48
|
+
this.tokenPath = options.tokenPath ?? process.env.OPEN_BROWSER_CLIENT_TOKEN_FILE ?? selected.tokenPath;
|
|
49
|
+
const codex = process.env.CODEX_THREAD_ID || process.env.CODEX_SESSION_ID;
|
|
50
|
+
this.agentName = options.agentName ?? (process.env.OPEN_BROWSER_AGENT_NAME?.trim() ||
|
|
51
|
+
(codex ? 'Codex' : options.fallbackName ?? 'SDK'));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async call(method, params = {}) {
|
|
55
|
+
if (!agentMethods.includes(method))
|
|
56
|
+
throw new OpenBrowserError('UNKNOWN_METHOD', '未知的 Agent API 方法。');
|
|
57
|
+
if (!params || typeof params !== 'object' || Array.isArray(params))
|
|
58
|
+
throw new OpenBrowserError('INVALID_PARAMS', '参数必须是 JSON 对象。');
|
|
59
|
+
if (['createWorkspace', 'open'].includes(method) &&
|
|
60
|
+
(typeof params.name !== 'string' || !params.name.trim()))
|
|
61
|
+
throw new OpenBrowserError('TASK_NAME_REQUIRED', '创建 Agent 任务时必须提供非空任务名称 name。');
|
|
62
|
+
if (['createWorkspace','open'].includes(method) && params.agentName === undefined)
|
|
63
|
+
params = { ...params, agentName: this.agentName };
|
|
64
|
+
return localRequest(this.socketPath,this.tokenPath,'/v1/call',method,params);
|
|
65
|
+
}
|
|
66
|
+
async capabilities() {
|
|
67
|
+
try { return await this.call('capabilities'); }
|
|
68
|
+
catch(error) {
|
|
69
|
+
if (['UNKNOWN_METHOD','unknown_method','forbidden'].includes(error.code)) return {version:0,visual:{enabled:false,actions:[]}};
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
captureVisual(page, options = {}) { return this.call('captureVisual',{...options,...page}); }
|
|
74
|
+
respondDialog(page, response) { return this.call('respondDialog',{...response,...page}); }
|
|
75
|
+
listUploads(workspaceId) { return this.call('listUploads',{workspaceId}); }
|
|
76
|
+
listDownloads(workspaceId) { return this.call('listDownloads', {workspaceId}); }
|
|
77
|
+
listOutputs(workspaceId) { return this.call('listOutputs', {workspaceId}); }
|
|
78
|
+
readOutput(workspaceId, outputId, options = {}) { return this.call('readOutput', { ...options, workspaceId, outputId }); }
|
|
79
|
+
cancelDownload(workspaceId, downloadId) { return this.call('cancelDownload', {workspaceId, downloadId}); }
|
|
80
|
+
eventCursor(workspaceId) { return this.call('eventCursor',{workspaceId}); }
|
|
81
|
+
waitForEvent(page,options) { return this.call('waitForEvent',{...options,...page}); }
|
|
82
|
+
listEvents(workspaceId, options = {}) { return this.call('listEvents', { ...options, workspaceId }); }
|
|
83
|
+
getRecoverySummary(workspaceId, options = {}) { return this.call('getRecoverySummary', { ...options, workspaceId }); }
|
|
84
|
+
listOperations(workspaceId, options = {}) { return this.call('listOperations', { ...options, workspaceId }); }
|
|
85
|
+
finishWorkspace(workspaceId, keepPageIds, operationId) {
|
|
86
|
+
return this.call('finishWorkspace', {workspaceId, keepPageIds, operationId});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Finish a workspace with a fresh idempotency key generated by the SDK. */
|
|
90
|
+
finish(workspaceId, keepPageIds = []) {
|
|
91
|
+
return this.finishWorkspace(workspaceId, keepPageIds, randomUUID());
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
createWorkspace(params = {}) { return this.call('createWorkspace', params); }
|
|
95
|
+
open(params = {}) { return this.call('open', params); }
|
|
96
|
+
grantOrigin(params) { return this.call('grantOrigin', params); }
|
|
97
|
+
listWorkspaces() { return this.call('listWorkspaces'); }
|
|
98
|
+
getWorkspace(workspaceId) { return this.call('getWorkspace', { workspaceId }); }
|
|
99
|
+
openPage(workspaceId, url) { return this.call('openPage', { workspaceId, url }); }
|
|
100
|
+
observe(page) { return this.call('observe', page); }
|
|
101
|
+
/** Open one URL and immediately return its first observation. */
|
|
102
|
+
async openAndObserve(options = {}, observeOptions = {}) {
|
|
103
|
+
const page = await this.open(options);
|
|
104
|
+
const observation = await this.observe({ ...page, ...observeOptions });
|
|
105
|
+
return { ...page, observation };
|
|
106
|
+
}
|
|
107
|
+
/** Observe immediately before acting, while preserving document and control checks. */
|
|
108
|
+
async actAfterObserve(page, request = {}) {
|
|
109
|
+
const { actions, observeAfter, timeoutMs, operationId = randomUUID() } = request;
|
|
110
|
+
if (!Array.isArray(actions) || actions.length === 0)
|
|
111
|
+
throw new OpenBrowserError('INVALID_PARAMS', 'actAfterObserve 需要至少一个 action。');
|
|
112
|
+
const observation = await this.observe(page);
|
|
113
|
+
const receipt = await this.act({
|
|
114
|
+
...page,
|
|
115
|
+
documentId: observation.documentId,
|
|
116
|
+
controlGeneration: observation.controlGeneration,
|
|
117
|
+
}, { actions, observeAfter, timeoutMs, operationId });
|
|
118
|
+
return { observation, receipt };
|
|
119
|
+
}
|
|
120
|
+
runWorkflow(page, request) { return this.call('runWorkflow',{...request,...page}); }
|
|
121
|
+
act(page, operation) { return this.call('act', { ...operation, ...page }); }
|
|
122
|
+
diagnoseOperation(workspaceId, operationId) { return this.call('diagnoseOperation', {workspaceId, operationId}); }
|
|
123
|
+
getOperation(workspaceId, operationId) {
|
|
124
|
+
return this.call('getOperation', { workspaceId, operationId });
|
|
125
|
+
}
|
|
126
|
+
cancelOperation(workspaceId, operationId) {
|
|
127
|
+
return this.call('cancelOperation', { workspaceId, operationId });
|
|
128
|
+
}
|
|
129
|
+
handOff(workspaceId) { return this.call('handOff', { workspaceId }); }
|
|
130
|
+
closeWorkspace(workspaceId) { return this.call('closeWorkspace', { workspaceId }); }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function localRequest(socket, credentials, endpoint, method, params) {
|
|
134
|
+
const body = JSON.stringify({ method, params });
|
|
135
|
+
let token;
|
|
136
|
+
try {
|
|
137
|
+
token = (await readFile(credentials, 'utf8')).trim();
|
|
138
|
+
} catch {
|
|
139
|
+
throw unavailable();
|
|
140
|
+
}
|
|
141
|
+
if (!token) throw unavailable();
|
|
142
|
+
return new Promise((resolve, reject) => {
|
|
143
|
+
const req = request({
|
|
144
|
+
socketPath: socket,
|
|
145
|
+
method: 'POST',
|
|
146
|
+
path: endpoint,
|
|
147
|
+
headers: {
|
|
148
|
+
authorization: 'Bearer ' + token,
|
|
149
|
+
'content-type': 'application/json',
|
|
150
|
+
'content-length': Buffer.byteLength(body),
|
|
151
|
+
},
|
|
152
|
+
}, res => {
|
|
153
|
+
let data = '';
|
|
154
|
+
res.setEncoding('utf8');
|
|
155
|
+
res.on('data', chunk => { data += chunk; });
|
|
156
|
+
res.on('error', () => reject(unavailable()));
|
|
157
|
+
res.on('end', () => {
|
|
158
|
+
let reply;
|
|
159
|
+
try { reply = JSON.parse(data); } catch {}
|
|
160
|
+
if (typeof reply?.error?.code === 'string') {
|
|
161
|
+
reject(new OpenBrowserError(reply.error.code, reply.error.message || reply.error.code));
|
|
162
|
+
} else if (res.statusCode === 200 && reply && Object.hasOwn(reply, 'result')) {
|
|
163
|
+
resolve(reply.result);
|
|
164
|
+
} else {
|
|
165
|
+
reject(new OpenBrowserError('INVALID_RESPONSE', '本地服务返回了无法识别的响应。'));
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
});
|
|
169
|
+
req.once('error', () => reject(unavailable()));
|
|
170
|
+
req.setTimeout(limits.clientTimeoutMs, () => {
|
|
171
|
+
reject(new OpenBrowserError('REQUEST_TIMEOUT', '等待服务响应超时。对于已派发的动作,请按 operationId 查询回执。'));
|
|
172
|
+
req.destroy();
|
|
173
|
+
});
|
|
174
|
+
req.end(body);
|
|
175
|
+
});
|
|
176
|
+
}
|
package/service.mjs
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { limits } from './api-contract.mjs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { AccessRegistry } from './access-registry.mjs';
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import net from 'node:net';
|
|
6
|
+
import { createInterface } from 'node:readline';
|
|
7
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
8
|
+
import { chmod, lstat, mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { pathToFileURL } from 'node:url';
|
|
10
|
+
import { launchBrowser } from './control.mjs';
|
|
11
|
+
import { agentMethods } from './sdk.mjs';
|
|
12
|
+
import { BrowserService } from './engine-service.mjs';
|
|
13
|
+
import { socketPath, stateDir, tokenPath, adminTokenPath } from './paths.mjs';
|
|
14
|
+
|
|
15
|
+
function listen(server) {
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
server.once('error', reject);
|
|
18
|
+
server.listen(socketPath, () => {
|
|
19
|
+
server.removeListener('error', reject);
|
|
20
|
+
resolve();
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function bind(server) {
|
|
26
|
+
try { await listen(server); }
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (error.code !== 'EADDRINUSE' || process.platform === 'win32') throw error;
|
|
29
|
+
const active = await new Promise((resolve, reject) => {
|
|
30
|
+
const probe = net.connect(socketPath);
|
|
31
|
+
probe.once('connect', () => { probe.end(); resolve(true); });
|
|
32
|
+
probe.once('error', err => err.code === 'ECONNREFUSED' ? resolve(false) : reject(err));
|
|
33
|
+
});
|
|
34
|
+
if (active || !(await lstat(socketPath)).isSocket()) throw error;
|
|
35
|
+
await unlink(socketPath);
|
|
36
|
+
await listen(server);
|
|
37
|
+
}
|
|
38
|
+
if (process.platform !== 'win32') await chmod(socketPath, 0o600);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function reply(res, status, body) {
|
|
42
|
+
if (res.destroyed) return;
|
|
43
|
+
const data = JSON.stringify(body);
|
|
44
|
+
if (Buffer.byteLength(data) > limits.responseBytes)
|
|
45
|
+
return reply(res, 413, {error:{code:'response_too_large',message:'Reduce page or history limit'}});
|
|
46
|
+
res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' });
|
|
47
|
+
res.end(data);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function validToken(header, expected) {
|
|
51
|
+
const actual = Buffer.from(header || '');
|
|
52
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function readRequest(req) {
|
|
56
|
+
let size = 0;
|
|
57
|
+
const chunks = [];
|
|
58
|
+
for await (const chunk of req) {
|
|
59
|
+
size += chunk.length;
|
|
60
|
+
if (size > limits.requestBytes) throw new Error('request too large');
|
|
61
|
+
chunks.push(chunk);
|
|
62
|
+
}
|
|
63
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function errorCode(error) {
|
|
67
|
+
return typeof error?.code === 'string' && /^[a-z_]{1,64}$/i.test(error.code)
|
|
68
|
+
? error.code : 'operation_failed';
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function startApplication({ headless = false, mode = 'service', onShow, onBar,
|
|
72
|
+
launchServiceBrowser = launchBrowser, readOnlyObserver, chromiumNetLog } = {}) {
|
|
73
|
+
if (!['web', 'native', 'service', 'chromium'].includes(mode)) throw new Error('invalid_mode');
|
|
74
|
+
await mkdir(stateDir, { mode: 0o700, recursive: true });
|
|
75
|
+
if (process.platform !== 'win32') await chmod(stateDir, 0o700);
|
|
76
|
+
const token = randomBytes(32).toString('hex');
|
|
77
|
+
const authorization = Buffer.from('Bearer ' + token);
|
|
78
|
+
const adminToken = randomBytes(32).toString('hex');
|
|
79
|
+
let registry;
|
|
80
|
+
let browser, engine, studio, uiContext, page, shell, sharedContext;
|
|
81
|
+
let ready = false;
|
|
82
|
+
let closing;
|
|
83
|
+
let showing;
|
|
84
|
+
|
|
85
|
+
async function openControlWindow() {
|
|
86
|
+
if (shell) return shell.show();
|
|
87
|
+
if (mode === 'native') { onShow?.(); return; }
|
|
88
|
+
if (mode !== 'web') throw Object.assign(new Error('desktop_unavailable'), { code: 'desktop_unavailable' });
|
|
89
|
+
if (showing) return showing;
|
|
90
|
+
showing = (async () => {
|
|
91
|
+
if (!page || page.isClosed()) {
|
|
92
|
+
page = await uiContext.newPage();
|
|
93
|
+
await page.goto(studio.issueUrl(), { waitUntil: 'domcontentloaded' });
|
|
94
|
+
}
|
|
95
|
+
await page.bringToFront();
|
|
96
|
+
return page;
|
|
97
|
+
})();
|
|
98
|
+
try { return await showing; }
|
|
99
|
+
finally { showing = undefined; }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const server = http.createServer({ requestTimeout: 20_000, headersTimeout: 10_000 }, async (req, res) => {
|
|
103
|
+
const fail = (status, code, message) => reply(res, status, { error: { code, message } });
|
|
104
|
+
const admin = req.url === '/v1/admin';
|
|
105
|
+
if ((!admin && req.url !== '/v1/call') || req.method !== 'POST') return fail(404, 'not_found', 'Unknown endpoint');
|
|
106
|
+
const header = req.headers.authorization;
|
|
107
|
+
const identity = () => validToken(header, authorization) ? 'local' :
|
|
108
|
+
(header?.startsWith('Bearer ') && registry?.principal(header.slice(7)));
|
|
109
|
+
if (req.headers.origin || !(admin ? validToken(header, Buffer.from('Bearer ' + adminToken)) : identity()))
|
|
110
|
+
return fail(403, 'forbidden', 'Local client authorization required');
|
|
111
|
+
if (!ready) return fail(503, 'not_ready', 'Service is starting or stopping');
|
|
112
|
+
let input;
|
|
113
|
+
try { input = await readRequest(req); }
|
|
114
|
+
catch { return fail(400, 'invalid_request', 'Invalid JSON request or size limit exceeded'); }
|
|
115
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
116
|
+
return fail(400, 'invalid_request', 'Expected request object');
|
|
117
|
+
const { method, params = {} } = input;
|
|
118
|
+
if (!params || typeof params !== 'object' || Array.isArray(params))
|
|
119
|
+
return fail(400, 'invalid_request', 'Expected params object');
|
|
120
|
+
try {
|
|
121
|
+
if (admin) return reply(res, 200, {result: await registry.admin(engine, method, params)});
|
|
122
|
+
const client = identity();
|
|
123
|
+
if (!client) return fail(403,'forbidden','Client revoked');
|
|
124
|
+
if (method === 'desktop.open' && client === 'local') { await openControlWindow(); return reply(res, 200, { result: true }); }
|
|
125
|
+
if (!agentMethods.includes(method)) return fail(403, 'forbidden', 'Method unavailable to this client');
|
|
126
|
+
const result = await registry.call(engine, client, method, params);
|
|
127
|
+
reply(res, 200, { result: result ?? null });
|
|
128
|
+
} catch (error) {
|
|
129
|
+
const code = errorCode(error);
|
|
130
|
+
fail(400, code, code.replaceAll('_', ' '));
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
await bind(server);
|
|
135
|
+
let resolveClosed;
|
|
136
|
+
const closed = new Promise(resolve => { resolveClosed = resolve; });
|
|
137
|
+
function close() {
|
|
138
|
+
if (closing) return closing;
|
|
139
|
+
ready = false;
|
|
140
|
+
closing = (async () => {
|
|
141
|
+
shell?.stop();
|
|
142
|
+
// Remove this instance's token before releasing the socket for the next instance.
|
|
143
|
+
if ((await readFile(tokenPath, 'utf8').catch(() => '')).trim() === token)
|
|
144
|
+
await unlink(tokenPath).catch(() => {});
|
|
145
|
+
if ((await readFile(adminTokenPath, 'utf8').catch(() => '')).trim() === adminToken) await unlink(adminTokenPath).catch(() => {});
|
|
146
|
+
const serverClosed = new Promise(resolve => server.close(resolve));
|
|
147
|
+
server.closeAllConnections();
|
|
148
|
+
try {
|
|
149
|
+
if (studio) await studio.close();
|
|
150
|
+
if (engine) await engine.shutdown();
|
|
151
|
+
} finally {
|
|
152
|
+
await sharedContext?.close().catch(() => {});
|
|
153
|
+
await browser?.close().catch(() => {});
|
|
154
|
+
await serverClosed;
|
|
155
|
+
registry?.db.close();
|
|
156
|
+
resolveClosed();
|
|
157
|
+
}
|
|
158
|
+
})();
|
|
159
|
+
return closing;
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
registry = new AccessRegistry(path.join(stateDir, 'open-browser-access.sqlite'));
|
|
163
|
+
if (mode === 'chromium') {
|
|
164
|
+
const { launchChromiumShell } = await import('./chromium-shell.mjs');
|
|
165
|
+
const { chromiumHost } = await import('./chromium-host.mjs');
|
|
166
|
+
sharedContext = await launchChromiumShell({ headless, netLogPath:chromiumNetLog });
|
|
167
|
+
try { shell = await chromiumHost(sharedContext); }
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (error.code !== 'extension_reload') throw error;
|
|
170
|
+
await sharedContext.close();
|
|
171
|
+
sharedContext = await launchChromiumShell({ headless, netLogPath:chromiumNetLog });
|
|
172
|
+
shell = await chromiumHost(sharedContext);
|
|
173
|
+
}
|
|
174
|
+
browser = sharedContext.browser();
|
|
175
|
+
} else {
|
|
176
|
+
browser = await launchServiceBrowser({ headless: mode === 'native' || headless });
|
|
177
|
+
}
|
|
178
|
+
engine = new BrowserService(browser, { concurrency: 4, sharedContext, readOnlyObserver, journalPath: path.join(stateDir, 'open-browser-receipts.sqlite'), releaseTab: shell?.releaseTab, groupTab: shell?.groupTab, onActivity: shell?.onActivity,
|
|
179
|
+
onActionTarget: shell?.onActionTarget });
|
|
180
|
+
const call = async (method, params = {}) => {
|
|
181
|
+
if (method === 'createWorkspace') return registry.call(engine, 'local', method, params);
|
|
182
|
+
if (method === 'listWorkspaces') {
|
|
183
|
+
const owners = new Set([...engine.workspaces.values()].map(ws => ws.owner));
|
|
184
|
+
return (await Promise.all([...owners].map(owner => engine.call(method, params, owner)))).flat();
|
|
185
|
+
}
|
|
186
|
+
return engine.call(method === 'finishWorkspace' ? 'hostFinishWorkspace' : method, params, registry.owner(params.workspaceId) || 'local', 'desktop');
|
|
187
|
+
};
|
|
188
|
+
if (mode === 'web') {
|
|
189
|
+
const { startStudio } = await import('./studio/index.mjs');
|
|
190
|
+
studio = await startStudio({ call });
|
|
191
|
+
uiContext = await browser.newContext({ viewport: null, acceptDownloads: false, serviceWorkers: 'block' });
|
|
192
|
+
const uiOrigin = new URL(studio.url).origin;
|
|
193
|
+
await uiContext.route('**/*', route => {
|
|
194
|
+
return new URL(route.request().url()).origin === uiOrigin ? route.continue() : route.abort();
|
|
195
|
+
});
|
|
196
|
+
await openControlWindow();
|
|
197
|
+
}
|
|
198
|
+
async function hostCall(method, params = {}) {
|
|
199
|
+
if (!ready) throw Object.assign(new Error('not_ready'), { code: 'not_ready' });
|
|
200
|
+
switch (method) {
|
|
201
|
+
case 'listWorkspaces': return call(method, params);
|
|
202
|
+
case 'listAgentHistory': return registry.listHistory(engine, 'local', params);
|
|
203
|
+
case 'getWorkspace': return call(method, params);
|
|
204
|
+
default: return call(method, params);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
for (const [file,value] of [[tokenPath,token],[adminTokenPath,adminToken]]) {
|
|
208
|
+
const temporary = file + '.' + process.pid;
|
|
209
|
+
await writeFile(temporary, value + '\n', { mode: 0o600, flag: 'wx' });
|
|
210
|
+
await rename(temporary, file);
|
|
211
|
+
}
|
|
212
|
+
ready = true;
|
|
213
|
+
shell?.start(hostCall, onBar);
|
|
214
|
+
browser.once('disconnected', () => { void close(); });
|
|
215
|
+
return { close, closed, openControlWindow, studio, page, hostCall, sharedContext,
|
|
216
|
+
clickBar: frame => shell?.clickBar(frame, hostCall) };
|
|
217
|
+
} catch (error) {
|
|
218
|
+
await close();
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async function main() {
|
|
224
|
+
let active;
|
|
225
|
+
process.on('SIGUSR2', () => { void active?.openControlWindow().catch(() => {}); });
|
|
226
|
+
const native = process.argv.includes('--native-host');
|
|
227
|
+
const desktopBar = !native && process.argv.includes('--chromium') && process.argv.includes('--desktop-bar');
|
|
228
|
+
const send = frame => process.stdout.write(JSON.stringify(frame) + '\n');
|
|
229
|
+
const app = await startApplication({ headless: process.argv.includes('--headless'),
|
|
230
|
+
mode: native ? 'native' : process.argv.includes('--chromium') ? 'chromium' : 'service',
|
|
231
|
+
onBar: desktopBar ? bar => send({ event: 'desktop.bar', bar }) : undefined,
|
|
232
|
+
onShow: () => send({ event: 'desktop.open' }) });
|
|
233
|
+
active = app;
|
|
234
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { void app.close(); });
|
|
235
|
+
if (native || desktopBar) {
|
|
236
|
+
const channel = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
237
|
+
channel.on('line', async line => {
|
|
238
|
+
if (desktopBar) {
|
|
239
|
+
try {
|
|
240
|
+
if (Buffer.byteLength(line) > 4096) return;
|
|
241
|
+
const frame = JSON.parse(line);
|
|
242
|
+
if (frame?.event === 'desktop.bar.click') await app.clickBar(frame);
|
|
243
|
+
} catch { /* An obsolete click has no effect on control ownership. */ }
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
let id = null;
|
|
247
|
+
try {
|
|
248
|
+
if (Buffer.byteLength(line) > 256 * 1024) throw new Error();
|
|
249
|
+
const frame = JSON.parse(line);
|
|
250
|
+
if (!frame || !(typeof frame.id === 'string' || Number.isSafeInteger(frame.id))
|
|
251
|
+
|| typeof frame.method !== 'string' || !frame.method ||
|
|
252
|
+
(frame.params !== undefined && (!frame.params || typeof frame.params !== 'object' || Array.isArray(frame.params))))
|
|
253
|
+
throw new Error();
|
|
254
|
+
id = frame.id;
|
|
255
|
+
const result = await app.hostCall(frame.method, frame.params);
|
|
256
|
+
send({ id, result: result ?? null });
|
|
257
|
+
} catch (error) { send({ id, error: id === null ? 'invalid_request' : errorCode(error) }); }
|
|
258
|
+
});
|
|
259
|
+
channel.once('close', () => { void app.close(); });
|
|
260
|
+
app.closed.then(() => { channel.close(); process.stdin.unref?.(); });
|
|
261
|
+
send({ ready: true });
|
|
262
|
+
} else console.log('open-browser ready');
|
|
263
|
+
await app.closed;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
267
|
+
main().catch(error => {
|
|
268
|
+
console.error(error.code === 'EADDRINUSE' ? 'open-browser is already running.' : error.message);
|
|
269
|
+
process.exitCode = 1;
|
|
270
|
+
});
|
|
271
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { perform } from './action-execution.mjs';
|
|
2
|
+
// A template describes a site, semantic controls and success conditions. Runtime
|
|
3
|
+
// bindings refer to grants previously issued by the local service.
|
|
4
|
+
export const workflowOrigin=Symbol('workflowOrigin');
|
|
5
|
+
const stateTypes={checked:[true,false,'mixed'],pressed:[true,false,'mixed'],selected:[true,false],expanded:[true,false]};
|
|
6
|
+
|
|
7
|
+
function invalid() {
|
|
8
|
+
throw Object.assign(new Error('invalid_workflow'),{code:'invalid_workflow'});
|
|
9
|
+
}
|
|
10
|
+
function fields(value,allowed) {
|
|
11
|
+
if(!value || typeof value!=='object' || Array.isArray(value) ||
|
|
12
|
+
Object.keys(value).some(key=>!allowed.includes(key))) invalid();
|
|
13
|
+
}
|
|
14
|
+
function string(value,limit) {
|
|
15
|
+
if(typeof value!=='string' || !value.trim() || value.length>limit) invalid();
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function target(value,allowScope=true) {
|
|
19
|
+
fields(value,allowScope ? ['role','name','within'] : ['role','name']);
|
|
20
|
+
const {role,name,within}=value;
|
|
21
|
+
return {role:string(role,80),name:string(name,160),...(within!==undefined && {within:target(within,false)})};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function workflowRequest(params) {
|
|
25
|
+
const {workflow,bindings={},workspaceId,pageId,documentId,controlGeneration,operationId,timeoutMs}=params;
|
|
26
|
+
fields(params,['workflow','bindings','workspaceId','pageId','documentId','controlGeneration','operationId','timeoutMs']);
|
|
27
|
+
if(timeoutMs!==undefined && (!Number.isInteger(timeoutMs) || timeoutMs<1 || timeoutMs>60000)) invalid();
|
|
28
|
+
fields(workflow,['version','origin','steps']);
|
|
29
|
+
if(workflow.version!==1 || !Array.isArray(workflow.steps) || !workflow.steps.length || workflow.steps.length>32) invalid();
|
|
30
|
+
const origin=URL.parse(workflow.origin);
|
|
31
|
+
if(!origin || !['http:','https:'].includes(origin.protocol) || origin.origin!==workflow.origin) invalid();
|
|
32
|
+
if(!bindings || typeof bindings!=='object' || Array.isArray(bindings)) invalid();
|
|
33
|
+
const keys=new Set();
|
|
34
|
+
const actions=workflow.steps.map(step=>{
|
|
35
|
+
const action={kind:step?.kind,target:target(step?.target)};
|
|
36
|
+
switch(action.kind) {
|
|
37
|
+
case 'click':
|
|
38
|
+
fields(step,['kind','target']);
|
|
39
|
+
break;
|
|
40
|
+
case 'fillCredential':
|
|
41
|
+
case 'upload': {
|
|
42
|
+
fields(step,['kind','target','binding']);
|
|
43
|
+
const name=string(step.binding,80);
|
|
44
|
+
if(!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(name) || !Object.hasOwn(bindings,name)) invalid();
|
|
45
|
+
keys.add(name);
|
|
46
|
+
action[action.kind==='upload'?'fileId':'credentialRef']=string(bindings[name],160);
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
case 'expect':
|
|
50
|
+
fields(step,['kind','target','state','timeoutMs']);
|
|
51
|
+
if(step.state!==undefined) fields(step.state,Object.keys(stateTypes));
|
|
52
|
+
for(const [key,value] of Object.entries(step.state ?? {})) {
|
|
53
|
+
if(!stateTypes[key].includes(value)) invalid();
|
|
54
|
+
}
|
|
55
|
+
if(step.timeoutMs!==undefined && (!Number.isInteger(step.timeoutMs) || step.timeoutMs<1 || step.timeoutMs>10000)) invalid();
|
|
56
|
+
action.state=step.state ?? {};
|
|
57
|
+
action.timeoutMs=step.timeoutMs ?? 5000;
|
|
58
|
+
break;
|
|
59
|
+
default: invalid();
|
|
60
|
+
}
|
|
61
|
+
return action;
|
|
62
|
+
});
|
|
63
|
+
fields(bindings,[...keys]);
|
|
64
|
+
return {workspaceId,pageId,documentId,controlGeneration,operationId, ...(timeoutMs!==undefined && {timeoutMs}), [workflowOrigin]:origin.origin,actions};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Calls ordinary observe and act execution inside the scheduler's existing
|
|
68
|
+
// workspace lane. Each write uses a newly published ref and current document.
|
|
69
|
+
export async function performWorkflow(service,ws,tab,params,op,fail) {
|
|
70
|
+
const {receipt}=op;
|
|
71
|
+
const origin=params[workflowOrigin];
|
|
72
|
+
const check=()=>{
|
|
73
|
+
if(op.cancel || op.controller.signal.aborted) fail('operation_cancelled');
|
|
74
|
+
if(op.deadline !== undefined && Date.now() >= op.deadline) fail('run_timeout');
|
|
75
|
+
service.requireControl(ws,params.controlGeneration);
|
|
76
|
+
if(!ws.origins.has(origin) || URL.parse(tab.page.url())?.origin!==origin) fail('workflow_origin_changed');
|
|
77
|
+
};
|
|
78
|
+
receipt.state='running';
|
|
79
|
+
receipt.phase='running';
|
|
80
|
+
check();
|
|
81
|
+
if(tab.documentId!==params.documentId) fail('stale_document');
|
|
82
|
+
for(const step of params.actions) {
|
|
83
|
+
const deadline=Date.now()+(step.timeoutMs ?? 0);
|
|
84
|
+
let view,element;
|
|
85
|
+
for(;;) {
|
|
86
|
+
check();
|
|
87
|
+
view=await service.observe(ws,tab,{locator:step.target});
|
|
88
|
+
check();
|
|
89
|
+
if(view.match.status==='ambiguous') fail('target_ambiguous');
|
|
90
|
+
element=view.elements[0];
|
|
91
|
+
if(step.kind!=='expect') {
|
|
92
|
+
if(!element) fail('target_missing');
|
|
93
|
+
break;
|
|
94
|
+
}
|
|
95
|
+
if(element && Object.entries(step.state).every(([k,v])=>element[k]===v)) break;
|
|
96
|
+
if(Date.now()>=deadline) fail('wait_timeout');
|
|
97
|
+
const remaining = Math.min(deadline-Date.now(), op.deadline === undefined ? Infinity : op.deadline-Date.now());
|
|
98
|
+
if(remaining <= 0) fail('run_timeout');
|
|
99
|
+
await new Promise(resolve=>setTimeout(resolve,Math.min(80,remaining)));
|
|
100
|
+
}
|
|
101
|
+
if(step.kind==='expect') {
|
|
102
|
+
receipt.completedSteps++;
|
|
103
|
+
receipt.phase='verifying';
|
|
104
|
+
service.store.save(ws.owner,ws.id,op.digest,receipt);
|
|
105
|
+
service.notify(ws);
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const {target,...action}=step;
|
|
109
|
+
await perform(service,ws,tab,{documentId:view.documentId,controlGeneration:view.controlGeneration,
|
|
110
|
+
actions:[{...action,ref:element.ref}]},op,{finalize:false});
|
|
111
|
+
if(['cancelled','failed','outcome_unknown'].includes(receipt.state)) return;
|
|
112
|
+
}
|
|
113
|
+
receipt.state='completed';
|
|
114
|
+
receipt.phase='completed';
|
|
115
|
+
}
|