codex-browser-use 0.0.0-stage → 4.8.2
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/LICENSE +21 -0
- package/README.md +312 -2
- package/bin/browser-use.js +213 -0
- package/bin/chrome-native-host.js +29 -0
- package/extension/background.js +1384 -0
- package/extension/content-script.js +3 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/manifest.json +33 -0
- package/package.json +44 -4
- package/rules/browser_use.md +26 -0
- package/skill/SKILL.md +72 -0
- package/skill/references/cookbook.md +281 -0
- package/skill/references/tools.md +18 -0
- package/src/ax-tree.js +889 -0
- package/src/backend-discovery.js +123 -0
- package/src/backend-native-driver.js +223 -0
- package/src/backend-page-commands.js +91 -0
- package/src/backend-tabs.js +490 -0
- package/src/backend-transport.js +165 -0
- package/src/bridge-browser.js +3787 -0
- package/src/bridge-client.js +181 -0
- package/src/config.js +166 -0
- package/src/content-extractor.js +576 -0
- package/src/engine-discovery.js +90 -0
- package/src/extension.js +26 -0
- package/src/frame-reader.js +160 -0
- package/src/install.js +303 -0
- package/src/locators.js +1497 -0
- package/src/official-runtime.js +359 -0
- package/src/portable-server.js +244 -0
- package/src/read-only.js +333 -0
- package/src/repl-session.js +180 -0
- package/src/repl-worker.js +190 -0
- package/src/script-runner.js +1546 -0
- package/src/server.js +1121 -0
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import { constants } from "node:fs";
|
|
2
|
+
import { lstat, mkdir, open, rename, unlink } from "node:fs/promises";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { createConnection } from "node:net";
|
|
5
|
+
import { homedir, tmpdir } from "node:os";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { parse, stringify } from "smol-toml";
|
|
9
|
+
|
|
10
|
+
/** @typedef {{ session_id: string, turn_id: string }} TurnIdentity */
|
|
11
|
+
/** @typedef {{ timeoutMs: number, run: (identity?: TurnIdentity) => Promise<unknown> }} RuntimeHook */
|
|
12
|
+
/** @typedef {{ action: 'accept' | 'decline' | 'cancel', content?: Record<string, unknown>, _meta?: Record<string, unknown> }} ElicitationResult */
|
|
13
|
+
/**
|
|
14
|
+
* @typedef {object} RuntimeHostOptions
|
|
15
|
+
* @property {string} enginePath Installed official plugin root; proprietary files remain there.
|
|
16
|
+
* @property {string} configRoot Adapter-owned configuration directory.
|
|
17
|
+
* @property {Record<string, string | undefined>} [env] Overrides merged with the current environment.
|
|
18
|
+
* @property {Record<string, unknown> | (() => Record<string, unknown>)} [requestMeta]
|
|
19
|
+
* @property {(request: unknown) => Promise<ElicitationResult>} [onElicitation]
|
|
20
|
+
* @property {(content: unknown) => void} [emitContentItem]
|
|
21
|
+
* @property {(hook: RuntimeHook) => (() => void)} [addAfterSubmittedCodeHook]
|
|
22
|
+
* @property {(hook: RuntimeHook) => (() => void)} [addTurnEndedHandler]
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** @type {object | undefined} */
|
|
26
|
+
let connectedHost;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Raw local-stream bridge. The installed service owns JSON framing and decoding;
|
|
30
|
+
* its transport expects a connected socket's on/write/end interface unchanged.
|
|
31
|
+
* @param {{connectTimeoutMs?: number}} [options]
|
|
32
|
+
* @returns {{createConnection: (socketPath: string) => Promise<import('node:net').Socket>, close: () => void}}
|
|
33
|
+
*/
|
|
34
|
+
export function createNativePipe(options = {}) {
|
|
35
|
+
const timeoutMs = options.connectTimeoutMs ?? 10000;
|
|
36
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new Error("Invalid native pipe connection timeout");
|
|
37
|
+
/** @type {Set<import('node:net').Socket>} */
|
|
38
|
+
const sockets = new Set();
|
|
39
|
+
let closed = false;
|
|
40
|
+
return {
|
|
41
|
+
/** @param {string} socketPath @returns {Promise<import('node:net').Socket>} */
|
|
42
|
+
async createConnection(socketPath) {
|
|
43
|
+
if (closed) throw new Error("Native pipe bridge is closed");
|
|
44
|
+
if (typeof socketPath !== "string" || !path.isAbsolute(socketPath)) throw new Error("Native pipe requires an absolute local socket path");
|
|
45
|
+
const socket = createConnection({ path: socketPath });
|
|
46
|
+
sockets.add(socket);
|
|
47
|
+
socket.once("close", () => sockets.delete(socket));
|
|
48
|
+
// Keep errors handled during the handoff to the original transport too.
|
|
49
|
+
// The transport installs its own error listener after the promise resolves.
|
|
50
|
+
socket.on("error", () => sockets.delete(socket));
|
|
51
|
+
return new Promise((resolve, reject) => {
|
|
52
|
+
const timer = setTimeout(() => socket.destroy(new Error(`Native pipe connection timed out after ${timeoutMs}ms`)), timeoutMs);
|
|
53
|
+
/** @returns {void} */
|
|
54
|
+
const cleanup = () => {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
socket.removeListener("connect", onConnect);
|
|
57
|
+
socket.removeListener("error", onError);
|
|
58
|
+
socket.removeListener("close", onClose);
|
|
59
|
+
};
|
|
60
|
+
/** @returns {void} */
|
|
61
|
+
const onConnect = () => { cleanup(); resolve(socket); };
|
|
62
|
+
/** @param {Error} error @returns {void} */
|
|
63
|
+
const onError = (error) => { cleanup(); reject(error); };
|
|
64
|
+
/** @returns {void} */
|
|
65
|
+
const onClose = () => { cleanup(); reject(new Error("Native pipe closed before connecting")); };
|
|
66
|
+
socket.once("connect", onConnect);
|
|
67
|
+
socket.once("error", onError);
|
|
68
|
+
socket.once("close", onClose);
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
close() {
|
|
72
|
+
closed = true;
|
|
73
|
+
for (const socket of sockets) socket.destroy();
|
|
74
|
+
sockets.clear();
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** @param {unknown} error @returns {boolean} */
|
|
80
|
+
function missing(error) {
|
|
81
|
+
return error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** @param {unknown} value @returns {value is Record<string, unknown>} */
|
|
85
|
+
function isRecord(value) {
|
|
86
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** @param {unknown} value @returns {TurnIdentity} */
|
|
90
|
+
function turnIdentity(value) {
|
|
91
|
+
if (!isRecord(value)) throw new Error("Browser lifecycle requires session_id and turn_id");
|
|
92
|
+
const { session_id, turn_id } = value;
|
|
93
|
+
if (typeof session_id !== "string" || typeof turn_id !== "string" ||
|
|
94
|
+
!/^[A-Za-z0-9_-]{1,128}$/u.test(session_id) || !/^[A-Za-z0-9_-]{1,128}$/u.test(turn_id)) {
|
|
95
|
+
throw new Error("Browser lifecycle requires valid session_id and turn_id");
|
|
96
|
+
}
|
|
97
|
+
return { session_id, turn_id };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Owns only the adapter's TOML files, never the user's Codex configuration.
|
|
102
|
+
* Missing files are empty; malformed or inaccessible files fail closed.
|
|
103
|
+
* @param {string} root
|
|
104
|
+
* @param {{stateNamespace?: string}} [options] Isolates mutable state while sharing read-only policy.
|
|
105
|
+
* @returns {{ read: () => Promise<{config: Record<string, unknown>}>, readRequirements: () => Promise<{requirements: Record<string, unknown>}>, readToml: (name: string) => Promise<Record<string, unknown>>, writeToml: (name: string, value: Record<string, unknown>) => Promise<void> }}
|
|
106
|
+
*/
|
|
107
|
+
export function createRuntimeConfig(root, options = {}) {
|
|
108
|
+
if (!path.isAbsolute(root)) throw new Error("Browser configRoot must be an absolute path");
|
|
109
|
+
if (options.stateNamespace !== undefined && !/^[A-Za-z0-9_-]{1,128}$/u.test(options.stateNamespace)) {
|
|
110
|
+
throw new Error("Invalid browser state namespace");
|
|
111
|
+
}
|
|
112
|
+
const base = path.resolve(root);
|
|
113
|
+
const stateBase = options.stateNamespace === undefined ? base : path.join(base, "state", options.stateNamespace);
|
|
114
|
+
/** @type {Map<string, Promise<void>>} */
|
|
115
|
+
const writes = new Map();
|
|
116
|
+
|
|
117
|
+
/** @param {string} name @returns {string} */
|
|
118
|
+
function resolveName(name) {
|
|
119
|
+
if (!/^(?:config\.toml|requirements\.toml|browser\/config\.toml|browser\/sessions\/[A-Za-z0-9_-]{1,128}\.toml)$/u.test(name)) {
|
|
120
|
+
throw new Error("Unsupported browser configuration path");
|
|
121
|
+
}
|
|
122
|
+
return path.join(name.startsWith("browser/") ? stateBase : base, name);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** @param {string} target @param {boolean} create @returns {Promise<void>} */
|
|
126
|
+
async function checkParents(target, create) {
|
|
127
|
+
const parent = path.dirname(target);
|
|
128
|
+
// The selected root and its children cannot redirect state through symlinks.
|
|
129
|
+
// System ancestors such as macOS /tmp -> /private/tmp are outside this root.
|
|
130
|
+
const chain = [base];
|
|
131
|
+
let cursor = base;
|
|
132
|
+
for (const segment of path.relative(base, parent).split(path.sep).filter(Boolean)) {
|
|
133
|
+
cursor = path.join(cursor, segment);
|
|
134
|
+
chain.push(cursor);
|
|
135
|
+
}
|
|
136
|
+
for (const directory of chain) {
|
|
137
|
+
try {
|
|
138
|
+
const stat = await lstat(directory);
|
|
139
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("Browser configuration directories must not be symlinks or files");
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (!missing(error)) throw error;
|
|
142
|
+
if (!create) continue;
|
|
143
|
+
try {
|
|
144
|
+
await mkdir(directory, { mode: 0o700, recursive: directory === base });
|
|
145
|
+
} catch (creationError) {
|
|
146
|
+
if (!(creationError instanceof Error) || !("code" in creationError) || creationError.code !== "EEXIST") throw creationError;
|
|
147
|
+
}
|
|
148
|
+
const created = await lstat(directory);
|
|
149
|
+
if (created.isSymbolicLink() || !created.isDirectory()) throw new Error("Browser configuration directories must not be symlinks or files");
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** @param {string} name @returns {Promise<Record<string, unknown>>} */
|
|
155
|
+
async function readToml(name) {
|
|
156
|
+
const target = resolveName(name);
|
|
157
|
+
await writes.get(target);
|
|
158
|
+
await checkParents(target, false);
|
|
159
|
+
let handle;
|
|
160
|
+
try {
|
|
161
|
+
handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
162
|
+
const result = parse(await handle.readFile("utf8"));
|
|
163
|
+
if (!isRecord(result)) throw new Error("Browser configuration must be a TOML table");
|
|
164
|
+
return result;
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (missing(error)) return {};
|
|
167
|
+
throw error;
|
|
168
|
+
} finally {
|
|
169
|
+
await handle?.close();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** @param {string} name @param {Record<string, unknown>} value @returns {Promise<void>} */
|
|
174
|
+
async function writeToml(name, value) {
|
|
175
|
+
if (!name.startsWith("browser/")) throw new Error("The browser engine may only write browser state files");
|
|
176
|
+
const target = resolveName(name);
|
|
177
|
+
if (!isRecord(value)) throw new Error("Browser state must be a TOML table");
|
|
178
|
+
const bytes = stringify(value);
|
|
179
|
+
const prior = writes.get(target) ?? Promise.resolve();
|
|
180
|
+
const write = prior.catch(() => undefined).then(async () => {
|
|
181
|
+
await checkParents(target, true);
|
|
182
|
+
try {
|
|
183
|
+
if ((await lstat(target)).isSymbolicLink()) throw new Error("Browser state files must not be symlinks");
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (!missing(error)) throw error;
|
|
186
|
+
}
|
|
187
|
+
const temporary = `${target}.${randomUUID()}.tmp`;
|
|
188
|
+
const handle = await open(temporary, "wx", 0o600);
|
|
189
|
+
try {
|
|
190
|
+
try {
|
|
191
|
+
await handle.writeFile(bytes, "utf8");
|
|
192
|
+
await handle.sync();
|
|
193
|
+
} finally {
|
|
194
|
+
await handle.close();
|
|
195
|
+
}
|
|
196
|
+
await checkParents(target, false);
|
|
197
|
+
await rename(temporary, target);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
await unlink(temporary);
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
writes.set(target, write);
|
|
204
|
+
try {
|
|
205
|
+
await write;
|
|
206
|
+
} finally {
|
|
207
|
+
if (writes.get(target) === write) writes.delete(target);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
read: async () => ({ config: await readToml("config.toml") }),
|
|
213
|
+
readRequirements: async () => ({ requirements: await readToml("requirements.toml") }),
|
|
214
|
+
readToml,
|
|
215
|
+
writeToml,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** @param {RuntimeHook} hook @param {TurnIdentity | undefined} identity @returns {Promise<void>} */
|
|
220
|
+
async function invokeHook(hook, identity) {
|
|
221
|
+
if (!Number.isFinite(hook.timeoutMs) || hook.timeoutMs <= 0) throw new Error("Invalid browser hook timeout");
|
|
222
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
223
|
+
let timer;
|
|
224
|
+
try {
|
|
225
|
+
await Promise.race([
|
|
226
|
+
Promise.resolve().then(() => hook.run(identity)),
|
|
227
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("Browser lifecycle hook timed out; terminate its worker")), hook.timeoutMs); }),
|
|
228
|
+
]);
|
|
229
|
+
} finally {
|
|
230
|
+
clearTimeout(timer);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Supplies the host contract expected by an unmodified installed browser engine.
|
|
236
|
+
* Each host must live in its own worker; the official service has singleton state.
|
|
237
|
+
* The caller installs nodeRepl on globalThis before importing browser-client.mjs.
|
|
238
|
+
* @param {RuntimeHostOptions} options
|
|
239
|
+
* @returns {{ nodeRepl: Record<string, unknown>, endTurn: (identity?: TurnIdentity) => Promise<void>, runAfterSubmittedCodeHooks: () => Promise<void>, close: () => Promise<void> }}
|
|
240
|
+
*/
|
|
241
|
+
export function createRuntimeHost(options) {
|
|
242
|
+
if (!path.isAbsolute(options.enginePath)) throw new Error("Browser enginePath must be an absolute plugin root");
|
|
243
|
+
const enginePath = path.join(options.enginePath, "scripts", "browser-service.mjs");
|
|
244
|
+
// The official engine publishes whole state snapshots. Sharing those files
|
|
245
|
+
// between independent workers would overwrite approvals and denials even
|
|
246
|
+
// with atomic writes, so each host owns a separate mutable namespace.
|
|
247
|
+
const config = createRuntimeConfig(options.configRoot, { stateNamespace: randomUUID() });
|
|
248
|
+
const nativePipe = createNativePipe();
|
|
249
|
+
const env = Object.freeze({ ...process.env, ...options.env });
|
|
250
|
+
const identity = { session_id: randomUUID(), turn_id: randomUUID() };
|
|
251
|
+
/** @type {Set<RuntimeHook>} */
|
|
252
|
+
const afterHooks = new Set();
|
|
253
|
+
/** @type {Set<RuntimeHook>} */
|
|
254
|
+
const turnHooks = new Set();
|
|
255
|
+
/** @type {Array<() => void>} */
|
|
256
|
+
const unregister = [];
|
|
257
|
+
/** @type {Promise<{handleRpc: (request: unknown) => Promise<unknown>}> | undefined} */
|
|
258
|
+
let service;
|
|
259
|
+
let closed = false;
|
|
260
|
+
|
|
261
|
+
/** @returns {Record<string, unknown>} */
|
|
262
|
+
function metadata() {
|
|
263
|
+
const provided = typeof options.requestMeta === "function" ? options.requestMeta() : options.requestMeta;
|
|
264
|
+
return provided ?? { "x-codex-turn-metadata": identity };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** @returns {TurnIdentity} */
|
|
268
|
+
function currentTurn() {
|
|
269
|
+
let value = metadata()["x-codex-turn-metadata"];
|
|
270
|
+
if (typeof value === "string") value = JSON.parse(value);
|
|
271
|
+
return turnIdentity(value);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** @param {RuntimeHook} hook @param {Set<RuntimeHook>} set @param {((hook: RuntimeHook) => (() => void)) | undefined} external @returns {() => void} */
|
|
275
|
+
function register(hook, set, external) {
|
|
276
|
+
if (closed) throw new Error("Browser runtime host is closed");
|
|
277
|
+
set.add(hook);
|
|
278
|
+
const removeExternal = external?.(hook);
|
|
279
|
+
let removed = false;
|
|
280
|
+
const remove = () => {
|
|
281
|
+
if (removed) return;
|
|
282
|
+
removed = true;
|
|
283
|
+
set.delete(hook);
|
|
284
|
+
removeExternal?.();
|
|
285
|
+
};
|
|
286
|
+
unregister.push(remove);
|
|
287
|
+
return remove;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/** @type {Record<string, unknown>} */
|
|
291
|
+
const nodeRepl = {
|
|
292
|
+
config,
|
|
293
|
+
nativePipe,
|
|
294
|
+
env,
|
|
295
|
+
cwd: process.cwd(),
|
|
296
|
+
homeDir: homedir(),
|
|
297
|
+
tmpDir: tmpdir(),
|
|
298
|
+
get requestMeta() { return metadata(); },
|
|
299
|
+
/** @param {unknown} value @returns {void} */
|
|
300
|
+
setResponseMeta(value) { options.emitContentItem?.({ type: "metadata", value }); },
|
|
301
|
+
/** @param {unknown} value @returns {void} */
|
|
302
|
+
emitContentItem(value) { options.emitContentItem?.(value); },
|
|
303
|
+
/** @param {unknown} value @returns {void} */
|
|
304
|
+
emitImage(value) { options.emitContentItem?.({ type: "image", value }); },
|
|
305
|
+
/** @param {unknown} value @returns {void} */
|
|
306
|
+
write(value) { options.emitContentItem?.({ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }); },
|
|
307
|
+
fetch: globalThis.fetch.bind(globalThis),
|
|
308
|
+
/** @param {unknown} request @returns {Promise<ElicitationResult>} */
|
|
309
|
+
async createElicitation(request) {
|
|
310
|
+
if (!options.onElicitation) throw new Error("This MCP client cannot obtain browser approval; access was not granted");
|
|
311
|
+
const response = await options.onElicitation(request);
|
|
312
|
+
if (!isRecord(response) || !["accept", "decline", "cancel"].includes(response.action)) throw new Error("Invalid browser approval response");
|
|
313
|
+
return response;
|
|
314
|
+
},
|
|
315
|
+
/** @param {RuntimeHook} hook @returns {() => void} */
|
|
316
|
+
addAfterSubmittedCodeHook(hook) { return register(hook, afterHooks, options.addAfterSubmittedCodeHook); },
|
|
317
|
+
/** @param {RuntimeHook} hook @returns {() => void} */
|
|
318
|
+
addTurnEndedHandler(hook) { return register(hook, turnHooks, options.addTurnEndedHandler); },
|
|
319
|
+
/** @param {string} channel @param {unknown} request @returns {Promise<unknown>} */
|
|
320
|
+
async rpc(channel, request) {
|
|
321
|
+
if (closed) throw new Error("Browser runtime host is closed");
|
|
322
|
+
if (channel !== "browser") throw new Error("Unsupported runtime RPC channel");
|
|
323
|
+
if (globalThis.nodeRepl !== nodeRepl) throw new Error("Install this host as globalThis.nodeRepl in its isolated worker");
|
|
324
|
+
if (connectedHost && connectedHost !== nodeRepl) throw new Error("Use one official browser runtime host per worker");
|
|
325
|
+
connectedHost = nodeRepl;
|
|
326
|
+
service ??= import(pathToFileURL(enginePath).href);
|
|
327
|
+
return (await service).handleRpc(request);
|
|
328
|
+
},
|
|
329
|
+
};
|
|
330
|
+
|
|
331
|
+
/** @param {TurnIdentity} [value] @returns {Promise<void>} */
|
|
332
|
+
async function endTurn(value) {
|
|
333
|
+
const turn = value ? turnIdentity(value) : currentTurn();
|
|
334
|
+
await Promise.all([...turnHooks].map((hook) => invokeHook(hook, turn)));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
return {
|
|
338
|
+
nodeRepl,
|
|
339
|
+
endTurn,
|
|
340
|
+
async runAfterSubmittedCodeHooks() {
|
|
341
|
+
if (closed) throw new Error("Browser runtime host is closed");
|
|
342
|
+
if (options.addAfterSubmittedCodeHook) return;
|
|
343
|
+
for (const hook of afterHooks) await invokeHook(hook, undefined);
|
|
344
|
+
},
|
|
345
|
+
async close() {
|
|
346
|
+
if (closed) return;
|
|
347
|
+
// The worker must be terminated after close: there is no exported engine shutdown API.
|
|
348
|
+
try {
|
|
349
|
+
await endTurn();
|
|
350
|
+
} finally {
|
|
351
|
+
closed = true;
|
|
352
|
+
nativePipe.close();
|
|
353
|
+
for (const remove of unregister) remove();
|
|
354
|
+
afterHooks.clear();
|
|
355
|
+
turnHooks.clear();
|
|
356
|
+
}
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
}
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { realpathSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
7
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { ElicitRequestParamsSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
10
|
+
import { discoverEngine } from "./engine-discovery.js";
|
|
11
|
+
import { readBackend } from "./backend-discovery.js";
|
|
12
|
+
import { ReplSession } from "./repl-session.js";
|
|
13
|
+
|
|
14
|
+
/** @typedef {import('@modelcontextprotocol/sdk/types.js').CallToolResult} ToolResult */
|
|
15
|
+
/** @typedef {{path:string,version:string,clientPath:string,servicePath:string,apiPath:string,manifestPath:string}} Engine */
|
|
16
|
+
/** @typedef {{requestId?:string|number,signal?:AbortSignal,_meta?:Record<string,unknown>}} ToolContext */
|
|
17
|
+
|
|
18
|
+
/** @param {string|undefined} label @param {ToolContext} context @returns {string} */
|
|
19
|
+
function sessionKey(label, context) {
|
|
20
|
+
const providerSession = context._meta?.["ai.opencode/sessionID"];
|
|
21
|
+
if (providerSession === undefined) return label ?? "default";
|
|
22
|
+
if (typeof providerSession !== "string" || !providerSession.length || providerSession.length > 256) {
|
|
23
|
+
throw new Error("Invalid OpenCode session metadata");
|
|
24
|
+
}
|
|
25
|
+
return JSON.stringify([providerSession, label ?? "default"]);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const instructions = `Use browser_js to execute JavaScript with top-level await. The persistent
|
|
29
|
+
agent binding is initialized using the locally installed original browser-client.
|
|
30
|
+
Each MCP connection is isolated. An OpenCode session gets its own runtime when its session ID is
|
|
31
|
+
present. Subagents sharing a conversation must choose distinct session labels and pass the same
|
|
32
|
+
label to all their tools. Use browser_close_session when finished.
|
|
33
|
+
Select the requested browser explicitly, e.g. const browser = await agent.browsers.get("chrome").
|
|
34
|
+
Read its complete documentation before actions: nodeRepl.write(await browser.documentation()).
|
|
35
|
+
Keep browser/tab bindings across calls. Use the documented playwright/cua/dom_cua APIs.
|
|
36
|
+
Webpage evaluate is the engine's guarded DOM evaluation, not arbitrary page mutation.
|
|
37
|
+
Use browser_end_turn after completing a task so claimed tabs release and unmarked new tabs clean up.
|
|
38
|
+
Mark deliverables/handoffs through the original tab API before ending the turn.
|
|
39
|
+
Do not replace another agent's claimed tab or bypass approval requests. If approval is unsupported,
|
|
40
|
+
report the limitation. Never fabricate a permission grant. This JS runtime executes trusted local
|
|
41
|
+
code with the operating-system privileges of the launching CLI; it is not a hostile-code sandbox.`;
|
|
42
|
+
|
|
43
|
+
/** Convert an exception to a tool error without disguising failure as null.
|
|
44
|
+
* @param {unknown} error @returns {ToolResult} */
|
|
45
|
+
function toolError(error) {
|
|
46
|
+
return {isError: true, content: [{type: "text", text: error instanceof Error ? error.message : String(error)}]};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @param {unknown} value @returns {ToolResult} */
|
|
50
|
+
function textResult(value) {
|
|
51
|
+
return {content: [{type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2)}]};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Adapt the original host's approval shape to standard MCP without fabricating a grant.
|
|
55
|
+
* @param {unknown} request @returns {import('@modelcontextprotocol/sdk/types.js').ElicitRequestParams} */
|
|
56
|
+
export function normalizeElicitation(request) {
|
|
57
|
+
if (!request || typeof request !== "object" || Array.isArray(request)) throw new Error("Invalid browser permission request");
|
|
58
|
+
const {meta, ...rest} = request;
|
|
59
|
+
if (meta !== undefined && (!meta || typeof meta !== "object" || Array.isArray(meta))) throw new Error("Invalid browser permission metadata");
|
|
60
|
+
if (rest._meta !== undefined && (!rest._meta || typeof rest._meta !== "object" || Array.isArray(rest._meta))) throw new Error("Invalid MCP permission metadata");
|
|
61
|
+
const metadata = {...meta, ...rest._meta};
|
|
62
|
+
if (["browser_auth", "browser_email_otp"].includes(metadata.codex_approval_kind)) {
|
|
63
|
+
throw new Error("This provider adapter does not implement the original secure credential-entry flow. Sign in manually in the selected browser, then retry; no credentials or access were granted.");
|
|
64
|
+
}
|
|
65
|
+
return ElicitRequestParamsSchema.parse({
|
|
66
|
+
...rest,
|
|
67
|
+
...(rest.mode !== "url" && rest.requestedSchema === undefined ? {requestedSchema: {type: "object", properties: {}}} : {}),
|
|
68
|
+
_meta: metadata,
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Create a separate runtime for one MCP connection. No browser is selected at startup.
|
|
73
|
+
* @param {{engine?:Engine, env?:NodeJS.ProcessEnv, configRoot?:string, session?:ReplSession}} [options]
|
|
74
|
+
* @returns {Promise<{server:McpServer,session:ReplSession,close:()=>Promise<void>}>} */
|
|
75
|
+
export async function createPortableServer(options = {}) {
|
|
76
|
+
const env = options.env ?? process.env;
|
|
77
|
+
const engine = options.engine ?? await discoverEngine({env});
|
|
78
|
+
const server = new McpServer({name: "browser-use", version: "2.0.0"}, {instructions});
|
|
79
|
+
/** @typedef {{session:ReplSession,queue:Promise<void>,generation:number,closing?:boolean,request?:{requestId?:string|number,signal?:AbortSignal}}} SessionRecord */
|
|
80
|
+
/** @type {Map<string,SessionRecord>} */
|
|
81
|
+
const sessions = new Map();
|
|
82
|
+
let closed = false;
|
|
83
|
+
/** @param {string} [label] @returns {SessionRecord} */
|
|
84
|
+
function getSession(label = "default") {
|
|
85
|
+
if (closed) throw new Error("Browser server is closing; new sessions are not accepted.");
|
|
86
|
+
const existing = sessions.get(label);
|
|
87
|
+
if (existing) return existing;
|
|
88
|
+
if (sessions.size >= 16) throw new Error("This connection already has 16 sessions; close an unused session first.");
|
|
89
|
+
/** @type {SessionRecord} */
|
|
90
|
+
const record = {session: undefined, queue: Promise.resolve(), generation: 0};
|
|
91
|
+
record.session = label === "default" && options.session ? options.session : new ReplSession({
|
|
92
|
+
enginePath: engine.path,
|
|
93
|
+
env,
|
|
94
|
+
hostConfigRoot: options.configRoot ?? env.BROWSER_USE_CONFIG_ROOT ?? path.join(homedir(), ".local", "share", "browser-use"),
|
|
95
|
+
requestMeta: {"x-codex-turn-metadata": {session_id: randomUUID(), turn_id: randomUUID()}},
|
|
96
|
+
async onElicitation(params) {
|
|
97
|
+
const capabilities = server.server.getClientCapabilities();
|
|
98
|
+
if (!capabilities?.elicitation) throw new Error("This MCP client cannot display the browser engine's permission request. Use a client with MCP elicitation support; no access was granted.");
|
|
99
|
+
return server.server.elicitInput(normalizeElicitation(params), {relatedRequestId: record.request?.requestId, signal: record.request?.signal});
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
sessions.set(label, record);
|
|
103
|
+
return record;
|
|
104
|
+
}
|
|
105
|
+
const session = getSession().session;
|
|
106
|
+
const sessionSchema = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/).optional().describe("Stable label isolating subagents sharing this MCP connection; omitted uses default.");
|
|
107
|
+
/** @param {string|undefined} label @param {(session:ReplSession)=>Promise<ToolResult>} operation @param {ToolContext} extra @returns {Promise<ToolResult>} */
|
|
108
|
+
function run(label, operation, extra) {
|
|
109
|
+
let record;
|
|
110
|
+
try { record = getSession(sessionKey(label, extra)); }
|
|
111
|
+
catch (error) { return Promise.resolve(toolError(error)); }
|
|
112
|
+
const generation = record.generation;
|
|
113
|
+
const result = record.queue.then(async () => {
|
|
114
|
+
if (closed || record.closing || record.generation !== generation) {
|
|
115
|
+
return toolError(new Error("Browser session changed before this request started."));
|
|
116
|
+
}
|
|
117
|
+
if (extra.signal?.aborted) return toolError(new Error("Browser request was cancelled before execution."));
|
|
118
|
+
record.request = extra;
|
|
119
|
+
try { return await operation(record.session); }
|
|
120
|
+
catch (error) { return toolError(error); }
|
|
121
|
+
finally { record.request = undefined; }
|
|
122
|
+
});
|
|
123
|
+
record.queue = result.then(() => undefined, () => undefined);
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
/** @param {string|undefined} label @param {"reset"|"close"} action @param {ToolContext} context @returns {Promise<ToolResult>} */
|
|
127
|
+
async function interrupt(label, action, context) {
|
|
128
|
+
try {
|
|
129
|
+
const key = sessionKey(label, context);
|
|
130
|
+
if (action === "close" && label === undefined && key === "default") {
|
|
131
|
+
throw new Error("Provide a session label to close a shared connection's browser session.");
|
|
132
|
+
}
|
|
133
|
+
const record = action === "close" ? sessions.get(key) : getSession(key);
|
|
134
|
+
if (!record) return textResult("Browser session closed.");
|
|
135
|
+
if (record.closing) throw new Error("Browser session is closing.");
|
|
136
|
+
record.generation++;
|
|
137
|
+
if (action === "close") {
|
|
138
|
+
record.closing = true;
|
|
139
|
+
try { await record.session.close(); }
|
|
140
|
+
finally { sessions.delete(key); }
|
|
141
|
+
return textResult("Browser session closed.");
|
|
142
|
+
}
|
|
143
|
+
// Start the reset immediately and make later evaluations wait for cleanup.
|
|
144
|
+
const reset = record.session.reset();
|
|
145
|
+
record.queue = Promise.allSettled([record.queue, reset]).then(() => undefined);
|
|
146
|
+
await reset;
|
|
147
|
+
return textResult("Runtime reset. The next browser_js call initializes a new agent binding.");
|
|
148
|
+
} catch (error) {
|
|
149
|
+
return toolError(error);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
server.registerTool("browser_js", {
|
|
153
|
+
description: instructions,
|
|
154
|
+
inputSchema: {
|
|
155
|
+
code: z.string().min(1).max(1_000_000).describe("JavaScript using the persistent agent/browser/tab bindings. Explicitly write text or emit images."),
|
|
156
|
+
timeout_ms: z.number().int().min(100).max(300_000).optional().describe("Execution deadline; expiry terminates and resets this connection's worker."),
|
|
157
|
+
session: sessionSchema,
|
|
158
|
+
},
|
|
159
|
+
}, ({code, timeout_ms, session: label}, extra) => run(label, (runtime) => runtime.evaluate(code, {timeoutMs: timeout_ms, signal: extra.signal}), extra));
|
|
160
|
+
server.registerTool("browser_documentation", {
|
|
161
|
+
description: "Read bootstrap instructions without connecting to or inspecting the user's browser. After selecting a browser, read browser.documentation() through browser_js for supported APIs.",
|
|
162
|
+
inputSchema: {},
|
|
163
|
+
annotations: {readOnlyHint: true},
|
|
164
|
+
}, async () => textResult({instructions, engineVersion: engine.version, enginePath: engine.path}));
|
|
165
|
+
server.registerTool("browser_status", {
|
|
166
|
+
description: "Report the selected engine, bridge descriptor and client approval support without inspecting browser tabs.",
|
|
167
|
+
inputSchema: {}, annotations: {readOnlyHint: true},
|
|
168
|
+
}, async () => {
|
|
169
|
+
const client = server.server.getClientVersion();
|
|
170
|
+
const elicitation = server.server.getClientCapabilities()?.elicitation;
|
|
171
|
+
const descriptor = env.BROWSER_USE_BRIDGE_FILE;
|
|
172
|
+
let bridge = {state: "not configured"};
|
|
173
|
+
if (descriptor) {
|
|
174
|
+
try {
|
|
175
|
+
await readBackend(descriptor);
|
|
176
|
+
bridge = {state: "socket descriptor valid"};
|
|
177
|
+
} catch (error) {
|
|
178
|
+
bridge = {state: "unavailable", reason: error instanceof Error ? error.message : String(error)};
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return textResult({
|
|
182
|
+
engine, runtime: process.version, client,
|
|
183
|
+
approval: elicitation ? "MCP elicitation advertised by client" : "MCP elicitation unavailable",
|
|
184
|
+
bridge, sessionIsolation: "one worker per session label and OpenCode session ID, scoped to this MCP connection",
|
|
185
|
+
browserConnectivity: "not checked", parity: "original engine reused; provider host equivalence must be tested",
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
server.registerTool("browser_end_turn", {
|
|
189
|
+
description: "Finish the task: run the original engine's turn cleanup, release claimed user tabs and clean up unmarked new tabs. Starts a fresh turn while preserving JavaScript bindings.",
|
|
190
|
+
inputSchema: {session: sessionSchema},
|
|
191
|
+
}, ({session: label}, extra) => run(label, async (runtime) => {
|
|
192
|
+
const result = await runtime.endTurn();
|
|
193
|
+
return result?.isError ? result : textResult("Turn ended. Obtain fresh tab bindings before using released or closed tabs.");
|
|
194
|
+
}, extra));
|
|
195
|
+
server.registerTool("browser_reset", {
|
|
196
|
+
description: "Run cleanup and reset this connection's JS worker. Browser/tab bindings are discarded. Other connections are unaffected.",
|
|
197
|
+
inputSchema: {session: sessionSchema},
|
|
198
|
+
}, ({session: label}, extra) => interrupt(label, "reset", extra));
|
|
199
|
+
server.registerTool("browser_close_session", {
|
|
200
|
+
description: "End and remove a labeled session or the current OpenCode session, running original engine cleanup.",
|
|
201
|
+
inputSchema: {session: sessionSchema},
|
|
202
|
+
}, ({session: label}, extra) => interrupt(label, "close", extra));
|
|
203
|
+
/** @returns {Promise<void>} */
|
|
204
|
+
async function close() {
|
|
205
|
+
if (closed) return;
|
|
206
|
+
closed = true;
|
|
207
|
+
const results = await Promise.allSettled([...sessions.values()].map((record) => record.session.close()));
|
|
208
|
+
await server.close();
|
|
209
|
+
const failed = results.find((result) => result.status === "rejected");
|
|
210
|
+
if (failed) throw failed.reason;
|
|
211
|
+
}
|
|
212
|
+
server.server.onclose = () => { void close().catch((error) => console.error("Browser cleanup failed:", error.message)); };
|
|
213
|
+
return {server, session, close};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Start a provider-independent stdio MCP server. @returns {Promise<void>} */
|
|
217
|
+
export async function main() {
|
|
218
|
+
const runtime = await createPortableServer();
|
|
219
|
+
await runtime.server.connect(new StdioServerTransport());
|
|
220
|
+
/** @returns {void} */
|
|
221
|
+
const stop = () => { void runtime.close().catch((error) => { console.error(error); process.exitCode = 1; }); };
|
|
222
|
+
process.once("SIGINT", stop);
|
|
223
|
+
process.once("SIGTERM", stop);
|
|
224
|
+
process.stdin.once("end", stop);
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** @param {string} metaUrl @returns {boolean} */
|
|
228
|
+
function isExecutedDirectly(metaUrl) {
|
|
229
|
+
if (!process.argv[1]) return false;
|
|
230
|
+
const selfPath = fileURLToPath(metaUrl);
|
|
231
|
+
if (path.resolve(process.argv[1]) === selfPath) return true;
|
|
232
|
+
try {
|
|
233
|
+
return realpathSync(process.argv[1]) === realpathSync(selfPath);
|
|
234
|
+
} catch {
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (isExecutedDirectly(import.meta.url)) {
|
|
240
|
+
main().catch((error) => {
|
|
241
|
+
console.error("Fatal portable server error:", error);
|
|
242
|
+
process.exitCode = 1;
|
|
243
|
+
});
|
|
244
|
+
}
|