@execbox/quickjs 0.4.0 → 0.6.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.
Files changed (58) hide show
  1. package/README.md +38 -38
  2. package/dist/index.cjs +23 -309
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +6 -6
  5. package/dist/index.d.cts.map +1 -1
  6. package/dist/index.d.ts +6 -6
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +18 -304
  9. package/dist/index.js.map +1 -1
  10. package/dist/{protocolEndpoint-DGOUVf6J.cjs → protocolEndpoint-BGyrwlr_.cjs} +5 -40
  11. package/dist/protocolEndpoint-BGyrwlr_.cjs.map +1 -0
  12. package/dist/{protocolEndpoint-T_JEz8YY.js → protocolEndpoint-Ceadcq_L.js} +4 -39
  13. package/dist/protocolEndpoint-Ceadcq_L.js.map +1 -0
  14. package/dist/remoteEndpoint.cjs +45 -0
  15. package/dist/remoteEndpoint.cjs.map +1 -0
  16. package/dist/remoteEndpoint.d.cts +29 -0
  17. package/dist/remoteEndpoint.d.cts.map +1 -0
  18. package/dist/remoteEndpoint.d.ts +29 -0
  19. package/dist/remoteEndpoint.d.ts.map +1 -0
  20. package/dist/remoteEndpoint.js +45 -0
  21. package/dist/remoteEndpoint.js.map +1 -0
  22. package/dist/runner/index.cjs +1 -1
  23. package/dist/runner/index.d.cts +2 -2
  24. package/dist/runner/index.d.cts.map +1 -1
  25. package/dist/runner/index.d.ts +2 -2
  26. package/dist/runner/index.d.ts.map +1 -1
  27. package/dist/runner/index.js +1 -1
  28. package/dist/runner/protocolEndpoint.cjs +2 -2
  29. package/dist/runner/protocolEndpoint.d.cts +2 -2
  30. package/dist/runner/protocolEndpoint.d.cts.map +1 -1
  31. package/dist/runner/protocolEndpoint.d.ts +2 -2
  32. package/dist/runner/protocolEndpoint.d.ts.map +1 -1
  33. package/dist/runner/protocolEndpoint.js +2 -2
  34. package/dist/runner-DRLfwiqY.cjs +348 -0
  35. package/dist/runner-DRLfwiqY.cjs.map +1 -0
  36. package/dist/runner-oZXbguX3.js +343 -0
  37. package/dist/runner-oZXbguX3.js.map +1 -0
  38. package/dist/{types-BeVqrcj8.d.ts → types-C-XfFJ7u.d.cts} +8 -21
  39. package/dist/types-C-XfFJ7u.d.cts.map +1 -0
  40. package/dist/{types-CnNmLawC.d.cts → types-CE7SvejR.d.ts} +8 -21
  41. package/dist/types-CE7SvejR.d.ts.map +1 -0
  42. package/dist/workerEntry.cjs +2 -2
  43. package/dist/workerEntry.js +2 -2
  44. package/package.json +12 -3
  45. package/dist/processEntry.cjs +0 -17
  46. package/dist/processEntry.cjs.map +0 -1
  47. package/dist/processEntry.d.cts +0 -5
  48. package/dist/processEntry.d.ts +0 -5
  49. package/dist/processEntry.js +0 -18
  50. package/dist/processEntry.js.map +0 -1
  51. package/dist/protocolEndpoint-DGOUVf6J.cjs.map +0 -1
  52. package/dist/protocolEndpoint-T_JEz8YY.js.map +0 -1
  53. package/dist/runner-CteKTaPD.js +0 -5654
  54. package/dist/runner-CteKTaPD.js.map +0 -1
  55. package/dist/runner-DRt0kpEk.cjs +0 -5707
  56. package/dist/runner-DRt0kpEk.cjs.map +0 -1
  57. package/dist/types-BeVqrcj8.d.ts.map +0 -1
  58. package/dist/types-CnNmLawC.d.cts.map +0 -1
@@ -0,0 +1,343 @@
1
+ import { ExecuteFailure, formatConsoleLine, getExecutionTimeoutMessage, isExecuteFailure, isKnownExecuteErrorCode, normalizeCode, normalizeThrownMessage, resolveExecutorRuntimeOptions, truncateLogs } from "@execbox/core/runtime";
2
+ import { randomUUID } from "node:crypto";
3
+ import { RELEASE_SYNC, isFail, memoizePromiseFactory, newQuickJSWASMModule, shouldInterruptAfterDeadline } from "quickjs-emscripten";
4
+
5
+ //#region src/quickjsBridge.ts
6
+ /**
7
+ * Creates a guest-visible error object that carries a trusted host error code marker.
8
+ */
9
+ function createGuestErrorHandle(context, code, message, trustedHostErrorKey) {
10
+ const errorHandle = context.newError({
11
+ message,
12
+ name: "Error"
13
+ });
14
+ const codeHandle = context.newString(code);
15
+ const trustedHostMarkerHandle = context.true;
16
+ try {
17
+ context.setProp(errorHandle, "code", codeHandle);
18
+ context.setProp(errorHandle, trustedHostErrorKey, trustedHostMarkerHandle);
19
+ return errorHandle;
20
+ } finally {
21
+ codeHandle.dispose();
22
+ trustedHostMarkerHandle.dispose();
23
+ }
24
+ }
25
+ /**
26
+ * Converts a guest QuickJS handle into a JSON-compatible host value.
27
+ */
28
+ function fromGuestHandle(context, handle) {
29
+ const guestType = context.typeof(handle);
30
+ if (guestType === "undefined") return;
31
+ if (guestType === "function" || guestType === "symbol" || guestType === "bigint") throw new ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
32
+ const jsonHandle = context.getProp(context.global, "JSON");
33
+ const stringifyHandle = context.getProp(jsonHandle, "stringify");
34
+ try {
35
+ const stringified = context.unwrapResult(context.callFunction(stringifyHandle, jsonHandle, handle));
36
+ if (context.typeof(stringified) === "undefined") throw new ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
37
+ const jsonValue = context.getString(stringified);
38
+ return JSON.parse(jsonValue);
39
+ } catch (error) {
40
+ if (error instanceof ExecuteFailure) throw error;
41
+ throw new ExecuteFailure("serialization_error", "Guest code returned a non-serializable value");
42
+ } finally {
43
+ stringifyHandle.dispose();
44
+ jsonHandle.dispose();
45
+ }
46
+ }
47
+ /**
48
+ * Converts a host JSON-compatible value into a guest QuickJS handle.
49
+ */
50
+ function toGuestHandle(context, value) {
51
+ if (value === void 0) return context.undefined;
52
+ const jsonValue = JSON.stringify(value);
53
+ if (jsonValue === void 0) throw new ExecuteFailure("serialization_error", "Host value is not JSON-serializable");
54
+ return context.unwrapResult(context.evalCode(`(${jsonValue})`, "host-value.json"));
55
+ }
56
+
57
+ //#endregion
58
+ //#region src/runner/index.ts
59
+ /**
60
+ * @packageDocumentation
61
+ * Public API for the `@execbox/quickjs/runner` entrypoint.
62
+ */
63
+ const loadDefaultModule = memoizePromiseFactory(() => newQuickJSWASMModule(RELEASE_SYNC));
64
+ /**
65
+ * Converts unexpected executor failures into stable public result errors.
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: getExecutionTimeoutMessage()
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, trustedHostErrorKey) {
87
+ const codeHandle = context.getProp(handle, "code");
88
+ const messageHandle = context.getProp(handle, "message");
89
+ const trustedMarkerHandle = context.getProp(handle, trustedHostErrorKey);
90
+ try {
91
+ const code = context.typeof(codeHandle) === "string" ? context.getString(codeHandle) : void 0;
92
+ const trustedHostError = context.typeof(trustedMarkerHandle) === "boolean";
93
+ const message = context.typeof(messageHandle) === "string" ? context.getString(messageHandle) : normalizeThrownMessage(context.dump(handle));
94
+ if (trustedHostError && isKnownExecuteErrorCode(code)) return {
95
+ code,
96
+ message
97
+ };
98
+ return {
99
+ code: "runtime_error",
100
+ message
101
+ };
102
+ } finally {
103
+ codeHandle.dispose();
104
+ messageHandle.dispose();
105
+ trustedMarkerHandle.dispose();
106
+ }
107
+ }
108
+ async function waitForPromiseSettlement(runtime, promise, deadline, trustedHostErrorKey) {
109
+ let settled = false;
110
+ let rejection;
111
+ promise.then(() => {
112
+ settled = true;
113
+ }, (error) => {
114
+ settled = true;
115
+ rejection = error;
116
+ });
117
+ while (!settled) {
118
+ if (Date.now() > deadline) throw new ExecuteFailure("timeout", getExecutionTimeoutMessage());
119
+ const pendingJobsResult = runtime.executePendingJobs(-1);
120
+ if (isFail(pendingJobsResult)) {
121
+ const pendingError = pendingJobsResult.error;
122
+ try {
123
+ const executeError = errorFromGuestHandle(pendingError.context, pendingError, trustedHostErrorKey);
124
+ throw new ExecuteFailure(executeError.code, executeError.message);
125
+ } finally {
126
+ pendingError.dispose();
127
+ }
128
+ }
129
+ await new Promise((resolve) => setTimeout(resolve, 0));
130
+ }
131
+ if (rejection !== void 0) throw rejection;
132
+ }
133
+ function injectConsole(context, logs) {
134
+ const consoleHandle = context.newObject();
135
+ try {
136
+ for (const methodName of [
137
+ "log",
138
+ "info",
139
+ "warn",
140
+ "error"
141
+ ]) {
142
+ const methodHandle = context.newFunction(methodName, (...args) => {
143
+ logs.push(formatConsoleLine(args.map((arg) => context.dump(arg))));
144
+ return context.undefined;
145
+ });
146
+ context.setProp(consoleHandle, methodName, methodHandle);
147
+ methodHandle.dispose();
148
+ }
149
+ context.setProp(context.global, "console", consoleHandle);
150
+ } finally {
151
+ consoleHandle.dispose();
152
+ }
153
+ }
154
+ function injectProviders(context, providers, signal, trustedHostErrorKey, onToolCall) {
155
+ for (const provider of providers) {
156
+ const providerHandle = context.newObject();
157
+ try {
158
+ for (const [safeToolName] of Object.entries(provider.tools)) {
159
+ const toolHandle = createToolHandle(context, provider.name, safeToolName, signal, trustedHostErrorKey, onToolCall);
160
+ context.setProp(providerHandle, safeToolName, toolHandle);
161
+ toolHandle.dispose();
162
+ }
163
+ context.setProp(context.global, provider.name, providerHandle);
164
+ } finally {
165
+ providerHandle.dispose();
166
+ }
167
+ }
168
+ }
169
+ function createToolHandle(context, providerName, safeToolName, signal, trustedHostErrorKey, onToolCall) {
170
+ return context.newFunction(safeToolName, (...args) => {
171
+ const deferred = context.newPromise();
172
+ const disposeDeferred = () => {
173
+ if (context.alive && deferred.alive) deferred.dispose();
174
+ };
175
+ let input;
176
+ try {
177
+ input = args[0] === void 0 ? void 0 : fromGuestHandle(context, args[0]);
178
+ } catch (error) {
179
+ const executeError = isExecuteFailure(error) ? error : new ExecuteFailure("serialization_error", "Guest code passed a non-serializable tool input");
180
+ const errorHandle = createGuestErrorHandle(context, executeError.code, executeError.message, trustedHostErrorKey);
181
+ try {
182
+ deferred.reject(errorHandle);
183
+ return deferred.handle;
184
+ } finally {
185
+ errorHandle.dispose();
186
+ queueMicrotask(disposeDeferred);
187
+ }
188
+ }
189
+ const onAbort = () => {
190
+ signal.removeEventListener("abort", onAbort);
191
+ if (!context.alive || !deferred.alive) {
192
+ disposeDeferred();
193
+ return;
194
+ }
195
+ const errorHandle = createGuestErrorHandle(context, "timeout", getExecutionTimeoutMessage(), trustedHostErrorKey);
196
+ try {
197
+ deferred.reject(errorHandle);
198
+ } finally {
199
+ errorHandle.dispose();
200
+ disposeDeferred();
201
+ }
202
+ };
203
+ signal.addEventListener("abort", onAbort, { once: true });
204
+ let responsePromise;
205
+ try {
206
+ if (signal.aborted) throw new ExecuteFailure("timeout", getExecutionTimeoutMessage());
207
+ responsePromise = Promise.resolve(onToolCall({
208
+ input,
209
+ providerName,
210
+ safeToolName
211
+ }));
212
+ } catch (error) {
213
+ responsePromise = Promise.reject(error);
214
+ }
215
+ responsePromise.then((response) => {
216
+ signal.removeEventListener("abort", onAbort);
217
+ if (!context.alive || !deferred.alive) {
218
+ disposeDeferred();
219
+ return;
220
+ }
221
+ let resultHandle;
222
+ try {
223
+ if (!response.ok) {
224
+ const errorHandle = createGuestErrorHandle(context, response.error.code, response.error.message, trustedHostErrorKey);
225
+ deferred.reject(errorHandle);
226
+ errorHandle.dispose();
227
+ return;
228
+ }
229
+ resultHandle = toGuestHandle(context, response.result);
230
+ deferred.resolve(resultHandle);
231
+ } finally {
232
+ resultHandle?.dispose();
233
+ disposeDeferred();
234
+ }
235
+ }).catch((error) => {
236
+ signal.removeEventListener("abort", onAbort);
237
+ if (!context.alive || !deferred.alive) {
238
+ disposeDeferred();
239
+ return;
240
+ }
241
+ const errorHandle = createGuestErrorHandle(context, isExecuteFailure(error) ? error.code : "internal_error", normalizeThrownMessage(error), trustedHostErrorKey);
242
+ try {
243
+ deferred.reject(errorHandle);
244
+ } finally {
245
+ errorHandle.dispose();
246
+ disposeDeferred();
247
+ }
248
+ });
249
+ return deferred.handle;
250
+ });
251
+ }
252
+ /**
253
+ * Runs one QuickJS-backed execution session using a transport-neutral tool callback.
254
+ */
255
+ async function runQuickJsSession(request, options = {}) {
256
+ const runtimeOptions = resolveExecutorRuntimeOptions(options);
257
+ const loadModule = async () => {
258
+ if (options.module) return options.module;
259
+ return options.loadModule ? await options.loadModule() : await loadDefaultModule();
260
+ };
261
+ const { maxLogChars, maxLogLines, memoryLimitBytes, timeoutMs } = runtimeOptions;
262
+ const startedAt = Date.now();
263
+ const logs = [];
264
+ const abortController = new AbortController();
265
+ const trustedHostErrorKey = `__execboxHostError_${randomUUID()}`;
266
+ const signal = request.abortController?.signal ?? request.signal ?? abortController.signal;
267
+ const runtime = (await loadModule()).newRuntime();
268
+ let deadline = Number.POSITIVE_INFINITY;
269
+ runtime.setMemoryLimit(memoryLimitBytes);
270
+ const context = runtime.newContext();
271
+ try {
272
+ injectConsole(context, logs);
273
+ injectProviders(context, request.providers, signal, trustedHostErrorKey, request.onToolCall);
274
+ deadline = Date.now() + timeoutMs;
275
+ const shouldInterrupt = shouldInterruptAfterDeadline(deadline);
276
+ runtime.setInterruptHandler((currentRuntime) => {
277
+ return signal.aborted || shouldInterrupt(currentRuntime);
278
+ });
279
+ request.onStarted?.();
280
+ const executableSource = normalizeCode(request.code);
281
+ const functionHandle = context.unwrapResult(context.evalCode(`(${executableSource})`, "sandbox-user-code.js"));
282
+ try {
283
+ const promiseHandle = context.unwrapResult(context.callFunction(functionHandle, context.undefined));
284
+ try {
285
+ const promiseResult = context.resolvePromise(promiseHandle);
286
+ await waitForPromiseSettlement(runtime, promiseResult, deadline, trustedHostErrorKey);
287
+ const settledResult = await promiseResult;
288
+ if (isFail(settledResult)) {
289
+ const errorHandle = settledResult.error;
290
+ try {
291
+ return {
292
+ durationMs: Date.now() - startedAt,
293
+ error: errorFromGuestHandle(context, errorHandle, trustedHostErrorKey),
294
+ logs: truncateLogs(logs, maxLogLines, maxLogChars),
295
+ ok: false
296
+ };
297
+ } finally {
298
+ errorHandle.dispose();
299
+ }
300
+ }
301
+ try {
302
+ const value = fromGuestHandle(context, settledResult.value);
303
+ return {
304
+ durationMs: Date.now() - startedAt,
305
+ logs: truncateLogs(logs, maxLogLines, maxLogChars),
306
+ ok: true,
307
+ result: value
308
+ };
309
+ } catch (error) {
310
+ return {
311
+ durationMs: Date.now() - startedAt,
312
+ error: toExecuteError(error, deadline),
313
+ logs: truncateLogs(logs, maxLogLines, maxLogChars),
314
+ ok: false
315
+ };
316
+ } finally {
317
+ settledResult.value.dispose();
318
+ }
319
+ } finally {
320
+ promiseHandle.dispose();
321
+ }
322
+ } finally {
323
+ functionHandle.dispose();
324
+ }
325
+ } catch (error) {
326
+ abortController.abort();
327
+ return {
328
+ durationMs: Date.now() - startedAt,
329
+ error: toExecuteError(error, deadline),
330
+ logs: truncateLogs(logs, maxLogLines, maxLogChars),
331
+ ok: false
332
+ };
333
+ } finally {
334
+ request.abortController?.abort();
335
+ abortController.abort();
336
+ context.dispose();
337
+ runtime.dispose();
338
+ }
339
+ }
340
+
341
+ //#endregion
342
+ export { runQuickJsSession as t };
343
+ //# sourceMappingURL=runner-oZXbguX3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runner-oZXbguX3.js","names":["rejection: unknown","input: unknown","responsePromise: Promise<ToolCallResult>","resultHandle: QuickJSHandle | undefined","logs: string[]"],"sources":["../src/quickjsBridge.ts","../src/runner/index.ts"],"sourcesContent":["import type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\n\nimport { ExecuteFailure } from \"@execbox/core/runtime\";\nimport type { ExecuteErrorCode } from \"@execbox/core\";\n\n/**\n * Creates a guest-visible error object that carries a trusted host error code marker.\n */\nexport function createGuestErrorHandle(\n context: QuickJSContext,\n code: ExecuteErrorCode,\n message: string,\n trustedHostErrorKey: string,\n): QuickJSHandle {\n const errorHandle = context.newError({ message, name: \"Error\" });\n const codeHandle = context.newString(code);\n const trustedHostMarkerHandle = context.true;\n\n try {\n context.setProp(errorHandle, \"code\", codeHandle);\n context.setProp(errorHandle, trustedHostErrorKey, trustedHostMarkerHandle);\n return errorHandle;\n } finally {\n codeHandle.dispose();\n trustedHostMarkerHandle.dispose();\n }\n}\n\n/**\n * Converts a guest QuickJS handle into a JSON-compatible host value.\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\n/**\n * Converts a host JSON-compatible value into a guest QuickJS handle.\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","/**\n * @packageDocumentation\n * Public API for the `@execbox/quickjs/runner` entrypoint.\n */\nimport { randomUUID } from \"node:crypto\";\n\nimport {\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 formatConsoleLine,\n getExecutionTimeoutMessage,\n isExecuteFailure,\n isKnownExecuteErrorCode,\n normalizeCode,\n normalizeThrownMessage,\n resolveExecutorRuntimeOptions,\n truncateLogs,\n} from \"@execbox/core/runtime\";\nimport type {\n ExecuteError,\n ExecuteResult,\n ExecutorRuntimeOptions,\n ProviderManifest,\n ToolCall,\n ToolCallResult,\n} from \"@execbox/core\";\n\nimport {\n createGuestErrorHandle,\n fromGuestHandle,\n toGuestHandle,\n} from \"../quickjsBridge.ts\";\nimport type { QuickJsInlineExecutorOptions } from \"../types.ts\";\n\nexport type {\n QuickJsExecutorHost,\n QuickJsExecutorOptions,\n QuickJsHostedMode,\n QuickJsInlineExecutorOptions,\n QuickJsWorkerExecutorOptions,\n WorkerResourceLimits,\n} from \"../types.ts\";\n\nconst loadDefaultModule = memoizePromiseFactory(() =>\n newQuickJSWASMModule(RELEASE_SYNC),\n);\n\n/**\n * Transport-neutral host tool call emitted from a QuickJS session.\n */\nexport type QuickJsSessionToolCall = ToolCall;\n\n/**\n * Input required to run one transport-backed QuickJS execution session.\n */\nexport interface QuickJsSessionRequest {\n /** Optional abort controller that should be triggered when execution stops. */\n abortController?: AbortController;\n\n /** Guest JavaScript source to evaluate inside QuickJS. */\n code: string;\n\n /** Host callback used to fulfill guest tool calls. */\n onToolCall: (call: ToolCall) => Promise<ToolCallResult> | ToolCallResult;\n\n /** Optional hook invoked once the guest runtime has started. */\n onStarted?: () => void;\n\n /** Transport-safe provider manifests exposed to the guest runtime. */\n providers: ProviderManifest[];\n\n /** Optional caller-owned abort signal for the session. */\n signal?: AbortSignal;\n}\n\n/**\n * Options controlling one transport-backed QuickJS session.\n */\nexport type QuickJsSessionOptions = ExecutorRuntimeOptions &\n Pick<QuickJsInlineExecutorOptions, \"loadModule\"> & {\n /** Optional preloaded QuickJS WASM module instance. */\n module?: QuickJSWASMModule;\n };\n\n/**\n * Converts unexpected executor failures into stable public result errors.\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: getExecutionTimeoutMessage(),\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 trustedHostErrorKey: string,\n): ExecuteError {\n const codeHandle = context.getProp(handle, \"code\");\n const messageHandle = context.getProp(handle, \"message\");\n const trustedMarkerHandle = context.getProp(handle, trustedHostErrorKey);\n\n try {\n const code =\n context.typeof(codeHandle) === \"string\"\n ? context.getString(codeHandle)\n : undefined;\n const trustedHostError = context.typeof(trustedMarkerHandle) === \"boolean\";\n const message =\n context.typeof(messageHandle) === \"string\"\n ? context.getString(messageHandle)\n : normalizeThrownMessage(context.dump(handle));\n\n if (trustedHostError && isKnownExecuteErrorCode(code)) {\n return {\n code,\n message,\n };\n }\n\n return {\n code: \"runtime_error\",\n message,\n };\n } finally {\n codeHandle.dispose();\n messageHandle.dispose();\n trustedMarkerHandle.dispose();\n }\n}\n\nasync function waitForPromiseSettlement(\n runtime: QuickJSRuntime,\n promise: Promise<unknown>,\n deadline: number,\n trustedHostErrorKey: string,\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\", getExecutionTimeoutMessage());\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 trustedHostErrorKey,\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: ProviderManifest[],\n signal: AbortSignal,\n trustedHostErrorKey: string,\n onToolCall: QuickJsSessionRequest[\"onToolCall\"],\n): void {\n for (const provider of providers) {\n const providerHandle = context.newObject();\n\n try {\n for (const [safeToolName] of Object.entries(provider.tools)) {\n const toolHandle = createToolHandle(\n context,\n provider.name,\n safeToolName,\n signal,\n trustedHostErrorKey,\n onToolCall,\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 providerName: string,\n safeToolName: string,\n signal: AbortSignal,\n trustedHostErrorKey: string,\n onToolCall: QuickJsSessionRequest[\"onToolCall\"],\n): QuickJSHandle {\n return context.newFunction(safeToolName, (...args) => {\n const deferred = context.newPromise();\n const disposeDeferred = () => {\n if (context.alive && deferred.alive) {\n deferred.dispose();\n }\n };\n let input: unknown;\n\n try {\n input =\n args[0] === undefined ? undefined : fromGuestHandle(context, args[0]);\n } catch (error) {\n const executeError = isExecuteFailure(error)\n ? error\n : new ExecuteFailure(\n \"serialization_error\",\n \"Guest code passed a non-serializable tool input\",\n );\n const errorHandle = createGuestErrorHandle(\n context,\n executeError.code,\n executeError.message,\n trustedHostErrorKey,\n );\n\n try {\n deferred.reject(errorHandle);\n return deferred.handle;\n } finally {\n errorHandle.dispose();\n queueMicrotask(disposeDeferred);\n }\n }\n const onAbort = () => {\n signal.removeEventListener(\"abort\", onAbort);\n if (!context.alive || !deferred.alive) {\n disposeDeferred();\n return;\n }\n\n const errorHandle = createGuestErrorHandle(\n context,\n \"timeout\",\n getExecutionTimeoutMessage(),\n trustedHostErrorKey,\n );\n\n try {\n deferred.reject(errorHandle);\n } finally {\n errorHandle.dispose();\n disposeDeferred();\n }\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n\n let responsePromise: Promise<ToolCallResult>;\n\n try {\n if (signal.aborted) {\n throw new ExecuteFailure(\"timeout\", getExecutionTimeoutMessage());\n }\n\n responsePromise = Promise.resolve(\n onToolCall({\n input,\n providerName,\n safeToolName,\n }),\n );\n } catch (error) {\n responsePromise = Promise.reject(error);\n }\n\n void responsePromise\n .then((response) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (!context.alive || !deferred.alive) {\n disposeDeferred();\n return;\n }\n\n let resultHandle: QuickJSHandle | undefined;\n\n try {\n if (!response.ok) {\n const errorHandle = createGuestErrorHandle(\n context,\n response.error.code,\n response.error.message,\n trustedHostErrorKey,\n );\n deferred.reject(errorHandle);\n errorHandle.dispose();\n return;\n }\n\n resultHandle = toGuestHandle(context, response.result);\n deferred.resolve(resultHandle);\n } finally {\n resultHandle?.dispose();\n disposeDeferred();\n }\n })\n .catch((error) => {\n signal.removeEventListener(\"abort\", onAbort);\n if (!context.alive || !deferred.alive) {\n disposeDeferred();\n return;\n }\n\n const errorHandle = createGuestErrorHandle(\n context,\n isExecuteFailure(error) ? error.code : \"internal_error\",\n normalizeThrownMessage(error),\n trustedHostErrorKey,\n );\n\n try {\n deferred.reject(errorHandle);\n } finally {\n errorHandle.dispose();\n disposeDeferred();\n }\n });\n\n return deferred.handle;\n });\n}\n\n/**\n * Runs one QuickJS-backed execution session using a transport-neutral tool callback.\n */\nexport async function runQuickJsSession(\n request: QuickJsSessionRequest,\n options: QuickJsSessionOptions = {},\n): Promise<ExecuteResult> {\n const runtimeOptions = resolveExecutorRuntimeOptions(options);\n const loadModule = async () => {\n if (options.module) {\n return options.module;\n }\n\n const loaded = options.loadModule\n ? await options.loadModule()\n : await loadDefaultModule();\n return loaded as QuickJSWASMModule;\n };\n const { maxLogChars, maxLogLines, memoryLimitBytes, timeoutMs } =\n runtimeOptions;\n const startedAt = Date.now();\n const logs: string[] = [];\n const abortController = new AbortController();\n const trustedHostErrorKey = `__execboxHostError_${randomUUID()}`;\n const signal =\n request.abortController?.signal ?? request.signal ?? abortController.signal;\n const module = await loadModule();\n const runtime = module.newRuntime();\n let deadline = Number.POSITIVE_INFINITY;\n runtime.setMemoryLimit(memoryLimitBytes);\n const context = runtime.newContext();\n\n try {\n injectConsole(context, logs);\n injectProviders(\n context,\n request.providers,\n signal,\n trustedHostErrorKey,\n request.onToolCall,\n );\n const executionStartedAt = Date.now();\n deadline = executionStartedAt + timeoutMs;\n const shouldInterrupt = shouldInterruptAfterDeadline(deadline);\n runtime.setInterruptHandler((currentRuntime) => {\n return signal.aborted || shouldInterrupt(currentRuntime);\n });\n request.onStarted?.();\n\n const executableSource = normalizeCode(request.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(\n runtime,\n promiseResult,\n deadline,\n trustedHostErrorKey,\n );\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(\n context,\n errorHandle,\n trustedHostErrorKey,\n ),\n logs: truncateLogs(logs, maxLogLines, 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, maxLogLines, 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, maxLogLines, 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, maxLogLines, maxLogChars),\n ok: false,\n };\n } finally {\n request.abortController?.abort();\n abortController.abort();\n context.dispose();\n runtime.dispose();\n }\n}\n"],"mappings":";;;;;;;;AAQA,SAAgB,uBACd,SACA,MACA,SACA,qBACe;CACf,MAAM,cAAc,QAAQ,SAAS;EAAE;EAAS,MAAM;EAAS,CAAC;CAChE,MAAM,aAAa,QAAQ,UAAU,KAAK;CAC1C,MAAM,0BAA0B,QAAQ;AAExC,KAAI;AACF,UAAQ,QAAQ,aAAa,QAAQ,WAAW;AAChD,UAAQ,QAAQ,aAAa,qBAAqB,wBAAwB;AAC1E,SAAO;WACC;AACR,aAAW,SAAS;AACpB,0BAAwB,SAAS;;;;;;AAOrC,SAAgB,gBACd,SACA,QACS;CACT,MAAM,YAAY,QAAQ,OAAO,OAAO;AAExC,KAAI,cAAc,YAChB;AAGF,KACE,cAAc,cACd,cAAc,YACd,cAAc,SAEd,OAAM,IAAI,eACR,uBACA,+CACD;CAGH,MAAM,aAAa,QAAQ,QAAQ,QAAQ,QAAQ,OAAO;CAC1D,MAAM,kBAAkB,QAAQ,Q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gBAAgB,SAAS,cAAc,MAAM;AAE3D,YAAO;MACL,YAAY,KAAK,KAAK,GAAG;MACzB,MAAM,aAAa,MAAM,aAAa,YAAY;MAClD,IAAI;MACJ,QAAQ;MACT;aACM,OAAO;AACd,YAAO;MACL,YAAY,KAAK,KAAK,GAAG;MACzB,OAAO,eAAe,OAAO,SAAS;MACtC,MAAM,aAAa,MAAM,aAAa,YAAY;MAClD,IAAI;MACL;cACO;AACR,mBAAc,MAAM,SAAS;;aAEvB;AACR,kBAAc,SAAS;;YAEjB;AACR,kBAAe,SAAS;;UAEnB,OAAO;AACd,kBAAgB,OAAO;AAEvB,SAAO;GACL,YAAY,KAAK,KAAK,GAAG;GACzB,OAAO,eAAe,OAAO,SAAS;GACtC,MAAM,aAAa,MAAM,aAAa,YAAY;GAClD,IAAI;GACL;WACO;AACR,UAAQ,iBAAiB,OAAO;AAChC,kBAAgB,OAAO;AACvB,UAAQ,SAAS;AACjB,UAAQ,SAAS"}
@@ -9,9 +9,9 @@ import { ExecutorPoolOptions, ExecutorRuntimeOptions } from "@execbox/core";
9
9
  /**
10
10
  * Host boundary options available to the QuickJS executor.
11
11
  */
12
- type QuickJsExecutorHost = "inline" | "worker" | "process";
12
+ type QuickJsExecutorHost = "inline" | "worker";
13
13
  /**
14
- * Lifecycle modes for hosted QuickJS shells.
14
+ * Lifecycle modes for worker-hosted QuickJS shells.
15
15
  */
16
16
  type QuickJsHostedMode = "pooled" | "ephemeral";
17
17
  /**
@@ -40,32 +40,19 @@ interface QuickJsInlineExecutorOptions extends ExecutorRuntimeOptions {
40
40
  interface QuickJsWorkerExecutorOptions extends ExecutorRuntimeOptions {
41
41
  /** Uses a worker thread to host each QuickJS runtime. */
42
42
  host: "worker";
43
- /** Time to wait before forcefully tearing down a hung hosted shell. */
43
+ /** Time to wait before forcefully tearing down a hung worker shell. */
44
44
  cancelGraceMs?: number;
45
- /** Whether to reuse hosted shells or spawn a fresh one per execution. */
45
+ /** Whether to reuse worker shells or spawn a fresh one per execution. */
46
46
  mode?: QuickJsHostedMode;
47
- /** Pool sizing and idle-eviction settings for pooled hosted shells. */
47
+ /** Pool sizing and idle-eviction settings for pooled worker shells. */
48
48
  pool?: ExecutorPoolOptions;
49
49
  /** Optional worker thread V8 limits used as a coarse safety backstop. */
50
50
  workerResourceLimits?: WorkerResourceLimits;
51
51
  }
52
- /**
53
- * Options for constructing a process-backed QuickJS executor.
54
- */
55
- interface QuickJsProcessExecutorOptions extends ExecutorRuntimeOptions {
56
- /** Uses a child process to host each QuickJS runtime. */
57
- host: "process";
58
- /** Time to wait before forcefully tearing down a hung hosted shell. */
59
- cancelGraceMs?: number;
60
- /** Whether to reuse hosted shells or spawn a fresh one per execution. */
61
- mode?: QuickJsHostedMode;
62
- /** Pool sizing and idle-eviction settings for pooled hosted shells. */
63
- pool?: ExecutorPoolOptions;
64
- }
65
52
  /**
66
53
  * Options for constructing a QuickJS executor.
67
54
  */
68
- type QuickJsExecutorOptions = QuickJsInlineExecutorOptions | QuickJsWorkerExecutorOptions | QuickJsProcessExecutorOptions;
55
+ type QuickJsExecutorOptions = QuickJsInlineExecutorOptions | QuickJsWorkerExecutorOptions;
69
56
  //#endregion
70
- export { QuickJsProcessExecutorOptions as a, QuickJsInlineExecutorOptions as i, QuickJsExecutorOptions as n, QuickJsWorkerExecutorOptions as o, QuickJsHostedMode as r, WorkerResourceLimits as s, QuickJsExecutorHost as t };
71
- //# sourceMappingURL=types-BeVqrcj8.d.ts.map
57
+ export { QuickJsWorkerExecutorOptions as a, QuickJsInlineExecutorOptions as i, QuickJsExecutorOptions as n, WorkerResourceLimits as o, QuickJsHostedMode as r, QuickJsExecutorHost as t };
58
+ //# sourceMappingURL=types-C-XfFJ7u.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-C-XfFJ7u.d.cts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;AAQA,CAAA,CAAA;AAKY,IAAA,CALA,mBAAA,CAAA,CAAA,CAKiB,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA;AAK7B,CAAA,CAAA;AAYA,CAAA,CAAA,CAAA,SAAA,CAAA,KAAA,CAAA,GAAA,CAAA,MAAA,CAAA,MAAA,CAAA,OAAA,CAAA,MAAA;AAWA,CAAA,CAAA;AAQS,IAAA,CApCG,iBAAA,CAAA,CAAA,CAoCH,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,SAAA,CAAA;;;;AARmE,SAAA,CAvB3D,oBAAA,CAuB2D;EAoBhE,CAAA,CAAA,CAAA,CAAA,OAAA,CAAA,IAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,UAAA,CAAA,IAAA,CAAA,EAAA,CAAA,SAAA,CAAA,CAAA,CAAA;;;;;;;;;;UA/BK,4BAAA,CAAA,OAAA,CAAqC;;;;qBAKjC;;;;;UAMJ,4BAAA,CAAA,OAAA,CAAqC;;;;;;SAQ7C;;SAGA;;yBAGgB;;;;;KAMb,sBAAA,CAAA,CAAA,CACR,+BACA"}
@@ -9,9 +9,9 @@ import { ExecutorPoolOptions, ExecutorRuntimeOptions } from "@execbox/core";
9
9
  /**
10
10
  * Host boundary options available to the QuickJS executor.
11
11
  */
12
- type QuickJsExecutorHost = "inline" | "worker" | "process";
12
+ type QuickJsExecutorHost = "inline" | "worker";
13
13
  /**
14
- * Lifecycle modes for hosted QuickJS shells.
14
+ * Lifecycle modes for worker-hosted QuickJS shells.
15
15
  */
16
16
  type QuickJsHostedMode = "pooled" | "ephemeral";
17
17
  /**
@@ -40,32 +40,19 @@ interface QuickJsInlineExecutorOptions extends ExecutorRuntimeOptions {
40
40
  interface QuickJsWorkerExecutorOptions extends ExecutorRuntimeOptions {
41
41
  /** Uses a worker thread to host each QuickJS runtime. */
42
42
  host: "worker";
43
- /** Time to wait before forcefully tearing down a hung hosted shell. */
43
+ /** Time to wait before forcefully tearing down a hung worker shell. */
44
44
  cancelGraceMs?: number;
45
- /** Whether to reuse hosted shells or spawn a fresh one per execution. */
45
+ /** Whether to reuse worker shells or spawn a fresh one per execution. */
46
46
  mode?: QuickJsHostedMode;
47
- /** Pool sizing and idle-eviction settings for pooled hosted shells. */
47
+ /** Pool sizing and idle-eviction settings for pooled worker shells. */
48
48
  pool?: ExecutorPoolOptions;
49
49
  /** Optional worker thread V8 limits used as a coarse safety backstop. */
50
50
  workerResourceLimits?: WorkerResourceLimits;
51
51
  }
52
- /**
53
- * Options for constructing a process-backed QuickJS executor.
54
- */
55
- interface QuickJsProcessExecutorOptions extends ExecutorRuntimeOptions {
56
- /** Uses a child process to host each QuickJS runtime. */
57
- host: "process";
58
- /** Time to wait before forcefully tearing down a hung hosted shell. */
59
- cancelGraceMs?: number;
60
- /** Whether to reuse hosted shells or spawn a fresh one per execution. */
61
- mode?: QuickJsHostedMode;
62
- /** Pool sizing and idle-eviction settings for pooled hosted shells. */
63
- pool?: ExecutorPoolOptions;
64
- }
65
52
  /**
66
53
  * Options for constructing a QuickJS executor.
67
54
  */
68
- type QuickJsExecutorOptions = QuickJsInlineExecutorOptions | QuickJsWorkerExecutorOptions | QuickJsProcessExecutorOptions;
55
+ type QuickJsExecutorOptions = QuickJsInlineExecutorOptions | QuickJsWorkerExecutorOptions;
69
56
  //#endregion
70
- export { QuickJsProcessExecutorOptions as a, QuickJsInlineExecutorOptions as i, QuickJsExecutorOptions as n, QuickJsWorkerExecutorOptions as o, QuickJsHostedMode as r, WorkerResourceLimits as s, QuickJsExecutorHost as t };
71
- //# sourceMappingURL=types-CnNmLawC.d.cts.map
57
+ export { QuickJsWorkerExecutorOptions as a, QuickJsInlineExecutorOptions as i, QuickJsExecutorOptions as n, WorkerResourceLimits as o, QuickJsHostedMode as r, QuickJsExecutorHost as t };
58
+ //# sourceMappingURL=types-CE7SvejR.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-CE7SvejR.d.ts","names":[],"sources":["../src/types.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;AAQA,CAAA,CAAA;AAKY,IAAA,CALA,mBAAA,CAAA,CAAA,CAKiB,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,MAAA,CAAA;AAK7B,CAAA,CAAA;AAYA,CAAA,CAAA,CAAA,SAAA,CAAA,KAAA,CAAA,GAAA,CAAA,MAAA,CAAA,MAAA,CAAA,OAAA,CAAA,MAAA;AAWA,CAAA,CAAA;AAQS,IAAA,CApCG,iBAAA,CAAA,CAAA,CAoCH,CAAA,MAAA,CAAA,CAAA,CAAA,CAAA,CAAA,SAAA,CAAA;;;;AARmE,SAAA,CAvB3D,oBAAA,CAuB2D;EAoBhE,CAAA,CAAA,CAAA,CAAA,OAAA,CAAA,IAAA,CAAA,EAAA,CAAA,GAAA,CAAA,GAAA,CAAA,UAAA,CAAA,IAAA,CAAA,EAAA,CAAA,SAAA,CAAA,CAAA,CAAA;;;;;;;;;;UA/BK,4BAAA,CAAA,OAAA,CAAqC;;;;qBAKjC;;;;;UAMJ,4BAAA,CAAA,OAAA,CAAqC;;;;;;SAQ7C;;SAGA;;yBAGgB;;;;;KAMb,sBAAA,CAAA,CAAA,CACR,+BACA"}
@@ -1,5 +1,5 @@
1
- require('./runner-DRt0kpEk.cjs');
2
- const require_protocolEndpoint = require('./protocolEndpoint-DGOUVf6J.cjs');
1
+ require('./runner-DRLfwiqY.cjs');
2
+ const require_protocolEndpoint = require('./protocolEndpoint-BGyrwlr_.cjs');
3
3
  let node_worker_threads = require("node:worker_threads");
4
4
 
5
5
  //#region src/workerEntry.ts
@@ -1,5 +1,5 @@
1
- import "./runner-CteKTaPD.js";
2
- import { t as attachQuickJsProtocolEndpoint } from "./protocolEndpoint-T_JEz8YY.js";
1
+ import "./runner-oZXbguX3.js";
2
+ import { t as attachQuickJsProtocolEndpoint } from "./protocolEndpoint-Ceadcq_L.js";
3
3
  import { parentPort } from "node:worker_threads";
4
4
 
5
5
  //#region src/workerEntry.ts
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@execbox/quickjs",
3
- "version": "0.4.0",
4
- "description": "QuickJS executor for the execbox core package across inline, worker, and process hosts.",
3
+ "version": "0.6.0",
4
+ "description": "QuickJS executor for the execbox core package across inline and worker hosts.",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "engines": {
@@ -37,6 +37,15 @@
37
37
  },
38
38
  "import": "./dist/runner/protocolEndpoint.js",
39
39
  "require": "./dist/runner/protocolEndpoint.cjs"
40
+ },
41
+ "./remote-endpoint": {
42
+ "source": "./src/remoteEndpoint.ts",
43
+ "types": {
44
+ "import": "./dist/remoteEndpoint.d.ts",
45
+ "require": "./dist/remoteEndpoint.d.cts"
46
+ },
47
+ "import": "./dist/remoteEndpoint.js",
48
+ "require": "./dist/remoteEndpoint.cjs"
40
49
  }
41
50
  },
42
51
  "sideEffects": false,
@@ -63,7 +72,7 @@
63
72
  "homepage": "https://github.com/aallam/execbox/tree/main/packages/quickjs#readme",
64
73
  "bugs": "https://github.com/aallam/execbox/issues",
65
74
  "dependencies": {
66
- "@execbox/core": "^0.4.0",
75
+ "@execbox/core": "^0.5.0",
67
76
  "quickjs-emscripten": "^0.31.0"
68
77
  }
69
78
  }
@@ -1,17 +0,0 @@
1
- require('./runner-DRt0kpEk.cjs');
2
- const require_protocolEndpoint = require('./protocolEndpoint-DGOUVf6J.cjs');
3
-
4
- //#region src/processEntry.ts
5
- if (typeof process.send !== "function") throw new Error("QuickJsExecutor process host requires a child process IPC channel");
6
- require_protocolEndpoint.attachQuickJsProtocolEndpoint({
7
- onMessage(handler) {
8
- process.on("message", handler);
9
- return () => process.off("message", handler);
10
- },
11
- send(message) {
12
- process.send?.(message);
13
- }
14
- });
15
-
16
- //#endregion
17
- //# sourceMappingURL=processEntry.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"processEntry.cjs","names":["attachQuickJsProtocolEndpoint"],"sources":["../src/processEntry.ts"],"sourcesContent":["import type { DispatcherMessage, RunnerMessage } from \"@execbox/core/protocol\";\n\nimport { attachQuickJsProtocolEndpoint } from \"./runner/protocolEndpoint.ts\";\n\nif (typeof process.send !== \"function\") {\n throw new Error(\n \"QuickJsExecutor process host requires a child process IPC channel\",\n );\n}\n\nattachQuickJsProtocolEndpoint({\n onMessage(handler: (message: DispatcherMessage) => void): () => void {\n process.on(\"message\", handler);\n return () => process.off(\"message\", handler);\n },\n send(message: RunnerMessage): void {\n process.send?.(message);\n },\n});\n"],"mappings":";;;;AAIA,IAAI,OAAO,QAAQ,SAAS,WAC1B,OAAM,IAAI,MACR,oEACD;AAGHA,uDAA8B;CAC5B,UAAU,SAA2D;AACnE,UAAQ,GAAG,WAAW,QAAQ;AAC9B,eAAa,QAAQ,IAAI,WAAW,QAAQ;;CAE9C,KAAK,SAA8B;AACjC,UAAQ,OAAO,QAAQ;;CAE1B,CAAC"}
@@ -1,5 +0,0 @@
1
- /**
2
- * @packageDocumentation
3
- * Public TypeScript declarations for this package entrypoint.
4
- */
5
- export { };
@@ -1,5 +0,0 @@
1
- /**
2
- * @packageDocumentation
3
- * Public TypeScript declarations for this package entrypoint.
4
- */
5
- export { };
@@ -1,18 +0,0 @@
1
- import "./runner-CteKTaPD.js";
2
- import { t as attachQuickJsProtocolEndpoint } from "./protocolEndpoint-T_JEz8YY.js";
3
-
4
- //#region src/processEntry.ts
5
- if (typeof process.send !== "function") throw new Error("QuickJsExecutor process host requires a child process IPC channel");
6
- attachQuickJsProtocolEndpoint({
7
- onMessage(handler) {
8
- process.on("message", handler);
9
- return () => process.off("message", handler);
10
- },
11
- send(message) {
12
- process.send?.(message);
13
- }
14
- });
15
-
16
- //#endregion
17
- export { };
18
- //# sourceMappingURL=processEntry.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"processEntry.js","names":[],"sources":["../src/processEntry.ts"],"sourcesContent":["import type { DispatcherMessage, RunnerMessage } from \"@execbox/core/protocol\";\n\nimport { attachQuickJsProtocolEndpoint } from \"./runner/protocolEndpoint.ts\";\n\nif (typeof process.send !== \"function\") {\n throw new Error(\n \"QuickJsExecutor process host requires a child process IPC channel\",\n );\n}\n\nattachQuickJsProtocolEndpoint({\n onMessage(handler: (message: DispatcherMessage) => void): () => void {\n process.on(\"message\", handler);\n return () => process.off(\"message\", handler);\n },\n send(message: RunnerMessage): void {\n process.send?.(message);\n },\n});\n"],"mappings":";;;;AAIA,IAAI,OAAO,QAAQ,SAAS,WAC1B,OAAM,IAAI,MACR,oEACD;AAGH,8BAA8B;CAC5B,UAAU,SAA2D;AACnE,UAAQ,GAAG,WAAW,QAAQ;AAC9B,eAAa,QAAQ,IAAI,WAAW,QAAQ;;CAE9C,KAAK,SAA8B;AACjC,UAAQ,OAAO,QAAQ;;CAE1B,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"protocolEndpoint-DGOUVf6J.cjs","names":["activeAbortController: AbortController | undefined","activeExecutionId: string | undefined","runQuickJsSession"],"sources":["../../core/src/protocol/messages.ts","../src/runner/protocolEndpoint.ts"],"sourcesContent":["import type {\n ExecutorRuntimeOptions,\n ProviderManifest,\n ToolCall,\n ToolCallResult,\n} from \"../runner.ts\";\nimport type { ExecuteResult } from \"../types.ts\";\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction isRuntimeOptions(value: unknown): value is ExecutorRuntimeOptions {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n isFiniteNumber(value.maxLogChars) &&\n isFiniteNumber(value.maxLogLines) &&\n isFiniteNumber(value.memoryLimitBytes) &&\n isFiniteNumber(value.timeoutMs)\n );\n}\n\nfunction isProviderManifest(value: unknown): value is ProviderManifest {\n if (!isRecord(value) || typeof value.name !== \"string\") {\n return false;\n }\n\n if (!isRecord(value.tools) || typeof value.types !== \"string\") {\n return false;\n }\n\n return Object.values(value.tools).every(\n (tool) =>\n isRecord(tool) &&\n typeof tool.originalName === \"string\" &&\n typeof tool.safeName === \"string\" &&\n (tool.description === undefined || typeof tool.description === \"string\"),\n );\n}\n\nfunction isExecuteError(\n value: unknown,\n): value is { code: string; message: string } {\n return (\n isRecord(value) &&\n typeof value.code === \"string\" &&\n typeof value.message === \"string\"\n );\n}\n\nfunction isDonePayload(value: unknown): value is DoneMessage {\n if (!isRecord(value) || !isFiniteNumber(value.durationMs)) {\n return false;\n }\n\n if (\n !Array.isArray(value.logs) ||\n !value.logs.every((log) => typeof log === \"string\")\n ) {\n return false;\n }\n\n if (typeof value.ok !== \"boolean\") {\n return false;\n }\n\n return value.ok ? true : isExecuteError(value.error);\n}\n\n/**\n * Message sent from dispatcher to runner to start one execution session.\n */\nexport interface ExecuteMessage {\n code: string;\n id: string;\n options: ExecutorRuntimeOptions;\n providers: ProviderManifest[];\n type: \"execute\";\n}\n\n/**\n * Message sent from dispatcher to request prompt cancellation.\n */\nexport interface CancelMessage {\n id: string;\n type: \"cancel\";\n}\n\n/**\n * Message sent from a runner when guest code invokes a host tool.\n */\nexport interface ToolCallMessage extends ToolCall {\n callId: string;\n type: \"tool_call\";\n}\n\n/**\n * Message carrying a trusted host tool result back to the runner.\n */\nexport type ToolResultMessage = {\n callId: string;\n type: \"tool_result\";\n} & ToolCallResult;\n\n/**\n * Message indicating the runner has finished bootstrapping guest execution timing.\n */\nexport interface StartedMessage {\n id: string;\n type: \"started\";\n}\n\n/**\n * Final successful execution result returned by a runner.\n *\n * Node IPC can omit `undefined` fields during serialization, so `result`\n * remains optional at the protocol boundary and is normalized by the host.\n */\nexport type DoneSuccessMessage<T = unknown> = {\n durationMs: number;\n id: string;\n logs: string[];\n ok: true;\n result?: T;\n type: \"done\";\n};\n\n/**\n * Final failed execution result returned by a runner.\n */\nexport type DoneFailureMessage = {\n id: string;\n type: \"done\";\n} & Extract<ExecuteResult, { ok: false }>;\n\n/**\n * Final execution result returned by a runner.\n */\nexport type DoneMessage = DoneSuccessMessage | DoneFailureMessage;\n\n/**\n * Messages accepted by a runner transport endpoint.\n */\nexport type DispatcherMessage =\n | CancelMessage\n | ExecuteMessage\n | ToolResultMessage;\n\n/**\n * Messages emitted by a runner transport endpoint.\n */\nexport type RunnerMessage = DoneMessage | StartedMessage | ToolCallMessage;\n\n/**\n * Returns whether an unknown value is a dispatcher-to-runner message.\n */\nexport function isDispatcherMessage(\n value: unknown,\n): value is DispatcherMessage {\n if (!isRecord(value) || typeof value.type !== \"string\") {\n return false;\n }\n\n switch (value.type) {\n case \"cancel\":\n return typeof value.id === \"string\";\n case \"execute\":\n return (\n typeof value.code === \"string\" &&\n typeof value.id === \"string\" &&\n isRuntimeOptions(value.options) &&\n Array.isArray(value.providers) &&\n value.providers.every(isProviderManifest)\n );\n case \"tool_result\":\n if (typeof value.callId !== \"string\" || typeof value.ok !== \"boolean\") {\n return false;\n }\n\n if (value.ok) {\n return \"result\" in value;\n }\n\n return isExecuteError(value.error);\n default:\n return false;\n }\n}\n\n/**\n * Returns whether an unknown value is a runner-to-dispatcher message.\n */\nexport function isRunnerMessage(value: unknown): value is RunnerMessage {\n if (!isRecord(value) || typeof value.type !== \"string\") {\n return false;\n }\n\n switch (value.type) {\n case \"started\":\n return typeof value.id === \"string\";\n case \"tool_call\":\n return (\n typeof value.callId === \"string\" &&\n typeof value.providerName === \"string\" &&\n typeof value.safeToolName === \"string\" &&\n \"input\" in value\n );\n case \"done\":\n return typeof value.id === \"string\" && isDonePayload(value);\n default:\n return false;\n }\n}\n","/**\n * @packageDocumentation\n * Public API for the `@execbox/quickjs/runner/protocol-endpoint` entrypoint.\n */\nimport { randomUUID } from \"node:crypto\";\n\nimport type {\n DispatcherMessage,\n ExecuteMessage,\n RunnerMessage,\n} from \"@execbox/core/protocol\";\nimport type { ToolCallResult } from \"@execbox/core\";\n// This entrypoint is executed directly from source in worker/process tests before\n// workspace packages are built, so its runtime validator must stay source-local.\nimport { isDispatcherMessage } from \"../../../core/src/protocol/messages.ts\";\n\nimport { runQuickJsSession } from \"./index.ts\";\n\n/**\n * Minimal worker/process-side port used by the shared QuickJS protocol endpoint.\n */\nexport interface QuickJsProtocolPort {\n onMessage(handler: (message: DispatcherMessage) => void): void | (() => void);\n send(message: RunnerMessage): void;\n}\n\n/**\n * Attaches the shared QuickJS protocol loop to a worker/process messaging port.\n */\nexport function attachQuickJsProtocolEndpoint(\n port: QuickJsProtocolPort,\n): () => void {\n const pendingToolCalls = new Map<string, (result: ToolCallResult) => void>();\n let activeAbortController: AbortController | undefined;\n let activeExecutionId: string | undefined;\n\n async function startExecution(message: ExecuteMessage): Promise<void> {\n if (activeExecutionId) {\n port.send({\n durationMs: 0,\n error: {\n code: \"internal_error\",\n message: \"QuickJS endpoint already has an active execution\",\n },\n id: message.id,\n logs: [],\n ok: false,\n type: \"done\",\n });\n return;\n }\n\n const abortController = new AbortController();\n activeAbortController = abortController;\n activeExecutionId = message.id;\n\n try {\n const result = await runQuickJsSession(\n {\n abortController,\n code: message.code,\n onStarted: () => {\n port.send({\n id: message.id,\n type: \"started\",\n });\n },\n onToolCall: (call) =>\n new Promise<ToolCallResult>((resolve) => {\n const callId = randomUUID();\n pendingToolCalls.set(callId, resolve);\n port.send({\n ...call,\n callId,\n type: \"tool_call\",\n });\n }),\n providers: message.providers,\n },\n message.options,\n );\n\n port.send({\n ...result,\n id: message.id,\n type: \"done\",\n });\n } catch (error) {\n port.send({\n durationMs: 0,\n error: {\n code: \"internal_error\",\n message: error instanceof Error ? error.message : String(error),\n },\n id: message.id,\n logs: [],\n ok: false,\n type: \"done\",\n });\n } finally {\n pendingToolCalls.clear();\n activeAbortController = undefined;\n activeExecutionId = undefined;\n }\n }\n\n const maybeDetach = port.onMessage((message: DispatcherMessage) => {\n if (!isDispatcherMessage(message)) {\n return;\n }\n\n switch (message.type) {\n case \"cancel\":\n if (message.id === activeExecutionId) {\n activeAbortController?.abort();\n }\n break;\n case \"execute\":\n void startExecution(message);\n break;\n case \"tool_result\": {\n const resolve = pendingToolCalls.get(message.callId);\n pendingToolCalls.delete(message.callId);\n resolve?.(message);\n break;\n }\n }\n });\n\n return () => {\n if (typeof maybeDetach === \"function\") {\n maybeDetach();\n }\n pendingToolCalls.clear();\n activeAbortController?.abort();\n activeAbortController = undefined;\n activeExecutionId = undefined;\n };\n}\n"],"mappings":";;;;AAQA,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU;;AAGhD,SAAS,eAAe,OAAiC;AACvD,QAAO,OAAO,UAAU,YAAY,OAAO,SAAS,MAAM;;AAG5D,SAAS,iBAAiB,OAAiD;AACzE,KAAI,CAAC,SAAS,MAAM,CAClB,QAAO;AAGT,QACE,eAAe,MAAM,YAAY,IACjC,eAAe,MAAM,YAAY,IACjC,eAAe,MAAM,iBAAiB,IACtC,eAAe,MAAM,UAAU;;AAInC,SAAS,mBAAmB,OAA2C;AACrE,KAAI,CAAC,SAAS,MAAM,IAAI,OAAO,MAAM,SAAS,SAC5C,QAAO;AAGT,KAAI,CAAC,SAAS,MAAM,MAAM,IAAI,OAAO,MAAM,UAAU,SACnD,QAAO;AAGT,QAAO,OAAO,OAAO,MAAM,MAAM,CAAC,OAC/B,SACC,SAAS,KAAK,IACd,OAAO,KAAK,iBAAiB,YAC7B,OAAO,KAAK,aAAa,aACxB,KAAK,gBAAgB,UAAa,OAAO,KAAK,gBAAgB,UAClE;;AAGH,SAAS,eACP,OAC4C;AAC5C,QACE,SAAS,MAAM,IACf,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,YAAY;;;;;AA8G7B,SAAgB,oBACd,OAC4B;AAC5B,KAAI,CAAC,SAAS,MAAM,IAAI,OAAO,MAAM,SAAS,SAC5C,QAAO;AAGT,SAAQ,MAAM,MAAd;EACE,KAAK,SACH,QAAO,OAAO,MAAM,OAAO;EAC7B,KAAK,UACH,QACE,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,OAAO,YACpB,iBAAiB,MAAM,QAAQ,IAC/B,MAAM,QAAQ,MAAM,UAAU,IAC9B,MAAM,UAAU,MAAM,mBAAmB;EAE7C,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