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
package/src/read-only.js
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { parse } from "acorn";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Methods that mutate browser state or trigger side effects. Page evaluation is
|
|
5
|
+
* a read-only scope: agents use the dedicated action tools for writes.
|
|
6
|
+
*/
|
|
7
|
+
const mutatingMethods = new Set([
|
|
8
|
+
"addEventListener", "after", "append", "appendChild", "beforescriptexecute", "before", "blur",
|
|
9
|
+
"checkValidity", "clear", "click", "close", "dispatchEvent", "execCommand", "focus",
|
|
10
|
+
"insertAdjacentElement", "insertAdjacentHTML", "insertAdjacentText", "insertBefore", "open",
|
|
11
|
+
"prepend", "remove", "removeAttribute", "removeAttributeNS", "removeChild", "replaceChild",
|
|
12
|
+
"replaceWith", "reportValidity", "requestFullscreen", "requestPointerLock", "requestSubmit",
|
|
13
|
+
"reset", "scrollBy", "scrollTo", "setAttribute", "setAttributeNS", "setCustomValidity",
|
|
14
|
+
"setRangeText", "setSelectionRange", "showModal", "submit", "toggleAttribute", "write",
|
|
15
|
+
"writeln",
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
const mutatingNamespaces = new Map([
|
|
19
|
+
["localStorage", new Set(["clear", "removeItem", "setItem"])],
|
|
20
|
+
["sessionStorage", new Set(["clear", "removeItem", "setItem"])],
|
|
21
|
+
["history", new Set(["back", "forward", "go", "pushState", "replaceState"])],
|
|
22
|
+
["location", new Set(["assign", "reload", "replace"])],
|
|
23
|
+
["navigator", new Set(["sendBeacon", "share", "vibrate"])],
|
|
24
|
+
["clipboard", new Set(["write", "writeText"])],
|
|
25
|
+
["indexedDB", new Set(["deleteDatabase", "open"])],
|
|
26
|
+
["caches", new Set(["delete", "open"])],
|
|
27
|
+
["classList", new Set(["add", "remove", "toggle", "replace"])],
|
|
28
|
+
["style", new Set(["setProperty", "removeProperty"])],
|
|
29
|
+
["Object", new Set(["assign", "defineProperty", "defineProperties", "setPrototypeOf"])],
|
|
30
|
+
["Reflect", new Set(["set", "deleteProperty", "defineProperty", "setPrototypeOf"])],
|
|
31
|
+
]);
|
|
32
|
+
|
|
33
|
+
const forbiddenCalls = new Set(["eval", "fetch", "import", "require"]);
|
|
34
|
+
|
|
35
|
+
const FORBIDDEN_ASSIGN_PROPS = new Set(["__proto__", "prototype", "constructor"]);
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Reject an expression that can mutate the page or reach the network.
|
|
39
|
+
* This is a static policy check, not a sandbox.
|
|
40
|
+
* @param {string} source
|
|
41
|
+
* @returns {string} the original source when the expression is read-only
|
|
42
|
+
*/
|
|
43
|
+
export function assertReadOnly(source) {
|
|
44
|
+
if (typeof source !== "string" || source.trim() === "") {
|
|
45
|
+
throw new Error("Browser evaluate requires a JavaScript expression");
|
|
46
|
+
}
|
|
47
|
+
let ast;
|
|
48
|
+
try {
|
|
49
|
+
ast = parse(`(${source})`, { ecmaVersion: "latest" });
|
|
50
|
+
} catch {
|
|
51
|
+
try {
|
|
52
|
+
ast = parse(source, { ecmaVersion: "latest" });
|
|
53
|
+
} catch (error) {
|
|
54
|
+
throw new Error(`Browser evaluate could not parse the expression: ${error.message}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const nonPlainReassigned = collectNonPlainReassignments(ast);
|
|
58
|
+
const violation = findViolation(ast, [], nonPlainReassigned);
|
|
59
|
+
if (violation) throw new Error(`Browser evaluate is read-only: ${violation}`);
|
|
60
|
+
return source;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const SCOPE_CREATORS = new Set([
|
|
64
|
+
"Program", "BlockStatement", "FunctionDeclaration", "FunctionExpression",
|
|
65
|
+
"ArrowFunctionExpression", "ForStatement", "ForInStatement", "ForOfStatement",
|
|
66
|
+
"CatchClause", "SwitchStatement",
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
/** @param {any} init @returns {boolean} */
|
|
70
|
+
function isPlainContainerInit(init) {
|
|
71
|
+
if (!init || typeof init !== "object") return false;
|
|
72
|
+
if (init.type === "ObjectExpression" || init.type === "ArrayExpression") return true;
|
|
73
|
+
if (
|
|
74
|
+
init.type === "CallExpression" &&
|
|
75
|
+
!init.optional &&
|
|
76
|
+
init.callee?.type === "MemberExpression" &&
|
|
77
|
+
!init.callee.computed &&
|
|
78
|
+
init.callee.object?.type === "Identifier" &&
|
|
79
|
+
init.callee.object.name === "Object" &&
|
|
80
|
+
init.callee.property?.type === "Identifier" &&
|
|
81
|
+
init.callee.property.name === "create" &&
|
|
82
|
+
Array.isArray(init.arguments) &&
|
|
83
|
+
init.arguments.length === 1 &&
|
|
84
|
+
init.arguments[0]?.type === "Literal" &&
|
|
85
|
+
init.arguments[0].value === null
|
|
86
|
+
) {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @param {any} root @returns {Set<string>} */
|
|
93
|
+
function collectNonPlainReassignments(root) {
|
|
94
|
+
const out = new Set();
|
|
95
|
+
const visit = (node) => {
|
|
96
|
+
if (!node || typeof node !== "object") return;
|
|
97
|
+
if (node.type === "AssignmentExpression") {
|
|
98
|
+
if (node.left?.type === "Identifier") {
|
|
99
|
+
if (!(node.operator === "=" && isPlainContainerInit(node.right))) {
|
|
100
|
+
out.add(node.left.name);
|
|
101
|
+
}
|
|
102
|
+
} else if (node.left?.type === "ObjectPattern" || node.left?.type === "ArrayPattern") {
|
|
103
|
+
collectPatternIdentifiers(node.left, out);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
for (const value of Object.values(node)) {
|
|
107
|
+
if (Array.isArray(value)) {
|
|
108
|
+
for (const child of value) visit(child);
|
|
109
|
+
} else if (value && typeof value === "object") {
|
|
110
|
+
visit(value);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
visit(root);
|
|
115
|
+
return out;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @param {any} pattern @param {Set<string>} out */
|
|
119
|
+
function collectPatternIdentifiers(pattern, out) {
|
|
120
|
+
if (!pattern || typeof pattern !== "object") return;
|
|
121
|
+
switch (pattern.type) {
|
|
122
|
+
case "Identifier":
|
|
123
|
+
out.add(pattern.name);
|
|
124
|
+
break;
|
|
125
|
+
case "ObjectPattern":
|
|
126
|
+
for (const prop of pattern.properties ?? []) {
|
|
127
|
+
collectPatternIdentifiers(prop?.type === "Property" ? prop.value : prop, out);
|
|
128
|
+
}
|
|
129
|
+
break;
|
|
130
|
+
case "ArrayPattern":
|
|
131
|
+
for (const elem of pattern.elements ?? []) {
|
|
132
|
+
if (elem) collectPatternIdentifiers(elem, out);
|
|
133
|
+
}
|
|
134
|
+
break;
|
|
135
|
+
case "RestElement":
|
|
136
|
+
collectPatternIdentifiers(pattern.argument, out);
|
|
137
|
+
break;
|
|
138
|
+
case "AssignmentPattern":
|
|
139
|
+
collectPatternIdentifiers(pattern.left, out);
|
|
140
|
+
break;
|
|
141
|
+
default:
|
|
142
|
+
break;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** @param {any} node @param {Set<string>} out */
|
|
147
|
+
function collectHoistedVars(node, out) {
|
|
148
|
+
if (!node || typeof node !== "object") return;
|
|
149
|
+
if (["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"].includes(node.type)) return;
|
|
150
|
+
if (node.type === "VariableDeclaration" && node.kind === "var") {
|
|
151
|
+
for (const decl of node.declarations ?? []) collectPatternIdentifiers(decl.id, out);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
for (const value of Object.values(node)) {
|
|
155
|
+
if (Array.isArray(value)) {
|
|
156
|
+
for (const child of value) collectHoistedVars(child, out);
|
|
157
|
+
} else if (value && typeof value === "object") {
|
|
158
|
+
collectHoistedVars(value, out);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** @param {any} statements @param {{locals:Set<string>, plainContainers:Set<string>}} scope @param {Set<string>} nonPlainReassigned */
|
|
164
|
+
function collectDirectDeclarations(statements, scope, nonPlainReassigned) {
|
|
165
|
+
for (const stmt of Array.isArray(statements) ? statements : []) {
|
|
166
|
+
if (!stmt || typeof stmt !== "object") continue;
|
|
167
|
+
if (stmt.type === "VariableDeclaration") {
|
|
168
|
+
for (const decl of stmt.declarations ?? []) {
|
|
169
|
+
collectPatternIdentifiers(decl.id, scope.locals);
|
|
170
|
+
if (decl.id?.type === "Identifier" && isPlainContainerInit(decl.init) && !nonPlainReassigned.has(decl.id.name)) {
|
|
171
|
+
scope.plainContainers.add(decl.id.name);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
} else if ((stmt.type === "FunctionDeclaration" || stmt.type === "ClassDeclaration") && stmt.id?.name) {
|
|
175
|
+
scope.locals.add(stmt.id.name);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** @param {any} node @param {Set<string>} nonPlainReassigned @returns {{locals:Set<string>, plainContainers:Set<string>}} */
|
|
181
|
+
function createScopeForNode(node, nonPlainReassigned) {
|
|
182
|
+
const scope = { locals: new Set(), plainContainers: new Set() };
|
|
183
|
+
const type = node.type;
|
|
184
|
+
if (type === "Program" || type === "BlockStatement") {
|
|
185
|
+
collectDirectDeclarations(node.body, scope, nonPlainReassigned);
|
|
186
|
+
if (type === "Program") {
|
|
187
|
+
for (const stmt of node.body ?? []) collectHoistedVars(stmt, scope.locals);
|
|
188
|
+
}
|
|
189
|
+
} else if (type === "FunctionDeclaration" || type === "FunctionExpression" || type === "ArrowFunctionExpression") {
|
|
190
|
+
if (node.id?.name) scope.locals.add(node.id.name);
|
|
191
|
+
for (const param of node.params ?? []) collectPatternIdentifiers(param, scope.locals);
|
|
192
|
+
if (node.body?.type === "BlockStatement") {
|
|
193
|
+
collectDirectDeclarations(node.body.body, scope, nonPlainReassigned);
|
|
194
|
+
for (const stmt of node.body.body ?? []) collectHoistedVars(stmt, scope.locals);
|
|
195
|
+
}
|
|
196
|
+
} else if (type === "ForStatement") {
|
|
197
|
+
if (node.init?.type === "VariableDeclaration") {
|
|
198
|
+
collectDirectDeclarations([node.init], scope, nonPlainReassigned);
|
|
199
|
+
}
|
|
200
|
+
} else if (type === "ForInStatement" || type === "ForOfStatement") {
|
|
201
|
+
if (node.left?.type === "VariableDeclaration") {
|
|
202
|
+
for (const decl of node.left.declarations ?? []) collectPatternIdentifiers(decl.id, scope.locals);
|
|
203
|
+
}
|
|
204
|
+
} else if (type === "CatchClause" && node.param) {
|
|
205
|
+
collectPatternIdentifiers(node.param, scope.locals);
|
|
206
|
+
} else if (type === "SwitchStatement") {
|
|
207
|
+
for (const c of node.cases ?? []) collectDirectDeclarations(c.consequent, scope, nonPlainReassigned);
|
|
208
|
+
}
|
|
209
|
+
return scope;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** @param {string} name @param {Array<{locals:Set<string>, plainContainers:Set<string>}>} scopes @returns {boolean} */
|
|
213
|
+
function isLocalIdentifier(name, scopes) {
|
|
214
|
+
for (let i = scopes.length - 1; i >= 0; i--) {
|
|
215
|
+
if (scopes[i].locals.has(name)) return true;
|
|
216
|
+
}
|
|
217
|
+
return false;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** @param {string} name @param {Array<{locals:Set<string>, plainContainers:Set<string>}>} scopes @returns {boolean} */
|
|
221
|
+
function isLocalPlainContainer(name, scopes) {
|
|
222
|
+
for (let i = scopes.length - 1; i >= 0; i--) {
|
|
223
|
+
if (scopes[i].plainContainers.has(name)) return true;
|
|
224
|
+
if (scopes[i].locals.has(name)) return false;
|
|
225
|
+
}
|
|
226
|
+
return false;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** @param {any} node @param {Array<{locals:Set<string>, plainContainers:Set<string>}>} scopes @returns {boolean} */
|
|
230
|
+
function isSafePlainMemberTarget(node, scopes) {
|
|
231
|
+
if (node?.type !== "MemberExpression" || node.object?.type !== "Identifier") return false;
|
|
232
|
+
if (!isLocalPlainContainer(node.object.name, scopes)) return false;
|
|
233
|
+
if (!node.computed) return !FORBIDDEN_ASSIGN_PROPS.has(node.property?.name);
|
|
234
|
+
if (node.property?.type === "Literal") {
|
|
235
|
+
return !FORBIDDEN_ASSIGN_PROPS.has(String(node.property.value));
|
|
236
|
+
}
|
|
237
|
+
if (node.property?.type === "TemplateLiteral" && node.property.expressions?.length === 0) {
|
|
238
|
+
return !FORBIDDEN_ASSIGN_PROPS.has(String(node.property.quasis?.[0]?.value?.cooked ?? ""));
|
|
239
|
+
}
|
|
240
|
+
return true;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* @param {unknown} node
|
|
245
|
+
* @param {Array<{locals:Set<string>, plainContainers:Set<string>}>} scopes
|
|
246
|
+
* @param {Set<string>} nonPlainReassigned
|
|
247
|
+
* @returns {string|null}
|
|
248
|
+
*/
|
|
249
|
+
function findViolation(node, scopes = [], nonPlainReassigned = new Set()) {
|
|
250
|
+
if (!node || typeof node !== "object") return null;
|
|
251
|
+
const record = /** @type {Record<string, unknown>} */ (node);
|
|
252
|
+
const type = record.type;
|
|
253
|
+
|
|
254
|
+
const activeScopes = SCOPE_CREATORS.has(String(type))
|
|
255
|
+
? [...scopes, createScopeForNode(record, nonPlainReassigned)]
|
|
256
|
+
: scopes;
|
|
257
|
+
|
|
258
|
+
if (type === "AssignmentExpression") {
|
|
259
|
+
const left = /** @type {any} */ (record.left);
|
|
260
|
+
if (left?.type === "Identifier" && isLocalIdentifier(left.name, activeScopes)) {
|
|
261
|
+
return findViolation(record.right, activeScopes, nonPlainReassigned);
|
|
262
|
+
}
|
|
263
|
+
if (isSafePlainMemberTarget(left, activeScopes)) {
|
|
264
|
+
if (left.computed) {
|
|
265
|
+
const keyViolation = findViolation(left.property, activeScopes, nonPlainReassigned);
|
|
266
|
+
if (keyViolation) return keyViolation;
|
|
267
|
+
}
|
|
268
|
+
return findViolation(record.right, activeScopes, nonPlainReassigned);
|
|
269
|
+
}
|
|
270
|
+
return "assignment is not allowed (only local variables and direct properties/indices of locally created {} or [] objects may be assigned; do not mutate DOM nodes, parameters, or globals)";
|
|
271
|
+
}
|
|
272
|
+
if (type === "UpdateExpression") {
|
|
273
|
+
const arg = /** @type {any} */ (record.argument);
|
|
274
|
+
if (arg?.type === "Identifier" && isLocalIdentifier(arg.name, activeScopes)) {
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
if (isSafePlainMemberTarget(arg, activeScopes)) {
|
|
278
|
+
return arg.computed ? findViolation(arg.property, activeScopes, nonPlainReassigned) : null;
|
|
279
|
+
}
|
|
280
|
+
return "increment and decrement are not allowed";
|
|
281
|
+
}
|
|
282
|
+
if (type === "UnaryExpression" && record.operator === "delete") return "delete is not allowed";
|
|
283
|
+
if (type === "ImportExpression") return "dynamic import is not allowed";
|
|
284
|
+
if (type === "NewExpression" && record.callee && /** @type {any} */ (record.callee).name === "Function") {
|
|
285
|
+
return "dynamic code construction is not allowed";
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (type === "CallExpression") {
|
|
289
|
+
const callee = /** @type {any} */ (record.callee);
|
|
290
|
+
if (callee?.type === "Identifier" && forbiddenCalls.has(callee.name)) {
|
|
291
|
+
return `${callee.name}() is not allowed`;
|
|
292
|
+
}
|
|
293
|
+
if (callee?.type === "MemberExpression" && !callee.computed) {
|
|
294
|
+
const object = callee.object;
|
|
295
|
+
const property = callee.property?.name;
|
|
296
|
+
if (typeof property === "string" && mutatingMethods.has(property)) {
|
|
297
|
+
return `${property}() is not allowed`;
|
|
298
|
+
}
|
|
299
|
+
const namespace = namespaceOf(object);
|
|
300
|
+
if (namespace && typeof property === "string" && mutatingNamespaces.get(namespace)?.has(property)) {
|
|
301
|
+
return `${namespace}.${property}() is not allowed`;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
for (const value of Object.values(record)) {
|
|
307
|
+
if (Array.isArray(value)) {
|
|
308
|
+
for (const child of value) {
|
|
309
|
+
const violation = findViolation(child, activeScopes, nonPlainReassigned);
|
|
310
|
+
if (violation) return violation;
|
|
311
|
+
}
|
|
312
|
+
} else if (value && typeof value === "object") {
|
|
313
|
+
const violation = findViolation(value, activeScopes, nonPlainReassigned);
|
|
314
|
+
if (violation) return violation;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Resolve a namespace chain such as `window.localStorage` to `localStorage`.
|
|
322
|
+
* @param {any} node
|
|
323
|
+
* @returns {string|null}
|
|
324
|
+
*/
|
|
325
|
+
function namespaceOf(node) {
|
|
326
|
+
if (!node || typeof node !== "object") return null;
|
|
327
|
+
if (node.type === "Identifier") return node.name;
|
|
328
|
+
if (node.type === "MemberExpression" && !node.computed && node.property?.type === "Identifier") {
|
|
329
|
+
return node.property.name;
|
|
330
|
+
}
|
|
331
|
+
if (node.type === "ChainExpression") return namespaceOf(node.expression);
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { fork } from "node:child_process";
|
|
2
|
+
import { once } from "node:events";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
|
|
5
|
+
/** @typedef {{type: 'text', text: string} | {type: 'image', data: string, mimeType: string}} ContentItem */
|
|
6
|
+
/** @typedef {{content: ContentItem[], isError?: boolean}} EvaluationResult */
|
|
7
|
+
/** @typedef {{enginePath?: string, requestMeta?: Record<string, unknown>, env?: Record<string, string>, hostConfigRoot?: string, onElicitation?: (request: unknown) => Promise<unknown>}} SessionOptions */
|
|
8
|
+
|
|
9
|
+
/** One isolated, serialized JavaScript runtime per MCP connection. */
|
|
10
|
+
export class ReplSession {
|
|
11
|
+
/** @param {SessionOptions} [options] */
|
|
12
|
+
constructor(options = {}) {
|
|
13
|
+
this.options = options;
|
|
14
|
+
/** @type {import('node:child_process').ChildProcess | null} */
|
|
15
|
+
this.child = null;
|
|
16
|
+
/** @type {Map<number, {resolve: (result: EvaluationResult) => void, reject: (error: Error) => void}>} */
|
|
17
|
+
this.pending = new Map();
|
|
18
|
+
/** @type {WeakMap<import('node:child_process').ChildProcess, Error>} */
|
|
19
|
+
this.terminationErrors = new WeakMap();
|
|
20
|
+
this.nextId = 0;
|
|
21
|
+
this.closed = false;
|
|
22
|
+
this.closing = false;
|
|
23
|
+
this.generation = 0;
|
|
24
|
+
/** @type {Promise<void> | undefined} */
|
|
25
|
+
this.closePromise = undefined;
|
|
26
|
+
this.queue = Promise.resolve();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param {boolean} [allowClosing] @returns {import('node:child_process').ChildProcess} */
|
|
30
|
+
ensureWorker(allowClosing = false) {
|
|
31
|
+
if (this.closed || (this.closing && !allowClosing)) throw new Error("JavaScript session is closed");
|
|
32
|
+
if (this.child) return this.child;
|
|
33
|
+
const child = fork(fileURLToPath(new URL("./repl-worker.js", import.meta.url)), [], {
|
|
34
|
+
stdio: ["ignore", "ignore", "pipe", "ipc"],
|
|
35
|
+
execArgv: [],
|
|
36
|
+
env: { ...process.env, ...this.options.env },
|
|
37
|
+
serialization: "advanced",
|
|
38
|
+
});
|
|
39
|
+
this.child = child;
|
|
40
|
+
// Diagnostics must never enter the parent's MCP stdout transport.
|
|
41
|
+
child.stderr?.on("data", (chunk) => process.stderr.write(chunk));
|
|
42
|
+
child.on("message", (message) => {
|
|
43
|
+
if (!message || typeof message !== "object") return;
|
|
44
|
+
if (message.type === "elicitation") {
|
|
45
|
+
void this.respondToElicitation(child, message);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (message.type !== "result") return;
|
|
49
|
+
const pending = this.pending.get(message.id);
|
|
50
|
+
if (!pending) return;
|
|
51
|
+
this.pending.delete(message.id);
|
|
52
|
+
pending.resolve(message.result);
|
|
53
|
+
});
|
|
54
|
+
child.on("error", (error) => this.rejectWorker(child, error));
|
|
55
|
+
child.on("exit", (code, signal) => {
|
|
56
|
+
this.rejectWorker(child, this.terminationErrors.get(child) ?? new Error(`JavaScript worker exited (${signal ?? code})`));
|
|
57
|
+
});
|
|
58
|
+
return child;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {import('node:child_process').ChildProcess} child @param {{id: number, request: unknown}} message @returns {Promise<void>} */
|
|
62
|
+
async respondToElicitation(child, message) {
|
|
63
|
+
try {
|
|
64
|
+
if (!this.options.onElicitation) throw new Error("This MCP client cannot request browser approval");
|
|
65
|
+
const result = await this.options.onElicitation(message.request);
|
|
66
|
+
if (child.connected) child.send({ type: "elicitation_result", id: message.id, result });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (child.connected) child.send({ type: "elicitation_result", id: message.id, error: error instanceof Error ? error.message : String(error) });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @param {import('node:child_process').ChildProcess} child @param {Error} error @returns {void} */
|
|
73
|
+
rejectWorker(child, error) {
|
|
74
|
+
if (this.child !== child) return;
|
|
75
|
+
this.child = null;
|
|
76
|
+
for (const pending of this.pending.values()) pending.reject(error);
|
|
77
|
+
this.pending.clear();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** @template T @param {() => Promise<T>} operation @returns {Promise<T>} */
|
|
81
|
+
serialized(operation) {
|
|
82
|
+
const next = this.queue.then(operation, operation);
|
|
83
|
+
this.queue = next.then(() => undefined, () => undefined);
|
|
84
|
+
return next;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** @param {string} code @param {{timeoutMs?: number, requestMeta?: Record<string, unknown>, signal?: AbortSignal}} [options] @returns {Promise<EvaluationResult>} */
|
|
88
|
+
evaluate(code, options = {}) {
|
|
89
|
+
if (this.closing || this.closed) return Promise.reject(new Error("JavaScript session is closed"));
|
|
90
|
+
if (typeof code !== "string" || !code.trim()) return Promise.reject(new Error("JavaScript code must be a non-empty string"));
|
|
91
|
+
const timeoutMs = options.timeoutMs ?? 30000;
|
|
92
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 300000) return Promise.reject(new Error("timeoutMs must be an integer from 1 through 300000"));
|
|
93
|
+
const generation = this.generation;
|
|
94
|
+
return this.serialized(() => {
|
|
95
|
+
if (generation !== this.generation) throw new Error(this.closing || this.closed ? "JavaScript session is closed" : "JavaScript session was reset before this request started");
|
|
96
|
+
return this.request("evaluate", { code, requestMeta: options.requestMeta }, timeoutMs, options.signal);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** @param {string} type @param {Record<string, unknown>} params @param {number} timeoutMs @param {AbortSignal} [signal] @returns {Promise<EvaluationResult>} */
|
|
101
|
+
async request(type, params, timeoutMs, signal) {
|
|
102
|
+
signal?.throwIfAborted();
|
|
103
|
+
const child = this.ensureWorker(type === "close");
|
|
104
|
+
const id = ++this.nextId;
|
|
105
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
106
|
+
let timer;
|
|
107
|
+
const abort = () => this.terminateWorker(child, new Error("JavaScript execution cancelled; session bindings were reset"));
|
|
108
|
+
try {
|
|
109
|
+
return await new Promise((resolve, reject) => {
|
|
110
|
+
this.pending.set(id, { resolve, reject });
|
|
111
|
+
timer = setTimeout(() => {
|
|
112
|
+
// Kill before letting the serialized queue proceed: timed-out code
|
|
113
|
+
// must not continue changing browser state beside the next request.
|
|
114
|
+
this.terminateWorker(child, new Error(`JavaScript execution timed out after ${timeoutMs}ms; session bindings were reset`));
|
|
115
|
+
}, timeoutMs);
|
|
116
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
117
|
+
const workerOptions = { ...this.options };
|
|
118
|
+
delete workerOptions.onElicitation;
|
|
119
|
+
child.send({ type, id, params, options: workerOptions }, (error) => {
|
|
120
|
+
if (error) this.rejectWorker(child, error);
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
} finally {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
signal?.removeEventListener("abort", abort);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** @param {import("node:child_process").ChildProcess} child @param {Error} error @returns {void} */
|
|
130
|
+
terminateWorker(child, error) {
|
|
131
|
+
this.terminationErrors.set(child, error);
|
|
132
|
+
if (!child.kill("SIGKILL") && (child.exitCode !== null || child.signalCode !== null)) this.rejectWorker(child, error);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** End the current browser turn while retaining JavaScript bindings. @returns {Promise<EvaluationResult>} */
|
|
136
|
+
endTurn() {
|
|
137
|
+
return this.serialized(async () => this.child ? this.request("end_turn", {}, 30000) : { content: [] });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Discard bindings and release the current browser session. @returns {Promise<void>} */
|
|
141
|
+
reset() {
|
|
142
|
+
if (this.closing || this.closed) return Promise.reject(new Error("JavaScript session is closed"));
|
|
143
|
+
this.generation += 1;
|
|
144
|
+
if (this.child && this.pending.size > 0) this.terminateWorker(this.child, new Error("JavaScript session reset during execution; worker terminated"));
|
|
145
|
+
return this.serialized(async () => this.stopWorker());
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** @returns {Promise<void>} */
|
|
149
|
+
async stopWorker() {
|
|
150
|
+
const child = this.child;
|
|
151
|
+
if (!child) return;
|
|
152
|
+
try {
|
|
153
|
+
const result = await this.request("close", {}, 5000);
|
|
154
|
+
if (result.isError) throw new Error(result.content.filter((item) => item.type === "text").map((item) => item.text).join("\n"));
|
|
155
|
+
} finally {
|
|
156
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
157
|
+
const exited = once(child, "exit");
|
|
158
|
+
child.kill("SIGKILL");
|
|
159
|
+
await exited;
|
|
160
|
+
}
|
|
161
|
+
if (this.child === child) this.child = null;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Permanently close this MCP connection's runtime. @returns {Promise<void>} */
|
|
166
|
+
close() {
|
|
167
|
+
if (this.closePromise) return this.closePromise;
|
|
168
|
+
this.closing = true;
|
|
169
|
+
this.generation += 1;
|
|
170
|
+
if (this.child && this.pending.size > 0) this.terminateWorker(this.child, new Error("JavaScript session closed during execution; worker terminated"));
|
|
171
|
+
this.closePromise = this.serialized(async () => {
|
|
172
|
+
try {
|
|
173
|
+
await this.stopWorker();
|
|
174
|
+
} finally {
|
|
175
|
+
this.closed = true;
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
return this.closePromise;
|
|
179
|
+
}
|
|
180
|
+
}
|