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.
- package/LICENSE +21 -0
- package/README.md +312 -2
- package/bin/browser-use.js +200 -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 +231 -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,576 @@
|
|
|
1
|
+
const VALID_FORMATS = new Set(["markdown", "tables", "links", "text"]);
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Build a self-contained read-only IIFE expression for CDP `Runtime.evaluate`
|
|
5
|
+
* that extracts clean structured content from the current page.
|
|
6
|
+
* @param {{format?:"markdown"|"tables"|"links"|"text", maxChars?:number}} [options]
|
|
7
|
+
* @returns {string}
|
|
8
|
+
*/
|
|
9
|
+
export function extractContentExpression({ format = "markdown", maxChars = 16_000 } = {}) {
|
|
10
|
+
const targetFormat = VALID_FORMATS.has(format) ? format : "markdown";
|
|
11
|
+
const limit = Number.isFinite(Number(maxChars)) && Number(maxChars) > 0
|
|
12
|
+
? Math.floor(Number(maxChars))
|
|
13
|
+
: 16_000;
|
|
14
|
+
|
|
15
|
+
return `(() => {
|
|
16
|
+
const FORMAT = ${JSON.stringify(targetFormat)};
|
|
17
|
+
const MAX_CHARS = ${limit};
|
|
18
|
+
const BOILERPLATE_TAGS = new Set([
|
|
19
|
+
"NAV", "HEADER", "FOOTER", "ASIDE", "SCRIPT", "STYLE", "NOSCRIPT", "SVG", "TEMPLATE",
|
|
20
|
+
]);
|
|
21
|
+
const BLOCK_TAGS = new Set([
|
|
22
|
+
"ADDRESS", "ARTICLE", "ASIDE", "BLOCKQUOTE", "DD", "DETAILS", "DIALOG", "DIV",
|
|
23
|
+
"DL", "DT", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "FORM", "H1", "H2",
|
|
24
|
+
"H3", "H4", "H5", "H6", "HEADER", "HGROUP", "HR", "LI", "MAIN", "NAV", "OL",
|
|
25
|
+
"P", "PRE", "SECTION", "TABLE", "UL",
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
const normalizeSpace = (value) => String(value ?? "").replace(/\\s+/g, " ").trim();
|
|
29
|
+
|
|
30
|
+
const normalizeMultilineText = (value) => String(value ?? "")
|
|
31
|
+
.replace(/\\r\\n?/g, "\\n")
|
|
32
|
+
.split("\\n")
|
|
33
|
+
.map((line) => line.replace(/[ \\t]+/g, " ").trim())
|
|
34
|
+
.join("\\n")
|
|
35
|
+
.replace(/\\n{3,}/g, "\\n\\n")
|
|
36
|
+
.trim();
|
|
37
|
+
|
|
38
|
+
const clipText = (raw, limitChars) => {
|
|
39
|
+
const text = String(raw ?? "").trim();
|
|
40
|
+
if (text.length <= limitChars) return { text, truncated: false };
|
|
41
|
+
const suffix = "\\n...(truncated)";
|
|
42
|
+
const budget = Math.max(0, limitChars - suffix.length);
|
|
43
|
+
const clipped = budget > 0
|
|
44
|
+
? text.slice(0, budget).trimEnd() + suffix
|
|
45
|
+
: suffix.slice(0, limitChars);
|
|
46
|
+
return { text: clipped, truncated: true };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const tagOf = (el) => String(el && el.tagName ? el.tagName : "").toUpperCase();
|
|
50
|
+
|
|
51
|
+
const isOwnHidden = (el) => {
|
|
52
|
+
if (!el || el.nodeType !== 1) return false;
|
|
53
|
+
if (el.hidden === true) return true;
|
|
54
|
+
if (typeof el.getAttribute === "function") {
|
|
55
|
+
if (el.getAttribute("hidden") !== null) return true;
|
|
56
|
+
if (el.getAttribute("aria-hidden") === "true") return true;
|
|
57
|
+
}
|
|
58
|
+
if (el.style) {
|
|
59
|
+
if (el.style.display === "none" || el.style.visibility === "hidden") return true;
|
|
60
|
+
}
|
|
61
|
+
if (typeof getComputedStyle === "function") {
|
|
62
|
+
try {
|
|
63
|
+
const cs = getComputedStyle(el);
|
|
64
|
+
if (cs && (cs.display === "none" || cs.visibility === "hidden")) return true;
|
|
65
|
+
} catch (_err) {
|
|
66
|
+
// Ignore detached or cross-realm elements.
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return false;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const isElementVisible = (el) => {
|
|
73
|
+
for (let curr = el; curr && curr.nodeType === 1; curr = curr.parentElement) {
|
|
74
|
+
if (isOwnHidden(curr)) return false;
|
|
75
|
+
}
|
|
76
|
+
return true;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const isInsideBoilerplate = (el) => {
|
|
80
|
+
for (let curr = el; curr && curr.nodeType === 1; curr = curr.parentElement) {
|
|
81
|
+
if (BOILERPLATE_TAGS.has(tagOf(curr))) return true;
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const queryAll = (root, selector) => {
|
|
87
|
+
if (!root) return [];
|
|
88
|
+
if (typeof root.querySelectorAll === "function") {
|
|
89
|
+
try {
|
|
90
|
+
return Array.from(root.querySelectorAll(selector));
|
|
91
|
+
} catch (_err) {
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return [];
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const collectElementsByTags = (root, tags) => {
|
|
99
|
+
const wanted = new Set(tags.map((t) => t.toUpperCase()));
|
|
100
|
+
const out = [];
|
|
101
|
+
const walk = (node) => {
|
|
102
|
+
if (!node || node.nodeType !== 1) return;
|
|
103
|
+
if (wanted.has(tagOf(node))) out.push(node);
|
|
104
|
+
const children = node.children || node.childNodes || [];
|
|
105
|
+
for (let i = 0; i < children.length; i++) {
|
|
106
|
+
if (children[i] && children[i].nodeType === 1) walk(children[i]);
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
walk(root);
|
|
110
|
+
return out;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const extractVisibleText = (node, { skipBoilerplate = true } = {}) => {
|
|
114
|
+
if (!node) return "";
|
|
115
|
+
if (node.nodeType === 3) return String(node.nodeValue ?? node.textContent ?? "");
|
|
116
|
+
if (node.nodeType !== 1) return "";
|
|
117
|
+
const tag = tagOf(node);
|
|
118
|
+
if (isOwnHidden(node)) return "";
|
|
119
|
+
if (skipBoilerplate && BOILERPLATE_TAGS.has(tag)) return "";
|
|
120
|
+
if (tag === "SCRIPT" || tag === "STYLE" || tag === "NOSCRIPT" || tag === "TEMPLATE") return "";
|
|
121
|
+
if (tag === "BR") return "\\n";
|
|
122
|
+
const children = node.childNodes || [];
|
|
123
|
+
if (!children.length) return String(node.textContent ?? "");
|
|
124
|
+
const parts = [];
|
|
125
|
+
for (let i = 0; i < children.length; i++) {
|
|
126
|
+
parts.push(extractVisibleText(children[i], { skipBoilerplate }));
|
|
127
|
+
}
|
|
128
|
+
const joined = parts.join("");
|
|
129
|
+
return BLOCK_TAGS.has(tag) ? "\\n" + joined + "\\n" : joined;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const measureTextAndLinks = (root) => {
|
|
133
|
+
let totalLen = 0;
|
|
134
|
+
let linkLen = 0;
|
|
135
|
+
let blockCount = 0;
|
|
136
|
+
const walk = (node, insideLink) => {
|
|
137
|
+
if (!node) return;
|
|
138
|
+
if (node.nodeType === 3) {
|
|
139
|
+
const len = normalizeSpace(node.nodeValue ?? node.textContent ?? "").length;
|
|
140
|
+
totalLen += len;
|
|
141
|
+
if (insideLink) linkLen += len;
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (node.nodeType !== 1) return;
|
|
145
|
+
const tag = tagOf(node);
|
|
146
|
+
if (isOwnHidden(node) || BOILERPLATE_TAGS.has(tag)) return;
|
|
147
|
+
if (tag === "P" || tag === "PRE" || tag === "TABLE" || tag === "BLOCKQUOTE" || /^H[1-6]$/.test(tag)) {
|
|
148
|
+
blockCount += 1;
|
|
149
|
+
}
|
|
150
|
+
const nextInsideLink = insideLink || tag === "A";
|
|
151
|
+
const children = node.childNodes || [];
|
|
152
|
+
for (let i = 0; i < children.length; i++) {
|
|
153
|
+
walk(children[i], nextInsideLink);
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
walk(root, false);
|
|
157
|
+
return { totalLen, linkLen, blockCount };
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const extractTableData = (tableEl) => {
|
|
161
|
+
let caption = "";
|
|
162
|
+
const captions = collectElementsByTags(tableEl, ["CAPTION"]);
|
|
163
|
+
if (captions.length > 0 && isElementVisible(captions[0])) {
|
|
164
|
+
caption = normalizeSpace(extractVisibleText(captions[0], { skipBoilerplate: false }));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const rowEls = collectElementsByTags(tableEl, ["TR"]).filter((tr) => isElementVisible(tr));
|
|
168
|
+
let headers = [];
|
|
169
|
+
const rows = [];
|
|
170
|
+
|
|
171
|
+
for (let i = 0; i < rowEls.length; i++) {
|
|
172
|
+
const tr = rowEls[i];
|
|
173
|
+
const cells = [];
|
|
174
|
+
const childEls = tr.children || tr.childNodes || [];
|
|
175
|
+
let thCount = 0;
|
|
176
|
+
let cellCount = 0;
|
|
177
|
+
for (let c = 0; c < childEls.length; c++) {
|
|
178
|
+
const cell = childEls[c];
|
|
179
|
+
if (!cell || cell.nodeType !== 1) continue;
|
|
180
|
+
const cTag = tagOf(cell);
|
|
181
|
+
if (cTag !== "TH" && cTag !== "TD") continue;
|
|
182
|
+
if (isOwnHidden(cell)) continue;
|
|
183
|
+
cellCount += 1;
|
|
184
|
+
if (cTag === "TH") thCount += 1;
|
|
185
|
+
cells.push(normalizeSpace(extractVisibleText(cell, { skipBoilerplate: false })));
|
|
186
|
+
}
|
|
187
|
+
if (cellCount === 0) continue;
|
|
188
|
+
const inThead = tr.parentElement && tagOf(tr.parentElement) === "THEAD";
|
|
189
|
+
if (headers.length === 0 && rows.length === 0 && (inThead || thCount === cellCount)) {
|
|
190
|
+
headers = cells;
|
|
191
|
+
} else {
|
|
192
|
+
rows.push(cells);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return { caption, headers, rows };
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const escapeTableCell = (cell) => String(cell ?? "").replace(/\\|/g, "\\\\|").replace(/\\n/g, " ").trim();
|
|
200
|
+
|
|
201
|
+
const renderTableMarkdown = (tableData) => {
|
|
202
|
+
const { caption, headers, rows } = tableData;
|
|
203
|
+
const activeHeaders = headers.length > 0 ? headers : (rows.length > 0 ? rows[0] : []);
|
|
204
|
+
const dataRows = headers.length > 0 ? rows : rows.slice(1);
|
|
205
|
+
let colCount = activeHeaders.length;
|
|
206
|
+
for (let i = 0; i < dataRows.length; i++) {
|
|
207
|
+
if (dataRows[i].length > colCount) colCount = dataRows[i].length;
|
|
208
|
+
}
|
|
209
|
+
if (colCount === 0) return "";
|
|
210
|
+
const padRow = (r) => {
|
|
211
|
+
const out = [];
|
|
212
|
+
for (let i = 0; i < colCount; i++) out.push(escapeTableCell(r[i] ?? ""));
|
|
213
|
+
return "| " + out.join(" | ") + " |";
|
|
214
|
+
};
|
|
215
|
+
const lines = [];
|
|
216
|
+
if (caption) lines.push("**" + caption + "**", "");
|
|
217
|
+
lines.push(padRow(activeHeaders));
|
|
218
|
+
lines.push("| " + Array.from({ length: colCount }, () => "---").join(" | ") + " |");
|
|
219
|
+
for (let i = 0; i < dataRows.length; i++) {
|
|
220
|
+
lines.push(padRow(dataRows[i]));
|
|
221
|
+
}
|
|
222
|
+
return lines.join("\\n");
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const getAttr = (el, name) => (el && typeof el.getAttribute === "function" ? el.getAttribute(name) : null);
|
|
226
|
+
|
|
227
|
+
const resolveLinkHref = (aEl) => {
|
|
228
|
+
const rawAttr = String(getAttr(aEl, "href") ?? "").trim();
|
|
229
|
+
const propHref = typeof aEl.href === "string" ? aEl.href.trim() : "";
|
|
230
|
+
const candidate = rawAttr || propHref;
|
|
231
|
+
if (!candidate || /^javascript:/i.test(candidate)) return "";
|
|
232
|
+
if (/^javascript:/i.test(rawAttr)) return "";
|
|
233
|
+
if (propHref && !/^javascript:/i.test(propHref) && !rawAttr.startsWith("#")) return propHref;
|
|
234
|
+
return candidate;
|
|
235
|
+
};
|
|
236
|
+
|
|
237
|
+
const extractLinksList = (root) => {
|
|
238
|
+
const anchors = queryAll(root, "a[href]").length > 0
|
|
239
|
+
? queryAll(root, "a[href]")
|
|
240
|
+
: collectElementsByTags(root, ["A"]).filter((a) => getAttr(a, "href") !== null || Boolean(a.href));
|
|
241
|
+
const seen = new Set();
|
|
242
|
+
const links = [];
|
|
243
|
+
for (let i = 0; i < anchors.length; i++) {
|
|
244
|
+
const a = anchors[i];
|
|
245
|
+
if (!isElementVisible(a)) continue;
|
|
246
|
+
const href = resolveLinkHref(a);
|
|
247
|
+
if (!href || seen.has(href)) continue;
|
|
248
|
+
let text = normalizeSpace(extractVisibleText(a, { skipBoilerplate: false }));
|
|
249
|
+
if (!text) text = normalizeSpace(getAttr(a, "aria-label") || getAttr(a, "title") || "");
|
|
250
|
+
if (!text) {
|
|
251
|
+
const imgs = collectElementsByTags(a, ["IMG"]);
|
|
252
|
+
for (let k = 0; k < imgs.length; k++) {
|
|
253
|
+
const alt = normalizeSpace(getAttr(imgs[k], "alt") || "");
|
|
254
|
+
if (alt) {
|
|
255
|
+
text = alt;
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (!text) continue;
|
|
261
|
+
seen.add(href);
|
|
262
|
+
links.push({ text, href });
|
|
263
|
+
}
|
|
264
|
+
return links;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
const countVisibleTables = (root) => {
|
|
268
|
+
const tables = queryAll(root, "table").length > 0
|
|
269
|
+
? queryAll(root, "table")
|
|
270
|
+
: collectElementsByTags(root, ["TABLE"]);
|
|
271
|
+
return tables.filter((t) => isElementVisible(t));
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
const pickPrimaryContainer = (body) => {
|
|
275
|
+
if (!body) return document.documentElement;
|
|
276
|
+
const semanticCandidates = [];
|
|
277
|
+
const primaryMatches = queryAll(document, 'article, main, [role="main"]');
|
|
278
|
+
const fallbackMatches = primaryMatches.length > 0
|
|
279
|
+
? primaryMatches
|
|
280
|
+
: collectElementsByTags(body, ["ARTICLE", "MAIN", "DIV", "SECTION"]).filter((el) => {
|
|
281
|
+
const t = tagOf(el);
|
|
282
|
+
return t === "ARTICLE" || t === "MAIN" || getAttr(el, "role") === "main";
|
|
283
|
+
});
|
|
284
|
+
for (let i = 0; i < fallbackMatches.length; i++) {
|
|
285
|
+
const el = fallbackMatches[i];
|
|
286
|
+
if (!isElementVisible(el) || isInsideBoilerplate(el)) continue;
|
|
287
|
+
const stats = measureTextAndLinks(el);
|
|
288
|
+
if (stats.totalLen >= 200) {
|
|
289
|
+
semanticCandidates.push({ el, score: stats.totalLen });
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
if (semanticCandidates.length > 0) {
|
|
293
|
+
semanticCandidates.sort((a, b) => b.score - a.score);
|
|
294
|
+
return semanticCandidates[0].el;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const densityBlocks = collectElementsByTags(body, ["SECTION", "DIV", "ARTICLE", "MAIN"]);
|
|
298
|
+
let bestEl = null;
|
|
299
|
+
let bestScore = 0;
|
|
300
|
+
for (let i = 0; i < densityBlocks.length; i++) {
|
|
301
|
+
const el = densityBlocks[i];
|
|
302
|
+
if (!isElementVisible(el) || isInsideBoilerplate(el)) continue;
|
|
303
|
+
const stats = measureTextAndLinks(el);
|
|
304
|
+
if (stats.totalLen < 120 || (stats.blockCount < 2 && stats.totalLen < 200)) continue;
|
|
305
|
+
const linkDensity = stats.linkLen / Math.max(1, stats.totalLen);
|
|
306
|
+
const nonLinkLen = Math.max(0, stats.totalLen - stats.linkLen);
|
|
307
|
+
const score = nonLinkLen * (1 - Math.min(0.9, linkDensity)) + stats.blockCount * 20;
|
|
308
|
+
if (score > bestScore) {
|
|
309
|
+
bestScore = score;
|
|
310
|
+
bestEl = el;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return bestEl || body;
|
|
314
|
+
};
|
|
315
|
+
|
|
316
|
+
const renderMarkdownNode = (node) => {
|
|
317
|
+
if (!node) return "";
|
|
318
|
+
if (node.nodeType === 3) {
|
|
319
|
+
return String(node.nodeValue ?? node.textContent ?? "").replace(/[ \\t\\r\\n]+/g, " ");
|
|
320
|
+
}
|
|
321
|
+
if (node.nodeType !== 1) return "";
|
|
322
|
+
const tag = tagOf(node);
|
|
323
|
+
if (isOwnHidden(node) || BOILERPLATE_TAGS.has(tag)) return "";
|
|
324
|
+
|
|
325
|
+
if (tag === "BR") return "\\n";
|
|
326
|
+
if (tag === "HR") return "\\n\\n---\\n\\n";
|
|
327
|
+
|
|
328
|
+
if (tag === "PRE") {
|
|
329
|
+
const rawPre = String(node.textContent ?? "").replace(/\\r\\n?/g, "\\n").replace(/^\\n+|\\n+$/g, "");
|
|
330
|
+
if (!rawPre) return "";
|
|
331
|
+
const codeChildren = collectElementsByTags(node, ["CODE"]);
|
|
332
|
+
let lang = "";
|
|
333
|
+
if (codeChildren.length > 0) {
|
|
334
|
+
const cls = String(getAttr(codeChildren[0], "class") || codeChildren[0].className || "");
|
|
335
|
+
const m = cls.match(/language-([a-zA-Z0-9_-]+)/);
|
|
336
|
+
if (m) lang = m[1];
|
|
337
|
+
}
|
|
338
|
+
return "\\n\\n\`\`\`" + lang + "\\n" + rawPre + "\\n\`\`\`\\n\\n";
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (tag === "CODE") {
|
|
342
|
+
const codeText = normalizeSpace(node.textContent ?? "");
|
|
343
|
+
return codeText ? "\`" + codeText + "\`" : "";
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (tag === "TABLE") {
|
|
347
|
+
const md = renderTableMarkdown(extractTableData(node));
|
|
348
|
+
return md ? "\\n\\n" + md + "\\n\\n" : "";
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const renderChildren = () => {
|
|
352
|
+
const children = node.childNodes || [];
|
|
353
|
+
if (!children.length) return String(node.textContent ?? "").replace(/[ \\t\\r\\n]+/g, " ");
|
|
354
|
+
let acc = "";
|
|
355
|
+
for (let i = 0; i < children.length; i++) {
|
|
356
|
+
acc += renderMarkdownNode(children[i]);
|
|
357
|
+
}
|
|
358
|
+
return acc;
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
if (/^H[1-6]$/.test(tag)) {
|
|
362
|
+
const level = Number(tag.slice(1));
|
|
363
|
+
const text = normalizeSpace(renderChildren());
|
|
364
|
+
return text ? "\\n\\n" + "#".repeat(level) + " " + text + "\\n\\n" : "";
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
if (tag === "A") {
|
|
368
|
+
const href = resolveLinkHref(node);
|
|
369
|
+
const inner = normalizeSpace(renderChildren());
|
|
370
|
+
if (!inner) return "";
|
|
371
|
+
if (!href) return inner;
|
|
372
|
+
return "[" + inner + "](" + href + ")";
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (tag === "BLOCKQUOTE") {
|
|
376
|
+
const inner = normalizeMarkdownOutput(renderChildren());
|
|
377
|
+
if (!inner) return "";
|
|
378
|
+
const quoted = inner
|
|
379
|
+
.split("\\n")
|
|
380
|
+
.map((line) => (line ? "> " + line : ">"))
|
|
381
|
+
.join("\\n");
|
|
382
|
+
return "\\n\\n" + quoted + "\\n\\n";
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (tag === "UL" || tag === "OL") {
|
|
386
|
+
const items = [];
|
|
387
|
+
const children = node.children || node.childNodes || [];
|
|
388
|
+
for (let i = 0; i < children.length; i++) {
|
|
389
|
+
const child = children[i];
|
|
390
|
+
if (!child || child.nodeType !== 1 || tagOf(child) !== "LI") continue;
|
|
391
|
+
if (isOwnHidden(child)) continue;
|
|
392
|
+
const itemMd = renderListItem(child, 0);
|
|
393
|
+
if (itemMd) items.push(itemMd);
|
|
394
|
+
}
|
|
395
|
+
return items.length ? "\\n\\n" + items.join("\\n") + "\\n\\n" : "";
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (tag === "LI") {
|
|
399
|
+
return renderListItem(node, 0);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (tag === "P") {
|
|
403
|
+
const inner = renderChildren().replace(/^[ \\t]+|[ \\t]+$/g, "");
|
|
404
|
+
return inner.trim() ? "\\n\\n" + inner.trim() + "\\n\\n" : "";
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const inner = renderChildren();
|
|
408
|
+
if (BLOCK_TAGS.has(tag)) {
|
|
409
|
+
return inner.trim() ? "\\n\\n" + inner.trim() + "\\n\\n" : "";
|
|
410
|
+
}
|
|
411
|
+
return inner;
|
|
412
|
+
};
|
|
413
|
+
|
|
414
|
+
const renderListItem = (liNode, depth) => {
|
|
415
|
+
const inlineParts = [];
|
|
416
|
+
const nestedLists = [];
|
|
417
|
+
const children = liNode.childNodes || [];
|
|
418
|
+
for (let i = 0; i < children.length; i++) {
|
|
419
|
+
const child = children[i];
|
|
420
|
+
if (child && child.nodeType === 1 && (tagOf(child) === "UL" || tagOf(child) === "OL")) {
|
|
421
|
+
nestedLists.push(child);
|
|
422
|
+
} else {
|
|
423
|
+
inlineParts.push(renderMarkdownNode(child));
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
const text = normalizeSpace(inlineParts.join(""));
|
|
427
|
+
const lines = [];
|
|
428
|
+
const indent = " ".repeat(depth);
|
|
429
|
+
if (text) lines.push(indent + "- " + text);
|
|
430
|
+
for (let i = 0; i < nestedLists.length; i++) {
|
|
431
|
+
const list = nestedLists[i];
|
|
432
|
+
if (isOwnHidden(list)) continue;
|
|
433
|
+
const listChildren = list.children || list.childNodes || [];
|
|
434
|
+
for (let k = 0; k < listChildren.length; k++) {
|
|
435
|
+
const sub = listChildren[k];
|
|
436
|
+
if (sub && sub.nodeType === 1 && tagOf(sub) === "LI" && !isOwnHidden(sub)) {
|
|
437
|
+
const subMd = renderListItem(sub, depth + 1);
|
|
438
|
+
if (subMd) lines.push(subMd);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
return lines.join("\\n");
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
const normalizeMarkdownOutput = (raw) => {
|
|
446
|
+
const parts = String(raw ?? "").split(/(\`\`\`[\\s\\S]*?\`\`\`)/g);
|
|
447
|
+
const out = [];
|
|
448
|
+
for (let i = 0; i < parts.length; i++) {
|
|
449
|
+
const part = parts[i];
|
|
450
|
+
if (i % 2 === 1) {
|
|
451
|
+
out.push("\\n\\n" + part + "\\n\\n");
|
|
452
|
+
} else {
|
|
453
|
+
const cleaned = part
|
|
454
|
+
.replace(/\\r\\n?/g, "\\n")
|
|
455
|
+
.split("\\n")
|
|
456
|
+
.map((line) => {
|
|
457
|
+
const rtrimmed = line.trimEnd();
|
|
458
|
+
if (rtrimmed.trim() === "") return "";
|
|
459
|
+
const listMatch = rtrimmed.match(/^( +)(- .*)$/);
|
|
460
|
+
if (listMatch) return listMatch[1] + listMatch[2].replace(/[ \\t]+/g, " ");
|
|
461
|
+
return rtrimmed.replace(/[ \\t]+/g, " ").replace(/^ +/, "");
|
|
462
|
+
})
|
|
463
|
+
.join("\\n");
|
|
464
|
+
out.push(cleaned);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
return out.join("").replace(/\\n{3,}/g, "\\n\\n").trim();
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
const title = normalizeSpace(document && document.title);
|
|
471
|
+
const url = String(
|
|
472
|
+
(typeof location !== "undefined" && location && location.href) ||
|
|
473
|
+
(document && document.URL) ||
|
|
474
|
+
""
|
|
475
|
+
);
|
|
476
|
+
const body = (document && (document.body || document.documentElement)) || null;
|
|
477
|
+
const visibleTables = body ? countVisibleTables(body) : [];
|
|
478
|
+
const allLinks = body ? extractLinksList(body) : [];
|
|
479
|
+
const tablesCount = visibleTables.length;
|
|
480
|
+
const linksCount = allLinks.length;
|
|
481
|
+
|
|
482
|
+
if (FORMAT === "tables") {
|
|
483
|
+
const tables = visibleTables.map((t) => extractTableData(t));
|
|
484
|
+
const rendered = tables
|
|
485
|
+
.map((t) => renderTableMarkdown(t))
|
|
486
|
+
.filter(Boolean)
|
|
487
|
+
.join("\\n\\n");
|
|
488
|
+
const clipped = clipText(rendered, MAX_CHARS);
|
|
489
|
+
return {
|
|
490
|
+
title,
|
|
491
|
+
url,
|
|
492
|
+
format: FORMAT,
|
|
493
|
+
text: clipped.text,
|
|
494
|
+
content: clipped.text,
|
|
495
|
+
truncated: clipped.truncated,
|
|
496
|
+
tablesCount,
|
|
497
|
+
linksCount,
|
|
498
|
+
tables,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
if (FORMAT === "links") {
|
|
503
|
+
const suffix = "\\n...(truncated)";
|
|
504
|
+
const lines = [];
|
|
505
|
+
const keptLinks = [];
|
|
506
|
+
let usedChars = 0;
|
|
507
|
+
let truncated = false;
|
|
508
|
+
for (let i = 0; i < allLinks.length; i++) {
|
|
509
|
+
const item = allLinks[i];
|
|
510
|
+
const line = "- [" + item.text + "](" + item.href + ")";
|
|
511
|
+
const addition = (lines.length > 0 ? 1 : 0) + line.length;
|
|
512
|
+
if (usedChars + addition > MAX_CHARS) {
|
|
513
|
+
truncated = true;
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
lines.push(line);
|
|
517
|
+
keptLinks.push(item);
|
|
518
|
+
usedChars += addition;
|
|
519
|
+
}
|
|
520
|
+
let text = lines.join("\\n");
|
|
521
|
+
if (truncated) {
|
|
522
|
+
while (lines.length > 0 && (lines.join("\\n").length + suffix.length) > MAX_CHARS) {
|
|
523
|
+
lines.pop();
|
|
524
|
+
keptLinks.pop();
|
|
525
|
+
}
|
|
526
|
+
text = lines.length > 0
|
|
527
|
+
? lines.join("\\n") + suffix
|
|
528
|
+
: suffix.slice(0, MAX_CHARS);
|
|
529
|
+
}
|
|
530
|
+
return {
|
|
531
|
+
title,
|
|
532
|
+
url,
|
|
533
|
+
format: FORMAT,
|
|
534
|
+
text,
|
|
535
|
+
content: text,
|
|
536
|
+
truncated,
|
|
537
|
+
tablesCount,
|
|
538
|
+
linksCount,
|
|
539
|
+
links: keptLinks,
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
if (FORMAT === "text") {
|
|
544
|
+
const raw = body && typeof body.innerText === "string"
|
|
545
|
+
? body.innerText
|
|
546
|
+
: extractVisibleText(body, { skipBoilerplate: false });
|
|
547
|
+
const normalized = normalizeMultilineText(raw);
|
|
548
|
+
const clipped = clipText(normalized, MAX_CHARS);
|
|
549
|
+
return {
|
|
550
|
+
title,
|
|
551
|
+
url,
|
|
552
|
+
format: FORMAT,
|
|
553
|
+
text: clipped.text,
|
|
554
|
+
content: clipped.text,
|
|
555
|
+
truncated: clipped.truncated,
|
|
556
|
+
tablesCount,
|
|
557
|
+
linksCount,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const container = pickPrimaryContainer(body);
|
|
562
|
+
const rawMd = container ? renderMarkdownNode(container) : "";
|
|
563
|
+
const normalizedMd = normalizeMarkdownOutput(rawMd);
|
|
564
|
+
const clipped = clipText(normalizedMd, MAX_CHARS);
|
|
565
|
+
return {
|
|
566
|
+
title,
|
|
567
|
+
url,
|
|
568
|
+
format: "markdown",
|
|
569
|
+
text: clipped.text,
|
|
570
|
+
content: clipped.text,
|
|
571
|
+
truncated: clipped.truncated,
|
|
572
|
+
tablesCount,
|
|
573
|
+
linksCount,
|
|
574
|
+
};
|
|
575
|
+
})()`;
|
|
576
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { access, readFile, readdir, realpath, stat } from "node:fs/promises";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
/** @typedef {{path: string, version: string, clientPath: string, servicePath: string, apiPath: string, manifestPath: string}} BrowserEngine */
|
|
6
|
+
|
|
7
|
+
/** @param {string} [version] @returns {void} */
|
|
8
|
+
export function assertRuntime(version = process.versions.node) {
|
|
9
|
+
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
|
|
10
|
+
if (!match) throw new Error(`Unsupported Node.js version: ${version}`);
|
|
11
|
+
const [major, minor, patch] = match.slice(1).map(Number);
|
|
12
|
+
if (major < 26 || (major === 26 && (minor < 12 || (minor === 12 && patch < 1)))) {
|
|
13
|
+
throw new Error("Browser Use requires Node.js 26.12.1 or newer for the persistent REPL error handler.");
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Validate a locally installed engine without importing it or opening a browser.
|
|
19
|
+
* @param {string} enginePath
|
|
20
|
+
* @returns {Promise<BrowserEngine>}
|
|
21
|
+
*/
|
|
22
|
+
export async function validateEngine(enginePath) {
|
|
23
|
+
if (!path.isAbsolute(enginePath)) throw new Error("Engine path must be absolute");
|
|
24
|
+
const root = await realpath(enginePath);
|
|
25
|
+
const files = {
|
|
26
|
+
clientPath: path.join(root, "scripts/browser-client.mjs"),
|
|
27
|
+
servicePath: path.join(root, "scripts/browser-service.mjs"),
|
|
28
|
+
apiPath: path.join(root, "docs/api.json"),
|
|
29
|
+
manifestPath: path.join(root, ".codex-plugin/plugin.json"),
|
|
30
|
+
};
|
|
31
|
+
for (const file of Object.values(files)) {
|
|
32
|
+
await access(file);
|
|
33
|
+
if (!(await stat(file)).isFile()) throw new Error(`Engine component is not a file: ${file}`);
|
|
34
|
+
}
|
|
35
|
+
const manifest = JSON.parse(await readFile(files.manifestPath, "utf8"));
|
|
36
|
+
if (!["chrome", "browser"].includes(manifest.name) || typeof manifest.version !== "string" || !manifest.version.trim()) {
|
|
37
|
+
throw new Error("Expected an installed OpenAI chrome/browser plugin manifest with a version");
|
|
38
|
+
}
|
|
39
|
+
const api = JSON.parse(await readFile(files.apiPath, "utf8"));
|
|
40
|
+
if (!api.interfaces?.Agent || !api.interfaces?.Browser || !api.interfaces?.Tab) {
|
|
41
|
+
throw new Error("Engine API manifest is missing Agent, Browser, or Tab interfaces");
|
|
42
|
+
}
|
|
43
|
+
return { path: root, version: manifest.version, ...files };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Select a numeric release, never staging directories or an unrelated plugin.
|
|
48
|
+
* Explicit selections fail closed instead of silently using another engine.
|
|
49
|
+
* @param {{enginePath?: string, env?: NodeJS.ProcessEnv, homeDir?: string}} [options]
|
|
50
|
+
* @returns {Promise<BrowserEngine>}
|
|
51
|
+
*/
|
|
52
|
+
export async function discoverEngine(options = {}) {
|
|
53
|
+
assertRuntime();
|
|
54
|
+
const env = options.env ?? process.env;
|
|
55
|
+
const explicit = options.enginePath ?? env.BROWSER_USE_ENGINE_PATH;
|
|
56
|
+
if (explicit !== undefined) {
|
|
57
|
+
if (!explicit.trim()) throw new Error("BROWSER_USE_ENGINE_PATH cannot be empty");
|
|
58
|
+
return validateEngine(explicit);
|
|
59
|
+
}
|
|
60
|
+
const home = options.homeDir ?? os.homedir();
|
|
61
|
+
const homes = [...new Set([env.CODEX_HOME, path.join(home, ".codex")].filter(Boolean))];
|
|
62
|
+
/** @type {{root: string, version: string, rank: number}[]} */
|
|
63
|
+
const candidates = [];
|
|
64
|
+
for (const [rank, codexHome] of homes.entries()) {
|
|
65
|
+
const root = path.join(codexHome, "plugins/cache/openai-bundled/chrome");
|
|
66
|
+
let entries;
|
|
67
|
+
try {
|
|
68
|
+
entries = await readdir(root, { withFileTypes: true });
|
|
69
|
+
} catch (error) {
|
|
70
|
+
if (error.code === "ENOENT") continue;
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
for (const entry of entries) {
|
|
74
|
+
if (entry.isDirectory() && /^\d+(?:\.\d+)+$/.test(entry.name)) {
|
|
75
|
+
candidates.push({ root: path.join(root, entry.name), version: entry.name, rank });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
candidates.sort((a, b) => b.version.localeCompare(a.version, "en", { numeric: true }) || a.rank - b.rank);
|
|
80
|
+
/** @type {string[]} */
|
|
81
|
+
const invalid = [];
|
|
82
|
+
for (const candidate of candidates) {
|
|
83
|
+
try {
|
|
84
|
+
return await validateEngine(candidate.root);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
invalid.push(`${candidate.root}: ${error.message}`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
throw new Error(`No complete installed OpenAI Chrome engine found. Install the official Chrome plugin, then retry or set BROWSER_USE_ENGINE_PATH to its absolute directory.${invalid.length ? ` Invalid releases: ${invalid.join("; ")}` : ""}`);
|
|
90
|
+
}
|
package/src/extension.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { defaultBridgeFile } from "./backend-discovery.js";
|
|
5
|
+
|
|
6
|
+
export { defaultBridgeFile };
|
|
7
|
+
|
|
8
|
+
export const HOST_NAME = "com.portable_browser_use.bridge";
|
|
9
|
+
export const EXTENSION_ID = "ehooacpcolldccnemjebdnmfgmgekghn";
|
|
10
|
+
export const EXTENSION_VERSION = "0.6.4";
|
|
11
|
+
export const extensionSource = fileURLToPath(new URL("../extension", import.meta.url));
|
|
12
|
+
|
|
13
|
+
/** @returns {string} */
|
|
14
|
+
export function dataRoot() {
|
|
15
|
+
return path.join(homedir(), ".local", "share", "browser-use");
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** @returns {string} */
|
|
19
|
+
export function installedExtensionDir() {
|
|
20
|
+
return path.join(dataRoot(), "extension");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @returns {string} */
|
|
24
|
+
export function nativeHostLauncher() {
|
|
25
|
+
return path.join(dataRoot(), "chrome-host", "launch.sh");
|
|
26
|
+
}
|