@enclave-vm/client 2.20.0 → 2.20.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.
Files changed (2) hide show
  1. package/README.md +112 -153
  2. package/package.json +3 -3
package/README.md CHANGED
@@ -1,44 +1,30 @@
1
1
  # @enclave-vm/client
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/@enclave-vm/client.svg)](https://www.npmjs.com/package/@enclave-vm/client)
4
- [![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
5
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
6
-
7
- > Browser and Node.js client SDK for the EnclaveJS streaming runtime
3
+ A client for an EnclaveJS broker, for browser and Node.js applications that send scripts to a broker and follow their sessions.
8
4
 
9
- The @enclave-vm/client package is a client for an EnclaveJS broker, for browsers and Node.js applications. It sends a script to the broker over HTTP, reads the events of the session as they arrive, and gives you the result.
5
+ [![npm version](https://img.shields.io/npm/v/@enclave-vm/client.svg)](https://www.npmjs.com/package/@enclave-vm/client)
6
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/agentfront/enclave/blob/main/LICENSE)
10
7
 
11
- ## Features
8
+ The client talks to the HTTP routes of [`@enclave-vm/broker`](https://www.npmjs.com/package/@enclave-vm/broker): it creates a session with the script, reads the session's events as they arrive (NDJSON over `fetch`), reconnects when the stream is lost, and gives you the result. It builds on [`@enclave-vm/stream`](https://www.npmjs.com/package/@enclave-vm/stream) and [`@enclave-vm/types`](https://www.npmjs.com/package/@enclave-vm/types), and [`@enclave-vm/react`](https://www.npmjs.com/package/@enclave-vm/react) wraps it for React.
12
9
 
13
- - **Cross-Platform**: Works in browsers and Node.js, on top of `fetch`
14
- - **Streaming Support**: Session events are passed to your handlers as they arrive
15
- - **Auto-Reconnection**: A lost connection is resumed after the last event received, so every event is delivered once and in order
16
- - **Cancellation**: Stop a session with its handle, by its id, or with an `AbortSignal`
17
- - **Type-Safe**: Full TypeScript support
10
+ Tools run on the broker. The client is told about tool calls (`onToolCall`, `onToolResultApplied`), but it executes nothing and has no API to register tools.
18
11
 
19
- ## Installation
12
+ ## Install
20
13
 
21
14
  ```bash
22
15
  npm install @enclave-vm/client
23
- # or
24
- yarn add @enclave-vm/client
25
- # or
26
- pnpm add @enclave-vm/client
27
16
  ```
28
17
 
29
- ## Quick Start
18
+ ## Quick start
30
19
 
31
20
  ```typescript
32
21
  import { EnclaveClient } from '@enclave-vm/client';
33
22
 
34
- // Create client
35
- const client = new EnclaveClient({
36
- baseUrl: 'https://api.example.com',
37
- });
23
+ const client = new EnclaveClient({ baseUrl: 'https://api.example.com' });
38
24
 
39
- // Execute code and wait for the result
25
+ // Runs on the broker; `getUser` is a tool registered there
40
26
  const result = await client.execute(`
41
- const user = await callTool('getUser', { id: 123 });
27
+ const user = await callTool('getUser', { id: '123' });
42
28
  return { name: user.name };
43
29
  `);
44
30
 
@@ -49,142 +35,133 @@ if (result.success) {
49
35
  }
50
36
  ```
51
37
 
52
- Tools run on the broker. The client is told about tool calls (`onToolCall`, `onToolResultApplied`), but it executes nothing and has no API to register tools.
53
-
54
- ## Event Handling
38
+ `await client.execute(code, options)` is the same as `await client.executeStream(code, options).wait()`.
55
39
 
56
- Pass handlers with the options of `execute()` or `executeStream()`:
40
+ ## Configuration
57
41
 
58
42
  ```typescript
59
43
  import { EnclaveClient } from '@enclave-vm/client';
60
44
 
61
- const client = new EnclaveClient({ baseUrl: 'https://api.example.com' });
62
-
63
- const result = await client.execute(code, {
64
- onSessionInit: (event) => {
65
- console.log('Session started:', event.sessionId);
66
- },
67
- onStdout: (chunk) => {
68
- process.stdout.write(chunk);
69
- },
70
- onLog: (level, message, data) => {
71
- console.log(`[${level}]`, message, data);
72
- },
73
- onToolCall: (callId, toolName, args) => {
74
- console.log(`Tool called: ${toolName}`, args);
75
- },
76
- onToolResultApplied: (callId) => {
77
- console.log(`Tool result applied: ${callId}`);
78
- },
79
- onError: (errorCode, message) => {
80
- console.error(`${errorCode}: ${message}`);
81
- },
45
+ const client = new EnclaveClient({
46
+ baseUrl: 'https://api.example.com',
47
+ headers: { Authorization: 'Bearer your-api-token' },
48
+ timeout: 60000,
49
+ autoReconnect: true,
50
+ maxReconnectAttempts: 3,
51
+ reconnectDelay: 1000,
52
+ maxEventLength: 8388608,
82
53
  });
83
54
  ```
84
55
 
85
- The handlers are `onEvent` (every event), `onSessionInit`, `onStdout`, `onLog`, `onToolCall`, `onToolResultApplied`, `onHeartbeat`, `onError`, `onPartialResult`, `onToolProgress`, `onDeadlineExceeded` and `onCatalogChanged`. The end of the session has no handler of its own: the result comes from the promise of `execute()`, or from `wait()` on the handle.
56
+ | Option | Type | Default | Meaning |
57
+ | ---------------------- | ------------------------ | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
58
+ | `baseUrl` | `string` | Required | Base URL of the broker's routes (a trailing `/` is removed) |
59
+ | `headers` | `Record<string, string>` | none | Headers sent with every request |
60
+ | `timeout` | `number` | `60000` | How long the client waits for the server, in milliseconds: for the answer to a request, and for the next event on an open stream (there, never less than two heartbeat intervals). When it runs out the connection counts as lost. |
61
+ | `autoReconnect` | `boolean` | `true` | Reconnect when the connection is lost |
62
+ | `maxReconnectAttempts` | `number` | `3` | Reconnection attempts in a row before the session fails |
63
+ | `reconnectDelay` | `number` | `1000` | Base delay before a reconnection attempt, in milliseconds; it grows with each attempt in a row |
64
+ | `maxEventLength` | `number` | `8388608` | Largest event the client accepts, in characters (8 MiB). A longer event ends the session with `PARSE_ERROR`. |
65
+ | `fetch` | `typeof fetch` | global `fetch` | Custom fetch implementation. Required where there is no global `fetch`. |
66
+
67
+ These are all the options. Any other option makes the constructor throw a `TypeError` that names it: the client has no `encryption`, `auth`, `serverUrl` or `reconnect` option. A value the client cannot use, such as a `timeout` of `0`, throws as well.
68
+
69
+ ## Executing a script
86
70
 
87
- ## Streaming Execution
71
+ `execute(code, options?)` and `executeStream(code, options?)` take the same options: the event handlers below plus `sessionId`, `limits` and `signal`.
88
72
 
89
- `executeStream()` returns a handle for the running session at once:
73
+ | Option | Type | Meaning |
74
+ | ----------- | ------------------------ | ------------------------------------------------------------------- |
75
+ | `sessionId` | `SessionId` | Id of the session; generated (`s_` and a UUID) when left out |
76
+ | `limits` | `Partial<SessionLimits>` | Limits to ask the broker for; see [Session limits](#session-limits) |
77
+ | `signal` | `AbortSignal` | Aborting it cancels the session, like `cancel()` |
78
+
79
+ ### Event handlers
90
80
 
91
81
  ```typescript
92
82
  import { EnclaveClient } from '@enclave-vm/client';
93
83
 
94
84
  const client = new EnclaveClient({ baseUrl: 'https://api.example.com' });
95
85
 
96
- const session = client.executeStream(code, {
97
- onStdout: (chunk) => {
98
- process.stdout.write(chunk);
99
- },
86
+ const result = await client.execute('return 1 + 1', {
87
+ onSessionInit: (event) => console.log('Session started:', event.sessionId),
88
+ onLog: (level, message, data) => console.log(`[${level}]`, message, data),
89
+ onToolCall: (callId, toolName, args) => console.log(`Tool called: ${toolName}`, args),
90
+ onToolResultApplied: (callId) => console.log(`Tool result applied: ${callId}`),
91
+ onError: (code, message) => console.error(`${code}: ${message}`),
100
92
  });
93
+ ```
101
94
 
102
- console.log('Session ID:', session.sessionId);
103
- console.log('Active:', session.isActive());
104
- console.log('Events so far:', session.getEvents().length);
95
+ | Handler | Arguments | Called for |
96
+ | --------------------- | ----------------------------------------- | ----------------------------------------------------------------------------------- |
97
+ | `onEvent` | `(event)` | Every event |
98
+ | `onSessionInit` | `(event)` | `session_init` |
99
+ | `onStdout` | `(chunk)` | `stdout` |
100
+ | `onLog` | `(level, message, data?)` | `log` |
101
+ | `onToolCall` | `(callId, toolName, args)` | `tool_call` |
102
+ | `onToolResultApplied` | `(callId)` | `tool_result_applied` |
103
+ | `onHeartbeat` | `()` | `heartbeat` |
104
+ | `onError` | `(code, message)` | An `error` event, or `CANCEL_FAILED` when the broker did not confirm a cancellation |
105
+ | `onPartialResult` | `(path, data?, error?, hasNext?)` | `partial_result` |
106
+ | `onToolProgress` | `(callId, phase, elapsedMs)` | `tool_progress` |
107
+ | `onDeadlineExceeded` | `(elapsedMs, budgetMs)` | `deadline_exceeded` |
108
+ | `onCatalogChanged` | `(version, addedActions, removedActions)` | `catalog_changed` |
105
109
 
106
- // Wait for the result
107
- const result = await session.wait();
108
- ```
110
+ The end of the session has no handler of its own: the result comes from the promise of `execute()`, or from `wait()` on the handle.
109
111
 
110
- `await client.execute(code, options)` is the same as `await client.executeStream(code, options).wait()`.
112
+ ### Session handles
111
113
 
112
- ## Configuration Options
114
+ `executeStream()` returns a `SessionHandle` at once:
113
115
 
114
116
  ```typescript
115
117
  import { EnclaveClient } from '@enclave-vm/client';
116
118
 
117
- const client = new EnclaveClient({
118
- // Connection
119
- baseUrl: 'https://api.example.com',
120
-
121
- // Headers sent with every request (for example credentials)
122
- headers: {
123
- Authorization: 'Bearer your-api-token',
124
- },
119
+ const client = new EnclaveClient({ baseUrl: 'https://api.example.com' });
125
120
 
126
- // Waiting for the server
127
- timeout: 60000,
121
+ const session = client.executeStream('return 1 + 1', { onStdout: (chunk) => console.log(chunk) });
128
122
 
129
- // Reconnection
130
- autoReconnect: true,
131
- maxReconnectAttempts: 3,
132
- reconnectDelay: 1000,
123
+ console.log('Session ID:', session.sessionId);
124
+ console.log('Active:', session.isActive());
125
+ console.log('Events so far:', session.getEvents().length);
133
126
 
134
- // Largest event accepted
135
- maxEventLength: 8388608,
136
- });
127
+ const result = await session.wait();
137
128
  ```
138
129
 
139
- | Option | Default | Description |
140
- | ---------------------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
141
- | `baseUrl` | Required | Base URL of the broker |
142
- | `headers` | none | Headers sent with every request |
143
- | `timeout` | `60000` | How long the client waits for the server, in milliseconds: for the answer to a request, and for the next event on an open stream (there, never less than two heartbeat intervals). When it runs out the connection counts as lost. |
144
- | `autoReconnect` | `true` | Reconnect when the connection is lost |
145
- | `maxReconnectAttempts` | `3` | Reconnection attempts in a row before the session fails |
146
- | `reconnectDelay` | `1000` | Base delay before a reconnection attempt, in milliseconds; it grows with each attempt in a row |
147
- | `maxEventLength` | `8388608` | Largest event the client accepts, in characters (8 MiB). A longer event ends the session with `PARSE_ERROR`. |
148
- | `fetch` | global `fetch` | Custom fetch implementation. Required where there is no global `fetch`. |
130
+ | Member | Description |
131
+ | ----------------- | ------------------------------------------------ |
132
+ | `sessionId` | Id of the session |
133
+ | `wait()` | Resolves with the `SessionResult` |
134
+ | `cancel(reason?)` | Cancels the session (see below) |
135
+ | `getEvents()` | A copy of the events received so far |
136
+ | `isActive()` | Whether the session has not ended on this client |
149
137
 
150
- These are all the options. Any other option makes the constructor throw a `TypeError` that names it: the client has no `encryption`, `auth`, `serverUrl` or `reconnect` option. A value the client cannot use, such as a `timeout` of `0`, throws as well.
151
-
152
- The client does not encrypt. Requests and events travel as plain JSON over HTTP and are protected only by the transport: use an `https:` base URL, and send credentials with `headers`.
138
+ `SessionResult` has `success`, `sessionId`, `value`, `error` (`{ code?, message }`), `errors` (per-path errors), `stats` (`durationMs`, `toolCallCount`, `stdoutBytes`) and `events`.
153
139
 
154
- ## Session Management
140
+ ### Session ids and the broker
155
141
 
156
- Every execution is a session with an id that starts with `s_`. The client generates the id unless you pass one with the `sessionId` option; an id that does not start with `s_` is refused before a request is made.
142
+ Every session has an id that starts with `s_`. An id that does not, or an id that is already running on this client, is refused before a request is made (`SESSION_ERROR`).
157
143
 
158
144
  ```typescript
159
- import { EnclaveClient } from '@enclave-vm/client';
160
-
161
- const client = new EnclaveClient({ baseUrl: 'https://api.example.com' });
162
-
163
- const session = client.executeStream(code, {
164
- // Limits requested for the session
165
- limits: {
166
- sessionTtlMs: 60000,
167
- maxToolCalls: 100,
168
- },
169
- });
170
-
171
- console.log('Session ID:', session.sessionId);
172
-
173
- // Ask the broker about the session (null if it does not know the session)
145
+ // Ask the broker about a session (null if it does not know the session)
174
146
  const info = await client.getSession(session.sessionId);
175
147
  console.log(info?.state, info?.stats.toolCallCount);
176
148
 
177
- // Cancel the session
149
+ // Cancel
178
150
  await session.cancel('User cancelled');
179
151
  // or: await client.cancelSession(session.sessionId, 'User cancelled');
180
-
181
- const result = await session.wait();
182
- console.log(result.error?.code); // 'CANCELLED'
183
152
  ```
184
153
 
185
- `cancel()`, `cancelSession()` and aborting the `signal` option all do the same: the session ends in the client as `CANCELLED`, and the broker is asked to end it with `DELETE {baseUrl}/sessions/:sessionId`. They do not reject. If the broker does not confirm the stop, `onError` is called with the code `CANCEL_FAILED`: the script may still be running.
154
+ `cancel()`, `cancelSession()` and aborting the `signal` option all do the same: the session ends in the client as `CANCELLED`, and the broker is asked to end it with `DELETE {baseUrl}/sessions/:sessionId`. They do not reject. If the broker does not confirm the stop, `onError` is called with the code `CANCEL_FAILED`: the script may still be running. `cancelSession()` acts only on a session this client is running; for any other id it does nothing.
155
+
156
+ ### Session limits
157
+
158
+ The client sends three fields of `limits` to the broker, as the `config` of `POST /sessions`: `sessionTtlMs` (as `maxExecutionMs`), `maxToolCalls` and `heartbeatIntervalMs`. The other fields of `SessionLimits` are not sent. The broker can lower `maxExecutionMs` and `maxToolCalls` to its own limits but never raise them, and keeps `heartbeatIntervalMs` within its bounds.
186
159
 
187
- ## Error Handling
160
+ ### Reconnection
161
+
162
+ When the stream is lost and `autoReconnect` is on, the client reconnects with `GET {baseUrl}/sessions/:sessionId/stream?fromSeq=N`, asking for the events after the last one it received. Events at or below the last sequence number received are dropped as replays, so no event is delivered twice. If the attempts are used up, the session fails with the code of the last failure.
163
+
164
+ ## Error handling
188
165
 
189
166
  A session that fails is not a rejected promise. `execute()` and `wait()` resolve with `success: false` and an `error`:
190
167
 
@@ -193,7 +170,7 @@ import { EnclaveClient, EnclaveClientError } from '@enclave-vm/client';
193
170
 
194
171
  const client = new EnclaveClient({ baseUrl: 'https://api.example.com' });
195
172
 
196
- const result = await client.execute(code);
173
+ const result = await client.execute('return 1 + 1');
197
174
 
198
175
  if (!result.success) {
199
176
  switch (result.error?.code) {
@@ -236,46 +213,28 @@ try {
236
213
  | `SESSION_ERROR` | The broker refused to start the session, the session id is not valid, or the id is already running on this client |
237
214
  | `RECONNECT_FAILED` | The broker refused a reconnection |
238
215
 
239
- When the connection is lost and `autoReconnect` is on, the client reconnects first. If the attempts are used up, the session fails with the code of the last failure.
216
+ ## Security notes
240
217
 
241
- ## Browser Usage
218
+ - **No encryption.** Requests and events travel as plain JSON over HTTP, protected only by the transport. Use an `https:` base URL. An encrypted (`enc`) event ends the session with `PARSE_ERROR`.
219
+ - **No authentication of its own.** Send credentials with `headers`; the broker, or what is in front of it, has to check them. Without an `identify` hook on the broker, any caller that can reach the broker's routes can read and end every session (see the broker's README).
220
+ - **Tool calls are visible.** Tool names, arguments and the result of the script reach the client in the events.
242
221
 
243
- In the browser the client uses the global `fetch`:
222
+ ## Related packages
244
223
 
245
- ```typescript
246
- import { EnclaveClient } from '@enclave-vm/client';
247
-
248
- const client = new EnclaveClient({
249
- baseUrl: 'https://api.example.com',
250
- });
251
-
252
- async function runCode() {
253
- const result = await client.execute(
254
- `
255
- const data = await callTool('fetchData', { url: '/api/users' });
256
- return data;
257
- `,
258
- {
259
- onStdout: (chunk) => {
260
- document.body.append(chunk);
261
- },
262
- },
263
- );
264
- console.log(result);
265
- }
266
-
267
- runCode();
268
- ```
224
+ | Package | Role |
225
+ | ---------------------------------------------------------------------- | ------------------------------------------------ |
226
+ | [@enclave-vm/broker](https://www.npmjs.com/package/@enclave-vm/broker) | The server side: tools, sessions and HTTP routes |
227
+ | [@enclave-vm/react](https://www.npmjs.com/package/@enclave-vm/react) | React provider and hooks on top of this client |
228
+ | [@enclave-vm/stream](https://www.npmjs.com/package/@enclave-vm/stream) | NDJSON and reconnection helpers |
229
+ | [@enclave-vm/types](https://www.npmjs.com/package/@enclave-vm/types) | Protocol types and Zod schemas |
269
230
 
270
- ## Related Packages
231
+ ## Documentation
271
232
 
272
- | Package | Description |
273
- | --------------------------------- | ------------------------------------------------------- |
274
- | [@enclave-vm/types](../types) | Type definitions and Zod schemas |
275
- | [@enclave-vm/stream](../stream) | Streaming protocol implementation |
276
- | [@enclave-vm/react](../react) | React hooks and components |
277
- | [@enclave-vm/runtime](../runtime) | Runtime worker building blocks (not a runnable service) |
233
+ - Documentation: https://agentfront.dev/docs/guides/enclave
234
+ - Repository: https://github.com/agentfront/enclave
235
+ - Architecture: https://github.com/agentfront/enclave/blob/main/README-ARCHITECTURE.md
236
+ - Security policy: https://github.com/agentfront/enclave/blob/main/SECURITY.md
278
237
 
279
238
  ## License
280
239
 
281
- Apache-2.0
240
+ Apache-2.0. See [LICENSE](https://github.com/agentfront/enclave/blob/main/LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@enclave-vm/client",
3
- "version": "2.20.0",
3
+ "version": "2.20.1",
4
4
  "description": "Browser and Node.js client SDK for the EnclaveJS streaming runtime",
5
5
  "author": "AgentFront <info@agentfront.dev>",
6
6
  "homepage": "https://github.com/agentfront/enclave",
@@ -33,7 +33,7 @@
33
33
  }
34
34
  },
35
35
  "dependencies": {
36
- "@enclave-vm/stream": "2.20.0",
37
- "@enclave-vm/types": "2.20.0"
36
+ "@enclave-vm/stream": "2.20.1",
37
+ "@enclave-vm/types": "2.20.1"
38
38
  }
39
39
  }