@zackbart/connecta 0.7.1 → 0.7.4
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/CHANGELOG.md +122 -0
- package/README.md +5 -2
- package/dist/connector-scope.d.ts +7 -4
- package/dist/connector-scope.d.ts.map +1 -1
- package/dist/connector-scope.js +36 -16
- package/dist/connector-scope.js.map +1 -1
- package/dist/connectors/remote-mcp.d.ts.map +1 -1
- package/dist/connectors/remote-mcp.js +164 -95
- package/dist/connectors/remote-mcp.js.map +1 -1
- package/dist/credential-health.d.ts +11 -7
- package/dist/credential-health.d.ts.map +1 -1
- package/dist/credential-health.js +26 -19
- package/dist/credential-health.js.map +1 -1
- package/dist/execute.d.ts +3 -0
- package/dist/execute.d.ts.map +1 -1
- package/dist/execute.js +70 -29
- package/dist/execute.js.map +1 -1
- package/dist/executor-admission.d.ts +53 -0
- package/dist/executor-admission.d.ts.map +1 -0
- package/dist/executor-admission.js +151 -0
- package/dist/executor-admission.js.map +1 -0
- package/dist/executor-result.d.ts +13 -0
- package/dist/executor-result.d.ts.map +1 -0
- package/dist/executor-result.js +57 -0
- package/dist/executor-result.js.map +1 -0
- package/dist/executors/quickjs-child.d.ts +2 -0
- package/dist/executors/quickjs-child.d.ts.map +1 -0
- package/dist/executors/quickjs-child.js +131 -0
- package/dist/executors/quickjs-child.js.map +1 -0
- package/dist/executors/quickjs-protocol.d.ts +55 -0
- package/dist/executors/quickjs-protocol.d.ts.map +1 -0
- package/dist/executors/quickjs-protocol.js +22 -0
- package/dist/executors/quickjs-protocol.js.map +1 -0
- package/dist/executors/quickjs-runtime.d.ts +26 -0
- package/dist/executors/quickjs-runtime.d.ts.map +1 -0
- package/dist/executors/quickjs-runtime.js +383 -0
- package/dist/executors/quickjs-runtime.js.map +1 -0
- package/dist/executors/quickjs.d.ts +20 -15
- package/dist/executors/quickjs.d.ts.map +1 -1
- package/dist/executors/quickjs.js +465 -265
- package/dist/executors/quickjs.js.map +1 -1
- package/dist/index.d.ts +15 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -1
- package/dist/meta-tools.d.ts +4 -0
- package/dist/meta-tools.d.ts.map +1 -1
- package/dist/meta-tools.js +49 -12
- package/dist/meta-tools.js.map +1 -1
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +36 -3
- package/dist/node.js.map +1 -1
- package/dist/registry.d.ts +21 -24
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +37 -25
- package/dist/registry.js.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +19 -9
- package/dist/server.js.map +1 -1
- package/dist/timeout.d.ts +9 -4
- package/dist/timeout.d.ts.map +1 -1
- package/dist/timeout.js +34 -4
- package/dist/timeout.js.map +1 -1
- package/dist/toolkits.d.ts +8 -0
- package/dist/toolkits.d.ts.map +1 -1
- package/dist/toolkits.js +3 -0
- package/dist/toolkits.js.map +1 -1
- package/dist/types.d.ts +19 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/ui.d.ts +13 -1
- package/dist/ui.d.ts.map +1 -1
- package/dist/ui.js +188 -7
- package/dist/ui.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/src/connector-scope.ts +43 -18
- package/src/connectors/remote-mcp.ts +184 -102
- package/src/credential-health.ts +33 -17
- package/src/execute.ts +93 -35
- package/src/executor-admission.ts +229 -0
- package/src/executor-result.ts +63 -0
- package/src/executors/quickjs-child.ts +168 -0
- package/src/executors/quickjs-protocol.ts +77 -0
- package/src/executors/quickjs-runtime.ts +440 -0
- package/src/executors/quickjs.ts +669 -302
- package/src/index.ts +30 -5
- package/src/meta-tools.ts +84 -27
- package/src/node.ts +36 -2
- package/src/registry.ts +53 -22
- package/src/server.ts +21 -10
- package/src/timeout.ts +41 -4
- package/src/toolkits.ts +11 -0
- package/src/types.ts +19 -2
- package/src/ui.ts +218 -12
- package/src/version.ts +1 -1
|
@@ -1,295 +1,495 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
const
|
|
19
|
-
const MAX_LOG_TOTAL_CHARS = 256_000;
|
|
1
|
+
// Node's built-in code-mode executor. QuickJS itself lives in a disposable
|
|
2
|
+
// child process: guest CPU, WASM aborts, and interpreter OOMs cannot block or
|
|
3
|
+
// terminate the HTTP-serving process.
|
|
4
|
+
import { fork } from "node:child_process";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { AdmissionController, ExecutorAdmissionError, } from "../executor-admission.js";
|
|
7
|
+
import { MAX_QUICKJS_IPC_BYTES, MAX_QUICKJS_HOST_RPC_BYTES, serializedBytes, stringifyBounded, } from "./quickjs-protocol.js";
|
|
8
|
+
export { normalizeCode } from "./quickjs-runtime.js";
|
|
9
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
10
|
+
const DEFAULT_CPU_TIME_MS = 250;
|
|
11
|
+
const DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
12
|
+
const DEFAULT_STACK_LIMIT_BYTES = 1024 * 1024;
|
|
13
|
+
const DEFAULT_CONCURRENCY = 1;
|
|
14
|
+
const DEFAULT_MAX_QUEUE_SIZE = 32;
|
|
15
|
+
const DEFAULT_QUEUE_TIMEOUT_MS = 5_000;
|
|
16
|
+
const CHILD_EXIT_GRACE_MS = 250;
|
|
17
|
+
const CHILD_STARTUP_TIMEOUT_MS = 10_000;
|
|
18
|
+
const MAX_ERROR_CHARS = 4_000;
|
|
20
19
|
function msg(err) {
|
|
21
20
|
return err instanceof Error ? err.message : String(err);
|
|
22
21
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
// which would otherwise defeat the detection and wrap the whole thing.
|
|
32
|
-
const head = c.replace(/^(?:\s+|\/\/[^\n]*|\/\*[\s\S]*?\*\/)+/, "");
|
|
33
|
-
if (/^async\b/.test(head) || head.startsWith("("))
|
|
34
|
-
return c;
|
|
35
|
-
return `async () => {\n${c}\n}`;
|
|
22
|
+
function positiveWhole(value, fallback, name) {
|
|
23
|
+
const resolved = value ?? fallback;
|
|
24
|
+
if (!Number.isFinite(resolved) ||
|
|
25
|
+
!Number.isInteger(resolved) ||
|
|
26
|
+
resolved < 1) {
|
|
27
|
+
throw new TypeError(`${name} must be a positive whole number.`);
|
|
28
|
+
}
|
|
29
|
+
return resolved;
|
|
36
30
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
return { log: emit, info: emit, warn: emit, error: emit, debug: emit };
|
|
44
|
-
})();`,
|
|
45
|
-
`globalThis.__invoke = async (ns, fn, args) => {
|
|
46
|
-
const r = JSON.parse(await __call(ns, fn, JSON.stringify(args)));
|
|
47
|
-
if (!r.ok) throw new Error(r.error);
|
|
48
|
-
return r.value;
|
|
49
|
-
};`,
|
|
50
|
-
];
|
|
51
|
-
for (const p of providers) {
|
|
52
|
-
const ns = JSON.stringify(p.name);
|
|
53
|
-
const fields = Object.keys(p.fns).map((fn) => {
|
|
54
|
-
const f = JSON.stringify(fn);
|
|
55
|
-
// Forward every argument verbatim, positionally — same as codemode's
|
|
56
|
-
// sandbox proxy (`(...args) => call(fn, args)`). The host wrappers in
|
|
57
|
-
// buildSandboxProviders already guard the no-arg case, so no coercion.
|
|
58
|
-
return ` [${f}]: (...a) => __invoke(${ns}, ${f}, a),`;
|
|
59
|
-
});
|
|
60
|
-
lines.push(`globalThis[${ns}] = Object.freeze({\n${fields.join("\n")}\n});`);
|
|
31
|
+
function nonNegativeWhole(value, fallback, name) {
|
|
32
|
+
const resolved = value ?? fallback;
|
|
33
|
+
if (!Number.isFinite(resolved) ||
|
|
34
|
+
!Number.isInteger(resolved) ||
|
|
35
|
+
resolved < 0) {
|
|
36
|
+
throw new TypeError(`${name} must be a non-negative whole number.`);
|
|
61
37
|
}
|
|
62
|
-
return
|
|
38
|
+
return resolved;
|
|
63
39
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
return e.name === "InternalError" && e.message === "interrupted";
|
|
40
|
+
function errorPayload(error) {
|
|
41
|
+
return JSON.stringify({
|
|
42
|
+
ok: false,
|
|
43
|
+
error: error.slice(0, MAX_ERROR_CHARS),
|
|
44
|
+
});
|
|
70
45
|
}
|
|
71
|
-
function
|
|
72
|
-
if (
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
|
|
46
|
+
function delay(ms, signal) {
|
|
47
|
+
if (ms <= 0)
|
|
48
|
+
return Promise.resolve();
|
|
49
|
+
return new Promise((resolve, reject) => {
|
|
50
|
+
const timer = setTimeout(() => {
|
|
51
|
+
signal?.removeEventListener("abort", onAbort);
|
|
52
|
+
resolve();
|
|
53
|
+
}, ms);
|
|
54
|
+
const onAbort = () => {
|
|
55
|
+
clearTimeout(timer);
|
|
56
|
+
signal?.removeEventListener("abort", onAbort);
|
|
57
|
+
reject(new ExecutorAdmissionError("executor_cancelled", "Execution was cancelled while the sandbox was restarting."));
|
|
58
|
+
};
|
|
59
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
60
|
+
if (signal?.aborted)
|
|
61
|
+
onAbort();
|
|
62
|
+
});
|
|
81
63
|
}
|
|
82
|
-
function
|
|
83
|
-
|
|
84
|
-
|
|
64
|
+
function waitForReady(ready, signal) {
|
|
65
|
+
if (!signal)
|
|
66
|
+
return ready;
|
|
67
|
+
return new Promise((resolve, reject) => {
|
|
68
|
+
let settled = false;
|
|
69
|
+
const finish = (operation) => {
|
|
70
|
+
if (settled)
|
|
71
|
+
return;
|
|
72
|
+
settled = true;
|
|
73
|
+
signal.removeEventListener("abort", onAbort);
|
|
74
|
+
operation();
|
|
75
|
+
};
|
|
76
|
+
const onAbort = () => finish(() => reject(new ExecutorAdmissionError("executor_cancelled", "Execution was cancelled while the sandbox was starting.")));
|
|
77
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
78
|
+
if (signal.aborted) {
|
|
79
|
+
onAbort();
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
void ready.then(() => finish(resolve), (error) => finish(() => reject(error instanceof Error ? error : new Error(String(error)))));
|
|
85
83
|
});
|
|
86
84
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
85
|
+
class QuickJsChildPool {
|
|
86
|
+
admission;
|
|
87
|
+
slots;
|
|
88
|
+
available;
|
|
89
|
+
runtimeOptions;
|
|
90
|
+
closed = false;
|
|
91
|
+
nextJobId = 1;
|
|
92
|
+
constructor(options) {
|
|
93
|
+
const concurrency = positiveWhole(options.concurrency, DEFAULT_CONCURRENCY, "concurrency");
|
|
94
|
+
const queueTimeoutMs = positiveWhole(options.queueTimeoutMs, DEFAULT_QUEUE_TIMEOUT_MS, "queueTimeoutMs");
|
|
95
|
+
this.admission = new AdmissionController({
|
|
96
|
+
concurrency,
|
|
97
|
+
maxQueueSize: nonNegativeWhole(options.maxQueueSize, DEFAULT_MAX_QUEUE_SIZE, "maxQueueSize"),
|
|
98
|
+
queueTimeoutMs,
|
|
99
|
+
retryAfterMs: queueTimeoutMs,
|
|
100
|
+
});
|
|
101
|
+
this.runtimeOptions = {
|
|
102
|
+
timeoutMs: positiveWhole(options.timeoutMs, DEFAULT_TIMEOUT_MS, "timeoutMs"),
|
|
103
|
+
cpuTimeMs: positiveWhole(options.cpuTimeMs, DEFAULT_CPU_TIME_MS, "cpuTimeMs"),
|
|
104
|
+
memoryLimitBytes: positiveWhole(options.memoryLimitBytes, DEFAULT_MEMORY_LIMIT_BYTES, "memoryLimitBytes"),
|
|
105
|
+
maxStackSizeBytes: positiveWhole(options.maxStackSizeBytes, DEFAULT_STACK_LIMIT_BYTES, "maxStackSizeBytes"),
|
|
106
|
+
};
|
|
107
|
+
this.slots = Array.from({ length: concurrency }, () => ({
|
|
108
|
+
consecutiveCrashes: 0,
|
|
109
|
+
notBefore: 0,
|
|
110
|
+
}));
|
|
111
|
+
this.available = [...this.slots];
|
|
112
|
+
}
|
|
113
|
+
async acquire(options = {}) {
|
|
114
|
+
const admission = await this.admission.acquire(options);
|
|
115
|
+
const slot = this.available.shift();
|
|
116
|
+
if (!slot) {
|
|
117
|
+
admission.release();
|
|
118
|
+
throw new Error("Executor admission invariant failed: no child slot.");
|
|
119
|
+
}
|
|
120
|
+
let released = false;
|
|
121
|
+
let executed = false;
|
|
122
|
+
return {
|
|
123
|
+
execute: async (code, providers) => {
|
|
124
|
+
if (released)
|
|
125
|
+
throw new Error("Executor lease was already released.");
|
|
126
|
+
if (executed)
|
|
127
|
+
throw new Error("Executor lease may execute only once.");
|
|
128
|
+
executed = true;
|
|
129
|
+
return this.run(slot, code, providers, options.signal);
|
|
130
|
+
},
|
|
131
|
+
release: () => {
|
|
132
|
+
if (released)
|
|
133
|
+
return;
|
|
134
|
+
released = true;
|
|
135
|
+
if (slot.active) {
|
|
136
|
+
this.rejectActive(slot, new Error("Executor lease was released during execution."));
|
|
137
|
+
this.recycle(slot);
|
|
138
|
+
}
|
|
139
|
+
this.available.push(slot);
|
|
140
|
+
admission.release();
|
|
141
|
+
},
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
async execute(code, providers) {
|
|
145
|
+
const lease = await this.acquire();
|
|
146
|
+
try {
|
|
147
|
+
return await lease.execute(code, providers);
|
|
148
|
+
}
|
|
149
|
+
finally {
|
|
150
|
+
lease.release();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
async close() {
|
|
154
|
+
if (this.closed)
|
|
155
|
+
return;
|
|
156
|
+
this.closed = true;
|
|
157
|
+
this.admission.close();
|
|
158
|
+
const exits = this.slots.map((slot) => this.stopSlot(slot));
|
|
159
|
+
await Promise.allSettled(exits);
|
|
160
|
+
}
|
|
161
|
+
async run(slot, code, providers, signal) {
|
|
162
|
+
if (signal?.aborted) {
|
|
163
|
+
throw new ExecutorAdmissionError("executor_cancelled", "Execution was cancelled before it started.");
|
|
164
|
+
}
|
|
165
|
+
await this.ensureChild(slot, signal);
|
|
166
|
+
if (signal?.aborted) {
|
|
167
|
+
throw new ExecutorAdmissionError("executor_cancelled", "Execution was cancelled before it started.");
|
|
168
|
+
}
|
|
169
|
+
const child = slot.child;
|
|
170
|
+
if (!child?.connected) {
|
|
171
|
+
throw new Error("QuickJS child IPC channel is unavailable.");
|
|
172
|
+
}
|
|
173
|
+
const id = this.nextJobId++;
|
|
174
|
+
const providerMap = new Map(providers.map((item) => [item.name, item]));
|
|
175
|
+
let payloadJson;
|
|
176
|
+
let runMessage;
|
|
177
|
+
try {
|
|
178
|
+
payloadJson = stringifyBounded({
|
|
179
|
+
id,
|
|
180
|
+
code,
|
|
181
|
+
providerNames: providers.map((item) => item.name),
|
|
182
|
+
options: this.runtimeOptions,
|
|
183
|
+
}, "QuickJS run payload");
|
|
184
|
+
runMessage = { type: "run", payloadJson };
|
|
185
|
+
stringifyBounded(runMessage, "QuickJS run IPC envelope");
|
|
186
|
+
}
|
|
187
|
+
catch (err) {
|
|
188
|
+
return { result: undefined, error: msg(err) };
|
|
189
|
+
}
|
|
190
|
+
child.ref();
|
|
191
|
+
child.channel?.ref();
|
|
192
|
+
return new Promise((resolve, reject) => {
|
|
193
|
+
const wallTimer = setTimeout(() => {
|
|
194
|
+
this.resolveActive(slot, {
|
|
195
|
+
result: undefined,
|
|
196
|
+
error: `QuickJS child exceeded the ${this.runtimeOptions.timeoutMs}ms wall budget and was terminated.`,
|
|
197
|
+
});
|
|
198
|
+
this.recycle(slot);
|
|
199
|
+
}, this.runtimeOptions.timeoutMs + CHILD_EXIT_GRACE_MS);
|
|
200
|
+
const active = {
|
|
201
|
+
id,
|
|
202
|
+
providers: providerMap,
|
|
203
|
+
resolve,
|
|
204
|
+
reject,
|
|
205
|
+
...(signal ? { signal } : {}),
|
|
206
|
+
wallTimer,
|
|
207
|
+
};
|
|
208
|
+
active.onAbort = () => {
|
|
209
|
+
this.rejectActive(slot, new ExecutorAdmissionError("executor_cancelled", "Execution was cancelled."));
|
|
210
|
+
this.recycle(slot);
|
|
211
|
+
};
|
|
212
|
+
signal?.addEventListener("abort", active.onAbort, { once: true });
|
|
213
|
+
slot.active = active;
|
|
214
|
+
if (signal?.aborted) {
|
|
215
|
+
active.onAbort();
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
try {
|
|
219
|
+
child.send(runMessage, (error) => {
|
|
220
|
+
if (!error || slot.active?.id !== id)
|
|
221
|
+
return;
|
|
222
|
+
this.rejectActive(slot, error);
|
|
223
|
+
this.recycle(slot);
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
this.rejectActive(slot, err instanceof Error ? err : new Error(String(err)));
|
|
228
|
+
this.recycle(slot);
|
|
104
229
|
}
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
async ensureChild(slot, signal) {
|
|
233
|
+
if (this.closed) {
|
|
234
|
+
throw new ExecutorAdmissionError("executor_closed", "Executor is shutting down.");
|
|
235
|
+
}
|
|
236
|
+
if (slot.child?.connected) {
|
|
237
|
+
if (slot.ready)
|
|
238
|
+
await waitForReady(slot.ready, signal);
|
|
105
239
|
return;
|
|
106
240
|
}
|
|
107
|
-
|
|
241
|
+
await delay(Math.max(0, slot.notBefore - Date.now()), signal);
|
|
242
|
+
if (this.closed) {
|
|
243
|
+
throw new ExecutorAdmissionError("executor_closed", "Executor is shutting down.");
|
|
244
|
+
}
|
|
245
|
+
const sourceMode = import.meta.url.endsWith(".ts");
|
|
246
|
+
const childUrl = new URL(sourceMode ? "./quickjs-child.ts" : "./quickjs-child.js", import.meta.url);
|
|
247
|
+
const child = fork(fileURLToPath(childUrl), [], {
|
|
248
|
+
execArgv: sourceMode ? ["--import", "tsx"] : [],
|
|
249
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
250
|
+
});
|
|
251
|
+
slot.child = child;
|
|
252
|
+
slot.ready = new Promise((resolve, reject) => {
|
|
253
|
+
slot.resolveReady = resolve;
|
|
254
|
+
slot.rejectReady = reject;
|
|
255
|
+
});
|
|
256
|
+
slot.readyTimer = setTimeout(() => {
|
|
257
|
+
if (slot.child !== child || !slot.ready)
|
|
258
|
+
return;
|
|
259
|
+
const error = new Error(`QuickJS child did not become ready within ${CHILD_STARTUP_TIMEOUT_MS}ms.`);
|
|
260
|
+
this.failChildStartup(slot, child, error);
|
|
261
|
+
}, CHILD_STARTUP_TIMEOUT_MS);
|
|
262
|
+
child.on("message", (message) => {
|
|
263
|
+
void this.onMessage(slot, child, message);
|
|
264
|
+
});
|
|
265
|
+
child.on("error", (error) => {
|
|
266
|
+
if (slot.child !== child)
|
|
267
|
+
return;
|
|
268
|
+
if (slot.ready) {
|
|
269
|
+
this.failChildStartup(slot, child, error);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
this.rejectActive(slot, error);
|
|
273
|
+
this.recycle(slot);
|
|
274
|
+
});
|
|
275
|
+
child.on("exit", (code, exitSignal) => {
|
|
276
|
+
const expected = slot.expectedExit === child;
|
|
277
|
+
if (slot.expectedExit === child)
|
|
278
|
+
slot.expectedExit = undefined;
|
|
279
|
+
this.rejectChildReady(slot, child, new Error(`QuickJS child exited before becoming ready` +
|
|
280
|
+
` (${exitSignal ? `signal ${exitSignal}` : `code ${String(code)}`}).`));
|
|
281
|
+
if (slot.child === child)
|
|
282
|
+
slot.child = undefined;
|
|
283
|
+
if (expected)
|
|
284
|
+
return;
|
|
285
|
+
this.recordCrash(slot);
|
|
286
|
+
this.resolveActive(slot, {
|
|
287
|
+
result: undefined,
|
|
288
|
+
error: `QuickJS child exited unexpectedly` +
|
|
289
|
+
` (${exitSignal ? `signal ${exitSignal}` : `code ${String(code)}`}).`,
|
|
290
|
+
});
|
|
291
|
+
});
|
|
292
|
+
child.unref();
|
|
293
|
+
child.channel?.unref();
|
|
294
|
+
if (slot.ready)
|
|
295
|
+
await waitForReady(slot.ready, signal);
|
|
296
|
+
}
|
|
297
|
+
async onMessage(slot, child, message) {
|
|
298
|
+
// A compromised child is exactly the adversary this process boundary
|
|
299
|
+
// contains, and this handler's rejection would crash the serving process.
|
|
300
|
+
// Refuse malformed intake before touching any field.
|
|
301
|
+
if (!message || typeof message !== "object")
|
|
302
|
+
return;
|
|
303
|
+
if (message.type === "ready") {
|
|
304
|
+
this.resolveChildReady(slot, child);
|
|
108
305
|
return;
|
|
109
|
-
// Cap the entry before retaining it: `getString` yields a transient copy,
|
|
110
|
-
// but slicing here keeps only a bounded string alive in `logs`.
|
|
111
|
-
let entry = ctx.getString(h);
|
|
112
|
-
if (entry.length > MAX_LOG_ENTRY_CHARS) {
|
|
113
|
-
entry = `${entry.slice(0, MAX_LOG_ENTRY_CHARS)}…[entry truncated]`;
|
|
114
306
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
307
|
+
const active = slot.active;
|
|
308
|
+
if (!active || slot.child !== child)
|
|
309
|
+
return;
|
|
310
|
+
if (typeof message.payloadJson !== "string")
|
|
311
|
+
return;
|
|
312
|
+
if (message.type === "host-call") {
|
|
313
|
+
if (message.jobId !== active.id)
|
|
314
|
+
return;
|
|
315
|
+
await this.handleHostCall(child, active, message);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (message.type !== "result" || message.jobId !== active.id)
|
|
319
|
+
return;
|
|
320
|
+
if (serializedBytes(message.payloadJson) > MAX_QUICKJS_IPC_BYTES) {
|
|
321
|
+
this.resolveActive(slot, {
|
|
322
|
+
result: undefined,
|
|
323
|
+
error: "QuickJS execution result exceeded the IPC limit.",
|
|
324
|
+
});
|
|
325
|
+
this.recycle(slot);
|
|
118
326
|
return;
|
|
119
327
|
}
|
|
120
|
-
logs.push(entry);
|
|
121
|
-
logTotalChars += entry.length;
|
|
122
|
-
});
|
|
123
|
-
ctx.setProp(ctx.global, "__log", logFn);
|
|
124
|
-
logFn.dispose();
|
|
125
|
-
const byName = new Map(providers.map((p) => [p.name, p]));
|
|
126
|
-
const invoke = async (ns, fn, argsJson) => {
|
|
127
328
|
try {
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
if (
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
329
|
+
const payload = JSON.parse(message.payloadJson);
|
|
330
|
+
slot.consecutiveCrashes = 0;
|
|
331
|
+
slot.notBefore = 0;
|
|
332
|
+
this.resolveActive(slot, payload.outcome);
|
|
333
|
+
if (payload.timedOut) {
|
|
334
|
+
// A timed-out host call may still retain QuickJS handles. A fresh child
|
|
335
|
+
// is cheaper and safer than reusing a context with unknown stragglers.
|
|
336
|
+
// The runtime sets this flag itself: matching error text here would let
|
|
337
|
+
// a guest throw "Execution timed out…" and force cold-start churn.
|
|
338
|
+
this.recycle(slot);
|
|
339
|
+
}
|
|
137
340
|
}
|
|
138
341
|
catch (err) {
|
|
139
|
-
|
|
342
|
+
this.resolveActive(slot, {
|
|
343
|
+
result: undefined,
|
|
344
|
+
error: `QuickJS child returned an invalid result: ${msg(err)}`,
|
|
345
|
+
});
|
|
346
|
+
this.recycle(slot);
|
|
140
347
|
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
348
|
+
}
|
|
349
|
+
async handleHostCall(child, active, message) {
|
|
350
|
+
let payloadJson;
|
|
351
|
+
try {
|
|
352
|
+
if (serializedBytes(message.payloadJson) >
|
|
353
|
+
MAX_QUICKJS_HOST_RPC_BYTES) {
|
|
354
|
+
throw new RangeError("Host call arguments exceeded the IPC limit.");
|
|
355
|
+
}
|
|
356
|
+
const payload = JSON.parse(message.payloadJson);
|
|
357
|
+
const provider = active.providers.get(payload.namespace);
|
|
358
|
+
const fn = provider && Object.hasOwn(provider.fns, payload.functionName)
|
|
359
|
+
? provider.fns[payload.functionName]
|
|
360
|
+
: undefined;
|
|
361
|
+
if (!fn) {
|
|
362
|
+
throw new Error(`Unknown function ${payload.namespace}.${payload.functionName}`);
|
|
153
363
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
364
|
+
const value = await fn(...payload.args);
|
|
365
|
+
try {
|
|
366
|
+
payloadJson = stringifyBounded({ ok: true, value }, `Host result from ${payload.namespace}.${payload.functionName}`, MAX_QUICKJS_HOST_RPC_BYTES);
|
|
367
|
+
}
|
|
368
|
+
catch (err) {
|
|
369
|
+
const detail = err instanceof RangeError
|
|
370
|
+
? `Host result from ${payload.namespace}.${payload.functionName} exceeds the ${MAX_QUICKJS_HOST_RPC_BYTES}-byte serialized bridge limit.`
|
|
371
|
+
: `Host result from ${payload.namespace}.${payload.functionName} could not be serialized: ${msg(err)}`;
|
|
372
|
+
payloadJson = errorPayload(detail);
|
|
158
373
|
}
|
|
159
|
-
|
|
374
|
+
}
|
|
375
|
+
catch (err) {
|
|
376
|
+
payloadJson = errorPayload(msg(err));
|
|
377
|
+
}
|
|
378
|
+
if (!child.connected)
|
|
379
|
+
return;
|
|
380
|
+
try {
|
|
381
|
+
const response = {
|
|
382
|
+
type: "host-result",
|
|
383
|
+
jobId: message.jobId,
|
|
384
|
+
callId: message.callId,
|
|
385
|
+
payloadJson,
|
|
386
|
+
};
|
|
387
|
+
stringifyBounded(response, "QuickJS host-result IPC envelope");
|
|
388
|
+
child.send(response);
|
|
389
|
+
}
|
|
390
|
+
catch {
|
|
391
|
+
// The execution has already ended or the child is exiting. Its exit
|
|
392
|
+
// handler owns the structured failure for any still-active job.
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
resolveActive(slot, outcome) {
|
|
396
|
+
const active = slot.active;
|
|
397
|
+
if (!active)
|
|
398
|
+
return;
|
|
399
|
+
this.clearActive(slot, active);
|
|
400
|
+
active.resolve(outcome);
|
|
401
|
+
}
|
|
402
|
+
rejectActive(slot, error) {
|
|
403
|
+
const active = slot.active;
|
|
404
|
+
if (!active)
|
|
405
|
+
return;
|
|
406
|
+
this.clearActive(slot, active);
|
|
407
|
+
active.reject(error);
|
|
408
|
+
}
|
|
409
|
+
clearActive(slot, active) {
|
|
410
|
+
clearTimeout(active.wallTimer);
|
|
411
|
+
if (active.onAbort) {
|
|
412
|
+
active.signal?.removeEventListener("abort", active.onAbort);
|
|
413
|
+
}
|
|
414
|
+
slot.active = undefined;
|
|
415
|
+
slot.child?.unref();
|
|
416
|
+
slot.child?.channel?.unref();
|
|
417
|
+
}
|
|
418
|
+
resolveChildReady(slot, child) {
|
|
419
|
+
if (slot.child !== child || !slot.ready)
|
|
420
|
+
return;
|
|
421
|
+
if (slot.readyTimer)
|
|
422
|
+
clearTimeout(slot.readyTimer);
|
|
423
|
+
const resolve = slot.resolveReady;
|
|
424
|
+
slot.ready = undefined;
|
|
425
|
+
slot.resolveReady = undefined;
|
|
426
|
+
slot.rejectReady = undefined;
|
|
427
|
+
slot.readyTimer = undefined;
|
|
428
|
+
resolve?.();
|
|
429
|
+
}
|
|
430
|
+
rejectChildReady(slot, child, error) {
|
|
431
|
+
if (slot.child !== child || !slot.ready)
|
|
432
|
+
return;
|
|
433
|
+
if (slot.readyTimer)
|
|
434
|
+
clearTimeout(slot.readyTimer);
|
|
435
|
+
const reject = slot.rejectReady;
|
|
436
|
+
slot.ready = undefined;
|
|
437
|
+
slot.resolveReady = undefined;
|
|
438
|
+
slot.rejectReady = undefined;
|
|
439
|
+
slot.readyTimer = undefined;
|
|
440
|
+
reject?.(error);
|
|
441
|
+
}
|
|
442
|
+
recordCrash(slot) {
|
|
443
|
+
slot.consecutiveCrashes++;
|
|
444
|
+
slot.notBefore =
|
|
445
|
+
Date.now() +
|
|
446
|
+
Math.min(5_000, 100 * 2 ** (slot.consecutiveCrashes - 1));
|
|
447
|
+
}
|
|
448
|
+
failChildStartup(slot, child, error) {
|
|
449
|
+
if (slot.child !== child || !slot.ready)
|
|
450
|
+
return;
|
|
451
|
+
// Detach before the rejected readiness promise can release the lease. A
|
|
452
|
+
// queued successor must never observe a connected child that is unready
|
|
453
|
+
// and already on its way out.
|
|
454
|
+
slot.expectedExit = child;
|
|
455
|
+
this.rejectChildReady(slot, child, error);
|
|
456
|
+
slot.child = undefined;
|
|
457
|
+
this.recordCrash(slot);
|
|
458
|
+
child.kill();
|
|
459
|
+
}
|
|
460
|
+
recycle(slot) {
|
|
461
|
+
const child = slot.child;
|
|
462
|
+
if (!child)
|
|
463
|
+
return;
|
|
464
|
+
this.rejectChildReady(slot, child, new Error("QuickJS child was recycled before becoming ready."));
|
|
465
|
+
slot.expectedExit = child;
|
|
466
|
+
slot.child = undefined;
|
|
467
|
+
child.kill();
|
|
468
|
+
}
|
|
469
|
+
stopSlot(slot) {
|
|
470
|
+
const child = slot.child;
|
|
471
|
+
if (!child)
|
|
472
|
+
return Promise.resolve();
|
|
473
|
+
this.rejectActive(slot, new ExecutorAdmissionError("executor_closed", "Executor is shutting down."));
|
|
474
|
+
this.rejectChildReady(slot, child, new ExecutorAdmissionError("executor_closed", "Executor is shutting down."));
|
|
475
|
+
slot.expectedExit = child;
|
|
476
|
+
slot.child = undefined;
|
|
477
|
+
return new Promise((resolve) => {
|
|
478
|
+
const timer = setTimeout(resolve, 1_000);
|
|
479
|
+
child.once("exit", () => {
|
|
480
|
+
clearTimeout(timer);
|
|
481
|
+
resolve();
|
|
482
|
+
});
|
|
483
|
+
child.kill();
|
|
160
484
|
});
|
|
161
|
-
|
|
162
|
-
});
|
|
163
|
-
ctx.setProp(ctx.global, "__call", callFn);
|
|
164
|
-
callFn.dispose();
|
|
165
|
-
return bridge;
|
|
485
|
+
}
|
|
166
486
|
}
|
|
167
487
|
/**
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* the point. One fresh QuickJS context per execution; the WASM module itself
|
|
172
|
-
* is cached across calls by quickjs-emscripten.
|
|
488
|
+
* Bounded Node QuickJS executor. Admission is acquired before connecta builds
|
|
489
|
+
* providers; one lease maps to one child and carries execution, avoiding a
|
|
490
|
+
* double-acquire deadlock at concurrency 1.
|
|
173
491
|
*/
|
|
174
492
|
export function quickJsExecutor(options = {}) {
|
|
175
|
-
|
|
176
|
-
const memoryLimitBytes = options.memoryLimitBytes ?? 64 * 1024 * 1024;
|
|
177
|
-
const maxStackSizeBytes = options.maxStackSizeBytes ?? 1024 * 1024;
|
|
178
|
-
return {
|
|
179
|
-
async execute(code, providers) {
|
|
180
|
-
const QuickJS = await getQuickJS();
|
|
181
|
-
const ctx = QuickJS.newContext();
|
|
182
|
-
const deadline = Date.now() + timeoutMs;
|
|
183
|
-
const timeoutError = `Execution timed out after ${timeoutMs}ms.`;
|
|
184
|
-
ctx.runtime.setMemoryLimit(memoryLimitBytes);
|
|
185
|
-
ctx.runtime.setMaxStackSize(maxStackSizeBytes);
|
|
186
|
-
ctx.runtime.setInterruptHandler(shouldInterruptAfterDeadline(deadline));
|
|
187
|
-
const logs = [];
|
|
188
|
-
const bridge = installBridge(ctx, providers, logs);
|
|
189
|
-
const finish = (r) => {
|
|
190
|
-
bridge.aborted = true;
|
|
191
|
-
// Outstanding host calls still hold deferred-promise handles; their
|
|
192
|
-
// callbacks free them and wake the drain, which disposes the context
|
|
193
|
-
// once the last straggler settles. Re-arm before every wait so the
|
|
194
|
-
// deferred never resolves-and-stays-resolved between settles — that
|
|
195
|
-
// would spin the microtask queue and starve the very timers the
|
|
196
|
-
// stragglers are waiting on. Arming before the pending check (and
|
|
197
|
-
// synchronously, before the first await) closes the settle-before-arm
|
|
198
|
-
// window: any settle after this point resolves the promise we await.
|
|
199
|
-
if (bridge.pending === 0)
|
|
200
|
-
ctx.dispose();
|
|
201
|
-
else {
|
|
202
|
-
void (async () => {
|
|
203
|
-
armWake(bridge);
|
|
204
|
-
while (bridge.pending > 0) {
|
|
205
|
-
await bridge.waitForSettle;
|
|
206
|
-
armWake(bridge);
|
|
207
|
-
}
|
|
208
|
-
ctx.dispose();
|
|
209
|
-
})();
|
|
210
|
-
}
|
|
211
|
-
return logs.length > 0 ? { ...r, logs } : r;
|
|
212
|
-
};
|
|
213
|
-
const fail = (error) => finish({ result: undefined, error });
|
|
214
|
-
const setup = ctx.evalCode(setupScript(providers));
|
|
215
|
-
if (setup.error) {
|
|
216
|
-
const detail = formatGuestError(ctx.dump(setup.error));
|
|
217
|
-
setup.error.dispose();
|
|
218
|
-
return fail(`Sandbox setup failed: ${detail}`);
|
|
219
|
-
}
|
|
220
|
-
setup.value.dispose();
|
|
221
|
-
const evaluated = ctx.evalCode(`Promise.resolve((\n${normalizeCode(code)}\n)())`);
|
|
222
|
-
if (evaluated.error) {
|
|
223
|
-
const dumped = ctx.dump(evaluated.error);
|
|
224
|
-
evaluated.error.dispose();
|
|
225
|
-
// A synchronous runaway (no await to yield on) trips the deadline
|
|
226
|
-
// interrupt here; surface the friendly timeout, not "interrupted".
|
|
227
|
-
if (isInterrupt(dumped) && Date.now() >= deadline)
|
|
228
|
-
return fail(timeoutError);
|
|
229
|
-
return fail(formatGuestError(dumped));
|
|
230
|
-
}
|
|
231
|
-
const promiseHandle = evaluated.value;
|
|
232
|
-
// Drive the guest: run microtask jobs, inspect the result promise,
|
|
233
|
-
// sleep until a host call settles (or the budget runs out), repeat.
|
|
234
|
-
// Returns without touching the context lifecycle; disposal happens below.
|
|
235
|
-
const drive = async () => {
|
|
236
|
-
for (;;) {
|
|
237
|
-
const jobs = ctx.runtime.executePendingJobs();
|
|
238
|
-
if (jobs.error) {
|
|
239
|
-
const dumped = ctx.dump(jobs.error);
|
|
240
|
-
jobs.error.dispose();
|
|
241
|
-
// A runaway inside a resumed continuation trips the interrupt here.
|
|
242
|
-
if (isInterrupt(dumped) && Date.now() >= deadline) {
|
|
243
|
-
return { result: undefined, error: timeoutError };
|
|
244
|
-
}
|
|
245
|
-
return { result: undefined, error: formatGuestError(dumped) };
|
|
246
|
-
}
|
|
247
|
-
const state = ctx.getPromiseState(promiseHandle);
|
|
248
|
-
if (state.type === "fulfilled") {
|
|
249
|
-
const result = ctx.dump(state.value);
|
|
250
|
-
state.value.dispose();
|
|
251
|
-
return { result };
|
|
252
|
-
}
|
|
253
|
-
if (state.type === "rejected") {
|
|
254
|
-
const dumped = ctx.dump(state.error);
|
|
255
|
-
state.error.dispose();
|
|
256
|
-
// A synchronous runaway rejects the async fn's promise with the
|
|
257
|
-
// interrupt; surface the friendly timeout, not "interrupted".
|
|
258
|
-
if (isInterrupt(dumped) && Date.now() >= deadline) {
|
|
259
|
-
return { result: undefined, error: timeoutError };
|
|
260
|
-
}
|
|
261
|
-
return { result: undefined, error: formatGuestError(dumped) };
|
|
262
|
-
}
|
|
263
|
-
if (bridge.pending === 0) {
|
|
264
|
-
return {
|
|
265
|
-
result: undefined,
|
|
266
|
-
error: "Execution stalled: code awaits something that can never settle.",
|
|
267
|
-
};
|
|
268
|
-
}
|
|
269
|
-
const remaining = deadline - Date.now();
|
|
270
|
-
if (remaining <= 0) {
|
|
271
|
-
return { result: undefined, error: timeoutError };
|
|
272
|
-
}
|
|
273
|
-
const settled = await Promise.race([
|
|
274
|
-
bridge.waitForSettle.then(() => true),
|
|
275
|
-
new Promise((r) => setTimeout(() => r(false), remaining)),
|
|
276
|
-
]);
|
|
277
|
-
if (settled)
|
|
278
|
-
armWake(bridge);
|
|
279
|
-
else {
|
|
280
|
-
return { result: undefined, error: timeoutError };
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
};
|
|
284
|
-
let outcome;
|
|
285
|
-
try {
|
|
286
|
-
outcome = await drive();
|
|
287
|
-
}
|
|
288
|
-
finally {
|
|
289
|
-
promiseHandle.dispose();
|
|
290
|
-
}
|
|
291
|
-
return finish(outcome);
|
|
292
|
-
},
|
|
293
|
-
};
|
|
493
|
+
return new QuickJsChildPool(options);
|
|
294
494
|
}
|
|
295
495
|
//# sourceMappingURL=quickjs.js.map
|