@silmaril-security/sdk 0.9.0 → 0.10.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +200 -24
  3. package/dist/adapters/deepagents.cjs +255 -42
  4. package/dist/adapters/deepagents.cjs.map +1 -1
  5. package/dist/adapters/deepagents.d.cts +9 -5
  6. package/dist/adapters/deepagents.d.ts +9 -5
  7. package/dist/adapters/deepagents.js +261 -43
  8. package/dist/adapters/deepagents.js.map +1 -1
  9. package/dist/adapters/langchain.cjs +153 -32
  10. package/dist/adapters/langchain.cjs.map +1 -1
  11. package/dist/adapters/langchain.d.cts +1 -1
  12. package/dist/adapters/langchain.d.ts +1 -1
  13. package/dist/adapters/langchain.js +153 -32
  14. package/dist/adapters/langchain.js.map +1 -1
  15. package/dist/adapters/vercel-v4.cjs +700 -0
  16. package/dist/adapters/vercel-v4.cjs.map +1 -0
  17. package/dist/adapters/vercel-v4.d.cts +79 -0
  18. package/dist/adapters/vercel-v4.d.ts +79 -0
  19. package/dist/adapters/vercel-v4.js +670 -0
  20. package/dist/adapters/vercel-v4.js.map +1 -0
  21. package/dist/adapters/vercel.cjs +41 -15
  22. package/dist/adapters/vercel.cjs.map +1 -1
  23. package/dist/adapters/vercel.d.cts +1 -1
  24. package/dist/adapters/vercel.d.ts +1 -1
  25. package/dist/adapters/vercel.js +41 -15
  26. package/dist/adapters/vercel.js.map +1 -1
  27. package/dist/{firewall-Bv5y03P0.d.cts → firewall-BXM2BWEr.d.cts} +60 -1
  28. package/dist/{firewall-Bv5y03P0.d.ts → firewall-BXM2BWEr.d.ts} +60 -1
  29. package/dist/index.cjs +451 -50
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +2 -2
  32. package/dist/index.d.ts +2 -2
  33. package/dist/index.js +451 -50
  34. package/dist/index.js.map +1 -1
  35. package/package.json +21 -5
package/dist/index.cjs CHANGED
@@ -200,7 +200,8 @@ var init_hooks = __esm({
200
200
  FirewallHook.LLM_START,
201
201
  FirewallHook.CHAT_MODEL_START,
202
202
  FirewallHook.TOOL_START,
203
- FirewallHook.TOOL_END
203
+ FirewallHook.TOOL_END,
204
+ FirewallHook.LLM_END
204
205
  ]);
205
206
  INPUT_HOOKS = /* @__PURE__ */ new Set([
206
207
  FirewallHook.LLM_START,
@@ -243,6 +244,216 @@ var init_modes = __esm({
243
244
  }
244
245
  });
245
246
 
247
+ // src/pending.ts
248
+ function retryBudget(maxRetries) {
249
+ return Math.min(maxRetries, retryLimit.getStore() ?? maxRetries);
250
+ }
251
+ function conversationId(metadata) {
252
+ const value = metadata?.conversationId;
253
+ return typeof value === "string" && value.length > 0 ? value : void 0;
254
+ }
255
+ function validateLimit(name, value) {
256
+ if (!Number.isSafeInteger(value) || value < 1) {
257
+ throw new Error(`Firewall: ${name} must be a positive integer, got ${value}`);
258
+ }
259
+ return value;
260
+ }
261
+ function reportBackground(message, error) {
262
+ console.warn(`silmaril.firewall: ${message}`, ...error === void 0 ? [] : [error]);
263
+ }
264
+ function settled(gate, signal) {
265
+ return new Promise((resolve, reject) => {
266
+ const onAbort = () => reject(signal?.reason);
267
+ signal?.addEventListener("abort", onAbort, { once: true });
268
+ void gate.then(() => {
269
+ signal?.removeEventListener("abort", onAbort);
270
+ resolve();
271
+ });
272
+ });
273
+ }
274
+ async function alongside(check, run, discard = () => void 0) {
275
+ const running = Promise.resolve().then(run);
276
+ try {
277
+ const [result] = await Promise.all([running, check]);
278
+ return result;
279
+ } catch (error) {
280
+ running.then(discard, () => void 0);
281
+ throw error;
282
+ }
283
+ }
284
+ var import_node_async_hooks, DEFAULT_MAX_CONCURRENT, DEFAULT_MAX_QUEUED, BACKGROUND_RETRIES, retryLimit, PendingVerdicts, Deferred;
285
+ var init_pending = __esm({
286
+ "src/pending.ts"() {
287
+ "use strict";
288
+ import_node_async_hooks = require("async_hooks");
289
+ DEFAULT_MAX_CONCURRENT = 32;
290
+ DEFAULT_MAX_QUEUED = 64;
291
+ BACKGROUND_RETRIES = 1;
292
+ retryLimit = new import_node_async_hooks.AsyncLocalStorage();
293
+ PendingVerdicts = class {
294
+ constructor(maxConcurrent, maxQueued) {
295
+ this.maxConcurrent = maxConcurrent;
296
+ this.maxQueued = maxQueued;
297
+ }
298
+ maxConcurrent;
299
+ maxQueued;
300
+ gates = /* @__PURE__ */ new Map();
301
+ depths = /* @__PURE__ */ new Map();
302
+ outstanding = /* @__PURE__ */ new Set();
303
+ waiting = [];
304
+ running = 0;
305
+ background = 0;
306
+ /**
307
+ * Start a classification the caller joins by awaiting the returned promise.
308
+ * An aborted signal stops it waiting for its turn; later classifications keep their order.
309
+ */
310
+ submit(call, conversation, signal) {
311
+ const pending = this.start(call, conversation, signal);
312
+ pending.catch(() => void 0);
313
+ return pending;
314
+ }
315
+ /** Start a classification nobody joins; failures are reported, never thrown. */
316
+ observe(call, conversation) {
317
+ const conversationFull = conversation !== void 0 && (this.depths.get(conversation) ?? 0) >= this.maxQueued;
318
+ if (conversationFull || this.background >= this.maxConcurrent * this.maxQueued) {
319
+ reportBackground("dropped background classification: queue is full");
320
+ return Promise.resolve(void 0);
321
+ }
322
+ this.background++;
323
+ const pending = this.start(() => retryLimit.run(BACKGROUND_RETRIES, call), conversation, void 0);
324
+ const release = () => {
325
+ this.background--;
326
+ };
327
+ pending.then(release, release);
328
+ return pending.catch((error) => {
329
+ reportBackground("background classification failed", error);
330
+ return void 0;
331
+ });
332
+ }
333
+ /** Wait until every classification started so far has finished. */
334
+ async drain() {
335
+ while (this.outstanding.size > 0) {
336
+ await Promise.allSettled([...this.outstanding]);
337
+ }
338
+ }
339
+ start(call, conversation, signal) {
340
+ const previous = conversation === void 0 ? void 0 : this.gates.get(conversation);
341
+ const pending = this.run(call, previous, signal);
342
+ this.outstanding.add(pending);
343
+ if (conversation !== void 0) {
344
+ const gate = Promise.allSettled([previous, pending]).then(() => void 0);
345
+ this.gates.set(conversation, gate);
346
+ this.depths.set(conversation, (this.depths.get(conversation) ?? 0) + 1);
347
+ void gate.then(() => {
348
+ if (this.gates.get(conversation) === gate) {
349
+ this.gates.delete(conversation);
350
+ }
351
+ });
352
+ }
353
+ const finish = () => {
354
+ this.outstanding.delete(pending);
355
+ if (conversation === void 0) {
356
+ return;
357
+ }
358
+ const depth = (this.depths.get(conversation) ?? 1) - 1;
359
+ if (depth > 0) {
360
+ this.depths.set(conversation, depth);
361
+ } else {
362
+ this.depths.delete(conversation);
363
+ }
364
+ };
365
+ pending.then(finish, finish);
366
+ return pending;
367
+ }
368
+ async run(call, previous, signal) {
369
+ signal?.throwIfAborted();
370
+ if (previous !== void 0) {
371
+ await settled(previous, signal);
372
+ }
373
+ await this.acquire(signal);
374
+ try {
375
+ return await call();
376
+ } finally {
377
+ const next = this.waiting.shift();
378
+ if (next) {
379
+ next();
380
+ } else {
381
+ this.running--;
382
+ }
383
+ }
384
+ }
385
+ acquire(signal) {
386
+ if (this.running < this.maxConcurrent) {
387
+ this.running++;
388
+ return Promise.resolve();
389
+ }
390
+ return new Promise((resolve, reject) => {
391
+ const onAbort = () => {
392
+ const position = this.waiting.indexOf(grant);
393
+ if (position >= 0) {
394
+ this.waiting.splice(position, 1);
395
+ reject(signal?.reason);
396
+ }
397
+ };
398
+ const grant = () => {
399
+ signal?.removeEventListener("abort", onAbort);
400
+ resolve();
401
+ };
402
+ this.waiting.push(grant);
403
+ signal?.addEventListener("abort", onAbort, { once: true });
404
+ });
405
+ }
406
+ };
407
+ Deferred = class {
408
+ scopes = /* @__PURE__ */ new Map();
409
+ add(scope, promise) {
410
+ const verdict = { promise, passed: false, failed: false, failure: void 0 };
411
+ promise.then(
412
+ () => {
413
+ verdict.passed = true;
414
+ },
415
+ (error) => {
416
+ verdict.failed = true;
417
+ verdict.failure = error;
418
+ }
419
+ );
420
+ const verdicts = this.scopes.get(scope) ?? [];
421
+ verdicts.push(verdict);
422
+ this.scopes.set(scope, verdicts);
423
+ }
424
+ /** Wait for every verdict in the scope and throw the first failure. */
425
+ async join(scope) {
426
+ for (const verdict of [...this.scopes.get(scope) ?? []]) {
427
+ await verdict.promise.catch(() => void 0);
428
+ if (verdict.failed) {
429
+ throw verdict.failure;
430
+ }
431
+ }
432
+ const unfinished = (this.scopes.get(scope) ?? []).filter((verdict) => !verdict.passed);
433
+ if (unfinished.length > 0) {
434
+ this.scopes.set(scope, unfinished);
435
+ } else {
436
+ this.scopes.delete(scope);
437
+ }
438
+ }
439
+ /** Throw the failure of a verdict that has already landed, without waiting for the rest. */
440
+ check(scope) {
441
+ const landed = this.scopes.get(scope)?.find((verdict) => verdict.failed);
442
+ if (landed !== void 0) {
443
+ throw landed.failure;
444
+ }
445
+ }
446
+ /** Forget a scope once its execution has ended. */
447
+ drop(scope) {
448
+ this.scopes.delete(scope);
449
+ }
450
+ clear() {
451
+ this.scopes.clear();
452
+ }
453
+ };
454
+ }
455
+ });
456
+
246
457
  // src/utils/extract.ts
247
458
  function extractTextFromPrompts(prompts) {
248
459
  return prompts.map((p) => p.trim()).filter((p) => p.length > 0).join("\n");
@@ -375,6 +586,19 @@ var init_thread_identity = __esm({
375
586
  }
376
587
  return discarded;
377
588
  }
589
+ /** The outermost tracked ancestor, which scopes verdicts deferred by its descendants. */
590
+ root(runId) {
591
+ const visited = /* @__PURE__ */ new Set([runId]);
592
+ let current = runId;
593
+ for (; ; ) {
594
+ const parent = this.runs.get(current)?.parentRunId;
595
+ if (parent === void 0 || visited.has(parent) || !this.runs.has(parent)) {
596
+ return current;
597
+ }
598
+ visited.add(parent);
599
+ current = parent;
600
+ }
601
+ }
378
602
  get(runId) {
379
603
  const run = this.runs.get(runId);
380
604
  return run ? run.threadId : this.boundIdentity?.threadId;
@@ -452,7 +676,14 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
452
676
  const { ensureConfig } = await import("@langchain/core/runnables");
453
677
  const threads = new RunThreadIdentity(boundIdentity, () => ensureConfig());
454
678
  const { BaseTracer } = await import("@langchain/core/tracers/base");
679
+ const deferred = new Deferred();
680
+ const dropScope = (runId) => {
681
+ if (threads.root(runId) === runId) {
682
+ deferred.drop(runId);
683
+ }
684
+ };
455
685
  let finishRun = (runId) => {
686
+ dropScope(runId);
456
687
  threads.finish(runId);
457
688
  };
458
689
  const enabledHooks = resolveHooks(options.hooks);
@@ -473,40 +704,17 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
473
704
  logger("onClassify callback threw", err);
474
705
  }
475
706
  };
476
- const classifyEvent = async (text, hookLabel, runId, toolName) => {
477
- let result;
478
- try {
479
- result = await firewall.classify(text, {
480
- hook: hookLabel,
481
- metadata: {
482
- langgraph: { run_id: runId },
483
- ...threads.get(runId) === void 0 ? {} : { conversationId: threads.get(runId) }
484
- },
485
- ...requestedMode !== void 0 ? { mode: requestedMode } : {},
486
- ...toolName !== void 0 ? { toolName } : {}
487
- });
488
- } catch (err) {
489
- if (isReviewCompatibilityError(err)) {
490
- throw err;
491
- }
492
- if (!failOpen) {
493
- throw err;
494
- }
495
- logger("classification failed, allowing prompt through", err);
496
- return;
497
- }
498
- const threshold = result.threshold;
707
+ const parallel = options.parallel ?? false;
708
+ const background = requestedMode === "shadow" && failOpen;
709
+ const report = (result, text, hookLabel, runId, toolName) => {
499
710
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
500
711
  const effectiveMode = requestedMode ?? result.mode ?? "block";
501
- const commonEventFields = {
712
+ fireOnClassify({
502
713
  hook: hookLabel,
503
714
  ...toolName !== void 0 ? { toolName } : {},
504
715
  runId,
505
716
  text,
506
- result
507
- };
508
- fireOnClassify({
509
- ...commonEventFields,
717
+ result,
510
718
  blocked,
511
719
  mode: effectiveMode,
512
720
  shadowMode: effectiveMode === "shadow"
@@ -516,7 +724,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
516
724
  }
517
725
  throw new FirewallBlockedException({
518
726
  score: result.score,
519
- threshold,
727
+ threshold: result.threshold,
520
728
  promptText: text,
521
729
  runId,
522
730
  hook: hookLabel,
@@ -524,9 +732,63 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
524
732
  result
525
733
  });
526
734
  };
735
+ const classifyEvent = async (text, hookLabel, runId, request, toolName) => {
736
+ let result;
737
+ try {
738
+ result = await firewall.classify(text, request);
739
+ } catch (err) {
740
+ if (isReviewCompatibilityError(err)) {
741
+ throw err;
742
+ }
743
+ if (!failOpen) {
744
+ throw err;
745
+ }
746
+ logger("classification failed, allowing prompt through", err);
747
+ return;
748
+ }
749
+ report(result, text, hookLabel, runId, toolName);
750
+ };
751
+ const settle = (runId) => deferred.join(threads.root(runId));
752
+ const settleRoot = async (runId) => {
753
+ if (threads.root(runId) === runId) {
754
+ await settle(runId);
755
+ }
756
+ };
757
+ const checkLanded = (runId) => {
758
+ try {
759
+ deferred.check(threads.root(runId));
760
+ } catch (error) {
761
+ finishRun(runId);
762
+ throw error;
763
+ }
764
+ };
527
765
  const classify = async (text, hook, runId, toolName) => {
766
+ const request = {
767
+ hook,
768
+ metadata: {
769
+ langgraph: { run_id: runId },
770
+ ...threads.get(runId) === void 0 ? {} : { conversationId: threads.get(runId) }
771
+ },
772
+ ...requestedMode !== void 0 ? { mode: requestedMode } : {},
773
+ ...toolName !== void 0 ? { toolName } : {}
774
+ };
775
+ const conversation = conversationId(request.metadata);
776
+ const check = () => classifyEvent(text, hook, runId, request, toolName);
528
777
  try {
529
- await classifyEvent(text, hook, runId, toolName);
778
+ if (background) {
779
+ void firewall.observe(text, request).then((result) => {
780
+ if (result !== void 0) {
781
+ report(result, text, hook, runId, toolName);
782
+ }
783
+ });
784
+ } else if (!parallel) {
785
+ await check();
786
+ } else if (DEFERRED_LABELS.has(hook)) {
787
+ deferred.add(threads.root(runId), firewall.pending.submit(check, conversation));
788
+ } else {
789
+ await settle(runId);
790
+ await firewall.pending.submit(check, conversation);
791
+ }
530
792
  } catch (error) {
531
793
  finishRun(runId);
532
794
  throw error;
@@ -582,16 +844,19 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
582
844
  async handleAgentEnd() {
583
845
  }
584
846
  async handleLLMNewToken(_token, _idx, runId) {
847
+ checkLanded(runId);
585
848
  return this.getRunById(runId) ?? this._createRunForLLMStart(serialized(void 0, "llm"), [], runId);
586
849
  }
587
850
  capture(runId, parentRunId, metadata) {
588
851
  for (const id of threads.start(runId, parentRunId, metadata)) {
852
+ deferred.drop(id);
589
853
  this.runMap.delete(id);
590
854
  this.runTreeMap?.delete(id);
591
855
  }
592
856
  }
593
857
  finishAll() {
594
858
  for (const id of [...this.runMap.keys()]) this.finishRun(id);
859
+ deferred.clear();
595
860
  this.runTreeMap?.clear();
596
861
  }
597
862
  finishRun(runId) {
@@ -686,6 +951,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
686
951
  async handleLLMEnd(output, runId) {
687
952
  try {
688
953
  if (!this.getRunById(runId)) this._createRunForLLMStart(serialized(void 0, "llm"), [], runId);
954
+ await settle(runId);
689
955
  if (enabledHooks.has(FirewallHook.LLM_END)) {
690
956
  const text = extractTextFromLLMResult(output);
691
957
  if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.LLM_END], runId);
@@ -702,6 +968,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
702
968
  const text = String(output).trim();
703
969
  if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.TOOL_END], runId, kwargs?.name);
704
970
  }
971
+ await settleRoot(runId);
705
972
  return await super.handleToolEnd(output, runId);
706
973
  } finally {
707
974
  finishRun(runId);
@@ -714,17 +981,21 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
714
981
  const text = extractTextFromDocuments(documents);
715
982
  if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.RETRIEVER_END], runId);
716
983
  }
984
+ await settleRoot(runId);
717
985
  return await super.handleRetrieverEnd(documents, runId);
718
986
  } finally {
719
987
  finishRun(runId);
720
988
  }
721
989
  }
722
990
  async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
723
- return super.handleChainStart(serialized(chain, "chain"), inputs, runId, parentRunId, tags, metadata, runType, name);
991
+ const run = await super.handleChainStart(serialized(chain, "chain"), inputs, runId, parentRunId, tags, metadata, runType, name);
992
+ checkLanded(runId);
993
+ return run;
724
994
  }
725
995
  async handleChainEnd(...args) {
726
996
  if (!this.getRunById(args[1])) this._createRunForChainStart(serialized(void 0, "chain"), {}, args[1]);
727
997
  try {
998
+ await settleRoot(args[1]);
728
999
  return await super.handleChainEnd(...args);
729
1000
  } finally {
730
1001
  finishRun(args[1]);
@@ -765,6 +1036,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
765
1036
  }
766
1037
  const handler = new SilmarilFirewallHandler();
767
1038
  finishRun = (runId) => {
1039
+ dropScope(runId);
768
1040
  handler.finishRun(runId);
769
1041
  };
770
1042
  handlerCleanups.set(handler, () => handler.finishAll());
@@ -869,17 +1141,22 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
869
1141
  }
870
1142
  return new ComposableBinding({ bound: installBoundary(runnable), config: {} });
871
1143
  }
872
- var handlerCleanups, USER_ROLES;
1144
+ var handlerCleanups, USER_ROLES, DEFERRED_LABELS;
873
1145
  var init_langchain = __esm({
874
1146
  "src/adapters/langchain.ts"() {
875
1147
  "use strict";
876
1148
  init_exceptions();
877
1149
  init_hooks();
878
1150
  init_modes();
1151
+ init_pending();
879
1152
  init_extract();
880
1153
  init_thread_identity();
881
1154
  handlerCleanups = /* @__PURE__ */ new WeakMap();
882
1155
  USER_ROLES = /* @__PURE__ */ new Set(["human", "user"]);
1156
+ DEFERRED_LABELS = /* @__PURE__ */ new Set([
1157
+ HookLabel.USER_INPUT,
1158
+ HookLabel.TOOL_RESPONSE
1159
+ ]);
883
1160
  }
884
1161
  });
885
1162
 
@@ -921,6 +1198,7 @@ var import_node_crypto = require("crypto");
921
1198
  init_exceptions();
922
1199
  init_hooks();
923
1200
  init_modes();
1201
+ init_pending();
924
1202
  function stringifyToolValue(value) {
925
1203
  if (value === null || value === void 0) {
926
1204
  return "";
@@ -995,14 +1273,15 @@ function findLastUserMessage(messages) {
995
1273
  }
996
1274
  function createMiddleware(firewall, options = {}) {
997
1275
  const scanInput = options.scanInput ?? true;
998
- const scanOutput = options.scanOutput ?? false;
1276
+ const scanOutput = options.scanOutput ?? true;
1277
+ const parallel = options.parallel ?? false;
999
1278
  const requestedMode = validateMode(options.mode) ?? (options.shadowMode === void 0 ? firewall.mode : options.shadowMode ? "shadow" : "block");
1000
1279
  const classifyOrBlock = async (text, hook, context = { toolName: void 0, toolCallId: void 0 }) => {
1001
1280
  if (!text.trim()) {
1002
1281
  return;
1003
1282
  }
1004
1283
  const { toolName, toolCallId } = context;
1005
- const result = await firewall.classify(
1284
+ const classify = () => firewall.classify(
1006
1285
  text,
1007
1286
  {
1008
1287
  hook,
@@ -1010,6 +1289,7 @@ function createMiddleware(firewall, options = {}) {
1010
1289
  ...requestedMode !== void 0 ? { mode: requestedMode } : {}
1011
1290
  }
1012
1291
  );
1292
+ const result = await (parallel ? firewall.pending.submit(classify) : classify());
1013
1293
  const threshold = result.threshold;
1014
1294
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
1015
1295
  const effectiveMode = requestedMode ?? result.mode ?? "block";
@@ -1064,11 +1344,14 @@ function createMiddleware(firewall, options = {}) {
1064
1344
  await classifyOrBlock(text, HookLabel.USER_INPUT);
1065
1345
  };
1066
1346
  const scanGenerateResult = async (result) => {
1067
- if (scanOutput && typeof result.text === "string" && result.text.length > 0) {
1068
- await classifyOrBlock(result.text, HookLabel.LLM_OUTPUT);
1069
- }
1070
- if (options.scanToolCalls && Array.isArray(result.toolCalls)) {
1071
- for (const call of result.toolCalls) {
1347
+ const content = Array.isArray(result.content) ? result.content : [];
1348
+ const text = typeof result.text === "string" ? result.text : content.filter((part) => part?.type === "text").map((part) => part.text ?? "").join("");
1349
+ if (scanOutput && text.length > 0) {
1350
+ await classifyOrBlock(text, HookLabel.LLM_OUTPUT);
1351
+ }
1352
+ const toolCalls = Array.isArray(result.toolCalls) ? result.toolCalls : content.filter((part) => part?.type === "tool-call");
1353
+ if (options.scanToolCalls) {
1354
+ for (const call of toolCalls) {
1072
1355
  if (!call || typeof call !== "object") {
1073
1356
  continue;
1074
1357
  }
@@ -1082,6 +1365,16 @@ function createMiddleware(firewall, options = {}) {
1082
1365
  }
1083
1366
  }
1084
1367
  };
1368
+ const guarded = async (prompt, run, discard) => {
1369
+ if (!scanInput) {
1370
+ return run();
1371
+ }
1372
+ if (parallel) {
1373
+ return alongside(scanPrompt(prompt), run, discard);
1374
+ }
1375
+ await scanPrompt(prompt);
1376
+ return run();
1377
+ };
1085
1378
  return {
1086
1379
  specificationVersion: "v3",
1087
1380
  middlewareVersion: "v2",
@@ -1089,10 +1382,7 @@ function createMiddleware(firewall, options = {}) {
1089
1382
  params,
1090
1383
  doGenerate
1091
1384
  }) {
1092
- if (scanInput) {
1093
- await scanPrompt(params.prompt ?? []);
1094
- }
1095
- const result = await doGenerate();
1385
+ const result = await guarded(params.prompt ?? [], doGenerate);
1096
1386
  await scanGenerateResult(result);
1097
1387
  return result;
1098
1388
  },
@@ -1100,10 +1390,9 @@ function createMiddleware(firewall, options = {}) {
1100
1390
  params,
1101
1391
  doStream
1102
1392
  }) {
1103
- if (scanInput) {
1104
- await scanPrompt(params.prompt ?? []);
1105
- }
1106
- const { stream, ...rest } = await doStream();
1393
+ const { stream, ...rest } = await guarded(params.prompt ?? [], doStream, (started) => {
1394
+ void started.stream.cancel().catch(() => void 0);
1395
+ });
1107
1396
  if (!scanOutput) {
1108
1397
  return { stream, ...rest };
1109
1398
  }
@@ -1141,6 +1430,7 @@ function createMiddleware(firewall, options = {}) {
1141
1430
 
1142
1431
  // src/firewall.ts
1143
1432
  init_exceptions();
1433
+ init_hooks();
1144
1434
  init_modes();
1145
1435
 
1146
1436
  // src/outcomes.ts
@@ -1249,6 +1539,9 @@ function normalizeHarmfulOutcomeCountMap(values, fieldName) {
1249
1539
  return out;
1250
1540
  }
1251
1541
 
1542
+ // src/firewall.ts
1543
+ init_pending();
1544
+
1252
1545
  // src/sanitization.ts
1253
1546
  function isHighSurrogate(code) {
1254
1547
  return code >= 55296 && code <= 56319;
@@ -1276,7 +1569,7 @@ function sanitizeText(text) {
1276
1569
  }
1277
1570
 
1278
1571
  // src/firewall.ts
1279
- var SDK_VERSION = "0.9.0";
1572
+ var SDK_VERSION = "0.10.0";
1280
1573
  var DEFAULT_TIMEOUT_MS = 1e4;
1281
1574
  var DEFAULT_MAX_RETRIES = 5;
1282
1575
  var MAX_BACKOFF_SECONDS = 30;
@@ -1359,6 +1652,26 @@ function blockResultFromResponse(data, requestedMode, requestedReview) {
1359
1652
  }
1360
1653
  return Object.freeze(result);
1361
1654
  }
1655
+ function wireCopy(value) {
1656
+ const encoded = JSON.stringify(value);
1657
+ return encoded === void 0 ? value : JSON.parse(encoded);
1658
+ }
1659
+ function snapshotRequest(options) {
1660
+ return {
1661
+ ...options,
1662
+ ...options.metadata === void 0 ? {} : { metadata: wireCopy(options.metadata) },
1663
+ ...options.governance === void 0 ? {} : { governance: wireCopy(options.governance) }
1664
+ };
1665
+ }
1666
+ function outputRequest(input) {
1667
+ return {
1668
+ hook: HookLabel.LLM_OUTPUT,
1669
+ ...input.mode === void 0 ? {} : { mode: input.mode },
1670
+ ...input.review === void 0 ? {} : { review: input.review },
1671
+ ...input.metadata === void 0 ? {} : { metadata: input.metadata },
1672
+ ...input.signal === void 0 ? {} : { signal: input.signal }
1673
+ };
1674
+ }
1362
1675
  function isRecord2(value) {
1363
1676
  return typeof value === "object" && value !== null && !Array.isArray(value);
1364
1677
  }
@@ -1604,6 +1917,8 @@ var Firewall = class {
1604
1917
  shadowMode;
1605
1918
  mode;
1606
1919
  review;
1920
+ /** @internal Shared by adapters so one conversation keeps a single send order. */
1921
+ pending;
1607
1922
  headers;
1608
1923
  constructor(options) {
1609
1924
  if (!options.apiKey) {
@@ -1626,6 +1941,10 @@ var Firewall = class {
1626
1941
  this.mode = validateMode(options.mode) ?? legacyMode(options.shadowMode);
1627
1942
  this.review = validateReview(options.review, "review");
1628
1943
  this.shadowMode = this.mode === "shadow";
1944
+ this.pending = new PendingVerdicts(
1945
+ validateLimit("maxConcurrent", options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT),
1946
+ validateLimit("maxQueued", options.maxQueued ?? DEFAULT_MAX_QUEUED)
1947
+ );
1629
1948
  this.headers = Object.freeze({
1630
1949
  "x-api-key": this.apiKey,
1631
1950
  "content-type": "application/json"
@@ -1635,6 +1954,87 @@ var Firewall = class {
1635
1954
  const requestId = options.requestId ?? (0, import_node_crypto.randomUUID)();
1636
1955
  return this.classifySingle(sanitizeText(text), options, { requestId });
1637
1956
  }
1957
+ /**
1958
+ * Run an operation while its input is classified and withhold a blocked result.
1959
+ * The operation's signal aborts when a block arrives before it finishes.
1960
+ */
1961
+ async protect(operation, options) {
1962
+ const { text, output, ...request } = options;
1963
+ const requestedMode = validateMode(options.mode) ?? this.mode;
1964
+ const controller = new AbortController();
1965
+ if (requestedMode === "shadow" || requestedMode === "warn") {
1966
+ const observed = this.observable(request);
1967
+ if (observed !== void 0) {
1968
+ void this.background(text, observed);
1969
+ }
1970
+ const result2 = await operation(controller.signal);
1971
+ if (observed !== void 0 && output !== void 0) {
1972
+ void this.background(output(result2), outputRequest(observed));
1973
+ }
1974
+ return result2;
1975
+ }
1976
+ const input = snapshotRequest(request);
1977
+ const conversation = conversationId(input.metadata);
1978
+ const outputOptions = outputRequest(input);
1979
+ const verdict = this.pending.submit(() => this.enforce(text, input), conversation, input.signal);
1980
+ const [, result] = await Promise.all([
1981
+ verdict.catch((error) => {
1982
+ controller.abort(error);
1983
+ throw error;
1984
+ }),
1985
+ Promise.resolve().then(() => operation(controller.signal))
1986
+ ]);
1987
+ if (output !== void 0) {
1988
+ const generated = output(result);
1989
+ await this.pending.submit(
1990
+ () => this.enforce(generated, outputOptions),
1991
+ conversation,
1992
+ input.signal
1993
+ );
1994
+ }
1995
+ return result;
1996
+ }
1997
+ /** Wait for classifications still running in the background. */
1998
+ flush() {
1999
+ return this.pending.drain();
2000
+ }
2001
+ /**
2002
+ * @internal Classify in the background with one retry; resolves undefined on failure.
2003
+ * The request is copied now and detached from the caller's signal.
2004
+ */
2005
+ observe(text, options = {}) {
2006
+ const request = this.observable(options);
2007
+ return request === void 0 ? Promise.resolve(void 0) : this.background(text, request);
2008
+ }
2009
+ background(text, request) {
2010
+ return this.pending.observe(() => this.classify(text, request), conversationId(request.metadata));
2011
+ }
2012
+ /** Copy a background request, reporting one that cannot be copied instead of failing the caller. */
2013
+ observable(options) {
2014
+ try {
2015
+ const request = snapshotRequest(options);
2016
+ delete request.signal;
2017
+ return request;
2018
+ } catch (error) {
2019
+ reportBackground("background classification failed", error);
2020
+ return void 0;
2021
+ }
2022
+ }
2023
+ async enforce(text, options) {
2024
+ const result = await this.classify(text, options);
2025
+ const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
2026
+ if (blocked && (result.mode ?? "block") === "block") {
2027
+ throw new FirewallBlockedException({
2028
+ score: result.score,
2029
+ threshold: result.threshold,
2030
+ promptText: text,
2031
+ ...options.hook === void 0 ? {} : { hook: options.hook },
2032
+ ...options.toolName === void 0 ? {} : { toolName: options.toolName },
2033
+ result
2034
+ });
2035
+ }
2036
+ return result;
2037
+ }
1638
2038
  async classifyBatch(texts, options = {}) {
1639
2039
  if (texts.length === 0) {
1640
2040
  throw new Error("Firewall: texts must not be empty");
@@ -1711,7 +2111,8 @@ var Firewall = class {
1711
2111
  asMiddleware(options = {}) {
1712
2112
  return createMiddleware(this, options);
1713
2113
  }
1714
- async postWithRetry(payload, callerSignal, maxRetries = DEFAULT_MAX_RETRIES) {
2114
+ async postWithRetry(payload, callerSignal) {
2115
+ const maxRetries = retryBudget(DEFAULT_MAX_RETRIES);
1715
2116
  callerSignal?.throwIfAborted();
1716
2117
  const body = JSON.stringify(payload);
1717
2118
  for (let attempt = 0; attempt <= maxRetries; attempt++) {