@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/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;
@@ -423,6 +461,10 @@ var WebSocketChannel = class {
423
461
  retryTimeout = null;
424
462
  messageBuffer = [];
425
463
  constructor(config) {
464
+ const maxBufferedMessages = config.maxBufferedMessages ?? DEFAULT_MAX_BUFFERED_MESSAGES;
465
+ if (typeof maxBufferedMessages !== "number" || !Number.isSafeInteger(maxBufferedMessages) || maxBufferedMessages < 1) {
466
+ throw new RangeError("maxBufferedMessages must be a positive integer");
467
+ }
426
468
  this.config = {
427
469
  url: config.url,
428
470
  reconnect: {
@@ -432,6 +474,7 @@ var WebSocketChannel = class {
432
474
  maxDelayMs: config.reconnect?.maxDelayMs ?? 3e4
433
475
  },
434
476
  connectionTimeoutMs: config.connectionTimeoutMs ?? 1e4,
477
+ maxBufferedMessages,
435
478
  debug: config.debug ?? false
436
479
  };
437
480
  }
@@ -501,8 +544,10 @@ var WebSocketChannel = class {
501
544
  const data = (0, import_stream.serializeEvent)(event);
502
545
  if (this.isOpen && this.ws) {
503
546
  this.ws.send(data);
504
- } else {
547
+ } else if (this.messageBuffer.length < this.config.maxBufferedMessages) {
505
548
  this.messageBuffer.push(data);
549
+ } else {
550
+ this.log("Message buffer is full, dropping event");
506
551
  }
507
552
  }
508
553
  /**
@@ -599,6 +644,7 @@ function createWebSocketChannel(config) {
599
644
  // Annotate the CommonJS export names for ESM import in node:
600
645
  0 && (module.exports = {
601
646
  MemoryChannel,
647
+ RuntimeNotImplementedError,
602
648
  RuntimeWorkerImpl,
603
649
  SessionExecutor,
604
650
  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.19.2",
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.19.2",
40
+ "@enclave-vm/stream": "2.19.2",
41
+ "@enclave-vm/types": "2.19.2"
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;