@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/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.9.0] - 2026-11-05
4
+
5
+ ### Changed
6
+
7
+ - Sync the bundled OpenAPI spec and regenerate the types. Existing responses gain properties: `result_reported_at` on `AgentRunResponse`, set once the run's answer is in `output`, and `alias` on `SlackTriggerConfigResponse`
8
+ - Move `SeclaiApiVersion.Latest` to `2026-11-04`. Nothing is sent unless `apiVersion` is set, so a client that passes `SeclaiApiVersion.Latest` now opts into `2026-11-04`. From `2026-11-02`, `updateAgentDefinition()`, and `updateAgent()` when it sets `sampling_config`, refuse a definition or sampling rule that references a metadata key no trigger declares (with a 400 and a 422 respectively), where older versions declare the key as optional; from `2026-11-04`, `createEvaluationResult()` rejects `retry_triggered: true`, `updateAgent()` rejects `evaluation_mode` `eval_and_retry`, and `createEvaluationCriteria()` and `updateEvaluationCriteria()` reject a `step_id` that does not name a `display_result` or `streaming_result` step, each with a 400
9
+ - Note API changes that apply on every API version, whatever `apiVersion` is set: a run started with `runAgent()`, `runStreamingAgent()` or the helpers built on them is refused with a 400 when its `metadata` sends a custom key the trigger does not declare, or lacks a required one, so declare custom keys with `setMetadataKeys()` before sending them; `updateAgentDefinition()` rejects a definition holding a `gate` or `retry` step (use `if_else`, or `repeat_until` to run steps again until a condition holds); the `agent_eval_fail` rollback trigger is accepted and never fires, and the default rollback triggers no longer include it; `max_retries` and `retry_on_failure` on `updateAgent()` are accepted and have no effect; and `evaluation_mode` on `AgentSummaryResponse` defaults to `sample_and_flag` instead of `eval_and_retry`
10
+ - Check the `runAgent()` response in `runAgentAndPoll()` before polling, so a run that ended at once is returned without waiting one `pollIntervalMs`. After an abort through `signal` during the start request, that run is now returned instead of throwing `Polling aborted.`, and with `includeStepOutputs` it comes back without step outputs. When `timeoutMs` elapses during the start request, that run is also returned, where `SeclaiStreamingError` was thrown
11
+ - Mark `input` on `SetSlackTriggerConfigRequest` deprecated. The API ignores it: a Slack run's input is the text after `/seclai <alias>`, or the message the shortcut was used on. It stays on the type so existing calls still compile
12
+ - Mark `max_retries` and `retry_on_failure` on `UpdateAgentRequest`, and `retry_count` and `retry_triggered` on `CreateEvaluationResultRequest`, deprecated. They have no effect, and from `2026-11-04` `retry_triggered: true` returns a 400. They stay on the types so existing calls still compile
13
+
14
+ ### Added
15
+
16
+ - Add `getMetadataKeys()` and `setMetadataKeys()` to read and replace the run metadata keys an agent trigger declares, which steps reference as `{{metadata.<key>}}`. A key's `required` defaults to `false` and can be omitted
17
+ - Add `getKnowledgeBaseMetadataKeyStats()` to see which item-metadata keys a knowledge base's content carries, with item counts and top values for all time and the last 30 and 7 days
18
+ - Accept `alias` on `setSlackTriggerConfig()`, the name people type after `/seclai` to run the agent
19
+ - Add the `returnOnResult` option to `runAgentAndPoll()` and `runStreamingAgentAndWait()`, to return as soon as a run has `result_reported_at` set (from `runAgent()` or a poll), or a `result` event arrives, without waiting for later steps. The run may still be in progress and can still fail
20
+ - Add the `throwOnIncomplete` option to `runStreamingAgentAndWait()`, to throw `SeclaiStreamingError`, with the latest snapshot in `run`, when the stream ends or breaks before `done`, or the server answers with plain JSON for a run that has not finished, instead of returning a run that has not finished or throwing the fetch error. It will become the default in the next major version
21
+ - Add `run` to `SeclaiStreamingError`: the latest snapshot of the unfinished run when `runStreamingAgentAndWait()` or `runAgentAndPoll()` gives up, so a reported answer in `output` is not lost
22
+ - Add the `SeclaiApiVersion.V2026_11_02` and `SeclaiApiVersion.V2026_11_04` constants, so those versions are accepted as `apiVersion`
23
+ - Add the type exports `MetadataOrigin`, `MetadataKeyDeclaration`, `MetadataKeyDeclarationInput`, `SetMetadataKeysRequest`, `DeclarableMetadataKey`, `MetadataKeysResponse`, `KnowledgeBaseMetadataKeyStatsResponse`, `MetadataKeyWindowResponse`, `MetadataKeyCountResponse` and `MetadataValueCountResponse`
24
+
3
25
  ## [1.8.0] - 2026-10-31
4
26
 
5
27
  ### Changed
@@ -270,6 +292,7 @@ _Stable release. No functional changes since 0.0.1._
270
292
 
271
293
  _Initial release._
272
294
 
295
+ [1.9.0]: https://github.com/seclai/seclai-javascript/releases/tag/1.9.0
273
296
  [1.8.0]: https://github.com/seclai/seclai-javascript/releases/tag/1.8.0
274
297
  [1.7.0]: https://github.com/seclai/seclai-javascript/releases/tag/1.7.0
275
298
  [1.6.1]: https://github.com/seclai/seclai-javascript/releases/tag/1.6.1
package/README.md CHANGED
@@ -104,7 +104,7 @@ or set environment variables:
104
104
 
105
105
  Online API documentation (latest):
106
106
 
107
- https://seclai.github.io/seclai-javascript/1.8.0/
107
+ https://seclai.github.io/seclai-javascript/1.9.0/
108
108
 
109
109
  Release history is in [`CHANGELOG.md`](CHANGELOG.md).
110
110
 
@@ -127,7 +127,7 @@ Leave `apiVersion` unset and the header is omitted, so the account's pinned
127
127
  baseline applies and responses keep their current shapes. Upgrading this package
128
128
  alone never changes the wire contract.
129
129
 
130
- Known versions are on `SeclaiApiVersion` (`V2026_07_01` through `V2026_10_28`,
130
+ Known versions are on `SeclaiApiVersion` (`V2026_07_01` through `V2026_11_04`,
131
131
  plus `Default` and `Latest`), imported from `@seclai/sdk`. A version this release was
132
132
  **not** built against throws at construction: a newer version can reshape
133
133
  responses, and this client would decode them incorrectly rather than reject them.
@@ -190,6 +190,9 @@ a request that used to succeed, or (from `2026-10-21`) which fields can be
190
190
  returns `null` `score` and `passed` for one.
191
191
  - `2026-10-28` changes what an `if_else` or `switch` step's `output` contains.
192
192
  Read the arm it took from the step's `decision`, which is set on every version.
193
+ - `2026-11-02` refuses an agent write that references a metadata key no trigger
194
+ declares, where older versions declare the key for you.
195
+ - `2026-11-04` rejects with a 400 evaluation settings that were accepted before.
193
196
 
194
197
  | Version | What it changes |
195
198
  | --- | --- |
@@ -205,6 +208,8 @@ a request that used to succeed, or (from `2026-10-21`) which fields can be
205
208
  | `2026-10-19` | `createSource()` rejects `polling_max_items` on any source type but an RSS feed with a 400. Below it the value is stored |
206
209
  | `2026-10-21` | An evaluation result whose evaluator returned no verdict (`error`) is left out of `failed` and of `pass_rate` / `failure_rate` in `getNonManualEvaluationSummary()`, and `getEvaluationCriteriaSummary()` averages `average_score` over passed and failed results only. `testDraftEvaluation()` returns `score` and `passed` as `null` for an `error` result. Below it the summary counts `error` results in `failed` and the rates, `average_score` includes their stored scores, and the test draft returns `score` 0.5 and `passed: false`. The summary's `error` count is returned on every version |
207
210
  | `2026-10-28` | An `if_else` or `switch` step's `output` is the result of the arm it took, or its input when that arm is empty or it took none. Below it the `output` is a `{"branch": ...}` marker naming the arm, with no `attachments`. The step's `decision` names the arm on every version |
211
+ | `2026-11-02` | `updateAgentDefinition()`, and `updateAgent()` when it sets `sampling_config`, refuse a definition or sampling rule that references a metadata key no trigger declares, with a 400 and a 422 respectively. Declare the key first with `setMetadataKeys()`. An `agent_definition` import through `createAgent()` or `updateAgent()` is not refused and still declares the keys it reads. Below it each such key is declared on the trigger as optional |
212
+ | `2026-11-04` | `createEvaluationResult()` rejects `retry_triggered: true` and `updateAgent()` rejects `evaluation_mode` `eval_and_retry` with a 400: evaluations never retry a step. `createEvaluationCriteria()`, and `updateEvaluationCriteria()` when it changes `step_id`, reject a `step_id` that does not name a `display_result` or `streaming_result` step with a 400. Below it `eval_and_retry` is stored as `sample_and_flag` |
208
213
 
209
214
  **`Latest` moves with the SDK.** `SeclaiApiVersion.Latest` is the newest version
210
215
  the installed release knows, so upgrading the package can opt a client that
@@ -212,8 +217,10 @@ passes it into every version added since — `1.6.0` moved it from `2026-07-27`
212
217
  `2026-10-03`, across the `2026-09-30` output change, and `1.7.0` moves it to
213
218
  `2026-10-21`, across the `2026-10-05` status change, the `2026-10-13` and
214
219
  `2026-10-19` source-setting rejections, the `2026-10-16` input change and the
215
- `2026-10-21` evaluation change, and `1.8.0` moves it to `2026-10-28`,
216
- across the `if_else` / `switch` step-output change. Pass a
220
+ `2026-10-21` evaluation change, `1.8.0` moves it to `2026-10-28`,
221
+ across the `if_else` / `switch` step-output change, and `1.9.0` moves it to
222
+ `2026-11-04`, across the `2026-11-02` undeclared-metadata-key refusal and the
223
+ `2026-11-04` evaluation-setting rejections. Pass a
217
224
  dated constant such as `SeclaiApiVersion.V2026_07_27` to keep behaviour fixed
218
225
  across upgrades.
219
226
 
@@ -354,13 +361,25 @@ await client.deleteAgentRun("run_id");
354
361
 
355
362
  The SDK provides two streaming patterns over the SSE `/runs/stream` endpoint:
356
363
 
357
- **Block until done** — returns the final `done` payload or throws on timeout:
364
+ **Block until done** — returns the run from the `done` event. If `timeoutMs`
365
+ elapses first, it throws `SeclaiStreamingError`, whose `run` holds the latest
366
+ snapshot: the `result` snapshot if one arrived, else the `init` snapshot. An
367
+ abort through `signal` rethrows the abort error.
358
368
 
369
+ By default, a stream that ends before `done` returns the latest snapshot when
370
+ its status is not `pending`, so the run returned may not have finished: check
371
+ `status` and `result_reported_at`. A stream that breaks throws the fetch error.
372
+ Pass `throwOnIncomplete: true` to throw `SeclaiStreamingError`, with the snapshot
373
+ in `run`, in both cases instead, and also when the server answers with plain
374
+ JSON for a run that has not finished. It is recommended, and becomes the default in
375
+ the next major version:
376
+
377
+ <!-- sdksync:check -->
359
378
  ```ts
360
379
  const result = await client.runStreamingAgentAndWait(
361
380
  "agent_id",
362
381
  { input: "Hello", metadata: {} },
363
- { timeoutMs: 60_000 },
382
+ { timeoutMs: 60_000, throwOnIncomplete: true },
364
383
  );
365
384
  ```
366
385
 
@@ -377,6 +396,40 @@ for await (const event of client.runStreamingAgent(
377
396
  }
378
397
  ```
379
398
 
399
+ When the server answers with plain JSON instead of an SSE stream,
400
+ `runStreamingAgent` yields only a `done` event, so read the answer from it.
401
+
402
+ A `result` event carries the run's answer in `output` once `result_reported_at`
403
+ is set. It comes before `done`, and for an agent that reports its result early it
404
+ can arrive while later steps still run. Pass `returnOnResult: true` to
405
+ `runStreamingAgentAndWait` to return that `result` snapshot without waiting for
406
+ `done`. Such a run may still be in progress: its `status` is not terminal and the
407
+ run can still fail, so check `result_reported_at`, not `status`:
408
+
409
+ <!-- sdksync:check -->
410
+ ```ts
411
+ const run = await client.runStreamingAgentAndWait("agent_id", { input: "Hello" }, { returnOnResult: true });
412
+ if (run.result_reported_at) console.log(run.output);
413
+ ```
414
+
415
+ On a timeout, or with `throwOnIncomplete` on a cut stream, read the answer, if
416
+ one was reported, from the error's `run`:
417
+
418
+ ```ts
419
+ import { SeclaiStreamingError } from "@seclai/sdk";
420
+
421
+ try {
422
+ const run = await client.runStreamingAgentAndWait("agent_id", { input: "Hello" }, { throwOnIncomplete: true });
423
+ console.log(run.output);
424
+ } catch (err) {
425
+ if (err instanceof SeclaiStreamingError && err.run?.result_reported_at) {
426
+ console.log("Answer, run not finished:", err.run.output);
427
+ } else {
428
+ throw err;
429
+ }
430
+ }
431
+ ```
432
+
380
433
  Pass `include_reasoning: true` to also receive `stream_reasoning` events carrying
381
434
  the model's reasoning while it thinks. They are sent only for a
382
435
  `streaming_result` step whose author enabled `show_reasoning`, and reasoning is
@@ -404,6 +457,23 @@ const result = await client.runAgentAndPoll(
404
457
  );
405
458
  ```
406
459
 
460
+ A run's answer can be ready before its last step finishes: once
461
+ `result_reported_at` is set on `getAgentRun()`, `output` holds the answer. Pass
462
+ `returnOnResult: true` to return as soon as a run has it set, the one
463
+ `runAgent()` returns included. With `includeStepOutputs`, when that run would end
464
+ the poll and `signal` is not aborted, it is fetched again at once, because the
465
+ `runAgent()` response carries no step outputs; after an abort it comes back
466
+ without step outputs. Such a run may still be in progress: its `status`
467
+ is not terminal and the run can still fail, so check `result_reported_at`, not
468
+ `status`. If `timeoutMs` elapses first, it throws `SeclaiStreamingError` with the
469
+ latest run it has (the `runAgent()` response if no poll ran) in `run`.
470
+
471
+ <!-- sdksync:check -->
472
+ ```ts
473
+ const run = await client.runAgentAndPoll("agent_id", { input: "Hello" }, { returnOnResult: true });
474
+ if (run.result_reported_at) console.log(run.output);
475
+ ```
476
+
407
477
  ### Agent input uploads
408
478
 
409
479
  <!-- sdksync:check -->
@@ -465,11 +535,15 @@ are listed in the run's `email_attachment_issues` metadata. By default the run f
465
535
  ### Agent Slack triggers
466
536
 
467
537
  Configure an agent's `SLACK_COMMAND` trigger, which people run from Slack with
468
- `/seclai` or the message shortcut. Omitted fields are left unchanged.
538
+ `/seclai <alias>` or the message shortcut. Omitted fields are left unchanged.
539
+ `alias` is generated from the agent's name when not set; the text after the alias,
540
+ or the message the shortcut was used on, is the run's input. `input` is
541
+ deprecated and ignored by the API.
469
542
 
470
543
  <!-- sdksync:check -->
471
544
  ```ts
472
545
  const slack = await client.setSlackTriggerConfig("agent_id", "trigger_id", {
546
+ alias: "support", // people run `/seclai support`
473
547
  scope: "selected_channels", // or "bot_channels"
474
548
  channel_ids: ["C0123456789"],
475
549
  activation: "everywhere", // or "channel_opt_in"
@@ -505,6 +579,33 @@ const { accepted_attachments } = await client.setAcceptedAttachments("agent_id",
505
579
  console.log(accepted_attachments.map((slot) => `${slot.name}: ${slot.min}..${slot.max ?? "any"}`));
506
580
  ```
507
581
 
582
+ ### Trigger metadata keys
583
+
584
+ Declare the run metadata keys a trigger provides, which steps reference as
585
+ `{{metadata.<key>}}`. `system` and `source` keys are written by the platform;
586
+ `custom` keys are sent by the caller or set on the trigger, and only a `custom`
587
+ key can be `required` (default `false`): a caller-started run without it is
588
+ refused. A run is also refused with a 400 when its `metadata` sends a custom key
589
+ the trigger does not declare, on every API version, so declare custom keys with
590
+ `setMetadataKeys()` before sending them in a run's `metadata`. The call replaces
591
+ the whole declaration, and is refused with a 400 when the agent references a key
592
+ no trigger of its branch declares.
593
+
594
+ <!-- sdksync:check -->
595
+ ```ts
596
+ const agent = await client.getAgent("agent_id");
597
+ const current = await client.getMetadataKeys("agent_id", agent.trigger_id!);
598
+ console.log(current.declarable_keys.map((k) => `${k.key} (${k.origin})`));
599
+
600
+ const updated = await client.setMetadataKeys("agent_id", agent.trigger_id!, {
601
+ metadata_keys: [
602
+ { key: "customer_id", origin: "custom", required: true },
603
+ { key: "region", origin: "custom" },
604
+ ],
605
+ });
606
+ console.log(updated.warnings); // agents whose `call_agent` mapping no longer fits
607
+ ```
608
+
508
609
  ### Agent email governance
509
610
 
510
611
  ```ts
@@ -585,6 +686,17 @@ await client.updateKnowledgeBase("kb_id", { name: "Renamed KB" });
585
686
  await client.deleteKnowledgeBase("kb_id");
586
687
  ```
587
688
 
689
+ See which item-metadata keys a knowledge base's content carries, for all time
690
+ and the last 30 and 7 days:
691
+
692
+ <!-- sdksync:check -->
693
+ ```ts
694
+ const stats = await client.getKnowledgeBaseMetadataKeyStats("kb_id");
695
+ for (const w of stats.windows) {
696
+ console.log(w.window, w.total_items, w.keys.map((k) => `${k.key}: ${k.items}`));
697
+ }
698
+ ```
699
+
588
700
  ### Memory banks
589
701
 
590
702
  ```ts
package/dist/index.cjs CHANGED
@@ -65,10 +65,12 @@ var SeclaiApiVersion = {
65
65
  V2026_10_19: "2026-10-19",
66
66
  V2026_10_21: "2026-10-21",
67
67
  V2026_10_28: "2026-10-28",
68
+ V2026_11_02: "2026-11-02",
69
+ V2026_11_04: "2026-11-04",
68
70
  /** Baseline applied to an unpinned, header-less caller. */
69
71
  Default: "2026-07-01",
70
72
  /** Newest version known to this SDK release. May lag the server. */
71
- Latest: "2026-10-28"
73
+ Latest: "2026-11-04"
72
74
  };
73
75
  var KNOWN_API_VERSIONS = Object.entries(SeclaiApiVersion).filter(([k]) => k.startsWith("V")).map(([, v]) => v);
74
76
 
@@ -115,10 +117,17 @@ var SeclaiAPIValidationError = class extends SeclaiAPIStatusError {
115
117
  var SeclaiStreamingError = class extends SeclaiError {
116
118
  /** The run ID associated with the failed stream, when available. */
117
119
  runId;
118
- constructor(message, runId) {
120
+ /**
121
+ * Set by `runStreamingAgentAndWait()` and `runAgentAndPoll()` to the latest
122
+ * run they had, if any (when it has `result_reported_at` set, its `output`
123
+ * is the answer). The run may still be in progress, and can still fail.
124
+ */
125
+ run;
126
+ constructor(message, runId, run) {
119
127
  super(message);
120
128
  this.name = "SeclaiStreamingError";
121
129
  this.runId = runId;
130
+ this.run = run;
122
131
  }
123
132
  };
124
133
 
@@ -1134,11 +1143,46 @@ var Seclai = class {
1134
1143
  * takes no `include_reasoning`, and one passed anyway is not sent: this method
1135
1144
  * returns no `stream_reasoning` events.
1136
1145
  *
1146
+ * A `result` event carries the run's answer in `output` once
1147
+ * `result_reported_at` is set, and can arrive while later steps still run.
1148
+ * Pass `returnOnResult: true` to return that `result` snapshot as soon as it
1149
+ * arrives, without waiting for `done`. Such a run may still be in progress:
1150
+ * its `status` is not terminal and the run can still fail, so check
1151
+ * `result_reported_at`, not `status`.
1152
+ *
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.
1156
+ *
1157
+ * 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.
1164
+ *
1137
1165
  * @param agentId - Agent identifier.
1138
1166
  * @param body - Streaming run request payload, without `include_reasoning`.
1139
- * @param opts - Timeout and abort signal options.
1140
- * @returns Final agent run payload from the `done` event.
1141
- * @throws {@link SeclaiStreamingError} If the stream ends before a `done` event.
1167
+ * @param opts - Timeout, abort signal and `returnOnResult` options.
1168
+ * @returns The run from the `done` event; with `returnOnResult`, the
1169
+ * `result` snapshot; without `throwOnIncomplete`, possibly an unfinished
1170
+ * 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.
1174
+ *
1175
+ * @example
1176
+ * ```ts
1177
+ * try {
1178
+ * const run = await client.runStreamingAgentAndWait("agent-id", { input: "Hello" }, { throwOnIncomplete: true });
1179
+ * console.log(run.output);
1180
+ * } catch (err) {
1181
+ * if (err instanceof SeclaiStreamingError && err.run?.result_reported_at) {
1182
+ * console.log("Answer (run not finished):", err.run.output);
1183
+ * } else throw err;
1184
+ * }
1185
+ * ```
1142
1186
  */
1143
1187
  async runStreamingAgentAndWait(agentId, body, opts) {
1144
1188
  const { include_reasoning: _ignored, ...runBody } = body;
@@ -1158,6 +1202,7 @@ var Seclai = class {
1158
1202
  }, timeoutMs);
1159
1203
  const signal = anySignal([opts?.signal, timeoutController.signal]);
1160
1204
  let lastSeen;
1205
+ let reported;
1161
1206
  try {
1162
1207
  const init = { method: "POST", headers, body: JSON.stringify(runBody) };
1163
1208
  if (signal) init.signal = signal;
@@ -1186,7 +1231,14 @@ var Seclai = class {
1186
1231
  });
1187
1232
  }
1188
1233
  if (isJson) {
1189
- return await response.json();
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;
1190
1242
  }
1191
1243
  if (!response.body) {
1192
1244
  throw new SeclaiConfigurationError(
@@ -1198,31 +1250,48 @@ var Seclai = class {
1198
1250
  let final;
1199
1251
  const parser = createSseParser((msg) => {
1200
1252
  if (!msg.data) return;
1201
- if (msg.event === "init" || msg.event === "done") {
1253
+ if (msg.event === "init" || msg.event === "result" || msg.event === "done") {
1202
1254
  try {
1203
1255
  const parsed = JSON.parse(msg.data);
1204
1256
  lastSeen = parsed;
1257
+ if (msg.event === "result") reported = parsed;
1205
1258
  if (msg.event === "done") final = parsed;
1206
1259
  } catch {
1207
1260
  }
1208
1261
  }
1209
1262
  });
1210
- while (!final) {
1211
- const { value, done } = await reader.read();
1212
- if (done) break;
1213
- if (value) parser.feed(decoder.decode(value, { stream: true }));
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 }));
1269
+ }
1270
+ } catch (err) {
1271
+ if (opts?.signal?.aborted || !opts?.throwOnIncomplete && !timedOut) throw err;
1272
+ readFailure = err instanceof Error ? err.message : String(err);
1214
1273
  }
1274
+ parser.feed(decoder.decode());
1215
1275
  parser.end();
1216
1276
  if (final) return final;
1217
- if (lastSeen && lastSeen.status && lastSeen.status !== "pending") {
1277
+ if (opts?.returnOnResult && reported) {
1278
+ reader.cancel().catch(() => {
1279
+ });
1280
+ return reported;
1281
+ }
1282
+ if (!opts?.throwOnIncomplete && !timedOut && lastSeen?.status && lastSeen.status !== "pending") {
1218
1283
  return lastSeen;
1219
1284
  }
1220
- throw new SeclaiStreamingError("Stream ended before receiving a 'done' event.", lastSeen?.run_id);
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);
1221
1289
  } catch (err) {
1222
- if (timedOut) {
1290
+ if (timedOut && !opts?.signal?.aborted && !(err instanceof SeclaiStreamingError)) {
1223
1291
  throw new SeclaiStreamingError(
1224
1292
  `Timed out after ${timeoutMs}ms waiting for streaming agent run to complete.`,
1225
- lastSeen?.run_id
1293
+ lastSeen?.run_id,
1294
+ reported ?? lastSeen
1226
1295
  );
1227
1296
  }
1228
1297
  throw err;
@@ -1244,6 +1313,10 @@ var Seclai = class {
1244
1313
  * @example
1245
1314
  * ```ts
1246
1315
  * for await (const event of client.runStreamingAgent("agent-id", { input: "Hello!" })) {
1316
+ * // `result` carries the answer in `output`, possibly before later steps finish.
1317
+ * if (event.event === "result") {
1318
+ * console.log("Answer:", (event.data as AgentRunResponse).output);
1319
+ * }
1247
1320
  * if (event.event === "done") {
1248
1321
  * console.log("Final:", event.data);
1249
1322
  * }
@@ -1347,11 +1420,38 @@ var Seclai = class {
1347
1420
  *
1348
1421
  * This is useful in environments where SSE streaming is unavailable.
1349
1422
  *
1423
+ * A run's answer can be ready before its last step finishes: once
1424
+ * `result_reported_at` is set, `output` holds the answer. Pass
1425
+ * `returnOnResult: true` to return as soon as a run has it set, the run
1426
+ * `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.
1429
+ * Such a run may still be in progress: its `status` is not terminal and the
1430
+ * run can still fail, so check `result_reported_at`, not `status`.
1431
+ *
1432
+ * 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`.
1443
+ *
1350
1444
  * @param agentId - Agent identifier.
1351
1445
  * @param body - Run request payload.
1352
1446
  * @param opts - Polling configuration and abort signal.
1353
- * @returns The terminal agent run.
1354
- * @throws {@link SeclaiStreamingError} On timeout.
1447
+ * @returns The terminal agent run, or, with `returnOnResult`, the first run
1448
+ * with `result_reported_at` set.
1449
+ * @throws {@link SeclaiStreamingError} If `timeoutMs` elapses before the run
1450
+ * 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`.
1355
1455
  */
1356
1456
  async runAgentAndPoll(agentId, body, opts) {
1357
1457
  const pollInterval = opts?.pollIntervalMs ?? 2e3;
@@ -1360,20 +1460,29 @@ var Seclai = class {
1360
1460
  const run = await this.runAgent(agentId, body);
1361
1461
  const runId = run.id ?? run.run_id;
1362
1462
  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 });
1468
+ }
1469
+ }
1363
1470
  while (true) {
1471
+ const status = current.status;
1472
+ if (status === "completed" || status === "failed" || status === "cancelled") {
1473
+ return current;
1474
+ }
1475
+ if (opts?.returnOnResult && current.result_reported_at) return current;
1364
1476
  if (opts?.signal?.aborted) throw new SeclaiError("Polling aborted.");
1365
1477
  if (Date.now() - startTime > timeout) {
1366
- throw new SeclaiStreamingError(`Polling timed out after ${timeout}ms.`, runId);
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);
1367
1480
  }
1368
1481
  await new Promise((r) => setTimeout(r, pollInterval));
1369
- const current = await this.getAgentRun(
1482
+ current = await this.getAgentRun(
1370
1483
  runId,
1371
1484
  opts?.includeStepOutputs ? { includeStepOutputs: true } : void 0
1372
1485
  );
1373
- const status = current.status;
1374
- if (status === "completed" || status === "failed" || status === "cancelled") {
1375
- return current;
1376
- }
1377
1486
  }
1378
1487
  }
1379
1488
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1735,8 +1844,9 @@ var Seclai = class {
1735
1844
  * Configure an agent's `SLACK_COMMAND` trigger, which people run from Slack
1736
1845
  * with `/seclai` or the message shortcut.
1737
1846
  *
1738
- * Sets the Slack connection, form, channels, reply visibility and conversation
1739
- * settings. Omitted fields are left unchanged.
1847
+ * Sets the Slack connection, `alias` (the name people type after `/seclai`),
1848
+ * form, channels, reply visibility and conversation settings. Omitted fields
1849
+ * are left unchanged. `input` is deprecated and ignored by the API.
1740
1850
  *
1741
1851
  * @param agentId - Agent identifier.
1742
1852
  * @param triggerId - Trigger identifier.
@@ -1766,6 +1876,40 @@ var Seclai = class {
1766
1876
  json: body
1767
1877
  });
1768
1878
  }
1879
+ /**
1880
+ * Get the run metadata keys a trigger declares.
1881
+ *
1882
+ * Steps may reference a declared key as `{{metadata.<key>}}`. The response
1883
+ * also lists the system and source keys the trigger's type can declare.
1884
+ *
1885
+ * @param agentId - Agent identifier.
1886
+ * @param triggerId - Trigger identifier, as `getAgent()` returns it.
1887
+ * @returns The trigger's declared and declarable metadata keys.
1888
+ */
1889
+ async getMetadataKeys(agentId, triggerId) {
1890
+ return await this.request(
1891
+ "GET",
1892
+ `/agents/${agentId}/triggers/${triggerId}/metadata-keys`
1893
+ );
1894
+ }
1895
+ /**
1896
+ * Replace the run metadata keys a trigger declares.
1897
+ *
1898
+ * The body is the whole declaration and replaces the current one. The API
1899
+ * answers 400 when the agent references a key that no trigger of its branch
1900
+ * declares.
1901
+ *
1902
+ * @param agentId - Agent identifier.
1903
+ * @param triggerId - Trigger identifier, as `getAgent()` returns it.
1904
+ * @param body - The full declaration; each key's `required` defaults to `false`.
1905
+ * @returns The trigger's metadata keys, with `warnings` naming agents whose
1906
+ * `call_agent` mapping no longer fits.
1907
+ */
1908
+ async setMetadataKeys(agentId, triggerId, body) {
1909
+ return await this.request("PUT", `/agents/${agentId}/triggers/${triggerId}/metadata-keys`, {
1910
+ json: body
1911
+ });
1912
+ }
1769
1913
  // ═══════════════════════════════════════════════════════════════════════════
1770
1914
  // Agent Email Governance
1771
1915
  // ═══════════════════════════════════════════════════════════════════════════
@@ -1932,6 +2076,21 @@ var Seclai = class {
1932
2076
  async getKnowledgeBase(knowledgeBaseId) {
1933
2077
  return await this.request("GET", `/knowledge_bases/${knowledgeBaseId}`);
1934
2078
  }
2079
+ /**
2080
+ * Get the item-metadata keys seen in a knowledge base's content.
2081
+ *
2082
+ * Reports, for all time and the last 30 and 7 days, each key's item count,
2083
+ * number of distinct values and five most frequent values.
2084
+ *
2085
+ * @param knowledgeBaseId - Knowledge base identifier.
2086
+ * @returns The key statistics per window.
2087
+ */
2088
+ async getKnowledgeBaseMetadataKeyStats(knowledgeBaseId) {
2089
+ return await this.request(
2090
+ "GET",
2091
+ `/knowledge_bases/${knowledgeBaseId}/metadata-key-stats`
2092
+ );
2093
+ }
1935
2094
  /**
1936
2095
  * Update a knowledge base.
1937
2096
  *