@enclave-vm/runtime 2.19.1 → 2.20.0-rc.1

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.d.ts CHANGED
@@ -1,26 +1,27 @@
1
1
  /**
2
2
  * @enclave-vm/runtime
3
3
  *
4
- * Standalone runtime worker for EnclaveJS.
5
- * Can be deployed as a separate process/worker for distributed execution.
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
- * port: 3001,
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
- * await worker.start();
18
- * console.log('Runtime is ready!');
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';
package/index.js CHANGED
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  MemoryChannel: () => MemoryChannel,
24
+ RuntimeNotImplementedError: () => RuntimeNotImplementedError,
24
25
  RuntimeWorkerImpl: () => RuntimeWorker,
25
26
  SessionExecutor: () => SessionExecutor,
26
27
  WebSocketChannel: () => WebSocketChannel,
@@ -34,6 +35,15 @@ module.exports = __toCommonJS(index_exports);
34
35
 
35
36
  // libs/runtime/src/session-executor.ts
36
37
  var import_core = require("@enclave-vm/core");
38
+ var RuntimeNotImplementedError = class extends Error {
39
+ code = "NOT_IMPLEMENTED";
40
+ constructor(operation) {
41
+ super(
42
+ `${operation} is not implemented: @enclave-vm/runtime does not execute code. Run scripts with @enclave-vm/broker or @enclave-vm/core.`
43
+ );
44
+ this.name = "RuntimeNotImplementedError";
45
+ }
46
+ };
37
47
  var SessionExecutor = class {
38
48
  sessionId;
39
49
  session;
@@ -41,7 +51,6 @@ var SessionExecutor = class {
41
51
  code;
42
52
  debug;
43
53
  unsubscribe = null;
44
- executing = false;
45
54
  constructor(options) {
46
55
  const { code, channel, limits, debug = false } = options;
47
56
  this.code = code;
@@ -89,24 +98,24 @@ var SessionExecutor = class {
89
98
  return state === "completed" || state === "cancelled" || state === "failed";
90
99
  }
91
100
  /**
92
- * Execute the code
101
+ * Execute the code: not implemented.
102
+ *
103
+ * Nothing in this package runs a script. Rather than report a running session that never
104
+ * finishes, the session is ended with the error code `NOT_IMPLEMENTED` (the channel
105
+ * receives its `final` event) and the returned promise rejects.
106
+ *
107
+ * @throws RuntimeNotImplementedError always
93
108
  */
94
109
  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;
110
+ const error = new RuntimeNotImplementedError("SessionExecutor.execute()");
111
+ if (!this.isTerminal) {
112
+ this.log(`Session ${this.sessionId} cannot be executed: ${error.message} (${this.code.length} characters)`);
113
+ if (this.session.state === "starting") {
114
+ this.session.start();
115
+ }
116
+ this.session.fail(error);
109
117
  }
118
+ throw error;
110
119
  }
111
120
  /**
112
121
  * Submit a tool result
@@ -150,7 +159,7 @@ function createSessionExecutor(options) {
150
159
  // libs/runtime/src/runtime-worker.ts
151
160
  var DEFAULT_CONFIG = {
152
161
  port: 3001,
153
- host: "0.0.0.0",
162
+ host: "127.0.0.1",
154
163
  wsPath: "/ws",
155
164
  maxSessions: 10,
156
165
  defaultLimits: {},
@@ -158,6 +167,19 @@ var DEFAULT_CONFIG = {
158
167
  heartbeatIntervalMs: 15e3,
159
168
  connectionTimeoutMs: 3e4
160
169
  };
170
+ function resolveConfig(config) {
171
+ const resolved = { ...DEFAULT_CONFIG };
172
+ const target = resolved;
173
+ for (const [key, value] of Object.entries(config ?? {})) {
174
+ if (value !== void 0) {
175
+ target[key] = value;
176
+ }
177
+ }
178
+ if (typeof resolved.maxSessions !== "number" || !Number.isSafeInteger(resolved.maxSessions) || resolved.maxSessions < 1) {
179
+ throw new RangeError("maxSessions must be a positive integer");
180
+ }
181
+ return resolved;
182
+ }
161
183
  var RuntimeWorker = class {
162
184
  config;
163
185
  sessions;
@@ -165,10 +187,7 @@ var RuntimeWorker = class {
165
187
  startedAt = 0;
166
188
  totalSessions = 0;
167
189
  constructor(config = {}) {
168
- this.config = {
169
- ...DEFAULT_CONFIG,
170
- ...config
171
- };
190
+ this.config = resolveConfig(config);
172
191
  this.sessions = /* @__PURE__ */ new Map();
173
192
  }
174
193
  /**
@@ -178,7 +197,10 @@ var RuntimeWorker = class {
178
197
  return this.state === "running";
179
198
  }
180
199
  /**
181
- * Start the runtime worker
200
+ * Start the runtime worker: mark it as running, so that `handleRequest()` accepts requests.
201
+ *
202
+ * No server is started and no port is opened. The requests come from the application that
203
+ * embeds the worker.
182
204
  */
183
205
  async start() {
184
206
  if (this.state !== "idle" && this.state !== "stopped") {
@@ -239,8 +261,14 @@ var RuntimeWorker = class {
239
261
  }
240
262
  /**
241
263
  * Handle incoming request from channel
264
+ *
265
+ * The caller is trusted: nothing here authenticates where a request came from. An `execute`
266
+ * request rejects with `RuntimeNotImplementedError`.
242
267
  */
243
268
  async handleRequest(request, channel) {
269
+ if (typeof request !== "object" || request === null || typeof request.type !== "string") {
270
+ throw new TypeError("Invalid runtime request");
271
+ }
244
272
  switch (request.type) {
245
273
  case "execute":
246
274
  await this.handleExecute(request, channel);
@@ -259,7 +287,10 @@ var RuntimeWorker = class {
259
287
  }
260
288
  }
261
289
  /**
262
- * Handle execute request
290
+ * Handle execute request: the session is created, ended with the error code
291
+ * `NOT_IMPLEMENTED` on its channel, and removed again.
292
+ *
293
+ * @throws RuntimeNotImplementedError when the request was valid
263
294
  */
264
295
  async handleExecute(request, channel) {
265
296
  if (!this.isRunning) {
@@ -269,6 +300,9 @@ var RuntimeWorker = class {
269
300
  throw new Error(`Maximum sessions reached (${this.config.maxSessions})`);
270
301
  }
271
302
  const { sessionId, code, limits } = request;
303
+ if (typeof code !== "string") {
304
+ throw new TypeError("Invalid execute request: `code` must be a string");
305
+ }
272
306
  if (this.sessions.has(sessionId)) {
273
307
  throw new Error(`Session ${sessionId} already exists`);
274
308
  }
@@ -281,11 +315,14 @@ var RuntimeWorker = class {
281
315
  });
282
316
  this.sessions.set(executor.sessionId, executor);
283
317
  this.totalSessions++;
284
- executor.execute().catch((error) => {
318
+ try {
319
+ await executor.execute();
320
+ } catch (error) {
285
321
  this.log(`Session ${executor.sessionId} execution error: ${error}`);
286
- }).finally(() => {
322
+ throw error;
323
+ } finally {
287
324
  this.cleanupSession(executor.sessionId);
288
- });
325
+ }
289
326
  }
290
327
  /**
291
328
  * Handle cancel request
@@ -414,6 +451,7 @@ function createMemoryChannelPair() {
414
451
 
415
452
  // libs/runtime/src/channels/websocket-channel.ts
416
453
  var import_stream = require("@enclave-vm/stream");
454
+ var DEFAULT_MAX_BUFFERED_MESSAGES = 1e3;
417
455
  var WebSocketChannel = class {
418
456
  config;
419
457
  ws = null;
@@ -421,8 +459,14 @@ var WebSocketChannel = class {
421
459
  messageHandlers = /* @__PURE__ */ new Set();
422
460
  retryCount = 0;
423
461
  retryTimeout = null;
462
+ /** Fails the connect that is in progress, if any. */
463
+ pendingConnectFailure = null;
424
464
  messageBuffer = [];
425
465
  constructor(config) {
466
+ const maxBufferedMessages = config.maxBufferedMessages ?? DEFAULT_MAX_BUFFERED_MESSAGES;
467
+ if (typeof maxBufferedMessages !== "number" || !Number.isSafeInteger(maxBufferedMessages) || maxBufferedMessages < 1) {
468
+ throw new RangeError("maxBufferedMessages must be a positive integer");
469
+ }
426
470
  this.config = {
427
471
  url: config.url,
428
472
  reconnect: {
@@ -432,6 +476,7 @@ var WebSocketChannel = class {
432
476
  maxDelayMs: config.reconnect?.maxDelayMs ?? 3e4
433
477
  },
434
478
  connectionTimeoutMs: config.connectionTimeoutMs ?? 1e4,
479
+ maxBufferedMessages,
435
480
  debug: config.debug ?? false
436
481
  };
437
482
  }
@@ -450,11 +495,19 @@ var WebSocketChannel = class {
450
495
  /**
451
496
  * Connect to the WebSocket server
452
497
  */
453
- async connect() {
498
+ connect() {
454
499
  if (this.state === "connected" || this.state === "connecting") {
455
- return;
500
+ return Promise.resolve();
456
501
  }
457
502
  return new Promise((resolve, reject) => {
503
+ let settled = false;
504
+ const fail = (error) => {
505
+ if (settled) return;
506
+ settled = true;
507
+ this.pendingConnectFailure = null;
508
+ reject(error);
509
+ };
510
+ this.pendingConnectFailure = fail;
458
511
  this.state = "connecting";
459
512
  this.log(`Connecting to ${this.config.url}`);
460
513
  const WebSocketImpl = typeof WebSocket !== "undefined" ? WebSocket : require("ws");
@@ -462,12 +515,15 @@ var WebSocketChannel = class {
462
515
  this.ws = socket;
463
516
  const timeout = setTimeout(() => {
464
517
  if (this.state === "connecting") {
518
+ fail(new Error("Connection timeout"));
465
519
  socket.close();
466
- reject(new Error("Connection timeout"));
467
520
  }
468
521
  }, this.config.connectionTimeoutMs);
469
522
  socket.onopen = () => {
470
523
  clearTimeout(timeout);
524
+ if (settled) return;
525
+ settled = true;
526
+ this.pendingConnectFailure = null;
471
527
  this.state = "connected";
472
528
  this.retryCount = 0;
473
529
  this.log("Connected");
@@ -477,6 +533,7 @@ var WebSocketChannel = class {
477
533
  socket.onclose = (event) => {
478
534
  clearTimeout(timeout);
479
535
  this.log(`Disconnected: ${event.code} ${event.reason}`);
536
+ fail(new Error("Connection closed before it opened"));
480
537
  if (this.state !== "closed") {
481
538
  this.state = "disconnected";
482
539
  this.handleDisconnect();
@@ -486,7 +543,7 @@ var WebSocketChannel = class {
486
543
  clearTimeout(timeout);
487
544
  this.log(`Error: ${error}`);
488
545
  if (this.state === "connecting") {
489
- reject(new Error("Connection failed"));
546
+ fail(new Error("Connection failed"));
490
547
  }
491
548
  };
492
549
  socket.onmessage = (event) => {
@@ -501,8 +558,10 @@ var WebSocketChannel = class {
501
558
  const data = (0, import_stream.serializeEvent)(event);
502
559
  if (this.isOpen && this.ws) {
503
560
  this.ws.send(data);
504
- } else {
561
+ } else if (this.messageBuffer.length < this.config.maxBufferedMessages) {
505
562
  this.messageBuffer.push(data);
563
+ } else {
564
+ this.log("Message buffer is full, dropping event");
506
565
  }
507
566
  }
508
567
  /**
@@ -519,6 +578,7 @@ var WebSocketChannel = class {
519
578
  */
520
579
  close() {
521
580
  this.state = "closed";
581
+ this.pendingConnectFailure?.(new Error("Channel closed"));
522
582
  if (this.retryTimeout) {
523
583
  clearTimeout(this.retryTimeout);
524
584
  this.retryTimeout = null;
@@ -599,6 +659,7 @@ function createWebSocketChannel(config) {
599
659
  // Annotate the CommonJS export names for ESM import in node:
600
660
  0 && (module.exports = {
601
661
  MemoryChannel,
662
+ RuntimeNotImplementedError,
602
663
  RuntimeWorkerImpl,
603
664
  SessionExecutor,
604
665
  WebSocketChannel,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@enclave-vm/runtime",
3
- "version": "2.19.1",
4
- "description": "Standalone runtime worker for EnclaveJS - deployable execution environment",
3
+ "version": "2.20.0-rc.1",
4
+ "description": "Building blocks of a runtime worker for EnclaveJS: session bookkeeping and channels (does not execute code)",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
7
7
  "license": "Apache-2.0",
@@ -36,9 +36,9 @@
36
36
  "enclave-runtime": "./cli.js"
37
37
  },
38
38
  "dependencies": {
39
- "@enclave-vm/core": "2.19.1",
40
- "@enclave-vm/stream": "2.19.1",
41
- "@enclave-vm/types": "2.19.1"
39
+ "@enclave-vm/core": "2.20.0-rc.1",
40
+ "@enclave-vm/stream": "2.20.0-rc.1",
41
+ "@enclave-vm/types": "2.20.0-rc.1"
42
42
  },
43
43
  "devDependencies": {
44
44
  "ws": "^8.19.0"
@@ -1,8 +1,12 @@
1
1
  /**
2
2
  * Runtime Worker
3
3
  *
4
- * Standalone worker that executes Enclave sessions.
5
- * Can run as a separate process/worker and communicate via WebSocket.
4
+ * Session bookkeeping of a runtime worker, for requests that the embedding application hands
5
+ * to `handleRequest()` together with a channel.
6
+ *
7
+ * What it does not do: it opens no port (`start()` only changes the worker's state; `port`,
8
+ * `host` and `wsPath` are not used), it authenticates nobody, and it does not execute code
9
+ * (an `execute` request is answered with `RuntimeNotImplementedError`).
6
10
  *
7
11
  * @packageDocumentation
8
12
  */
@@ -10,8 +14,8 @@ import type { RuntimeConfig, RuntimeStats, RuntimeSession, RuntimeWorker as IRun
10
14
  /**
11
15
  * Runtime worker implementation
12
16
  *
13
- * Manages multiple session executors and provides a WebSocket interface
14
- * for communication with the broker.
17
+ * Keeps the session executors of the requests it is handed. It has no network interface of
18
+ * its own, and executing a session's code is not implemented.
15
19
  */
16
20
  export declare class RuntimeWorker implements IRuntimeWorker {
17
21
  private readonly config;
@@ -25,7 +29,10 @@ export declare class RuntimeWorker implements IRuntimeWorker {
25
29
  */
26
30
  get isRunning(): boolean;
27
31
  /**
28
- * Start the runtime worker
32
+ * Start the runtime worker: mark it as running, so that `handleRequest()` accepts requests.
33
+ *
34
+ * No server is started and no port is opened. The requests come from the application that
35
+ * embeds the worker.
29
36
  */
30
37
  start(): Promise<void>;
31
38
  /**
@@ -42,10 +49,16 @@ export declare class RuntimeWorker implements IRuntimeWorker {
42
49
  getSessions(): RuntimeSession[];
43
50
  /**
44
51
  * Handle incoming request from channel
52
+ *
53
+ * The caller is trusted: nothing here authenticates where a request came from. An `execute`
54
+ * request rejects with `RuntimeNotImplementedError`.
45
55
  */
46
56
  handleRequest(request: RuntimeRequest, channel: RuntimeChannel): Promise<void>;
47
57
  /**
48
- * Handle execute request
58
+ * Handle execute request: the session is created, ended with the error code
59
+ * `NOT_IMPLEMENTED` on its channel, and removed again.
60
+ *
61
+ * @throws RuntimeNotImplementedError when the request was valid
49
62
  */
50
63
  private handleExecute;
51
64
  /**
@@ -1,12 +1,26 @@
1
1
  /**
2
2
  * Session Executor
3
3
  *
4
- * Wraps enclave-vm session for runtime execution.
4
+ * Wraps an enclave-vm session and forwards its events to a runtime channel.
5
+ *
6
+ * It does not execute code: no execution engine is wired into this package. `execute()`
7
+ * says so (see `RuntimeNotImplementedError`).
5
8
  *
6
9
  * @packageDocumentation
7
10
  */
8
11
  import type { SessionId, CallId, SessionLimits } from '@enclave-vm/types';
9
12
  import type { RuntimeChannel, RuntimeSession } from './types';
13
+ /**
14
+ * Thrown by the operations of this package that are not implemented.
15
+ *
16
+ * `@enclave-vm/runtime` has the session bookkeeping and the channels of a runtime worker, but
17
+ * nothing in it runs a script. Scripts are run by `@enclave-vm/broker` (sessions, tools and
18
+ * streaming over HTTP) and `@enclave-vm/core` (the sandbox).
19
+ */
20
+ export declare class RuntimeNotImplementedError extends Error {
21
+ readonly code = "NOT_IMPLEMENTED";
22
+ constructor(operation: string);
23
+ }
10
24
  /**
11
25
  * Session executor options
12
26
  */
@@ -16,7 +30,7 @@ export interface SessionExecutorOptions {
16
30
  */
17
31
  sessionId?: SessionId;
18
32
  /**
19
- * Code to execute
33
+ * Code of the session. It is kept and never run: see `SessionExecutor.execute()`.
20
34
  */
21
35
  code: string;
22
36
  /**
@@ -35,8 +49,8 @@ export interface SessionExecutorOptions {
35
49
  /**
36
50
  * Session executor
37
51
  *
38
- * Manages execution of a single session, handling communication
39
- * between the enclave-vm session and the runtime channel.
52
+ * Holds one session and forwards its events to the runtime channel. Cancelling and tool
53
+ * results go to the session; executing the session's code is not implemented.
40
54
  */
41
55
  export declare class SessionExecutor {
42
56
  readonly sessionId: SessionId;
@@ -45,7 +59,6 @@ export declare class SessionExecutor {
45
59
  private readonly code;
46
60
  private readonly debug;
47
61
  private unsubscribe;
48
- private executing;
49
62
  constructor(options: SessionExecutorOptions);
50
63
  /**
51
64
  * Get session info
@@ -60,7 +73,13 @@ export declare class SessionExecutor {
60
73
  */
61
74
  get isTerminal(): boolean;
62
75
  /**
63
- * Execute the code
76
+ * Execute the code: not implemented.
77
+ *
78
+ * Nothing in this package runs a script. Rather than report a running session that never
79
+ * finishes, the session is ended with the error code `NOT_IMPLEMENTED` (the channel
80
+ * receives its `final` event) and the returned promise rejects.
81
+ *
82
+ * @throws RuntimeNotImplementedError always
64
83
  */
65
84
  execute(): Promise<void>;
66
85
  /**
package/types.d.ts CHANGED
@@ -8,25 +8,28 @@
8
8
  import type { SessionId, SessionLimits, StreamEvent, RuntimeChannelMessage } from '@enclave-vm/types';
9
9
  /**
10
10
  * Runtime configuration
11
+ *
12
+ * `port`, `host` and `wsPath` are kept for compatibility and are not used: this package
13
+ * starts no server and opens no port.
11
14
  */
12
15
  export interface RuntimeConfig {
13
16
  /**
14
- * Port to listen on
17
+ * Not used (no server is started)
15
18
  * @default 3001
16
19
  */
17
20
  port?: number;
18
21
  /**
19
- * Host to bind to
20
- * @default '0.0.0.0'
22
+ * Not used (no server is started)
23
+ * @default '127.0.0.1'
21
24
  */
22
25
  host?: string;
23
26
  /**
24
- * Path for WebSocket connections
27
+ * Not used (no server is started)
25
28
  * @default '/ws'
26
29
  */
27
30
  wsPath?: string;
28
31
  /**
29
- * Maximum concurrent sessions per runtime
32
+ * Maximum concurrent sessions per runtime. A positive integer.
30
33
  * @default 10
31
34
  */
32
35
  maxSessions?: number;