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,190 @@
|
|
|
1
|
+
import repl from "node:repl";
|
|
2
|
+
import { PassThrough, Writable } from "node:stream";
|
|
3
|
+
import { inspect, format } from "node:util";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { parse } from "acorn";
|
|
8
|
+
|
|
9
|
+
/** @typedef {{type: 'text', text: string} | {type: 'image', data: string, mimeType: string}} ContentItem */
|
|
10
|
+
/** @typedef {{nodeRepl: Record<string, any>, runAfterSubmittedCodeHooks?: () => Promise<void>, endTurn?: () => Promise<void>, close?: () => Promise<void>}} RuntimeHost */
|
|
11
|
+
/** @type {RuntimeHost | undefined} */
|
|
12
|
+
let host;
|
|
13
|
+
/** @type {Promise<void> | undefined} */
|
|
14
|
+
let initialized;
|
|
15
|
+
/** @type {repl.REPLServer | undefined} */
|
|
16
|
+
let runtime;
|
|
17
|
+
/** @type {((error: Error) => void) | undefined} */
|
|
18
|
+
let rejectEvaluation;
|
|
19
|
+
/** @type {ContentItem[]} */
|
|
20
|
+
let output = [];
|
|
21
|
+
let outputBytes = 0;
|
|
22
|
+
let outputTruncated = false;
|
|
23
|
+
/** @type {Record<string, unknown> | undefined} */
|
|
24
|
+
let responseMeta;
|
|
25
|
+
/** @type {Record<string, unknown>} */
|
|
26
|
+
let requestMeta = {};
|
|
27
|
+
/** @type {Map<number, {resolve: (value: unknown) => void, reject: (error: Error) => void}>} */
|
|
28
|
+
const elicitations = new Map();
|
|
29
|
+
let nextElicitation = 0;
|
|
30
|
+
const MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
|
31
|
+
|
|
32
|
+
/** @param {unknown} item @returns {void} */
|
|
33
|
+
function emitContentItem(item) {
|
|
34
|
+
if (typeof item === "string") item = { type: "text", text: item };
|
|
35
|
+
if (item?.type === "metadata") {
|
|
36
|
+
if (item.value && typeof item.value === "object") responseMeta = { ...responseMeta, ...item.value };
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
if (!item || typeof item !== "object" || !["text", "image", "audio", "resource", "resource_link"].includes(item.type)) throw new Error("Unsupported browser output content type");
|
|
40
|
+
const bytes = Buffer.byteLength(JSON.stringify(item));
|
|
41
|
+
if (outputBytes + bytes > MAX_OUTPUT_BYTES) {
|
|
42
|
+
if (!outputTruncated) output.push({ type: "text", text: "[Output truncated at 2 MiB; emit a smaller result.]" });
|
|
43
|
+
outputTruncated = true;
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
outputBytes += bytes;
|
|
47
|
+
output.push(item);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** @param {unknown} value @returns {void} */
|
|
51
|
+
function write(value) {
|
|
52
|
+
emitContentItem({ type: "text", text: typeof value === "string" ? value : inspect(value, { depth: 8, maxArrayLength: 1000, maxStringLength: 100000 }) });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** @param {unknown} value @returns {void} */
|
|
56
|
+
function emitImage(value) {
|
|
57
|
+
if (typeof value === "string") {
|
|
58
|
+
const match = /^data:(image\/[a-z0-9.+-]+);base64,([A-Za-z0-9+/=\r\n]+)$/i.exec(value);
|
|
59
|
+
if (!match) throw new Error("emitImage expects image bytes or a base64 image data URL");
|
|
60
|
+
emitContentItem({ type: "image", mimeType: match[1], data: match[2] });
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const descriptor = value && typeof value === "object" && "bytes" in value ? value : { bytes: value, mimeType: "image/png" };
|
|
64
|
+
if (!(descriptor.bytes instanceof Uint8Array)) throw new Error("emitImage expects Uint8Array bytes");
|
|
65
|
+
const mimeType = descriptor.mimeType ?? "image/png";
|
|
66
|
+
if (typeof mimeType !== "string" || !mimeType.startsWith("image/")) throw new Error("Invalid image MIME type");
|
|
67
|
+
emitContentItem({ type: "image", mimeType, data: Buffer.from(descriptor.bytes).toString("base64") });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** @param {unknown} request @returns {Promise<unknown>} */
|
|
71
|
+
function onElicitation(request) {
|
|
72
|
+
const id = ++nextElicitation;
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
elicitations.set(id, { resolve, reject });
|
|
75
|
+
process.send?.({ type: "elicitation", id, request });
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Keep redeclaration semantics explicit without modifying strings, nested lexical scopes, or comments. @param {string} code @returns {string} */
|
|
80
|
+
function redeclarableCode(code) {
|
|
81
|
+
const tree = parse(code, { ecmaVersion: "latest", sourceType: "script", allowAwaitOutsideFunction: true });
|
|
82
|
+
/** @type {{start: number, end: number, replacement: string}[]} */
|
|
83
|
+
const edits = [];
|
|
84
|
+
for (const statement of tree.body) {
|
|
85
|
+
if (statement.type === "VariableDeclaration" && statement.kind !== "var") edits.push({ start: statement.start, end: statement.start + statement.kind.length, replacement: "var" });
|
|
86
|
+
if (statement.type === "ClassDeclaration" && statement.id) edits.push({ start: statement.start, end: statement.start, replacement: `var ${statement.id.name} = ` });
|
|
87
|
+
}
|
|
88
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) code = code.slice(0, edit.start) + edit.replacement + code.slice(edit.end);
|
|
89
|
+
return code;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @param {Record<string, any>} options @returns {Promise<void>} */
|
|
93
|
+
async function initialize(options) {
|
|
94
|
+
const initialMeta = options.requestMeta ?? {};
|
|
95
|
+
const initialTurn = initialMeta["x-codex-turn-metadata"];
|
|
96
|
+
const turn = typeof initialTurn === "string" ? JSON.parse(initialTurn) : initialTurn ?? {};
|
|
97
|
+
if (!turn || typeof turn !== "object" || Array.isArray(turn)) throw new Error("Browser turn metadata must be an object");
|
|
98
|
+
// A replacement worker never reuses a remotely ended or interrupted session.
|
|
99
|
+
// Preserve policy/model context while issuing identities owned by this worker.
|
|
100
|
+
requestMeta = { ...initialMeta, "x-codex-turn-metadata": JSON.stringify({ ...turn, session_id: randomUUID(), turn_id: randomUUID() }) };
|
|
101
|
+
/** @type {Record<string, any>} */
|
|
102
|
+
let nodeRepl = { write, emitImage };
|
|
103
|
+
if (options.enginePath) {
|
|
104
|
+
const { createRuntimeHost } = await import("./official-runtime.js");
|
|
105
|
+
const env = {...process.env, ...options.env};
|
|
106
|
+
if (env.BROWSER_USE_BRIDGE_FILE) {
|
|
107
|
+
const {readBackend} = await import("./backend-discovery.js");
|
|
108
|
+
env.BROWSER_USE_BACKEND_PATHS = await readBackend(env.BROWSER_USE_BRIDGE_FILE);
|
|
109
|
+
}
|
|
110
|
+
host = await createRuntimeHost({ enginePath: options.enginePath, env, configRoot: options.hostConfigRoot, requestMeta: () => requestMeta, onElicitation, emitContentItem });
|
|
111
|
+
nodeRepl = host.nodeRepl;
|
|
112
|
+
nodeRepl.write = write;
|
|
113
|
+
nodeRepl.emitImage = emitImage;
|
|
114
|
+
}
|
|
115
|
+
globalThis.nodeRepl = nodeRepl;
|
|
116
|
+
// Imported browser-client code uses the process console for displayValue,
|
|
117
|
+
// so capture it too, not only console calls evaluated in the REPL context.
|
|
118
|
+
globalThis.console = { ...console, ...Object.fromEntries(["log", "info", "warn", "error", "debug"].map((level) => [level, (...args) => write(format(...args))])) };
|
|
119
|
+
runtime = repl.start({
|
|
120
|
+
prompt: "",
|
|
121
|
+
input: new PassThrough(),
|
|
122
|
+
output: new Writable({ write(_chunk, _encoding, callback) { callback(); } }),
|
|
123
|
+
terminal: false,
|
|
124
|
+
useGlobal: false,
|
|
125
|
+
handleError(error) { rejectEvaluation?.(error); return "ignore"; },
|
|
126
|
+
});
|
|
127
|
+
Object.assign(runtime.context, { nodeRepl, console: globalThis.console, Buffer, Uint8Array, setTimeout, clearTimeout, fetch });
|
|
128
|
+
if (options.enginePath) {
|
|
129
|
+
const client = await import(pathToFileURL(path.join(options.enginePath, "scripts/browser-client.mjs")).href);
|
|
130
|
+
runtime.context.agent = await client.setupBrowserRuntime();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** @param {string} code @returns {Promise<unknown>} */
|
|
135
|
+
function evaluate(code) {
|
|
136
|
+
const source = redeclarableCode(code);
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
rejectEvaluation = reject;
|
|
139
|
+
runtime.eval(`${source}\n`, runtime.context, "browser-session.js", (error, result) => {
|
|
140
|
+
if (error) reject(error);
|
|
141
|
+
else resolve(result);
|
|
142
|
+
});
|
|
143
|
+
}).finally(() => { rejectEvaluation = undefined; });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** @param {{type: string, id: number, options?: Record<string, any>, params?: Record<string, any>, result?: unknown, error?: string}} message @returns {Promise<void>} */
|
|
147
|
+
async function handleMessage(message) {
|
|
148
|
+
if (message.type === "elicitation_result") {
|
|
149
|
+
const pending = elicitations.get(message.id);
|
|
150
|
+
if (pending) {
|
|
151
|
+
elicitations.delete(message.id);
|
|
152
|
+
if (message.error) pending.reject(new Error(message.error));
|
|
153
|
+
else pending.resolve(message.result);
|
|
154
|
+
}
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
output = [];
|
|
158
|
+
outputBytes = 0;
|
|
159
|
+
outputTruncated = false;
|
|
160
|
+
responseMeta = undefined;
|
|
161
|
+
try {
|
|
162
|
+
initialized ??= initialize(message.options ?? {});
|
|
163
|
+
await initialized;
|
|
164
|
+
if (message.params?.requestMeta) requestMeta = message.params.requestMeta;
|
|
165
|
+
if (message.type === "evaluate") {
|
|
166
|
+
try {
|
|
167
|
+
const value = await evaluate(message.params.code);
|
|
168
|
+
if (value !== undefined) write(value);
|
|
169
|
+
} finally {
|
|
170
|
+
await host?.runAfterSubmittedCodeHooks?.();
|
|
171
|
+
}
|
|
172
|
+
} else if (message.type === "end_turn") {
|
|
173
|
+
await host?.endTurn?.();
|
|
174
|
+
const metadata = requestMeta["x-codex-turn-metadata"];
|
|
175
|
+
const turn = typeof metadata === "string" ? JSON.parse(metadata) : metadata;
|
|
176
|
+
requestMeta["x-codex-turn-metadata"] = JSON.stringify({ ...turn, turn_id: randomUUID() });
|
|
177
|
+
} else if (message.type === "close") {
|
|
178
|
+
await host?.close?.();
|
|
179
|
+
runtime?.close();
|
|
180
|
+
} else throw new Error(`Unknown JavaScript worker request: ${message.type}`);
|
|
181
|
+
process.send?.({ type: "result", id: message.id, result: { content: output, ...(responseMeta ? { _meta: responseMeta } : {}) } });
|
|
182
|
+
if (message.type === "close") process.disconnect();
|
|
183
|
+
} catch (error) {
|
|
184
|
+
emitContentItem({ type: "text", text: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
|
|
185
|
+
process.send?.({ type: "result", id: message.id, result: { content: output, isError: true, ...(responseMeta ? { _meta: responseMeta } : {}) } });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
process.on("message", (message) => { void handleMessage(message); });
|
|
190
|
+
process.on("disconnect", () => { process.exit(0); });
|