@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/dist/index.js CHANGED
@@ -496,47 +496,122 @@ function createSseParser(onMessage) {
496
496
  eventName = void 0;
497
497
  dataLines = [];
498
498
  }
499
+ function processLine(rawLine) {
500
+ let line = rawLine;
501
+ if (line.endsWith("\r")) line = line.slice(0, -1);
502
+ if (line === "") {
503
+ dispatch();
504
+ return;
505
+ }
506
+ if (line.startsWith(":")) return;
507
+ const colon = line.indexOf(":");
508
+ const field = colon === -1 ? line : line.slice(0, colon);
509
+ let value = colon === -1 ? "" : line.slice(colon + 1);
510
+ if (value.startsWith(" ")) value = value.slice(1);
511
+ if (field === "event") {
512
+ eventName = value;
513
+ } else if (field === "data") {
514
+ dataLines.push(value);
515
+ }
516
+ }
499
517
  function feed(textChunk) {
500
518
  buffer += textChunk;
501
519
  while (true) {
502
520
  const newlineIdx = buffer.indexOf("\n");
503
521
  if (newlineIdx === -1) return;
504
- let line = buffer.slice(0, newlineIdx);
522
+ const line = buffer.slice(0, newlineIdx);
505
523
  buffer = buffer.slice(newlineIdx + 1);
506
- if (line.endsWith("\r")) line = line.slice(0, -1);
507
- if (line === "") {
508
- dispatch();
509
- continue;
510
- }
511
- if (line.startsWith(":")) continue;
512
- const colon = line.indexOf(":");
513
- const field = colon === -1 ? line : line.slice(0, colon);
514
- let value = colon === -1 ? "" : line.slice(colon + 1);
515
- if (value.startsWith(" ")) value = value.slice(1);
516
- if (field === "event") {
517
- eventName = value;
518
- } else if (field === "data") {
519
- dataLines.push(value);
520
- }
524
+ processLine(line);
525
+ }
526
+ }
527
+ function end() {
528
+ if (buffer !== "") {
529
+ const line = buffer;
530
+ buffer = "";
531
+ processLine(line);
521
532
  }
533
+ dispatch();
534
+ }
535
+ function abandon() {
536
+ buffer = "";
537
+ dispatch();
522
538
  }
523
- return { feed, end: dispatch };
539
+ return { feed, end, abandon };
524
540
  }
525
541
  function anySignal(signals) {
526
542
  const present = signals.filter(Boolean);
527
- if (present.length === 0) return void 0;
528
- if (present.length === 1) return present[0];
543
+ if (present.length === 0) return { signal: void 0, cleanup: () => {
544
+ } };
545
+ if (present.length === 1) return { signal: present[0], cleanup: () => {
546
+ } };
529
547
  const controller = new AbortController();
530
- const onAbort = () => controller.abort();
548
+ const listening = [];
549
+ const cleanup = () => {
550
+ for (const [s, onAbort] of listening) s.removeEventListener("abort", onAbort);
551
+ listening.length = 0;
552
+ };
531
553
  for (const s of present) {
532
554
  if (s.aborted) {
533
- controller.abort();
555
+ cleanup();
556
+ controller.abort(s.reason);
534
557
  break;
535
558
  }
559
+ const onAbort = () => controller.abort(s.reason);
536
560
  s.addEventListener("abort", onAbort, { once: true });
561
+ listening.push([s, onAbort]);
537
562
  }
538
- return controller.signal;
563
+ return { signal: controller.signal, cleanup };
564
+ }
565
+ function abortReason(signal) {
566
+ return signal.reason !== void 0 ? signal.reason : new DOMException("This operation was aborted", "AbortError");
567
+ }
568
+ function throwIfAborted(signal) {
569
+ if (signal?.aborted) throw abortReason(signal);
570
+ }
571
+ var MAX_TIMER_MS = 2147483647;
572
+ function sleep(ms, signal) {
573
+ return new Promise((resolve, reject) => {
574
+ if (signal?.aborted) {
575
+ reject(abortReason(signal));
576
+ return;
577
+ }
578
+ let remaining = Math.max(ms, 0);
579
+ let timer;
580
+ const onAbort = () => {
581
+ clearTimeout(timer);
582
+ reject(abortReason(signal));
583
+ };
584
+ const arm = () => {
585
+ const step = Math.min(remaining, MAX_TIMER_MS);
586
+ remaining -= step;
587
+ timer = setTimeout(() => {
588
+ if (remaining > 0) return arm();
589
+ signal?.removeEventListener("abort", onAbort);
590
+ resolve();
591
+ }, step);
592
+ };
593
+ signal?.addEventListener("abort", onAbort, { once: true });
594
+ arm();
595
+ });
596
+ }
597
+ function isTerminalStatus(status) {
598
+ return status === "completed" || status === "failed" || status === "cancelled";
599
+ }
600
+ function isRunSnapshot(data) {
601
+ return data !== null && typeof data === "object" && !Array.isArray(data);
602
+ }
603
+ function streamTimeoutMessage(timeoutMs) {
604
+ return `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`;
605
+ }
606
+ function incompleteRunError(reason, run, runId) {
607
+ const state = run?.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
608
+ return new SeclaiStreamingError(`${reason} ${state}`, runId ?? run?.run_id, run);
539
609
  }
610
+ function withCause(error, cause) {
611
+ Object.defineProperty(error, "cause", { value: cause, enumerable: false, writable: true, configurable: true });
612
+ return error;
613
+ }
614
+ var streamTimeouts = /* @__PURE__ */ new WeakSet();
540
615
  function toBlob(file, mimeType) {
541
616
  if (file instanceof Blob) return file;
542
617
  const opts = mimeType ? { type: mimeType } : void 0;
@@ -1146,11 +1221,11 @@ var Seclai = class {
1146
1221
  /**
1147
1222
  * Run an agent in streaming mode (SSE) and wait for the final result.
1148
1223
  *
1149
- * Consumes the entire SSE stream and returns only the terminal `done` payload.
1150
- * For real-time event access, use {@link runStreamingAgent} instead. The body
1151
- * takes no `include_reasoning` or `include_commentary`, and one passed anyway
1152
- * is not sent: this method returns no `stream_reasoning` or
1153
- * `stream_commentary` events.
1224
+ * Reads the events of {@link runStreamingAgent} and returns the run from the
1225
+ * terminal `done` event. For real-time event access, use
1226
+ * {@link runStreamingAgent} instead. The body takes no `include_reasoning`
1227
+ * or `include_commentary`, and one passed anyway is not sent: this method
1228
+ * returns no `stream_reasoning` or `stream_commentary` events.
1154
1229
  *
1155
1230
  * A `result` event carries the run's answer in `output` once
1156
1231
  * `result_reported_at` is set, and can arrive while later steps still run.
@@ -1159,17 +1234,24 @@ var Seclai = class {
1159
1234
  * its `status` is not terminal and the run can still fail, so check
1160
1235
  * `result_reported_at`, not `status`.
1161
1236
  *
1162
- * If `timeoutMs` elapses, this throws {@link SeclaiStreamingError} with the
1163
- * latest snapshot in `run`: the `result` snapshot if one arrived, else the
1164
- * `init` snapshot. An abort from `signal` rethrows the abort error.
1237
+ * The latest snapshot is the `result` event's run if one arrived, else the
1238
+ * `init` event's run. When the server sends an `error`
1239
+ * event, this throws {@link SeclaiStreamingError} with the server's error
1240
+ * text in its message; when the server sends a `timeout` event, or
1241
+ * `timeoutMs` elapses (unless an HTTP error status arrives as it elapses),
1242
+ * it throws {@link SeclaiStreamingError} too. Each
1243
+ * carries the latest snapshot in `run`. An abort from `signal` rethrows the
1244
+ * abort error. Every way out of this method closes the response body.
1165
1245
  *
1166
1246
  * By default, a stream that ends before `done` returns the latest snapshot
1167
- * when its status is not `pending`, so the run returned may not have
1168
- * finished: check `status` and `result_reported_at`. A stream that breaks
1169
- * throws the fetch error. Pass `throwOnIncomplete: true` to throw
1170
- * {@link SeclaiStreamingError} with the snapshot in `run` in both cases
1171
- * instead; it is recommended, and becomes the default in the next major
1172
- * version.
1247
+ * when its status is not `pending`, so the run returned may
1248
+ * not have finished: check `status` and `result_reported_at`. A stream that
1249
+ * breaks throws the fetch error, unless a `done` event, or with
1250
+ * `returnOnResult` a `result` event, was read in full before it
1251
+ * broke. Pass `throwOnIncomplete: true` to throw
1252
+ * {@link SeclaiStreamingError} with the latest snapshot in `run` in both
1253
+ * cases instead; it is recommended, and becomes the default in the next
1254
+ * major version.
1173
1255
  *
1174
1256
  * @param agentId - Agent identifier.
1175
1257
  * @param body - Streaming run request payload, without `include_reasoning`
@@ -1178,9 +1260,14 @@ var Seclai = class {
1178
1260
  * @returns The run from the `done` event; with `returnOnResult`, the
1179
1261
  * `result` snapshot; without `throwOnIncomplete`, possibly an unfinished
1180
1262
  * snapshot (see above).
1181
- * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses, or, with
1182
- * `throwOnIncomplete`, the stream ends or breaks, before the run finished.
1183
- * Its `run` holds the latest snapshot.
1263
+ * @throws {@link SeclaiStreamingError} If the server sends an `error` or
1264
+ * `timeout` event, `timeoutMs` elapses (unless an HTTP error status
1265
+ * arrives as it elapses), or, with `throwOnIncomplete`, the
1266
+ * stream ends or breaks, before the run finished. Its `run` holds the
1267
+ * latest snapshot. On `timeoutMs`, when the request or read was cut off,
1268
+ * its `cause` is the error it ended with.
1269
+ * @throws {@link SeclaiAPIStatusError} For an HTTP error status, also one
1270
+ * that arrives as `timeoutMs` elapses.
1184
1271
  *
1185
1272
  * @example
1186
1273
  * ```ts
@@ -1200,120 +1287,56 @@ var Seclai = class {
1200
1287
  include_commentary: _commentary,
1201
1288
  ...runBody
1202
1289
  } = body;
1203
- const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
1204
- const authHdrs = await this.authHeaders();
1205
- const headers = this.requestHeaders([
1206
- this.defaultHeaders,
1207
- authHdrs,
1208
- { accept: "text/event-stream", "content-type": "application/json" }
1209
- ]);
1210
1290
  const timeoutMs = opts?.timeoutMs ?? 6e4;
1211
- const timeoutController = new AbortController();
1212
- let timedOut = false;
1213
- const timeoutId = setTimeout(() => {
1214
- timedOut = true;
1215
- timeoutController.abort();
1216
- }, timeoutMs);
1217
- const signal = anySignal([opts?.signal, timeoutController.signal]);
1218
- let lastSeen;
1291
+ const streamOpts = { timeoutMs };
1292
+ if (opts?.signal) streamOpts.signal = opts.signal;
1293
+ const progress = { jsonReply: false, reading: false, timedOut: false };
1294
+ let initial;
1219
1295
  let reported;
1296
+ const snapshot = () => reported ?? initial;
1220
1297
  try {
1221
- const init = { method: "POST", headers, body: JSON.stringify(runBody) };
1222
- if (signal) init.signal = signal;
1223
- const response = await this.fetcher(url, init);
1224
- const contentType = response.headers.get("content-type") ?? "";
1225
- const isJson = contentType.includes("application/json");
1226
- if (!response.ok) {
1227
- const responseText = await safeText(response);
1228
- if (response.status === 422) {
1229
- const validation = await safeJson(response);
1230
- throw new SeclaiAPIValidationError({
1231
- message: "Validation error",
1232
- statusCode: response.status,
1233
- method: "POST",
1234
- url: url.toString(),
1235
- responseText,
1236
- headers: new Headers(response.headers),
1237
- validationError: validation
1238
- });
1239
- }
1240
- throw new SeclaiAPIStatusError({
1241
- message: `Request failed with status ${response.status}`,
1242
- statusCode: response.status,
1243
- method: "POST",
1244
- url: url.toString(),
1245
- responseText,
1246
- headers: new Headers(response.headers)
1247
- });
1248
- }
1249
- if (isJson) {
1250
- const run2 = await response.json();
1251
- const status = run2.status;
1252
- const finished = status === "completed" || status === "failed" || status === "cancelled" || Boolean(opts?.returnOnResult && run2.result_reported_at);
1253
- if (opts?.throwOnIncomplete && !finished) {
1254
- const state2 = run2.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
1255
- throw new SeclaiStreamingError(`The server answered with JSON for a run that has not finished. ${state2}`, run2.run_id, run2);
1256
- }
1257
- return run2;
1258
- }
1259
- if (!response.body) {
1260
- throw new SeclaiConfigurationError(
1261
- "Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies."
1262
- );
1263
- }
1264
- const reader = response.body.getReader();
1265
- const decoder = new TextDecoder();
1266
- let final;
1267
- const parser = createSseParser((msg) => {
1268
- if (!msg.data) return;
1269
- if (msg.event === "init" || msg.event === "result" || msg.event === "done") {
1270
- try {
1271
- const parsed = JSON.parse(msg.data);
1272
- lastSeen = parsed;
1273
- if (msg.event === "result") reported = parsed;
1274
- if (msg.event === "done") final = parsed;
1275
- } catch {
1298
+ for await (const { event, data } of this.streamRunEvents(agentId, runBody, streamOpts, progress)) {
1299
+ if (event === "error" || event === "timeout") {
1300
+ const info = isRunSnapshot(data) ? data : {};
1301
+ const runId = typeof info.run_id === "string" ? info.run_id : void 0;
1302
+ if (event === "timeout") {
1303
+ throw incompleteRunError("The server timed out the streaming agent run before it finished.", snapshot(), runId);
1276
1304
  }
1305
+ const text = typeof info.error === "string" ? info.error : typeof data === "string" ? data : void 0;
1306
+ const reason = text ? `The streaming agent run failed on the server: ${text}${/[.!?]$/.test(text) ? "" : "."}` : "The streaming agent run failed on the server.";
1307
+ throw incompleteRunError(reason, snapshot(), runId);
1277
1308
  }
1278
- });
1279
- let readFailure;
1280
- try {
1281
- while (!final && !(opts?.returnOnResult && reported)) {
1282
- const { value, done } = await reader.read();
1283
- if (done) break;
1284
- if (value) parser.feed(decoder.decode(value, { stream: true }));
1309
+ if (!isRunSnapshot(data)) continue;
1310
+ if (event === "init") {
1311
+ initial = data;
1312
+ } else if (event === "result") {
1313
+ reported = data;
1314
+ if (opts?.returnOnResult) return data;
1315
+ } else if (event === "done") {
1316
+ const finished = isTerminalStatus(data.status) || Boolean(opts?.returnOnResult && data.result_reported_at);
1317
+ if (progress.jsonReply && opts?.throwOnIncomplete && !finished) {
1318
+ throw incompleteRunError("The server answered with JSON for a run that has not finished.", data);
1319
+ }
1320
+ return data;
1285
1321
  }
1286
- } catch (err) {
1287
- if (opts?.signal?.aborted || !opts?.throwOnIncomplete && !timedOut) throw err;
1288
- readFailure = err instanceof Error ? err.message : String(err);
1289
- }
1290
- parser.feed(decoder.decode());
1291
- parser.end();
1292
- if (final) return final;
1293
- if (opts?.returnOnResult && reported) {
1294
- reader.cancel().catch(() => {
1295
- });
1296
- return reported;
1297
- }
1298
- if (!opts?.throwOnIncomplete && !timedOut && lastSeen?.status && lastSeen.status !== "pending") {
1299
- return lastSeen;
1300
1322
  }
1301
- const run = reported ?? lastSeen;
1302
- const state = reported ? "A result had been reported; see `run`." : "No result had been reported.";
1303
- 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.";
1304
- throw new SeclaiStreamingError(`${reason} ${state}`, run?.run_id, run);
1305
1323
  } catch (err) {
1306
- if (timedOut && !opts?.signal?.aborted && !(err instanceof SeclaiStreamingError)) {
1307
- throw new SeclaiStreamingError(
1308
- `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`,
1309
- lastSeen?.run_id,
1310
- reported ?? lastSeen
1311
- );
1324
+ if (opts?.signal?.aborted) throw err;
1325
+ if (streamTimeouts.has(err)) {
1326
+ throw withCause(incompleteRunError(streamTimeoutMessage(timeoutMs), snapshot()), err.cause);
1327
+ }
1328
+ if (opts?.throwOnIncomplete && progress.reading && !(err instanceof SeclaiStreamingError)) {
1329
+ const message = err instanceof Error ? err.message : String(err);
1330
+ throw incompleteRunError(`Stream failed before the run finished: ${message}.`, snapshot());
1312
1331
  }
1313
1332
  throw err;
1314
- } finally {
1315
- clearTimeout(timeoutId);
1316
1333
  }
1334
+ if (progress.timedOut) throw incompleteRunError(streamTimeoutMessage(timeoutMs), snapshot());
1335
+ const latest = snapshot();
1336
+ if (!opts?.throwOnIncomplete && latest?.status && latest.status !== "pending") {
1337
+ return latest;
1338
+ }
1339
+ throw incompleteRunError("Stream ended before receiving a 'done' event.", snapshot());
1317
1340
  }
1318
1341
  /**
1319
1342
  * Run an agent in streaming mode and yield each SSE event as it arrives.
@@ -1323,6 +1346,13 @@ var Seclai = class {
1323
1346
  * `include_commentary` in `body` to also receive `stream_reasoning` or
1324
1347
  * `stream_commentary` events.
1325
1348
  *
1349
+ * The server ends the stream after `done`, after `error` (data
1350
+ * `{ run_id, error }`, the stream failed on the server) or after `timeout`
1351
+ * (data `{ run_id }`); all three are yielded like any other event. When the
1352
+ * server answers with plain JSON instead of SSE, its run is yielded as one
1353
+ * `done` event. Leaving the loop early (`break`, `return` or a throw)
1354
+ * closes the response body.
1355
+ *
1326
1356
  * From `apiVersion` `2026-11-14`, an agent whose definition fails to validate
1327
1357
  * is refused with HTTP 409 ({@link SeclaiAPIStatusError}) before any event,
1328
1358
  * and no run is created.
@@ -1331,6 +1361,11 @@ var Seclai = class {
1331
1361
  * @param body - Streaming run request payload.
1332
1362
  * @param opts - Timeout and abort signal options.
1333
1363
  * @yields {@link AgentRunEvent} for each SSE message.
1364
+ * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses, with the
1365
+ * error the request or read ended with as its `cause`. An HTTP error
1366
+ * status that arrives as it elapses is thrown as itself. An event read
1367
+ * in full before the stream broke or timed out is yielded first, unless
1368
+ * `signal` was aborted.
1334
1369
  *
1335
1370
  * @example
1336
1371
  * ```ts
@@ -1346,6 +1381,14 @@ var Seclai = class {
1346
1381
  * ```
1347
1382
  */
1348
1383
  async *runStreamingAgent(agentId, body, opts) {
1384
+ yield* this.streamRunEvents(agentId, body, opts);
1385
+ }
1386
+ /**
1387
+ * The stream behind {@link runStreamingAgent} and
1388
+ * {@link runStreamingAgentAndWait}: one request, reader and parser for both.
1389
+ * `progress` tells the wait helper what the events alone do not.
1390
+ */
1391
+ async *streamRunEvents(agentId, body, opts, progress) {
1349
1392
  const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
1350
1393
  const authHdrs = await this.authHeaders();
1351
1394
  const headers = this.requestHeaders([
@@ -1358,9 +1401,11 @@ var Seclai = class {
1358
1401
  let timedOut = false;
1359
1402
  const timeoutId = setTimeout(() => {
1360
1403
  timedOut = true;
1404
+ if (progress) progress.timedOut = true;
1361
1405
  timeoutController.abort();
1362
1406
  }, timeoutMs);
1363
- const signal = anySignal([opts?.signal, timeoutController.signal]);
1407
+ const { signal, cleanup } = anySignal([opts?.signal, timeoutController.signal]);
1408
+ let reader;
1364
1409
  try {
1365
1410
  const init = { method: "POST", headers, body: JSON.stringify(body) };
1366
1411
  if (signal) init.signal = signal;
@@ -1392,15 +1437,17 @@ var Seclai = class {
1392
1437
  }
1393
1438
  if (isJson) {
1394
1439
  const data = await response.json();
1440
+ if (progress) progress.jsonReply = true;
1395
1441
  yield { event: "done", data };
1396
1442
  return;
1397
1443
  }
1398
1444
  if (!response.body) {
1399
1445
  throw new SeclaiConfigurationError(
1400
- "Streaming response body is not available in this environment."
1446
+ "Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies."
1401
1447
  );
1402
1448
  }
1403
- const reader = response.body.getReader();
1449
+ reader = response.body.getReader();
1450
+ if (progress) progress.reading = true;
1404
1451
  const decoder = new TextDecoder();
1405
1452
  const events = [];
1406
1453
  const parser = createSseParser((msg) => {
@@ -1414,26 +1461,40 @@ var Seclai = class {
1414
1461
  events.push({ event: msg.event ?? "message", data });
1415
1462
  });
1416
1463
  while (true) {
1417
- const { value, done } = await reader.read();
1464
+ let chunk;
1465
+ try {
1466
+ chunk = await reader.read();
1467
+ } catch (err) {
1468
+ if (!opts?.signal?.aborted) {
1469
+ parser.feed(decoder.decode());
1470
+ parser.abandon();
1471
+ while (events.length > 0) yield events.shift();
1472
+ }
1473
+ throw err;
1474
+ }
1475
+ const { value, done } = chunk;
1418
1476
  if (value) parser.feed(decoder.decode(value, { stream: true }));
1477
+ if (done) {
1478
+ parser.feed(decoder.decode());
1479
+ parser.end();
1480
+ }
1419
1481
  while (events.length > 0) {
1420
1482
  yield events.shift();
1421
1483
  }
1422
1484
  if (done) break;
1423
1485
  }
1424
- parser.end();
1425
- while (events.length > 0) {
1426
- yield events.shift();
1427
- }
1428
1486
  } catch (err) {
1429
- if (timedOut) {
1430
- throw new SeclaiStreamingError(
1431
- `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`
1432
- );
1487
+ if (timedOut && !(err instanceof SeclaiAPIStatusError)) {
1488
+ const timeout = withCause(new SeclaiStreamingError(streamTimeoutMessage(timeoutMs)), err);
1489
+ streamTimeouts.add(timeout);
1490
+ throw timeout;
1433
1491
  }
1434
1492
  throw err;
1435
1493
  } finally {
1436
1494
  clearTimeout(timeoutId);
1495
+ cleanup();
1496
+ reader?.cancel().catch(() => {
1497
+ });
1437
1498
  }
1438
1499
  }
1439
1500
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1448,22 +1509,33 @@ var Seclai = class {
1448
1509
  * `result_reported_at` is set, `output` holds the answer. Pass
1449
1510
  * `returnOnResult: true` to return as soon as a run has it set, the run
1450
1511
  * `runAgent()` returns included. With `includeStepOutputs`, when that run
1451
- * would end the poll and `signal` is not aborted, it is fetched again at
1452
- * once for its step outputs.
1512
+ * would end the poll, it is fetched again at once for its step outputs.
1453
1513
  * Such a run may still be in progress: its `status` is not terminal and the
1454
1514
  * run can still fail, so check `result_reported_at`, not `status`.
1455
1515
  *
1456
1516
  * When `timeoutMs` elapses first, this throws {@link SeclaiStreamingError}
1457
- * with the latest run it has (the `runAgent()` response if no poll ran) in
1458
- * `run`. If that run has `result_reported_at`
1459
- * set, its `output` is the answer.
1460
- *
1461
- * `signal` is checked at the top of each poll, after the check for a run
1462
- * that ends the poll. A run that has ended the poll by then, whether the
1463
- * start run or a polled one, is returned even after an abort; the start run
1464
- * then comes back without step outputs, even when `includeStepOutputs` is
1465
- * set. Otherwise an abort throws `SeclaiError("Polling aborted.")`, which is
1466
- * not an `AbortError` and does not carry `signal.reason`.
1517
+ * with the latest run it has (the `runAgent()` response if no poll answered)
1518
+ * in `run`. If that run has `result_reported_at` set, its `output` is the
1519
+ * answer. No poll is sent at or after the deadline: a wait between polls that
1520
+ * reaches it ends the call with the timeout, so a `timeoutMs` no greater than
1521
+ * `pollIntervalMs` sends no poll. With a `fetch` that honours `signal`, a
1522
+ * poll still in flight at the deadline is aborted and the timeout is thrown.
1523
+ * Any error but an HTTP error status that a poll ends with once the deadline
1524
+ * has passed is the timeout's `cause`; an HTTP error status a poll gets after
1525
+ * the deadline is thrown as itself, and a caller abort throws `signal.reason`
1526
+ * instead. `timeoutMs` does not cut off the start request (the server may
1527
+ * already have created the run) or the fetch for an ended start run's step
1528
+ * outputs; only `signal` does. A request is not cut off while more than
1529
+ * 2^31-1 ms remain.
1530
+ *
1531
+ * `signal` is passed to every request and to the wait between polls. An
1532
+ * abort throws `signal.reason`, as `signal.throwIfAborted()` does (by
1533
+ * default an `AbortError`), or an `AbortError` for a signal that has no
1534
+ * `reason`: an already-aborted signal starts no run. A run
1535
+ * that has ended the poll is returned even after an abort. When the start
1536
+ * run has ended it and `includeStepOutputs` is set, an abort during the
1537
+ * fetch for its step outputs (with a `fetch` that honours `signal`) returns
1538
+ * the start run without step outputs.
1467
1539
  *
1468
1540
  * @param agentId - Agent identifier.
1469
1541
  * @param body - Run request payload.
@@ -1472,41 +1544,72 @@ var Seclai = class {
1472
1544
  * with `result_reported_at` set.
1473
1545
  * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run
1474
1546
  * finished. Its `run` holds the latest run it has (the `runAgent()`
1475
- * response if no poll ran).
1476
- * @throws {@link SeclaiError} `"Polling aborted."` If `signal` is aborted and,
1477
- * at the next poll's check, the run has not ended the poll. It is not an
1478
- * `AbortError` and does not carry `signal.reason`.
1547
+ * response if no poll answered), and its `cause` the error a poll ended
1548
+ * with at the deadline, if one did (a caller abort throws `signal.reason`
1549
+ * instead).
1550
+ * @throws `signal.reason` If `signal` is aborted before the run has ended
1551
+ * the poll.
1479
1552
  */
1480
1553
  async runAgentAndPoll(agentId, body, opts) {
1481
1554
  const pollInterval = opts?.pollIntervalMs ?? 2e3;
1482
1555
  const timeout = opts?.timeoutMs ?? 3e5;
1483
- const startTime = Date.now();
1484
- const run = await this.runAgent(agentId, body);
1485
- const runId = run.id ?? run.run_id;
1556
+ const signal = opts?.signal;
1557
+ const deadline = Date.now() + timeout;
1558
+ throwIfAborted(signal);
1559
+ let current;
1560
+ let runId;
1561
+ const timedOut = () => incompleteRunError(`Polling timed out after ${timeout}ms.`, current, runId);
1562
+ const abortable = async (bounded, send) => {
1563
+ const limit = new AbortController();
1564
+ const left = deadline - Date.now();
1565
+ if (bounded && left <= 0) throw timedOut();
1566
+ const timer = bounded && Number.isFinite(left) && left <= MAX_TIMER_MS ? setTimeout(() => limit.abort(), Math.max(left, 0)) : void 0;
1567
+ const linked = anySignal([signal, limit.signal]);
1568
+ try {
1569
+ return await send(linked.signal);
1570
+ } catch (err) {
1571
+ throwIfAborted(signal);
1572
+ if (limit.signal.aborted && !(err instanceof SeclaiAPIStatusError)) {
1573
+ throw withCause(timedOut(), err);
1574
+ }
1575
+ throw err;
1576
+ } finally {
1577
+ clearTimeout(timer);
1578
+ linked.cleanup();
1579
+ }
1580
+ };
1581
+ const pollOpts = (s) => {
1582
+ const o = {};
1583
+ if (opts?.includeStepOutputs) o.query = { include_step_outputs: true };
1584
+ if (s) o.signal = s;
1585
+ return o;
1586
+ };
1587
+ const endsPoll = (r) => isTerminalStatus(r.status) || Boolean(opts?.returnOnResult && r.result_reported_at);
1588
+ const run = await abortable(false, (s) => {
1589
+ const startOpts = { json: body };
1590
+ if (s) startOpts.signal = s;
1591
+ return this.request("POST", `/agents/${agentId}/runs`, startOpts);
1592
+ });
1593
+ runId = run.id ?? run.run_id;
1486
1594
  if (!runId) throw new SeclaiError("Agent run response did not contain an id.");
1487
- let current = run;
1488
- if (opts?.includeStepOutputs) {
1489
- const status = run.status;
1490
- if (status === "completed" || status === "failed" || status === "cancelled" || opts.returnOnResult && run.result_reported_at) {
1491
- if (!opts.signal?.aborted) current = await this.getAgentRun(runId, { includeStepOutputs: true });
1595
+ current = run;
1596
+ if (opts?.includeStepOutputs && endsPoll(run) && !signal?.aborted) {
1597
+ try {
1598
+ current = await abortable(false, (s) => this.request("GET", `/agents/runs/${runId}`, pollOpts(s)));
1599
+ } catch (err) {
1600
+ if (!signal?.aborted) throw err;
1492
1601
  }
1493
1602
  }
1494
1603
  while (true) {
1495
- const status = current.status;
1496
- if (status === "completed" || status === "failed" || status === "cancelled") {
1497
- return current;
1498
- }
1499
- if (opts?.returnOnResult && current.result_reported_at) return current;
1500
- if (opts?.signal?.aborted) throw new SeclaiError("Polling aborted.");
1501
- if (Date.now() - startTime > timeout) {
1502
- const state = current.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
1503
- throw new SeclaiStreamingError(`Polling timed out after ${timeout}ms. ${state}`, runId, current);
1604
+ if (endsPoll(current)) return current;
1605
+ throwIfAborted(signal);
1606
+ const left = deadline - Date.now();
1607
+ if (left <= pollInterval) {
1608
+ if (left > 0) await sleep(left, signal);
1609
+ throw timedOut();
1504
1610
  }
1505
- await new Promise((r) => setTimeout(r, pollInterval));
1506
- current = await this.getAgentRun(
1507
- runId,
1508
- opts?.includeStepOutputs ? { includeStepOutputs: true } : void 0
1509
- );
1611
+ await sleep(pollInterval, signal);
1612
+ current = await abortable(true, (s) => this.request("GET", `/agents/runs/${runId}`, pollOpts(s)));
1510
1613
  }
1511
1614
  }
1512
1615
  // ═══════════════════════════════════════════════════════════════════════════