@enclave-vm/client 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/esm/index.mjs ADDED
@@ -0,0 +1,415 @@
1
+ // libs/enclavejs-client/src/client.ts
2
+ import {
3
+ generateSessionId,
4
+ isFinalEvent,
5
+ isSessionInitEvent,
6
+ isStdoutEvent,
7
+ isLogEvent,
8
+ isToolCallEvent,
9
+ isToolResultAppliedEvent,
10
+ isHeartbeatEvent,
11
+ isErrorEvent
12
+ } from "@enclave-vm/types";
13
+ import { parseNdjsonStream, ReconnectionStateMachine, HeartbeatMonitor } from "@enclave-vm/stream";
14
+
15
+ // libs/enclavejs-client/src/types.ts
16
+ var EnclaveClientError = class extends Error {
17
+ code;
18
+ cause;
19
+ constructor(code, message, cause) {
20
+ super(message);
21
+ this.name = "EnclaveClientError";
22
+ this.code = code;
23
+ this.cause = cause;
24
+ }
25
+ };
26
+
27
+ // libs/enclavejs-client/src/client.ts
28
+ var DEFAULT_CONFIG = {
29
+ timeout: 6e4,
30
+ autoReconnect: true,
31
+ maxReconnectAttempts: 3,
32
+ reconnectDelay: 1e3,
33
+ heartbeatTimeoutMs: 3e4
34
+ };
35
+ var EnclaveClient = class {
36
+ config;
37
+ activeSessions = /* @__PURE__ */ new Map();
38
+ /**
39
+ * Create a new EnclaveClient instance.
40
+ */
41
+ constructor(config) {
42
+ const baseUrl = config.baseUrl.replace(/\/$/, "");
43
+ this.config = {
44
+ baseUrl,
45
+ headers: config.headers,
46
+ timeout: config.timeout ?? DEFAULT_CONFIG.timeout,
47
+ autoReconnect: config.autoReconnect ?? DEFAULT_CONFIG.autoReconnect,
48
+ maxReconnectAttempts: config.maxReconnectAttempts ?? DEFAULT_CONFIG.maxReconnectAttempts,
49
+ reconnectDelay: config.reconnectDelay ?? DEFAULT_CONFIG.reconnectDelay,
50
+ fetch: config.fetch ?? globalThis.fetch.bind(globalThis)
51
+ };
52
+ }
53
+ /**
54
+ * Execute code and return the result.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * const result = await client.execute('return 1 + 1');
59
+ * if (result.success) {
60
+ * console.log(result.value);
61
+ * }
62
+ * ```
63
+ */
64
+ async execute(code, options = {}) {
65
+ const handle = this.executeStream(code, options);
66
+ return handle.wait();
67
+ }
68
+ /**
69
+ * Execute code and return a session handle for streaming.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * const session = client.executeStream('return 1 + 1', {
74
+ * onStdout: (chunk) => console.log(chunk),
75
+ * onToolCall: (callId, name, args) => console.log('Tool:', name),
76
+ * });
77
+ *
78
+ * const result = await session.wait();
79
+ * ```
80
+ */
81
+ executeStream(code, options = {}) {
82
+ const sessionId = options.sessionId ?? generateSessionId();
83
+ const abortController = new AbortController();
84
+ if (options.signal) {
85
+ options.signal.addEventListener("abort", () => {
86
+ abortController.abort(options.signal?.reason);
87
+ });
88
+ }
89
+ let resolveResult;
90
+ let rejectResult;
91
+ const resultPromise = new Promise((resolve, reject) => {
92
+ resolveResult = resolve;
93
+ rejectResult = reject;
94
+ });
95
+ const reconnectState = new ReconnectionStateMachine({
96
+ config: {
97
+ maxRetries: this.config.maxReconnectAttempts,
98
+ initialDelayMs: this.config.reconnectDelay
99
+ },
100
+ onEvent: (event) => {
101
+ if (event.type === "retry_started") {
102
+ this.reconnectSession(sessionId);
103
+ }
104
+ }
105
+ });
106
+ const heartbeatMonitor = new HeartbeatMonitor({
107
+ timeoutMs: DEFAULT_CONFIG.heartbeatTimeoutMs,
108
+ onTimeout: () => {
109
+ if (this.config.autoReconnect) {
110
+ const session2 = this.activeSessions.get(sessionId);
111
+ if (session2) {
112
+ reconnectState.onDisconnected("Heartbeat timeout");
113
+ }
114
+ }
115
+ }
116
+ });
117
+ const session = {
118
+ sessionId,
119
+ events: [],
120
+ abortController,
121
+ resolve: resolveResult,
122
+ reject: rejectResult,
123
+ handlers: options,
124
+ startTime: Date.now(),
125
+ toolCallCount: 0,
126
+ stdoutBytes: 0,
127
+ reconnectState,
128
+ heartbeatMonitor,
129
+ lastSequence: 0
130
+ };
131
+ this.activeSessions.set(sessionId, session);
132
+ this.startSession(session, code, options.limits).catch((error) => {
133
+ this.handleSessionError(sessionId, error);
134
+ });
135
+ const eventsRef = session.events;
136
+ return {
137
+ sessionId,
138
+ wait: () => resultPromise,
139
+ cancel: async (reason) => {
140
+ await this.cancelSession(sessionId, reason);
141
+ },
142
+ getEvents: () => [...eventsRef],
143
+ isActive: () => this.activeSessions.has(sessionId)
144
+ };
145
+ }
146
+ /**
147
+ * Get information about a session.
148
+ */
149
+ async getSession(sessionId) {
150
+ const url = `${this.config.baseUrl}/sessions/${sessionId}`;
151
+ try {
152
+ const response = await this.config.fetch(url, {
153
+ method: "GET",
154
+ headers: this.buildHeaders()
155
+ });
156
+ if (response.status === 404) {
157
+ return null;
158
+ }
159
+ if (!response.ok) {
160
+ throw new EnclaveClientError("SESSION_ERROR", `Failed to get session: ${response.status}`);
161
+ }
162
+ return await response.json();
163
+ } catch (error) {
164
+ if (error instanceof EnclaveClientError) throw error;
165
+ throw new EnclaveClientError(
166
+ "NETWORK_ERROR",
167
+ "Failed to get session",
168
+ error instanceof Error ? error : void 0
169
+ );
170
+ }
171
+ }
172
+ /**
173
+ * Cancel a running session.
174
+ */
175
+ async cancelSession(sessionId, reason) {
176
+ const session = this.activeSessions.get(sessionId);
177
+ if (!session) {
178
+ return;
179
+ }
180
+ session.heartbeatMonitor.stop();
181
+ session.reconnectState.close();
182
+ session.abortController.abort(reason);
183
+ const url = `${this.config.baseUrl}/sessions/${sessionId}/cancel`;
184
+ try {
185
+ await this.config.fetch(url, {
186
+ method: "POST",
187
+ headers: this.buildHeaders(),
188
+ body: JSON.stringify({ reason })
189
+ });
190
+ } catch {
191
+ }
192
+ this.completeSession(sessionId, {
193
+ success: false,
194
+ sessionId,
195
+ error: { code: "CANCELLED", message: reason ?? "Session cancelled" },
196
+ events: session.events,
197
+ stats: {
198
+ durationMs: Date.now() - session.startTime,
199
+ toolCallCount: session.toolCallCount,
200
+ stdoutBytes: session.stdoutBytes
201
+ }
202
+ });
203
+ }
204
+ /**
205
+ * Start a session and begin streaming events.
206
+ */
207
+ async startSession(session, code, limits) {
208
+ const url = `${this.config.baseUrl}/sessions`;
209
+ const body = {
210
+ sessionId: session.sessionId,
211
+ code
212
+ };
213
+ if (limits) {
214
+ body.config = {
215
+ maxExecutionMs: limits.sessionTtlMs,
216
+ maxToolCalls: limits.maxToolCalls,
217
+ heartbeatIntervalMs: limits.heartbeatIntervalMs
218
+ };
219
+ }
220
+ try {
221
+ const response = await this.config.fetch(url, {
222
+ method: "POST",
223
+ headers: {
224
+ ...this.buildHeaders(),
225
+ "Content-Type": "application/json",
226
+ Accept: "application/x-ndjson"
227
+ },
228
+ body: JSON.stringify(body),
229
+ signal: session.abortController.signal
230
+ });
231
+ if (!response.ok) {
232
+ const errorText = await response.text();
233
+ throw new EnclaveClientError("SESSION_ERROR", `Failed to start session: ${response.status} - ${errorText}`);
234
+ }
235
+ session.reconnectState.onConnected();
236
+ session.heartbeatMonitor.start();
237
+ await this.streamResponse(session, response);
238
+ } catch (error) {
239
+ if (error instanceof Error && error.name === "AbortError") {
240
+ return;
241
+ }
242
+ if (this.config.autoReconnect && session.reconnectState.canReconnect()) {
243
+ session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Connection lost");
244
+ return;
245
+ }
246
+ throw error;
247
+ }
248
+ }
249
+ /**
250
+ * Stream and parse the NDJSON response.
251
+ */
252
+ async streamResponse(session, response) {
253
+ const body = response.body;
254
+ if (!body) {
255
+ throw new EnclaveClientError("PARSE_ERROR", "No response body");
256
+ }
257
+ try {
258
+ for await (const event of parseNdjsonStream(body)) {
259
+ this.handleEvent(session, event);
260
+ }
261
+ } catch (error) {
262
+ if (error instanceof Error && error.name === "AbortError") {
263
+ return;
264
+ }
265
+ if (this.config.autoReconnect && session.reconnectState.canReconnect()) {
266
+ session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Stream error");
267
+ return;
268
+ }
269
+ throw error;
270
+ }
271
+ }
272
+ /**
273
+ * Handle a received stream event.
274
+ */
275
+ handleEvent(session, event) {
276
+ if (event.seq !== void 0) {
277
+ session.lastSequence = event.seq;
278
+ }
279
+ session.events.push(event);
280
+ session.handlers.onEvent?.(event);
281
+ if (isSessionInitEvent(event)) {
282
+ session.handlers.onSessionInit?.(event);
283
+ } else if (isStdoutEvent(event)) {
284
+ session.stdoutBytes += event.payload.chunk.length;
285
+ session.handlers.onStdout?.(event.payload.chunk);
286
+ } else if (isLogEvent(event)) {
287
+ session.handlers.onLog?.(event.payload.level, event.payload.message, event.payload.data);
288
+ } else if (isToolCallEvent(event)) {
289
+ session.toolCallCount++;
290
+ session.handlers.onToolCall?.(event.payload.callId, event.payload.toolName, event.payload.args);
291
+ } else if (isToolResultAppliedEvent(event)) {
292
+ session.handlers.onToolResultApplied?.(event.payload.callId);
293
+ } else if (isHeartbeatEvent(event)) {
294
+ session.heartbeatMonitor.onHeartbeat();
295
+ session.handlers.onHeartbeat?.();
296
+ } else if (isErrorEvent(event)) {
297
+ session.handlers.onError?.(event.payload.code ?? "UNKNOWN", event.payload.message);
298
+ } else if (isFinalEvent(event)) {
299
+ this.handleFinalEvent(session, event);
300
+ }
301
+ }
302
+ /**
303
+ * Handle the final event and complete the session.
304
+ */
305
+ handleFinalEvent(session, event) {
306
+ session.heartbeatMonitor.stop();
307
+ session.reconnectState.close();
308
+ const result = {
309
+ success: event.payload.ok,
310
+ sessionId: session.sessionId,
311
+ events: session.events,
312
+ stats: {
313
+ durationMs: Date.now() - session.startTime,
314
+ toolCallCount: session.toolCallCount,
315
+ stdoutBytes: session.stdoutBytes
316
+ }
317
+ };
318
+ if (event.payload.ok) {
319
+ result.value = event.payload.result;
320
+ } else {
321
+ result.error = {
322
+ code: event.payload.error?.code,
323
+ message: event.payload.error?.message ?? "Unknown error"
324
+ };
325
+ }
326
+ this.completeSession(session.sessionId, result);
327
+ }
328
+ /**
329
+ * Handle a session error.
330
+ */
331
+ handleSessionError(sessionId, error) {
332
+ const session = this.activeSessions.get(sessionId);
333
+ if (!session) return;
334
+ session.heartbeatMonitor.stop();
335
+ session.reconnectState.close();
336
+ const clientError = error instanceof EnclaveClientError ? error : new EnclaveClientError(
337
+ "NETWORK_ERROR",
338
+ error instanceof Error ? error.message : "Unknown error",
339
+ error instanceof Error ? error : void 0
340
+ );
341
+ this.completeSession(sessionId, {
342
+ success: false,
343
+ sessionId,
344
+ error: { code: clientError.code, message: clientError.message },
345
+ events: session.events,
346
+ stats: {
347
+ durationMs: Date.now() - session.startTime,
348
+ toolCallCount: session.toolCallCount,
349
+ stdoutBytes: session.stdoutBytes
350
+ }
351
+ });
352
+ }
353
+ /**
354
+ * Complete a session and clean up.
355
+ */
356
+ completeSession(sessionId, result) {
357
+ const session = this.activeSessions.get(sessionId);
358
+ if (!session) return;
359
+ this.activeSessions.delete(sessionId);
360
+ session.resolve(result);
361
+ }
362
+ /**
363
+ * Attempt to reconnect a session.
364
+ */
365
+ async reconnectSession(sessionId) {
366
+ const session = this.activeSessions.get(sessionId);
367
+ if (!session) return;
368
+ const url = `${this.config.baseUrl}/sessions/${sessionId}/stream`;
369
+ const params = new URLSearchParams();
370
+ if (session.lastSequence > 0) {
371
+ params.set("from", String(session.lastSequence + 1));
372
+ }
373
+ try {
374
+ const response = await this.config.fetch(`${url}?${params}`, {
375
+ method: "GET",
376
+ headers: {
377
+ ...this.buildHeaders(),
378
+ Accept: "application/x-ndjson"
379
+ },
380
+ signal: session.abortController.signal
381
+ });
382
+ if (!response.ok) {
383
+ throw new EnclaveClientError("RECONNECT_FAILED", `Reconnection failed: ${response.status}`);
384
+ }
385
+ session.reconnectState.onConnected();
386
+ session.heartbeatMonitor.start();
387
+ await this.streamResponse(session, response);
388
+ } catch (error) {
389
+ if (error instanceof Error && error.name === "AbortError") {
390
+ return;
391
+ }
392
+ if (session.reconnectState.canReconnect()) {
393
+ session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Reconnection failed");
394
+ } else {
395
+ this.handleSessionError(sessionId, error);
396
+ }
397
+ }
398
+ }
399
+ /**
400
+ * Build request headers.
401
+ */
402
+ buildHeaders() {
403
+ return {
404
+ ...this.config.headers
405
+ };
406
+ }
407
+ };
408
+
409
+ // libs/enclavejs-client/src/index.ts
410
+ import { ConnectionState } from "@enclave-vm/stream";
411
+ export {
412
+ ConnectionState,
413
+ EnclaveClient,
414
+ EnclaveClientError
415
+ };
@@ -0,0 +1,6 @@
1
+ {
2
+ "type": "module",
3
+ "sideEffects": false,
4
+ "main": "./index.mjs",
5
+ "module": "./index.mjs"
6
+ }
package/index.d.ts.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,OAAO,EACL,kBAAkB,EAClB,KAAK,mBAAmB,EACxB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,KAAK,aAAa,EAClB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,eAAe,GACrB,MAAM,YAAY,CAAC;AAGpB,YAAY,EACV,SAAS,EACT,aAAa,EACb,WAAW,EACX,gBAAgB,EAChB,WAAW,EACX,QAAQ,EACR,aAAa,EACb,sBAAsB,EACtB,UAAU,EACV,cAAc,EACd,UAAU,GACX,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC"}