@seclai/sdk 1.8.0 → 1.9.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
@@ -14,10 +14,12 @@ var SeclaiApiVersion = {
14
14
  V2026_10_19: "2026-10-19",
15
15
  V2026_10_21: "2026-10-21",
16
16
  V2026_10_28: "2026-10-28",
17
+ V2026_11_02: "2026-11-02",
18
+ V2026_11_04: "2026-11-04",
17
19
  /** Baseline applied to an unpinned, header-less caller. */
18
20
  Default: "2026-07-01",
19
21
  /** Newest version known to this SDK release. May lag the server. */
20
- Latest: "2026-10-28"
22
+ Latest: "2026-11-04"
21
23
  };
22
24
  var KNOWN_API_VERSIONS = Object.entries(SeclaiApiVersion).filter(([k]) => k.startsWith("V")).map(([, v]) => v);
23
25
 
@@ -64,10 +66,17 @@ var SeclaiAPIValidationError = class extends SeclaiAPIStatusError {
64
66
  var SeclaiStreamingError = class extends SeclaiError {
65
67
  /** The run ID associated with the failed stream, when available. */
66
68
  runId;
67
- constructor(message, runId) {
69
+ /**
70
+ * Set by `runStreamingAgentAndWait()` and `runAgentAndPoll()` to the latest
71
+ * run they had, if any (when it has `result_reported_at` set, its `output`
72
+ * is the answer). The run may still be in progress, and can still fail.
73
+ */
74
+ run;
75
+ constructor(message, runId, run) {
68
76
  super(message);
69
77
  this.name = "SeclaiStreamingError";
70
78
  this.runId = runId;
79
+ this.run = run;
71
80
  }
72
81
  };
73
82
 
@@ -1083,11 +1092,46 @@ var Seclai = class {
1083
1092
  * takes no `include_reasoning`, and one passed anyway is not sent: this method
1084
1093
  * returns no `stream_reasoning` events.
1085
1094
  *
1095
+ * A `result` event carries the run's answer in `output` once
1096
+ * `result_reported_at` is set, and can arrive while later steps still run.
1097
+ * Pass `returnOnResult: true` to return that `result` snapshot as soon as it
1098
+ * arrives, without waiting for `done`. Such a run may still be in progress:
1099
+ * its `status` is not terminal and the run can still fail, so check
1100
+ * `result_reported_at`, not `status`.
1101
+ *
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.
1105
+ *
1106
+ * 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.
1113
+ *
1086
1114
  * @param agentId - Agent identifier.
1087
1115
  * @param body - Streaming run request payload, without `include_reasoning`.
1088
- * @param opts - Timeout and abort signal options.
1089
- * @returns Final agent run payload from the `done` event.
1090
- * @throws {@link SeclaiStreamingError} If the stream ends before a `done` event.
1116
+ * @param opts - Timeout, abort signal and `returnOnResult` options.
1117
+ * @returns The run from the `done` event; with `returnOnResult`, the
1118
+ * `result` snapshot; without `throwOnIncomplete`, possibly an unfinished
1119
+ * 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.
1123
+ *
1124
+ * @example
1125
+ * ```ts
1126
+ * try {
1127
+ * const run = await client.runStreamingAgentAndWait("agent-id", { input: "Hello" }, { throwOnIncomplete: true });
1128
+ * console.log(run.output);
1129
+ * } catch (err) {
1130
+ * if (err instanceof SeclaiStreamingError && err.run?.result_reported_at) {
1131
+ * console.log("Answer (run not finished):", err.run.output);
1132
+ * } else throw err;
1133
+ * }
1134
+ * ```
1091
1135
  */
1092
1136
  async runStreamingAgentAndWait(agentId, body, opts) {
1093
1137
  const { include_reasoning: _ignored, ...runBody } = body;
@@ -1107,6 +1151,7 @@ var Seclai = class {
1107
1151
  }, timeoutMs);
1108
1152
  const signal = anySignal([opts?.signal, timeoutController.signal]);
1109
1153
  let lastSeen;
1154
+ let reported;
1110
1155
  try {
1111
1156
  const init = { method: "POST", headers, body: JSON.stringify(runBody) };
1112
1157
  if (signal) init.signal = signal;
@@ -1135,7 +1180,14 @@ var Seclai = class {
1135
1180
  });
1136
1181
  }
1137
1182
  if (isJson) {
1138
- return await response.json();
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;
1139
1191
  }
1140
1192
  if (!response.body) {
1141
1193
  throw new SeclaiConfigurationError(
@@ -1147,31 +1199,48 @@ var Seclai = class {
1147
1199
  let final;
1148
1200
  const parser = createSseParser((msg) => {
1149
1201
  if (!msg.data) return;
1150
- if (msg.event === "init" || msg.event === "done") {
1202
+ if (msg.event === "init" || msg.event === "result" || msg.event === "done") {
1151
1203
  try {
1152
1204
  const parsed = JSON.parse(msg.data);
1153
1205
  lastSeen = parsed;
1206
+ if (msg.event === "result") reported = parsed;
1154
1207
  if (msg.event === "done") final = parsed;
1155
1208
  } catch {
1156
1209
  }
1157
1210
  }
1158
1211
  });
1159
- while (!final) {
1160
- const { value, done } = await reader.read();
1161
- if (done) break;
1162
- if (value) parser.feed(decoder.decode(value, { stream: true }));
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 }));
1218
+ }
1219
+ } catch (err) {
1220
+ if (opts?.signal?.aborted || !opts?.throwOnIncomplete && !timedOut) throw err;
1221
+ readFailure = err instanceof Error ? err.message : String(err);
1163
1222
  }
1223
+ parser.feed(decoder.decode());
1164
1224
  parser.end();
1165
1225
  if (final) return final;
1166
- if (lastSeen && lastSeen.status && lastSeen.status !== "pending") {
1226
+ if (opts?.returnOnResult && reported) {
1227
+ reader.cancel().catch(() => {
1228
+ });
1229
+ return reported;
1230
+ }
1231
+ if (!opts?.throwOnIncomplete && !timedOut && lastSeen?.status && lastSeen.status !== "pending") {
1167
1232
  return lastSeen;
1168
1233
  }
1169
- throw new SeclaiStreamingError("Stream ended before receiving a 'done' event.", lastSeen?.run_id);
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);
1170
1238
  } catch (err) {
1171
- if (timedOut) {
1239
+ if (timedOut && !opts?.signal?.aborted && !(err instanceof SeclaiStreamingError)) {
1172
1240
  throw new SeclaiStreamingError(
1173
1241
  `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`,
1174
- lastSeen?.run_id
1242
+ lastSeen?.run_id,
1243
+ reported ?? lastSeen
1175
1244
  );
1176
1245
  }
1177
1246
  throw err;
@@ -1193,6 +1262,10 @@ var Seclai = class {
1193
1262
  * @example
1194
1263
  * ```ts
1195
1264
  * for await (const event of client.runStreamingAgent("agent-id", { input: "Hello!" })) {
1265
+ * // `result` carries the answer in `output`, possibly before later steps finish.
1266
+ * if (event.event === "result") {
1267
+ * console.log("Answer:", (event.data as AgentRunResponse).output);
1268
+ * }
1196
1269
  * if (event.event === "done") {
1197
1270
  * console.log("Final:", event.data);
1198
1271
  * }
@@ -1296,11 +1369,38 @@ var Seclai = class {
1296
1369
  *
1297
1370
  * This is useful in environments where SSE streaming is unavailable.
1298
1371
  *
1372
+ * A run's answer can be ready before its last step finishes: once
1373
+ * `result_reported_at` is set, `output` holds the answer. Pass
1374
+ * `returnOnResult: true` to return as soon as a run has it set, the run
1375
+ * `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.
1378
+ * Such a run may still be in progress: its `status` is not terminal and the
1379
+ * run can still fail, so check `result_reported_at`, not `status`.
1380
+ *
1381
+ * 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`.
1392
+ *
1299
1393
  * @param agentId - Agent identifier.
1300
1394
  * @param body - Run request payload.
1301
1395
  * @param opts - Polling configuration and abort signal.
1302
- * @returns The terminal agent run.
1303
- * @throws {@link SeclaiStreamingError} On timeout.
1396
+ * @returns The terminal agent run, or, with `returnOnResult`, the first run
1397
+ * with `result_reported_at` set.
1398
+ * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run
1399
+ * 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`.
1304
1404
  */
1305
1405
  async runAgentAndPoll(agentId, body, opts) {
1306
1406
  const pollInterval = opts?.pollIntervalMs ?? 2e3;
@@ -1309,20 +1409,29 @@ var Seclai = class {
1309
1409
  const run = await this.runAgent(agentId, body);
1310
1410
  const runId = run.id ?? run.run_id;
1311
1411
  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 });
1417
+ }
1418
+ }
1312
1419
  while (true) {
1420
+ const status = current.status;
1421
+ if (status === "completed" || status === "failed" || status === "cancelled") {
1422
+ return current;
1423
+ }
1424
+ if (opts?.returnOnResult && current.result_reported_at) return current;
1313
1425
  if (opts?.signal?.aborted) throw new SeclaiError("Polling aborted.");
1314
1426
  if (Date.now() - startTime > timeout) {
1315
- throw new SeclaiStreamingError(`Polling timed out after ${timeout}ms.`, runId);
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);
1316
1429
  }
1317
1430
  await new Promise((r) => setTimeout(r, pollInterval));
1318
- const current = await this.getAgentRun(
1431
+ current = await this.getAgentRun(
1319
1432
  runId,
1320
1433
  opts?.includeStepOutputs ? { includeStepOutputs: true } : void 0
1321
1434
  );
1322
- const status = current.status;
1323
- if (status === "completed" || status === "failed" || status === "cancelled") {
1324
- return current;
1325
- }
1326
1435
  }
1327
1436
  }
1328
1437
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1684,8 +1793,9 @@ var Seclai = class {
1684
1793
  * Configure an agent's `SLACK_COMMAND` trigger, which people run from Slack
1685
1794
  * with `/seclai` or the message shortcut.
1686
1795
  *
1687
- * Sets the Slack connection, form, channels, reply visibility and conversation
1688
- * settings. Omitted fields are left unchanged.
1796
+ * Sets the Slack connection, `alias` (the name people type after `/seclai`),
1797
+ * form, channels, reply visibility and conversation settings. Omitted fields
1798
+ * are left unchanged. `input` is deprecated and ignored by the API.
1689
1799
  *
1690
1800
  * @param agentId - Agent identifier.
1691
1801
  * @param triggerId - Trigger identifier.
@@ -1715,6 +1825,40 @@ var Seclai = class {
1715
1825
  json: body
1716
1826
  });
1717
1827
  }
1828
+ /**
1829
+ * Get the run metadata keys a trigger declares.
1830
+ *
1831
+ * Steps may reference a declared key as `{{metadata.<key>}}`. The response
1832
+ * also lists the system and source keys the trigger's type can declare.
1833
+ *
1834
+ * @param agentId - Agent identifier.
1835
+ * @param triggerId - Trigger identifier, as `getAgent()` returns it.
1836
+ * @returns The trigger's declared and declarable metadata keys.
1837
+ */
1838
+ async getMetadataKeys(agentId, triggerId) {
1839
+ return await this.request(
1840
+ "GET",
1841
+ `/agents/${agentId}/triggers/${triggerId}/metadata-keys`
1842
+ );
1843
+ }
1844
+ /**
1845
+ * Replace the run metadata keys a trigger declares.
1846
+ *
1847
+ * The body is the whole declaration and replaces the current one. The API
1848
+ * answers 400 when the agent references a key that no trigger of its branch
1849
+ * declares.
1850
+ *
1851
+ * @param agentId - Agent identifier.
1852
+ * @param triggerId - Trigger identifier, as `getAgent()` returns it.
1853
+ * @param body - The full declaration; each key's `required` defaults to `false`.
1854
+ * @returns The trigger's metadata keys, with `warnings` naming agents whose
1855
+ * `call_agent` mapping no longer fits.
1856
+ */
1857
+ async setMetadataKeys(agentId, triggerId, body) {
1858
+ return await this.request("PUT", `/agents/${agentId}/triggers/${triggerId}/metadata-keys`, {
1859
+ json: body
1860
+ });
1861
+ }
1718
1862
  // ═══════════════════════════════════════════════════════════════════════════
1719
1863
  // Agent Email Governance
1720
1864
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1881,6 +2025,21 @@ var Seclai = class {
1881
2025
  async getKnowledgeBase(knowledgeBaseId) {
1882
2026
  return await this.request("GET", `/knowledge_bases/${knowledgeBaseId}`);
1883
2027
  }
2028
+ /**
2029
+ * Get the item-metadata keys seen in a knowledge base's content.
2030
+ *
2031
+ * Reports, for all time and the last 30 and 7 days, each key's item count,
2032
+ * number of distinct values and five most frequent values.
2033
+ *
2034
+ * @param knowledgeBaseId - Knowledge base identifier.
2035
+ * @returns The key statistics per window.
2036
+ */
2037
+ async getKnowledgeBaseMetadataKeyStats(knowledgeBaseId) {
2038
+ return await this.request(
2039
+ "GET",
2040
+ `/knowledge_bases/${knowledgeBaseId}/metadata-key-stats`
2041
+ );
2042
+ }
1884
2043
  /**
1885
2044
  * Update a knowledge base.
1886
2045
  *