codex-browser-use 4.8.3 → 4.9.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/README.md +5 -5
- package/bin/browser-use.js +67 -11
- package/extension/background.js +419 -137
- package/extension/manifest.json +2 -10
- package/package.json +2 -2
- package/rules/browser_use.md +6 -20
- package/skill/SKILL.md +7 -7
- package/skill/references/cookbook.md +3 -3
- package/src/ax-tree.js +63 -35
- package/src/backend-discovery.js +15 -8
- package/src/backend-native-driver.js +38 -12
- package/src/backend-tabs.js +93 -7
- package/src/backend-transport.js +3 -3
- package/src/bridge-browser.js +383 -113
- package/src/config.js +44 -11
- package/src/content-extractor.js +53 -19
- package/src/extension.js +6 -1
- package/src/install.js +243 -19
- package/src/locators.js +259 -36
- package/src/read-only.js +254 -52
- package/src/script-runner.js +199 -48
- package/src/server.js +64 -26
package/src/config.js
CHANGED
|
@@ -1,24 +1,57 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { homedir } from "node:os";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
5
|
|
|
6
6
|
const SERVER_PATH = fileURLToPath(new URL("./server.js", import.meta.url));
|
|
7
|
-
const
|
|
7
|
+
const HOMEBREW_ARM_NODE_LINK = "/opt/homebrew/bin/node";
|
|
8
|
+
const HOMEBREW_INTEL_NODE_LINK = "/usr/local/bin/node";
|
|
8
9
|
|
|
9
10
|
/**
|
|
10
|
-
* Prefer
|
|
11
|
-
* does not break
|
|
11
|
+
* Prefer an unversioned/alias Node binary over ephemeral Cellar, Volta image,
|
|
12
|
+
* or `fnm` multishell paths so `brew upgrade` / shell exit does not break configs.
|
|
13
|
+
* @param {string} [execPath]
|
|
14
|
+
* @param {(p:string)=>boolean} [fileExists]
|
|
15
|
+
* @param {string} [home]
|
|
12
16
|
* @returns {string}
|
|
13
17
|
*/
|
|
14
|
-
export function stableNodePath() {
|
|
15
|
-
if (
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
) {
|
|
19
|
-
return
|
|
18
|
+
export function stableNodePath(execPath = process.execPath, fileExists = existsSync, home = homedir()) {
|
|
19
|
+
if (/^\/opt\/homebrew\/Cellar\/node(?:@[\d.]+)?\/[^/]+\/bin\/node$/u.test(execPath) && fileExists(HOMEBREW_ARM_NODE_LINK)) {
|
|
20
|
+
return HOMEBREW_ARM_NODE_LINK;
|
|
21
|
+
}
|
|
22
|
+
if (/^\/usr\/local\/Cellar\/node(?:@[\d.]+)?\/[^/]+\/bin\/node$/u.test(execPath) && fileExists(HOMEBREW_INTEL_NODE_LINK)) {
|
|
23
|
+
return HOMEBREW_INTEL_NODE_LINK;
|
|
24
|
+
}
|
|
25
|
+
if (/[/\\]\.volta[/\\]tools[/\\]image[/\\]node[/\\][^/\\]+[/\\]bin[/\\]node(?:\.exe)?$/u.test(execPath)) {
|
|
26
|
+
const voltaBin = path.join(home, ".volta", "bin", process.platform === "win32" ? "node.exe" : "node");
|
|
27
|
+
if (fileExists(voltaBin)) return voltaBin;
|
|
28
|
+
}
|
|
29
|
+
if (/[/\\]fnm_multishells[/\\][^/\\]+[/\\]bin[/\\]node(?:\.exe)?$/u.test(execPath)) {
|
|
30
|
+
for (const candidate of [
|
|
31
|
+
path.join(home, ".local", "share", "fnm", "aliases", "default", "bin", "node"),
|
|
32
|
+
path.join(home, ".fnm", "aliases", "default", "bin", "node"),
|
|
33
|
+
path.join(home, "Library", "Application Support", "fnm", "aliases", "default", "bin", "node"),
|
|
34
|
+
]) {
|
|
35
|
+
if (fileExists(candidate)) return candidate;
|
|
36
|
+
}
|
|
20
37
|
}
|
|
21
|
-
return
|
|
38
|
+
return execPath;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Detect temporary/ephemeral package paths (e.g. `npx` `_npx` cache or OS temp dirs)
|
|
43
|
+
* that should not be hardcoded into persistent configs or native messaging launchers.
|
|
44
|
+
* @param {string} filePath
|
|
45
|
+
* @returns {boolean}
|
|
46
|
+
*/
|
|
47
|
+
export function isEphemeralPackagePath(filePath) {
|
|
48
|
+
const resolved = path.resolve(String(filePath || ""));
|
|
49
|
+
if (/(?:^|[/\\])_npx(?:[/\\]|$)/u.test(resolved)) return true;
|
|
50
|
+
if (/(?:^|[/\\])npm-cache[/\\]_npx(?:[/\\]|$)/u.test(resolved)) return true;
|
|
51
|
+
const tmp = path.resolve(tmpdir());
|
|
52
|
+
if (resolved === tmp || resolved.startsWith(`${tmp}${path.sep}`)) return true;
|
|
53
|
+
if (/^\/(?:private\/)?var\/folders\//u.test(resolved)) return true;
|
|
54
|
+
return false;
|
|
22
55
|
}
|
|
23
56
|
|
|
24
57
|
/**
|
package/src/content-extractor.js
CHANGED
|
@@ -48,25 +48,27 @@ export function extractContentExpression({ format = "markdown", maxChars = 16_00
|
|
|
48
48
|
|
|
49
49
|
const tagOf = (el) => String(el && el.tagName ? el.tagName : "").toUpperCase();
|
|
50
50
|
|
|
51
|
+
const ownHiddenCache = typeof WeakMap === "function" ? new WeakMap() : null;
|
|
51
52
|
const isOwnHidden = (el) => {
|
|
52
53
|
if (!el || el.nodeType !== 1) return false;
|
|
53
|
-
if (
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (typeof getComputedStyle === "function") {
|
|
54
|
+
if (ownHiddenCache && ownHiddenCache.has(el)) return ownHiddenCache.get(el);
|
|
55
|
+
let hidden = false;
|
|
56
|
+
if (el.hidden === true) hidden = true;
|
|
57
|
+
else if (typeof el.getAttribute === "function" &&
|
|
58
|
+
(el.getAttribute("hidden") !== null || el.getAttribute("aria-hidden") === "true")) {
|
|
59
|
+
hidden = true;
|
|
60
|
+
} else if (el.style && (el.style.display === "none" || el.style.visibility === "hidden")) {
|
|
61
|
+
hidden = true;
|
|
62
|
+
} else if (typeof getComputedStyle === "function") {
|
|
62
63
|
try {
|
|
63
64
|
const cs = getComputedStyle(el);
|
|
64
|
-
if (cs && (cs.display === "none" || cs.visibility === "hidden"))
|
|
65
|
+
if (cs && (cs.display === "none" || cs.visibility === "hidden")) hidden = true;
|
|
65
66
|
} catch (_err) {
|
|
66
67
|
// Ignore detached or cross-realm elements.
|
|
67
68
|
}
|
|
68
69
|
}
|
|
69
|
-
|
|
70
|
+
if (ownHiddenCache) ownHiddenCache.set(el, hidden);
|
|
71
|
+
return hidden;
|
|
70
72
|
};
|
|
71
73
|
|
|
72
74
|
const isElementVisible = (el) => {
|
|
@@ -235,8 +237,9 @@ export function extractContentExpression({ format = "markdown", maxChars = 16_00
|
|
|
235
237
|
};
|
|
236
238
|
|
|
237
239
|
const extractLinksList = (root) => {
|
|
238
|
-
const
|
|
239
|
-
|
|
240
|
+
const queried = queryAll(root, "a[href]");
|
|
241
|
+
const anchors = queried.length > 0
|
|
242
|
+
? queried
|
|
240
243
|
: collectElementsByTags(root, ["A"]).filter((a) => getAttr(a, "href") !== null || Boolean(a.href));
|
|
241
244
|
const seen = new Set();
|
|
242
245
|
const links = [];
|
|
@@ -265,8 +268,9 @@ export function extractContentExpression({ format = "markdown", maxChars = 16_00
|
|
|
265
268
|
};
|
|
266
269
|
|
|
267
270
|
const countVisibleTables = (root) => {
|
|
268
|
-
const
|
|
269
|
-
|
|
271
|
+
const queried = queryAll(root, "table");
|
|
272
|
+
const tables = queried.length > 0
|
|
273
|
+
? queried
|
|
270
274
|
: collectElementsByTags(root, ["TABLE"]);
|
|
271
275
|
return tables.filter((t) => isElementVisible(t));
|
|
272
276
|
};
|
|
@@ -475,12 +479,42 @@ export function extractContentExpression({ format = "markdown", maxChars = 16_00
|
|
|
475
479
|
);
|
|
476
480
|
const body = (document && (document.body || document.documentElement)) || null;
|
|
477
481
|
const visibleTables = body ? countVisibleTables(body) : [];
|
|
478
|
-
const allLinks = body ? extractLinksList(body) :
|
|
482
|
+
const allLinks = body && FORMAT === "links" ? extractLinksList(body) : null;
|
|
479
483
|
const tablesCount = visibleTables.length;
|
|
480
|
-
const linksCount = allLinks
|
|
484
|
+
const linksCount = allLinks
|
|
485
|
+
? allLinks.length
|
|
486
|
+
: (body ? queryAll(body, "a[href]").length : 0);
|
|
481
487
|
|
|
482
488
|
if (FORMAT === "tables") {
|
|
483
|
-
const
|
|
489
|
+
const allTables = visibleTables.map((t) => extractTableData(t));
|
|
490
|
+
const tables = [];
|
|
491
|
+
let usedTableChars = 0;
|
|
492
|
+
let tablesTruncated = false;
|
|
493
|
+
for (let i = 0; i < allTables.length; i++) {
|
|
494
|
+
const tbl = allTables[i];
|
|
495
|
+
const sz = JSON.stringify(tbl).length;
|
|
496
|
+
if (tables.length === 0 && sz > MAX_CHARS && Array.isArray(tbl.rows)) {
|
|
497
|
+
const rows = [];
|
|
498
|
+
let acc = JSON.stringify({ headers: tbl.headers || [], rows: [] }).length;
|
|
499
|
+
for (const row of tbl.rows) {
|
|
500
|
+
const rowLen = JSON.stringify(row).length + 1;
|
|
501
|
+
if (rows.length > 0 && acc + rowLen > MAX_CHARS) {
|
|
502
|
+
tablesTruncated = true;
|
|
503
|
+
break;
|
|
504
|
+
}
|
|
505
|
+
rows.push(row);
|
|
506
|
+
acc += rowLen;
|
|
507
|
+
}
|
|
508
|
+
tables.push({ ...tbl, rows });
|
|
509
|
+
break;
|
|
510
|
+
}
|
|
511
|
+
if (tables.length > 0 && usedTableChars + sz > MAX_CHARS) {
|
|
512
|
+
tablesTruncated = true;
|
|
513
|
+
break;
|
|
514
|
+
}
|
|
515
|
+
tables.push(tbl);
|
|
516
|
+
usedTableChars += sz;
|
|
517
|
+
}
|
|
484
518
|
const rendered = tables
|
|
485
519
|
.map((t) => renderTableMarkdown(t))
|
|
486
520
|
.filter(Boolean)
|
|
@@ -492,7 +526,7 @@ export function extractContentExpression({ format = "markdown", maxChars = 16_00
|
|
|
492
526
|
format: FORMAT,
|
|
493
527
|
text: clipped.text,
|
|
494
528
|
content: clipped.text,
|
|
495
|
-
truncated: clipped.truncated,
|
|
529
|
+
truncated: clipped.truncated || tablesTruncated,
|
|
496
530
|
tablesCount,
|
|
497
531
|
linksCount,
|
|
498
532
|
tables,
|
package/src/extension.js
CHANGED
|
@@ -7,7 +7,7 @@ export { defaultBridgeFile };
|
|
|
7
7
|
|
|
8
8
|
export const HOST_NAME = "com.portable_browser_use.bridge";
|
|
9
9
|
export const EXTENSION_ID = "ehooacpcolldccnemjebdnmfgmgekghn";
|
|
10
|
-
export const EXTENSION_VERSION = "0.
|
|
10
|
+
export const EXTENSION_VERSION = "0.7.0";
|
|
11
11
|
export const extensionSource = fileURLToPath(new URL("../extension", import.meta.url));
|
|
12
12
|
|
|
13
13
|
/** @returns {string} */
|
|
@@ -20,6 +20,11 @@ export function installedExtensionDir() {
|
|
|
20
20
|
return path.join(dataRoot(), "extension");
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/** @returns {string} */
|
|
24
|
+
export function installedRuntimeDir() {
|
|
25
|
+
return path.join(dataRoot(), "runtime");
|
|
26
|
+
}
|
|
27
|
+
|
|
23
28
|
/** @returns {string} */
|
|
24
29
|
export function nativeHostLauncher() {
|
|
25
30
|
return path.join(dataRoot(), "chrome-host", "launch.sh");
|
package/src/install.js
CHANGED
|
@@ -10,10 +10,12 @@ import {
|
|
|
10
10
|
defaultBridgeFile,
|
|
11
11
|
extensionSource,
|
|
12
12
|
installedExtensionDir,
|
|
13
|
+
installedRuntimeDir,
|
|
13
14
|
nativeHostLauncher,
|
|
14
15
|
} from "./extension.js";
|
|
15
|
-
import { buildConfig, clientRuleTarget, clientSkillTarget, clientTarget, normalizeClient, stableNodePath } from "./config.js";
|
|
16
|
+
import { buildConfig, clientRuleTarget, clientSkillTarget, clientTarget, isEphemeralPackagePath, normalizeClient, stableNodePath } from "./config.js";
|
|
16
17
|
|
|
18
|
+
const packageRoot = fileURLToPath(new URL("..", import.meta.url));
|
|
17
19
|
const nativeHostEntry = fileURLToPath(new URL("../bin/chrome-native-host.js", import.meta.url));
|
|
18
20
|
const repoSkillSource = fileURLToPath(new URL("../../skill/SKILL.md", import.meta.url));
|
|
19
21
|
const localSkillSource = fileURLToPath(new URL("../skill/SKILL.md", import.meta.url));
|
|
@@ -86,6 +88,7 @@ async function backupOnce(file) {
|
|
|
86
88
|
|
|
87
89
|
/**
|
|
88
90
|
* Copy the bundled extension to a stable path and report its pinned ID.
|
|
91
|
+
* Verifies critical bundle files in addition to version and rolls back on rename failure.
|
|
89
92
|
* @param {{source?:string, destination?:string}} [options]
|
|
90
93
|
*/
|
|
91
94
|
export async function installExtension({ source = extensionSource, destination = installedExtensionDir() } = {}) {
|
|
@@ -97,19 +100,148 @@ export async function installExtension({ source = extensionSource, destination =
|
|
|
97
100
|
try {
|
|
98
101
|
const existing = JSON.parse(await readFile(path.join(destination, "manifest.json"), "utf8"));
|
|
99
102
|
changed = existing.version !== manifest.version;
|
|
103
|
+
if (!changed) {
|
|
104
|
+
for (const critical of ["background.js", "content-script.js"]) {
|
|
105
|
+
const srcStat = await stat(path.join(source, critical)).catch(() => null);
|
|
106
|
+
if (!srcStat?.isFile()) continue;
|
|
107
|
+
const dstStat = await stat(path.join(destination, critical));
|
|
108
|
+
if (!dstStat.isFile() || dstStat.size !== srcStat.size) {
|
|
109
|
+
changed = true;
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
100
114
|
} catch {
|
|
101
115
|
changed = true;
|
|
102
116
|
}
|
|
103
117
|
if (changed) {
|
|
104
118
|
const temporary = `${destination}.tmp-${randomUUID()}`;
|
|
105
|
-
await
|
|
106
|
-
|
|
107
|
-
|
|
119
|
+
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
|
|
120
|
+
let backup = null;
|
|
121
|
+
try {
|
|
122
|
+
await cp(source, temporary, { recursive: true });
|
|
123
|
+
backup = await backupDirectory(destination);
|
|
124
|
+
await rename(temporary, destination);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
await rm(temporary, { recursive: true, force: true }).catch(() => {});
|
|
127
|
+
if (backup) {
|
|
128
|
+
await rename(backup, destination).catch(() => {});
|
|
129
|
+
}
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
108
132
|
return { path: destination, id: EXTENSION_ID, version: manifest.version, changed: true, backup };
|
|
109
133
|
}
|
|
110
134
|
return { path: destination, id: EXTENSION_ID, version: manifest.version, changed: false, backup: null };
|
|
111
135
|
}
|
|
112
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Resolve runtime `node_modules` directory (package-local or hoisted parent for `_npx`)
|
|
139
|
+
* and copy only runtime dependencies + transitive packages into `destNodeModules`.
|
|
140
|
+
* @param {string} sourceRoot
|
|
141
|
+
* @param {string} destNodeModules
|
|
142
|
+
*/
|
|
143
|
+
async function copyRuntimeDependencies(sourceRoot, destNodeModules) {
|
|
144
|
+
const pkg = JSON.parse(await readFile(path.join(sourceRoot, "package.json"), "utf8"));
|
|
145
|
+
const roots = Object.keys(pkg.dependencies ?? {});
|
|
146
|
+
if (roots.length === 0) return;
|
|
147
|
+
|
|
148
|
+
const searchBases = [path.join(sourceRoot, "node_modules")];
|
|
149
|
+
let cur = path.dirname(sourceRoot);
|
|
150
|
+
for (let i = 0; i < 4; i++) {
|
|
151
|
+
const candidate = path.basename(cur) === "node_modules" ? cur : path.join(cur, "node_modules");
|
|
152
|
+
if (!searchBases.includes(candidate)) searchBases.push(candidate);
|
|
153
|
+
const parent = path.dirname(cur);
|
|
154
|
+
if (parent === cur) break;
|
|
155
|
+
cur = parent;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** @param {string} pkgName @param {string} fromDir @returns {Promise<string|null>} */
|
|
159
|
+
async function findPackageDir(pkgName, fromDir) {
|
|
160
|
+
const candidates = fromDir ? [path.join(fromDir, "node_modules", pkgName), ...searchBases.map((b) => path.join(b, pkgName))] : searchBases.map((b) => path.join(b, pkgName));
|
|
161
|
+
for (const dir of candidates) {
|
|
162
|
+
try {
|
|
163
|
+
const info = await stat(path.join(dir, "package.json"));
|
|
164
|
+
if (info.isFile()) return dir;
|
|
165
|
+
} catch {
|
|
166
|
+
// Try next candidate.
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const visited = new Set();
|
|
173
|
+
const queue = roots.map((name) => ({ name, fromDir: sourceRoot }));
|
|
174
|
+
await mkdir(destNodeModules, { recursive: true, mode: 0o755 });
|
|
175
|
+
while (queue.length > 0) {
|
|
176
|
+
const { name, fromDir } = queue.shift();
|
|
177
|
+
if (visited.has(name)) continue;
|
|
178
|
+
const found = await findPackageDir(name, fromDir);
|
|
179
|
+
if (!found) continue;
|
|
180
|
+
visited.add(name);
|
|
181
|
+
const destPkg = path.join(destNodeModules, ...name.split("/"));
|
|
182
|
+
await mkdir(path.dirname(destPkg), { recursive: true, mode: 0o755 });
|
|
183
|
+
await cp(found, destPkg, {
|
|
184
|
+
recursive: true,
|
|
185
|
+
dereference: true,
|
|
186
|
+
filter: (src) => path.basename(src) !== ".bin",
|
|
187
|
+
});
|
|
188
|
+
try {
|
|
189
|
+
const depPkg = JSON.parse(await readFile(path.join(found, "package.json"), "utf8"));
|
|
190
|
+
for (const depName of [...Object.keys(depPkg.dependencies ?? {}), ...Object.keys(depPkg.optionalDependencies ?? {})]) {
|
|
191
|
+
if (!visited.has(depName)) queue.push({ name: depName, fromDir: found });
|
|
192
|
+
}
|
|
193
|
+
} catch {
|
|
194
|
+
// Ignore malformed dependency package.json.
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Stage a persistent self-contained MCP + native host runtime so ephemeral `npx` caches
|
|
201
|
+
* can be pruned without breaking installed browser native messaging or MCP configs.
|
|
202
|
+
* @param {{sourceRoot?:string, destination?:string}} [options]
|
|
203
|
+
* @returns {Promise<{staged:boolean, dir:string, serverPath:string, nativeHostEntry:string}>}
|
|
204
|
+
*/
|
|
205
|
+
export async function stageRuntime({ sourceRoot = packageRoot, destination = installedRuntimeDir() } = {}) {
|
|
206
|
+
const temporary = `${destination}.tmp-${randomUUID()}`;
|
|
207
|
+
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 });
|
|
208
|
+
let backup = null;
|
|
209
|
+
try {
|
|
210
|
+
await mkdir(temporary, { recursive: true, mode: 0o755 });
|
|
211
|
+
await cp(path.join(sourceRoot, "package.json"), path.join(temporary, "package.json"));
|
|
212
|
+
await cp(path.join(sourceRoot, "bin"), path.join(temporary, "bin"), { recursive: true, dereference: true });
|
|
213
|
+
await cp(path.join(sourceRoot, "src"), path.join(temporary, "src"), { recursive: true, dereference: true });
|
|
214
|
+
await cp(path.join(sourceRoot, "extension"), path.join(temporary, "extension"), { recursive: true, dereference: true });
|
|
215
|
+
await copyRuntimeDependencies(sourceRoot, path.join(temporary, "node_modules"));
|
|
216
|
+
backup = await backupDirectory(destination);
|
|
217
|
+
await rename(temporary, destination);
|
|
218
|
+
} catch (error) {
|
|
219
|
+
await rm(temporary, { recursive: true, force: true }).catch(() => {});
|
|
220
|
+
if (backup) await rename(backup, destination).catch(() => {});
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
return {
|
|
224
|
+
staged: true,
|
|
225
|
+
dir: destination,
|
|
226
|
+
serverPath: path.join(destination, "src", "server.js"),
|
|
227
|
+
nativeHostEntry: path.join(destination, "bin", "chrome-native-host.js"),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Resolve permanent entrypoints for `install`, auto-staging when running from `_npx` or temp dirs.
|
|
233
|
+
* @param {{stageIfEphemeral?:boolean, destination?:string}} [options]
|
|
234
|
+
* @returns {Promise<{staged:boolean, serverPath:string, nativeHostEntry:string}>}
|
|
235
|
+
*/
|
|
236
|
+
export async function resolveRuntimePaths({ stageIfEphemeral = true, destination = installedRuntimeDir() } = {}) {
|
|
237
|
+
const directServer = fileURLToPath(new URL("./server.js", import.meta.url));
|
|
238
|
+
if (stageIfEphemeral && isEphemeralPackagePath(nativeHostEntry)) {
|
|
239
|
+
const staged = await stageRuntime({ sourceRoot: packageRoot, destination });
|
|
240
|
+
return { staged: true, serverPath: staged.serverPath, nativeHostEntry: staged.nativeHostEntry };
|
|
241
|
+
}
|
|
242
|
+
return { staged: false, serverPath: directServer, nativeHostEntry };
|
|
243
|
+
}
|
|
244
|
+
|
|
113
245
|
/** @param {string} destination @returns {Promise<string|null>} */
|
|
114
246
|
async function backupDirectory(destination) {
|
|
115
247
|
try {
|
|
@@ -131,17 +263,28 @@ export function nativeMessagingDirs() {
|
|
|
131
263
|
const support = path.join(home, "Library", "Application Support");
|
|
132
264
|
return [
|
|
133
265
|
path.join(support, "Google", "Chrome", "NativeMessagingHosts"),
|
|
266
|
+
path.join(support, "Google", "Chrome Beta", "NativeMessagingHosts"),
|
|
267
|
+
path.join(support, "Google", "Chrome Canary", "NativeMessagingHosts"),
|
|
268
|
+
path.join(support, "Google", "Chrome Dev", "NativeMessagingHosts"),
|
|
269
|
+
path.join(support, "Google", "Chrome for Testing", "NativeMessagingHosts"),
|
|
134
270
|
path.join(support, "Chromium", "NativeMessagingHosts"),
|
|
271
|
+
path.join(support, "Arc", "User Data", "NativeMessagingHosts"),
|
|
135
272
|
path.join(support, "Microsoft Edge", "NativeMessagingHosts"),
|
|
136
273
|
path.join(support, "BraveSoftware", "Brave-Browser", "NativeMessagingHosts"),
|
|
274
|
+
path.join(support, "Vivaldi", "NativeMessagingHosts"),
|
|
275
|
+
path.join(support, "com.operasoftware.Opera", "NativeMessagingHosts"),
|
|
137
276
|
];
|
|
138
277
|
}
|
|
139
278
|
if (process.platform === "linux") {
|
|
140
279
|
return [
|
|
141
280
|
path.join(home, ".config", "google-chrome", "NativeMessagingHosts"),
|
|
281
|
+
path.join(home, ".config", "google-chrome-beta", "NativeMessagingHosts"),
|
|
282
|
+
path.join(home, ".config", "google-chrome-unstable", "NativeMessagingHosts"),
|
|
142
283
|
path.join(home, ".config", "chromium", "NativeMessagingHosts"),
|
|
143
284
|
path.join(home, ".config", "microsoft-edge", "NativeMessagingHosts"),
|
|
144
285
|
path.join(home, ".config", "BraveSoftware", "Brave-Browser", "NativeMessagingHosts"),
|
|
286
|
+
path.join(home, ".config", "vivaldi", "NativeMessagingHosts"),
|
|
287
|
+
path.join(home, ".config", "opera", "NativeMessagingHosts"),
|
|
145
288
|
];
|
|
146
289
|
}
|
|
147
290
|
throw new Error("Native host installation supports macOS and Linux; on Windows, register the host with the Chrome registry key manually");
|
|
@@ -149,11 +292,24 @@ export function nativeMessagingDirs() {
|
|
|
149
292
|
|
|
150
293
|
/**
|
|
151
294
|
* Write the launcher and native messaging manifests for every installed browser.
|
|
152
|
-
* @param {{extensionId?:string, bridgeFile?:string}} [options]
|
|
295
|
+
* @param {{extensionId?:string, bridgeFile?:string, nativeHostPath?:string}} [options]
|
|
153
296
|
*/
|
|
154
|
-
export async function installNativeHost({ extensionId = EXTENSION_ID, bridgeFile = defaultBridgeFile() } = {}) {
|
|
297
|
+
export async function installNativeHost({ extensionId = EXTENSION_ID, bridgeFile = defaultBridgeFile(), nativeHostPath } = {}) {
|
|
155
298
|
const launcher = nativeHostLauncher();
|
|
156
|
-
const
|
|
299
|
+
const entry = nativeHostPath ?? nativeHostEntry;
|
|
300
|
+
const preferredNode = stableNodePath();
|
|
301
|
+
const script = [
|
|
302
|
+
"#!/bin/sh",
|
|
303
|
+
`NODE=${shellQuote(preferredNode)}`,
|
|
304
|
+
'if [ ! -x "$NODE" ]; then',
|
|
305
|
+
' for c in /opt/homebrew/bin/node /usr/local/bin/node "$HOME/.volta/bin/node" "$HOME/.local/share/fnm/aliases/default/bin/node"; do',
|
|
306
|
+
' if [ -x "$c" ]; then NODE="$c"; break; fi',
|
|
307
|
+
" done",
|
|
308
|
+
"fi",
|
|
309
|
+
'if [ ! -x "$NODE" ]; then NODE="$(command -v node 2>/dev/null || echo node)"; fi',
|
|
310
|
+
`exec "$NODE" ${shellQuote(entry)} ${shellQuote(path.resolve(bridgeFile))}`,
|
|
311
|
+
"",
|
|
312
|
+
].join("\n");
|
|
157
313
|
await writeAtomic(launcher, script, 0o700);
|
|
158
314
|
const manifest = {
|
|
159
315
|
name: HOST_NAME,
|
|
@@ -163,7 +319,6 @@ export async function installNativeHost({ extensionId = EXTENSION_ID, bridgeFile
|
|
|
163
319
|
allowed_origins: [`chrome-extension://${extensionId}/`],
|
|
164
320
|
};
|
|
165
321
|
const written = [];
|
|
166
|
-
let chromeWritten = false;
|
|
167
322
|
for (const directory of nativeMessagingDirs()) {
|
|
168
323
|
const browserRoot = path.dirname(directory);
|
|
169
324
|
let exists = true;
|
|
@@ -172,38 +327,107 @@ export async function installNativeHost({ extensionId = EXTENSION_ID, bridgeFile
|
|
|
172
327
|
} catch {
|
|
173
328
|
exists = false;
|
|
174
329
|
}
|
|
175
|
-
const
|
|
176
|
-
|
|
330
|
+
const isDefaultChrome = directory.includes(`${path.sep}Google${path.sep}Chrome${path.sep}`) ||
|
|
331
|
+
directory.includes(`${path.sep}google-chrome${path.sep}`);
|
|
332
|
+
if (!exists && !isDefaultChrome) continue;
|
|
177
333
|
const file = path.join(directory, `${HOST_NAME}.json`);
|
|
178
334
|
const backup = await backupOnce(file);
|
|
179
335
|
await writeAtomic(file, `${JSON.stringify(manifest, null, 2)}\n`, 0o600);
|
|
180
336
|
written.push({ file, backup });
|
|
181
|
-
if (isChrome) chromeWritten = true;
|
|
182
337
|
}
|
|
183
|
-
if (
|
|
184
|
-
return { launcher, manifests: written };
|
|
338
|
+
if (written.length === 0) throw new Error("Could not locate a Chrome native messaging directory");
|
|
339
|
+
return { launcher, entry, manifests: written };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Strip JS/JSONC `//` line comments, block comments, and trailing commas outside string literals.
|
|
344
|
+
* @param {string} raw
|
|
345
|
+
* @returns {string}
|
|
346
|
+
*/
|
|
347
|
+
export function stripJsonComments(raw) {
|
|
348
|
+
let out = "";
|
|
349
|
+
let inStr = false;
|
|
350
|
+
let escaped = false;
|
|
351
|
+
let lineComment = false;
|
|
352
|
+
let blockComment = false;
|
|
353
|
+
for (let i = 0; i < raw.length; i++) {
|
|
354
|
+
const ch = raw[i];
|
|
355
|
+
const next = raw[i + 1];
|
|
356
|
+
if (lineComment) {
|
|
357
|
+
if (ch === "\n") {
|
|
358
|
+
lineComment = false;
|
|
359
|
+
out += ch;
|
|
360
|
+
}
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (blockComment) {
|
|
364
|
+
if (ch === "*" && next === "/") {
|
|
365
|
+
blockComment = false;
|
|
366
|
+
i += 1;
|
|
367
|
+
}
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (inStr) {
|
|
371
|
+
out += ch;
|
|
372
|
+
if (escaped) escaped = false;
|
|
373
|
+
else if (ch === "\\") escaped = true;
|
|
374
|
+
else if (ch === '"') inStr = false;
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
if (ch === '"') {
|
|
378
|
+
inStr = true;
|
|
379
|
+
out += ch;
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
if (ch === "/" && next === "/") {
|
|
383
|
+
lineComment = true;
|
|
384
|
+
i += 1;
|
|
385
|
+
continue;
|
|
386
|
+
}
|
|
387
|
+
if (ch === "/" && next === "*") {
|
|
388
|
+
blockComment = true;
|
|
389
|
+
i += 1;
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
out += ch;
|
|
393
|
+
}
|
|
394
|
+
return out.replace(/,\s*([}\]])/gu, "$1");
|
|
185
395
|
}
|
|
186
396
|
|
|
187
397
|
/**
|
|
188
398
|
* Merge the browser-use entry into a client's MCP configuration.
|
|
189
|
-
* @param {{client:string, bridgeFile?:string, profile?:string, write?:boolean, home?:string}} options
|
|
399
|
+
* @param {{client:string, bridgeFile?:string, serverPath?:string, profile?:string, write?:boolean, home?:string}} options
|
|
190
400
|
*/
|
|
191
|
-
export async function configureClient({ client, bridgeFile = defaultBridgeFile(), profile, write = false, home = homedir() }) {
|
|
401
|
+
export async function configureClient({ client, bridgeFile = defaultBridgeFile(), serverPath, profile, write = false, home = homedir() }) {
|
|
192
402
|
const name = normalizeClient(client);
|
|
193
403
|
const target = clientTarget(name, home);
|
|
194
|
-
const config = buildConfig(name, { bridgeFile, profile });
|
|
404
|
+
const config = buildConfig(name, { bridgeFile, serverPath, profile });
|
|
195
405
|
if (!write || target.file === null) {
|
|
196
406
|
return { written: false, file: target.file, config };
|
|
197
407
|
}
|
|
198
408
|
let existing = {};
|
|
199
409
|
try {
|
|
200
|
-
|
|
410
|
+
const raw = await readFile(target.file, "utf8");
|
|
411
|
+
existing = raw.trim() ? JSON.parse(stripJsonComments(raw)) : {};
|
|
201
412
|
} catch (error) {
|
|
202
413
|
if (error.code !== "ENOENT") throw new Error(`${target.file} is not valid JSON: ${error.message}`);
|
|
203
414
|
}
|
|
415
|
+
const mergeEntries = (prevServers = {}, nextServers = {}) => {
|
|
416
|
+
const out = { ...prevServers };
|
|
417
|
+
for (const [key, entry] of Object.entries(nextServers)) {
|
|
418
|
+
const prevEntry = prevServers[key];
|
|
419
|
+
if (prevEntry && typeof prevEntry === "object" && entry && typeof entry === "object") {
|
|
420
|
+
const mergedEnv = (prevEntry.env || entry.env) ? { ...(prevEntry.env ?? {}), ...(entry.env ?? {}) } : undefined;
|
|
421
|
+
out[key] = { ...entry, ...(mergedEnv ? { env: mergedEnv } : {}) };
|
|
422
|
+
} else {
|
|
423
|
+
out[key] = entry;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return out;
|
|
427
|
+
};
|
|
204
428
|
const merged = target.key === "mcp.servers"
|
|
205
|
-
? { ...existing, mcp: { ...existing.mcp, servers:
|
|
206
|
-
: { ...existing, mcpServers:
|
|
429
|
+
? { ...existing, mcp: { ...existing.mcp, servers: mergeEntries(existing.mcp?.servers, config.mcp.servers) } }
|
|
430
|
+
: { ...existing, mcpServers: mergeEntries(existing.mcpServers, config.mcpServers) };
|
|
207
431
|
const backup = await backupOnce(target.file);
|
|
208
432
|
await writeAtomic(target.file, `${JSON.stringify(merged, null, 2)}\n`, 0o600);
|
|
209
433
|
return { written: true, file: target.file, backup, config };
|