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