@silmaril-security/sdk 0.11.4 → 0.12.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.
@@ -165,6 +165,14 @@ var Deferred = class {
165
165
  throw landed.failure;
166
166
  }
167
167
  }
168
+ /** True when every verdict in every scope has passed. */
169
+ idle() {
170
+ return [...this.scopes.values()].every((verdicts) => verdicts.every((verdict) => verdict.passed));
171
+ }
172
+ /** Resolve once every verdict known now has settled, whether it passed or failed. */
173
+ async settled() {
174
+ await Promise.allSettled([...this.scopes.values()].flat().map((verdict) => verdict.promise));
175
+ }
168
176
  /** Forget a scope once its execution has ended. */
169
177
  drop(scope) {
170
178
  this.scopes.delete(scope);
@@ -335,8 +343,25 @@ var RunThreadIdentity = class {
335
343
  }
336
344
  };
337
345
 
346
+ // src/verdicts.ts
347
+ async function digest(text) {
348
+ const bytes = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
349
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
350
+ }
351
+ async function verdictKey(message, threadId, mode) {
352
+ if (!threadId || !message.id) return void 0;
353
+ try {
354
+ return JSON.stringify([threadId, message.id, await digest(JSON.stringify([message.content, message.additional_kwargs])), mode]);
355
+ } catch {
356
+ return void 0;
357
+ }
358
+ }
359
+
338
360
  // src/adapters/langchain.ts
339
361
  var handlerCleanups = /* @__PURE__ */ new WeakMap();
362
+ var handlerHolds = /* @__PURE__ */ new WeakMap();
363
+ var HOLD = "invocation";
364
+ var MAX_WITHHELD_CHUNKS = 1024;
340
365
  var USER_ROLES = /* @__PURE__ */ new Set(["human", "user"]);
341
366
  var DEFERRED_LABELS = /* @__PURE__ */ new Set([
342
367
  HookLabel.USER_INPUT,
@@ -381,7 +406,7 @@ function findLastUserMessage(messages) {
381
406
  async function createLangChainHandler(firewall, options = {}) {
382
407
  return buildLangChainHandler(firewall, options);
383
408
  }
384
- async function buildLangChainHandler(firewall, options, boundIdentity) {
409
+ async function buildLangChainHandler(firewall, options, boundIdentity, hold) {
385
410
  rejectConversationOptions(options);
386
411
  const { ensureConfig } = await import("@langchain/core/runnables");
387
412
  const threads = new RunThreadIdentity(boundIdentity, () => ensureConfig());
@@ -415,7 +440,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
415
440
  }
416
441
  };
417
442
  const parallel = options.parallel ?? false;
418
- const background = requestedMode === "shadow" && failOpen;
443
+ const background = (requestedMode === "shadow" || requestedMode === "warn") && failOpen;
419
444
  const report = (result, text, hookLabel, runId, toolName) => {
420
445
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
421
446
  const effectiveMode = requestedMode ?? result.mode ?? "block";
@@ -454,11 +479,19 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
454
479
  throw err;
455
480
  }
456
481
  logger("classification failed, allowing prompt through", err);
457
- return;
482
+ return false;
458
483
  }
459
484
  report(result, text, hookLabel, runId, toolName);
485
+ return true;
460
486
  };
461
487
  const settle = (runId) => deferred.join(threads.root(runId));
488
+ const holdModelStart = () => {
489
+ let started = () => void 0;
490
+ hold?.add(HOLD, new Promise((resolve) => {
491
+ started = resolve;
492
+ }));
493
+ return started;
494
+ };
462
495
  const settleRoot = async (runId) => {
463
496
  if (threads.root(runId) === runId) {
464
497
  await settle(runId);
@@ -472,7 +505,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
472
505
  throw error;
473
506
  }
474
507
  };
475
- const classify = async (text, hook, runId, toolName) => {
508
+ const classify = async (text, hook, runId, toolName, onAllowed) => {
476
509
  const request = {
477
510
  hook,
478
511
  metadata: {
@@ -483,18 +516,23 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
483
516
  ...toolName !== void 0 ? { toolName } : {}
484
517
  };
485
518
  const conversation = conversationId(request.metadata);
486
- const check = () => classifyEvent(text, hook, runId, request, toolName);
519
+ const check = async () => {
520
+ if (await classifyEvent(text, hook, runId, request, toolName)) onAllowed?.();
521
+ };
487
522
  try {
488
523
  if (background) {
489
524
  void firewall.observe(text, request).then((result) => {
490
525
  if (result !== void 0) {
491
526
  report(result, text, hook, runId, toolName);
527
+ onAllowed?.();
492
528
  }
493
529
  });
494
530
  } else if (!parallel) {
495
531
  await check();
496
532
  } else if (DEFERRED_LABELS.has(hook)) {
497
- deferred.add(threads.root(runId), firewall.pending.submit(check, conversation));
533
+ const verdict = firewall.pending.submit(check, conversation);
534
+ deferred.add(threads.root(runId), verdict);
535
+ hold?.add(HOLD, verdict);
498
536
  } else {
499
537
  await settle(runId);
500
538
  await firewall.pending.submit(check, conversation);
@@ -554,7 +592,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
554
592
  async handleAgentEnd() {
555
593
  }
556
594
  async handleLLMNewToken(_token, _idx, runId) {
557
- checkLanded(runId);
595
+ if (hold === void 0) checkLanded(runId);
558
596
  return this.getRunById(runId) ?? this._createRunForLLMStart(serialized(void 0, "llm"), [], runId);
559
597
  }
560
598
  capture(runId, parentRunId, metadata) {
@@ -596,6 +634,14 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
596
634
  return super._createRunForRetrieverStart(...args);
597
635
  }
598
636
  async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata) {
637
+ const started = holdModelStart();
638
+ try {
639
+ return await this.startChatModel(llm, messages, runId, parentRunId, extraParams, tags, metadata);
640
+ } finally {
641
+ started();
642
+ }
643
+ }
644
+ async startChatModel(llm, messages, runId, parentRunId, extraParams, tags, metadata) {
599
645
  const batches = messages;
600
646
  const run = this.getRunById(runId) ?? this._createRunForChatModelStart(
601
647
  serialized(llm, "chat_model"),
@@ -609,25 +655,35 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
609
655
  if (enabledHooks.has(FirewallHook.CHAT_MODEL_START)) {
610
656
  const lastUser = findLastUserMessage(batches.flat());
611
657
  const text = lastUser ? extractMessageText(lastUser.content).trim() : "";
612
- if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.CHAT_MODEL_START], runId);
658
+ const key = lastUser === void 0 ? void 0 : await verdictKey(lastUser, threads.get(runId), requestedMode);
659
+ if (text && firewall.verdicts.get(key) !== false) {
660
+ await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.CHAT_MODEL_START], runId, void 0, () => {
661
+ if (key !== void 0) firewall.verdicts.set(key, false);
662
+ });
663
+ }
613
664
  }
614
665
  return run;
615
666
  }
616
667
  async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata) {
617
- const run = this.getRunById(runId) ?? this._createRunForLLMStart(
618
- serialized(llm, "llm"),
619
- prompts,
620
- runId,
621
- parentRunId,
622
- extraParams,
623
- tags,
624
- metadata
625
- );
626
- if (enabledHooks.has(FirewallHook.LLM_START)) {
627
- const text = extractTextFromPrompts(prompts);
628
- if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.LLM_START], runId);
668
+ const started = holdModelStart();
669
+ try {
670
+ const run = this.getRunById(runId) ?? this._createRunForLLMStart(
671
+ serialized(llm, "llm"),
672
+ prompts,
673
+ runId,
674
+ parentRunId,
675
+ extraParams,
676
+ tags,
677
+ metadata
678
+ );
679
+ if (enabledHooks.has(FirewallHook.LLM_START)) {
680
+ const text = extractTextFromPrompts(prompts);
681
+ if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.LLM_START], runId);
682
+ }
683
+ return run;
684
+ } finally {
685
+ started();
629
686
  }
630
- return run;
631
687
  }
632
688
  async handleToolStart(tool, inputStr, runId, parentRunId, tags, metadata) {
633
689
  const run = this.getRunById(runId) ?? this._createRunForToolStart(
@@ -750,8 +806,46 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
750
806
  handler.finishRun(runId);
751
807
  };
752
808
  handlerCleanups.set(handler, () => handler.finishAll());
809
+ if (hold !== void 0) handlerHolds.set(handler, hold);
753
810
  return handler;
754
811
  }
812
+ async function* withheld(upstream, holds) {
813
+ const iterator = upstream[Symbol.asyncIterator]();
814
+ const buffer = [];
815
+ const pull = () => {
816
+ const pending = iterator.next();
817
+ pending.catch(() => void 0);
818
+ return pending;
819
+ };
820
+ let next = pull();
821
+ try {
822
+ for (; ; ) {
823
+ let step;
824
+ if (buffer.length > 0) {
825
+ for (const hold of holds) hold.check(HOLD);
826
+ if (holds.every((hold) => hold.idle())) {
827
+ yield* buffer.splice(0);
828
+ continue;
829
+ }
830
+ if (buffer.length >= MAX_WITHHELD_CHUNKS) {
831
+ await Promise.all(holds.map((hold) => hold.settled()));
832
+ continue;
833
+ }
834
+ step = await Promise.race([next, Promise.all(holds.map((hold) => hold.settled())).then(() => void 0)]);
835
+ if (step === void 0) continue;
836
+ } else {
837
+ step = await next;
838
+ }
839
+ if (step.done) break;
840
+ buffer.push(step.value);
841
+ next = pull();
842
+ }
843
+ for (const hold of holds) await hold.join(HOLD);
844
+ yield* buffer;
845
+ } finally {
846
+ await iterator.return?.();
847
+ }
848
+ }
755
849
  async function protectLangChainRunnable(firewall, runnable, options = {}) {
756
850
  rejectConversationOptions(options);
757
851
  const { RunnableBinding, RunnableRetry, ensureConfig, mergeConfigs } = await import("@langchain/core/runnables");
@@ -760,7 +854,7 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
760
854
  const effective = ensureConfig(config);
761
855
  const handler = await buildLangChainHandler(firewall, options, {
762
856
  threadId: validThreadId(effective.configurable?.thread_id)
763
- });
857
+ }, new Deferred());
764
858
  return { callbacks: [handler] };
765
859
  }];
766
860
  class ProtectedBinding extends RunnableBinding {
@@ -773,9 +867,13 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
773
867
  });
774
868
  const scoped = new RunnableBinding({ bound: this.bound, config: this.config, configFactories: scopedFactories });
775
869
  const config = await scoped._mergeConfig(...configs);
776
- return { config, dispose: () => {
777
- for (const handler of created) handlerCleanups.get(handler)?.();
778
- } };
870
+ return {
871
+ config,
872
+ holds: created.flatMap((handler) => handlerHolds.get(handler) ?? []),
873
+ dispose: () => {
874
+ for (const handler of created) handlerCleanups.get(handler)?.();
875
+ }
876
+ };
779
877
  }
780
878
  async invoke(input, options2) {
781
879
  const scoped = await this.scopedConfig(options2, this.kwargs);
@@ -796,7 +894,7 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
796
894
  }
797
895
  const managed = async function* () {
798
896
  try {
799
- yield* upstream;
897
+ yield* withheld(upstream, scoped.holds);
800
898
  } finally {
801
899
  scoped.dispose();
802
900
  }