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