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