codex-browser-use 0.0.0-stage → 4.8.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.
@@ -0,0 +1,181 @@
1
+ import { createConnection } from "node:net";
2
+ import { endianness } from "node:os";
3
+ import { readBackend } from "./backend-discovery.js";
4
+ import { FrameReader, encodeFrame } from "./frame-reader.js";
5
+
6
+ const littleEndian = endianness() === "LE";
7
+ const maxFrameBytes = 16 * 1024 * 1024;
8
+
9
+ /**
10
+ * Framed JSON-RPC client for the project's Chrome bridge.
11
+ * One client owns one bridge connection and therefore one browser session.
12
+ */
13
+ export class BridgeClient {
14
+ /**
15
+ * @param {{bridgeFile:string, connectTimeoutMs?:number, requestTimeoutMs?:number}} options
16
+ */
17
+ constructor({ bridgeFile, connectTimeoutMs = 10_000, requestTimeoutMs = 30_000 }) {
18
+ if (typeof bridgeFile !== "string" || bridgeFile.length === 0) {
19
+ throw new Error("A browser bridge descriptor path is required");
20
+ }
21
+ this.bridgeFile = bridgeFile;
22
+ this.connectTimeoutMs = connectTimeoutMs;
23
+ this.requestTimeoutMs = requestTimeoutMs;
24
+ /** @type {import("node:net").Socket|null} */
25
+ this.socket = null;
26
+ /** @type {Map<number,{resolve:(value:unknown)=>void, reject:(error:Error)=>void, timer:NodeJS.Timeout}>} */
27
+ this.pending = new Map();
28
+ this.nextId = 1;
29
+ this.reader = new FrameReader({
30
+ littleEndian,
31
+ maxFrameBytes,
32
+ maxBufferedBytes: 2 * (maxFrameBytes + 4),
33
+ overflowError: "Browser bridge input buffer exceeds limit",
34
+ lengthError: "Invalid browser bridge frame length",
35
+ });
36
+ this.closed = false;
37
+ this.connecting = null;
38
+ /** @type {Set<(method:string, params:unknown)=>void>} */
39
+ this.listeners = new Set();
40
+ }
41
+
42
+ /** @returns {Promise<BridgeClient>} */
43
+ async connect() {
44
+ if (this.closed) throw new Error("Browser bridge client is closed");
45
+ if (this.socket) return this;
46
+ this.connecting ??= this.#open().finally(() => { this.connecting = null; });
47
+ await this.connecting;
48
+ return this;
49
+ }
50
+
51
+ /** @returns {Promise<void>} */
52
+ async #open() {
53
+ const socketPath = await readBackend(this.bridgeFile);
54
+ const socket = createConnection({ path: socketPath });
55
+ this.socket = socket;
56
+ socket.on("data", (chunk) => this.#onData(chunk));
57
+ socket.on("error", (error) => this.#fail(error));
58
+ socket.on("close", () => this.#fail(new Error("Browser bridge connection closed")));
59
+ await new Promise((resolve, reject) => {
60
+ const timer = setTimeout(() => {
61
+ socket.destroy();
62
+ reject(new Error(`Browser bridge connection timed out after ${this.connectTimeoutMs}ms`));
63
+ }, this.connectTimeoutMs);
64
+ socket.once("connect", () => {
65
+ clearTimeout(timer);
66
+ resolve();
67
+ });
68
+ socket.once("error", (error) => {
69
+ clearTimeout(timer);
70
+ reject(error);
71
+ });
72
+ });
73
+ }
74
+
75
+ /** @param {(method:string, params:unknown)=>void} listener @returns {()=>void} */
76
+ onEvent(listener) {
77
+ this.listeners.add(listener);
78
+ return () => this.listeners.delete(listener);
79
+ }
80
+
81
+ /**
82
+ * Call one bridge RPC method.
83
+ * @param {string} method
84
+ * @param {Record<string, unknown>} params
85
+ * @param {{timeoutMs?:number}} [options]
86
+ * @returns {Promise<unknown>}
87
+ */
88
+ async request(method, params = {}, { timeoutMs = this.requestTimeoutMs } = {}) {
89
+ await this.connect();
90
+ const socket = this.socket;
91
+ if (!socket || socket.destroyed) throw new Error("Browser bridge connection is unavailable");
92
+ const id = this.nextId++;
93
+ return await new Promise((resolve, reject) => {
94
+ const timer = setTimeout(() => {
95
+ this.pending.delete(id);
96
+ reject(new Error(`Browser bridge request timed out: ${method}`));
97
+ }, timeoutMs);
98
+ this.pending.set(id, { resolve, reject, timer });
99
+ try {
100
+ socket.write(encodeFrame({ jsonrpc: "2.0", id, method, params }, {
101
+ littleEndian,
102
+ maxFrameBytes,
103
+ overflowError: "Browser bridge request exceeds frame limit",
104
+ }));
105
+ } catch (error) {
106
+ clearTimeout(timer);
107
+ this.pending.delete(id);
108
+ reject(error instanceof Error ? error : new Error(String(error)));
109
+ }
110
+ });
111
+ }
112
+
113
+ /** @param {Buffer} chunk @returns {void} */
114
+ #onData(chunk) {
115
+ try {
116
+ this.reader.push(chunk);
117
+ let body;
118
+ while ((body = this.reader.nextFrame()) !== null) {
119
+ let message;
120
+ try {
121
+ message = JSON.parse(body.toString("utf8"));
122
+ } catch (error) {
123
+ this.#fail(new Error(`Invalid browser bridge response: ${error.message}`));
124
+ return;
125
+ }
126
+ this.#dispatch(message);
127
+ }
128
+ } catch (error) {
129
+ this.#fail(error instanceof Error ? error : new Error(String(error)));
130
+ }
131
+ }
132
+
133
+ /** @param {Record<string, unknown>} message @returns {void} */
134
+ #dispatch(message) {
135
+ if (!Number.isSafeInteger(message.id)) {
136
+ if (typeof message.method === "string") {
137
+ for (const listener of this.listeners) listener(message.method, message.params);
138
+ }
139
+ return;
140
+ }
141
+ const entry = this.pending.get(Number(message.id));
142
+ if (!entry) return;
143
+ this.pending.delete(Number(message.id));
144
+ clearTimeout(entry.timer);
145
+ if (message.error && typeof message.error === "object") {
146
+ entry.reject(new Error(String(message.error.message ?? "Browser bridge request failed")));
147
+ } else {
148
+ entry.resolve(message.result ?? null);
149
+ }
150
+ }
151
+
152
+ /** @param {Error} error @returns {void} */
153
+ #fail(error) {
154
+ if (this.closed) return;
155
+ this.closed = true;
156
+ for (const entry of this.pending.values()) {
157
+ clearTimeout(entry.timer);
158
+ entry.reject(error);
159
+ }
160
+ this.pending.clear();
161
+ }
162
+
163
+ /** @returns {Promise<void>} */
164
+ async close() {
165
+ if (this.closed) return;
166
+ this.closed = true;
167
+ const socket = this.socket;
168
+ this.socket = null;
169
+ for (const entry of this.pending.values()) {
170
+ clearTimeout(entry.timer);
171
+ entry.reject(new Error("Browser bridge client closed"));
172
+ }
173
+ this.pending.clear();
174
+ if (!socket || socket.destroyed) return;
175
+ await new Promise((resolve) => {
176
+ socket.once("close", resolve);
177
+ socket.end();
178
+ setTimeout(() => socket.destroy(), 1_000).unref();
179
+ });
180
+ }
181
+ }
package/src/config.js ADDED
@@ -0,0 +1,166 @@
1
+ import { existsSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { homedir } from "node:os";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const SERVER_PATH = fileURLToPath(new URL("./server.js", import.meta.url));
7
+ const HOMEBREW_NODE_LINK = "/opt/homebrew/bin/node";
8
+
9
+ /**
10
+ * Prefer Homebrew's unversioned symlink over a Cellar path so `brew upgrade node`
11
+ * does not break existing client configs.
12
+ * @returns {string}
13
+ */
14
+ export function stableNodePath() {
15
+ if (
16
+ /^\/opt\/homebrew\/Cellar\/node\/[^/]+\/bin\/node$/u.test(process.execPath) &&
17
+ existsSync(HOMEBREW_NODE_LINK)
18
+ ) {
19
+ return HOMEBREW_NODE_LINK;
20
+ }
21
+ return process.execPath;
22
+ }
23
+
24
+ /**
25
+ * Recommend the most token-efficient tool profile for a client host:
26
+ * lazy-loading IDE clients can use `full`, while CLI/non-lazy hosts benefit from `compact`.
27
+ * @param {string} client
28
+ * @returns {"compact"|"full"}
29
+ */
30
+ export function recommendedProfileForClient(client) {
31
+ const name = normalizeClient(client);
32
+ return ["antigravity", "cursor", "windsurf"].includes(name) ? "full" : "compact";
33
+ }
34
+
35
+ /**
36
+ * Print a mergeable client fragment; never write a client's configuration.
37
+ * @param {string} client
38
+ * @param {{nodePath?:string, serverPath?:string, bridgeFile?:string, profile?:string}} [options]
39
+ * @returns {Record<string, any>}
40
+ */
41
+ export function buildConfig(client, options = {}) {
42
+ const command = options.nodePath ?? stableNodePath();
43
+ const args = [options.serverPath ?? SERVER_PATH];
44
+ const effectiveProfile = options.profile === "auto"
45
+ ? recommendedProfileForClient(client)
46
+ : options.profile;
47
+ if (effectiveProfile && effectiveProfile !== "full") {
48
+ args.push("--profile", effectiveProfile);
49
+ }
50
+ const env = options.bridgeFile ? { BROWSER_USE_BRIDGE_FILE: path.resolve(options.bridgeFile) } : {};
51
+ const name = "browser-use";
52
+ if (client === "opencode" || client === "opencode2") {
53
+ return {
54
+ $schema: "https://opencode.ai/config.json",
55
+ mcp: { servers: { [name]: { type: "local", command: [command, ...args], environment: env, disabled: false } } },
56
+ };
57
+ }
58
+ if (client === "codex") {
59
+ return { mcp_servers: { [name]: { command, args, env, startup_timeout_sec: 30, tool_timeout_sec: 180 } } };
60
+ }
61
+ if (client === "antigravity" || client === "agy") {
62
+ return {
63
+ mcpServers: {
64
+ [name]: {
65
+ command,
66
+ args,
67
+ env,
68
+ tools: {
69
+ browser_run: { eager: true },
70
+ browser_batch: { eager: true },
71
+ browser_get_state: { eager: true },
72
+ browser_end_turn: { eager: true },
73
+ },
74
+ },
75
+ },
76
+ };
77
+ }
78
+ if (client === "copilot" || client === "github-copilot") {
79
+ return { mcpServers: { "browser-use-portable": { command, args, env, type: "local", tools: ["*"] } } };
80
+ }
81
+ if (client === "commandcode" || client === "command-code") {
82
+ return { mcpServers: { [name]: { transport: "stdio", enabled: true, command, args, env } } };
83
+ }
84
+ if (["generic", "claude_code", "claude", "cursor", "windsurf"].includes(client)) {
85
+ return { mcpServers: { [name]: { command, args, env } } };
86
+ }
87
+ throw new Error(`Unknown client ${JSON.stringify(client)}. Choose generic, claude_code, commandcode, copilot, antigravity, cursor, windsurf, opencode, or codex.`);
88
+ }
89
+
90
+ /** @param {Record<string, any>} config @returns {string} */
91
+ export function codexToml(config) {
92
+ const server = config.mcp_servers["browser-use"];
93
+ const environment = Object.entries(server.env).map(([key, value]) => `${key} = ${JSON.stringify(value)}`).join("\n");
94
+ return `[mcp_servers.browser-use]\ncommand = ${JSON.stringify(server.command)}\nargs = ${JSON.stringify(server.args)}\nstartup_timeout_sec = ${server.startup_timeout_sec}\ntool_timeout_sec = ${server.tool_timeout_sec}\n\n[mcp_servers.browser-use.env]\n${environment}\n`;
95
+ }
96
+
97
+ /**
98
+ * Where each client keeps its MCP settings. `null` means the CLI prints a
99
+ * fragment instead of writing, because the file is TOML, JSONC, or shared.
100
+ * @param {string} client
101
+ * @param {string} [home]
102
+ * @returns {{file:string|null, key:"mcpServers"|"mcp.servers"}}
103
+ */
104
+ export function clientTarget(client, home = homedir()) {
105
+ switch (normalizeClient(client)) {
106
+ case "commandcode": return { file: path.join(home, ".commandcode", "mcp.json"), key: "mcpServers" };
107
+ case "claude_code": return { file: path.join(home, ".claude.json"), key: "mcpServers" };
108
+ case "copilot": return { file: path.join(home, ".copilot", "mcp-config.json"), key: "mcpServers" };
109
+ case "antigravity": return { file: path.join(home, ".gemini", "config", "mcp_config.json"), key: "mcpServers" };
110
+ case "cursor": return { file: path.join(home, ".cursor", "mcp.json"), key: "mcpServers" };
111
+ case "windsurf": return { file: path.join(home, ".codeium", "windsurf", "mcp_config.json"), key: "mcpServers" };
112
+ default: return { file: null, key: "mcpServers" };
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Where each client keeps its installed `codex-browser-use` skill markdown.
118
+ * @param {string} client
119
+ * @param {string} [home]
120
+ * @returns {string}
121
+ */
122
+ export function clientSkillTarget(client, home = homedir()) {
123
+ const dir = "codex-browser-use";
124
+ switch (normalizeClient(client)) {
125
+ case "antigravity": return path.join(home, ".gemini", "config", "skills", dir, "SKILL.md");
126
+ case "claude_code": return path.join(home, ".claude", "skills", dir, "SKILL.md");
127
+ case "codex": return path.join(home, ".codex", "skills", dir, "SKILL.md");
128
+ case "cursor": return path.join(home, ".cursor", "skills", dir, "SKILL.md");
129
+ case "windsurf": return path.join(home, ".codeium", "windsurf", "skills", dir, "SKILL.md");
130
+ default: return path.join(home, ".agents", "skills", dir, "SKILL.md");
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Where each client keeps its always-on browser-use rules file (`file: null` when skills alone apply).
136
+ * @param {string} client
137
+ * @param {string} [home]
138
+ * @returns {{file:string|null, format:"md"|"mdc"|null}}
139
+ */
140
+ export function clientRuleTarget(client, home = homedir()) {
141
+ switch (normalizeClient(client)) {
142
+ case "antigravity":
143
+ return { file: path.join(home, ".gemini", "config", "rules", "browser_use.md"), format: "md" };
144
+ case "cursor":
145
+ return { file: path.join(home, ".cursor", "rules", "browser_use.mdc"), format: "mdc" };
146
+ case "windsurf":
147
+ return { file: path.join(home, ".codeium", "windsurf", "rules", "browser_use.md"), format: "md" };
148
+ case "commandcode":
149
+ case "copilot":
150
+ case "opencode":
151
+ case "generic":
152
+ return { file: path.join(home, ".agents", "rules", "browser_use.md"), format: "md" };
153
+ default:
154
+ return { file: null, format: null };
155
+ }
156
+ }
157
+
158
+ /** @param {string} client @returns {string} */
159
+ export function normalizeClient(client) {
160
+ if (client === "command-code") return "commandcode";
161
+ if (client === "claude" || client === "claude-code") return "claude_code";
162
+ if (client === "github-copilot") return "copilot";
163
+ if (client === "agy") return "antigravity";
164
+ if (client === "opencode2") return "opencode";
165
+ return client;
166
+ }