@enclave-vm/runtime 2.19.1 → 2.19.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -257
- package/channels/websocket-channel.d.ts +10 -0
- package/cli.d.ts +7 -5
- package/cli.js +34 -351
- package/esm/cli.mjs +34 -351
- package/esm/index.mjs +72 -27
- package/index.d.ts +12 -11
- package/index.js +73 -27
- package/package.json +5 -5
- package/runtime-worker.d.ts +19 -6
- package/session-executor.d.ts +25 -6
- package/types.d.ts +8 -5
package/esm/cli.mjs
CHANGED
|
@@ -1,320 +1,40 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
// libs/runtime/src/
|
|
4
|
-
|
|
5
|
-
var
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
debug;
|
|
11
|
-
unsubscribe = null;
|
|
12
|
-
executing = false;
|
|
13
|
-
constructor(options) {
|
|
14
|
-
const { code, channel, limits, debug = false } = options;
|
|
15
|
-
this.code = code;
|
|
16
|
-
this.channel = channel;
|
|
17
|
-
this.debug = debug;
|
|
18
|
-
this.session = createSession({
|
|
19
|
-
sessionId: options.sessionId,
|
|
20
|
-
ttlMs: limits?.sessionTtlMs,
|
|
21
|
-
config: {
|
|
22
|
-
limits
|
|
23
|
-
},
|
|
24
|
-
toolHandler: async (callId, toolName, args) => {
|
|
25
|
-
this.log(`Tool call: ${toolName}(${JSON.stringify(args)})`);
|
|
26
|
-
}
|
|
27
|
-
});
|
|
28
|
-
this.sessionId = this.session.sessionId;
|
|
29
|
-
this.unsubscribe = this.session.events.on((event) => {
|
|
30
|
-
if (this.channel.isOpen) {
|
|
31
|
-
this.channel.send(event);
|
|
32
|
-
}
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Get session info
|
|
37
|
-
*/
|
|
38
|
-
getInfo() {
|
|
39
|
-
return {
|
|
40
|
-
sessionId: this.sessionId,
|
|
41
|
-
state: this.session.state,
|
|
42
|
-
createdAt: this.session.createdAt,
|
|
43
|
-
expiresAt: this.session.expiresAt
|
|
44
|
-
};
|
|
45
|
-
}
|
|
46
|
-
/**
|
|
47
|
-
* Get current state
|
|
48
|
-
*/
|
|
49
|
-
get state() {
|
|
50
|
-
return this.session.state;
|
|
51
|
-
}
|
|
52
|
-
/**
|
|
53
|
-
* Check if session is in terminal state
|
|
54
|
-
*/
|
|
55
|
-
get isTerminal() {
|
|
56
|
-
const state = this.session.state;
|
|
57
|
-
return state === "completed" || state === "cancelled" || state === "failed";
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Execute the code
|
|
61
|
-
*/
|
|
62
|
-
async execute() {
|
|
63
|
-
if (this.executing) {
|
|
64
|
-
throw new Error("Session is already executing");
|
|
65
|
-
}
|
|
66
|
-
this.executing = true;
|
|
67
|
-
try {
|
|
68
|
-
this.log(`Starting execution for session ${this.sessionId}`);
|
|
69
|
-
this.session.start();
|
|
70
|
-
const result = await this.session.wait();
|
|
71
|
-
this.log(`Session ${this.sessionId} completed: ${result.finalState}`);
|
|
72
|
-
} catch (error) {
|
|
73
|
-
this.log(`Session ${this.sessionId} error: ${error}`);
|
|
74
|
-
throw error;
|
|
75
|
-
} finally {
|
|
76
|
-
this.executing = false;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Submit a tool result
|
|
81
|
-
*/
|
|
82
|
-
async submitToolResult(callId, success, value, error) {
|
|
83
|
-
await this.session.submitToolResult({
|
|
84
|
-
callId,
|
|
85
|
-
success,
|
|
86
|
-
value,
|
|
87
|
-
error
|
|
88
|
-
});
|
|
89
|
-
}
|
|
90
|
-
/**
|
|
91
|
-
* Cancel the session
|
|
92
|
-
*/
|
|
93
|
-
async cancel(reason) {
|
|
94
|
-
await this.session.cancel(reason);
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Dispose of the executor
|
|
98
|
-
*/
|
|
99
|
-
dispose() {
|
|
100
|
-
if (this.unsubscribe) {
|
|
101
|
-
this.unsubscribe();
|
|
102
|
-
this.unsubscribe = null;
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
/**
|
|
106
|
-
* Log debug message
|
|
107
|
-
*/
|
|
108
|
-
log(message) {
|
|
109
|
-
if (this.debug) {
|
|
110
|
-
console.log(`[SessionExecutor] ${message}`);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
function createSessionExecutor(options) {
|
|
115
|
-
return new SessionExecutor(options);
|
|
3
|
+
// libs/runtime/src/cli.ts
|
|
4
|
+
var EXIT_OK = 0;
|
|
5
|
+
var EXIT_ERROR = 1;
|
|
6
|
+
var NOT_IMPLEMENTED = "enclave-runtime: not implemented. @enclave-vm/runtime does not execute code and does not listen on a port, so there is no worker to start.\nRun scripts with @enclave-vm/broker (sessions, tools and streaming over HTTP) or @enclave-vm/core (the sandbox).";
|
|
7
|
+
function fail(message) {
|
|
8
|
+
console.error(message);
|
|
9
|
+
process.exit(EXIT_ERROR);
|
|
116
10
|
}
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
port: 3001,
|
|
121
|
-
host: "0.0.0.0",
|
|
122
|
-
wsPath: "/ws",
|
|
123
|
-
maxSessions: 10,
|
|
124
|
-
defaultLimits: {},
|
|
125
|
-
debug: false,
|
|
126
|
-
heartbeatIntervalMs: 15e3,
|
|
127
|
-
connectionTimeoutMs: 3e4
|
|
128
|
-
};
|
|
129
|
-
var RuntimeWorker = class {
|
|
130
|
-
config;
|
|
131
|
-
sessions;
|
|
132
|
-
state = "idle";
|
|
133
|
-
startedAt = 0;
|
|
134
|
-
totalSessions = 0;
|
|
135
|
-
constructor(config = {}) {
|
|
136
|
-
this.config = {
|
|
137
|
-
...DEFAULT_CONFIG,
|
|
138
|
-
...config
|
|
139
|
-
};
|
|
140
|
-
this.sessions = /* @__PURE__ */ new Map();
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Check if runtime is running
|
|
144
|
-
*/
|
|
145
|
-
get isRunning() {
|
|
146
|
-
return this.state === "running";
|
|
147
|
-
}
|
|
148
|
-
/**
|
|
149
|
-
* Start the runtime worker
|
|
150
|
-
*/
|
|
151
|
-
async start() {
|
|
152
|
-
if (this.state !== "idle" && this.state !== "stopped") {
|
|
153
|
-
throw new Error(`Cannot start runtime in state: ${this.state}`);
|
|
154
|
-
}
|
|
155
|
-
this.state = "starting";
|
|
156
|
-
this.startedAt = Date.now();
|
|
157
|
-
this.state = "running";
|
|
158
|
-
this.log("Runtime worker started");
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Stop the runtime worker
|
|
162
|
-
*/
|
|
163
|
-
async stop() {
|
|
164
|
-
if (this.state === "stopped" || this.state === "stopping") {
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
this.state = "stopping";
|
|
168
|
-
const cancelPromises = [];
|
|
169
|
-
for (const [_sessionId, executor] of this.sessions) {
|
|
170
|
-
cancelPromises.push(
|
|
171
|
-
executor.cancel("Runtime stopping").catch(() => {
|
|
172
|
-
})
|
|
173
|
-
);
|
|
174
|
-
}
|
|
175
|
-
await Promise.all(cancelPromises);
|
|
176
|
-
for (const executor of this.sessions.values()) {
|
|
177
|
-
executor.dispose();
|
|
178
|
-
}
|
|
179
|
-
this.sessions.clear();
|
|
180
|
-
this.state = "stopped";
|
|
181
|
-
this.log("Runtime worker stopped");
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Get runtime statistics
|
|
185
|
-
*/
|
|
186
|
-
getStats() {
|
|
187
|
-
const now = Date.now();
|
|
188
|
-
const memoryUsage = process.memoryUsage();
|
|
189
|
-
return {
|
|
190
|
-
state: this.state,
|
|
191
|
-
activeSessions: this.sessions.size,
|
|
192
|
-
totalSessions: this.totalSessions,
|
|
193
|
-
startedAt: this.startedAt,
|
|
194
|
-
uptimeMs: this.startedAt > 0 ? now - this.startedAt : 0,
|
|
195
|
-
memoryUsage: {
|
|
196
|
-
heapUsed: memoryUsage.heapUsed,
|
|
197
|
-
heapTotal: memoryUsage.heapTotal,
|
|
198
|
-
rss: memoryUsage.rss
|
|
199
|
-
}
|
|
200
|
-
};
|
|
201
|
-
}
|
|
202
|
-
/**
|
|
203
|
-
* Get active sessions
|
|
204
|
-
*/
|
|
205
|
-
getSessions() {
|
|
206
|
-
return Array.from(this.sessions.values()).map((executor) => executor.getInfo());
|
|
11
|
+
function valueOf(option, value) {
|
|
12
|
+
if (value === void 0 || value.startsWith("--")) {
|
|
13
|
+
fail(`Option ${option} needs a value`);
|
|
207
14
|
}
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
break;
|
|
216
|
-
case "cancel":
|
|
217
|
-
await this.handleCancel(request);
|
|
218
|
-
break;
|
|
219
|
-
case "tool_result":
|
|
220
|
-
await this.handleToolResult(request);
|
|
221
|
-
break;
|
|
222
|
-
case "ping":
|
|
223
|
-
this.log("Received ping");
|
|
224
|
-
break;
|
|
225
|
-
default:
|
|
226
|
-
this.log(`Unknown request type: ${request.type}`);
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Handle execute request
|
|
231
|
-
*/
|
|
232
|
-
async handleExecute(request, channel) {
|
|
233
|
-
if (!this.isRunning) {
|
|
234
|
-
throw new Error("Runtime is not running");
|
|
235
|
-
}
|
|
236
|
-
if (this.sessions.size >= this.config.maxSessions) {
|
|
237
|
-
throw new Error(`Maximum sessions reached (${this.config.maxSessions})`);
|
|
238
|
-
}
|
|
239
|
-
const { sessionId, code, limits } = request;
|
|
240
|
-
if (this.sessions.has(sessionId)) {
|
|
241
|
-
throw new Error(`Session ${sessionId} already exists`);
|
|
242
|
-
}
|
|
243
|
-
const executor = createSessionExecutor({
|
|
244
|
-
sessionId,
|
|
245
|
-
code,
|
|
246
|
-
limits,
|
|
247
|
-
channel,
|
|
248
|
-
debug: this.config.debug
|
|
249
|
-
});
|
|
250
|
-
this.sessions.set(executor.sessionId, executor);
|
|
251
|
-
this.totalSessions++;
|
|
252
|
-
executor.execute().catch((error) => {
|
|
253
|
-
this.log(`Session ${executor.sessionId} execution error: ${error}`);
|
|
254
|
-
}).finally(() => {
|
|
255
|
-
this.cleanupSession(executor.sessionId);
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Handle cancel request
|
|
260
|
-
*/
|
|
261
|
-
async handleCancel(request) {
|
|
262
|
-
const executor = this.sessions.get(request.sessionId);
|
|
263
|
-
if (!executor) {
|
|
264
|
-
this.log(`Cancel request for unknown session: ${request.sessionId}`);
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
await executor.cancel(request.reason);
|
|
268
|
-
this.cleanupSession(request.sessionId);
|
|
269
|
-
}
|
|
270
|
-
/**
|
|
271
|
-
* Handle tool result
|
|
272
|
-
*/
|
|
273
|
-
async handleToolResult(request) {
|
|
274
|
-
const executor = this.sessions.get(request.sessionId);
|
|
275
|
-
if (!executor) {
|
|
276
|
-
this.log(`Tool result for unknown session: ${request.sessionId}`);
|
|
277
|
-
return;
|
|
278
|
-
}
|
|
279
|
-
await executor.submitToolResult(request.callId, request.success, request.value, request.error);
|
|
280
|
-
}
|
|
281
|
-
/**
|
|
282
|
-
* Clean up a session
|
|
283
|
-
*/
|
|
284
|
-
cleanupSession(sessionId) {
|
|
285
|
-
const executor = this.sessions.get(sessionId);
|
|
286
|
-
if (executor) {
|
|
287
|
-
executor.dispose();
|
|
288
|
-
this.sessions.delete(sessionId);
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
/**
|
|
292
|
-
* Log debug message
|
|
293
|
-
*/
|
|
294
|
-
log(message) {
|
|
295
|
-
if (this.config.debug) {
|
|
296
|
-
console.log(`[RuntimeWorker] ${message}`);
|
|
297
|
-
}
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
function integerOf(option, value, minimum) {
|
|
18
|
+
const text = valueOf(option, value);
|
|
19
|
+
const parsed = Number(text);
|
|
20
|
+
if (!/^\d+$/.test(text) || !Number.isSafeInteger(parsed) || parsed < minimum) {
|
|
21
|
+
fail(`Option ${option} needs a whole number of ${minimum} or more, got "${text}"`);
|
|
298
22
|
}
|
|
299
|
-
|
|
300
|
-
function createRuntimeWorker(config) {
|
|
301
|
-
return new RuntimeWorker(config);
|
|
23
|
+
return parsed;
|
|
302
24
|
}
|
|
303
|
-
|
|
304
|
-
// libs/runtime/src/cli.ts
|
|
305
25
|
function parseArgs(args) {
|
|
306
26
|
const config = {};
|
|
307
27
|
for (let i = 0; i < args.length; i++) {
|
|
308
28
|
const arg = args[i];
|
|
309
29
|
switch (arg) {
|
|
310
30
|
case "--port":
|
|
311
|
-
config.port =
|
|
31
|
+
config.port = integerOf(arg, args[++i], 0);
|
|
312
32
|
break;
|
|
313
33
|
case "--host":
|
|
314
|
-
config.host = args[++i];
|
|
34
|
+
config.host = valueOf(arg, args[++i]);
|
|
315
35
|
break;
|
|
316
36
|
case "--max-sessions":
|
|
317
|
-
config.maxSessions =
|
|
37
|
+
config.maxSessions = integerOf(arg, args[++i], 1);
|
|
318
38
|
break;
|
|
319
39
|
case "--debug":
|
|
320
40
|
config.debug = true;
|
|
@@ -322,13 +42,10 @@ function parseArgs(args) {
|
|
|
322
42
|
case "--help":
|
|
323
43
|
case "-h":
|
|
324
44
|
printHelp();
|
|
325
|
-
process.exit(
|
|
45
|
+
process.exit(EXIT_OK);
|
|
326
46
|
break;
|
|
327
47
|
default:
|
|
328
|
-
|
|
329
|
-
console.error(`Unknown option: ${arg}`);
|
|
330
|
-
process.exit(1);
|
|
331
|
-
}
|
|
48
|
+
fail(`Unknown option: ${arg}`);
|
|
332
49
|
}
|
|
333
50
|
}
|
|
334
51
|
return config;
|
|
@@ -337,55 +54,21 @@ function printHelp() {
|
|
|
337
54
|
console.log(`
|
|
338
55
|
Enclave Runtime Worker
|
|
339
56
|
|
|
57
|
+
${NOT_IMPLEMENTED}
|
|
58
|
+
|
|
340
59
|
Usage:
|
|
341
60
|
npx enclave-runtime [options]
|
|
342
61
|
|
|
343
|
-
Options:
|
|
344
|
-
--port <port>
|
|
345
|
-
--host <host>
|
|
346
|
-
--max-sessions <n>
|
|
347
|
-
--debug
|
|
62
|
+
Options (accepted and checked; none of them starts anything):
|
|
63
|
+
--port <port> Reserved (nothing listens)
|
|
64
|
+
--host <host> Reserved (nothing listens)
|
|
65
|
+
--max-sessions <n> Reserved
|
|
66
|
+
--debug Reserved
|
|
348
67
|
--help, -h Show this help message
|
|
349
|
-
|
|
350
|
-
Examples:
|
|
351
|
-
npx enclave-runtime --port 3001
|
|
352
|
-
npx enclave-runtime --port 8080 --max-sessions 20 --debug
|
|
353
68
|
`);
|
|
354
69
|
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
console.log("Starting Enclave Runtime Worker...");
|
|
359
|
-
console.log(` Port: ${config.port ?? 3001}`);
|
|
360
|
-
console.log(` Host: ${config.host ?? "0.0.0.0"}`);
|
|
361
|
-
console.log(` Max Sessions: ${config.maxSessions ?? 10}`);
|
|
362
|
-
console.log(` Debug: ${config.debug ?? false}`);
|
|
363
|
-
const worker = createRuntimeWorker(config);
|
|
364
|
-
const shutdown = async (signal) => {
|
|
365
|
-
console.log(`
|
|
366
|
-
Received ${signal}, shutting down...`);
|
|
367
|
-
await worker.stop();
|
|
368
|
-
console.log("Runtime stopped");
|
|
369
|
-
process.exit(0);
|
|
370
|
-
};
|
|
371
|
-
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
372
|
-
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
373
|
-
await worker.start();
|
|
374
|
-
console.log("Runtime worker is running");
|
|
375
|
-
console.log(` PID: ${process.pid}`);
|
|
376
|
-
if (config.debug) {
|
|
377
|
-
setInterval(() => {
|
|
378
|
-
const stats = worker.getStats();
|
|
379
|
-
console.log("Stats:", {
|
|
380
|
-
activeSessions: stats.activeSessions,
|
|
381
|
-
totalSessions: stats.totalSessions,
|
|
382
|
-
uptimeMs: stats.uptimeMs,
|
|
383
|
-
memoryMB: Math.round(stats.memoryUsage.heapUsed / 1024 / 1024)
|
|
384
|
-
});
|
|
385
|
-
}, 3e4);
|
|
386
|
-
}
|
|
70
|
+
function main() {
|
|
71
|
+
parseArgs(process.argv.slice(2));
|
|
72
|
+
fail(NOT_IMPLEMENTED);
|
|
387
73
|
}
|
|
388
|
-
main()
|
|
389
|
-
console.error("Failed to start runtime:", error);
|
|
390
|
-
process.exit(1);
|
|
391
|
-
});
|
|
74
|
+
main();
|
package/esm/index.mjs
CHANGED
|
@@ -7,6 +7,15 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
|
|
|
7
7
|
|
|
8
8
|
// libs/runtime/src/session-executor.ts
|
|
9
9
|
import { createSession } from "@enclave-vm/core";
|
|
10
|
+
var RuntimeNotImplementedError = class extends Error {
|
|
11
|
+
code = "NOT_IMPLEMENTED";
|
|
12
|
+
constructor(operation) {
|
|
13
|
+
super(
|
|
14
|
+
`${operation} is not implemented: @enclave-vm/runtime does not execute code. Run scripts with @enclave-vm/broker or @enclave-vm/core.`
|
|
15
|
+
);
|
|
16
|
+
this.name = "RuntimeNotImplementedError";
|
|
17
|
+
}
|
|
18
|
+
};
|
|
10
19
|
var SessionExecutor = class {
|
|
11
20
|
sessionId;
|
|
12
21
|
session;
|
|
@@ -14,7 +23,6 @@ var SessionExecutor = class {
|
|
|
14
23
|
code;
|
|
15
24
|
debug;
|
|
16
25
|
unsubscribe = null;
|
|
17
|
-
executing = false;
|
|
18
26
|
constructor(options) {
|
|
19
27
|
const { code, channel, limits, debug = false } = options;
|
|
20
28
|
this.code = code;
|
|
@@ -62,24 +70,24 @@ var SessionExecutor = class {
|
|
|
62
70
|
return state === "completed" || state === "cancelled" || state === "failed";
|
|
63
71
|
}
|
|
64
72
|
/**
|
|
65
|
-
* Execute the code
|
|
73
|
+
* Execute the code: not implemented.
|
|
74
|
+
*
|
|
75
|
+
* Nothing in this package runs a script. Rather than report a running session that never
|
|
76
|
+
* finishes, the session is ended with the error code `NOT_IMPLEMENTED` (the channel
|
|
77
|
+
* receives its `final` event) and the returned promise rejects.
|
|
78
|
+
*
|
|
79
|
+
* @throws RuntimeNotImplementedError always
|
|
66
80
|
*/
|
|
67
81
|
async execute() {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
this.session.
|
|
75
|
-
const result = await this.session.wait();
|
|
76
|
-
this.log(`Session ${this.sessionId} completed: ${result.finalState}`);
|
|
77
|
-
} catch (error) {
|
|
78
|
-
this.log(`Session ${this.sessionId} error: ${error}`);
|
|
79
|
-
throw error;
|
|
80
|
-
} finally {
|
|
81
|
-
this.executing = false;
|
|
82
|
+
const error = new RuntimeNotImplementedError("SessionExecutor.execute()");
|
|
83
|
+
if (!this.isTerminal) {
|
|
84
|
+
this.log(`Session ${this.sessionId} cannot be executed: ${error.message} (${this.code.length} characters)`);
|
|
85
|
+
if (this.session.state === "starting") {
|
|
86
|
+
this.session.start();
|
|
87
|
+
}
|
|
88
|
+
this.session.fail(error);
|
|
82
89
|
}
|
|
90
|
+
throw error;
|
|
83
91
|
}
|
|
84
92
|
/**
|
|
85
93
|
* Submit a tool result
|
|
@@ -123,7 +131,7 @@ function createSessionExecutor(options) {
|
|
|
123
131
|
// libs/runtime/src/runtime-worker.ts
|
|
124
132
|
var DEFAULT_CONFIG = {
|
|
125
133
|
port: 3001,
|
|
126
|
-
host: "
|
|
134
|
+
host: "127.0.0.1",
|
|
127
135
|
wsPath: "/ws",
|
|
128
136
|
maxSessions: 10,
|
|
129
137
|
defaultLimits: {},
|
|
@@ -131,6 +139,19 @@ var DEFAULT_CONFIG = {
|
|
|
131
139
|
heartbeatIntervalMs: 15e3,
|
|
132
140
|
connectionTimeoutMs: 3e4
|
|
133
141
|
};
|
|
142
|
+
function resolveConfig(config) {
|
|
143
|
+
const resolved = { ...DEFAULT_CONFIG };
|
|
144
|
+
const target = resolved;
|
|
145
|
+
for (const [key, value] of Object.entries(config ?? {})) {
|
|
146
|
+
if (value !== void 0) {
|
|
147
|
+
target[key] = value;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (typeof resolved.maxSessions !== "number" || !Number.isSafeInteger(resolved.maxSessions) || resolved.maxSessions < 1) {
|
|
151
|
+
throw new RangeError("maxSessions must be a positive integer");
|
|
152
|
+
}
|
|
153
|
+
return resolved;
|
|
154
|
+
}
|
|
134
155
|
var RuntimeWorker = class {
|
|
135
156
|
config;
|
|
136
157
|
sessions;
|
|
@@ -138,10 +159,7 @@ var RuntimeWorker = class {
|
|
|
138
159
|
startedAt = 0;
|
|
139
160
|
totalSessions = 0;
|
|
140
161
|
constructor(config = {}) {
|
|
141
|
-
this.config =
|
|
142
|
-
...DEFAULT_CONFIG,
|
|
143
|
-
...config
|
|
144
|
-
};
|
|
162
|
+
this.config = resolveConfig(config);
|
|
145
163
|
this.sessions = /* @__PURE__ */ new Map();
|
|
146
164
|
}
|
|
147
165
|
/**
|
|
@@ -151,7 +169,10 @@ var RuntimeWorker = class {
|
|
|
151
169
|
return this.state === "running";
|
|
152
170
|
}
|
|
153
171
|
/**
|
|
154
|
-
* Start the runtime worker
|
|
172
|
+
* Start the runtime worker: mark it as running, so that `handleRequest()` accepts requests.
|
|
173
|
+
*
|
|
174
|
+
* No server is started and no port is opened. The requests come from the application that
|
|
175
|
+
* embeds the worker.
|
|
155
176
|
*/
|
|
156
177
|
async start() {
|
|
157
178
|
if (this.state !== "idle" && this.state !== "stopped") {
|
|
@@ -212,8 +233,14 @@ var RuntimeWorker = class {
|
|
|
212
233
|
}
|
|
213
234
|
/**
|
|
214
235
|
* Handle incoming request from channel
|
|
236
|
+
*
|
|
237
|
+
* The caller is trusted: nothing here authenticates where a request came from. An `execute`
|
|
238
|
+
* request rejects with `RuntimeNotImplementedError`.
|
|
215
239
|
*/
|
|
216
240
|
async handleRequest(request, channel) {
|
|
241
|
+
if (typeof request !== "object" || request === null || typeof request.type !== "string") {
|
|
242
|
+
throw new TypeError("Invalid runtime request");
|
|
243
|
+
}
|
|
217
244
|
switch (request.type) {
|
|
218
245
|
case "execute":
|
|
219
246
|
await this.handleExecute(request, channel);
|
|
@@ -232,7 +259,10 @@ var RuntimeWorker = class {
|
|
|
232
259
|
}
|
|
233
260
|
}
|
|
234
261
|
/**
|
|
235
|
-
* Handle execute request
|
|
262
|
+
* Handle execute request: the session is created, ended with the error code
|
|
263
|
+
* `NOT_IMPLEMENTED` on its channel, and removed again.
|
|
264
|
+
*
|
|
265
|
+
* @throws RuntimeNotImplementedError when the request was valid
|
|
236
266
|
*/
|
|
237
267
|
async handleExecute(request, channel) {
|
|
238
268
|
if (!this.isRunning) {
|
|
@@ -242,6 +272,9 @@ var RuntimeWorker = class {
|
|
|
242
272
|
throw new Error(`Maximum sessions reached (${this.config.maxSessions})`);
|
|
243
273
|
}
|
|
244
274
|
const { sessionId, code, limits } = request;
|
|
275
|
+
if (typeof code !== "string") {
|
|
276
|
+
throw new TypeError("Invalid execute request: `code` must be a string");
|
|
277
|
+
}
|
|
245
278
|
if (this.sessions.has(sessionId)) {
|
|
246
279
|
throw new Error(`Session ${sessionId} already exists`);
|
|
247
280
|
}
|
|
@@ -254,11 +287,14 @@ var RuntimeWorker = class {
|
|
|
254
287
|
});
|
|
255
288
|
this.sessions.set(executor.sessionId, executor);
|
|
256
289
|
this.totalSessions++;
|
|
257
|
-
|
|
290
|
+
try {
|
|
291
|
+
await executor.execute();
|
|
292
|
+
} catch (error) {
|
|
258
293
|
this.log(`Session ${executor.sessionId} execution error: ${error}`);
|
|
259
|
-
|
|
294
|
+
throw error;
|
|
295
|
+
} finally {
|
|
260
296
|
this.cleanupSession(executor.sessionId);
|
|
261
|
-
}
|
|
297
|
+
}
|
|
262
298
|
}
|
|
263
299
|
/**
|
|
264
300
|
* Handle cancel request
|
|
@@ -387,6 +423,7 @@ function createMemoryChannelPair() {
|
|
|
387
423
|
|
|
388
424
|
// libs/runtime/src/channels/websocket-channel.ts
|
|
389
425
|
import { serializeEvent } from "@enclave-vm/stream";
|
|
426
|
+
var DEFAULT_MAX_BUFFERED_MESSAGES = 1e3;
|
|
390
427
|
var WebSocketChannel = class {
|
|
391
428
|
config;
|
|
392
429
|
ws = null;
|
|
@@ -396,6 +433,10 @@ var WebSocketChannel = class {
|
|
|
396
433
|
retryTimeout = null;
|
|
397
434
|
messageBuffer = [];
|
|
398
435
|
constructor(config) {
|
|
436
|
+
const maxBufferedMessages = config.maxBufferedMessages ?? DEFAULT_MAX_BUFFERED_MESSAGES;
|
|
437
|
+
if (typeof maxBufferedMessages !== "number" || !Number.isSafeInteger(maxBufferedMessages) || maxBufferedMessages < 1) {
|
|
438
|
+
throw new RangeError("maxBufferedMessages must be a positive integer");
|
|
439
|
+
}
|
|
399
440
|
this.config = {
|
|
400
441
|
url: config.url,
|
|
401
442
|
reconnect: {
|
|
@@ -405,6 +446,7 @@ var WebSocketChannel = class {
|
|
|
405
446
|
maxDelayMs: config.reconnect?.maxDelayMs ?? 3e4
|
|
406
447
|
},
|
|
407
448
|
connectionTimeoutMs: config.connectionTimeoutMs ?? 1e4,
|
|
449
|
+
maxBufferedMessages,
|
|
408
450
|
debug: config.debug ?? false
|
|
409
451
|
};
|
|
410
452
|
}
|
|
@@ -474,8 +516,10 @@ var WebSocketChannel = class {
|
|
|
474
516
|
const data = serializeEvent(event);
|
|
475
517
|
if (this.isOpen && this.ws) {
|
|
476
518
|
this.ws.send(data);
|
|
477
|
-
} else {
|
|
519
|
+
} else if (this.messageBuffer.length < this.config.maxBufferedMessages) {
|
|
478
520
|
this.messageBuffer.push(data);
|
|
521
|
+
} else {
|
|
522
|
+
this.log("Message buffer is full, dropping event");
|
|
479
523
|
}
|
|
480
524
|
}
|
|
481
525
|
/**
|
|
@@ -571,6 +615,7 @@ function createWebSocketChannel(config) {
|
|
|
571
615
|
}
|
|
572
616
|
export {
|
|
573
617
|
MemoryChannel,
|
|
618
|
+
RuntimeNotImplementedError,
|
|
574
619
|
RuntimeWorker as RuntimeWorkerImpl,
|
|
575
620
|
SessionExecutor,
|
|
576
621
|
WebSocketChannel,
|
package/index.d.ts
CHANGED
|
@@ -1,26 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @enclave-vm/runtime
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* Building blocks of a runtime worker for EnclaveJS: session bookkeeping and the channels
|
|
5
|
+
* between a worker and a broker.
|
|
6
|
+
*
|
|
7
|
+
* This package is not a runnable service. It does not execute code (an `execute` request ends
|
|
8
|
+
* with `RuntimeNotImplementedError`), it starts no server and opens no port, and it has no
|
|
9
|
+
* authentication. To run scripts use `@enclave-vm/broker` or `@enclave-vm/core`.
|
|
6
10
|
*
|
|
7
11
|
* @example
|
|
8
12
|
* ```typescript
|
|
9
|
-
* import { createRuntimeWorker } from '@enclave-vm/runtime';
|
|
13
|
+
* import { createRuntimeWorker, createMemoryChannel } from '@enclave-vm/runtime';
|
|
10
14
|
*
|
|
11
|
-
* const worker = createRuntimeWorker({
|
|
12
|
-
*
|
|
13
|
-
* maxSessions: 10,
|
|
14
|
-
* debug: true,
|
|
15
|
-
* });
|
|
15
|
+
* const worker = createRuntimeWorker({ maxSessions: 10 });
|
|
16
|
+
* await worker.start(); // marks the worker as running; nothing is listening
|
|
16
17
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
18
|
+
* const channel = createMemoryChannel();
|
|
19
|
+
* await worker.handleRequest({ type: 'ping', timestamp: Date.now() }, channel);
|
|
19
20
|
* ```
|
|
20
21
|
*
|
|
21
22
|
* @packageDocumentation
|
|
22
23
|
*/
|
|
23
24
|
export type { RuntimeConfig, RuntimeState, RuntimeStats, RuntimeSession, RuntimeWorker, RuntimeChannel, RuntimeRequest, ExecuteRequest, CancelRequest, ToolResultRequest, PingRequest, RuntimeEventHandler, ConnectionHandler, WebSocketServer, } from './types';
|
|
24
25
|
export { RuntimeWorker as RuntimeWorkerImpl, createRuntimeWorker } from './runtime-worker';
|
|
25
|
-
export { SessionExecutor, createSessionExecutor, type SessionExecutorOptions } from './session-executor';
|
|
26
|
+
export { SessionExecutor, createSessionExecutor, RuntimeNotImplementedError, type SessionExecutorOptions, } from './session-executor';
|
|
26
27
|
export { MemoryChannel, createMemoryChannel, createMemoryChannelPair, WebSocketChannel, createWebSocketChannel, type WebSocketChannelConfig, type WebSocketChannelState, } from './channels';
|