@dudko.dev/agent-web 0.0.36 → 0.0.38
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 +156 -4
- package/dist/agent-web.js +270 -110
- package/dist/agent-web.js.map +1 -1
- package/dist/chunk-AY2BZYZY.js +573 -0
- package/dist/chunk-AY2BZYZY.js.map +1 -0
- package/dist/chunk-CTXDKSDD.js +39 -0
- package/dist/chunk-CTXDKSDD.js.map +1 -0
- package/dist/{chunk-CPSDKXO6.js → chunk-T6LZW7ML.js} +27 -35
- package/dist/chunk-T6LZW7ML.js.map +1 -0
- package/dist/chunk-V3JOK7EW.js +929 -0
- package/dist/chunk-V3JOK7EW.js.map +1 -0
- package/dist/index.cjs +5980 -3627
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +363 -3
- package/dist/index.d.ts +363 -3
- package/dist/index.js +1183 -583
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +879 -13
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +372 -13
- package/dist/mcp.d.ts +372 -13
- package/dist/mcp.js +857 -15
- package/dist/mcp.js.map +1 -1
- package/dist/sandbox-AMO2SA4X.js +269 -0
- package/dist/sandbox-AMO2SA4X.js.map +1 -0
- package/dist/sandbox-worker.cjs +745 -0
- package/dist/sandbox-worker.cjs.map +1 -0
- package/dist/sandbox-worker.d.cts +37 -0
- package/dist/sandbox-worker.d.ts +37 -0
- package/dist/sandbox-worker.js +27 -0
- package/dist/sandbox-worker.js.map +1 -0
- package/package.json +30 -11
- package/dist/chunk-CPSDKXO6.js.map +0 -1
|
@@ -0,0 +1,929 @@
|
|
|
1
|
+
// src/sandbox/engine.ts
|
|
2
|
+
var RUN_JS_TOOL = "run_js";
|
|
3
|
+
var SANDBOX_PACKAGE = "quickjs-emscripten";
|
|
4
|
+
var MIB = 1024 * 1024;
|
|
5
|
+
var SANDBOX_DEFAULTS = {
|
|
6
|
+
timeoutMs: 5e3,
|
|
7
|
+
memoryLimitBytes: 32 * MIB,
|
|
8
|
+
maxOutputChars: 8e3,
|
|
9
|
+
maxCodeChars: 1e5
|
|
10
|
+
};
|
|
11
|
+
var SANDBOX_CAPS = {
|
|
12
|
+
timeoutMs: 6e4,
|
|
13
|
+
memoryLimitBytes: 256 * MIB,
|
|
14
|
+
maxOutputChars: 1e5,
|
|
15
|
+
maxCodeChars: 1e6
|
|
16
|
+
};
|
|
17
|
+
var SANDBOX_FLOORS = {
|
|
18
|
+
timeoutMs: 50,
|
|
19
|
+
// What the engine's WebAssembly module asks for before it runs anything.
|
|
20
|
+
memoryLimitBytes: 16 * MIB,
|
|
21
|
+
maxOutputChars: 200,
|
|
22
|
+
maxCodeChars: 100
|
|
23
|
+
};
|
|
24
|
+
var SANDBOX_MAX_MODULES = 64;
|
|
25
|
+
var SANDBOX_MAX_MODULE_CHARS_TOTAL = 2e6;
|
|
26
|
+
var SANDBOX_MAX_FILE_CHARS = 1e6;
|
|
27
|
+
var SANDBOX_MAX_HOST_CALLS = 500;
|
|
28
|
+
var SANDBOX_MODULE_EXTENSIONS = [".js", ".mjs", ".json"];
|
|
29
|
+
var MAX_TIMERS = 1e3;
|
|
30
|
+
var GUEST_STACK_BYTES = 256 * 1024;
|
|
31
|
+
var ERROR_NAME_CHARS = 200;
|
|
32
|
+
var ERROR_TEXT_CHARS = 4e3;
|
|
33
|
+
var bounded = (value, key) => {
|
|
34
|
+
const n = typeof value === "number" && Number.isFinite(value) ? Math.floor(value) : NaN;
|
|
35
|
+
if (Number.isNaN(n) || n <= 0) {
|
|
36
|
+
return SANDBOX_DEFAULTS[key];
|
|
37
|
+
}
|
|
38
|
+
return Math.min(SANDBOX_CAPS[key], Math.max(SANDBOX_FLOORS[key], n));
|
|
39
|
+
};
|
|
40
|
+
var resolveSandboxLimits = (config) => ({
|
|
41
|
+
timeoutMs: bounded(config?.timeoutMs, "timeoutMs"),
|
|
42
|
+
memoryLimitBytes: bounded(config?.memoryLimitBytes, "memoryLimitBytes"),
|
|
43
|
+
maxOutputChars: bounded(config?.maxOutputChars, "maxOutputChars"),
|
|
44
|
+
maxCodeChars: bounded(config?.maxCodeChars, "maxCodeChars")
|
|
45
|
+
});
|
|
46
|
+
var SandboxUnavailableError = class extends Error {
|
|
47
|
+
constructor(message) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "SandboxUnavailableError";
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
var sandboxPeerMissing = (detail) => new SandboxUnavailableError(
|
|
53
|
+
`The sandbox (${RUN_JS_TOOL}) needs the optional package "${SANDBOX_PACKAGE}", which is not installed. Add it to your app: npm install ${SANDBOX_PACKAGE}${detail ? ` (${detail})` : ""}`
|
|
54
|
+
);
|
|
55
|
+
var sandboxPromptNote = (files) => `${RUN_JS_TOOL} runs JavaScript you wrote in an isolated sandbox and returns what it printed (console.log) and the value of its last expression. It is plain JavaScript on QuickJS (ES2023, top-level await), not Node and not a browser: no network, no npm packages, no process${files ? "; workspace files are reachable by relative path (import / require of .js, .mjs, .json) and through the async fs.readFile / fs.writeFile / fs.readdir" : ", no files"}. Never say that code was run, tested or printed something unless ${RUN_JS_TOOL} was called and returned it: quote its real output, and if it was not run, say so.`;
|
|
56
|
+
var SANDBOX_PLANNER_NOTE = `When the request needs code to be run, tested or checked on data, or a calculation that is easier to compute than to reason about, plan a step that calls ${RUN_JS_TOOL} for it.`;
|
|
57
|
+
var SANDBOX_SYNTHESIZER_NOTE = `Report the output of running code only when a ${RUN_JS_TOOL} call returned it; if the code was written but not run, say it was not run.`;
|
|
58
|
+
var clip = (text, max) => text.length > max ? text.slice(0, max) : text;
|
|
59
|
+
var errorText = (err) => {
|
|
60
|
+
if (err instanceof Error) {
|
|
61
|
+
return `${err.name}: ${err.message}`;
|
|
62
|
+
}
|
|
63
|
+
return typeof err === "string" ? err : "unknown error";
|
|
64
|
+
};
|
|
65
|
+
var dirname = (path) => {
|
|
66
|
+
const i = path.lastIndexOf("/");
|
|
67
|
+
return i <= 0 ? "/" : path.slice(0, i);
|
|
68
|
+
};
|
|
69
|
+
var resolveModulePath = (base, specifier) => {
|
|
70
|
+
const spec = String(specifier);
|
|
71
|
+
if (!/^(\.{1,2}\/|\/)/.test(spec) || /[\\\0]/.test(spec)) {
|
|
72
|
+
throw new Error(
|
|
73
|
+
`Cannot load "${clip(spec, 200)}": the sandbox has no packages and no Node or browser modules - only workspace files by path ("./lib.js")`
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
const parts = spec.startsWith("/") ? [] : dirname(base).split("/").filter(Boolean);
|
|
77
|
+
for (const seg of spec.split("/")) {
|
|
78
|
+
if (!seg || seg === ".") {
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (seg === "..") {
|
|
82
|
+
if (parts.length === 0) {
|
|
83
|
+
throw new Error(`Cannot load "${clip(spec, 200)}": the path leaves the workspace`);
|
|
84
|
+
}
|
|
85
|
+
parts.pop();
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
parts.push(seg);
|
|
89
|
+
}
|
|
90
|
+
const path = `/${parts.join("/")}`;
|
|
91
|
+
if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) {
|
|
92
|
+
throw new Error(
|
|
93
|
+
`Cannot load "${clip(path, 200)}": only ${SANDBOX_MODULE_EXTENSIONS.join(", ")} files can be imported`
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
return path;
|
|
97
|
+
};
|
|
98
|
+
var moduleSpecifiersOf = (source) => {
|
|
99
|
+
const found = /* @__PURE__ */ new Set();
|
|
100
|
+
const patterns = [
|
|
101
|
+
/\bimport\s*(?:[\w$*{}\s,]*?\bfrom\s*)?(['"])([^'"\n]+)\1/g,
|
|
102
|
+
/\bexport\s*[\w$*{}\s,]*?\bfrom\s*(['"])([^'"\n]+)\1/g,
|
|
103
|
+
/\b(?:import|require)\s*\(\s*(['"])([^'"\n]+)\1\s*\)/g
|
|
104
|
+
];
|
|
105
|
+
for (const re of patterns) {
|
|
106
|
+
for (const m of source.matchAll(re)) {
|
|
107
|
+
found.add(m[2]);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return [...found];
|
|
111
|
+
};
|
|
112
|
+
var looksLikeModule = (code) => /(^|[\n;])\s*(import\s*[\w$*{'"]|export\s+[\w$*{])/.test(code);
|
|
113
|
+
var EVAL_SCRIPT_ASYNC = 128;
|
|
114
|
+
var BOOTSTRAP = `(function (host, cfg) {
|
|
115
|
+
'use strict';
|
|
116
|
+
var g = globalThis, J = JSON, S = String, E = Error, P = Promise, M = Map, R = Reflect;
|
|
117
|
+
var hostLog = host.log, hostTimer = host.timer, hostClear = host.clear;
|
|
118
|
+
var hostCall = host.call, hostResolve = host.resolve, hostCompile = host.compile;
|
|
119
|
+
function inspect(v, depth, seen) {
|
|
120
|
+
var t = typeof v;
|
|
121
|
+
if (t === 'string') return depth ? J.stringify(v) : v;
|
|
122
|
+
if (t === 'bigint') return S(v) + 'n';
|
|
123
|
+
if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';
|
|
124
|
+
if (t !== 'object' || v === null) return S(v);
|
|
125
|
+
if (v instanceof E) return S(v.name) + ': ' + S(v.message) + (v.stack ? '\\n' + S(v.stack).replace(/\\n$/, '') : '');
|
|
126
|
+
if (seen.indexOf(v) >= 0) return '[Circular]';
|
|
127
|
+
if (depth > 4) return Array.isArray(v) ? '[Array]' : '[Object]';
|
|
128
|
+
if (v instanceof Date) return isNaN(v) ? 'Invalid Date' : v.toISOString();
|
|
129
|
+
if (v instanceof RegExp) return S(v);
|
|
130
|
+
seen.push(v);
|
|
131
|
+
var parts = [], out, i, keys;
|
|
132
|
+
if (Array.isArray(v)) {
|
|
133
|
+
for (i = 0; i < v.length && i < 100; i++) parts.push(inspect(v[i], depth + 1, seen));
|
|
134
|
+
if (v.length > 100) parts.push('... ' + (v.length - 100) + ' more');
|
|
135
|
+
out = parts.length ? '[ ' + parts.join(', ') + ' ]' : '[]';
|
|
136
|
+
} else if (v instanceof M) {
|
|
137
|
+
v.forEach(function (val, key) { if (parts.length < 50) parts.push(inspect(key, depth + 1, seen) + ' => ' + inspect(val, depth + 1, seen)); });
|
|
138
|
+
out = 'Map(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';
|
|
139
|
+
} else if (v instanceof Set) {
|
|
140
|
+
v.forEach(function (val) { if (parts.length < 50) parts.push(inspect(val, depth + 1, seen)); });
|
|
141
|
+
out = 'Set(' + v.size + ') {' + (parts.length ? ' ' + parts.join(', ') + ' ' : '') + '}';
|
|
142
|
+
} else {
|
|
143
|
+
keys = Object.keys(v);
|
|
144
|
+
for (i = 0; i < keys.length && i < 50; i++) parts.push(keys[i] + ': ' + inspect(v[keys[i]], depth + 1, seen));
|
|
145
|
+
if (keys.length > 50) parts.push('... ' + (keys.length - 50) + ' more');
|
|
146
|
+
out = parts.length ? '{ ' + parts.join(', ') + ' }' : '{}';
|
|
147
|
+
}
|
|
148
|
+
seen.pop();
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
function print(level) {
|
|
152
|
+
return function () {
|
|
153
|
+
var s = '', i;
|
|
154
|
+
try {
|
|
155
|
+
for (i = 0; i < arguments.length && s.length <= cfg.max; i++) s += (i ? ' ' : '') + inspect(arguments[i], 0, []);
|
|
156
|
+
} catch (e) { s += '[unprintable]'; }
|
|
157
|
+
hostLog(level, s.length > cfg.max ? s.slice(0, cfg.max + 1) : s);
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
g.console = { log: print(''), info: print(''), debug: print(''), trace: print(''), warn: print('warn'), error: print('error') };
|
|
161
|
+
function plain(v, depth, seen, budget) {
|
|
162
|
+
var t = typeof v, out, i, keys;
|
|
163
|
+
if ((budget.n -= 1) < 0) { budget.cut = true; return '[Truncated]'; }
|
|
164
|
+
if (v === null || t === 'boolean' || t === 'undefined') return v;
|
|
165
|
+
if (t === 'string') { if (v.length > cfg.max) { budget.cut = true; return v.slice(0, cfg.max); } return v; }
|
|
166
|
+
if (t === 'number') return isFinite(v) ? v : S(v);
|
|
167
|
+
if (t === 'bigint') return S(v) + 'n';
|
|
168
|
+
if (t === 'symbol') return S(v);
|
|
169
|
+
if (t === 'function') return '[Function' + (v.name ? ': ' + v.name : '') + ']';
|
|
170
|
+
if (v instanceof E) return { name: S(v.name), message: S(v.message) };
|
|
171
|
+
if (seen.indexOf(v) >= 0) return '[Circular]';
|
|
172
|
+
if (depth >= 8) return Array.isArray(v) ? '[Array]' : '[Object]';
|
|
173
|
+
if (v instanceof Date) return isNaN(v) ? null : v.toISOString();
|
|
174
|
+
seen.push(v);
|
|
175
|
+
if (v instanceof M) { out = []; v.forEach(function (val, key) { out.push([plain(key, depth + 1, seen, budget), plain(val, depth + 1, seen, budget)]); }); }
|
|
176
|
+
else if (v instanceof Set) { out = []; v.forEach(function (val) { out.push(plain(val, depth + 1, seen, budget)); }); }
|
|
177
|
+
else if (Array.isArray(v)) { out = []; for (i = 0; i < v.length && budget.n >= 0; i++) out.push(plain(v[i], depth + 1, seen, budget)); }
|
|
178
|
+
else { out = {}; keys = Object.keys(v); for (i = 0; i < keys.length && budget.n >= 0; i++) out[keys[i]] = plain(v[keys[i]], depth + 1, seen, budget); }
|
|
179
|
+
seen.pop();
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
function serialize(v, max) {
|
|
183
|
+
if (v === undefined) return '';
|
|
184
|
+
var budget = { n: 20000, cut: false }, text;
|
|
185
|
+
try { text = J.stringify(plain(v, 0, [], budget)); } catch (e) { text = J.stringify('[unserializable]'); }
|
|
186
|
+
if (text === undefined) return '';
|
|
187
|
+
if (text.length > max) return 'T' + text.slice(0, max);
|
|
188
|
+
return (budget.cut ? 'C' : 'J') + text;
|
|
189
|
+
}
|
|
190
|
+
function describe(e) {
|
|
191
|
+
var name = 'Error', message = '', stack = '';
|
|
192
|
+
try {
|
|
193
|
+
if (e instanceof E || (e && typeof e === 'object' && typeof e.message === 'string')) {
|
|
194
|
+
name = S(e.name || 'Error'); message = S(e.message); stack = typeof e.stack === 'string' ? e.stack : '';
|
|
195
|
+
} else { message = 'thrown: ' + inspect(e, 1, []); }
|
|
196
|
+
} catch (x) { message = '[unprintable error]'; }
|
|
197
|
+
return J.stringify([name.slice(0, cfg.nameMax), message.slice(0, cfg.textMax), stack.slice(0, cfg.textMax)]);
|
|
198
|
+
}
|
|
199
|
+
var timers = new M(), nextTimer = 1;
|
|
200
|
+
function timer(repeat) {
|
|
201
|
+
return function (fn, ms) {
|
|
202
|
+
if (typeof fn !== 'function') throw new TypeError('the first argument must be a function');
|
|
203
|
+
if (timers.size >= cfg.maxTimers) throw new RangeError('too many timers');
|
|
204
|
+
var id = nextTimer++;
|
|
205
|
+
ms = +ms; if (!(ms >= 0)) ms = 0; if (ms > 2147483647) ms = 2147483647;
|
|
206
|
+
if (repeat && ms < 1) ms = 1;
|
|
207
|
+
timers.set(id, { fn: fn, args: Array.prototype.slice.call(arguments, 2), ms: ms, repeat: repeat });
|
|
208
|
+
hostTimer(id, ms);
|
|
209
|
+
return id;
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function clear(id) { if (timers.delete(id)) hostClear(id); }
|
|
213
|
+
function fire(id) {
|
|
214
|
+
var t = timers.get(id);
|
|
215
|
+
if (!t) return;
|
|
216
|
+
if (t.repeat) hostTimer(id, t.ms); else timers.delete(id);
|
|
217
|
+
R.apply(t.fn, undefined, t.args);
|
|
218
|
+
}
|
|
219
|
+
g.setTimeout = timer(false); g.setInterval = timer(true);
|
|
220
|
+
g.clearTimeout = clear; g.clearInterval = clear;
|
|
221
|
+
g.queueMicrotask = function (fn) { P.resolve().then(fn); };
|
|
222
|
+
if (cfg.ops.length) {
|
|
223
|
+
var fs = {};
|
|
224
|
+
cfg.ops.forEach(function (op) {
|
|
225
|
+
fs[op] = function () {
|
|
226
|
+
var text;
|
|
227
|
+
try { text = J.stringify(Array.prototype.slice.call(arguments)); } catch (e) { return P.reject(new TypeError('fs.' + op + ': the arguments must be plain data')); }
|
|
228
|
+
if (text.length > cfg.maxCall) return P.reject(new RangeError('fs.' + op + ': the arguments are too large'));
|
|
229
|
+
return hostCall(op, text).then(function (r) { return r === '' ? undefined : J.parse(r); });
|
|
230
|
+
};
|
|
231
|
+
});
|
|
232
|
+
g.fs = fs;
|
|
233
|
+
}
|
|
234
|
+
var loaded = new M();
|
|
235
|
+
function requireFrom(base) {
|
|
236
|
+
return function require(spec) {
|
|
237
|
+
var path = hostResolve(base, S(spec)), mod = loaded.get(path), made;
|
|
238
|
+
if (mod) return mod.exports;
|
|
239
|
+
mod = { exports: {} };
|
|
240
|
+
loaded.set(path, mod);
|
|
241
|
+
made = hostCompile(path);
|
|
242
|
+
if (typeof made === 'string') mod.exports = J.parse(made);
|
|
243
|
+
else made.call(mod.exports, mod, mod.exports, requireFrom(path), path, path.slice(0, Math.max(1, path.lastIndexOf('/'))));
|
|
244
|
+
return mod.exports;
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
g.require = requireFrom(cfg.filename);
|
|
248
|
+
return { fire: fire, serialize: serialize, describe: describe };
|
|
249
|
+
})`;
|
|
250
|
+
var BOOTSTRAP_FILE = "<sandbox>";
|
|
251
|
+
var REFUSED = "refused:";
|
|
252
|
+
var WASM_PAGE = 65536;
|
|
253
|
+
var newBoundedModule = (lib, limitBytes) => {
|
|
254
|
+
const wasm = globalThis.WebAssembly;
|
|
255
|
+
const wasmMemory = new wasm.Memory({
|
|
256
|
+
initial: SANDBOX_FLOORS.memoryLimitBytes / WASM_PAGE,
|
|
257
|
+
maximum: Math.floor(limitBytes / WASM_PAGE)
|
|
258
|
+
});
|
|
259
|
+
return lib.newQuickJSWASMModuleFromVariant(lib.newVariant(lib.RELEASE_SYNC, { wasmMemory }));
|
|
260
|
+
};
|
|
261
|
+
var runGuest = async (lib, request, options = {}) => {
|
|
262
|
+
const { limits } = request;
|
|
263
|
+
const filename = request.filename ?? "/main.js";
|
|
264
|
+
const modules = request.modules;
|
|
265
|
+
const hostOps = options.hostCall ? request.hostOps ?? [] : [];
|
|
266
|
+
const mod = await newBoundedModule(lib, limits.memoryLimitBytes);
|
|
267
|
+
const rt = mod.newRuntime();
|
|
268
|
+
rt.setMemoryLimit(limits.memoryLimitBytes);
|
|
269
|
+
rt.setMaxStackSize(GUEST_STACK_BYTES);
|
|
270
|
+
const ctx = rt.newContext();
|
|
271
|
+
return new Promise((resolve) => {
|
|
272
|
+
const startedAt = Date.now();
|
|
273
|
+
let finished = false;
|
|
274
|
+
let interrupted = false;
|
|
275
|
+
let cpuMs = 0;
|
|
276
|
+
let entryAt = 0;
|
|
277
|
+
let waitMs = 0;
|
|
278
|
+
let waitingSince = 0;
|
|
279
|
+
let pendingCalls = 0;
|
|
280
|
+
let hostCalls = 0;
|
|
281
|
+
let watchdog;
|
|
282
|
+
const hostTimers = /* @__PURE__ */ new Map();
|
|
283
|
+
const out = [];
|
|
284
|
+
let outChars = 0;
|
|
285
|
+
let truncated = false;
|
|
286
|
+
let internals;
|
|
287
|
+
let main;
|
|
288
|
+
let mainKind = "value";
|
|
289
|
+
const cpuUsed = () => cpuMs + (entryAt ? Date.now() - entryAt : 0);
|
|
290
|
+
const wallUsed = () => Date.now() - startedAt - waitMs - (waitingSince ? Date.now() - waitingSince : 0);
|
|
291
|
+
const overTime = () => cpuUsed() > limits.timeoutMs || pendingCalls === 0 && wallUsed() > limits.timeoutMs;
|
|
292
|
+
rt.setInterruptHandler(() => {
|
|
293
|
+
if (finished || overTime()) {
|
|
294
|
+
interrupted = true;
|
|
295
|
+
return true;
|
|
296
|
+
}
|
|
297
|
+
return false;
|
|
298
|
+
});
|
|
299
|
+
const finish = (error, result) => {
|
|
300
|
+
if (finished) {
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
finished = true;
|
|
304
|
+
if (watchdog !== void 0) {
|
|
305
|
+
clearTimeout(watchdog);
|
|
306
|
+
}
|
|
307
|
+
for (const t of hostTimers.values()) {
|
|
308
|
+
clearTimeout(t);
|
|
309
|
+
}
|
|
310
|
+
hostTimers.clear();
|
|
311
|
+
resolve({
|
|
312
|
+
ok: !error,
|
|
313
|
+
stdout: out.join(""),
|
|
314
|
+
...result ? { result: result.value } : {},
|
|
315
|
+
...error ? { error } : {},
|
|
316
|
+
truncated,
|
|
317
|
+
durationMs: Date.now() - startedAt
|
|
318
|
+
});
|
|
319
|
+
};
|
|
320
|
+
const timedOut = () => ({
|
|
321
|
+
name: "TimeoutError",
|
|
322
|
+
message: `the run was stopped after ${limits.timeoutMs} ms (timeoutMs)`
|
|
323
|
+
});
|
|
324
|
+
const describe = (handle) => {
|
|
325
|
+
if (interrupted) {
|
|
326
|
+
return timedOut();
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
let raw;
|
|
330
|
+
if (internals) {
|
|
331
|
+
const r = ctx.callFunction(internals.describe, ctx.undefined, handle);
|
|
332
|
+
raw = r.error ? void 0 : JSON.parse(ctx.getString(r.value));
|
|
333
|
+
}
|
|
334
|
+
if (!Array.isArray(raw)) {
|
|
335
|
+
const d = ctx.dump(handle);
|
|
336
|
+
raw = [d?.name ?? "Error", d?.message ?? String(d), d?.stack ?? ""];
|
|
337
|
+
}
|
|
338
|
+
const [name, message, stack] = raw;
|
|
339
|
+
const frames = String(stack ?? "").split("\n").filter((line) => line.trim() && !line.includes(BOOTSTRAP_FILE)).join("\n");
|
|
340
|
+
return {
|
|
341
|
+
name: clip(String(name || "Error"), ERROR_NAME_CHARS),
|
|
342
|
+
message: clip(String(message ?? ""), ERROR_TEXT_CHARS),
|
|
343
|
+
...frames ? { stack: clip(frames, ERROR_TEXT_CHARS) } : {}
|
|
344
|
+
};
|
|
345
|
+
} catch {
|
|
346
|
+
return interrupted ? timedOut() : { name: "Error", message: "the program threw an error that could not be read" };
|
|
347
|
+
}
|
|
348
|
+
};
|
|
349
|
+
const engineFailure = (err) => {
|
|
350
|
+
if (interrupted) {
|
|
351
|
+
finish(timedOut());
|
|
352
|
+
} else if (err instanceof RangeError) {
|
|
353
|
+
finish({ name: "RangeError", message: "Maximum call stack size exceeded" });
|
|
354
|
+
} else {
|
|
355
|
+
finish({ name: "SandboxError", message: clip(errorText(err), ERROR_TEXT_CHARS) });
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
const armWatchdog = () => {
|
|
359
|
+
if (watchdog !== void 0) {
|
|
360
|
+
clearTimeout(watchdog);
|
|
361
|
+
watchdog = void 0;
|
|
362
|
+
}
|
|
363
|
+
if (finished || pendingCalls > 0) {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
watchdog = setTimeout(
|
|
367
|
+
() => {
|
|
368
|
+
watchdog = void 0;
|
|
369
|
+
if (overTime()) {
|
|
370
|
+
interrupted = true;
|
|
371
|
+
finish(timedOut());
|
|
372
|
+
} else {
|
|
373
|
+
armWatchdog();
|
|
374
|
+
}
|
|
375
|
+
},
|
|
376
|
+
Math.max(1, limits.timeoutMs - wallUsed() + 1)
|
|
377
|
+
);
|
|
378
|
+
};
|
|
379
|
+
const settle = () => {
|
|
380
|
+
while (!finished) {
|
|
381
|
+
if (interrupted) {
|
|
382
|
+
finish(timedOut());
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const state = ctx.getPromiseState(main);
|
|
386
|
+
if (state.type === "rejected") {
|
|
387
|
+
finish(describe(state.error));
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
if (state.type === "pending") {
|
|
391
|
+
if (hostTimers.size === 0 && pendingCalls === 0) {
|
|
392
|
+
finish({
|
|
393
|
+
name: "Error",
|
|
394
|
+
message: "the program awaits a promise that can never settle (nothing is left to run)"
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
if (mainKind !== "value") {
|
|
400
|
+
main = ctx.getProp(state.value, mainKind === "script" ? "value" : "default");
|
|
401
|
+
mainKind = "value";
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
if (!state.notAPromise) {
|
|
405
|
+
main = state.value;
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (hostTimers.size > 0 || pendingCalls > 0) {
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
const max = Math.max(200, limits.maxOutputChars - outChars);
|
|
412
|
+
const r = ctx.callFunction(
|
|
413
|
+
internals.serialize,
|
|
414
|
+
ctx.undefined,
|
|
415
|
+
state.value,
|
|
416
|
+
ctx.newNumber(max)
|
|
417
|
+
);
|
|
418
|
+
if (r.error) {
|
|
419
|
+
finish(describe(r.error));
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
const text = ctx.getString(r.value);
|
|
423
|
+
if (text === "") {
|
|
424
|
+
finish();
|
|
425
|
+
} else if (text[0] === "T") {
|
|
426
|
+
truncated = true;
|
|
427
|
+
finish(void 0, { value: clip(text.slice(1), max) });
|
|
428
|
+
} else {
|
|
429
|
+
truncated ||= text[0] === "C";
|
|
430
|
+
finish(void 0, { value: JSON.parse(text.slice(1)) });
|
|
431
|
+
}
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
const enter = (fn) => {
|
|
436
|
+
if (finished) {
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
entryAt = Date.now();
|
|
440
|
+
try {
|
|
441
|
+
fn();
|
|
442
|
+
while (!finished && !interrupted) {
|
|
443
|
+
const jobs = rt.executePendingJobs();
|
|
444
|
+
if (jobs.error) {
|
|
445
|
+
const error = describe(jobs.error);
|
|
446
|
+
cpuMs += Date.now() - entryAt;
|
|
447
|
+
entryAt = 0;
|
|
448
|
+
finish(error);
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (!rt.hasPendingJob()) {
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
cpuMs += Date.now() - entryAt;
|
|
456
|
+
entryAt = 0;
|
|
457
|
+
settle();
|
|
458
|
+
} catch (err) {
|
|
459
|
+
cpuMs += Date.now() - entryAt;
|
|
460
|
+
entryAt = 0;
|
|
461
|
+
engineFailure(err);
|
|
462
|
+
}
|
|
463
|
+
};
|
|
464
|
+
const guestError = (name, message) => Object.assign(new Error(message), { name });
|
|
465
|
+
const host = ctx.newObject();
|
|
466
|
+
const expose = (name, fn) => {
|
|
467
|
+
ctx.setProp(host, name, ctx.newFunction(name, fn));
|
|
468
|
+
};
|
|
469
|
+
expose("log", (levelHandle, textHandle) => {
|
|
470
|
+
if (outChars >= limits.maxOutputChars) {
|
|
471
|
+
truncated = true;
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
const level = ctx.getString(levelHandle);
|
|
475
|
+
let line = `${level ? `[${level}] ` : ""}${ctx.getString(textHandle)}
|
|
476
|
+
`;
|
|
477
|
+
if (outChars + line.length > limits.maxOutputChars) {
|
|
478
|
+
line = line.slice(0, limits.maxOutputChars - outChars);
|
|
479
|
+
truncated = true;
|
|
480
|
+
}
|
|
481
|
+
out.push(line);
|
|
482
|
+
outChars += line.length;
|
|
483
|
+
});
|
|
484
|
+
expose("timer", (idHandle, msHandle) => {
|
|
485
|
+
const id = ctx.getNumber(idHandle);
|
|
486
|
+
const ms = ctx.getNumber(msHandle);
|
|
487
|
+
const previous = hostTimers.get(id);
|
|
488
|
+
if (previous !== void 0) {
|
|
489
|
+
clearTimeout(previous);
|
|
490
|
+
} else if (hostTimers.size >= MAX_TIMERS) {
|
|
491
|
+
throw guestError("RangeError", "too many timers");
|
|
492
|
+
}
|
|
493
|
+
hostTimers.set(
|
|
494
|
+
id,
|
|
495
|
+
setTimeout(
|
|
496
|
+
() => {
|
|
497
|
+
hostTimers.delete(id);
|
|
498
|
+
enter(() => {
|
|
499
|
+
const r = ctx.callFunction(internals.fire, ctx.undefined, ctx.newNumber(id));
|
|
500
|
+
if (r.error) {
|
|
501
|
+
finish(describe(r.error));
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
},
|
|
505
|
+
// A timer past the deadline never fires: the watchdog ends the run first.
|
|
506
|
+
Math.min(Math.max(0, ms), limits.timeoutMs + 1)
|
|
507
|
+
)
|
|
508
|
+
);
|
|
509
|
+
});
|
|
510
|
+
expose("clear", (idHandle) => {
|
|
511
|
+
const id = ctx.getNumber(idHandle);
|
|
512
|
+
const t = hostTimers.get(id);
|
|
513
|
+
if (t !== void 0) {
|
|
514
|
+
clearTimeout(t);
|
|
515
|
+
hostTimers.delete(id);
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
expose("call", (opHandle, argsHandle) => {
|
|
519
|
+
const op = ctx.getString(opHandle);
|
|
520
|
+
if (!hostOps.includes(op) || !options.hostCall) {
|
|
521
|
+
throw guestError("Error", `fs.${clip(op, 40)} is not available in this sandbox`);
|
|
522
|
+
}
|
|
523
|
+
if ((hostCalls += 1) > SANDBOX_MAX_HOST_CALLS) {
|
|
524
|
+
throw guestError(
|
|
525
|
+
"RangeError",
|
|
526
|
+
`too many file operations in one run (limit ${SANDBOX_MAX_HOST_CALLS})`
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
const args = JSON.parse(ctx.getString(argsHandle));
|
|
530
|
+
const deferred = ctx.newPromise();
|
|
531
|
+
if (pendingCalls === 0) {
|
|
532
|
+
waitingSince = Date.now();
|
|
533
|
+
if (watchdog !== void 0) {
|
|
534
|
+
clearTimeout(watchdog);
|
|
535
|
+
watchdog = void 0;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
pendingCalls += 1;
|
|
539
|
+
const done = (settleGuest) => {
|
|
540
|
+
pendingCalls -= 1;
|
|
541
|
+
if (pendingCalls === 0) {
|
|
542
|
+
waitMs += Date.now() - waitingSince;
|
|
543
|
+
waitingSince = 0;
|
|
544
|
+
}
|
|
545
|
+
if (finished) {
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
armWatchdog();
|
|
549
|
+
enter(settleGuest);
|
|
550
|
+
};
|
|
551
|
+
options.hostCall(op, args).then(
|
|
552
|
+
(value) => done(() => {
|
|
553
|
+
const text = value === void 0 ? "" : JSON.stringify(value);
|
|
554
|
+
deferred.resolve(ctx.newString(text ?? ""));
|
|
555
|
+
}),
|
|
556
|
+
(err) => done(() => {
|
|
557
|
+
deferred.reject(
|
|
558
|
+
ctx.newError({
|
|
559
|
+
name: "Error",
|
|
560
|
+
message: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS)
|
|
561
|
+
})
|
|
562
|
+
);
|
|
563
|
+
})
|
|
564
|
+
);
|
|
565
|
+
return deferred.handle;
|
|
566
|
+
});
|
|
567
|
+
const load = (path) => {
|
|
568
|
+
if (!modules) {
|
|
569
|
+
throw guestError("Error", `Cannot load "${clip(path, 200)}": this sandbox has no files`);
|
|
570
|
+
}
|
|
571
|
+
if (!Object.hasOwn(modules, path)) {
|
|
572
|
+
throw guestError(
|
|
573
|
+
"Error",
|
|
574
|
+
`Cannot load "${clip(path, 200)}": no such file in the workspace (a module must exist before the run and be named by a literal path)`
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
return modules[path];
|
|
578
|
+
};
|
|
579
|
+
const resolvePath = (base, spec) => {
|
|
580
|
+
try {
|
|
581
|
+
return resolveModulePath(base, spec);
|
|
582
|
+
} catch (err) {
|
|
583
|
+
throw guestError("Error", err instanceof Error ? err.message : String(err));
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
expose(
|
|
587
|
+
"resolve",
|
|
588
|
+
(baseHandle, specHandle) => ctx.newString(
|
|
589
|
+
resolvePath(ctx.getString(baseHandle), ctx.getString(specHandle))
|
|
590
|
+
)
|
|
591
|
+
);
|
|
592
|
+
expose("compile", (pathHandle) => {
|
|
593
|
+
const path = ctx.getString(pathHandle);
|
|
594
|
+
const source = load(path);
|
|
595
|
+
if (path.toLowerCase().endsWith(".json")) {
|
|
596
|
+
return ctx.newString(source);
|
|
597
|
+
}
|
|
598
|
+
const r = ctx.evalCode(
|
|
599
|
+
`(function (module, exports, require, __filename, __dirname) {${source}
|
|
600
|
+
})`,
|
|
601
|
+
path
|
|
602
|
+
);
|
|
603
|
+
if (r.error) {
|
|
604
|
+
return { error: r.error };
|
|
605
|
+
}
|
|
606
|
+
return r.value;
|
|
607
|
+
});
|
|
608
|
+
rt.setModuleLoader(
|
|
609
|
+
(path) => {
|
|
610
|
+
try {
|
|
611
|
+
if (path.startsWith(REFUSED)) {
|
|
612
|
+
throw new Error(path.slice(REFUSED.length));
|
|
613
|
+
}
|
|
614
|
+
const source = load(path);
|
|
615
|
+
return path.toLowerCase().endsWith(".json") ? `export default JSON.parse(${JSON.stringify(source)})` : source;
|
|
616
|
+
} catch (err) {
|
|
617
|
+
return { error: err };
|
|
618
|
+
}
|
|
619
|
+
},
|
|
620
|
+
(base, spec) => {
|
|
621
|
+
try {
|
|
622
|
+
return resolveModulePath(base, spec);
|
|
623
|
+
} catch (err) {
|
|
624
|
+
return `${REFUSED}${err instanceof Error ? err.message : String(err)}`;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
);
|
|
628
|
+
try {
|
|
629
|
+
const boot = ctx.evalCode(BOOTSTRAP, BOOTSTRAP_FILE);
|
|
630
|
+
if (boot.error) {
|
|
631
|
+
finish({ name: "SandboxError", message: "the sandbox runtime failed to start" });
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
const made = ctx.callFunction(
|
|
635
|
+
boot.value,
|
|
636
|
+
ctx.undefined,
|
|
637
|
+
host,
|
|
638
|
+
ctx.evalCode(
|
|
639
|
+
`(${JSON.stringify({
|
|
640
|
+
max: limits.maxOutputChars,
|
|
641
|
+
nameMax: ERROR_NAME_CHARS,
|
|
642
|
+
textMax: ERROR_TEXT_CHARS,
|
|
643
|
+
maxTimers: MAX_TIMERS,
|
|
644
|
+
maxCall: SANDBOX_MAX_FILE_CHARS + 2e3,
|
|
645
|
+
ops: hostOps,
|
|
646
|
+
filename
|
|
647
|
+
})})`,
|
|
648
|
+
BOOTSTRAP_FILE
|
|
649
|
+
).unwrap()
|
|
650
|
+
);
|
|
651
|
+
if (made.error) {
|
|
652
|
+
finish({ name: "SandboxError", message: "the sandbox runtime failed to start" });
|
|
653
|
+
return;
|
|
654
|
+
}
|
|
655
|
+
internals = {
|
|
656
|
+
fire: ctx.getProp(made.value, "fire"),
|
|
657
|
+
serialize: ctx.getProp(made.value, "serialize"),
|
|
658
|
+
describe: ctx.getProp(made.value, "describe")
|
|
659
|
+
};
|
|
660
|
+
} catch (err) {
|
|
661
|
+
engineFailure(err);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
options.onStart?.();
|
|
665
|
+
armWatchdog();
|
|
666
|
+
enter(() => {
|
|
667
|
+
let evaluated = ctx.evalCode(request.code, filename, EVAL_SCRIPT_ASYNC);
|
|
668
|
+
mainKind = "script";
|
|
669
|
+
if (evaluated.error && !interrupted && looksLikeModule(request.code)) {
|
|
670
|
+
evaluated = ctx.evalCode(request.code, filename, { type: "module" });
|
|
671
|
+
mainKind = "module";
|
|
672
|
+
}
|
|
673
|
+
if (evaluated.error) {
|
|
674
|
+
finish(describe(evaluated.error));
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
main = evaluated.value;
|
|
678
|
+
});
|
|
679
|
+
});
|
|
680
|
+
};
|
|
681
|
+
var jsonSafe = (value, max) => {
|
|
682
|
+
let text;
|
|
683
|
+
try {
|
|
684
|
+
text = JSON.stringify(value);
|
|
685
|
+
} catch {
|
|
686
|
+
return { value: "[unserializable]", cut: true };
|
|
687
|
+
}
|
|
688
|
+
if (text === void 0) {
|
|
689
|
+
return { value: void 0, cut: false };
|
|
690
|
+
}
|
|
691
|
+
if (text.length > max) {
|
|
692
|
+
return { value: text.slice(0, max), cut: true };
|
|
693
|
+
}
|
|
694
|
+
return { value: JSON.parse(text), cut: false };
|
|
695
|
+
};
|
|
696
|
+
var sanitizeSandboxResult = (raw, limits) => {
|
|
697
|
+
const r = raw && typeof raw === "object" ? raw : {};
|
|
698
|
+
let truncated = r.truncated === true;
|
|
699
|
+
let stdout = typeof r.stdout === "string" ? r.stdout : "";
|
|
700
|
+
if (stdout.length > limits.maxOutputChars) {
|
|
701
|
+
stdout = stdout.slice(0, limits.maxOutputChars);
|
|
702
|
+
truncated = true;
|
|
703
|
+
}
|
|
704
|
+
const result = { ok: r.ok === true, stdout, truncated, durationMs: 0 };
|
|
705
|
+
if (Object.hasOwn(r, "result") && r.result !== void 0) {
|
|
706
|
+
const safe = jsonSafe(r.result, Math.max(200, limits.maxOutputChars - stdout.length));
|
|
707
|
+
if (safe.value !== void 0) {
|
|
708
|
+
result.result = safe.value;
|
|
709
|
+
}
|
|
710
|
+
truncated ||= safe.cut;
|
|
711
|
+
}
|
|
712
|
+
if (r.error && typeof r.error === "object") {
|
|
713
|
+
const e = r.error;
|
|
714
|
+
result.error = {
|
|
715
|
+
name: clip(typeof e.name === "string" ? e.name : "Error", ERROR_NAME_CHARS),
|
|
716
|
+
message: clip(typeof e.message === "string" ? e.message : "", ERROR_TEXT_CHARS),
|
|
717
|
+
...typeof e.stack === "string" && e.stack ? { stack: clip(e.stack, ERROR_TEXT_CHARS) } : {}
|
|
718
|
+
};
|
|
719
|
+
result.ok = false;
|
|
720
|
+
} else if (!result.ok) {
|
|
721
|
+
result.error = { name: "Error", message: "the run failed" };
|
|
722
|
+
}
|
|
723
|
+
result.truncated = truncated;
|
|
724
|
+
result.durationMs = typeof r.durationMs === "number" && Number.isFinite(r.durationMs) && r.durationMs >= 0 ? Math.round(r.durationMs) : 0;
|
|
725
|
+
return result;
|
|
726
|
+
};
|
|
727
|
+
var serveSandbox = (port, loadLib) => {
|
|
728
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
729
|
+
let seq = 0;
|
|
730
|
+
let busy = false;
|
|
731
|
+
const run = async (request) => {
|
|
732
|
+
let lib;
|
|
733
|
+
try {
|
|
734
|
+
lib = await loadLib();
|
|
735
|
+
} catch (err) {
|
|
736
|
+
port.post({ type: "failed", code: "peer-missing", message: errorText(err) });
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
try {
|
|
740
|
+
const result = await runGuest(lib, request, {
|
|
741
|
+
onStart: () => port.post({ type: "started" }),
|
|
742
|
+
hostCall: (op, args) => new Promise((resolve, reject) => {
|
|
743
|
+
const id = seq += 1;
|
|
744
|
+
waiting.set(id, { resolve, reject });
|
|
745
|
+
port.post({ type: "host-call", id, op, args });
|
|
746
|
+
})
|
|
747
|
+
});
|
|
748
|
+
port.post({ type: "done", result });
|
|
749
|
+
} catch (err) {
|
|
750
|
+
port.post({ type: "failed", code: "engine", message: errorText(err) });
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
port.listen((message) => {
|
|
754
|
+
const m = message;
|
|
755
|
+
if (m?.type === "run" && !busy) {
|
|
756
|
+
busy = true;
|
|
757
|
+
void run(m.request);
|
|
758
|
+
} else if (m?.type === "host-result") {
|
|
759
|
+
const w = waiting.get(m.id);
|
|
760
|
+
if (w) {
|
|
761
|
+
waiting.delete(m.id);
|
|
762
|
+
if (m.ok) {
|
|
763
|
+
w.resolve(m.value);
|
|
764
|
+
} else {
|
|
765
|
+
w.reject(new Error(typeof m.error === "string" ? m.error : "the file operation failed"));
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
});
|
|
770
|
+
};
|
|
771
|
+
var runInWorker = (port, request, options = {}) => new Promise((resolve, reject) => {
|
|
772
|
+
const { limits } = request;
|
|
773
|
+
const startedAt = Date.now();
|
|
774
|
+
const graceMs = options.graceMs ?? 1e3;
|
|
775
|
+
let over = false;
|
|
776
|
+
let serving = 0;
|
|
777
|
+
let timer;
|
|
778
|
+
const stop = () => {
|
|
779
|
+
over = true;
|
|
780
|
+
if (timer !== void 0) {
|
|
781
|
+
clearTimeout(timer);
|
|
782
|
+
}
|
|
783
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
784
|
+
try {
|
|
785
|
+
port.terminate?.();
|
|
786
|
+
} catch {
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
const end = (result) => {
|
|
790
|
+
if (over) {
|
|
791
|
+
return;
|
|
792
|
+
}
|
|
793
|
+
stop();
|
|
794
|
+
resolve({ ...result, durationMs: Date.now() - startedAt });
|
|
795
|
+
};
|
|
796
|
+
const fail = (err) => {
|
|
797
|
+
if (over) {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
stop();
|
|
801
|
+
reject(err);
|
|
802
|
+
};
|
|
803
|
+
const failed = (name, message) => ({
|
|
804
|
+
ok: false,
|
|
805
|
+
stdout: "",
|
|
806
|
+
error: { name, message },
|
|
807
|
+
truncated: false,
|
|
808
|
+
durationMs: 0
|
|
809
|
+
});
|
|
810
|
+
function onAbort() {
|
|
811
|
+
fail(Object.assign(new Error("The run was aborted"), { name: "AbortError" }));
|
|
812
|
+
}
|
|
813
|
+
const arm = (ms, onFire) => {
|
|
814
|
+
if (timer !== void 0) {
|
|
815
|
+
clearTimeout(timer);
|
|
816
|
+
}
|
|
817
|
+
timer = setTimeout(onFire, ms);
|
|
818
|
+
};
|
|
819
|
+
const armKill = () => arm(
|
|
820
|
+
limits.timeoutMs + graceMs,
|
|
821
|
+
() => end(
|
|
822
|
+
failed(
|
|
823
|
+
"TimeoutError",
|
|
824
|
+
`the run was killed after ${limits.timeoutMs} ms (timeoutMs): it did not stop by itself`
|
|
825
|
+
)
|
|
826
|
+
)
|
|
827
|
+
);
|
|
828
|
+
if (options.signal?.aborted) {
|
|
829
|
+
onAbort();
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
833
|
+
arm(
|
|
834
|
+
options.startupMs ?? 2e4,
|
|
835
|
+
() => fail(new SandboxUnavailableError("the sandbox worker did not start in time"))
|
|
836
|
+
);
|
|
837
|
+
port.listen(
|
|
838
|
+
(message) => {
|
|
839
|
+
if (over) {
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
const m = message;
|
|
843
|
+
switch (m?.type) {
|
|
844
|
+
case "started":
|
|
845
|
+
armKill();
|
|
846
|
+
break;
|
|
847
|
+
case "host-call": {
|
|
848
|
+
const id = m.id;
|
|
849
|
+
serving += 1;
|
|
850
|
+
if (timer !== void 0) {
|
|
851
|
+
clearTimeout(timer);
|
|
852
|
+
timer = void 0;
|
|
853
|
+
}
|
|
854
|
+
const answer = (reply) => {
|
|
855
|
+
serving -= 1;
|
|
856
|
+
if (over) {
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
if (serving === 0) {
|
|
860
|
+
armKill();
|
|
861
|
+
}
|
|
862
|
+
port.post(reply);
|
|
863
|
+
};
|
|
864
|
+
const call = options.hostCall ? options.hostCall(String(m.op), Array.isArray(m.args) ? m.args : []) : Promise.reject(new Error("this sandbox has no files"));
|
|
865
|
+
call.then(
|
|
866
|
+
(value) => answer({ type: "host-result", id, ok: true, value }),
|
|
867
|
+
(err) => answer({
|
|
868
|
+
type: "host-result",
|
|
869
|
+
id,
|
|
870
|
+
ok: false,
|
|
871
|
+
error: clip(err instanceof Error ? err.message : String(err), ERROR_TEXT_CHARS)
|
|
872
|
+
})
|
|
873
|
+
);
|
|
874
|
+
break;
|
|
875
|
+
}
|
|
876
|
+
case "done":
|
|
877
|
+
end(sanitizeSandboxResult(m.result, limits));
|
|
878
|
+
break;
|
|
879
|
+
case "failed":
|
|
880
|
+
fail(
|
|
881
|
+
m.code === "peer-missing" ? sandboxPeerMissing(clip(String(m.message), 300)) : new SandboxUnavailableError(
|
|
882
|
+
`the sandbox engine failed: ${clip(String(m.message), 300)}`
|
|
883
|
+
)
|
|
884
|
+
);
|
|
885
|
+
break;
|
|
886
|
+
}
|
|
887
|
+
},
|
|
888
|
+
(reason) => end(failed("SandboxError", `the sandbox stopped unexpectedly: ${clip(reason, 300)}`))
|
|
889
|
+
);
|
|
890
|
+
port.post({ type: "run", request });
|
|
891
|
+
});
|
|
892
|
+
var createSandboxQueue = (size) => {
|
|
893
|
+
let active = 0;
|
|
894
|
+
const waiting = [];
|
|
895
|
+
return async (task) => {
|
|
896
|
+
if (active >= size) {
|
|
897
|
+
await new Promise((go) => waiting.push(go));
|
|
898
|
+
}
|
|
899
|
+
active += 1;
|
|
900
|
+
try {
|
|
901
|
+
return await task();
|
|
902
|
+
} finally {
|
|
903
|
+
active -= 1;
|
|
904
|
+
waiting.shift()?.();
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
};
|
|
908
|
+
|
|
909
|
+
export {
|
|
910
|
+
RUN_JS_TOOL,
|
|
911
|
+
SANDBOX_PACKAGE,
|
|
912
|
+
SANDBOX_MAX_MODULES,
|
|
913
|
+
SANDBOX_MAX_MODULE_CHARS_TOTAL,
|
|
914
|
+
SANDBOX_MAX_FILE_CHARS,
|
|
915
|
+
SANDBOX_MODULE_EXTENSIONS,
|
|
916
|
+
resolveSandboxLimits,
|
|
917
|
+
sandboxPeerMissing,
|
|
918
|
+
sandboxPromptNote,
|
|
919
|
+
SANDBOX_PLANNER_NOTE,
|
|
920
|
+
SANDBOX_SYNTHESIZER_NOTE,
|
|
921
|
+
resolveModulePath,
|
|
922
|
+
moduleSpecifiersOf,
|
|
923
|
+
runGuest,
|
|
924
|
+
sanitizeSandboxResult,
|
|
925
|
+
serveSandbox,
|
|
926
|
+
runInWorker,
|
|
927
|
+
createSandboxQueue
|
|
928
|
+
};
|
|
929
|
+
//# sourceMappingURL=chunk-V3JOK7EW.js.map
|