@seclai/sdk 1.10.0 → 1.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +30 -14
- package/dist/index.cjs +295 -192
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +81 -35
- package/dist/index.d.ts +81 -35
- package/dist/index.js +295 -192
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -547,47 +547,122 @@ function createSseParser(onMessage) {
|
|
|
547
547
|
eventName = void 0;
|
|
548
548
|
dataLines = [];
|
|
549
549
|
}
|
|
550
|
+
function processLine(rawLine) {
|
|
551
|
+
let line = rawLine;
|
|
552
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
553
|
+
if (line === "") {
|
|
554
|
+
dispatch();
|
|
555
|
+
return;
|
|
556
|
+
}
|
|
557
|
+
if (line.startsWith(":")) return;
|
|
558
|
+
const colon = line.indexOf(":");
|
|
559
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
560
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
561
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
562
|
+
if (field === "event") {
|
|
563
|
+
eventName = value;
|
|
564
|
+
} else if (field === "data") {
|
|
565
|
+
dataLines.push(value);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
550
568
|
function feed(textChunk) {
|
|
551
569
|
buffer += textChunk;
|
|
552
570
|
while (true) {
|
|
553
571
|
const newlineIdx = buffer.indexOf("\n");
|
|
554
572
|
if (newlineIdx === -1) return;
|
|
555
|
-
|
|
573
|
+
const line = buffer.slice(0, newlineIdx);
|
|
556
574
|
buffer = buffer.slice(newlineIdx + 1);
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
566
|
-
if (value.startsWith(" ")) value = value.slice(1);
|
|
567
|
-
if (field === "event") {
|
|
568
|
-
eventName = value;
|
|
569
|
-
} else if (field === "data") {
|
|
570
|
-
dataLines.push(value);
|
|
571
|
-
}
|
|
575
|
+
processLine(line);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
function end() {
|
|
579
|
+
if (buffer !== "") {
|
|
580
|
+
const line = buffer;
|
|
581
|
+
buffer = "";
|
|
582
|
+
processLine(line);
|
|
572
583
|
}
|
|
584
|
+
dispatch();
|
|
585
|
+
}
|
|
586
|
+
function abandon() {
|
|
587
|
+
buffer = "";
|
|
588
|
+
dispatch();
|
|
573
589
|
}
|
|
574
|
-
return { feed, end
|
|
590
|
+
return { feed, end, abandon };
|
|
575
591
|
}
|
|
576
592
|
function anySignal(signals) {
|
|
577
593
|
const present = signals.filter(Boolean);
|
|
578
|
-
if (present.length === 0) return void 0
|
|
579
|
-
|
|
594
|
+
if (present.length === 0) return { signal: void 0, cleanup: () => {
|
|
595
|
+
} };
|
|
596
|
+
if (present.length === 1) return { signal: present[0], cleanup: () => {
|
|
597
|
+
} };
|
|
580
598
|
const controller = new AbortController();
|
|
581
|
-
const
|
|
599
|
+
const listening = [];
|
|
600
|
+
const cleanup = () => {
|
|
601
|
+
for (const [s, onAbort] of listening) s.removeEventListener("abort", onAbort);
|
|
602
|
+
listening.length = 0;
|
|
603
|
+
};
|
|
582
604
|
for (const s of present) {
|
|
583
605
|
if (s.aborted) {
|
|
584
|
-
|
|
606
|
+
cleanup();
|
|
607
|
+
controller.abort(s.reason);
|
|
585
608
|
break;
|
|
586
609
|
}
|
|
610
|
+
const onAbort = () => controller.abort(s.reason);
|
|
587
611
|
s.addEventListener("abort", onAbort, { once: true });
|
|
612
|
+
listening.push([s, onAbort]);
|
|
588
613
|
}
|
|
589
|
-
return controller.signal;
|
|
614
|
+
return { signal: controller.signal, cleanup };
|
|
615
|
+
}
|
|
616
|
+
function abortReason(signal) {
|
|
617
|
+
return signal.reason !== void 0 ? signal.reason : new DOMException("This operation was aborted", "AbortError");
|
|
618
|
+
}
|
|
619
|
+
function throwIfAborted(signal) {
|
|
620
|
+
if (signal?.aborted) throw abortReason(signal);
|
|
621
|
+
}
|
|
622
|
+
var MAX_TIMER_MS = 2147483647;
|
|
623
|
+
function sleep(ms, signal) {
|
|
624
|
+
return new Promise((resolve, reject) => {
|
|
625
|
+
if (signal?.aborted) {
|
|
626
|
+
reject(abortReason(signal));
|
|
627
|
+
return;
|
|
628
|
+
}
|
|
629
|
+
let remaining = Math.max(ms, 0);
|
|
630
|
+
let timer;
|
|
631
|
+
const onAbort = () => {
|
|
632
|
+
clearTimeout(timer);
|
|
633
|
+
reject(abortReason(signal));
|
|
634
|
+
};
|
|
635
|
+
const arm = () => {
|
|
636
|
+
const step = Math.min(remaining, MAX_TIMER_MS);
|
|
637
|
+
remaining -= step;
|
|
638
|
+
timer = setTimeout(() => {
|
|
639
|
+
if (remaining > 0) return arm();
|
|
640
|
+
signal?.removeEventListener("abort", onAbort);
|
|
641
|
+
resolve();
|
|
642
|
+
}, step);
|
|
643
|
+
};
|
|
644
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
645
|
+
arm();
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
function isTerminalStatus(status) {
|
|
649
|
+
return status === "completed" || status === "failed" || status === "cancelled";
|
|
650
|
+
}
|
|
651
|
+
function isRunSnapshot(data) {
|
|
652
|
+
return data !== null && typeof data === "object" && !Array.isArray(data);
|
|
653
|
+
}
|
|
654
|
+
function streamTimeoutMessage(timeoutMs) {
|
|
655
|
+
return `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`;
|
|
656
|
+
}
|
|
657
|
+
function incompleteRunError(reason, run, runId) {
|
|
658
|
+
const state = run?.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
|
|
659
|
+
return new SeclaiStreamingError(`${reason} ${state}`, runId ?? run?.run_id, run);
|
|
590
660
|
}
|
|
661
|
+
function withCause(error, cause) {
|
|
662
|
+
Object.defineProperty(error, "cause", { value: cause, enumerable: false, writable: true, configurable: true });
|
|
663
|
+
return error;
|
|
664
|
+
}
|
|
665
|
+
var streamTimeouts = /* @__PURE__ */ new WeakSet();
|
|
591
666
|
function toBlob(file, mimeType) {
|
|
592
667
|
if (file instanceof Blob) return file;
|
|
593
668
|
const opts = mimeType ? { type: mimeType } : void 0;
|
|
@@ -1197,11 +1272,11 @@ var Seclai = class {
|
|
|
1197
1272
|
/**
|
|
1198
1273
|
* Run an agent in streaming mode (SSE) and wait for the final result.
|
|
1199
1274
|
*
|
|
1200
|
-
*
|
|
1201
|
-
* For real-time event access, use
|
|
1202
|
-
* takes no `include_reasoning`
|
|
1203
|
-
* is not sent: this method
|
|
1204
|
-
* `stream_commentary` events.
|
|
1275
|
+
* Reads the events of {@link runStreamingAgent} and returns the run from the
|
|
1276
|
+
* terminal `done` event. For real-time event access, use
|
|
1277
|
+
* {@link runStreamingAgent} instead. The body takes no `include_reasoning`
|
|
1278
|
+
* or `include_commentary`, and one passed anyway is not sent: this method
|
|
1279
|
+
* returns no `stream_reasoning` or `stream_commentary` events.
|
|
1205
1280
|
*
|
|
1206
1281
|
* A `result` event carries the run's answer in `output` once
|
|
1207
1282
|
* `result_reported_at` is set, and can arrive while later steps still run.
|
|
@@ -1210,17 +1285,24 @@ var Seclai = class {
|
|
|
1210
1285
|
* its `status` is not terminal and the run can still fail, so check
|
|
1211
1286
|
* `result_reported_at`, not `status`.
|
|
1212
1287
|
*
|
|
1213
|
-
*
|
|
1214
|
-
*
|
|
1215
|
-
*
|
|
1288
|
+
* The latest snapshot is the `result` event's run if one arrived, else the
|
|
1289
|
+
* `init` event's run. When the server sends an `error`
|
|
1290
|
+
* event, this throws {@link SeclaiStreamingError} with the server's error
|
|
1291
|
+
* text in its message; when the server sends a `timeout` event, or
|
|
1292
|
+
* `timeoutMs` elapses (unless an HTTP error status arrives as it elapses),
|
|
1293
|
+
* it throws {@link SeclaiStreamingError} too. Each
|
|
1294
|
+
* carries the latest snapshot in `run`. An abort from `signal` rethrows the
|
|
1295
|
+
* abort error. Every way out of this method closes the response body.
|
|
1216
1296
|
*
|
|
1217
1297
|
* By default, a stream that ends before `done` returns the latest snapshot
|
|
1218
|
-
* when its status is not `pending`, so the run returned may
|
|
1219
|
-
* finished: check `status` and `result_reported_at`. A stream that
|
|
1220
|
-
* throws the fetch error
|
|
1221
|
-
*
|
|
1222
|
-
*
|
|
1223
|
-
*
|
|
1298
|
+
* when its status is not `pending`, so the run returned may
|
|
1299
|
+
* not have finished: check `status` and `result_reported_at`. A stream that
|
|
1300
|
+
* breaks throws the fetch error, unless a `done` event, or with
|
|
1301
|
+
* `returnOnResult` a `result` event, was read in full before it
|
|
1302
|
+
* broke. Pass `throwOnIncomplete: true` to throw
|
|
1303
|
+
* {@link SeclaiStreamingError} with the latest snapshot in `run` in both
|
|
1304
|
+
* cases instead; it is recommended, and becomes the default in the next
|
|
1305
|
+
* major version.
|
|
1224
1306
|
*
|
|
1225
1307
|
* @param agentId - Agent identifier.
|
|
1226
1308
|
* @param body - Streaming run request payload, without `include_reasoning`
|
|
@@ -1229,9 +1311,14 @@ var Seclai = class {
|
|
|
1229
1311
|
* @returns The run from the `done` event; with `returnOnResult`, the
|
|
1230
1312
|
* `result` snapshot; without `throwOnIncomplete`, possibly an unfinished
|
|
1231
1313
|
* snapshot (see above).
|
|
1232
|
-
* @throws {@link SeclaiStreamingError} If `
|
|
1233
|
-
* `
|
|
1234
|
-
*
|
|
1314
|
+
* @throws {@link SeclaiStreamingError} If the server sends an `error` or
|
|
1315
|
+
* `timeout` event, `timeoutMs` elapses (unless an HTTP error status
|
|
1316
|
+
* arrives as it elapses), or, with `throwOnIncomplete`, the
|
|
1317
|
+
* stream ends or breaks, before the run finished. Its `run` holds the
|
|
1318
|
+
* latest snapshot. On `timeoutMs`, when the request or read was cut off,
|
|
1319
|
+
* its `cause` is the error it ended with.
|
|
1320
|
+
* @throws {@link SeclaiAPIStatusError} For an HTTP error status, also one
|
|
1321
|
+
* that arrives as `timeoutMs` elapses.
|
|
1235
1322
|
*
|
|
1236
1323
|
* @example
|
|
1237
1324
|
* ```ts
|
|
@@ -1251,120 +1338,56 @@ var Seclai = class {
|
|
|
1251
1338
|
include_commentary: _commentary,
|
|
1252
1339
|
...runBody
|
|
1253
1340
|
} = body;
|
|
1254
|
-
const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
|
|
1255
|
-
const authHdrs = await this.authHeaders();
|
|
1256
|
-
const headers = this.requestHeaders([
|
|
1257
|
-
this.defaultHeaders,
|
|
1258
|
-
authHdrs,
|
|
1259
|
-
{ accept: "text/event-stream", "content-type": "application/json" }
|
|
1260
|
-
]);
|
|
1261
1341
|
const timeoutMs = opts?.timeoutMs ?? 6e4;
|
|
1262
|
-
const
|
|
1263
|
-
|
|
1264
|
-
const
|
|
1265
|
-
|
|
1266
|
-
timeoutController.abort();
|
|
1267
|
-
}, timeoutMs);
|
|
1268
|
-
const signal = anySignal([opts?.signal, timeoutController.signal]);
|
|
1269
|
-
let lastSeen;
|
|
1342
|
+
const streamOpts = { timeoutMs };
|
|
1343
|
+
if (opts?.signal) streamOpts.signal = opts.signal;
|
|
1344
|
+
const progress = { jsonReply: false, reading: false, timedOut: false };
|
|
1345
|
+
let initial;
|
|
1270
1346
|
let reported;
|
|
1347
|
+
const snapshot = () => reported ?? initial;
|
|
1271
1348
|
try {
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
const responseText = await safeText(response);
|
|
1279
|
-
if (response.status === 422) {
|
|
1280
|
-
const validation = await safeJson(response);
|
|
1281
|
-
throw new SeclaiAPIValidationError({
|
|
1282
|
-
message: "Validation error",
|
|
1283
|
-
statusCode: response.status,
|
|
1284
|
-
method: "POST",
|
|
1285
|
-
url: url.toString(),
|
|
1286
|
-
responseText,
|
|
1287
|
-
headers: new Headers(response.headers),
|
|
1288
|
-
validationError: validation
|
|
1289
|
-
});
|
|
1290
|
-
}
|
|
1291
|
-
throw new SeclaiAPIStatusError({
|
|
1292
|
-
message: `Request failed with status ${response.status}`,
|
|
1293
|
-
statusCode: response.status,
|
|
1294
|
-
method: "POST",
|
|
1295
|
-
url: url.toString(),
|
|
1296
|
-
responseText,
|
|
1297
|
-
headers: new Headers(response.headers)
|
|
1298
|
-
});
|
|
1299
|
-
}
|
|
1300
|
-
if (isJson) {
|
|
1301
|
-
const run2 = await response.json();
|
|
1302
|
-
const status = run2.status;
|
|
1303
|
-
const finished = status === "completed" || status === "failed" || status === "cancelled" || Boolean(opts?.returnOnResult && run2.result_reported_at);
|
|
1304
|
-
if (opts?.throwOnIncomplete && !finished) {
|
|
1305
|
-
const state2 = run2.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
|
|
1306
|
-
throw new SeclaiStreamingError(`The server answered with JSON for a run that has not finished. ${state2}`, run2.run_id, run2);
|
|
1307
|
-
}
|
|
1308
|
-
return run2;
|
|
1309
|
-
}
|
|
1310
|
-
if (!response.body) {
|
|
1311
|
-
throw new SeclaiConfigurationError(
|
|
1312
|
-
"Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies."
|
|
1313
|
-
);
|
|
1314
|
-
}
|
|
1315
|
-
const reader = response.body.getReader();
|
|
1316
|
-
const decoder = new TextDecoder();
|
|
1317
|
-
let final;
|
|
1318
|
-
const parser = createSseParser((msg) => {
|
|
1319
|
-
if (!msg.data) return;
|
|
1320
|
-
if (msg.event === "init" || msg.event === "result" || msg.event === "done") {
|
|
1321
|
-
try {
|
|
1322
|
-
const parsed = JSON.parse(msg.data);
|
|
1323
|
-
lastSeen = parsed;
|
|
1324
|
-
if (msg.event === "result") reported = parsed;
|
|
1325
|
-
if (msg.event === "done") final = parsed;
|
|
1326
|
-
} catch {
|
|
1349
|
+
for await (const { event, data } of this.streamRunEvents(agentId, runBody, streamOpts, progress)) {
|
|
1350
|
+
if (event === "error" || event === "timeout") {
|
|
1351
|
+
const info = isRunSnapshot(data) ? data : {};
|
|
1352
|
+
const runId = typeof info.run_id === "string" ? info.run_id : void 0;
|
|
1353
|
+
if (event === "timeout") {
|
|
1354
|
+
throw incompleteRunError("The server timed out the streaming agent run before it finished.", snapshot(), runId);
|
|
1327
1355
|
}
|
|
1356
|
+
const text = typeof info.error === "string" ? info.error : typeof data === "string" ? data : void 0;
|
|
1357
|
+
const reason = text ? `The streaming agent run failed on the server: ${text}${/[.!?]$/.test(text) ? "" : "."}` : "The streaming agent run failed on the server.";
|
|
1358
|
+
throw incompleteRunError(reason, snapshot(), runId);
|
|
1328
1359
|
}
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
if (
|
|
1335
|
-
|
|
1360
|
+
if (!isRunSnapshot(data)) continue;
|
|
1361
|
+
if (event === "init") {
|
|
1362
|
+
initial = data;
|
|
1363
|
+
} else if (event === "result") {
|
|
1364
|
+
reported = data;
|
|
1365
|
+
if (opts?.returnOnResult) return data;
|
|
1366
|
+
} else if (event === "done") {
|
|
1367
|
+
const finished = isTerminalStatus(data.status) || Boolean(opts?.returnOnResult && data.result_reported_at);
|
|
1368
|
+
if (progress.jsonReply && opts?.throwOnIncomplete && !finished) {
|
|
1369
|
+
throw incompleteRunError("The server answered with JSON for a run that has not finished.", data);
|
|
1370
|
+
}
|
|
1371
|
+
return data;
|
|
1336
1372
|
}
|
|
1337
|
-
} catch (err) {
|
|
1338
|
-
if (opts?.signal?.aborted || !opts?.throwOnIncomplete && !timedOut) throw err;
|
|
1339
|
-
readFailure = err instanceof Error ? err.message : String(err);
|
|
1340
|
-
}
|
|
1341
|
-
parser.feed(decoder.decode());
|
|
1342
|
-
parser.end();
|
|
1343
|
-
if (final) return final;
|
|
1344
|
-
if (opts?.returnOnResult && reported) {
|
|
1345
|
-
reader.cancel().catch(() => {
|
|
1346
|
-
});
|
|
1347
|
-
return reported;
|
|
1348
|
-
}
|
|
1349
|
-
if (!opts?.throwOnIncomplete && !timedOut && lastSeen?.status && lastSeen.status !== "pending") {
|
|
1350
|
-
return lastSeen;
|
|
1351
1373
|
}
|
|
1352
|
-
const run = reported ?? lastSeen;
|
|
1353
|
-
const state = reported ? "A result had been reported; see `run`." : "No result had been reported.";
|
|
1354
|
-
const reason = timedOut ? `Timed out after ${timeoutMs}ms before the streaming agent run finished.` : readFailure !== void 0 ? `Stream failed before the run finished: ${readFailure}.` : "Stream ended before receiving a 'done' event.";
|
|
1355
|
-
throw new SeclaiStreamingError(`${reason} ${state}`, run?.run_id, run);
|
|
1356
1374
|
} catch (err) {
|
|
1357
|
-
if (
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
);
|
|
1375
|
+
if (opts?.signal?.aborted) throw err;
|
|
1376
|
+
if (streamTimeouts.has(err)) {
|
|
1377
|
+
throw withCause(incompleteRunError(streamTimeoutMessage(timeoutMs), snapshot()), err.cause);
|
|
1378
|
+
}
|
|
1379
|
+
if (opts?.throwOnIncomplete && progress.reading && !(err instanceof SeclaiStreamingError)) {
|
|
1380
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1381
|
+
throw incompleteRunError(`Stream failed before the run finished: ${message}.`, snapshot());
|
|
1363
1382
|
}
|
|
1364
1383
|
throw err;
|
|
1365
|
-
} finally {
|
|
1366
|
-
clearTimeout(timeoutId);
|
|
1367
1384
|
}
|
|
1385
|
+
if (progress.timedOut) throw incompleteRunError(streamTimeoutMessage(timeoutMs), snapshot());
|
|
1386
|
+
const latest = snapshot();
|
|
1387
|
+
if (!opts?.throwOnIncomplete && latest?.status && latest.status !== "pending") {
|
|
1388
|
+
return latest;
|
|
1389
|
+
}
|
|
1390
|
+
throw incompleteRunError("Stream ended before receiving a 'done' event.", snapshot());
|
|
1368
1391
|
}
|
|
1369
1392
|
/**
|
|
1370
1393
|
* Run an agent in streaming mode and yield each SSE event as it arrives.
|
|
@@ -1374,6 +1397,13 @@ var Seclai = class {
|
|
|
1374
1397
|
* `include_commentary` in `body` to also receive `stream_reasoning` or
|
|
1375
1398
|
* `stream_commentary` events.
|
|
1376
1399
|
*
|
|
1400
|
+
* The server ends the stream after `done`, after `error` (data
|
|
1401
|
+
* `{ run_id, error }`, the stream failed on the server) or after `timeout`
|
|
1402
|
+
* (data `{ run_id }`); all three are yielded like any other event. When the
|
|
1403
|
+
* server answers with plain JSON instead of SSE, its run is yielded as one
|
|
1404
|
+
* `done` event. Leaving the loop early (`break`, `return` or a throw)
|
|
1405
|
+
* closes the response body.
|
|
1406
|
+
*
|
|
1377
1407
|
* From `apiVersion` `2026-11-14`, an agent whose definition fails to validate
|
|
1378
1408
|
* is refused with HTTP 409 ({@link SeclaiAPIStatusError}) before any event,
|
|
1379
1409
|
* and no run is created.
|
|
@@ -1382,6 +1412,11 @@ var Seclai = class {
|
|
|
1382
1412
|
* @param body - Streaming run request payload.
|
|
1383
1413
|
* @param opts - Timeout and abort signal options.
|
|
1384
1414
|
* @yields {@link AgentRunEvent} for each SSE message.
|
|
1415
|
+
* @throws {@link SeclaiStreamingError} If `timeoutMs` elapses, with the
|
|
1416
|
+
* error the request or read ended with as its `cause`. An HTTP error
|
|
1417
|
+
* status that arrives as it elapses is thrown as itself. An event read
|
|
1418
|
+
* in full before the stream broke or timed out is yielded first, unless
|
|
1419
|
+
* `signal` was aborted.
|
|
1385
1420
|
*
|
|
1386
1421
|
* @example
|
|
1387
1422
|
* ```ts
|
|
@@ -1397,6 +1432,14 @@ var Seclai = class {
|
|
|
1397
1432
|
* ```
|
|
1398
1433
|
*/
|
|
1399
1434
|
async *runStreamingAgent(agentId, body, opts) {
|
|
1435
|
+
yield* this.streamRunEvents(agentId, body, opts);
|
|
1436
|
+
}
|
|
1437
|
+
/**
|
|
1438
|
+
* The stream behind {@link runStreamingAgent} and
|
|
1439
|
+
* {@link runStreamingAgentAndWait}: one request, reader and parser for both.
|
|
1440
|
+
* `progress` tells the wait helper what the events alone do not.
|
|
1441
|
+
*/
|
|
1442
|
+
async *streamRunEvents(agentId, body, opts, progress) {
|
|
1400
1443
|
const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
|
|
1401
1444
|
const authHdrs = await this.authHeaders();
|
|
1402
1445
|
const headers = this.requestHeaders([
|
|
@@ -1409,9 +1452,11 @@ var Seclai = class {
|
|
|
1409
1452
|
let timedOut = false;
|
|
1410
1453
|
const timeoutId = setTimeout(() => {
|
|
1411
1454
|
timedOut = true;
|
|
1455
|
+
if (progress) progress.timedOut = true;
|
|
1412
1456
|
timeoutController.abort();
|
|
1413
1457
|
}, timeoutMs);
|
|
1414
|
-
const signal = anySignal([opts?.signal, timeoutController.signal]);
|
|
1458
|
+
const { signal, cleanup } = anySignal([opts?.signal, timeoutController.signal]);
|
|
1459
|
+
let reader;
|
|
1415
1460
|
try {
|
|
1416
1461
|
const init = { method: "POST", headers, body: JSON.stringify(body) };
|
|
1417
1462
|
if (signal) init.signal = signal;
|
|
@@ -1443,15 +1488,17 @@ var Seclai = class {
|
|
|
1443
1488
|
}
|
|
1444
1489
|
if (isJson) {
|
|
1445
1490
|
const data = await response.json();
|
|
1491
|
+
if (progress) progress.jsonReply = true;
|
|
1446
1492
|
yield { event: "done", data };
|
|
1447
1493
|
return;
|
|
1448
1494
|
}
|
|
1449
1495
|
if (!response.body) {
|
|
1450
1496
|
throw new SeclaiConfigurationError(
|
|
1451
|
-
"Streaming response body is not available in this environment."
|
|
1497
|
+
"Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies."
|
|
1452
1498
|
);
|
|
1453
1499
|
}
|
|
1454
|
-
|
|
1500
|
+
reader = response.body.getReader();
|
|
1501
|
+
if (progress) progress.reading = true;
|
|
1455
1502
|
const decoder = new TextDecoder();
|
|
1456
1503
|
const events = [];
|
|
1457
1504
|
const parser = createSseParser((msg) => {
|
|
@@ -1465,26 +1512,40 @@ var Seclai = class {
|
|
|
1465
1512
|
events.push({ event: msg.event ?? "message", data });
|
|
1466
1513
|
});
|
|
1467
1514
|
while (true) {
|
|
1468
|
-
|
|
1515
|
+
let chunk;
|
|
1516
|
+
try {
|
|
1517
|
+
chunk = await reader.read();
|
|
1518
|
+
} catch (err) {
|
|
1519
|
+
if (!opts?.signal?.aborted) {
|
|
1520
|
+
parser.feed(decoder.decode());
|
|
1521
|
+
parser.abandon();
|
|
1522
|
+
while (events.length > 0) yield events.shift();
|
|
1523
|
+
}
|
|
1524
|
+
throw err;
|
|
1525
|
+
}
|
|
1526
|
+
const { value, done } = chunk;
|
|
1469
1527
|
if (value) parser.feed(decoder.decode(value, { stream: true }));
|
|
1528
|
+
if (done) {
|
|
1529
|
+
parser.feed(decoder.decode());
|
|
1530
|
+
parser.end();
|
|
1531
|
+
}
|
|
1470
1532
|
while (events.length > 0) {
|
|
1471
1533
|
yield events.shift();
|
|
1472
1534
|
}
|
|
1473
1535
|
if (done) break;
|
|
1474
1536
|
}
|
|
1475
|
-
parser.end();
|
|
1476
|
-
while (events.length > 0) {
|
|
1477
|
-
yield events.shift();
|
|
1478
|
-
}
|
|
1479
1537
|
} catch (err) {
|
|
1480
|
-
if (timedOut) {
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1538
|
+
if (timedOut && !(err instanceof SeclaiAPIStatusError)) {
|
|
1539
|
+
const timeout = withCause(new SeclaiStreamingError(streamTimeoutMessage(timeoutMs)), err);
|
|
1540
|
+
streamTimeouts.add(timeout);
|
|
1541
|
+
throw timeout;
|
|
1484
1542
|
}
|
|
1485
1543
|
throw err;
|
|
1486
1544
|
} finally {
|
|
1487
1545
|
clearTimeout(timeoutId);
|
|
1546
|
+
cleanup();
|
|
1547
|
+
reader?.cancel().catch(() => {
|
|
1548
|
+
});
|
|
1488
1549
|
}
|
|
1489
1550
|
}
|
|
1490
1551
|
// ═══════════════════════════════════════════════════════════════════════════
|
|
@@ -1499,22 +1560,33 @@ var Seclai = class {
|
|
|
1499
1560
|
* `result_reported_at` is set, `output` holds the answer. Pass
|
|
1500
1561
|
* `returnOnResult: true` to return as soon as a run has it set, the run
|
|
1501
1562
|
* `runAgent()` returns included. With `includeStepOutputs`, when that run
|
|
1502
|
-
* would end the poll
|
|
1503
|
-
* once for its step outputs.
|
|
1563
|
+
* would end the poll, it is fetched again at once for its step outputs.
|
|
1504
1564
|
* Such a run may still be in progress: its `status` is not terminal and the
|
|
1505
1565
|
* run can still fail, so check `result_reported_at`, not `status`.
|
|
1506
1566
|
*
|
|
1507
1567
|
* When `timeoutMs` elapses first, this throws {@link SeclaiStreamingError}
|
|
1508
|
-
* with the latest run it has (the `runAgent()` response if no poll
|
|
1509
|
-
* `run`. If that run has `result_reported_at`
|
|
1510
|
-
*
|
|
1511
|
-
*
|
|
1512
|
-
* `
|
|
1513
|
-
*
|
|
1514
|
-
*
|
|
1515
|
-
*
|
|
1516
|
-
*
|
|
1517
|
-
*
|
|
1568
|
+
* with the latest run it has (the `runAgent()` response if no poll answered)
|
|
1569
|
+
* in `run`. If that run has `result_reported_at` set, its `output` is the
|
|
1570
|
+
* answer. No poll is sent at or after the deadline: a wait between polls that
|
|
1571
|
+
* reaches it ends the call with the timeout, so a `timeoutMs` no greater than
|
|
1572
|
+
* `pollIntervalMs` sends no poll. With a `fetch` that honours `signal`, a
|
|
1573
|
+
* poll still in flight at the deadline is aborted and the timeout is thrown.
|
|
1574
|
+
* Any error but an HTTP error status that a poll ends with once the deadline
|
|
1575
|
+
* has passed is the timeout's `cause`; an HTTP error status a poll gets after
|
|
1576
|
+
* the deadline is thrown as itself, and a caller abort throws `signal.reason`
|
|
1577
|
+
* instead. `timeoutMs` does not cut off the start request (the server may
|
|
1578
|
+
* already have created the run) or the fetch for an ended start run's step
|
|
1579
|
+
* outputs; only `signal` does. A request is not cut off while more than
|
|
1580
|
+
* 2^31-1 ms remain.
|
|
1581
|
+
*
|
|
1582
|
+
* `signal` is passed to every request and to the wait between polls. An
|
|
1583
|
+
* abort throws `signal.reason`, as `signal.throwIfAborted()` does (by
|
|
1584
|
+
* default an `AbortError`), or an `AbortError` for a signal that has no
|
|
1585
|
+
* `reason`: an already-aborted signal starts no run. A run
|
|
1586
|
+
* that has ended the poll is returned even after an abort. When the start
|
|
1587
|
+
* run has ended it and `includeStepOutputs` is set, an abort during the
|
|
1588
|
+
* fetch for its step outputs (with a `fetch` that honours `signal`) returns
|
|
1589
|
+
* the start run without step outputs.
|
|
1518
1590
|
*
|
|
1519
1591
|
* @param agentId - Agent identifier.
|
|
1520
1592
|
* @param body - Run request payload.
|
|
@@ -1523,41 +1595,72 @@ var Seclai = class {
|
|
|
1523
1595
|
* with `result_reported_at` set.
|
|
1524
1596
|
* @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run
|
|
1525
1597
|
* finished. Its `run` holds the latest run it has (the `runAgent()`
|
|
1526
|
-
* response if no poll
|
|
1527
|
-
*
|
|
1528
|
-
*
|
|
1529
|
-
*
|
|
1598
|
+
* response if no poll answered), and its `cause` the error a poll ended
|
|
1599
|
+
* with at the deadline, if one did (a caller abort throws `signal.reason`
|
|
1600
|
+
* instead).
|
|
1601
|
+
* @throws `signal.reason` If `signal` is aborted before the run has ended
|
|
1602
|
+
* the poll.
|
|
1530
1603
|
*/
|
|
1531
1604
|
async runAgentAndPoll(agentId, body, opts) {
|
|
1532
1605
|
const pollInterval = opts?.pollIntervalMs ?? 2e3;
|
|
1533
1606
|
const timeout = opts?.timeoutMs ?? 3e5;
|
|
1534
|
-
const
|
|
1535
|
-
const
|
|
1536
|
-
|
|
1607
|
+
const signal = opts?.signal;
|
|
1608
|
+
const deadline = Date.now() + timeout;
|
|
1609
|
+
throwIfAborted(signal);
|
|
1610
|
+
let current;
|
|
1611
|
+
let runId;
|
|
1612
|
+
const timedOut = () => incompleteRunError(`Polling timed out after ${timeout}ms.`, current, runId);
|
|
1613
|
+
const abortable = async (bounded, send) => {
|
|
1614
|
+
const limit = new AbortController();
|
|
1615
|
+
const left = deadline - Date.now();
|
|
1616
|
+
if (bounded && left <= 0) throw timedOut();
|
|
1617
|
+
const timer = bounded && Number.isFinite(left) && left <= MAX_TIMER_MS ? setTimeout(() => limit.abort(), Math.max(left, 0)) : void 0;
|
|
1618
|
+
const linked = anySignal([signal, limit.signal]);
|
|
1619
|
+
try {
|
|
1620
|
+
return await send(linked.signal);
|
|
1621
|
+
} catch (err) {
|
|
1622
|
+
throwIfAborted(signal);
|
|
1623
|
+
if (limit.signal.aborted && !(err instanceof SeclaiAPIStatusError)) {
|
|
1624
|
+
throw withCause(timedOut(), err);
|
|
1625
|
+
}
|
|
1626
|
+
throw err;
|
|
1627
|
+
} finally {
|
|
1628
|
+
clearTimeout(timer);
|
|
1629
|
+
linked.cleanup();
|
|
1630
|
+
}
|
|
1631
|
+
};
|
|
1632
|
+
const pollOpts = (s) => {
|
|
1633
|
+
const o = {};
|
|
1634
|
+
if (opts?.includeStepOutputs) o.query = { include_step_outputs: true };
|
|
1635
|
+
if (s) o.signal = s;
|
|
1636
|
+
return o;
|
|
1637
|
+
};
|
|
1638
|
+
const endsPoll = (r) => isTerminalStatus(r.status) || Boolean(opts?.returnOnResult && r.result_reported_at);
|
|
1639
|
+
const run = await abortable(false, (s) => {
|
|
1640
|
+
const startOpts = { json: body };
|
|
1641
|
+
if (s) startOpts.signal = s;
|
|
1642
|
+
return this.request("POST", `/agents/${agentId}/runs`, startOpts);
|
|
1643
|
+
});
|
|
1644
|
+
runId = run.id ?? run.run_id;
|
|
1537
1645
|
if (!runId) throw new SeclaiError("Agent run response did not contain an id.");
|
|
1538
|
-
|
|
1539
|
-
if (opts?.includeStepOutputs) {
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1646
|
+
current = run;
|
|
1647
|
+
if (opts?.includeStepOutputs && endsPoll(run) && !signal?.aborted) {
|
|
1648
|
+
try {
|
|
1649
|
+
current = await abortable(false, (s) => this.request("GET", `/agents/runs/${runId}`, pollOpts(s)));
|
|
1650
|
+
} catch (err) {
|
|
1651
|
+
if (!signal?.aborted) throw err;
|
|
1543
1652
|
}
|
|
1544
1653
|
}
|
|
1545
1654
|
while (true) {
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
if (Date.now() - startTime > timeout) {
|
|
1553
|
-
const state = current.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
|
|
1554
|
-
throw new SeclaiStreamingError(`Polling timed out after ${timeout}ms. ${state}`, runId, current);
|
|
1655
|
+
if (endsPoll(current)) return current;
|
|
1656
|
+
throwIfAborted(signal);
|
|
1657
|
+
const left = deadline - Date.now();
|
|
1658
|
+
if (left <= pollInterval) {
|
|
1659
|
+
if (left > 0) await sleep(left, signal);
|
|
1660
|
+
throw timedOut();
|
|
1555
1661
|
}
|
|
1556
|
-
await
|
|
1557
|
-
current = await this.
|
|
1558
|
-
runId,
|
|
1559
|
-
opts?.includeStepOutputs ? { includeStepOutputs: true } : void 0
|
|
1560
|
-
);
|
|
1662
|
+
await sleep(pollInterval, signal);
|
|
1663
|
+
current = await abortable(true, (s) => this.request("GET", `/agents/runs/${runId}`, pollOpts(s)));
|
|
1561
1664
|
}
|
|
1562
1665
|
}
|
|
1563
1666
|
// ═══════════════════════════════════════════════════════════════════════════
|