@enclave-vm/client 2.19.0 → 2.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -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,99 @@ 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,
137
185
  events: [],
138
- abortController,
139
186
  resolve: resolveResult,
140
- reject: rejectResult,
141
187
  handlers: options,
142
188
  startTime: Date.now(),
143
189
  toolCallCount: 0,
144
190
  stdoutBytes: 0,
145
- reconnectState,
146
- heartbeatMonitor,
147
- lastSequence: 0
191
+ // Create reconnection state machine
192
+ reconnectState: new import_stream.ReconnectionStateMachine({
193
+ config: {
194
+ maxRetries: this.config.maxReconnectAttempts,
195
+ initialDelayMs: this.config.reconnectDelay
196
+ },
197
+ onEvent: (event) => {
198
+ if (event.type === "retry_started") {
199
+ void this.reconnectSession(session);
200
+ }
201
+ }
202
+ }),
203
+ lastSequence: -1,
204
+ // The server sends a heartbeat at the interval the session asked for. Two intervals
205
+ // without any event, and at least `timeout`, is a stream that has gone silent.
206
+ silenceMs: Math.max(
207
+ this.config.timeout,
208
+ 2 * (options.limits?.heartbeatIntervalMs ?? import_types.DEFAULT_SESSION_LIMITS.heartbeatIntervalMs)
209
+ ),
210
+ connection: null,
211
+ ended: false,
212
+ detachSignal: () => void 0
148
213
  };
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 {
214
+ const handle = {
155
215
  sessionId,
156
216
  wait: () => resultPromise,
157
217
  cancel: async (reason) => {
158
- await this.cancelSession(sessionId, reason);
218
+ await this.stopSession(session, reason);
159
219
  },
160
- getEvents: () => [...eventsRef],
161
- isActive: () => this.activeSessions.has(sessionId)
220
+ getEvents: () => [...session.events],
221
+ isActive: () => !session.ended && this.activeSessions.get(sessionId) === session
162
222
  };
223
+ if (sessionPathSegment(sessionId) === null) {
224
+ this.refuseSession(session, "Invalid session id");
225
+ return handle;
226
+ }
227
+ if (this.activeSessions.has(sessionId)) {
228
+ this.refuseSession(session, `Session ${sessionId} is already running on this client`);
229
+ return handle;
230
+ }
231
+ this.activeSessions.set(sessionId, session);
232
+ const signal = options.signal;
233
+ if (signal) {
234
+ const reasonOf = () => typeof signal.reason === "string" ? signal.reason : void 0;
235
+ if (signal.aborted) {
236
+ this.endSession(session, this.cancelledResult(session, reasonOf()));
237
+ return handle;
238
+ }
239
+ const onAbort = () => {
240
+ void this.stopSession(session, reasonOf());
241
+ };
242
+ signal.addEventListener("abort", onAbort, { once: true });
243
+ session.detachSignal = () => signal.removeEventListener("abort", onAbort);
244
+ }
245
+ void this.startSession(session, code, options.limits);
246
+ return handle;
163
247
  }
164
248
  /**
165
249
  * Get information about a session.
166
250
  */
167
251
  async getSession(sessionId) {
168
- const url = `${this.config.baseUrl}/sessions/${sessionId}`;
252
+ const segment = sessionPathSegment(sessionId);
253
+ if (segment === null) {
254
+ throw new EnclaveClientError("SESSION_ERROR", "Invalid session id");
255
+ }
256
+ const url = `${this.config.baseUrl}/sessions/${segment}`;
169
257
  try {
170
- const response = await this.config.fetch(url, {
171
- method: "GET",
172
- headers: this.buildHeaders()
258
+ return await this.withDeadline("Getting the session", async (signal) => {
259
+ const response = await this.config.fetch(url, {
260
+ method: "GET",
261
+ headers: this.buildHeaders(),
262
+ signal
263
+ });
264
+ if (response.status === 404) {
265
+ return null;
266
+ }
267
+ if (!response.ok) {
268
+ throw new EnclaveClientError("SESSION_ERROR", `Failed to get session: ${response.status}`);
269
+ }
270
+ return await response.json();
173
271
  });
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
272
  } catch (error) {
182
273
  if (error instanceof EnclaveClientError) throw error;
183
274
  throw new EnclaveClientError(
@@ -189,35 +280,53 @@ var EnclaveClient = class {
189
280
  }
190
281
  /**
191
282
  * Cancel a running session.
283
+ *
284
+ * The session of this client ends as `CANCELLED`, and the server is asked to end the session
285
+ * (`DELETE /sessions/:sessionId`). When the server does not confirm that, the session's
286
+ * `onError` handler is called with the code `CANCEL_FAILED`: the script may still be running.
192
287
  */
193
288
  async cancelSession(sessionId, reason) {
194
289
  const session = this.activeSessions.get(sessionId);
195
290
  if (!session) {
196
291
  return;
197
292
  }
198
- session.heartbeatMonitor.stop();
199
- session.reconnectState.close();
200
- session.abortController.abort(reason);
201
- const url = `${this.config.baseUrl}/sessions/${sessionId}/cancel`;
293
+ await this.stopSession(session, reason);
294
+ }
295
+ /**
296
+ * End a session of this client as cancelled and ask the server to end it too.
297
+ * Never rejects.
298
+ */
299
+ async stopSession(session, reason) {
300
+ if (session.ended) {
301
+ return;
302
+ }
303
+ this.endSession(session, this.cancelledResult(session, reason));
304
+ const url = `${this.config.baseUrl}/sessions/${sessionPathSegment(session.sessionId)}`;
305
+ let failure = null;
202
306
  try {
203
- await this.config.fetch(url, {
204
- method: "POST",
205
- headers: this.buildHeaders(),
206
- body: JSON.stringify({ reason })
307
+ await this.withDeadline("Stopping the session", async (signal) => {
308
+ const response = await this.config.fetch(url, {
309
+ method: "DELETE",
310
+ headers: this.buildHeaders(),
311
+ signal
312
+ });
313
+ void response.body?.cancel().catch(() => void 0);
314
+ if (!response.ok && response.status !== 404) {
315
+ failure = `the server answered ${response.status}`;
316
+ }
207
317
  });
208
- } catch {
318
+ } catch (error) {
319
+ failure = error instanceof Error ? error.message : "the request failed";
209
320
  }
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
321
+ if (failure !== null) {
322
+ try {
323
+ session.handlers.onError?.(
324
+ "CANCEL_FAILED",
325
+ `The server did not confirm that session ${session.sessionId} was stopped: ${failure}`
326
+ );
327
+ } catch {
219
328
  }
220
- });
329
+ }
221
330
  }
222
331
  /**
223
332
  * Start a session and begin streaming events.
@@ -235,7 +344,7 @@ var EnclaveClient = class {
235
344
  heartbeatIntervalMs: limits.heartbeatIntervalMs
236
345
  };
237
346
  }
238
- try {
347
+ await this.runConnection(session, async (signal) => {
239
348
  const response = await this.config.fetch(url, {
240
349
  method: "POST",
241
350
  headers: {
@@ -244,55 +353,149 @@ var EnclaveClient = class {
244
353
  Accept: "application/x-ndjson"
245
354
  },
246
355
  body: JSON.stringify(body),
247
- signal: session.abortController.signal
356
+ signal
248
357
  });
249
358
  if (!response.ok) {
250
- const errorText = await response.text();
359
+ const errorText = (await response.text()).slice(0, 500);
251
360
  throw new EnclaveClientError("SESSION_ERROR", `Failed to start session: ${response.status} - ${errorText}`);
252
361
  }
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;
362
+ return response;
363
+ });
364
+ }
365
+ /**
366
+ * Attempt to reconnect a session.
367
+ */
368
+ async reconnectSession(session) {
369
+ if (session.ended) return;
370
+ const url = `${this.config.baseUrl}/sessions/${sessionPathSegment(session.sessionId)}/stream`;
371
+ const query = session.lastSequence >= 0 ? `?fromSeq=${session.lastSequence + 1}` : "";
372
+ await this.runConnection(session, async (signal) => {
373
+ const response = await this.config.fetch(`${url}${query}`, {
374
+ method: "GET",
375
+ headers: {
376
+ ...this.buildHeaders(),
377
+ Accept: "application/x-ndjson"
378
+ },
379
+ signal
380
+ });
381
+ if (!response.ok) {
382
+ void response.body?.cancel().catch(() => void 0);
383
+ throw new EnclaveClientError("RECONNECT_FAILED", `Reconnection failed: ${response.status}`);
259
384
  }
260
- if (this.config.autoReconnect && session.reconnectState.canReconnect()) {
261
- session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Connection lost");
385
+ return response;
386
+ });
387
+ }
388
+ /**
389
+ * Open a connection for a session and follow its stream until the session ends or the
390
+ * connection is lost. A session has one connection at a time: the previous one is closed
391
+ * first, and nothing that still arrives on it is delivered.
392
+ */
393
+ async runConnection(session, request) {
394
+ if (session.ended) return;
395
+ this.closeConnection(session);
396
+ const connection = { controller: new AbortController(), timer: null };
397
+ session.connection = connection;
398
+ try {
399
+ this.watch(session, connection, this.config.timeout, "No response from the server");
400
+ const response = await request(connection.controller.signal);
401
+ if (!this.isCurrent(session, connection)) {
402
+ void response.body?.cancel().catch(() => void 0);
262
403
  return;
263
404
  }
264
- throw error;
405
+ await this.streamResponse(session, connection, response);
406
+ } catch (error) {
407
+ this.connectionLost(session, connection, error);
265
408
  }
266
409
  }
267
410
  /**
268
411
  * Stream and parse the NDJSON response.
269
412
  */
270
- async streamResponse(session, response) {
413
+ async streamResponse(session, connection, response) {
271
414
  const body = response.body;
272
415
  if (!body) {
273
416
  throw new EnclaveClientError("PARSE_ERROR", "No response body");
274
417
  }
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;
418
+ this.watch(session, connection, session.silenceMs, "No event from the server");
419
+ for await (const event of (0, import_stream.parseNdjsonStream)(body, { maxLineLength: this.config.maxEventLength })) {
420
+ if (!this.isCurrent(session, connection)) return;
421
+ this.watch(session, connection, session.silenceMs, "No event from the server");
422
+ this.handleEvent(session, event);
423
+ if (session.ended) return;
424
+ }
425
+ if (!this.isCurrent(session, connection)) return;
426
+ throw new EnclaveClientError("NETWORK_ERROR", "The stream ended before the session was complete");
427
+ }
428
+ /**
429
+ * (Re)start the timer of a connection. When it runs out the connection counts as lost.
430
+ */
431
+ watch(session, connection, ms, what) {
432
+ if (connection.timer !== null) {
433
+ clearTimeout(connection.timer);
434
+ }
435
+ connection.timer = setTimeout(() => {
436
+ connection.timer = null;
437
+ this.connectionLost(session, connection, new EnclaveClientError("TIMEOUT", `${what} within ${ms} ms`));
438
+ }, ms);
439
+ }
440
+ /**
441
+ * Whether a connection is the one its session is using.
442
+ */
443
+ isCurrent(session, connection) {
444
+ return !session.ended && session.connection === connection;
445
+ }
446
+ /**
447
+ * Close the connection of a session, if it has one.
448
+ */
449
+ closeConnection(session) {
450
+ const connection = session.connection;
451
+ if (!connection) return;
452
+ session.connection = null;
453
+ if (connection.timer !== null) {
454
+ clearTimeout(connection.timer);
455
+ connection.timer = null;
288
456
  }
457
+ connection.controller.abort();
458
+ }
459
+ /**
460
+ * A connection failed, ended early or went silent: reconnect if that is allowed, otherwise
461
+ * the session fails. A connection that is no longer the session's own is ignored.
462
+ */
463
+ connectionLost(session, connection, error) {
464
+ if (!this.isCurrent(session, connection)) return;
465
+ this.closeConnection(session);
466
+ if (error instanceof import_stream.NdjsonLineTooLongError) {
467
+ this.failSession(
468
+ session,
469
+ new EnclaveClientError(
470
+ "PARSE_ERROR",
471
+ `The server sent an event longer than ${this.config.maxEventLength} characters`,
472
+ error
473
+ )
474
+ );
475
+ return;
476
+ }
477
+ if (this.config.autoReconnect && session.reconnectState.canReconnect()) {
478
+ session.reconnectState.onDisconnected(error instanceof Error ? error.message : "Connection lost");
479
+ return;
480
+ }
481
+ this.failSession(session, error);
289
482
  }
290
483
  /**
291
484
  * Handle a received stream event.
292
485
  */
293
486
  handleEvent(session, event) {
294
- if (event.seq !== void 0) {
295
- session.lastSequence = event.seq;
487
+ if (session.ended) return;
488
+ if (event.seq <= session.lastSequence) return;
489
+ session.lastSequence = event.seq;
490
+ if (session.reconnectState.getState() !== import_stream.ConnectionState.Connected) {
491
+ session.reconnectState.onConnected();
492
+ }
493
+ if (event.type === "enc") {
494
+ this.failSession(
495
+ session,
496
+ new EnclaveClientError("PARSE_ERROR", "The server sent an encrypted event, which this client cannot read")
497
+ );
498
+ return;
296
499
  }
297
500
  session.events.push(event);
298
501
  session.handlers.onEvent?.(event);
@@ -309,7 +512,6 @@ var EnclaveClient = class {
309
512
  } else if ((0, import_types.isToolResultAppliedEvent)(event)) {
310
513
  session.handlers.onToolResultApplied?.(event.payload.callId);
311
514
  } else if ((0, import_types.isHeartbeatEvent)(event)) {
312
- session.heartbeatMonitor.onHeartbeat();
313
515
  session.handlers.onHeartbeat?.();
314
516
  } else if ((0, import_types.isErrorEvent)(event)) {
315
517
  session.handlers.onError?.(event.payload.code ?? "UNKNOWN", event.payload.message);
@@ -338,17 +540,11 @@ var EnclaveClient = class {
338
540
  * Handle the final event and complete the session.
339
541
  */
340
542
  handleFinalEvent(session, event) {
341
- session.heartbeatMonitor.stop();
342
- session.reconnectState.close();
343
543
  const result = {
344
544
  success: event.payload.ok,
345
545
  sessionId: session.sessionId,
346
546
  events: session.events,
347
- stats: {
348
- durationMs: Date.now() - session.startTime,
349
- toolCallCount: session.toolCallCount,
350
- stdoutBytes: session.stdoutBytes
351
- }
547
+ stats: this.statsOf(session)
352
548
  };
353
549
  if (event.payload.ok) {
354
550
  result.value = event.payload.result;
@@ -365,78 +561,92 @@ var EnclaveClient = class {
365
561
  path: e.path
366
562
  }));
367
563
  }
368
- this.completeSession(session.sessionId, result);
564
+ this.endSession(session, result);
369
565
  }
370
566
  /**
371
- * Handle a session error.
567
+ * End a session with an error.
372
568
  */
373
- handleSessionError(sessionId, error) {
374
- const session = this.activeSessions.get(sessionId);
375
- if (!session) return;
376
- session.heartbeatMonitor.stop();
377
- session.reconnectState.close();
569
+ failSession(session, error) {
378
570
  const clientError = error instanceof EnclaveClientError ? error : new EnclaveClientError(
379
571
  "NETWORK_ERROR",
380
572
  error instanceof Error ? error.message : "Unknown error",
381
573
  error instanceof Error ? error : void 0
382
574
  );
383
- this.completeSession(sessionId, {
575
+ this.endSession(session, {
384
576
  success: false,
385
- sessionId,
577
+ sessionId: session.sessionId,
386
578
  error: { code: clientError.code, message: clientError.message },
387
579
  events: session.events,
388
- stats: {
389
- durationMs: Date.now() - session.startTime,
390
- toolCallCount: session.toolCallCount,
391
- stdoutBytes: session.stdoutBytes
392
- }
580
+ stats: this.statsOf(session)
393
581
  });
394
582
  }
395
583
  /**
396
- * Complete a session and clean up.
584
+ * End a session that was never requested from the server.
397
585
  */
398
- completeSession(sessionId, result) {
399
- const session = this.activeSessions.get(sessionId);
400
- if (!session) return;
401
- this.activeSessions.delete(sessionId);
402
- session.resolve(result);
586
+ refuseSession(session, message) {
587
+ session.ended = true;
588
+ session.reconnectState.close();
589
+ session.resolve({
590
+ success: false,
591
+ sessionId: session.sessionId,
592
+ error: { code: "SESSION_ERROR", message },
593
+ events: session.events,
594
+ stats: this.statsOf(session)
595
+ });
403
596
  }
404
597
  /**
405
- * Attempt to reconnect a session.
598
+ * Give a session its result and clean up. The first result is the only one.
406
599
  */
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));
600
+ endSession(session, result) {
601
+ if (session.ended) return;
602
+ session.ended = true;
603
+ this.closeConnection(session);
604
+ session.reconnectState.close();
605
+ session.detachSignal();
606
+ if (this.activeSessions.get(session.sessionId) === session) {
607
+ this.activeSessions.delete(session.sessionId);
414
608
  }
415
- try {
416
- const response = await this.config.fetch(`${url}?${params}`, {
417
- method: "GET",
418
- headers: {
419
- ...this.buildHeaders(),
420
- Accept: "application/x-ndjson"
609
+ session.resolve(result);
610
+ }
611
+ cancelledResult(session, reason) {
612
+ return {
613
+ success: false,
614
+ sessionId: session.sessionId,
615
+ error: { code: "CANCELLED", message: reason || "Session cancelled" },
616
+ events: session.events,
617
+ stats: this.statsOf(session)
618
+ };
619
+ }
620
+ statsOf(session) {
621
+ return {
622
+ durationMs: Date.now() - session.startTime,
623
+ toolCallCount: session.toolCallCount,
624
+ stdoutBytes: session.stdoutBytes
625
+ };
626
+ }
627
+ /**
628
+ * Run a request that is not a session stream, bounded by the configured timeout.
629
+ * The promise settles at the deadline even when the request does not react to its signal.
630
+ */
631
+ withDeadline(what, work) {
632
+ const controller = new AbortController();
633
+ const ms = this.config.timeout;
634
+ return new Promise((resolve, reject) => {
635
+ const timer = setTimeout(() => {
636
+ reject(new EnclaveClientError("TIMEOUT", `${what} timed out after ${ms} ms`));
637
+ controller.abort();
638
+ }, ms);
639
+ work(controller.signal).then(
640
+ (value) => {
641
+ clearTimeout(timer);
642
+ resolve(value);
421
643
  },
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
- }
644
+ (error) => {
645
+ clearTimeout(timer);
646
+ reject(error);
647
+ }
648
+ );
649
+ });
440
650
  }
441
651
  /**
442
652
  * Build request headers.