@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.js CHANGED
@@ -16,10 +16,14 @@ var SeclaiApiVersion = {
16
16
  V2026_10_28: "2026-10-28",
17
17
  V2026_11_02: "2026-11-02",
18
18
  V2026_11_04: "2026-11-04",
19
+ V2026_11_08: "2026-11-08",
20
+ V2026_11_09: "2026-11-09",
21
+ V2026_11_14: "2026-11-14",
22
+ V2026_11_19: "2026-11-19",
19
23
  /** Baseline applied to an unpinned, header-less caller. */
20
24
  Default: "2026-07-01",
21
25
  /** Newest version known to this SDK release. May lag the server. */
22
- Latest: "2026-11-04"
26
+ Latest: "2026-11-19"
23
27
  };
24
28
  var KNOWN_API_VERSIONS = Object.entries(SeclaiApiVersion).filter(([k]) => k.startsWith("V")).map(([, v]) => v);
25
29
 
@@ -45,6 +49,14 @@ var SeclaiAPIStatusError = class extends SeclaiError {
45
49
  url;
46
50
  /** Best-effort response body text (if available). */
47
51
  responseText;
52
+ /**
53
+ * Headers of the error response, such as `Retry-After` on a 503, or
54
+ * `Content-Range` on a 416 from a ranged `downloadAgentRunAttachment()`, whose
55
+ * value ends in `/<size>`, the file's size in bytes. Empty when the response
56
+ * headers are unknown. In a browser, only the headers the server's CORS policy
57
+ * exposes are present.
58
+ */
59
+ headers;
48
60
  constructor(opts) {
49
61
  super(opts.message);
50
62
  this.name = "SeclaiAPIStatusError";
@@ -52,6 +64,7 @@ var SeclaiAPIStatusError = class extends SeclaiError {
52
64
  this.method = opts.method;
53
65
  this.url = opts.url;
54
66
  this.responseText = opts.responseText;
67
+ this.headers = opts.headers ?? new Headers();
55
68
  }
56
69
  };
57
70
  var SeclaiAPIValidationError = class extends SeclaiAPIStatusError {
@@ -429,6 +442,34 @@ function mergeHeaders(...layers) {
429
442
  function headerKey(headers, name) {
430
443
  return Object.keys(headers ?? {}).filter((key) => key.toLowerCase() === name).pop();
431
444
  }
445
+ function byteRangeHeader(start, end, suffix) {
446
+ const hasStart = start !== void 0 && start !== null;
447
+ const hasEnd = end !== void 0 && end !== null;
448
+ const hasSuffix = suffix !== void 0 && suffix !== null;
449
+ if (!hasStart && !hasEnd && !hasSuffix) return void 0;
450
+ const fail = (why) => {
451
+ throw new SeclaiConfigurationError(`Invalid byte range: ${why}`);
452
+ };
453
+ if (hasSuffix) {
454
+ if (hasStart || hasEnd) fail("rangeSuffix cannot be combined with rangeStart or rangeEnd.");
455
+ if (!Number.isSafeInteger(suffix) || suffix < 1) {
456
+ fail(`rangeSuffix must be a whole number of at least 1, got ${String(suffix)}.`);
457
+ }
458
+ return `bytes=-${suffix}`;
459
+ }
460
+ if (!hasStart) fail("rangeEnd requires rangeStart; use rangeSuffix for the last bytes of the file.");
461
+ if (!Number.isSafeInteger(start) || start < 0) {
462
+ fail(`rangeStart must be a whole number of at least 0, got ${String(start)}.`);
463
+ }
464
+ if (!hasEnd) return `bytes=${start}-`;
465
+ if (!Number.isSafeInteger(end) || end < 0) {
466
+ fail(`rangeEnd must be a whole number of at least 0, got ${String(end)}.`);
467
+ }
468
+ if (end < start) {
469
+ fail(`rangeEnd (${end}) must not be less than rangeStart (${start}).`);
470
+ }
471
+ return `bytes=${start}-${end}`;
472
+ }
432
473
  async function safeText(response) {
433
474
  try {
434
475
  return await response.clone().text();
@@ -455,47 +496,122 @@ function createSseParser(onMessage) {
455
496
  eventName = void 0;
456
497
  dataLines = [];
457
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
+ }
458
517
  function feed(textChunk) {
459
518
  buffer += textChunk;
460
519
  while (true) {
461
520
  const newlineIdx = buffer.indexOf("\n");
462
521
  if (newlineIdx === -1) return;
463
- let line = buffer.slice(0, newlineIdx);
522
+ const line = buffer.slice(0, newlineIdx);
464
523
  buffer = buffer.slice(newlineIdx + 1);
465
- if (line.endsWith("\r")) line = line.slice(0, -1);
466
- if (line === "") {
467
- dispatch();
468
- continue;
469
- }
470
- if (line.startsWith(":")) continue;
471
- const colon = line.indexOf(":");
472
- const field = colon === -1 ? line : line.slice(0, colon);
473
- let value = colon === -1 ? "" : line.slice(colon + 1);
474
- if (value.startsWith(" ")) value = value.slice(1);
475
- if (field === "event") {
476
- eventName = value;
477
- } else if (field === "data") {
478
- dataLines.push(value);
479
- }
524
+ processLine(line);
525
+ }
526
+ }
527
+ function end() {
528
+ if (buffer !== "") {
529
+ const line = buffer;
530
+ buffer = "";
531
+ processLine(line);
480
532
  }
533
+ dispatch();
534
+ }
535
+ function abandon() {
536
+ buffer = "";
537
+ dispatch();
481
538
  }
482
- return { feed, end: dispatch };
539
+ return { feed, end, abandon };
483
540
  }
484
541
  function anySignal(signals) {
485
542
  const present = signals.filter(Boolean);
486
- if (present.length === 0) return void 0;
487
- 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
+ } };
488
547
  const controller = new AbortController();
489
- 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
+ };
490
553
  for (const s of present) {
491
554
  if (s.aborted) {
492
- controller.abort();
555
+ cleanup();
556
+ controller.abort(s.reason);
493
557
  break;
494
558
  }
559
+ const onAbort = () => controller.abort(s.reason);
495
560
  s.addEventListener("abort", onAbort, { once: true });
561
+ listening.push([s, onAbort]);
496
562
  }
497
- 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);
498
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);
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();
499
615
  function toBlob(file, mimeType) {
500
616
  if (file instanceof Blob) return file;
501
617
  const opts = mimeType ? { type: mimeType } : void 0;
@@ -695,6 +811,7 @@ var Seclai = class {
695
811
  method,
696
812
  url: url.toString(),
697
813
  responseText,
814
+ headers: new Headers(response.headers),
698
815
  validationError: validation
699
816
  });
700
817
  }
@@ -703,7 +820,8 @@ var Seclai = class {
703
820
  statusCode: response.status,
704
821
  method,
705
822
  url: url.toString(),
706
- responseText
823
+ responseText,
824
+ headers: new Headers(response.headers)
707
825
  });
708
826
  }
709
827
  if (!response.body) return null;
@@ -750,6 +868,7 @@ var Seclai = class {
750
868
  method,
751
869
  url: url.toString(),
752
870
  responseText,
871
+ headers: new Headers(response.headers),
753
872
  validationError: validation
754
873
  });
755
874
  }
@@ -758,7 +877,8 @@ var Seclai = class {
758
877
  statusCode: response.status,
759
878
  method,
760
879
  url: url.toString(),
761
- responseText
880
+ responseText,
881
+ headers: new Headers(response.headers)
762
882
  });
763
883
  }
764
884
  return response;
@@ -789,6 +909,7 @@ var Seclai = class {
789
909
  method: "POST",
790
910
  url: url.toString(),
791
911
  responseText,
912
+ headers: new Headers(response.headers),
792
913
  validationError: validation
793
914
  });
794
915
  }
@@ -797,7 +918,8 @@ var Seclai = class {
797
918
  statusCode: response.status,
798
919
  method: "POST",
799
920
  url: url.toString(),
800
- responseText
921
+ responseText,
922
+ headers: new Headers(response.headers)
801
923
  });
802
924
  }
803
925
  return await response.json();
@@ -863,6 +985,10 @@ var Seclai = class {
863
985
  /**
864
986
  * List the agent gallery: example agents to start from.
865
987
  *
988
+ * From `apiVersion` `2026-11-09`, `query` describes what the agent should do
989
+ * and entries come back ranked by how well they match it, best first. Before
990
+ * it, only entries containing every word of `query` are returned.
991
+ *
866
992
  * Pass an entry's `key` as `agent_template` to {@link createAgent}, with
867
993
  * `resource_bindings` for the resources it needs.
868
994
  *
@@ -1016,6 +1142,11 @@ var Seclai = class {
1016
1142
  /**
1017
1143
  * Start an agent run.
1018
1144
  *
1145
+ * From `apiVersion` `2026-11-14`, an agent whose definition fails to validate
1146
+ * is refused with HTTP 409 ({@link SeclaiAPIStatusError}) and no run is
1147
+ * created; earlier versions return the run, already failed with the
1148
+ * validation error as its cause.
1149
+ *
1019
1150
  * @param agentId - Agent identifier.
1020
1151
  * @param body - Run request payload (`input`, `metadata`, `priority`, etc.).
1021
1152
  * @returns The created agent run.
@@ -1069,14 +1200,17 @@ var Seclai = class {
1069
1200
  await this.cancelAgentRun(runId);
1070
1201
  }
1071
1202
  /**
1072
- * Cancel a running agent run.
1203
+ * Cancel an agent run that has not ended: `queued`, `pending`, `processing`,
1204
+ * `waiting_human` or `waiting_scheduled`.
1073
1205
  *
1074
1206
  * Cancellation is `DELETE` on the run resource — the API exposes no
1075
1207
  * `POST .../cancel` route, and no operation that deletes a run. Rejected when
1076
- * the run has already reached a terminal state.
1208
+ * the run has already ended (`completed`, `failed` or `cancelled`). From
1209
+ * `apiVersion` `2026-11-08` the cancelled run ends with status `cancelled`;
1210
+ * on earlier versions it ends `failed`.
1077
1211
  *
1078
1212
  * @param runId - Run identifier.
1079
- * @returns Updated run (with cancelled status).
1213
+ * @returns The updated run.
1080
1214
  */
1081
1215
  async cancelAgentRun(runId) {
1082
1216
  return await this.request("DELETE", `/agents/runs/${runId}`);
@@ -1087,10 +1221,11 @@ var Seclai = class {
1087
1221
  /**
1088
1222
  * Run an agent in streaming mode (SSE) and wait for the final result.
1089
1223
  *
1090
- * Consumes the entire SSE stream and returns only the terminal `done` payload.
1091
- * For real-time event access, use {@link runStreamingAgent} instead. The body
1092
- * takes no `include_reasoning`, and one passed anyway is not sent: this method
1093
- * returns no `stream_reasoning` 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.
1094
1229
  *
1095
1230
  * A `result` event carries the run's answer in `output` once
1096
1231
  * `result_reported_at` is set, and can arrive while later steps still run.
@@ -1099,27 +1234,40 @@ var Seclai = class {
1099
1234
  * its `status` is not terminal and the run can still fail, so check
1100
1235
  * `result_reported_at`, not `status`.
1101
1236
  *
1102
- * If `timeoutMs` elapses, this throws {@link SeclaiStreamingError} with the
1103
- * latest snapshot in `run`: the `result` snapshot if one arrived, else the
1104
- * `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.
1105
1245
  *
1106
1246
  * By default, a stream that ends before `done` returns the latest snapshot
1107
- * when its status is not `pending`, so the run returned may not have
1108
- * finished: check `status` and `result_reported_at`. A stream that breaks
1109
- * throws the fetch error. Pass `throwOnIncomplete: true` to throw
1110
- * {@link SeclaiStreamingError} with the snapshot in `run` in both cases
1111
- * instead; it is recommended, and becomes the default in the next major
1112
- * 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.
1113
1255
  *
1114
1256
  * @param agentId - Agent identifier.
1115
- * @param body - Streaming run request payload, without `include_reasoning`.
1257
+ * @param body - Streaming run request payload, without `include_reasoning`
1258
+ * or `include_commentary`.
1116
1259
  * @param opts - Timeout, abort signal and `returnOnResult` options.
1117
1260
  * @returns The run from the `done` event; with `returnOnResult`, the
1118
1261
  * `result` snapshot; without `throwOnIncomplete`, possibly an unfinished
1119
1262
  * snapshot (see above).
1120
- * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses, or, with
1121
- * `throwOnIncomplete`, the stream ends or breaks, before the run finished.
1122
- * 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.
1123
1271
  *
1124
1272
  * @example
1125
1273
  * ```ts
@@ -1134,130 +1282,90 @@ var Seclai = class {
1134
1282
  * ```
1135
1283
  */
1136
1284
  async runStreamingAgentAndWait(agentId, body, opts) {
1137
- const { include_reasoning: _ignored, ...runBody } = body;
1138
- const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
1139
- const authHdrs = await this.authHeaders();
1140
- const headers = this.requestHeaders([
1141
- this.defaultHeaders,
1142
- authHdrs,
1143
- { accept: "text/event-stream", "content-type": "application/json" }
1144
- ]);
1285
+ const {
1286
+ include_reasoning: _reasoning,
1287
+ include_commentary: _commentary,
1288
+ ...runBody
1289
+ } = body;
1145
1290
  const timeoutMs = opts?.timeoutMs ?? 6e4;
1146
- const timeoutController = new AbortController();
1147
- let timedOut = false;
1148
- const timeoutId = setTimeout(() => {
1149
- timedOut = true;
1150
- timeoutController.abort();
1151
- }, timeoutMs);
1152
- const signal = anySignal([opts?.signal, timeoutController.signal]);
1153
- 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;
1154
1295
  let reported;
1296
+ const snapshot = () => reported ?? initial;
1155
1297
  try {
1156
- const init = { method: "POST", headers, body: JSON.stringify(runBody) };
1157
- if (signal) init.signal = signal;
1158
- const response = await this.fetcher(url, init);
1159
- const contentType = response.headers.get("content-type") ?? "";
1160
- const isJson = contentType.includes("application/json");
1161
- if (!response.ok) {
1162
- const responseText = await safeText(response);
1163
- if (response.status === 422) {
1164
- const validation = await safeJson(response);
1165
- throw new SeclaiAPIValidationError({
1166
- message: "Validation error",
1167
- statusCode: response.status,
1168
- method: "POST",
1169
- url: url.toString(),
1170
- responseText,
1171
- validationError: validation
1172
- });
1173
- }
1174
- throw new SeclaiAPIStatusError({
1175
- message: `Request failed with status ${response.status}`,
1176
- statusCode: response.status,
1177
- method: "POST",
1178
- url: url.toString(),
1179
- responseText
1180
- });
1181
- }
1182
- if (isJson) {
1183
- const run2 = await response.json();
1184
- const status = run2.status;
1185
- const finished = status === "completed" || status === "failed" || status === "cancelled" || Boolean(opts?.returnOnResult && run2.result_reported_at);
1186
- if (opts?.throwOnIncomplete && !finished) {
1187
- const state2 = run2.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
1188
- throw new SeclaiStreamingError(`The server answered with JSON for a run that has not finished. ${state2}`, run2.run_id, run2);
1189
- }
1190
- return run2;
1191
- }
1192
- if (!response.body) {
1193
- throw new SeclaiConfigurationError(
1194
- "Streaming response body is not available in this environment. Provide a fetch implementation that supports ReadableStream bodies."
1195
- );
1196
- }
1197
- const reader = response.body.getReader();
1198
- const decoder = new TextDecoder();
1199
- let final;
1200
- const parser = createSseParser((msg) => {
1201
- if (!msg.data) return;
1202
- if (msg.event === "init" || msg.event === "result" || msg.event === "done") {
1203
- try {
1204
- const parsed = JSON.parse(msg.data);
1205
- lastSeen = parsed;
1206
- if (msg.event === "result") reported = parsed;
1207
- if (msg.event === "done") final = parsed;
1208
- } 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);
1209
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);
1210
1308
  }
1211
- });
1212
- let readFailure;
1213
- try {
1214
- while (!final && !(opts?.returnOnResult && reported)) {
1215
- const { value, done } = await reader.read();
1216
- if (done) break;
1217
- 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;
1218
1321
  }
1219
- } catch (err) {
1220
- if (opts?.signal?.aborted || !opts?.throwOnIncomplete && !timedOut) throw err;
1221
- readFailure = err instanceof Error ? err.message : String(err);
1222
- }
1223
- parser.feed(decoder.decode());
1224
- parser.end();
1225
- if (final) return final;
1226
- if (opts?.returnOnResult && reported) {
1227
- reader.cancel().catch(() => {
1228
- });
1229
- return reported;
1230
1322
  }
1231
- if (!opts?.throwOnIncomplete && !timedOut && lastSeen?.status && lastSeen.status !== "pending") {
1232
- return lastSeen;
1233
- }
1234
- const run = reported ?? lastSeen;
1235
- const state = reported ? "A result had been reported; see `run`." : "No result had been reported.";
1236
- 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.";
1237
- throw new SeclaiStreamingError(`${reason} ${state}`, run?.run_id, run);
1238
1323
  } catch (err) {
1239
- if (timedOut && !opts?.signal?.aborted && !(err instanceof SeclaiStreamingError)) {
1240
- throw new SeclaiStreamingError(
1241
- `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`,
1242
- lastSeen?.run_id,
1243
- reported ?? lastSeen
1244
- );
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());
1245
1331
  }
1246
1332
  throw err;
1247
- } finally {
1248
- clearTimeout(timeoutId);
1249
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());
1250
1340
  }
1251
1341
  /**
1252
1342
  * Run an agent in streaming mode and yield each SSE event as it arrives.
1253
1343
  *
1254
1344
  * This is an `AsyncGenerator` suitable for real-time UIs that want to render
1255
- * step progress as it happens.
1345
+ * step progress as it happens. Set `include_reasoning` or
1346
+ * `include_commentary` in `body` to also receive `stream_reasoning` or
1347
+ * `stream_commentary` events.
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
+ *
1356
+ * From `apiVersion` `2026-11-14`, an agent whose definition fails to validate
1357
+ * is refused with HTTP 409 ({@link SeclaiAPIStatusError}) before any event,
1358
+ * and no run is created.
1256
1359
  *
1257
1360
  * @param agentId - Agent identifier.
1258
1361
  * @param body - Streaming run request payload.
1259
1362
  * @param opts - Timeout and abort signal options.
1260
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.
1261
1369
  *
1262
1370
  * @example
1263
1371
  * ```ts
@@ -1273,6 +1381,14 @@ var Seclai = class {
1273
1381
  * ```
1274
1382
  */
1275
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) {
1276
1392
  const url = buildURL(this.baseUrl, `/agents/${agentId}/runs/stream`);
1277
1393
  const authHdrs = await this.authHeaders();
1278
1394
  const headers = this.requestHeaders([
@@ -1285,9 +1401,11 @@ var Seclai = class {
1285
1401
  let timedOut = false;
1286
1402
  const timeoutId = setTimeout(() => {
1287
1403
  timedOut = true;
1404
+ if (progress) progress.timedOut = true;
1288
1405
  timeoutController.abort();
1289
1406
  }, timeoutMs);
1290
- const signal = anySignal([opts?.signal, timeoutController.signal]);
1407
+ const { signal, cleanup } = anySignal([opts?.signal, timeoutController.signal]);
1408
+ let reader;
1291
1409
  try {
1292
1410
  const init = { method: "POST", headers, body: JSON.stringify(body) };
1293
1411
  if (signal) init.signal = signal;
@@ -1304,6 +1422,7 @@ var Seclai = class {
1304
1422
  method: "POST",
1305
1423
  url: url.toString(),
1306
1424
  responseText,
1425
+ headers: new Headers(response.headers),
1307
1426
  validationError: validation
1308
1427
  });
1309
1428
  }
@@ -1312,20 +1431,23 @@ var Seclai = class {
1312
1431
  statusCode: response.status,
1313
1432
  method: "POST",
1314
1433
  url: url.toString(),
1315
- responseText
1434
+ responseText,
1435
+ headers: new Headers(response.headers)
1316
1436
  });
1317
1437
  }
1318
1438
  if (isJson) {
1319
1439
  const data = await response.json();
1440
+ if (progress) progress.jsonReply = true;
1320
1441
  yield { event: "done", data };
1321
1442
  return;
1322
1443
  }
1323
1444
  if (!response.body) {
1324
1445
  throw new SeclaiConfigurationError(
1325
- "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."
1326
1447
  );
1327
1448
  }
1328
- const reader = response.body.getReader();
1449
+ reader = response.body.getReader();
1450
+ if (progress) progress.reading = true;
1329
1451
  const decoder = new TextDecoder();
1330
1452
  const events = [];
1331
1453
  const parser = createSseParser((msg) => {
@@ -1339,26 +1461,40 @@ var Seclai = class {
1339
1461
  events.push({ event: msg.event ?? "message", data });
1340
1462
  });
1341
1463
  while (true) {
1342
- 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;
1343
1476
  if (value) parser.feed(decoder.decode(value, { stream: true }));
1477
+ if (done) {
1478
+ parser.feed(decoder.decode());
1479
+ parser.end();
1480
+ }
1344
1481
  while (events.length > 0) {
1345
1482
  yield events.shift();
1346
1483
  }
1347
1484
  if (done) break;
1348
1485
  }
1349
- parser.end();
1350
- while (events.length > 0) {
1351
- yield events.shift();
1352
- }
1353
1486
  } catch (err) {
1354
- if (timedOut) {
1355
- throw new SeclaiStreamingError(
1356
- `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`
1357
- );
1487
+ if (timedOut && !(err instanceof SeclaiAPIStatusError)) {
1488
+ const timeout = withCause(new SeclaiStreamingError(streamTimeoutMessage(timeoutMs)), err);
1489
+ streamTimeouts.add(timeout);
1490
+ throw timeout;
1358
1491
  }
1359
1492
  throw err;
1360
1493
  } finally {
1361
1494
  clearTimeout(timeoutId);
1495
+ cleanup();
1496
+ reader?.cancel().catch(() => {
1497
+ });
1362
1498
  }
1363
1499
  }
1364
1500
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1373,22 +1509,33 @@ var Seclai = class {
1373
1509
  * `result_reported_at` is set, `output` holds the answer. Pass
1374
1510
  * `returnOnResult: true` to return as soon as a run has it set, the run
1375
1511
  * `runAgent()` returns included. With `includeStepOutputs`, when that run
1376
- * would end the poll and `signal` is not aborted, it is fetched again at
1377
- * once for its step outputs.
1512
+ * would end the poll, it is fetched again at once for its step outputs.
1378
1513
  * Such a run may still be in progress: its `status` is not terminal and the
1379
1514
  * run can still fail, so check `result_reported_at`, not `status`.
1380
1515
  *
1381
1516
  * When `timeoutMs` elapses first, this throws {@link SeclaiStreamingError}
1382
- * with the latest run it has (the `runAgent()` response if no poll ran) in
1383
- * `run`. If that run has `result_reported_at`
1384
- * set, its `output` is the answer.
1385
- *
1386
- * `signal` is checked at the top of each poll, after the check for a run
1387
- * that ends the poll. A run that has ended the poll by then, whether the
1388
- * start run or a polled one, is returned even after an abort; the start run
1389
- * then comes back without step outputs, even when `includeStepOutputs` is
1390
- * set. Otherwise an abort throws `SeclaiError("Polling aborted.")`, which is
1391
- * 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.
1392
1539
  *
1393
1540
  * @param agentId - Agent identifier.
1394
1541
  * @param body - Run request payload.
@@ -1397,41 +1544,72 @@ var Seclai = class {
1397
1544
  * with `result_reported_at` set.
1398
1545
  * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run
1399
1546
  * finished. Its `run` holds the latest run it has (the `runAgent()`
1400
- * response if no poll ran).
1401
- * @throws {@link SeclaiError} `"Polling aborted."` If `signal` is aborted and,
1402
- * at the next poll's check, the run has not ended the poll. It is not an
1403
- * `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.
1404
1552
  */
1405
1553
  async runAgentAndPoll(agentId, body, opts) {
1406
1554
  const pollInterval = opts?.pollIntervalMs ?? 2e3;
1407
1555
  const timeout = opts?.timeoutMs ?? 3e5;
1408
- const startTime = Date.now();
1409
- const run = await this.runAgent(agentId, body);
1410
- 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;
1411
1594
  if (!runId) throw new SeclaiError("Agent run response did not contain an id.");
1412
- let current = run;
1413
- if (opts?.includeStepOutputs) {
1414
- const status = run.status;
1415
- if (status === "completed" || status === "failed" || status === "cancelled" || opts.returnOnResult && run.result_reported_at) {
1416
- 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;
1417
1601
  }
1418
1602
  }
1419
1603
  while (true) {
1420
- const status = current.status;
1421
- if (status === "completed" || status === "failed" || status === "cancelled") {
1422
- return 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();
1423
1610
  }
1424
- if (opts?.returnOnResult && current.result_reported_at) return current;
1425
- if (opts?.signal?.aborted) throw new SeclaiError("Polling aborted.");
1426
- if (Date.now() - startTime > timeout) {
1427
- const state = current.result_reported_at ? "A result had been reported; see `run`." : "No result had been reported.";
1428
- throw new SeclaiStreamingError(`Polling timed out after ${timeout}ms. ${state}`, runId, current);
1429
- }
1430
- await new Promise((r) => setTimeout(r, pollInterval));
1431
- current = await this.getAgentRun(
1432
- runId,
1433
- opts?.includeStepOutputs ? { includeStepOutputs: true } : void 0
1434
- );
1611
+ await sleep(pollInterval, signal);
1612
+ current = await abortable(true, (s) => this.request("GET", `/agents/runs/${runId}`, pollOpts(s)));
1435
1613
  }
1436
1614
  }
1437
1615
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1500,22 +1678,50 @@ var Seclai = class {
1500
1678
  return await this.request("GET", `/agents/${agentId}/attachment-references`);
1501
1679
  }
1502
1680
  /**
1503
- * Download a file attachment emitted by a step in an agent run.
1681
+ * Download a file of an agent run (one a step emitted or one the run started
1682
+ * with), or one byte range of it.
1504
1683
  *
1505
1684
  * Returns the raw `Response` so you can stream or save the binary data.
1506
1685
  *
1686
+ * To fetch part of the file, set a byte range. Offsets are zero-based and
1687
+ * `rangeEnd` is inclusive:
1688
+ *
1689
+ * - `rangeStart` alone sends `Range: bytes=<rangeStart>-`, from that byte to the end.
1690
+ * - `rangeStart` and `rangeEnd` send `Range: bytes=<rangeStart>-<rangeEnd>`.
1691
+ * - `rangeSuffix` alone sends `Range: bytes=-<rangeSuffix>`, the last that many bytes.
1692
+ *
1693
+ * With none of them set, the SDK adds no `Range` header. The server answers a range
1694
+ * with status 206 and a `Content-Range` header, so check `resp.status` before
1695
+ * treating the body as the whole file. A range of an empty file is answered with
1696
+ * 200 and the whole (empty) file. A range that starts at or past the end of a
1697
+ * non-empty file throws {@link SeclaiAPIStatusError} with `statusCode` 416,
1698
+ * and its `headers.get("content-range")` ends in `/<size>`, the file's size in
1699
+ * bytes.
1700
+ *
1507
1701
  * @param runId - Run identifier.
1508
- * @param attachmentId - URL-safe-base64-encoded `storage_key` of the attachment
1509
- * (as surfaced in run output manifests and webhook/email payloads).
1702
+ * @param attachmentId - The `id` of an entry in the run's or a step's
1703
+ * `attachments`, or the URL-safe-base64-encoded storage key that webhook and
1704
+ * email links carry.
1510
1705
  * @param opts - Optional `downloadName` filename hint for the download
1511
- * disposition, and `signal`, which cancels the request; with a standard `fetch` this
1706
+ * disposition; `rangeStart`, `rangeEnd` and `rangeSuffix`, the byte range
1707
+ * described above; and `signal`, which cancels the request; with a standard `fetch` this
1512
1708
  * includes reading the body, so `AbortSignal.timeout(ms)` bounds the whole
1513
1709
  * transfer.
1514
- * @returns Raw response with the attachment bytes.
1710
+ * @returns Raw response with the attachment bytes: status 200 with the whole
1711
+ * file, or 206 with the requested range.
1712
+ * @throws {@link SeclaiConfigurationError} Before any request, when the range
1713
+ * options are not one of the three forms above: `rangeEnd` without
1714
+ * `rangeStart`, `rangeSuffix` with either of them, `rangeEnd` less than
1715
+ * `rangeStart`, a negative `rangeStart` or `rangeEnd`, a `rangeSuffix` below
1716
+ * 1, or a value that is not a safe integer (`Number.isSafeInteger`).
1717
+ * @throws {@link SeclaiAPIStatusError} On a non-2xx response, including 416
1718
+ * when the range cannot be satisfied.
1515
1719
  */
1516
1720
  async downloadAgentRunAttachment(runId, attachmentId, opts = {}) {
1721
+ const range = byteRangeHeader(opts.rangeStart, opts.rangeEnd, opts.rangeSuffix);
1517
1722
  return await this.requestRaw("GET", `/v2/agent-runs/${runId}/attachments/${attachmentId}`, {
1518
1723
  query: { download_name: opts.downloadName },
1724
+ ...range === void 0 ? {} : { headers: { Range: range } },
1519
1725
  signal: opts.signal
1520
1726
  });
1521
1727
  }
@@ -1968,11 +2174,12 @@ var Seclai = class {
1968
2174
  return await this.request("GET", "/agents/inbound-email-status");
1969
2175
  }
1970
2176
  /**
1971
- * Fail all of the account's QUEUED (over-quota parked) inbound-email runs at
1972
- * once.
2177
+ * Cancel all of the account's QUEUED (over-quota parked) inbound-email runs
2178
+ * at once.
1973
2179
  *
1974
- * A queued run consumed no quota or credits at queue time, so this merely
1975
- * fails them. Requires an account owner/admin.
2180
+ * A queued run consumed no quota or credits at queue time. Each ends
2181
+ * `cancelled`, or `failed` with an `apiVersion` before `2026-11-08`.
2182
+ * Requires an account owner/admin.
1976
2183
  *
1977
2184
  * @returns The count cancelled.
1978
2185
  */