@enclave-vm/client 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/esm/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  // libs/client/src/client.ts
2
2
  import {
3
+ DEFAULT_SESSION_LIMITS,
4
+ SESSION_ID_PREFIX,
3
5
  generateSessionId,
4
6
  isFinalEvent,
5
7
  isSessionInitEvent,
@@ -14,7 +16,13 @@ import {
14
16
  isDeadlineExceededEvent,
15
17
  isCatalogChangedEvent
16
18
  } from "@enclave-vm/types";
17
- import { parseNdjsonStream, ReconnectionStateMachine, HeartbeatMonitor } from "@enclave-vm/stream";
19
+ import {
20
+ ConnectionState,
21
+ DEFAULT_MAX_LINE_LENGTH,
22
+ NdjsonLineTooLongError,
23
+ ReconnectionStateMachine,
24
+ parseNdjsonStream
25
+ } from "@enclave-vm/stream";
18
26
 
19
27
  // libs/client/src/types.ts
20
28
  var EnclaveClientError = class extends Error {
@@ -34,25 +42,103 @@ var DEFAULT_CONFIG = {
34
42
  autoReconnect: true,
35
43
  maxReconnectAttempts: 3,
36
44
  reconnectDelay: 1e3,
37
- heartbeatTimeoutMs: 3e4
45
+ maxEventLength: DEFAULT_MAX_LINE_LENGTH
46
+ };
47
+ var CONFIG_KEYS = /* @__PURE__ */ new Set([
48
+ "baseUrl",
49
+ "headers",
50
+ "timeout",
51
+ "autoReconnect",
52
+ "maxReconnectAttempts",
53
+ "reconnectDelay",
54
+ "maxEventLength",
55
+ "fetch"
56
+ ]);
57
+ var UNIMPLEMENTED_OPTION_HINTS = {
58
+ encryption: "This client does not encrypt: requests and events travel as plain JSON, protected only by the transport. Use an https: baseUrl.",
59
+ auth: "Send credentials with the `headers` option.",
60
+ serverUrl: "The option is called `baseUrl`.",
61
+ reconnect: "Use `autoReconnect`, `maxReconnectAttempts` and `reconnectDelay`."
38
62
  };
63
+ function invalidConfig(message) {
64
+ throw new TypeError(`EnclaveClient: ${message}`);
65
+ }
66
+ function resolveConfig(config) {
67
+ if (typeof config !== "object" || config === null) {
68
+ invalidConfig("a configuration object with `baseUrl` is required");
69
+ }
70
+ for (const key of Object.keys(config)) {
71
+ if (CONFIG_KEYS.has(key) || config[key] === void 0) continue;
72
+ const hint = UNIMPLEMENTED_OPTION_HINTS[key];
73
+ invalidConfig(`unknown option "${key}".${hint ? ` ${hint}` : ""}`);
74
+ }
75
+ if (typeof config.baseUrl !== "string" || config.baseUrl.length === 0) {
76
+ invalidConfig("`baseUrl` must be a non-empty string");
77
+ }
78
+ if (config.headers !== void 0) {
79
+ const headers = config.headers;
80
+ if (typeof headers !== "object" || headers === null || Array.isArray(headers) || Object.values(headers).some((value) => typeof value !== "string")) {
81
+ invalidConfig("`headers` must be an object of strings");
82
+ }
83
+ }
84
+ const duration = (name, minimum) => {
85
+ const value = config[name];
86
+ if (value === void 0) return DEFAULT_CONFIG[name];
87
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum) {
88
+ invalidConfig(`\`${name}\` must be a number of milliseconds${minimum > 0 ? " above zero" : ", zero or more"}`);
89
+ }
90
+ return value;
91
+ };
92
+ const count = (name, minimum) => {
93
+ const value = config[name];
94
+ if (value === void 0) return DEFAULT_CONFIG[name];
95
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < minimum) {
96
+ invalidConfig(`\`${name}\` must be an integer of ${minimum} or more`);
97
+ }
98
+ return value;
99
+ };
100
+ if (config.autoReconnect !== void 0 && typeof config.autoReconnect !== "boolean") {
101
+ invalidConfig("`autoReconnect` must be a boolean");
102
+ }
103
+ if (config.fetch !== void 0 && typeof config.fetch !== "function") {
104
+ invalidConfig("`fetch` must be a function");
105
+ }
106
+ if (config.fetch === void 0 && typeof globalThis.fetch !== "function") {
107
+ invalidConfig("no global fetch is available; pass one with the `fetch` option");
108
+ }
109
+ return {
110
+ // Normalize baseUrl (remove trailing slash)
111
+ baseUrl: config.baseUrl.replace(/\/$/, ""),
112
+ headers: config.headers,
113
+ timeout: duration("timeout", 1),
114
+ autoReconnect: config.autoReconnect ?? DEFAULT_CONFIG.autoReconnect,
115
+ maxReconnectAttempts: count("maxReconnectAttempts", 0),
116
+ reconnectDelay: duration("reconnectDelay", 0),
117
+ maxEventLength: count("maxEventLength", 1),
118
+ fetch: config.fetch ?? globalThis.fetch.bind(globalThis)
119
+ };
120
+ }
121
+ function sessionPathSegment(sessionId) {
122
+ if (typeof sessionId !== "string" || !sessionId.startsWith(SESSION_ID_PREFIX) || sessionId.length <= SESSION_ID_PREFIX.length) {
123
+ return null;
124
+ }
125
+ try {
126
+ return encodeURIComponent(sessionId);
127
+ } catch {
128
+ return null;
129
+ }
130
+ }
39
131
  var EnclaveClient = class {
40
132
  config;
41
133
  activeSessions = /* @__PURE__ */ new Map();
42
134
  /**
43
135
  * Create a new EnclaveClient instance.
136
+ *
137
+ * @throws TypeError when the configuration has an option this client does not implement
138
+ * (for example `encryption` or `auth`) or a value it cannot use
44
139
  */
45
140
  constructor(config) {
46
- const baseUrl = config.baseUrl.replace(/\/$/, "");
47
- this.config = {
48
- baseUrl,
49
- headers: config.headers,
50
- timeout: config.timeout ?? DEFAULT_CONFIG.timeout,
51
- autoReconnect: config.autoReconnect ?? DEFAULT_CONFIG.autoReconnect,
52
- maxReconnectAttempts: config.maxReconnectAttempts ?? DEFAULT_CONFIG.maxReconnectAttempts,
53
- reconnectDelay: config.reconnectDelay ?? DEFAULT_CONFIG.reconnectDelay,
54
- fetch: config.fetch ?? globalThis.fetch.bind(globalThis)
55
- };
141
+ this.config = resolveConfig(config);
56
142
  }
57
143
  /**
58
144
  * Execute code and return the result.
@@ -84,86 +170,100 @@ var EnclaveClient = class {
84
170
  */
85
171
  executeStream(code, options = {}) {
86
172
  const sessionId = options.sessionId ?? generateSessionId();
87
- const abortController = new AbortController();
88
- if (options.signal) {
89
- options.signal.addEventListener("abort", () => {
90
- abortController.abort(options.signal?.reason);
91
- });
92
- }
93
173
  let resolveResult;
94
- let rejectResult;
95
- const resultPromise = new Promise((resolve, reject) => {
174
+ const resultPromise = new Promise((resolve) => {
96
175
  resolveResult = resolve;
97
- rejectResult = reject;
98
- });
99
- const reconnectState = new ReconnectionStateMachine({
100
- config: {
101
- maxRetries: this.config.maxReconnectAttempts,
102
- initialDelayMs: this.config.reconnectDelay
103
- },
104
- onEvent: (event) => {
105
- if (event.type === "retry_started") {
106
- this.reconnectSession(sessionId);
107
- }
108
- }
109
- });
110
- const heartbeatMonitor = new HeartbeatMonitor({
111
- timeoutMs: DEFAULT_CONFIG.heartbeatTimeoutMs,
112
- onTimeout: () => {
113
- if (this.config.autoReconnect) {
114
- const session2 = this.activeSessions.get(sessionId);
115
- if (session2) {
116
- reconnectState.onDisconnected("Heartbeat timeout");
117
- }
118
- }
119
- }
120
176
  });
121
177
  const session = {
122
178
  sessionId,
179
+ instanceId: generateSessionId(),
123
180
  events: [],
124
- abortController,
125
181
  resolve: resolveResult,
126
- reject: rejectResult,
127
182
  handlers: options,
128
183
  startTime: Date.now(),
129
184
  toolCallCount: 0,
130
185
  stdoutBytes: 0,
131
- reconnectState,
132
- heartbeatMonitor,
133
- lastSequence: 0
186
+ // Create reconnection state machine
187
+ reconnectState: new ReconnectionStateMachine({
188
+ config: {
189
+ maxRetries: this.config.maxReconnectAttempts,
190
+ initialDelayMs: this.config.reconnectDelay
191
+ },
192
+ onEvent: (event) => {
193
+ if (event.type === "retry_started") {
194
+ void this.reconnectSession(session);
195
+ }
196
+ }
197
+ }),
198
+ lastSequence: -1,
199
+ // The server sends a heartbeat at the interval the session asked for. Two intervals
200
+ // without any event, and at least `timeout`, is a stream that has gone silent.
201
+ silenceMs: Math.max(
202
+ this.config.timeout,
203
+ 2 * (options.limits?.heartbeatIntervalMs ?? DEFAULT_SESSION_LIMITS.heartbeatIntervalMs)
204
+ ),
205
+ connection: null,
206
+ ended: false,
207
+ detachSignal: () => void 0
134
208
  };
135
- this.activeSessions.set(sessionId, session);
136
- this.startSession(session, code, options.limits).catch((error) => {
137
- this.handleSessionError(sessionId, error);
138
- });
139
- const eventsRef = session.events;
140
- return {
209
+ const handle = {
141
210
  sessionId,
142
211
  wait: () => resultPromise,
143
212
  cancel: async (reason) => {
144
- await this.cancelSession(sessionId, reason);
213
+ await this.stopSession(session, reason);
145
214
  },
146
- getEvents: () => [...eventsRef],
147
- isActive: () => this.activeSessions.has(sessionId)
215
+ getEvents: () => [...session.events],
216
+ isActive: () => !session.ended && this.activeSessions.get(sessionId) === session
148
217
  };
218
+ if (sessionPathSegment(sessionId) === null) {
219
+ this.refuseSession(session, "Invalid session id");
220
+ return handle;
221
+ }
222
+ if (this.activeSessions.has(sessionId)) {
223
+ this.refuseSession(session, `Session ${sessionId} is already running on this client`);
224
+ return handle;
225
+ }
226
+ this.activeSessions.set(sessionId, session);
227
+ const signal = options.signal;
228
+ if (signal) {
229
+ const reasonOf = () => typeof signal.reason === "string" ? signal.reason : void 0;
230
+ if (signal.aborted) {
231
+ this.endSession(session, this.cancelledResult(session, reasonOf()));
232
+ return handle;
233
+ }
234
+ const onAbort = () => {
235
+ void this.stopSession(session, reasonOf());
236
+ };
237
+ signal.addEventListener("abort", onAbort, { once: true });
238
+ session.detachSignal = () => signal.removeEventListener("abort", onAbort);
239
+ }
240
+ void this.startSession(session, code, options.limits);
241
+ return handle;
149
242
  }
150
243
  /**
151
244
  * Get information about a session.
152
245
  */
153
246
  async getSession(sessionId) {
154
- const url = `${this.config.baseUrl}/sessions/${sessionId}`;
247
+ const segment = sessionPathSegment(sessionId);
248
+ if (segment === null) {
249
+ throw new EnclaveClientError("SESSION_ERROR", "Invalid session id");
250
+ }
251
+ const url = `${this.config.baseUrl}/sessions/${segment}`;
155
252
  try {
156
- const response = await this.config.fetch(url, {
157
- method: "GET",
158
- headers: this.buildHeaders()
253
+ return await this.withDeadline("Getting the session", async (signal) => {
254
+ const response = await this.config.fetch(url, {
255
+ method: "GET",
256
+ headers: this.buildHeaders(),
257
+ signal
258
+ });
259
+ if (response.status === 404) {
260
+ return null;
261
+ }
262
+ if (!response.ok) {
263
+ throw new EnclaveClientError("SESSION_ERROR", `Failed to get session: ${response.status}`);
264
+ }
265
+ return await response.json();
159
266
  });
160
- if (response.status === 404) {
161
- return null;
162
- }
163
- if (!response.ok) {
164
- throw new EnclaveClientError("SESSION_ERROR", `Failed to get session: ${response.status}`);
165
- }
166
- return await response.json();
167
267
  } catch (error) {
168
268
  if (error instanceof EnclaveClientError) throw error;
169
269
  throw new EnclaveClientError(
@@ -175,35 +275,77 @@ var EnclaveClient = class {
175
275
  }
176
276
  /**
177
277
  * Cancel a running session.
278
+ *
279
+ * The session of this client ends as `CANCELLED`, and the server is asked to end the session
280
+ * (`DELETE /sessions/:sessionId`). When the server does not confirm that, the session's
281
+ * `onError` handler is called with the code `CANCEL_FAILED`: the script may still be running.
178
282
  */
179
283
  async cancelSession(sessionId, reason) {
180
284
  const session = this.activeSessions.get(sessionId);
181
285
  if (!session) {
182
286
  return;
183
287
  }
184
- session.heartbeatMonitor.stop();
185
- session.reconnectState.close();
186
- session.abortController.abort(reason);
187
- const url = `${this.config.baseUrl}/sessions/${sessionId}/cancel`;
288
+ await this.stopSession(session, reason);
289
+ }
290
+ /**
291
+ * End a session of this client as cancelled and ask the server to end it too.
292
+ * Never rejects.
293
+ */
294
+ async stopSession(session, reason) {
295
+ if (session.ended) {
296
+ return;
297
+ }
298
+ const wasCreating = session.creating;
299
+ this.endSession(session, this.cancelledResult(session, reason));
300
+ const stop = await this.sendStop(session);
301
+ let failure = stop.failure;
302
+ if (stop.retryIfCreating && wasCreating) {
303
+ failure ??= "the session was still being created";
304
+ if (session.creating) {
305
+ session.stopAfterCreation = true;
306
+ } else {
307
+ void this.sendStop(session);
308
+ }
309
+ }
310
+ if (failure !== null) {
311
+ try {
312
+ session.handlers.onError?.(
313
+ "CANCEL_FAILED",
314
+ `The server did not confirm that session ${session.sessionId} was stopped: ${failure}`
315
+ );
316
+ } catch {
317
+ }
318
+ }
319
+ }
320
+ /**
321
+ * Ask the server to end a session (`DELETE /sessions/:sessionId`). Never rejects: a failure is
322
+ * what it answers with. An absent or replaced creation is no failure after its POST settles.
323
+ */
324
+ async sendStop(session) {
325
+ const url = `${this.config.baseUrl}/sessions/${sessionPathSegment(session.sessionId)}`;
326
+ let failure = null;
327
+ let retryIfCreating = false;
188
328
  try {
189
- await this.config.fetch(url, {
190
- method: "POST",
191
- headers: this.buildHeaders(),
192
- body: JSON.stringify({ reason })
329
+ await this.withDeadline("Stopping the session", async (signal) => {
330
+ const response = await this.config.fetch(url, {
331
+ method: "DELETE",
332
+ headers: this.sessionHeaders(session),
333
+ signal
334
+ });
335
+ void response.body?.cancel().catch(() => void 0);
336
+ if (response.status === 404 || response.status === 412) {
337
+ retryIfCreating = true;
338
+ } else if (response.status === 409) {
339
+ retryIfCreating = true;
340
+ failure = "the server could not confirm the session creation";
341
+ } else if (!response.ok) {
342
+ failure = `the server answered ${response.status}`;
343
+ }
193
344
  });
194
- } catch {
345
+ } catch (error) {
346
+ failure = error instanceof Error ? error.message : "the request failed";
195
347
  }
196
- this.completeSession(sessionId, {
197
- success: false,
198
- sessionId,
199
- error: { code: "CANCELLED", message: reason ?? "Session cancelled" },
200
- events: session.events,
201
- stats: {
202
- durationMs: Date.now() - session.startTime,
203
- toolCallCount: session.toolCallCount,
204
- stdoutBytes: session.stdoutBytes
205
- }
206
- });
348
+ return { failure, retryIfCreating };
207
349
  }
208
350
  /**
209
351
  * Start a session and begin streaming events.
@@ -221,64 +363,168 @@ var EnclaveClient = class {
221
363
  heartbeatIntervalMs: limits.heartbeatIntervalMs
222
364
  };
223
365
  }
224
- try {
225
- const response = await this.config.fetch(url, {
226
- method: "POST",
366
+ await this.runConnection(session, async (signal) => {
367
+ session.creating = true;
368
+ let response;
369
+ try {
370
+ response = await this.config.fetch(url, {
371
+ method: "POST",
372
+ headers: {
373
+ ...this.sessionHeaders(session),
374
+ "Content-Type": "application/json",
375
+ Accept: "application/x-ndjson"
376
+ },
377
+ body: JSON.stringify(body),
378
+ signal
379
+ });
380
+ } finally {
381
+ session.creating = false;
382
+ if (session.stopAfterCreation) {
383
+ session.stopAfterCreation = false;
384
+ void this.sendStop(session);
385
+ }
386
+ }
387
+ if (!response.ok) {
388
+ const errorText = (await response.text()).slice(0, 500);
389
+ throw new EnclaveClientError("SESSION_ERROR", `Failed to start session: ${response.status} - ${errorText}`);
390
+ }
391
+ return response;
392
+ });
393
+ }
394
+ /**
395
+ * Attempt to reconnect a session.
396
+ */
397
+ async reconnectSession(session) {
398
+ if (session.ended) return;
399
+ const url = `${this.config.baseUrl}/sessions/${sessionPathSegment(session.sessionId)}/stream`;
400
+ const query = session.lastSequence >= 0 ? `?fromSeq=${session.lastSequence + 1}` : "";
401
+ await this.runConnection(session, async (signal) => {
402
+ const response = await this.config.fetch(`${url}${query}`, {
403
+ method: "GET",
227
404
  headers: {
228
405
  ...this.buildHeaders(),
229
- "Content-Type": "application/json",
230
406
  Accept: "application/x-ndjson"
231
407
  },
232
- body: JSON.stringify(body),
233
- signal: session.abortController.signal
408
+ signal
234
409
  });
235
410
  if (!response.ok) {
236
- const errorText = await response.text();
237
- throw new EnclaveClientError("SESSION_ERROR", `Failed to start session: ${response.status} - ${errorText}`);
238
- }
239
- session.reconnectState.onConnected();
240
- session.heartbeatMonitor.start();
241
- await this.streamResponse(session, response);
242
- } catch (error) {
243
- if (error instanceof Error && error.name === "AbortError") {
244
- return;
411
+ void response.body?.cancel().catch(() => void 0);
412
+ throw new EnclaveClientError("RECONNECT_FAILED", `Reconnection failed: ${response.status}`);
245
413
  }
246
- if (this.config.autoReconnect && session.reconnectState.canReconnect()) {
247
- session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Connection lost");
414
+ return response;
415
+ });
416
+ }
417
+ /**
418
+ * Open a connection for a session and follow its stream until the session ends or the
419
+ * connection is lost. A session has one connection at a time: the previous one is closed
420
+ * first, and nothing that still arrives on it is delivered.
421
+ */
422
+ async runConnection(session, request) {
423
+ if (session.ended) return;
424
+ this.closeConnection(session);
425
+ const connection = { controller: new AbortController(), timer: null };
426
+ session.connection = connection;
427
+ try {
428
+ this.watch(session, connection, this.config.timeout, "No response from the server");
429
+ const response = await request(connection.controller.signal);
430
+ if (!this.isCurrent(session, connection)) {
431
+ void response.body?.cancel().catch(() => void 0);
248
432
  return;
249
433
  }
250
- throw error;
434
+ await this.streamResponse(session, connection, response);
435
+ } catch (error) {
436
+ this.connectionLost(session, connection, error);
251
437
  }
252
438
  }
253
439
  /**
254
440
  * Stream and parse the NDJSON response.
255
441
  */
256
- async streamResponse(session, response) {
442
+ async streamResponse(session, connection, response) {
257
443
  const body = response.body;
258
444
  if (!body) {
259
445
  throw new EnclaveClientError("PARSE_ERROR", "No response body");
260
446
  }
261
- try {
262
- for await (const event of parseNdjsonStream(body)) {
263
- this.handleEvent(session, event);
264
- }
265
- } catch (error) {
266
- if (error instanceof Error && error.name === "AbortError") {
267
- return;
268
- }
269
- if (this.config.autoReconnect && session.reconnectState.canReconnect()) {
270
- session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Stream error");
271
- return;
272
- }
273
- throw error;
447
+ this.watch(session, connection, session.silenceMs, "No event from the server");
448
+ for await (const event of parseNdjsonStream(body, { maxLineLength: this.config.maxEventLength })) {
449
+ if (!this.isCurrent(session, connection)) return;
450
+ this.watch(session, connection, session.silenceMs, "No event from the server");
451
+ this.handleEvent(session, event);
452
+ if (session.ended) return;
453
+ }
454
+ if (!this.isCurrent(session, connection)) return;
455
+ throw new EnclaveClientError("NETWORK_ERROR", "The stream ended before the session was complete");
456
+ }
457
+ /**
458
+ * (Re)start the timer of a connection. When it runs out the connection counts as lost.
459
+ */
460
+ watch(session, connection, ms, what) {
461
+ if (connection.timer !== null) {
462
+ clearTimeout(connection.timer);
463
+ }
464
+ connection.timer = setTimeout(() => {
465
+ connection.timer = null;
466
+ this.connectionLost(session, connection, new EnclaveClientError("TIMEOUT", `${what} within ${ms} ms`));
467
+ }, ms);
468
+ }
469
+ /**
470
+ * Whether a connection is the one its session is using.
471
+ */
472
+ isCurrent(session, connection) {
473
+ return !session.ended && session.connection === connection;
474
+ }
475
+ /**
476
+ * Close the connection of a session, if it has one.
477
+ */
478
+ closeConnection(session) {
479
+ const connection = session.connection;
480
+ if (!connection) return;
481
+ session.connection = null;
482
+ if (connection.timer !== null) {
483
+ clearTimeout(connection.timer);
484
+ connection.timer = null;
274
485
  }
486
+ connection.controller.abort();
487
+ }
488
+ /**
489
+ * A connection failed, ended early or went silent: reconnect if that is allowed, otherwise
490
+ * the session fails. A connection that is no longer the session's own is ignored.
491
+ */
492
+ connectionLost(session, connection, error) {
493
+ if (!this.isCurrent(session, connection)) return;
494
+ this.closeConnection(session);
495
+ if (error instanceof NdjsonLineTooLongError) {
496
+ this.failSession(
497
+ session,
498
+ new EnclaveClientError(
499
+ "PARSE_ERROR",
500
+ `The server sent an event longer than ${this.config.maxEventLength} characters`,
501
+ error
502
+ )
503
+ );
504
+ return;
505
+ }
506
+ if (this.config.autoReconnect && session.reconnectState.canReconnect()) {
507
+ session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Connection lost");
508
+ return;
509
+ }
510
+ this.failSession(session, error);
275
511
  }
276
512
  /**
277
513
  * Handle a received stream event.
278
514
  */
279
515
  handleEvent(session, event) {
280
- if (event.seq !== void 0) {
281
- session.lastSequence = event.seq;
516
+ if (session.ended) return;
517
+ if (event.seq <= session.lastSequence) return;
518
+ session.lastSequence = event.seq;
519
+ if (session.reconnectState.getState() !== ConnectionState.Connected) {
520
+ session.reconnectState.onConnected();
521
+ }
522
+ if (event.type === "enc") {
523
+ this.failSession(
524
+ session,
525
+ new EnclaveClientError("PARSE_ERROR", "The server sent an encrypted event, which this client cannot read")
526
+ );
527
+ return;
282
528
  }
283
529
  session.events.push(event);
284
530
  session.handlers.onEvent?.(event);
@@ -295,7 +541,6 @@ var EnclaveClient = class {
295
541
  } else if (isToolResultAppliedEvent(event)) {
296
542
  session.handlers.onToolResultApplied?.(event.payload.callId);
297
543
  } else if (isHeartbeatEvent(event)) {
298
- session.heartbeatMonitor.onHeartbeat();
299
544
  session.handlers.onHeartbeat?.();
300
545
  } else if (isErrorEvent(event)) {
301
546
  session.handlers.onError?.(event.payload.code ?? "UNKNOWN", event.payload.message);
@@ -324,17 +569,11 @@ var EnclaveClient = class {
324
569
  * Handle the final event and complete the session.
325
570
  */
326
571
  handleFinalEvent(session, event) {
327
- session.heartbeatMonitor.stop();
328
- session.reconnectState.close();
329
572
  const result = {
330
573
  success: event.payload.ok,
331
574
  sessionId: session.sessionId,
332
575
  events: session.events,
333
- stats: {
334
- durationMs: Date.now() - session.startTime,
335
- toolCallCount: session.toolCallCount,
336
- stdoutBytes: session.stdoutBytes
337
- }
576
+ stats: this.statsOf(session)
338
577
  };
339
578
  if (event.payload.ok) {
340
579
  result.value = event.payload.result;
@@ -351,78 +590,92 @@ var EnclaveClient = class {
351
590
  path: e.path
352
591
  }));
353
592
  }
354
- this.completeSession(session.sessionId, result);
593
+ this.endSession(session, result);
355
594
  }
356
595
  /**
357
- * Handle a session error.
596
+ * End a session with an error.
358
597
  */
359
- handleSessionError(sessionId, error) {
360
- const session = this.activeSessions.get(sessionId);
361
- if (!session) return;
362
- session.heartbeatMonitor.stop();
363
- session.reconnectState.close();
598
+ failSession(session, error) {
364
599
  const clientError = error instanceof EnclaveClientError ? error : new EnclaveClientError(
365
600
  "NETWORK_ERROR",
366
601
  error instanceof Error ? error.message : "Unknown error",
367
602
  error instanceof Error ? error : void 0
368
603
  );
369
- this.completeSession(sessionId, {
604
+ this.endSession(session, {
370
605
  success: false,
371
- sessionId,
606
+ sessionId: session.sessionId,
372
607
  error: { code: clientError.code, message: clientError.message },
373
608
  events: session.events,
374
- stats: {
375
- durationMs: Date.now() - session.startTime,
376
- toolCallCount: session.toolCallCount,
377
- stdoutBytes: session.stdoutBytes
378
- }
609
+ stats: this.statsOf(session)
379
610
  });
380
611
  }
381
612
  /**
382
- * Complete a session and clean up.
613
+ * End a session that was never requested from the server.
383
614
  */
384
- completeSession(sessionId, result) {
385
- const session = this.activeSessions.get(sessionId);
386
- if (!session) return;
387
- this.activeSessions.delete(sessionId);
388
- session.resolve(result);
615
+ refuseSession(session, message) {
616
+ session.ended = true;
617
+ session.reconnectState.close();
618
+ session.resolve({
619
+ success: false,
620
+ sessionId: session.sessionId,
621
+ error: { code: "SESSION_ERROR", message },
622
+ events: session.events,
623
+ stats: this.statsOf(session)
624
+ });
389
625
  }
390
626
  /**
391
- * Attempt to reconnect a session.
627
+ * Give a session its result and clean up. The first result is the only one.
392
628
  */
393
- async reconnectSession(sessionId) {
394
- const session = this.activeSessions.get(sessionId);
395
- if (!session) return;
396
- const url = `${this.config.baseUrl}/sessions/${sessionId}/stream`;
397
- const params = new URLSearchParams();
398
- if (session.lastSequence > 0) {
399
- params.set("from", String(session.lastSequence + 1));
629
+ endSession(session, result) {
630
+ if (session.ended) return;
631
+ session.ended = true;
632
+ this.closeConnection(session);
633
+ session.reconnectState.close();
634
+ session.detachSignal();
635
+ if (this.activeSessions.get(session.sessionId) === session) {
636
+ this.activeSessions.delete(session.sessionId);
400
637
  }
401
- try {
402
- const response = await this.config.fetch(`${url}?${params}`, {
403
- method: "GET",
404
- headers: {
405
- ...this.buildHeaders(),
406
- Accept: "application/x-ndjson"
638
+ session.resolve(result);
639
+ }
640
+ cancelledResult(session, reason) {
641
+ return {
642
+ success: false,
643
+ sessionId: session.sessionId,
644
+ error: { code: "CANCELLED", message: reason || "Session cancelled" },
645
+ events: session.events,
646
+ stats: this.statsOf(session)
647
+ };
648
+ }
649
+ statsOf(session) {
650
+ return {
651
+ durationMs: Date.now() - session.startTime,
652
+ toolCallCount: session.toolCallCount,
653
+ stdoutBytes: session.stdoutBytes
654
+ };
655
+ }
656
+ /**
657
+ * Run a request that is not a session stream, bounded by the configured timeout.
658
+ * The promise settles at the deadline even when the request does not react to its signal.
659
+ */
660
+ withDeadline(what, work) {
661
+ const controller = new AbortController();
662
+ const ms = this.config.timeout;
663
+ return new Promise((resolve, reject) => {
664
+ const timer = setTimeout(() => {
665
+ reject(new EnclaveClientError("TIMEOUT", `${what} timed out after ${ms} ms`));
666
+ controller.abort();
667
+ }, ms);
668
+ work(controller.signal).then(
669
+ (value) => {
670
+ clearTimeout(timer);
671
+ resolve(value);
407
672
  },
408
- signal: session.abortController.signal
409
- });
410
- if (!response.ok) {
411
- throw new EnclaveClientError("RECONNECT_FAILED", `Reconnection failed: ${response.status}`);
412
- }
413
- session.reconnectState.onConnected();
414
- session.heartbeatMonitor.start();
415
- await this.streamResponse(session, response);
416
- } catch (error) {
417
- if (error instanceof Error && error.name === "AbortError") {
418
- return;
419
- }
420
- if (session.reconnectState.canReconnect()) {
421
- session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Reconnection failed");
422
- } else {
423
- this.handleSessionError(sessionId, error);
424
- }
425
- }
673
+ (error) => {
674
+ clearTimeout(timer);
675
+ reject(error);
676
+ }
677
+ );
678
+ });
426
679
  }
427
680
  /**
428
681
  * Build request headers.
@@ -432,12 +685,21 @@ var EnclaveClient = class {
432
685
  ...this.config.headers
433
686
  };
434
687
  }
688
+ /** The creation identifier always takes precedence over configured headers. */
689
+ sessionHeaders(session) {
690
+ const headers = this.buildHeaders();
691
+ for (const name of Object.keys(headers)) {
692
+ if (name.toLowerCase() === "x-session-instance-id") delete headers[name];
693
+ }
694
+ headers["X-Session-Instance-ID"] = session.instanceId;
695
+ return headers;
696
+ }
435
697
  };
436
698
 
437
699
  // libs/client/src/index.ts
438
- import { ConnectionState } from "@enclave-vm/stream";
700
+ import { ConnectionState as ConnectionState2 } from "@enclave-vm/stream";
439
701
  export {
440
- ConnectionState,
702
+ ConnectionState2 as ConnectionState,
441
703
  EnclaveClient,
442
704
  EnclaveClientError
443
705
  };