@seclai/sdk 1.9.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.cjs CHANGED
@@ -67,10 +67,14 @@ var SeclaiApiVersion = {
67
67
  V2026_10_28: "2026-10-28",
68
68
  V2026_11_02: "2026-11-02",
69
69
  V2026_11_04: "2026-11-04",
70
+ V2026_11_08: "2026-11-08",
71
+ V2026_11_09: "2026-11-09",
72
+ V2026_11_14: "2026-11-14",
73
+ V2026_11_19: "2026-11-19",
70
74
  /** Baseline applied to an unpinned, header-less caller. */
71
75
  Default: "2026-07-01",
72
76
  /** Newest version known to this SDK release. May lag the server. */
73
- Latest: "2026-11-04"
77
+ Latest: "2026-11-19"
74
78
  };
75
79
  var KNOWN_API_VERSIONS = Object.entries(SeclaiApiVersion).filter(([k]) => k.startsWith("V")).map(([, v]) => v);
76
80
 
@@ -96,6 +100,14 @@ var SeclaiAPIStatusError = class extends SeclaiError {
96
100
  url;
97
101
  /** Best-effort response body text (if available). */
98
102
  responseText;
103
+ /**
104
+ * Headers of the error response, such as `Retry-After` on a 503, or
105
+ * `Content-Range` on a 416 from a ranged `downloadAgentRunAttachment()`, whose
106
+ * value ends in `/<size>`, the file's size in bytes. Empty when the response
107
+ * headers are unknown. In a browser, only the headers the server's CORS policy
108
+ * exposes are present.
109
+ */
110
+ headers;
99
111
  constructor(opts) {
100
112
  super(opts.message);
101
113
  this.name = "SeclaiAPIStatusError";
@@ -103,6 +115,7 @@ var SeclaiAPIStatusError = class extends SeclaiError {
103
115
  this.method = opts.method;
104
116
  this.url = opts.url;
105
117
  this.responseText = opts.responseText;
118
+ this.headers = opts.headers ?? new Headers();
106
119
  }
107
120
  };
108
121
  var SeclaiAPIValidationError = class extends SeclaiAPIStatusError {
@@ -480,6 +493,34 @@ function mergeHeaders(...layers) {
480
493
  function headerKey(headers, name) {
481
494
  return Object.keys(headers ?? {}).filter((key) => key.toLowerCase() === name).pop();
482
495
  }
496
+ function byteRangeHeader(start, end, suffix) {
497
+ const hasStart = start !== void 0 && start !== null;
498
+ const hasEnd = end !== void 0 && end !== null;
499
+ const hasSuffix = suffix !== void 0 && suffix !== null;
500
+ if (!hasStart && !hasEnd && !hasSuffix) return void 0;
501
+ const fail = (why) => {
502
+ throw new SeclaiConfigurationError(`Invalid byte range: ${why}`);
503
+ };
504
+ if (hasSuffix) {
505
+ if (hasStart || hasEnd) fail("rangeSuffix cannot be combined with rangeStart or rangeEnd.");
506
+ if (!Number.isSafeInteger(suffix) || suffix < 1) {
507
+ fail(`rangeSuffix must be a whole number of at least 1, got ${String(suffix)}.`);
508
+ }
509
+ return `bytes=-${suffix}`;
510
+ }
511
+ if (!hasStart) fail("rangeEnd requires rangeStart; use rangeSuffix for the last bytes of the file.");
512
+ if (!Number.isSafeInteger(start) || start < 0) {
513
+ fail(`rangeStart must be a whole number of at least 0, got ${String(start)}.`);
514
+ }
515
+ if (!hasEnd) return `bytes=${start}-`;
516
+ if (!Number.isSafeInteger(end) || end < 0) {
517
+ fail(`rangeEnd must be a whole number of at least 0, got ${String(end)}.`);
518
+ }
519
+ if (end < start) {
520
+ fail(`rangeEnd (${end}) must not be less than rangeStart (${start}).`);
521
+ }
522
+ return `bytes=${start}-${end}`;
523
+ }
483
524
  async function safeText(response) {
484
525
  try {
485
526
  return await response.clone().text();
@@ -506,47 +547,122 @@ function createSseParser(onMessage) {
506
547
  eventName = void 0;
507
548
  dataLines = [];
508
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
+ }
509
568
  function feed(textChunk) {
510
569
  buffer += textChunk;
511
570
  while (true) {
512
571
  const newlineIdx = buffer.indexOf("\n");
513
572
  if (newlineIdx === -1) return;
514
- let line = buffer.slice(0, newlineIdx);
573
+ const line = buffer.slice(0, newlineIdx);
515
574
  buffer = buffer.slice(newlineIdx + 1);
516
- if (line.endsWith("\r")) line = line.slice(0, -1);
517
- if (line === "") {
518
- dispatch();
519
- continue;
520
- }
521
- if (line.startsWith(":")) continue;
522
- const colon = line.indexOf(":");
523
- const field = colon === -1 ? line : line.slice(0, colon);
524
- let value = colon === -1 ? "" : line.slice(colon + 1);
525
- if (value.startsWith(" ")) value = value.slice(1);
526
- if (field === "event") {
527
- eventName = value;
528
- } else if (field === "data") {
529
- dataLines.push(value);
530
- }
575
+ processLine(line);
576
+ }
577
+ }
578
+ function end() {
579
+ if (buffer !== "") {
580
+ const line = buffer;
581
+ buffer = "";
582
+ processLine(line);
531
583
  }
584
+ dispatch();
585
+ }
586
+ function abandon() {
587
+ buffer = "";
588
+ dispatch();
532
589
  }
533
- return { feed, end: dispatch };
590
+ return { feed, end, abandon };
534
591
  }
535
592
  function anySignal(signals) {
536
593
  const present = signals.filter(Boolean);
537
- if (present.length === 0) return void 0;
538
- if (present.length === 1) return present[0];
594
+ if (present.length === 0) return { signal: void 0, cleanup: () => {
595
+ } };
596
+ if (present.length === 1) return { signal: present[0], cleanup: () => {
597
+ } };
539
598
  const controller = new AbortController();
540
- const onAbort = () => controller.abort();
599
+ const listening = [];
600
+ const cleanup = () => {
601
+ for (const [s, onAbort] of listening) s.removeEventListener("abort", onAbort);
602
+ listening.length = 0;
603
+ };
541
604
  for (const s of present) {
542
605
  if (s.aborted) {
543
- controller.abort();
606
+ cleanup();
607
+ controller.abort(s.reason);
544
608
  break;
545
609
  }
610
+ const onAbort = () => controller.abort(s.reason);
546
611
  s.addEventListener("abort", onAbort, { once: true });
612
+ listening.push([s, onAbort]);
547
613
  }
548
- 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);
549
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);
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();
550
666
  function toBlob(file, mimeType) {
551
667
  if (file instanceof Blob) return file;
552
668
  const opts = mimeType ? { type: mimeType } : void 0;
@@ -746,6 +862,7 @@ var Seclai = class {
746
862
  method,
747
863
  url: url.toString(),
748
864
  responseText,
865
+ headers: new Headers(response.headers),
749
866
  validationError: validation
750
867
  });
751
868
  }
@@ -754,7 +871,8 @@ var Seclai = class {
754
871
  statusCode: response.status,
755
872
  method,
756
873
  url: url.toString(),
757
- responseText
874
+ responseText,
875
+ headers: new Headers(response.headers)
758
876
  });
759
877
  }
760
878
  if (!response.body) return null;
@@ -801,6 +919,7 @@ var Seclai = class {
801
919
  method,
802
920
  url: url.toString(),
803
921
  responseText,
922
+ headers: new Headers(response.headers),
804
923
  validationError: validation
805
924
  });
806
925
  }
@@ -809,7 +928,8 @@ var Seclai = class {
809
928
  statusCode: response.status,
810
929
  method,
811
930
  url: url.toString(),
812
- responseText
931
+ responseText,
932
+ headers: new Headers(response.headers)
813
933
  });
814
934
  }
815
935
  return response;
@@ -840,6 +960,7 @@ var Seclai = class {
840
960
  method: "POST",
841
961
  url: url.toString(),
842
962
  responseText,
963
+ headers: new Headers(response.headers),
843
964
  validationError: validation
844
965
  });
845
966
  }
@@ -848,7 +969,8 @@ var Seclai = class {
848
969
  statusCode: response.status,
849
970
  method: "POST",
850
971
  url: url.toString(),
851
- responseText
972
+ responseText,
973
+ headers: new Headers(response.headers)
852
974
  });
853
975
  }
854
976
  return await response.json();
@@ -914,6 +1036,10 @@ var Seclai = class {
914
1036
  /**
915
1037
  * List the agent gallery: example agents to start from.
916
1038
  *
1039
+ * From `apiVersion` `2026-11-09`, `query` describes what the agent should do
1040
+ * and entries come back ranked by how well they match it, best first. Before
1041
+ * it, only entries containing every word of `query` are returned.
1042
+ *
917
1043
  * Pass an entry's `key` as `agent_template` to {@link createAgent}, with
918
1044
  * `resource_bindings` for the resources it needs.
919
1045
  *
@@ -1067,6 +1193,11 @@ var Seclai = class {
1067
1193
  /**
1068
1194
  * Start an agent run.
1069
1195
  *
1196
+ * From `apiVersion` `2026-11-14`, an agent whose definition fails to validate
1197
+ * is refused with HTTP 409 ({@link SeclaiAPIStatusError}) and no run is
1198
+ * created; earlier versions return the run, already failed with the
1199
+ * validation error as its cause.
1200
+ *
1070
1201
  * @param agentId - Agent identifier.
1071
1202
  * @param body - Run request payload (`input`, `metadata`, `priority`, etc.).
1072
1203
  * @returns The created agent run.
@@ -1120,14 +1251,17 @@ var Seclai = class {
1120
1251
  await this.cancelAgentRun(runId);
1121
1252
  }
1122
1253
  /**
1123
- * Cancel a running agent run.
1254
+ * Cancel an agent run that has not ended: `queued`, `pending`, `processing`,
1255
+ * `waiting_human` or `waiting_scheduled`.
1124
1256
  *
1125
1257
  * Cancellation is `DELETE` on the run resource — the API exposes no
1126
1258
  * `POST .../cancel` route, and no operation that deletes a run. Rejected when
1127
- * the run has already reached a terminal state.
1259
+ * the run has already ended (`completed`, `failed` or `cancelled`). From
1260
+ * `apiVersion` `2026-11-08` the cancelled run ends with status `cancelled`;
1261
+ * on earlier versions it ends `failed`.
1128
1262
  *
1129
1263
  * @param runId - Run identifier.
1130
- * @returns Updated run (with cancelled status).
1264
+ * @returns The updated run.
1131
1265
  */
1132
1266
  async cancelAgentRun(runId) {
1133
1267
  return await this.request("DELETE", `/agents/runs/${runId}`);
@@ -1138,10 +1272,11 @@ var Seclai = class {
1138
1272
  /**
1139
1273
  * Run an agent in streaming mode (SSE) and wait for the final result.
1140
1274
  *
1141
- * Consumes the entire SSE stream and returns only the terminal `done` payload.
1142
- * For real-time event access, use {@link runStreamingAgent} instead. The body
1143
- * takes no `include_reasoning`, and one passed anyway is not sent: this method
1144
- * returns no `stream_reasoning` 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.
1145
1280
  *
1146
1281
  * A `result` event carries the run's answer in `output` once
1147
1282
  * `result_reported_at` is set, and can arrive while later steps still run.
@@ -1150,27 +1285,40 @@ var Seclai = class {
1150
1285
  * its `status` is not terminal and the run can still fail, so check
1151
1286
  * `result_reported_at`, not `status`.
1152
1287
  *
1153
- * If `timeoutMs` elapses, this throws {@link SeclaiStreamingError} with the
1154
- * latest snapshot in `run`: the `result` snapshot if one arrived, else the
1155
- * `init` snapshot. An abort from `signal` rethrows the abort error.
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.
1156
1296
  *
1157
1297
  * By default, a stream that ends before `done` returns the latest snapshot
1158
- * when its status is not `pending`, so the run returned may not have
1159
- * finished: check `status` and `result_reported_at`. A stream that breaks
1160
- * throws the fetch error. Pass `throwOnIncomplete: true` to throw
1161
- * {@link SeclaiStreamingError} with the snapshot in `run` in both cases
1162
- * instead; it is recommended, and becomes the default in the next major
1163
- * version.
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.
1164
1306
  *
1165
1307
  * @param agentId - Agent identifier.
1166
- * @param body - Streaming run request payload, without `include_reasoning`.
1308
+ * @param body - Streaming run request payload, without `include_reasoning`
1309
+ * or `include_commentary`.
1167
1310
  * @param opts - Timeout, abort signal and `returnOnResult` options.
1168
1311
  * @returns The run from the `done` event; with `returnOnResult`, the
1169
1312
  * `result` snapshot; without `throwOnIncomplete`, possibly an unfinished
1170
1313
  * snapshot (see above).
1171
- * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses, or, with
1172
- * `throwOnIncomplete`, the stream ends or breaks, before the run finished.
1173
- * Its `run` holds the latest snapshot.
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.
1174
1322
  *
1175
1323
  * @example
1176
1324
  * ```ts
@@ -1185,130 +1333,90 @@ var Seclai = class {
1185
1333
  * ```
1186
1334
  */
1187
1335
  async runStreamingAgentAndWait(agentId, body, opts) {
1188
- const { include_reasoning: _ignored, ...runBody } = body;
1189
- const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
1190
- const authHdrs = await this.authHeaders();
1191
- const headers = this.requestHeaders([
1192
- this.defaultHeaders,
1193
- authHdrs,
1194
- { accept: "text/event-stream", "content-type": "application/json" }
1195
- ]);
1336
+ const {
1337
+ include_reasoning: _reasoning,
1338
+ include_commentary: _commentary,
1339
+ ...runBody
1340
+ } = body;
1196
1341
  const timeoutMs = opts?.timeoutMs ?? 6e4;
1197
- const timeoutController = new AbortController();
1198
- let timedOut = false;
1199
- const timeoutId = setTimeout(() => {
1200
- timedOut = true;
1201
- timeoutController.abort();
1202
- }, timeoutMs);
1203
- const signal = anySignal([opts?.signal, timeoutController.signal]);
1204
- 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;
1205
1346
  let reported;
1347
+ const snapshot = () => reported ?? initial;
1206
1348
  try {
1207
- const init = { method: "POST", headers, body: JSON.stringify(runBody) };
1208
- if (signal) init.signal = signal;
1209
- const response = await this.fetcher(url, init);
1210
- const contentType = response.headers.get("content-type") ?? "";
1211
- const isJson = contentType.includes("application/json");
1212
- if (!response.ok) {
1213
- const responseText = await safeText(response);
1214
- if (response.status === 422) {
1215
- const validation = await safeJson(response);
1216
- throw new SeclaiAPIValidationError({
1217
- message: "Validation error",
1218
- statusCode: response.status,
1219
- method: "POST",
1220
- url: url.toString(),
1221
- responseText,
1222
- validationError: validation
1223
- });
1224
- }
1225
- throw new SeclaiAPIStatusError({
1226
- message: `Request failed with status ${response.status}`,
1227
- statusCode: response.status,
1228
- method: "POST",
1229
- url: url.toString(),
1230
- responseText
1231
- });
1232
- }
1233
- if (isJson) {
1234
- const run2 = await response.json();
1235
- const status = run2.status;
1236
- const finished = status === "completed" || status === "failed" || status === "cancelled" || Boolean(opts?.returnOnResult && run2.result_reported_at);
1237
- if (opts?.throwOnIncomplete && !finished) {
1238
- const state2 = run2.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
1239
- throw new SeclaiStreamingError(`The server answered with JSON for a run that has not finished. ${state2}`, run2.run_id, run2);
1240
- }
1241
- return run2;
1242
- }
1243
- if (!response.body) {
1244
- throw new SeclaiConfigurationError(
1245
- "Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies."
1246
- );
1247
- }
1248
- const reader = response.body.getReader();
1249
- const decoder = new TextDecoder();
1250
- let final;
1251
- const parser = createSseParser((msg) => {
1252
- if (!msg.data) return;
1253
- if (msg.event === "init" || msg.event === "result" || msg.event === "done") {
1254
- try {
1255
- const parsed = JSON.parse(msg.data);
1256
- lastSeen = parsed;
1257
- if (msg.event === "result") reported = parsed;
1258
- if (msg.event === "done") final = parsed;
1259
- } 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);
1260
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);
1261
1359
  }
1262
- });
1263
- let readFailure;
1264
- try {
1265
- while (!final && !(opts?.returnOnResult && reported)) {
1266
- const { value, done } = await reader.read();
1267
- if (done) break;
1268
- if (value) parser.feed(decoder.decode(value, { stream: true }));
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;
1269
1372
  }
1270
- } catch (err) {
1271
- if (opts?.signal?.aborted || !opts?.throwOnIncomplete && !timedOut) throw err;
1272
- readFailure = err instanceof Error ? err.message : String(err);
1273
- }
1274
- parser.feed(decoder.decode());
1275
- parser.end();
1276
- if (final) return final;
1277
- if (opts?.returnOnResult && reported) {
1278
- reader.cancel().catch(() => {
1279
- });
1280
- return reported;
1281
1373
  }
1282
- if (!opts?.throwOnIncomplete && !timedOut && lastSeen?.status && lastSeen.status !== "pending") {
1283
- return lastSeen;
1284
- }
1285
- const run = reported ?? lastSeen;
1286
- const state = reported ? "A result had been reported; see `run`." : "No result had been reported.";
1287
- 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.";
1288
- throw new SeclaiStreamingError(`${reason} ${state}`, run?.run_id, run);
1289
1374
  } catch (err) {
1290
- if (timedOut && !opts?.signal?.aborted && !(err instanceof SeclaiStreamingError)) {
1291
- throw new SeclaiStreamingError(
1292
- `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`,
1293
- lastSeen?.run_id,
1294
- reported ?? lastSeen
1295
- );
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());
1296
1382
  }
1297
1383
  throw err;
1298
- } finally {
1299
- clearTimeout(timeoutId);
1300
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());
1301
1391
  }
1302
1392
  /**
1303
1393
  * Run an agent in streaming mode and yield each SSE event as it arrives.
1304
1394
  *
1305
1395
  * This is an `AsyncGenerator` suitable for real-time UIs that want to render
1306
- * step progress as it happens.
1396
+ * step progress as it happens. Set `include_reasoning` or
1397
+ * `include_commentary` in `body` to also receive `stream_reasoning` or
1398
+ * `stream_commentary` events.
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
+ *
1407
+ * From `apiVersion` `2026-11-14`, an agent whose definition fails to validate
1408
+ * is refused with HTTP 409 ({@link SeclaiAPIStatusError}) before any event,
1409
+ * and no run is created.
1307
1410
  *
1308
1411
  * @param agentId - Agent identifier.
1309
1412
  * @param body - Streaming run request payload.
1310
1413
  * @param opts - Timeout and abort signal options.
1311
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.
1312
1420
  *
1313
1421
  * @example
1314
1422
  * ```ts
@@ -1324,6 +1432,14 @@ var Seclai = class {
1324
1432
  * ```
1325
1433
  */
1326
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) {
1327
1443
  const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
1328
1444
  const authHdrs = await this.authHeaders();
1329
1445
  const headers = this.requestHeaders([
@@ -1336,9 +1452,11 @@ var Seclai = class {
1336
1452
  let timedOut = false;
1337
1453
  const timeoutId = setTimeout(() => {
1338
1454
  timedOut = true;
1455
+ if (progress) progress.timedOut = true;
1339
1456
  timeoutController.abort();
1340
1457
  }, timeoutMs);
1341
- const signal = anySignal([opts?.signal, timeoutController.signal]);
1458
+ const { signal, cleanup } = anySignal([opts?.signal, timeoutController.signal]);
1459
+ let reader;
1342
1460
  try {
1343
1461
  const init = { method: "POST", headers, body: JSON.stringify(body) };
1344
1462
  if (signal) init.signal = signal;
@@ -1355,6 +1473,7 @@ var Seclai = class {
1355
1473
  method: "POST",
1356
1474
  url: url.toString(),
1357
1475
  responseText,
1476
+ headers: new Headers(response.headers),
1358
1477
  validationError: validation
1359
1478
  });
1360
1479
  }
@@ -1363,20 +1482,23 @@ var Seclai = class {
1363
1482
  statusCode: response.status,
1364
1483
  method: "POST",
1365
1484
  url: url.toString(),
1366
- responseText
1485
+ responseText,
1486
+ headers: new Headers(response.headers)
1367
1487
  });
1368
1488
  }
1369
1489
  if (isJson) {
1370
1490
  const data = await response.json();
1491
+ if (progress) progress.jsonReply = true;
1371
1492
  yield { event: "done", data };
1372
1493
  return;
1373
1494
  }
1374
1495
  if (!response.body) {
1375
1496
  throw new SeclaiConfigurationError(
1376
- "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."
1377
1498
  );
1378
1499
  }
1379
- const reader = response.body.getReader();
1500
+ reader = response.body.getReader();
1501
+ if (progress) progress.reading = true;
1380
1502
  const decoder = new TextDecoder();
1381
1503
  const events = [];
1382
1504
  const parser = createSseParser((msg) => {
@@ -1390,26 +1512,40 @@ var Seclai = class {
1390
1512
  events.push({ event: msg.event ?? "message", data });
1391
1513
  });
1392
1514
  while (true) {
1393
- const { value, done } = await reader.read();
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;
1394
1527
  if (value) parser.feed(decoder.decode(value, { stream: true }));
1528
+ if (done) {
1529
+ parser.feed(decoder.decode());
1530
+ parser.end();
1531
+ }
1395
1532
  while (events.length > 0) {
1396
1533
  yield events.shift();
1397
1534
  }
1398
1535
  if (done) break;
1399
1536
  }
1400
- parser.end();
1401
- while (events.length > 0) {
1402
- yield events.shift();
1403
- }
1404
1537
  } catch (err) {
1405
- if (timedOut) {
1406
- throw new SeclaiStreamingError(
1407
- `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`
1408
- );
1538
+ if (timedOut && !(err instanceof SeclaiAPIStatusError)) {
1539
+ const timeout = withCause(new SeclaiStreamingError(streamTimeoutMessage(timeoutMs)), err);
1540
+ streamTimeouts.add(timeout);
1541
+ throw timeout;
1409
1542
  }
1410
1543
  throw err;
1411
1544
  } finally {
1412
1545
  clearTimeout(timeoutId);
1546
+ cleanup();
1547
+ reader?.cancel().catch(() => {
1548
+ });
1413
1549
  }
1414
1550
  }
1415
1551
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1424,22 +1560,33 @@ var Seclai = class {
1424
1560
  * `result_reported_at` is set, `output` holds the answer. Pass
1425
1561
  * `returnOnResult: true` to return as soon as a run has it set, the run
1426
1562
  * `runAgent()` returns included. With `includeStepOutputs`, when that run
1427
- * would end the poll and `signal` is not aborted, it is fetched again at
1428
- * once for its step outputs.
1563
+ * would end the poll, it is fetched again at once for its step outputs.
1429
1564
  * Such a run may still be in progress: its `status` is not terminal and the
1430
1565
  * run can still fail, so check `result_reported_at`, not `status`.
1431
1566
  *
1432
1567
  * When `timeoutMs` elapses first, this throws {@link SeclaiStreamingError}
1433
- * with the latest run it has (the `runAgent()` response if no poll ran) in
1434
- * `run`. If that run has `result_reported_at`
1435
- * set, its `output` is the answer.
1436
- *
1437
- * `signal` is checked at the top of each poll, after the check for a run
1438
- * that ends the poll. A run that has ended the poll by then, whether the
1439
- * start run or a polled one, is returned even after an abort; the start run
1440
- * then comes back without step outputs, even when `includeStepOutputs` is
1441
- * set. Otherwise an abort throws `SeclaiError("Polling aborted.")`, which is
1442
- * not an `AbortError` and does not carry `signal.reason`.
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.
1443
1590
  *
1444
1591
  * @param agentId - Agent identifier.
1445
1592
  * @param body - Run request payload.
@@ -1448,41 +1595,72 @@ var Seclai = class {
1448
1595
  * with `result_reported_at` set.
1449
1596
  * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run
1450
1597
  * finished. Its `run` holds the latest run it has (the `runAgent()`
1451
- * response if no poll ran).
1452
- * @throws {@link SeclaiError} `"Polling aborted."` If `signal` is aborted and,
1453
- * at the next poll's check, the run has not ended the poll. It is not an
1454
- * `AbortError` and does not carry `signal.reason`.
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.
1455
1603
  */
1456
1604
  async runAgentAndPoll(agentId, body, opts) {
1457
1605
  const pollInterval = opts?.pollIntervalMs ?? 2e3;
1458
1606
  const timeout = opts?.timeoutMs ?? 3e5;
1459
- const startTime = Date.now();
1460
- const run = await this.runAgent(agentId, body);
1461
- const runId = run.id ?? run.run_id;
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;
1462
1645
  if (!runId) throw new SeclaiError("Agent run response did not contain an id.");
1463
- let current = run;
1464
- if (opts?.includeStepOutputs) {
1465
- const status = run.status;
1466
- if (status === "completed" || status === "failed" || status === "cancelled" || opts.returnOnResult && run.result_reported_at) {
1467
- if (!opts.signal?.aborted) current = await this.getAgentRun(runId, { includeStepOutputs: true });
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;
1468
1652
  }
1469
1653
  }
1470
1654
  while (true) {
1471
- const status = current.status;
1472
- if (status === "completed" || status === "failed" || status === "cancelled") {
1473
- return 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();
1474
1661
  }
1475
- if (opts?.returnOnResult && current.result_reported_at) return current;
1476
- if (opts?.signal?.aborted) throw new SeclaiError("Polling aborted.");
1477
- if (Date.now() - startTime > timeout) {
1478
- const state = current.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
1479
- throw new SeclaiStreamingError(`Polling timed out after ${timeout}ms. ${state}`, runId, current);
1480
- }
1481
- await new Promise((r) => setTimeout(r, pollInterval));
1482
- current = await this.getAgentRun(
1483
- runId,
1484
- opts?.includeStepOutputs ? { includeStepOutputs: true } : void 0
1485
- );
1662
+ await sleep(pollInterval, signal);
1663
+ current = await abortable(true, (s) => this.request("GET", `/agents/runs/${runId}`, pollOpts(s)));
1486
1664
  }
1487
1665
  }
1488
1666
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1551,22 +1729,50 @@ var Seclai = class {
1551
1729
  return await this.request("GET", `/agents/${agentId}/attachment-references`);
1552
1730
  }
1553
1731
  /**
1554
- * Download a file attachment emitted by a step in an agent run.
1732
+ * Download a file of an agent run (one a step emitted or one the run started
1733
+ * with), or one byte range of it.
1555
1734
  *
1556
1735
  * Returns the raw `Response` so you can stream or save the binary data.
1557
1736
  *
1737
+ * To fetch part of the file, set a byte range. Offsets are zero-based and
1738
+ * `rangeEnd` is inclusive:
1739
+ *
1740
+ * - `rangeStart` alone sends `Range: bytes=<rangeStart>-`, from that byte to the end.
1741
+ * - `rangeStart` and `rangeEnd` send `Range: bytes=<rangeStart>-<rangeEnd>`.
1742
+ * - `rangeSuffix` alone sends `Range: bytes=-<rangeSuffix>`, the last that many bytes.
1743
+ *
1744
+ * With none of them set, the SDK adds no `Range` header. The server answers a range
1745
+ * with status 206 and a `Content-Range` header, so check `resp.status` before
1746
+ * treating the body as the whole file. A range of an empty file is answered with
1747
+ * 200 and the whole (empty) file. A range that starts at or past the end of a
1748
+ * non-empty file throws {@link SeclaiAPIStatusError} with `statusCode` 416,
1749
+ * and its `headers.get("content-range")` ends in `/<size>`, the file's size in
1750
+ * bytes.
1751
+ *
1558
1752
  * @param runId - Run identifier.
1559
- * @param attachmentId - URL-safe-base64-encoded `storage_key` of the attachment
1560
- * (as surfaced in run output manifests and webhook/email payloads).
1753
+ * @param attachmentId - The `id` of an entry in the run's or a step's
1754
+ * `attachments`, or the URL-safe-base64-encoded storage key that webhook and
1755
+ * email links carry.
1561
1756
  * @param opts - Optional `downloadName` filename hint for the download
1562
- * disposition, and `signal`, which cancels the request; with a standard `fetch` this
1757
+ * disposition; `rangeStart`, `rangeEnd` and `rangeSuffix`, the byte range
1758
+ * described above; and `signal`, which cancels the request; with a standard `fetch` this
1563
1759
  * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole
1564
1760
  * transfer.
1565
- * @returns Raw response with the attachment bytes.
1761
+ * @returns Raw response with the attachment bytes: status 200 with the whole
1762
+ * file, or 206 with the requested range.
1763
+ * @throws {@link SeclaiConfigurationError} Before any request, when the range
1764
+ * options are not one of the three forms above: `rangeEnd` without
1765
+ * `rangeStart`, `rangeSuffix` with either of them, `rangeEnd` less than
1766
+ * `rangeStart`, a negative `rangeStart` or `rangeEnd`, a `rangeSuffix` below
1767
+ * 1, or a value that is not a safe integer (`Number.isSafeInteger`).
1768
+ * @throws {@link SeclaiAPIStatusError} On a non-2xx response, including 416
1769
+ * when the range cannot be satisfied.
1566
1770
  */
1567
1771
  async downloadAgentRunAttachment(runId, attachmentId, opts = {}) {
1772
+ const range = byteRangeHeader(opts.rangeStart, opts.rangeEnd, opts.rangeSuffix);
1568
1773
  return await this.requestRaw("GET", `/v2/agent-runs/${runId}/attachments/${attachmentId}`, {
1569
1774
  query: { download_name: opts.downloadName },
1775
+ ...range === void 0 ? {} : { headers: { Range: range } },
1570
1776
  signal: opts.signal
1571
1777
  });
1572
1778
  }
@@ -2019,11 +2225,12 @@ var Seclai = class {
2019
2225
  return await this.request("GET", "/agents/inbound-email-status");
2020
2226
  }
2021
2227
  /**
2022
- * Fail all of the account's QUEUED (over-quota parked) inbound-email runs at
2023
- * once.
2228
+ * Cancel all of the account's QUEUED (over-quota parked) inbound-email runs
2229
+ * at once.
2024
2230
  *
2025
- * A queued run consumed no quota or credits at queue time, so this merely
2026
- * fails them. Requires an account owner/admin.
2231
+ * A queued run consumed no quota or credits at queue time. Each ends
2232
+ * `cancelled`, or `failed` with an `apiVersion` before `2026-11-08`.
2233
+ * Requires an account owner/admin.
2027
2234
  *
2028
2235
  * @returns The count cancelled.
2029
2236
  */