@enclave-vm/runtime 0.0.1 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.mjs ADDED
@@ -0,0 +1,582 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // libs/enclavejs-runtime/src/session-executor.ts
9
+ import { createSession } from "@enclave-vm/core";
10
+ var SessionExecutor = class {
11
+ sessionId;
12
+ session;
13
+ channel;
14
+ code;
15
+ debug;
16
+ unsubscribe = null;
17
+ executing = false;
18
+ constructor(options) {
19
+ const { code, channel, limits, debug = false } = options;
20
+ this.code = code;
21
+ this.channel = channel;
22
+ this.debug = debug;
23
+ this.session = createSession({
24
+ sessionId: options.sessionId,
25
+ ttlMs: limits?.sessionTtlMs,
26
+ config: {
27
+ limits
28
+ },
29
+ toolHandler: async (callId, toolName, args) => {
30
+ this.log(`Tool call: ${toolName}(${JSON.stringify(args)})`);
31
+ }
32
+ });
33
+ this.sessionId = this.session.sessionId;
34
+ this.unsubscribe = this.session.events.on((event) => {
35
+ if (this.channel.isOpen) {
36
+ this.channel.send(event);
37
+ }
38
+ });
39
+ }
40
+ /**
41
+ * Get session info
42
+ */
43
+ getInfo() {
44
+ return {
45
+ sessionId: this.sessionId,
46
+ state: this.session.state,
47
+ createdAt: this.session.createdAt,
48
+ expiresAt: this.session.expiresAt
49
+ };
50
+ }
51
+ /**
52
+ * Get current state
53
+ */
54
+ get state() {
55
+ return this.session.state;
56
+ }
57
+ /**
58
+ * Check if session is in terminal state
59
+ */
60
+ get isTerminal() {
61
+ const state = this.session.state;
62
+ return state === "completed" || state === "cancelled" || state === "failed";
63
+ }
64
+ /**
65
+ * Execute the code
66
+ */
67
+ async execute() {
68
+ if (this.executing) {
69
+ throw new Error("Session is already executing");
70
+ }
71
+ this.executing = true;
72
+ try {
73
+ this.log(`Starting execution for session ${this.sessionId}`);
74
+ this.session.start();
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
+ }
83
+ }
84
+ /**
85
+ * Submit a tool result
86
+ */
87
+ async submitToolResult(callId, success, value, error) {
88
+ await this.session.submitToolResult({
89
+ callId,
90
+ success,
91
+ value,
92
+ error
93
+ });
94
+ }
95
+ /**
96
+ * Cancel the session
97
+ */
98
+ async cancel(reason) {
99
+ await this.session.cancel(reason);
100
+ }
101
+ /**
102
+ * Dispose of the executor
103
+ */
104
+ dispose() {
105
+ if (this.unsubscribe) {
106
+ this.unsubscribe();
107
+ this.unsubscribe = null;
108
+ }
109
+ }
110
+ /**
111
+ * Log debug message
112
+ */
113
+ log(message) {
114
+ if (this.debug) {
115
+ console.log(`[SessionExecutor] ${message}`);
116
+ }
117
+ }
118
+ };
119
+ function createSessionExecutor(options) {
120
+ return new SessionExecutor(options);
121
+ }
122
+
123
+ // libs/enclavejs-runtime/src/runtime-worker.ts
124
+ var DEFAULT_CONFIG = {
125
+ port: 3001,
126
+ host: "0.0.0.0",
127
+ wsPath: "/ws",
128
+ maxSessions: 10,
129
+ defaultLimits: {},
130
+ debug: false,
131
+ heartbeatIntervalMs: 15e3,
132
+ connectionTimeoutMs: 3e4
133
+ };
134
+ var RuntimeWorker = class {
135
+ config;
136
+ sessions;
137
+ state = "idle";
138
+ startedAt = 0;
139
+ totalSessions = 0;
140
+ constructor(config = {}) {
141
+ this.config = {
142
+ ...DEFAULT_CONFIG,
143
+ ...config
144
+ };
145
+ this.sessions = /* @__PURE__ */ new Map();
146
+ }
147
+ /**
148
+ * Check if runtime is running
149
+ */
150
+ get isRunning() {
151
+ return this.state === "running";
152
+ }
153
+ /**
154
+ * Start the runtime worker
155
+ */
156
+ async start() {
157
+ if (this.state !== "idle" && this.state !== "stopped") {
158
+ throw new Error(`Cannot start runtime in state: ${this.state}`);
159
+ }
160
+ this.state = "starting";
161
+ this.startedAt = Date.now();
162
+ this.state = "running";
163
+ this.log("Runtime worker started");
164
+ }
165
+ /**
166
+ * Stop the runtime worker
167
+ */
168
+ async stop() {
169
+ if (this.state === "stopped" || this.state === "stopping") {
170
+ return;
171
+ }
172
+ this.state = "stopping";
173
+ const cancelPromises = [];
174
+ for (const [_sessionId, executor] of this.sessions) {
175
+ cancelPromises.push(
176
+ executor.cancel("Runtime stopping").catch(() => {
177
+ })
178
+ );
179
+ }
180
+ await Promise.all(cancelPromises);
181
+ for (const executor of this.sessions.values()) {
182
+ executor.dispose();
183
+ }
184
+ this.sessions.clear();
185
+ this.state = "stopped";
186
+ this.log("Runtime worker stopped");
187
+ }
188
+ /**
189
+ * Get runtime statistics
190
+ */
191
+ getStats() {
192
+ const now = Date.now();
193
+ const memoryUsage = process.memoryUsage();
194
+ return {
195
+ state: this.state,
196
+ activeSessions: this.sessions.size,
197
+ totalSessions: this.totalSessions,
198
+ startedAt: this.startedAt,
199
+ uptimeMs: this.startedAt > 0 ? now - this.startedAt : 0,
200
+ memoryUsage: {
201
+ heapUsed: memoryUsage.heapUsed,
202
+ heapTotal: memoryUsage.heapTotal,
203
+ rss: memoryUsage.rss
204
+ }
205
+ };
206
+ }
207
+ /**
208
+ * Get active sessions
209
+ */
210
+ getSessions() {
211
+ return Array.from(this.sessions.values()).map((executor) => executor.getInfo());
212
+ }
213
+ /**
214
+ * Handle incoming request from channel
215
+ */
216
+ async handleRequest(request, channel) {
217
+ switch (request.type) {
218
+ case "execute":
219
+ await this.handleExecute(request, channel);
220
+ break;
221
+ case "cancel":
222
+ await this.handleCancel(request);
223
+ break;
224
+ case "tool_result":
225
+ await this.handleToolResult(request);
226
+ break;
227
+ case "ping":
228
+ this.log("Received ping");
229
+ break;
230
+ default:
231
+ this.log(`Unknown request type: ${request.type}`);
232
+ }
233
+ }
234
+ /**
235
+ * Handle execute request
236
+ */
237
+ async handleExecute(request, channel) {
238
+ if (!this.isRunning) {
239
+ throw new Error("Runtime is not running");
240
+ }
241
+ if (this.sessions.size >= this.config.maxSessions) {
242
+ throw new Error(`Maximum sessions reached (${this.config.maxSessions})`);
243
+ }
244
+ const { sessionId, code, limits } = request;
245
+ if (this.sessions.has(sessionId)) {
246
+ throw new Error(`Session ${sessionId} already exists`);
247
+ }
248
+ const executor = createSessionExecutor({
249
+ sessionId,
250
+ code,
251
+ limits,
252
+ channel,
253
+ debug: this.config.debug
254
+ });
255
+ this.sessions.set(executor.sessionId, executor);
256
+ this.totalSessions++;
257
+ executor.execute().catch((error) => {
258
+ this.log(`Session ${executor.sessionId} execution error: ${error}`);
259
+ }).finally(() => {
260
+ this.cleanupSession(executor.sessionId);
261
+ });
262
+ }
263
+ /**
264
+ * Handle cancel request
265
+ */
266
+ async handleCancel(request) {
267
+ const executor = this.sessions.get(request.sessionId);
268
+ if (!executor) {
269
+ this.log(`Cancel request for unknown session: ${request.sessionId}`);
270
+ return;
271
+ }
272
+ await executor.cancel(request.reason);
273
+ this.cleanupSession(request.sessionId);
274
+ }
275
+ /**
276
+ * Handle tool result
277
+ */
278
+ async handleToolResult(request) {
279
+ const executor = this.sessions.get(request.sessionId);
280
+ if (!executor) {
281
+ this.log(`Tool result for unknown session: ${request.sessionId}`);
282
+ return;
283
+ }
284
+ await executor.submitToolResult(request.callId, request.success, request.value, request.error);
285
+ }
286
+ /**
287
+ * Clean up a session
288
+ */
289
+ cleanupSession(sessionId) {
290
+ const executor = this.sessions.get(sessionId);
291
+ if (executor) {
292
+ executor.dispose();
293
+ this.sessions.delete(sessionId);
294
+ }
295
+ }
296
+ /**
297
+ * Log debug message
298
+ */
299
+ log(message) {
300
+ if (this.config.debug) {
301
+ console.log(`[RuntimeWorker] ${message}`);
302
+ }
303
+ }
304
+ };
305
+ function createRuntimeWorker(config) {
306
+ return new RuntimeWorker(config);
307
+ }
308
+
309
+ // libs/enclavejs-runtime/src/channels/memory-channel.ts
310
+ var MemoryChannel = class {
311
+ eventQueue = [];
312
+ messageHandlers = /* @__PURE__ */ new Set();
313
+ _isOpen = true;
314
+ /**
315
+ * Whether the channel is open
316
+ */
317
+ get isOpen() {
318
+ return this._isOpen;
319
+ }
320
+ /**
321
+ * Send a stream event
322
+ */
323
+ send(event) {
324
+ if (!this._isOpen) {
325
+ throw new Error("Channel is closed");
326
+ }
327
+ this.eventQueue.push(event);
328
+ }
329
+ /**
330
+ * Get all queued events
331
+ */
332
+ getEvents() {
333
+ return [...this.eventQueue];
334
+ }
335
+ /**
336
+ * Clear the event queue
337
+ */
338
+ clearEvents() {
339
+ this.eventQueue.length = 0;
340
+ }
341
+ /**
342
+ * Receive messages
343
+ */
344
+ onMessage(handler) {
345
+ this.messageHandlers.add(handler);
346
+ return () => {
347
+ this.messageHandlers.delete(handler);
348
+ };
349
+ }
350
+ /**
351
+ * Inject a message (simulate incoming message)
352
+ */
353
+ injectMessage(message) {
354
+ if (!this._isOpen) {
355
+ throw new Error("Channel is closed");
356
+ }
357
+ for (const handler of this.messageHandlers) {
358
+ handler(message);
359
+ }
360
+ }
361
+ /**
362
+ * Close the channel
363
+ */
364
+ close() {
365
+ this._isOpen = false;
366
+ this.messageHandlers.clear();
367
+ }
368
+ };
369
+ function createMemoryChannel() {
370
+ return new MemoryChannel();
371
+ }
372
+ function createMemoryChannelPair() {
373
+ const client = new MemoryChannel();
374
+ const server = new MemoryChannel();
375
+ const originalClientSend = client.send.bind(client);
376
+ client.send = (event) => {
377
+ originalClientSend(event);
378
+ server.injectMessage(event);
379
+ };
380
+ const originalServerSend = server.send.bind(server);
381
+ server.send = (event) => {
382
+ originalServerSend(event);
383
+ client.injectMessage(event);
384
+ };
385
+ return { client, server };
386
+ }
387
+
388
+ // libs/enclavejs-runtime/src/channels/websocket-channel.ts
389
+ import { serializeEvent } from "@enclave-vm/stream";
390
+ var WebSocketChannel = class {
391
+ config;
392
+ ws = null;
393
+ state = "disconnected";
394
+ messageHandlers = /* @__PURE__ */ new Set();
395
+ retryCount = 0;
396
+ retryTimeout = null;
397
+ messageBuffer = [];
398
+ constructor(config) {
399
+ this.config = {
400
+ url: config.url,
401
+ reconnect: {
402
+ enabled: config.reconnect?.enabled ?? true,
403
+ maxRetries: config.reconnect?.maxRetries ?? 5,
404
+ initialDelayMs: config.reconnect?.initialDelayMs ?? 1e3,
405
+ maxDelayMs: config.reconnect?.maxDelayMs ?? 3e4
406
+ },
407
+ connectionTimeoutMs: config.connectionTimeoutMs ?? 1e4,
408
+ debug: config.debug ?? false
409
+ };
410
+ }
411
+ /**
412
+ * Whether the channel is open
413
+ */
414
+ get isOpen() {
415
+ return this.state === "connected";
416
+ }
417
+ /**
418
+ * Get current state
419
+ */
420
+ get channelState() {
421
+ return this.state;
422
+ }
423
+ /**
424
+ * Connect to the WebSocket server
425
+ */
426
+ async connect() {
427
+ if (this.state === "connected" || this.state === "connecting") {
428
+ return;
429
+ }
430
+ return new Promise((resolve, reject) => {
431
+ this.state = "connecting";
432
+ this.log(`Connecting to ${this.config.url}`);
433
+ const WebSocketImpl = typeof WebSocket !== "undefined" ? WebSocket : __require("ws");
434
+ const socket = new WebSocketImpl(this.config.url);
435
+ this.ws = socket;
436
+ const timeout = setTimeout(() => {
437
+ if (this.state === "connecting") {
438
+ socket.close();
439
+ reject(new Error("Connection timeout"));
440
+ }
441
+ }, this.config.connectionTimeoutMs);
442
+ socket.onopen = () => {
443
+ clearTimeout(timeout);
444
+ this.state = "connected";
445
+ this.retryCount = 0;
446
+ this.log("Connected");
447
+ this.flushBuffer();
448
+ resolve();
449
+ };
450
+ socket.onclose = (event) => {
451
+ clearTimeout(timeout);
452
+ this.log(`Disconnected: ${event.code} ${event.reason}`);
453
+ if (this.state !== "closed") {
454
+ this.state = "disconnected";
455
+ this.handleDisconnect();
456
+ }
457
+ };
458
+ socket.onerror = (error) => {
459
+ clearTimeout(timeout);
460
+ this.log(`Error: ${error}`);
461
+ if (this.state === "connecting") {
462
+ reject(new Error("Connection failed"));
463
+ }
464
+ };
465
+ socket.onmessage = (event) => {
466
+ this.handleMessage(event.data);
467
+ };
468
+ });
469
+ }
470
+ /**
471
+ * Send a stream event
472
+ */
473
+ send(event) {
474
+ const data = serializeEvent(event);
475
+ if (this.isOpen && this.ws) {
476
+ this.ws.send(data);
477
+ } else {
478
+ this.messageBuffer.push(data);
479
+ }
480
+ }
481
+ /**
482
+ * Receive messages
483
+ */
484
+ onMessage(handler) {
485
+ this.messageHandlers.add(handler);
486
+ return () => {
487
+ this.messageHandlers.delete(handler);
488
+ };
489
+ }
490
+ /**
491
+ * Close the channel
492
+ */
493
+ close() {
494
+ this.state = "closed";
495
+ if (this.retryTimeout) {
496
+ clearTimeout(this.retryTimeout);
497
+ this.retryTimeout = null;
498
+ }
499
+ if (this.ws) {
500
+ this.ws.close(1e3, "Channel closed");
501
+ this.ws = null;
502
+ }
503
+ this.messageHandlers.clear();
504
+ this.messageBuffer = [];
505
+ }
506
+ /**
507
+ * Handle incoming message
508
+ */
509
+ handleMessage(data) {
510
+ try {
511
+ const message = JSON.parse(data);
512
+ for (const handler of this.messageHandlers) {
513
+ try {
514
+ handler(message);
515
+ } catch (error) {
516
+ this.log(`Message handler error: ${error}`);
517
+ }
518
+ }
519
+ } catch (error) {
520
+ this.log(`Failed to parse message: ${error}`);
521
+ }
522
+ }
523
+ /**
524
+ * Handle disconnect
525
+ */
526
+ handleDisconnect() {
527
+ if (!this.config.reconnect.enabled) {
528
+ return;
529
+ }
530
+ if (this.retryCount >= this.config.reconnect.maxRetries) {
531
+ this.log("Max reconnection attempts reached");
532
+ this.state = "closed";
533
+ return;
534
+ }
535
+ this.state = "reconnecting";
536
+ this.retryCount++;
537
+ const delay = Math.min(
538
+ this.config.reconnect.initialDelayMs * Math.pow(2, this.retryCount - 1),
539
+ this.config.reconnect.maxDelayMs
540
+ );
541
+ this.log(`Reconnecting in ${delay}ms (attempt ${this.retryCount})`);
542
+ this.retryTimeout = setTimeout(() => {
543
+ this.connect().catch((error) => {
544
+ this.log(`Reconnection failed: ${error}`);
545
+ });
546
+ }, delay);
547
+ }
548
+ /**
549
+ * Flush message buffer
550
+ */
551
+ flushBuffer() {
552
+ if (!this.isOpen || !this.ws) {
553
+ return;
554
+ }
555
+ for (const data of this.messageBuffer) {
556
+ this.ws.send(data);
557
+ }
558
+ this.messageBuffer = [];
559
+ }
560
+ /**
561
+ * Log debug message
562
+ */
563
+ log(message) {
564
+ if (this.config.debug) {
565
+ console.log(`[WebSocketChannel] ${message}`);
566
+ }
567
+ }
568
+ };
569
+ function createWebSocketChannel(config) {
570
+ return new WebSocketChannel(config);
571
+ }
572
+ export {
573
+ MemoryChannel,
574
+ RuntimeWorker as RuntimeWorkerImpl,
575
+ SessionExecutor,
576
+ WebSocketChannel,
577
+ createMemoryChannel,
578
+ createMemoryChannelPair,
579
+ createRuntimeWorker,
580
+ createSessionExecutor,
581
+ createWebSocketChannel
582
+ };
@@ -0,0 +1,6 @@
1
+ {
2
+ "type": "module",
3
+ "sideEffects": false,
4
+ "main": "./index.mjs",
5
+ "module": "./index.mjs"
6
+ }