@mcploom/codexec-quickjs 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mouaad Aallam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,33 @@
1
+ # @mcploom/codexec-quickjs
2
+
3
+ QuickJS executor package for `@mcploom/codexec`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @mcploom/codexec @mcploom/codexec-quickjs
9
+ ```
10
+
11
+ Use this package when you want the smallest, easiest-to-install executor backend for codexec.
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { resolveProvider } from "@mcploom/codexec";
17
+ import { QuickJsExecutor } from "@mcploom/codexec-quickjs";
18
+
19
+ const provider = resolveProvider({
20
+ tools: {
21
+ echo: {
22
+ execute: async (input) => input,
23
+ },
24
+ },
25
+ });
26
+
27
+ const executor = new QuickJsExecutor();
28
+ const result = await executor.execute("await codemode.echo({ ok: true })", [
29
+ provider,
30
+ ]);
31
+ ```
32
+
33
+ Each execution runs in a fresh QuickJS runtime with captured `console.*` output, timeout handling, and JSON-only tool/result boundaries.
package/dist/index.cjs ADDED
@@ -0,0 +1,314 @@
1
+ let quickjs_emscripten = require("quickjs-emscripten");
2
+ let __mcploom_codexec = require("@mcploom/codexec");
3
+
4
+ //#region src/quickjsBridge.ts
5
+ function formatLogValue(value) {
6
+ if (typeof value === "string") return value;
7
+ if (value === void 0) return "undefined";
8
+ try {
9
+ return JSON.stringify(value);
10
+ } catch {
11
+ return String(value);
12
+ }
13
+ }
14
+ function formatConsoleLine(values) {
15
+ return values.map((value) => formatLogValue(value)).join(" ");
16
+ }
17
+ function createGuestErrorHandle(context, code, message) {
18
+ const errorHandle = context.newError({
19
+ message,
20
+ name: "Error"
21
+ });
22
+ const codeHandle = context.newString(code);
23
+ context.setProp(errorHandle, "code", codeHandle);
24
+ codeHandle.dispose();
25
+ return errorHandle;
26
+ }
27
+ function fromGuestHandle(context, handle) {
28
+ const guestType = context.typeof(handle);
29
+ if (guestType === "undefined") return;
30
+ if (guestType === "function" || guestType === "symbol" || guestType === "bigint") throw new __mcploom_codexec.ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
31
+ const jsonHandle = context.getProp(context.global, "JSON");
32
+ const stringifyHandle = context.getProp(jsonHandle, "stringify");
33
+ try {
34
+ const stringified = context.unwrapResult(context.callFunction(stringifyHandle, jsonHandle, handle));
35
+ if (context.typeof(stringified) === "undefined") throw new __mcploom_codexec.ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
36
+ const jsonValue = context.getString(stringified);
37
+ return JSON.parse(jsonValue);
38
+ } catch (error) {
39
+ if (error instanceof __mcploom_codexec.ExecuteFailure) throw error;
40
+ throw new __mcploom_codexec.ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
41
+ } finally {
42
+ stringifyHandle.dispose();
43
+ jsonHandle.dispose();
44
+ }
45
+ }
46
+ function toGuestHandle(context, value) {
47
+ if (value === void 0) return context.undefined;
48
+ const jsonValue = JSON.stringify(value);
49
+ if (jsonValue === void 0) throw new __mcploom_codexec.ExecuteFailure("serialization_error", "Host value is not JSON-serializable");
50
+ return context.unwrapResult(context.evalCode(`(${jsonValue})`, "host-value.json"));
51
+ }
52
+
53
+ //#endregion
54
+ //#region src/quickjsExecutor.ts
55
+ const DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
56
+ const DEFAULT_TIMEOUT_MS = 5e3;
57
+ const DEFAULT_MAX_LOG_LINES = 100;
58
+ const DEFAULT_MAX_LOG_CHARS = 64e3;
59
+ const loadDefaultModule = (0, quickjs_emscripten.memoizePromiseFactory)(() => (0, quickjs_emscripten.newQuickJSWASMModule)(quickjs_emscripten.RELEASE_SYNC));
60
+ function isKnownErrorCode(value) {
61
+ return value === "timeout" || value === "memory_limit" || value === "validation_error" || value === "tool_error" || value === "runtime_error" || value === "serialization_error" || value === "internal_error";
62
+ }
63
+ function normalizeThrownMessage(error) {
64
+ if (error instanceof Error) return error.message;
65
+ return String(error);
66
+ }
67
+ function toExecuteError(error, deadline) {
68
+ if ((0, __mcploom_codexec.isExecuteFailure)(error)) return {
69
+ code: error.code,
70
+ message: error.message
71
+ };
72
+ const message = normalizeThrownMessage(error);
73
+ if (Date.now() > deadline || message.includes("interrupted")) return {
74
+ code: "timeout",
75
+ message: "Execution timed out"
76
+ };
77
+ if (message.toLowerCase().includes("out of memory")) return {
78
+ code: "memory_limit",
79
+ message
80
+ };
81
+ return {
82
+ code: "runtime_error",
83
+ message
84
+ };
85
+ }
86
+ function errorFromGuestHandle(context, handle, deadline) {
87
+ const codeHandle = context.getProp(handle, "code");
88
+ const messageHandle = context.getProp(handle, "message");
89
+ try {
90
+ const code = context.typeof(codeHandle) === "string" ? context.getString(codeHandle) : void 0;
91
+ const message = context.typeof(messageHandle) === "string" ? context.getString(messageHandle) : normalizeThrownMessage(context.dump(handle));
92
+ if (isKnownErrorCode(code)) return {
93
+ code,
94
+ message
95
+ };
96
+ return toExecuteError(message, deadline);
97
+ } finally {
98
+ codeHandle.dispose();
99
+ messageHandle.dispose();
100
+ }
101
+ }
102
+ function truncateLogs(logs, maxLogLines, maxLogChars) {
103
+ const limitedLines = logs.slice(0, maxLogLines);
104
+ let remainingChars = maxLogChars;
105
+ const truncated = [];
106
+ for (const line of limitedLines) {
107
+ if (remainingChars <= 0) break;
108
+ if (line.length <= remainingChars) {
109
+ truncated.push(line);
110
+ remainingChars -= line.length;
111
+ continue;
112
+ }
113
+ truncated.push(line.slice(0, remainingChars));
114
+ break;
115
+ }
116
+ return truncated;
117
+ }
118
+ function createExecutionContext(signal, providerName, safeToolName, originalToolName) {
119
+ return {
120
+ originalToolName,
121
+ providerName,
122
+ safeToolName,
123
+ signal
124
+ };
125
+ }
126
+ async function waitForPromiseSettlement(runtime, promise, deadline) {
127
+ let settled = false;
128
+ let rejection;
129
+ promise.then(() => {
130
+ settled = true;
131
+ }, (error) => {
132
+ settled = true;
133
+ rejection = error;
134
+ });
135
+ while (!settled) {
136
+ if (Date.now() > deadline) throw new __mcploom_codexec.ExecuteFailure("timeout", "Execution timed out");
137
+ const pendingJobsResult = runtime.executePendingJobs(-1);
138
+ if ((0, quickjs_emscripten.isFail)(pendingJobsResult)) {
139
+ const pendingError = pendingJobsResult.error;
140
+ try {
141
+ const executeError = errorFromGuestHandle(pendingError.context, pendingError, deadline);
142
+ throw new __mcploom_codexec.ExecuteFailure(executeError.code, executeError.message);
143
+ } finally {
144
+ pendingError.dispose();
145
+ }
146
+ }
147
+ await new Promise((resolve) => setTimeout(resolve, 0));
148
+ }
149
+ if (rejection !== void 0) throw rejection;
150
+ }
151
+ function injectConsole(context, logs) {
152
+ const consoleHandle = context.newObject();
153
+ try {
154
+ for (const methodName of [
155
+ "log",
156
+ "info",
157
+ "warn",
158
+ "error"
159
+ ]) {
160
+ const methodHandle = context.newFunction(methodName, (...args) => {
161
+ logs.push(formatConsoleLine(args.map((arg) => context.dump(arg))));
162
+ return context.undefined;
163
+ });
164
+ context.setProp(consoleHandle, methodName, methodHandle);
165
+ methodHandle.dispose();
166
+ }
167
+ context.setProp(context.global, "console", consoleHandle);
168
+ } finally {
169
+ consoleHandle.dispose();
170
+ }
171
+ }
172
+ function injectProviders(context, providers, signal) {
173
+ for (const provider of providers) {
174
+ const providerHandle = context.newObject();
175
+ try {
176
+ for (const [safeToolName, descriptor] of Object.entries(provider.tools)) {
177
+ const toolHandle = createToolHandle(context, provider, descriptor, safeToolName, signal);
178
+ context.setProp(providerHandle, safeToolName, toolHandle);
179
+ toolHandle.dispose();
180
+ }
181
+ context.setProp(context.global, provider.name, providerHandle);
182
+ } finally {
183
+ providerHandle.dispose();
184
+ }
185
+ }
186
+ }
187
+ function createToolHandle(context, provider, descriptor, safeToolName, signal) {
188
+ return context.newFunction(safeToolName, (...args) => {
189
+ const deferred = context.newPromise();
190
+ const input = args[0] === void 0 ? void 0 : context.dump(args[0]);
191
+ const executionContext = createExecutionContext(signal, provider.name, safeToolName, descriptor.originalName);
192
+ Promise.resolve().then(async () => descriptor.execute(input, executionContext)).then((result) => {
193
+ if (!context.alive || !deferred.alive) return;
194
+ let resultHandle;
195
+ try {
196
+ resultHandle = toGuestHandle(context, result);
197
+ deferred.resolve(resultHandle);
198
+ } catch (error) {
199
+ const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);
200
+ const errorHandle = createGuestErrorHandle(context, executeError.code, executeError.message);
201
+ deferred.reject(errorHandle);
202
+ errorHandle.dispose();
203
+ } finally {
204
+ resultHandle?.dispose();
205
+ deferred.dispose();
206
+ }
207
+ }).catch((error) => {
208
+ if (!context.alive || !deferred.alive) return;
209
+ const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);
210
+ const errorHandle = createGuestErrorHandle(context, executeError.code, executeError.message);
211
+ deferred.reject(errorHandle);
212
+ errorHandle.dispose();
213
+ deferred.dispose();
214
+ });
215
+ return deferred.handle;
216
+ });
217
+ }
218
+ /**
219
+ * QuickJS-backed executor for one-shot sandboxed JavaScript runs.
220
+ */
221
+ var QuickJsExecutor = class {
222
+ loadModule;
223
+ maxLogChars;
224
+ maxLogLines;
225
+ memoryLimitBytes;
226
+ timeoutMs;
227
+ constructor(options = {}) {
228
+ this.loadModule = async () => {
229
+ return options.loadModule ? await options.loadModule() : await loadDefaultModule();
230
+ };
231
+ this.maxLogChars = options.maxLogChars ?? DEFAULT_MAX_LOG_CHARS;
232
+ this.maxLogLines = options.maxLogLines ?? DEFAULT_MAX_LOG_LINES;
233
+ this.memoryLimitBytes = options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES;
234
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
235
+ }
236
+ /**
237
+ * Executes JavaScript against the provided tool namespaces in a fresh QuickJS runtime.
238
+ */
239
+ async execute(code, providers) {
240
+ const startedAt = Date.now();
241
+ const deadline = startedAt + this.timeoutMs;
242
+ const logs = [];
243
+ const abortController = new AbortController();
244
+ const runtime = (await this.loadModule()).newRuntime();
245
+ runtime.setMemoryLimit(this.memoryLimitBytes);
246
+ runtime.setInterruptHandler((0, quickjs_emscripten.shouldInterruptAfterDeadline)(deadline));
247
+ const context = runtime.newContext();
248
+ try {
249
+ injectConsole(context, logs);
250
+ injectProviders(context, providers, abortController.signal);
251
+ const executableSource = (0, __mcploom_codexec.normalizeCode)(code);
252
+ const functionHandle = context.unwrapResult(context.evalCode(`(${executableSource})`, "sandbox-user-code.js"));
253
+ try {
254
+ const promiseHandle = context.unwrapResult(context.callFunction(functionHandle, context.undefined));
255
+ try {
256
+ const promiseResult = context.resolvePromise(promiseHandle);
257
+ await waitForPromiseSettlement(runtime, promiseResult, deadline);
258
+ const settledResult = await promiseResult;
259
+ if ((0, quickjs_emscripten.isFail)(settledResult)) {
260
+ const errorHandle = settledResult.error;
261
+ try {
262
+ return {
263
+ durationMs: Date.now() - startedAt,
264
+ error: errorFromGuestHandle(context, errorHandle, deadline),
265
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
266
+ ok: false
267
+ };
268
+ } finally {
269
+ errorHandle.dispose();
270
+ }
271
+ }
272
+ try {
273
+ const value = fromGuestHandle(context, settledResult.value);
274
+ return {
275
+ durationMs: Date.now() - startedAt,
276
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
277
+ ok: true,
278
+ result: value
279
+ };
280
+ } catch (error) {
281
+ return {
282
+ durationMs: Date.now() - startedAt,
283
+ error: toExecuteError(error, deadline),
284
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
285
+ ok: false
286
+ };
287
+ } finally {
288
+ settledResult.value.dispose();
289
+ }
290
+ } finally {
291
+ promiseHandle.dispose();
292
+ }
293
+ } finally {
294
+ functionHandle.dispose();
295
+ }
296
+ } catch (error) {
297
+ abortController.abort();
298
+ return {
299
+ durationMs: Date.now() - startedAt,
300
+ error: toExecuteError(error, deadline),
301
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
302
+ ok: false
303
+ };
304
+ } finally {
305
+ abortController.abort();
306
+ context.dispose();
307
+ runtime.dispose();
308
+ }
309
+ }
310
+ };
311
+
312
+ //#endregion
313
+ exports.QuickJsExecutor = QuickJsExecutor;
314
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["ExecuteFailure","RELEASE_SYNC","truncated: string[]","rejection: unknown","ExecuteFailure","resultHandle: QuickJSHandle | undefined","logs: string[]"],"sources":["../src/quickjsBridge.ts","../src/quickjsExecutor.ts"],"sourcesContent":["import type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\n\nimport { ExecuteFailure, type ExecuteErrorCode } from \"@mcploom/codexec\";\n\nfunction formatLogValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value === undefined) {\n return \"undefined\";\n }\n\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function formatConsoleLine(values: unknown[]): string {\n return values.map((value) => formatLogValue(value)).join(\" \");\n}\n\nexport function createGuestErrorHandle(\n context: QuickJSContext,\n code: ExecuteErrorCode,\n message: string,\n): QuickJSHandle {\n const errorHandle = context.newError({ message, name: \"Error\" });\n const codeHandle = context.newString(code);\n context.setProp(errorHandle, \"code\", codeHandle);\n codeHandle.dispose();\n return errorHandle;\n}\n\nexport function fromGuestHandle(\n context: QuickJSContext,\n handle: QuickJSHandle,\n): unknown {\n const guestType = context.typeof(handle);\n\n if (guestType === \"undefined\") {\n return undefined;\n }\n\n if (\n guestType === \"function\" ||\n guestType === \"symbol\" ||\n guestType === \"bigint\"\n ) {\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Guest code returned a non-serializable value\",\n );\n }\n\n const jsonHandle = context.getProp(context.global, \"JSON\");\n const stringifyHandle = context.getProp(jsonHandle, \"stringify\");\n\n try {\n const stringified = context.unwrapResult(\n context.callFunction(stringifyHandle, jsonHandle, handle),\n );\n const stringifiedType = context.typeof(stringified);\n\n if (stringifiedType === \"undefined\") {\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Guest code returned a non-serializable value\",\n );\n }\n\n const jsonValue = context.getString(stringified);\n return JSON.parse(jsonValue);\n } catch (error) {\n if (error instanceof ExecuteFailure) {\n throw error;\n }\n\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Guest code returned a non-serializable value\",\n );\n } finally {\n stringifyHandle.dispose();\n jsonHandle.dispose();\n }\n}\n\nexport function toGuestHandle(\n context: QuickJSContext,\n value: unknown,\n): QuickJSHandle {\n if (value === undefined) {\n return context.undefined;\n }\n\n const jsonValue = JSON.stringify(value);\n\n if (jsonValue === undefined) {\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Host value is not JSON-serializable\",\n );\n }\n\n return context.unwrapResult(\n context.evalCode(`(${jsonValue})`, \"host-value.json\"),\n );\n}\n","import {\n RELEASE_SYNC,\n isFail,\n memoizePromiseFactory,\n newQuickJSWASMModule,\n shouldInterruptAfterDeadline,\n type QuickJSContext,\n type QuickJSHandle,\n type QuickJSRuntime,\n type QuickJSWASMModule,\n} from \"quickjs-emscripten\";\n\nimport {\n ExecuteFailure,\n isExecuteFailure,\n normalizeCode,\n} from \"@mcploom/codexec\";\nimport type {\n ExecuteError,\n ExecuteResult,\n ResolvedToolDescriptor,\n ResolvedToolProvider,\n ToolExecutionContext,\n Executor,\n} from \"@mcploom/codexec\";\nimport {\n createGuestErrorHandle,\n formatConsoleLine,\n fromGuestHandle,\n toGuestHandle,\n} from \"./quickjsBridge\";\nimport type { QuickJsExecutorOptions } from \"./types\";\n\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst DEFAULT_MAX_LOG_LINES = 100;\nconst DEFAULT_MAX_LOG_CHARS = 64_000;\n\nconst loadDefaultModule = memoizePromiseFactory(() =>\n newQuickJSWASMModule(RELEASE_SYNC),\n);\n\nfunction isKnownErrorCode(value: unknown): value is ExecuteError[\"code\"] {\n return (\n value === \"timeout\" ||\n value === \"memory_limit\" ||\n value === \"validation_error\" ||\n value === \"tool_error\" ||\n value === \"runtime_error\" ||\n value === \"serialization_error\" ||\n value === \"internal_error\"\n );\n}\n\nfunction normalizeThrownMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n return String(error);\n}\n\nfunction toExecuteError(error: unknown, deadline: number): ExecuteError {\n if (isExecuteFailure(error)) {\n return {\n code: error.code,\n message: error.message,\n };\n }\n\n const message = normalizeThrownMessage(error);\n\n if (Date.now() > deadline || message.includes(\"interrupted\")) {\n return {\n code: \"timeout\",\n message: \"Execution timed out\",\n };\n }\n\n if (message.toLowerCase().includes(\"out of memory\")) {\n return {\n code: \"memory_limit\",\n message,\n };\n }\n\n return {\n code: \"runtime_error\",\n message,\n };\n}\n\nfunction errorFromGuestHandle(\n context: QuickJSContext,\n handle: QuickJSHandle,\n deadline: number,\n): ExecuteError {\n const codeHandle = context.getProp(handle, \"code\");\n const messageHandle = context.getProp(handle, \"message\");\n\n try {\n const code =\n context.typeof(codeHandle) === \"string\"\n ? context.getString(codeHandle)\n : undefined;\n const message =\n context.typeof(messageHandle) === \"string\"\n ? context.getString(messageHandle)\n : normalizeThrownMessage(context.dump(handle));\n\n if (isKnownErrorCode(code)) {\n return {\n code,\n message,\n };\n }\n\n return toExecuteError(message, deadline);\n } finally {\n codeHandle.dispose();\n messageHandle.dispose();\n }\n}\n\nfunction truncateLogs(\n logs: string[],\n maxLogLines: number,\n maxLogChars: number,\n): string[] {\n const limitedLines = logs.slice(0, maxLogLines);\n let remainingChars = maxLogChars;\n const truncated: string[] = [];\n\n for (const line of limitedLines) {\n if (remainingChars <= 0) {\n break;\n }\n\n if (line.length <= remainingChars) {\n truncated.push(line);\n remainingChars -= line.length;\n continue;\n }\n\n truncated.push(line.slice(0, remainingChars));\n break;\n }\n\n return truncated;\n}\n\nfunction createExecutionContext(\n signal: AbortSignal,\n providerName: string,\n safeToolName: string,\n originalToolName: string,\n): ToolExecutionContext {\n return {\n originalToolName,\n providerName,\n safeToolName,\n signal,\n };\n}\n\nasync function waitForPromiseSettlement(\n runtime: QuickJSRuntime,\n promise: Promise<unknown>,\n deadline: number,\n): Promise<void> {\n let settled = false;\n let rejection: unknown;\n\n promise.then(\n () => {\n settled = true;\n },\n (error) => {\n settled = true;\n rejection = error;\n },\n );\n\n while (!settled) {\n if (Date.now() > deadline) {\n throw new ExecuteFailure(\"timeout\", \"Execution timed out\");\n }\n\n const pendingJobsResult = runtime.executePendingJobs(-1);\n if (isFail(pendingJobsResult)) {\n const pendingError = pendingJobsResult.error;\n\n try {\n const executeError = errorFromGuestHandle(\n pendingError.context,\n pendingError,\n deadline,\n );\n throw new ExecuteFailure(executeError.code, executeError.message);\n } finally {\n pendingError.dispose();\n }\n }\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n if (rejection !== undefined) {\n throw rejection;\n }\n}\n\nfunction injectConsole(context: QuickJSContext, logs: string[]): void {\n const consoleHandle = context.newObject();\n\n try {\n for (const methodName of [\"log\", \"info\", \"warn\", \"error\"]) {\n const methodHandle = context.newFunction(methodName, (...args) => {\n logs.push(formatConsoleLine(args.map((arg) => context.dump(arg))));\n return context.undefined;\n });\n\n context.setProp(consoleHandle, methodName, methodHandle);\n methodHandle.dispose();\n }\n\n context.setProp(context.global, \"console\", consoleHandle);\n } finally {\n consoleHandle.dispose();\n }\n}\n\nfunction injectProviders(\n context: QuickJSContext,\n providers: ResolvedToolProvider[],\n signal: AbortSignal,\n): void {\n for (const provider of providers) {\n const providerHandle = context.newObject();\n\n try {\n for (const [safeToolName, descriptor] of Object.entries(provider.tools)) {\n const toolHandle = createToolHandle(\n context,\n provider,\n descriptor,\n safeToolName,\n signal,\n );\n context.setProp(providerHandle, safeToolName, toolHandle);\n toolHandle.dispose();\n }\n\n context.setProp(context.global, provider.name, providerHandle);\n } finally {\n providerHandle.dispose();\n }\n }\n}\n\nfunction createToolHandle(\n context: QuickJSContext,\n provider: ResolvedToolProvider,\n descriptor: ResolvedToolDescriptor,\n safeToolName: string,\n signal: AbortSignal,\n): QuickJSHandle {\n return context.newFunction(safeToolName, (...args) => {\n const deferred = context.newPromise();\n const input = args[0] === undefined ? undefined : context.dump(args[0]);\n const executionContext = createExecutionContext(\n signal,\n provider.name,\n safeToolName,\n descriptor.originalName,\n );\n\n void Promise.resolve()\n .then(async () => descriptor.execute(input, executionContext))\n .then((result) => {\n if (!context.alive || !deferred.alive) {\n return;\n }\n\n let resultHandle: QuickJSHandle | undefined;\n\n try {\n resultHandle = toGuestHandle(context, result);\n deferred.resolve(resultHandle);\n } catch (error) {\n const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);\n const errorHandle = createGuestErrorHandle(\n context,\n executeError.code,\n executeError.message,\n );\n deferred.reject(errorHandle);\n errorHandle.dispose();\n } finally {\n resultHandle?.dispose();\n deferred.dispose();\n }\n })\n .catch((error) => {\n if (!context.alive || !deferred.alive) {\n return;\n }\n\n const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);\n const errorHandle = createGuestErrorHandle(\n context,\n executeError.code,\n executeError.message,\n );\n deferred.reject(errorHandle);\n errorHandle.dispose();\n deferred.dispose();\n });\n\n return deferred.handle;\n });\n}\n\n/**\n * QuickJS-backed executor for one-shot sandboxed JavaScript runs.\n */\nexport class QuickJsExecutor implements Executor {\n private readonly loadModule: () => Promise<QuickJSWASMModule>;\n private readonly maxLogChars: number;\n private readonly maxLogLines: number;\n private readonly memoryLimitBytes: number;\n private readonly timeoutMs: number;\n\n constructor(options: QuickJsExecutorOptions = {}) {\n this.loadModule = async () => {\n const loaded = options.loadModule\n ? await options.loadModule()\n : await loadDefaultModule();\n return loaded as QuickJSWASMModule;\n };\n this.maxLogChars = options.maxLogChars ?? DEFAULT_MAX_LOG_CHARS;\n this.maxLogLines = options.maxLogLines ?? DEFAULT_MAX_LOG_LINES;\n this.memoryLimitBytes =\n options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n }\n\n /**\n * Executes JavaScript against the provided tool namespaces in a fresh QuickJS runtime.\n */\n async execute(\n code: string,\n providers: ResolvedToolProvider[],\n ): Promise<ExecuteResult> {\n const startedAt = Date.now();\n const deadline = startedAt + this.timeoutMs;\n const logs: string[] = [];\n const abortController = new AbortController();\n const module = await this.loadModule();\n const runtime = module.newRuntime();\n runtime.setMemoryLimit(this.memoryLimitBytes);\n runtime.setInterruptHandler(shouldInterruptAfterDeadline(deadline));\n const context = runtime.newContext();\n\n try {\n injectConsole(context, logs);\n injectProviders(context, providers, abortController.signal);\n\n const executableSource = normalizeCode(code);\n const functionHandle = context.unwrapResult(\n context.evalCode(`(${executableSource})`, \"sandbox-user-code.js\"),\n );\n\n try {\n const promiseHandle = context.unwrapResult(\n context.callFunction(functionHandle, context.undefined),\n );\n\n try {\n const promiseResult = context.resolvePromise(promiseHandle);\n await waitForPromiseSettlement(runtime, promiseResult, deadline);\n const settledResult = await promiseResult;\n\n if (isFail(settledResult)) {\n const errorHandle = settledResult.error;\n\n try {\n return {\n durationMs: Date.now() - startedAt,\n error: errorFromGuestHandle(context, errorHandle, deadline),\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: false,\n };\n } finally {\n errorHandle.dispose();\n }\n }\n\n try {\n const value = fromGuestHandle(context, settledResult.value);\n\n return {\n durationMs: Date.now() - startedAt,\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: true,\n result: value,\n };\n } catch (error) {\n return {\n durationMs: Date.now() - startedAt,\n error: toExecuteError(error, deadline),\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: false,\n };\n } finally {\n settledResult.value.dispose();\n }\n } finally {\n promiseHandle.dispose();\n }\n } finally {\n functionHandle.dispose();\n }\n } catch (error) {\n abortController.abort();\n\n return {\n durationMs: Date.now() - startedAt,\n error: toExecuteError(error, deadline),\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: false,\n };\n } finally {\n abortController.abort();\n context.dispose();\n runtime.dispose();\n }\n }\n}\n"],"mappings":";;;;AAIA,SAAS,eAAe,OAAwB;AAC9C,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI,UAAU,OACZ,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,MAAM;SACtB;AACN,SAAO,OAAO,MAAM;;;AAIxB,SAAgB,kBAAkB,QAA2B;AAC3D,QAAO,OAAO,KAAK,UAAU,eAAe,MAAM,CAAC,CAAC,KAAK,IAAI;;AAG/D,SAAgB,uBACd,SACA,MACA,SACe;CACf,MAAM,cAAc,QAAQ,SAAS;EAAE;EAAS,MAAM;EAAS,CAAC;CAChE,MAAM,aAAa,QAAQ,UAAU,KAAK;AAC1C,SAAQ,QAAQ,aAAa,QAAQ,WAAW;AAChD,YAAW,SAAS;AACpB,QAAO;;AAGT,S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OACL,YAAY,KAAK,KAAK,GAAG;OACzB,OAAO,eAAe,OAAO,SAAS;OACtC,MAAM,aAAa,MAAM,KAAK,aAAa,KAAK,YAAY;OAC5D,IAAI;OACL;eACO;AACR,oBAAc,MAAM,SAAS;;cAEvB;AACR,mBAAc,SAAS;;aAEjB;AACR,mBAAe,SAAS;;WAEnB,OAAO;AACd,mBAAgB,OAAO;AAEvB,UAAO;IACL,YAAY,KAAK,KAAK,GAAG;IACzB,OAAO,eAAe,OAAO,SAAS;IACtC,MAAM,aAAa,MAAM,KAAK,aAAa,KAAK,YAAY;IAC5D,IAAI;IACL;YACO;AACR,mBAAgB,OAAO;AACvB,WAAQ,SAAS;AACjB,WAAQ,SAAS"}
@@ -0,0 +1,38 @@
1
+ import { ExecuteResult, Executor, ResolvedToolProvider } from "@mcploom/codexec";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Options for constructing a {@link QuickJsExecutor}.
6
+ */
7
+ interface QuickJsExecutorOptions {
8
+ /** Optional QuickJS module loader override for tests or custom builds. */
9
+ loadModule?: () => Promise<unknown> | unknown;
10
+ /** Maximum total characters preserved across captured log lines. */
11
+ maxLogChars?: number;
12
+ /** Maximum number of captured log lines returned in the result. */
13
+ maxLogLines?: number;
14
+ /** Guest memory limit in bytes. */
15
+ memoryLimitBytes?: number;
16
+ /** Wall-clock execution timeout in milliseconds. */
17
+ timeoutMs?: number;
18
+ }
19
+ //#endregion
20
+ //#region src/quickjsExecutor.d.ts
21
+ /**
22
+ * QuickJS-backed executor for one-shot sandboxed JavaScript runs.
23
+ */
24
+ declare class QuickJsExecutor implements Executor {
25
+ private readonly loadModule;
26
+ private readonly maxLogChars;
27
+ private readonly maxLogLines;
28
+ private readonly memoryLimitBytes;
29
+ private readonly timeoutMs;
30
+ constructor(options?: QuickJsExecutorOptions);
31
+ /**
32
+ * Executes JavaScript against the provided tool namespaces in a fresh QuickJS runtime.
33
+ */
34
+ execute(code: string, providers: ResolvedToolProvider[]): Promise<ExecuteResult>;
35
+ }
36
+ //#endregion
37
+ export { QuickJsExecutor, type QuickJsExecutorOptions };
38
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/quickjsExecutor.ts"],"sourcesContent":[],"mappings":";;;;;;AAGiB,UAAA,sBAAA,CAEI;;qBAAA;;ECiUR,WAAA,CAAA,EAAA,MAAgB;EAON;EAmBR,WAAA,CAAA,EAAA,MAAA;EACF;EAAR,gBAAA,CAAA,EAAA,MAAA;EA3BmC;EAAQ,SAAA,CAAA,EAAA,MAAA;;;;;ADnUhD;;cCmUa,eAAA,YAA2B;;EAA3B,iBAAA,WAAgB;EAON,iBAAA,WAAA;EAmBR,iBAAA,gBAAA;EACF,iBAAA,SAAA;EAAR,WAAA,CAAA,OAAA,CAAA,EApBkB,sBAoBlB;EA3BmC;;;mCA0BzB,yBACV,QAAQ"}
@@ -0,0 +1,38 @@
1
+ import { ExecuteResult, Executor, ResolvedToolProvider } from "@mcploom/codexec";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * Options for constructing a {@link QuickJsExecutor}.
6
+ */
7
+ interface QuickJsExecutorOptions {
8
+ /** Optional QuickJS module loader override for tests or custom builds. */
9
+ loadModule?: () => Promise<unknown> | unknown;
10
+ /** Maximum total characters preserved across captured log lines. */
11
+ maxLogChars?: number;
12
+ /** Maximum number of captured log lines returned in the result. */
13
+ maxLogLines?: number;
14
+ /** Guest memory limit in bytes. */
15
+ memoryLimitBytes?: number;
16
+ /** Wall-clock execution timeout in milliseconds. */
17
+ timeoutMs?: number;
18
+ }
19
+ //#endregion
20
+ //#region src/quickjsExecutor.d.ts
21
+ /**
22
+ * QuickJS-backed executor for one-shot sandboxed JavaScript runs.
23
+ */
24
+ declare class QuickJsExecutor implements Executor {
25
+ private readonly loadModule;
26
+ private readonly maxLogChars;
27
+ private readonly maxLogLines;
28
+ private readonly memoryLimitBytes;
29
+ private readonly timeoutMs;
30
+ constructor(options?: QuickJsExecutorOptions);
31
+ /**
32
+ * Executes JavaScript against the provided tool namespaces in a fresh QuickJS runtime.
33
+ */
34
+ execute(code: string, providers: ResolvedToolProvider[]): Promise<ExecuteResult>;
35
+ }
36
+ //#endregion
37
+ export { QuickJsExecutor, type QuickJsExecutorOptions };
38
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/types.ts","../src/quickjsExecutor.ts"],"sourcesContent":[],"mappings":";;;;;;AAGiB,UAAA,sBAAA,CAEI;;qBAAA;;ECiUR,WAAA,CAAA,EAAA,MAAgB;EAON;EAmBR,WAAA,CAAA,EAAA,MAAA;EACF;EAAR,gBAAA,CAAA,EAAA,MAAA;EA3BmC;EAAQ,SAAA,CAAA,EAAA,MAAA;;;;;ADnUhD;;cCmUa,eAAA,YAA2B;;EAA3B,iBAAA,WAAgB;EAON,iBAAA,WAAA;EAmBR,iBAAA,gBAAA;EACF,iBAAA,SAAA;EAAR,WAAA,CAAA,OAAA,CAAA,EApBkB,sBAoBlB;EA3BmC;;;mCA0BzB,yBACV,QAAQ"}
package/dist/index.js ADDED
@@ -0,0 +1,314 @@
1
+ import { RELEASE_SYNC, isFail, memoizePromiseFactory, newQuickJSWASMModule, shouldInterruptAfterDeadline } from "quickjs-emscripten";
2
+ import { ExecuteFailure, isExecuteFailure, normalizeCode } from "@mcploom/codexec";
3
+
4
+ //#region src/quickjsBridge.ts
5
+ function formatLogValue(value) {
6
+ if (typeof value === "string") return value;
7
+ if (value === void 0) return "undefined";
8
+ try {
9
+ return JSON.stringify(value);
10
+ } catch {
11
+ return String(value);
12
+ }
13
+ }
14
+ function formatConsoleLine(values) {
15
+ return values.map((value) => formatLogValue(value)).join(" ");
16
+ }
17
+ function createGuestErrorHandle(context, code, message) {
18
+ const errorHandle = context.newError({
19
+ message,
20
+ name: "Error"
21
+ });
22
+ const codeHandle = context.newString(code);
23
+ context.setProp(errorHandle, "code", codeHandle);
24
+ codeHandle.dispose();
25
+ return errorHandle;
26
+ }
27
+ function fromGuestHandle(context, handle) {
28
+ const guestType = context.typeof(handle);
29
+ if (guestType === "undefined") return;
30
+ if (guestType === "function" || guestType === "symbol" || guestType === "bigint") throw new ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
31
+ const jsonHandle = context.getProp(context.global, "JSON");
32
+ const stringifyHandle = context.getProp(jsonHandle, "stringify");
33
+ try {
34
+ const stringified = context.unwrapResult(context.callFunction(stringifyHandle, jsonHandle, handle));
35
+ if (context.typeof(stringified) === "undefined") throw new ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
36
+ const jsonValue = context.getString(stringified);
37
+ return JSON.parse(jsonValue);
38
+ } catch (error) {
39
+ if (error instanceof ExecuteFailure) throw error;
40
+ throw new ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
41
+ } finally {
42
+ stringifyHandle.dispose();
43
+ jsonHandle.dispose();
44
+ }
45
+ }
46
+ function toGuestHandle(context, value) {
47
+ if (value === void 0) return context.undefined;
48
+ const jsonValue = JSON.stringify(value);
49
+ if (jsonValue === void 0) throw new ExecuteFailure("serialization_error", "Host value is not JSON-serializable");
50
+ return context.unwrapResult(context.evalCode(`(${jsonValue})`, "host-value.json"));
51
+ }
52
+
53
+ //#endregion
54
+ //#region src/quickjsExecutor.ts
55
+ const DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
56
+ const DEFAULT_TIMEOUT_MS = 5e3;
57
+ const DEFAULT_MAX_LOG_LINES = 100;
58
+ const DEFAULT_MAX_LOG_CHARS = 64e3;
59
+ const loadDefaultModule = memoizePromiseFactory(() => newQuickJSWASMModule(RELEASE_SYNC));
60
+ function isKnownErrorCode(value) {
61
+ return value === "timeout" || value === "memory_limit" || value === "validation_error" || value === "tool_error" || value === "runtime_error" || value === "serialization_error" || value === "internal_error";
62
+ }
63
+ function normalizeThrownMessage(error) {
64
+ if (error instanceof Error) return error.message;
65
+ return String(error);
66
+ }
67
+ function toExecuteError(error, deadline) {
68
+ if (isExecuteFailure(error)) return {
69
+ code: error.code,
70
+ message: error.message
71
+ };
72
+ const message = normalizeThrownMessage(error);
73
+ if (Date.now() > deadline || message.includes("interrupted")) return {
74
+ code: "timeout",
75
+ message: "Execution timed out"
76
+ };
77
+ if (message.toLowerCase().includes("out of memory")) return {
78
+ code: "memory_limit",
79
+ message
80
+ };
81
+ return {
82
+ code: "runtime_error",
83
+ message
84
+ };
85
+ }
86
+ function errorFromGuestHandle(context, handle, deadline) {
87
+ const codeHandle = context.getProp(handle, "code");
88
+ const messageHandle = context.getProp(handle, "message");
89
+ try {
90
+ const code = context.typeof(codeHandle) === "string" ? context.getString(codeHandle) : void 0;
91
+ const message = context.typeof(messageHandle) === "string" ? context.getString(messageHandle) : normalizeThrownMessage(context.dump(handle));
92
+ if (isKnownErrorCode(code)) return {
93
+ code,
94
+ message
95
+ };
96
+ return toExecuteError(message, deadline);
97
+ } finally {
98
+ codeHandle.dispose();
99
+ messageHandle.dispose();
100
+ }
101
+ }
102
+ function truncateLogs(logs, maxLogLines, maxLogChars) {
103
+ const limitedLines = logs.slice(0, maxLogLines);
104
+ let remainingChars = maxLogChars;
105
+ const truncated = [];
106
+ for (const line of limitedLines) {
107
+ if (remainingChars <= 0) break;
108
+ if (line.length <= remainingChars) {
109
+ truncated.push(line);
110
+ remainingChars -= line.length;
111
+ continue;
112
+ }
113
+ truncated.push(line.slice(0, remainingChars));
114
+ break;
115
+ }
116
+ return truncated;
117
+ }
118
+ function createExecutionContext(signal, providerName, safeToolName, originalToolName) {
119
+ return {
120
+ originalToolName,
121
+ providerName,
122
+ safeToolName,
123
+ signal
124
+ };
125
+ }
126
+ async function waitForPromiseSettlement(runtime, promise, deadline) {
127
+ let settled = false;
128
+ let rejection;
129
+ promise.then(() => {
130
+ settled = true;
131
+ }, (error) => {
132
+ settled = true;
133
+ rejection = error;
134
+ });
135
+ while (!settled) {
136
+ if (Date.now() > deadline) throw new ExecuteFailure("timeout", "Execution timed out");
137
+ const pendingJobsResult = runtime.executePendingJobs(-1);
138
+ if (isFail(pendingJobsResult)) {
139
+ const pendingError = pendingJobsResult.error;
140
+ try {
141
+ const executeError = errorFromGuestHandle(pendingError.context, pendingError, deadline);
142
+ throw new ExecuteFailure(executeError.code, executeError.message);
143
+ } finally {
144
+ pendingError.dispose();
145
+ }
146
+ }
147
+ await new Promise((resolve) => setTimeout(resolve, 0));
148
+ }
149
+ if (rejection !== void 0) throw rejection;
150
+ }
151
+ function injectConsole(context, logs) {
152
+ const consoleHandle = context.newObject();
153
+ try {
154
+ for (const methodName of [
155
+ "log",
156
+ "info",
157
+ "warn",
158
+ "error"
159
+ ]) {
160
+ const methodHandle = context.newFunction(methodName, (...args) => {
161
+ logs.push(formatConsoleLine(args.map((arg) => context.dump(arg))));
162
+ return context.undefined;
163
+ });
164
+ context.setProp(consoleHandle, methodName, methodHandle);
165
+ methodHandle.dispose();
166
+ }
167
+ context.setProp(context.global, "console", consoleHandle);
168
+ } finally {
169
+ consoleHandle.dispose();
170
+ }
171
+ }
172
+ function injectProviders(context, providers, signal) {
173
+ for (const provider of providers) {
174
+ const providerHandle = context.newObject();
175
+ try {
176
+ for (const [safeToolName, descriptor] of Object.entries(provider.tools)) {
177
+ const toolHandle = createToolHandle(context, provider, descriptor, safeToolName, signal);
178
+ context.setProp(providerHandle, safeToolName, toolHandle);
179
+ toolHandle.dispose();
180
+ }
181
+ context.setProp(context.global, provider.name, providerHandle);
182
+ } finally {
183
+ providerHandle.dispose();
184
+ }
185
+ }
186
+ }
187
+ function createToolHandle(context, provider, descriptor, safeToolName, signal) {
188
+ return context.newFunction(safeToolName, (...args) => {
189
+ const deferred = context.newPromise();
190
+ const input = args[0] === void 0 ? void 0 : context.dump(args[0]);
191
+ const executionContext = createExecutionContext(signal, provider.name, safeToolName, descriptor.originalName);
192
+ Promise.resolve().then(async () => descriptor.execute(input, executionContext)).then((result) => {
193
+ if (!context.alive || !deferred.alive) return;
194
+ let resultHandle;
195
+ try {
196
+ resultHandle = toGuestHandle(context, result);
197
+ deferred.resolve(resultHandle);
198
+ } catch (error) {
199
+ const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);
200
+ const errorHandle = createGuestErrorHandle(context, executeError.code, executeError.message);
201
+ deferred.reject(errorHandle);
202
+ errorHandle.dispose();
203
+ } finally {
204
+ resultHandle?.dispose();
205
+ deferred.dispose();
206
+ }
207
+ }).catch((error) => {
208
+ if (!context.alive || !deferred.alive) return;
209
+ const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);
210
+ const errorHandle = createGuestErrorHandle(context, executeError.code, executeError.message);
211
+ deferred.reject(errorHandle);
212
+ errorHandle.dispose();
213
+ deferred.dispose();
214
+ });
215
+ return deferred.handle;
216
+ });
217
+ }
218
+ /**
219
+ * QuickJS-backed executor for one-shot sandboxed JavaScript runs.
220
+ */
221
+ var QuickJsExecutor = class {
222
+ loadModule;
223
+ maxLogChars;
224
+ maxLogLines;
225
+ memoryLimitBytes;
226
+ timeoutMs;
227
+ constructor(options = {}) {
228
+ this.loadModule = async () => {
229
+ return options.loadModule ? await options.loadModule() : await loadDefaultModule();
230
+ };
231
+ this.maxLogChars = options.maxLogChars ?? DEFAULT_MAX_LOG_CHARS;
232
+ this.maxLogLines = options.maxLogLines ?? DEFAULT_MAX_LOG_LINES;
233
+ this.memoryLimitBytes = options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES;
234
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
235
+ }
236
+ /**
237
+ * Executes JavaScript against the provided tool namespaces in a fresh QuickJS runtime.
238
+ */
239
+ async execute(code, providers) {
240
+ const startedAt = Date.now();
241
+ const deadline = startedAt + this.timeoutMs;
242
+ const logs = [];
243
+ const abortController = new AbortController();
244
+ const runtime = (await this.loadModule()).newRuntime();
245
+ runtime.setMemoryLimit(this.memoryLimitBytes);
246
+ runtime.setInterruptHandler(shouldInterruptAfterDeadline(deadline));
247
+ const context = runtime.newContext();
248
+ try {
249
+ injectConsole(context, logs);
250
+ injectProviders(context, providers, abortController.signal);
251
+ const executableSource = normalizeCode(code);
252
+ const functionHandle = context.unwrapResult(context.evalCode(`(${executableSource})`, "sandbox-user-code.js"));
253
+ try {
254
+ const promiseHandle = context.unwrapResult(context.callFunction(functionHandle, context.undefined));
255
+ try {
256
+ const promiseResult = context.resolvePromise(promiseHandle);
257
+ await waitForPromiseSettlement(runtime, promiseResult, deadline);
258
+ const settledResult = await promiseResult;
259
+ if (isFail(settledResult)) {
260
+ const errorHandle = settledResult.error;
261
+ try {
262
+ return {
263
+ durationMs: Date.now() - startedAt,
264
+ error: errorFromGuestHandle(context, errorHandle, deadline),
265
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
266
+ ok: false
267
+ };
268
+ } finally {
269
+ errorHandle.dispose();
270
+ }
271
+ }
272
+ try {
273
+ const value = fromGuestHandle(context, settledResult.value);
274
+ return {
275
+ durationMs: Date.now() - startedAt,
276
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
277
+ ok: true,
278
+ result: value
279
+ };
280
+ } catch (error) {
281
+ return {
282
+ durationMs: Date.now() - startedAt,
283
+ error: toExecuteError(error, deadline),
284
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
285
+ ok: false
286
+ };
287
+ } finally {
288
+ settledResult.value.dispose();
289
+ }
290
+ } finally {
291
+ promiseHandle.dispose();
292
+ }
293
+ } finally {
294
+ functionHandle.dispose();
295
+ }
296
+ } catch (error) {
297
+ abortController.abort();
298
+ return {
299
+ durationMs: Date.now() - startedAt,
300
+ error: toExecuteError(error, deadline),
301
+ logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),
302
+ ok: false
303
+ };
304
+ } finally {
305
+ abortController.abort();
306
+ context.dispose();
307
+ runtime.dispose();
308
+ }
309
+ }
310
+ };
311
+
312
+ //#endregion
313
+ export { QuickJsExecutor };
314
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["truncated: string[]","rejection: unknown","resultHandle: QuickJSHandle | undefined","logs: string[]"],"sources":["../src/quickjsBridge.ts","../src/quickjsExecutor.ts"],"sourcesContent":["import type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\n\nimport { ExecuteFailure, type ExecuteErrorCode } from \"@mcploom/codexec\";\n\nfunction formatLogValue(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value === undefined) {\n return \"undefined\";\n }\n\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nexport function formatConsoleLine(values: unknown[]): string {\n return values.map((value) => formatLogValue(value)).join(\" \");\n}\n\nexport function createGuestErrorHandle(\n context: QuickJSContext,\n code: ExecuteErrorCode,\n message: string,\n): QuickJSHandle {\n const errorHandle = context.newError({ message, name: \"Error\" });\n const codeHandle = context.newString(code);\n context.setProp(errorHandle, \"code\", codeHandle);\n codeHandle.dispose();\n return errorHandle;\n}\n\nexport function fromGuestHandle(\n context: QuickJSContext,\n handle: QuickJSHandle,\n): unknown {\n const guestType = context.typeof(handle);\n\n if (guestType === \"undefined\") {\n return undefined;\n }\n\n if (\n guestType === \"function\" ||\n guestType === \"symbol\" ||\n guestType === \"bigint\"\n ) {\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Guest code returned a non-serializable value\",\n );\n }\n\n const jsonHandle = context.getProp(context.global, \"JSON\");\n const stringifyHandle = context.getProp(jsonHandle, \"stringify\");\n\n try {\n const stringified = context.unwrapResult(\n context.callFunction(stringifyHandle, jsonHandle, handle),\n );\n const stringifiedType = context.typeof(stringified);\n\n if (stringifiedType === \"undefined\") {\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Guest code returned a non-serializable value\",\n );\n }\n\n const jsonValue = context.getString(stringified);\n return JSON.parse(jsonValue);\n } catch (error) {\n if (error instanceof ExecuteFailure) {\n throw error;\n }\n\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Guest code returned a non-serializable value\",\n );\n } finally {\n stringifyHandle.dispose();\n jsonHandle.dispose();\n }\n}\n\nexport function toGuestHandle(\n context: QuickJSContext,\n value: unknown,\n): QuickJSHandle {\n if (value === undefined) {\n return context.undefined;\n }\n\n const jsonValue = JSON.stringify(value);\n\n if (jsonValue === undefined) {\n throw new ExecuteFailure(\n \"serialization_error\",\n \"Host value is not JSON-serializable\",\n );\n }\n\n return context.unwrapResult(\n context.evalCode(`(${jsonValue})`, \"host-value.json\"),\n );\n}\n","import {\n RELEASE_SYNC,\n isFail,\n memoizePromiseFactory,\n newQuickJSWASMModule,\n shouldInterruptAfterDeadline,\n type QuickJSContext,\n type QuickJSHandle,\n type QuickJSRuntime,\n type QuickJSWASMModule,\n} from \"quickjs-emscripten\";\n\nimport {\n ExecuteFailure,\n isExecuteFailure,\n normalizeCode,\n} from \"@mcploom/codexec\";\nimport type {\n ExecuteError,\n ExecuteResult,\n ResolvedToolDescriptor,\n ResolvedToolProvider,\n ToolExecutionContext,\n Executor,\n} from \"@mcploom/codexec\";\nimport {\n createGuestErrorHandle,\n formatConsoleLine,\n fromGuestHandle,\n toGuestHandle,\n} from \"./quickjsBridge\";\nimport type { QuickJsExecutorOptions } from \"./types\";\n\nconst DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;\nconst DEFAULT_TIMEOUT_MS = 5000;\nconst DEFAULT_MAX_LOG_LINES = 100;\nconst DEFAULT_MAX_LOG_CHARS = 64_000;\n\nconst loadDefaultModule = memoizePromiseFactory(() =>\n newQuickJSWASMModule(RELEASE_SYNC),\n);\n\nfunction isKnownErrorCode(value: unknown): value is ExecuteError[\"code\"] {\n return (\n value === \"timeout\" ||\n value === \"memory_limit\" ||\n value === \"validation_error\" ||\n value === \"tool_error\" ||\n value === \"runtime_error\" ||\n value === \"serialization_error\" ||\n value === \"internal_error\"\n );\n}\n\nfunction normalizeThrownMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n return String(error);\n}\n\nfunction toExecuteError(error: unknown, deadline: number): ExecuteError {\n if (isExecuteFailure(error)) {\n return {\n code: error.code,\n message: error.message,\n };\n }\n\n const message = normalizeThrownMessage(error);\n\n if (Date.now() > deadline || message.includes(\"interrupted\")) {\n return {\n code: \"timeout\",\n message: \"Execution timed out\",\n };\n }\n\n if (message.toLowerCase().includes(\"out of memory\")) {\n return {\n code: \"memory_limit\",\n message,\n };\n }\n\n return {\n code: \"runtime_error\",\n message,\n };\n}\n\nfunction errorFromGuestHandle(\n context: QuickJSContext,\n handle: QuickJSHandle,\n deadline: number,\n): ExecuteError {\n const codeHandle = context.getProp(handle, \"code\");\n const messageHandle = context.getProp(handle, \"message\");\n\n try {\n const code =\n context.typeof(codeHandle) === \"string\"\n ? context.getString(codeHandle)\n : undefined;\n const message =\n context.typeof(messageHandle) === \"string\"\n ? context.getString(messageHandle)\n : normalizeThrownMessage(context.dump(handle));\n\n if (isKnownErrorCode(code)) {\n return {\n code,\n message,\n };\n }\n\n return toExecuteError(message, deadline);\n } finally {\n codeHandle.dispose();\n messageHandle.dispose();\n }\n}\n\nfunction truncateLogs(\n logs: string[],\n maxLogLines: number,\n maxLogChars: number,\n): string[] {\n const limitedLines = logs.slice(0, maxLogLines);\n let remainingChars = maxLogChars;\n const truncated: string[] = [];\n\n for (const line of limitedLines) {\n if (remainingChars <= 0) {\n break;\n }\n\n if (line.length <= remainingChars) {\n truncated.push(line);\n remainingChars -= line.length;\n continue;\n }\n\n truncated.push(line.slice(0, remainingChars));\n break;\n }\n\n return truncated;\n}\n\nfunction createExecutionContext(\n signal: AbortSignal,\n providerName: string,\n safeToolName: string,\n originalToolName: string,\n): ToolExecutionContext {\n return {\n originalToolName,\n providerName,\n safeToolName,\n signal,\n };\n}\n\nasync function waitForPromiseSettlement(\n runtime: QuickJSRuntime,\n promise: Promise<unknown>,\n deadline: number,\n): Promise<void> {\n let settled = false;\n let rejection: unknown;\n\n promise.then(\n () => {\n settled = true;\n },\n (error) => {\n settled = true;\n rejection = error;\n },\n );\n\n while (!settled) {\n if (Date.now() > deadline) {\n throw new ExecuteFailure(\"timeout\", \"Execution timed out\");\n }\n\n const pendingJobsResult = runtime.executePendingJobs(-1);\n if (isFail(pendingJobsResult)) {\n const pendingError = pendingJobsResult.error;\n\n try {\n const executeError = errorFromGuestHandle(\n pendingError.context,\n pendingError,\n deadline,\n );\n throw new ExecuteFailure(executeError.code, executeError.message);\n } finally {\n pendingError.dispose();\n }\n }\n\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n\n if (rejection !== undefined) {\n throw rejection;\n }\n}\n\nfunction injectConsole(context: QuickJSContext, logs: string[]): void {\n const consoleHandle = context.newObject();\n\n try {\n for (const methodName of [\"log\", \"info\", \"warn\", \"error\"]) {\n const methodHandle = context.newFunction(methodName, (...args) => {\n logs.push(formatConsoleLine(args.map((arg) => context.dump(arg))));\n return context.undefined;\n });\n\n context.setProp(consoleHandle, methodName, methodHandle);\n methodHandle.dispose();\n }\n\n context.setProp(context.global, \"console\", consoleHandle);\n } finally {\n consoleHandle.dispose();\n }\n}\n\nfunction injectProviders(\n context: QuickJSContext,\n providers: ResolvedToolProvider[],\n signal: AbortSignal,\n): void {\n for (const provider of providers) {\n const providerHandle = context.newObject();\n\n try {\n for (const [safeToolName, descriptor] of Object.entries(provider.tools)) {\n const toolHandle = createToolHandle(\n context,\n provider,\n descriptor,\n safeToolName,\n signal,\n );\n context.setProp(providerHandle, safeToolName, toolHandle);\n toolHandle.dispose();\n }\n\n context.setProp(context.global, provider.name, providerHandle);\n } finally {\n providerHandle.dispose();\n }\n }\n}\n\nfunction createToolHandle(\n context: QuickJSContext,\n provider: ResolvedToolProvider,\n descriptor: ResolvedToolDescriptor,\n safeToolName: string,\n signal: AbortSignal,\n): QuickJSHandle {\n return context.newFunction(safeToolName, (...args) => {\n const deferred = context.newPromise();\n const input = args[0] === undefined ? undefined : context.dump(args[0]);\n const executionContext = createExecutionContext(\n signal,\n provider.name,\n safeToolName,\n descriptor.originalName,\n );\n\n void Promise.resolve()\n .then(async () => descriptor.execute(input, executionContext))\n .then((result) => {\n if (!context.alive || !deferred.alive) {\n return;\n }\n\n let resultHandle: QuickJSHandle | undefined;\n\n try {\n resultHandle = toGuestHandle(context, result);\n deferred.resolve(resultHandle);\n } catch (error) {\n const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);\n const errorHandle = createGuestErrorHandle(\n context,\n executeError.code,\n executeError.message,\n );\n deferred.reject(errorHandle);\n errorHandle.dispose();\n } finally {\n resultHandle?.dispose();\n deferred.dispose();\n }\n })\n .catch((error) => {\n if (!context.alive || !deferred.alive) {\n return;\n }\n\n const executeError = toExecuteError(error, Number.POSITIVE_INFINITY);\n const errorHandle = createGuestErrorHandle(\n context,\n executeError.code,\n executeError.message,\n );\n deferred.reject(errorHandle);\n errorHandle.dispose();\n deferred.dispose();\n });\n\n return deferred.handle;\n });\n}\n\n/**\n * QuickJS-backed executor for one-shot sandboxed JavaScript runs.\n */\nexport class QuickJsExecutor implements Executor {\n private readonly loadModule: () => Promise<QuickJSWASMModule>;\n private readonly maxLogChars: number;\n private readonly maxLogLines: number;\n private readonly memoryLimitBytes: number;\n private readonly timeoutMs: number;\n\n constructor(options: QuickJsExecutorOptions = {}) {\n this.loadModule = async () => {\n const loaded = options.loadModule\n ? await options.loadModule()\n : await loadDefaultModule();\n return loaded as QuickJSWASMModule;\n };\n this.maxLogChars = options.maxLogChars ?? DEFAULT_MAX_LOG_CHARS;\n this.maxLogLines = options.maxLogLines ?? DEFAULT_MAX_LOG_LINES;\n this.memoryLimitBytes =\n options.memoryLimitBytes ?? DEFAULT_MEMORY_LIMIT_BYTES;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n }\n\n /**\n * Executes JavaScript against the provided tool namespaces in a fresh QuickJS runtime.\n */\n async execute(\n code: string,\n providers: ResolvedToolProvider[],\n ): Promise<ExecuteResult> {\n const startedAt = Date.now();\n const deadline = startedAt + this.timeoutMs;\n const logs: string[] = [];\n const abortController = new AbortController();\n const module = await this.loadModule();\n const runtime = module.newRuntime();\n runtime.setMemoryLimit(this.memoryLimitBytes);\n runtime.setInterruptHandler(shouldInterruptAfterDeadline(deadline));\n const context = runtime.newContext();\n\n try {\n injectConsole(context, logs);\n injectProviders(context, providers, abortController.signal);\n\n const executableSource = normalizeCode(code);\n const functionHandle = context.unwrapResult(\n context.evalCode(`(${executableSource})`, \"sandbox-user-code.js\"),\n );\n\n try {\n const promiseHandle = context.unwrapResult(\n context.callFunction(functionHandle, context.undefined),\n );\n\n try {\n const promiseResult = context.resolvePromise(promiseHandle);\n await waitForPromiseSettlement(runtime, promiseResult, deadline);\n const settledResult = await promiseResult;\n\n if (isFail(settledResult)) {\n const errorHandle = settledResult.error;\n\n try {\n return {\n durationMs: Date.now() - startedAt,\n error: errorFromGuestHandle(context, errorHandle, deadline),\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: false,\n };\n } finally {\n errorHandle.dispose();\n }\n }\n\n try {\n const value = fromGuestHandle(context, settledResult.value);\n\n return {\n durationMs: Date.now() - startedAt,\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: true,\n result: value,\n };\n } catch (error) {\n return {\n durationMs: Date.now() - startedAt,\n error: toExecuteError(error, deadline),\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: false,\n };\n } finally {\n settledResult.value.dispose();\n }\n } finally {\n promiseHandle.dispose();\n }\n } finally {\n functionHandle.dispose();\n }\n } catch (error) {\n abortController.abort();\n\n return {\n durationMs: Date.now() - startedAt,\n error: toExecuteError(error, deadline),\n logs: truncateLogs(logs, this.maxLogLines, this.maxLogChars),\n ok: false,\n };\n } finally {\n abortController.abort();\n context.dispose();\n runtime.dispose();\n }\n }\n}\n"],"mappings":";;;;AAIA,SAAS,eAAe,OAAwB;AAC9C,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI,UAAU,OACZ,QAAO;AAGT,KAAI;AACF,SAAO,KAAK,UAAU,MAAM;SACtB;AACN,SAAO,OAAO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K,KAAK,GAAG;QACzB,OAAO,qBAAqB,SAAS,aAAa,SAAS;QAC3D,MAAM,aAAa,MAAM,KAAK,aAAa,KAAK,YAAY;QAC5D,IAAI;QACL;gBACO;AACR,mBAAY,SAAS;;;AAIzB,SAAI;MACF,MAAM,QAAQ,gBAAgB,SAAS,cAAc,MAAM;AAE3D,aAAO;OACL,YAAY,KAAK,KAAK,GAAG;OACzB,MAAM,aAAa,MAAM,KAAK,aAAa,KAAK,YAAY;OAC5D,IAAI;OACJ,QAAQ;OACT;cACM,OAAO;AACd,aAAO;OACL,YAAY,KAAK,KAAK,GAAG;OACzB,OAAO,eAAe,OAAO,SAAS;OACtC,MAAM,aAAa,MAAM,KAAK,aAAa,KAAK,YAAY;OAC5D,IAAI;OACL;eACO;AACR,oBAAc,MAAM,SAAS;;cAEvB;AACR,mBAAc,SAAS;;aAEjB;AACR,mBAAe,SAAS;;WAEnB,OAAO;AACd,mBAAgB,OAAO;AAEvB,UAAO;IACL,YAAY,KAAK,KAAK,GAAG;IACzB,OAAO,eAAe,OAAO,SAAS;IACtC,MAAM,aAAa,MAAM,KAAK,aAAa,KAAK,YAAY;IAC5D,IAAI;IACL;YACO;AACR,mBAAgB,OAAO;AACvB,WAAQ,SAAS;AACjB,WAAQ,SAAS"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@mcploom/codexec-quickjs",
3
+ "version": "0.1.0",
4
+ "description": "QuickJS executor for the mcploom codexec core package.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "main": "./dist/index.cjs",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.cjs"
18
+ }
19
+ },
20
+ "sideEffects": false,
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsdown"
28
+ },
29
+ "keywords": [
30
+ "mcp",
31
+ "model-context-protocol",
32
+ "quickjs",
33
+ "sandbox",
34
+ "code-execution"
35
+ ],
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/aallam/mcploom.git",
39
+ "directory": "packages/codexec-quickjs"
40
+ },
41
+ "homepage": "https://github.com/aallam/mcploom/tree/main/packages/codexec-quickjs#readme",
42
+ "bugs": "https://github.com/aallam/mcploom/issues",
43
+ "dependencies": {
44
+ "@mcploom/codexec": "^0.1.0",
45
+ "quickjs-emscripten": "^0.31.0"
46
+ }
47
+ }