@silmaril-security/sdk 0.11.3 → 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.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { H as HookLabel, B as BlockResult, R as ReviewLevel } from './firewall-BZ8kfq5c.cjs';
2
- export { A as ALL_HOOKS, C as ClassificationMetadata, a as ClassifyBatchOptions, b as ClassifyEvent, c as ClassifyOptions, D as DEFAULT_HOOKS, d as DEFAULT_TIMEOUT_MS, F as FIREWALL_HOOK_TO_LABEL, e as Firewall, f as FirewallHook, g as FirewallMiddleware, h as FirewallMode, i as FirewallOptions, G as GovernanceAction, j as GovernanceContext, k as GovernanceDecision, l as GovernanceResource, m as GovernanceResourceKind, n as HARMFUL_OUTCOMES, o as HarmfulOutcome, I as INPUT_HOOKS, K as KnownHarmfulOutcome, p as KnownPrimaryOutcome, L as LangChainAdapterOptions, q as LangChainFirewallHandler, M as MiddlewareOptions, O as OUTCOME_DESCRIPTIONS, r as OUTPUT_HOOKS, s as Outcome, P as PRIMARY_OUTCOMES, t as Prediction, u as PrimaryOutcome, v as ProtectOptions, U as UnknownOutcome, w as isHarmfulOutcome, x as isPrimaryOutcome, y as normalizeHarmfulOutcome, z as normalizeHarmfulOutcomeMap, E as normalizePrimaryOutcome, J as prependHook, N as prependToolName, Q as resolveHooks } from './firewall-BZ8kfq5c.cjs';
1
+ import { H as HookLabel, B as BlockResult, R as ReviewLevel } from './firewall-DGh3e3RE.cjs';
2
+ export { A as ALL_HOOKS, C as ClassificationMetadata, a as ClassifyBatchOptions, b as ClassifyEvent, c as ClassifyOptions, D as DEFAULT_HOOKS, d as DEFAULT_TIMEOUT_MS, F as FIREWALL_HOOK_TO_LABEL, e as Firewall, f as FirewallHook, g as FirewallMiddleware, h as FirewallMode, i as FirewallOptions, G as GovernanceAction, j as GovernanceContext, k as GovernanceDecision, l as GovernanceResource, m as GovernanceResourceKind, n as HARMFUL_OUTCOMES, o as HarmfulOutcome, I as INPUT_HOOKS, K as KnownHarmfulOutcome, p as KnownPrimaryOutcome, L as LangChainAdapterOptions, q as LangChainFirewallHandler, M as MiddlewareOptions, O as OUTCOME_DESCRIPTIONS, r as OUTPUT_HOOKS, s as Outcome, P as PRIMARY_OUTCOMES, t as Prediction, u as PrimaryOutcome, v as ProtectOptions, U as UnknownOutcome, w as isHarmfulOutcome, x as isPrimaryOutcome, y as normalizeHarmfulOutcome, z as normalizeHarmfulOutcomeMap, E as normalizePrimaryOutcome, J as prependHook, N as prependToolName, Q as resolveHooks } from './firewall-DGh3e3RE.cjs';
3
3
 
4
4
  interface MalformedInputDetails {
5
5
  field?: string;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { H as HookLabel, B as BlockResult, R as ReviewLevel } from './firewall-BZ8kfq5c.js';
2
- export { A as ALL_HOOKS, C as ClassificationMetadata, a as ClassifyBatchOptions, b as ClassifyEvent, c as ClassifyOptions, D as DEFAULT_HOOKS, d as DEFAULT_TIMEOUT_MS, F as FIREWALL_HOOK_TO_LABEL, e as Firewall, f as FirewallHook, g as FirewallMiddleware, h as FirewallMode, i as FirewallOptions, G as GovernanceAction, j as GovernanceContext, k as GovernanceDecision, l as GovernanceResource, m as GovernanceResourceKind, n as HARMFUL_OUTCOMES, o as HarmfulOutcome, I as INPUT_HOOKS, K as KnownHarmfulOutcome, p as KnownPrimaryOutcome, L as LangChainAdapterOptions, q as LangChainFirewallHandler, M as MiddlewareOptions, O as OUTCOME_DESCRIPTIONS, r as OUTPUT_HOOKS, s as Outcome, P as PRIMARY_OUTCOMES, t as Prediction, u as PrimaryOutcome, v as ProtectOptions, U as UnknownOutcome, w as isHarmfulOutcome, x as isPrimaryOutcome, y as normalizeHarmfulOutcome, z as normalizeHarmfulOutcomeMap, E as normalizePrimaryOutcome, J as prependHook, N as prependToolName, Q as resolveHooks } from './firewall-BZ8kfq5c.js';
1
+ import { H as HookLabel, B as BlockResult, R as ReviewLevel } from './firewall-DGh3e3RE.js';
2
+ export { A as ALL_HOOKS, C as ClassificationMetadata, a as ClassifyBatchOptions, b as ClassifyEvent, c as ClassifyOptions, D as DEFAULT_HOOKS, d as DEFAULT_TIMEOUT_MS, F as FIREWALL_HOOK_TO_LABEL, e as Firewall, f as FirewallHook, g as FirewallMiddleware, h as FirewallMode, i as FirewallOptions, G as GovernanceAction, j as GovernanceContext, k as GovernanceDecision, l as GovernanceResource, m as GovernanceResourceKind, n as HARMFUL_OUTCOMES, o as HarmfulOutcome, I as INPUT_HOOKS, K as KnownHarmfulOutcome, p as KnownPrimaryOutcome, L as LangChainAdapterOptions, q as LangChainFirewallHandler, M as MiddlewareOptions, O as OUTCOME_DESCRIPTIONS, r as OUTPUT_HOOKS, s as Outcome, P as PRIMARY_OUTCOMES, t as Prediction, u as PrimaryOutcome, v as ProtectOptions, U as UnknownOutcome, w as isHarmfulOutcome, x as isPrimaryOutcome, y as normalizeHarmfulOutcome, z as normalizeHarmfulOutcomeMap, E as normalizePrimaryOutcome, J as prependHook, N as prependToolName, Q as resolveHooks } from './firewall-DGh3e3RE.js';
3
3
 
4
4
  interface MalformedInputDetails {
5
5
  field?: string;
package/dist/index.js CHANGED
@@ -421,6 +421,14 @@ var init_pending = __esm({
421
421
  throw landed.failure;
422
422
  }
423
423
  }
424
+ /** True when every verdict in every scope has passed. */
425
+ idle() {
426
+ return [...this.scopes.values()].every((verdicts) => verdicts.every((verdict) => verdict.passed));
427
+ }
428
+ /** Resolve once every verdict known now has settled, whether it passed or failed. */
429
+ async settled() {
430
+ await Promise.allSettled([...this.scopes.values()].flat().map((verdict) => verdict.promise));
431
+ }
424
432
  /** Forget a scope once its execution has ended. */
425
433
  drop(scope) {
426
434
  this.scopes.delete(scope);
@@ -432,6 +440,46 @@ var init_pending = __esm({
432
440
  }
433
441
  });
434
442
 
443
+ // src/verdicts.ts
444
+ async function digest(text) {
445
+ const bytes = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
446
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
447
+ }
448
+ async function verdictKey(message, threadId, mode) {
449
+ if (!threadId || !message.id) return void 0;
450
+ try {
451
+ return JSON.stringify([threadId, message.id, await digest(JSON.stringify([message.content, message.additional_kwargs])), mode]);
452
+ } catch {
453
+ return void 0;
454
+ }
455
+ }
456
+ var REMEMBERED_LIMIT, Remembered;
457
+ var init_verdicts = __esm({
458
+ "src/verdicts.ts"() {
459
+ "use strict";
460
+ REMEMBERED_LIMIT = 1024;
461
+ Remembered = class {
462
+ entries = /* @__PURE__ */ new Map();
463
+ get(key) {
464
+ if (key === void 0 || !this.entries.has(key)) return void 0;
465
+ const value = this.entries.get(key);
466
+ this.set(key, value);
467
+ return value;
468
+ }
469
+ set(key, value) {
470
+ this.entries.delete(key);
471
+ this.entries.set(key, value);
472
+ while (this.entries.size > REMEMBERED_LIMIT) this.entries.delete(this.entries.keys().next().value);
473
+ }
474
+ take(key) {
475
+ const value = this.entries.get(key);
476
+ this.entries.delete(key);
477
+ return value;
478
+ }
479
+ };
480
+ }
481
+ });
482
+
435
483
  // src/utils/extract.ts
436
484
  function extractTextFromPrompts(prompts) {
437
485
  return prompts.map((p) => p.trim()).filter((p) => p.length > 0).join("\n");
@@ -649,7 +697,7 @@ function findLastUserMessage2(messages) {
649
697
  async function createLangChainHandler(firewall, options = {}) {
650
698
  return buildLangChainHandler(firewall, options);
651
699
  }
652
- async function buildLangChainHandler(firewall, options, boundIdentity) {
700
+ async function buildLangChainHandler(firewall, options, boundIdentity, hold) {
653
701
  rejectConversationOptions(options);
654
702
  const { ensureConfig } = await import("@langchain/core/runnables");
655
703
  const threads = new RunThreadIdentity(boundIdentity, () => ensureConfig());
@@ -683,7 +731,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
683
731
  }
684
732
  };
685
733
  const parallel = options.parallel ?? false;
686
- const background = requestedMode === "shadow" && failOpen;
734
+ const background = (requestedMode === "shadow" || requestedMode === "warn") && failOpen;
687
735
  const report = (result, text, hookLabel, runId, toolName) => {
688
736
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
689
737
  const effectiveMode = requestedMode ?? result.mode ?? "block";
@@ -722,11 +770,19 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
722
770
  throw err;
723
771
  }
724
772
  logger("classification failed, allowing prompt through", err);
725
- return;
773
+ return false;
726
774
  }
727
775
  report(result, text, hookLabel, runId, toolName);
776
+ return true;
728
777
  };
729
778
  const settle = (runId) => deferred.join(threads.root(runId));
779
+ const holdModelStart = () => {
780
+ let started = () => void 0;
781
+ hold?.add(HOLD, new Promise((resolve) => {
782
+ started = resolve;
783
+ }));
784
+ return started;
785
+ };
730
786
  const settleRoot = async (runId) => {
731
787
  if (threads.root(runId) === runId) {
732
788
  await settle(runId);
@@ -740,7 +796,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
740
796
  throw error;
741
797
  }
742
798
  };
743
- const classify = async (text, hook, runId, toolName) => {
799
+ const classify = async (text, hook, runId, toolName, onAllowed) => {
744
800
  const request = {
745
801
  hook,
746
802
  metadata: {
@@ -751,18 +807,23 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
751
807
  ...toolName !== void 0 ? { toolName } : {}
752
808
  };
753
809
  const conversation = conversationId(request.metadata);
754
- const check = () => classifyEvent(text, hook, runId, request, toolName);
810
+ const check = async () => {
811
+ if (await classifyEvent(text, hook, runId, request, toolName)) onAllowed?.();
812
+ };
755
813
  try {
756
814
  if (background) {
757
815
  void firewall.observe(text, request).then((result) => {
758
816
  if (result !== void 0) {
759
817
  report(result, text, hook, runId, toolName);
818
+ onAllowed?.();
760
819
  }
761
820
  });
762
821
  } else if (!parallel) {
763
822
  await check();
764
823
  } else if (DEFERRED_LABELS.has(hook)) {
765
- deferred.add(threads.root(runId), firewall.pending.submit(check, conversation));
824
+ const verdict = firewall.pending.submit(check, conversation);
825
+ deferred.add(threads.root(runId), verdict);
826
+ hold?.add(HOLD, verdict);
766
827
  } else {
767
828
  await settle(runId);
768
829
  await firewall.pending.submit(check, conversation);
@@ -822,7 +883,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
822
883
  async handleAgentEnd() {
823
884
  }
824
885
  async handleLLMNewToken(_token, _idx, runId) {
825
- checkLanded(runId);
886
+ if (hold === void 0) checkLanded(runId);
826
887
  return this.getRunById(runId) ?? this._createRunForLLMStart(serialized(void 0, "llm"), [], runId);
827
888
  }
828
889
  capture(runId, parentRunId, metadata) {
@@ -864,6 +925,14 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
864
925
  return super._createRunForRetrieverStart(...args);
865
926
  }
866
927
  async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata) {
928
+ const started = holdModelStart();
929
+ try {
930
+ return await this.startChatModel(llm, messages, runId, parentRunId, extraParams, tags, metadata);
931
+ } finally {
932
+ started();
933
+ }
934
+ }
935
+ async startChatModel(llm, messages, runId, parentRunId, extraParams, tags, metadata) {
867
936
  const batches = messages;
868
937
  const run = this.getRunById(runId) ?? this._createRunForChatModelStart(
869
938
  serialized(llm, "chat_model"),
@@ -877,25 +946,35 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
877
946
  if (enabledHooks.has(FirewallHook.CHAT_MODEL_START)) {
878
947
  const lastUser = findLastUserMessage2(batches.flat());
879
948
  const text = lastUser ? extractMessageText(lastUser.content).trim() : "";
880
- if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.CHAT_MODEL_START], runId);
949
+ const key = lastUser === void 0 ? void 0 : await verdictKey(lastUser, threads.get(runId), requestedMode);
950
+ if (text && firewall.verdicts.get(key) !== false) {
951
+ await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.CHAT_MODEL_START], runId, void 0, () => {
952
+ if (key !== void 0) firewall.verdicts.set(key, false);
953
+ });
954
+ }
881
955
  }
882
956
  return run;
883
957
  }
884
958
  async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata) {
885
- const run = this.getRunById(runId) ?? this._createRunForLLMStart(
886
- serialized(llm, "llm"),
887
- prompts,
888
- runId,
889
- parentRunId,
890
- extraParams,
891
- tags,
892
- metadata
893
- );
894
- if (enabledHooks.has(FirewallHook.LLM_START)) {
895
- const text = extractTextFromPrompts(prompts);
896
- if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.LLM_START], runId);
959
+ const started = holdModelStart();
960
+ try {
961
+ const run = this.getRunById(runId) ?? this._createRunForLLMStart(
962
+ serialized(llm, "llm"),
963
+ prompts,
964
+ runId,
965
+ parentRunId,
966
+ extraParams,
967
+ tags,
968
+ metadata
969
+ );
970
+ if (enabledHooks.has(FirewallHook.LLM_START)) {
971
+ const text = extractTextFromPrompts(prompts);
972
+ if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.LLM_START], runId);
973
+ }
974
+ return run;
975
+ } finally {
976
+ started();
897
977
  }
898
- return run;
899
978
  }
900
979
  async handleToolStart(tool, inputStr, runId, parentRunId, tags, metadata) {
901
980
  const run = this.getRunById(runId) ?? this._createRunForToolStart(
@@ -1018,8 +1097,46 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
1018
1097
  handler.finishRun(runId);
1019
1098
  };
1020
1099
  handlerCleanups.set(handler, () => handler.finishAll());
1100
+ if (hold !== void 0) handlerHolds.set(handler, hold);
1021
1101
  return handler;
1022
1102
  }
1103
+ async function* withheld(upstream, holds) {
1104
+ const iterator = upstream[Symbol.asyncIterator]();
1105
+ const buffer = [];
1106
+ const pull = () => {
1107
+ const pending = iterator.next();
1108
+ pending.catch(() => void 0);
1109
+ return pending;
1110
+ };
1111
+ let next = pull();
1112
+ try {
1113
+ for (; ; ) {
1114
+ let step;
1115
+ if (buffer.length > 0) {
1116
+ for (const hold of holds) hold.check(HOLD);
1117
+ if (holds.every((hold) => hold.idle())) {
1118
+ yield* buffer.splice(0);
1119
+ continue;
1120
+ }
1121
+ if (buffer.length >= MAX_WITHHELD_CHUNKS) {
1122
+ await Promise.all(holds.map((hold) => hold.settled()));
1123
+ continue;
1124
+ }
1125
+ step = await Promise.race([next, Promise.all(holds.map((hold) => hold.settled())).then(() => void 0)]);
1126
+ if (step === void 0) continue;
1127
+ } else {
1128
+ step = await next;
1129
+ }
1130
+ if (step.done) break;
1131
+ buffer.push(step.value);
1132
+ next = pull();
1133
+ }
1134
+ for (const hold of holds) await hold.join(HOLD);
1135
+ yield* buffer;
1136
+ } finally {
1137
+ await iterator.return?.();
1138
+ }
1139
+ }
1023
1140
  async function protectLangChainRunnable(firewall, runnable, options = {}) {
1024
1141
  rejectConversationOptions(options);
1025
1142
  const { RunnableBinding, RunnableRetry, ensureConfig, mergeConfigs } = await import("@langchain/core/runnables");
@@ -1028,7 +1145,7 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
1028
1145
  const effective = ensureConfig(config);
1029
1146
  const handler = await buildLangChainHandler(firewall, options, {
1030
1147
  threadId: validThreadId(effective.configurable?.thread_id)
1031
- });
1148
+ }, new Deferred());
1032
1149
  return { callbacks: [handler] };
1033
1150
  }];
1034
1151
  class ProtectedBinding extends RunnableBinding {
@@ -1041,9 +1158,13 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
1041
1158
  });
1042
1159
  const scoped = new RunnableBinding({ bound: this.bound, config: this.config, configFactories: scopedFactories });
1043
1160
  const config = await scoped._mergeConfig(...configs);
1044
- return { config, dispose: () => {
1045
- for (const handler of created) handlerCleanups.get(handler)?.();
1046
- } };
1161
+ return {
1162
+ config,
1163
+ holds: created.flatMap((handler) => handlerHolds.get(handler) ?? []),
1164
+ dispose: () => {
1165
+ for (const handler of created) handlerCleanups.get(handler)?.();
1166
+ }
1167
+ };
1047
1168
  }
1048
1169
  async invoke(input, options2) {
1049
1170
  const scoped = await this.scopedConfig(options2, this.kwargs);
@@ -1064,7 +1185,7 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
1064
1185
  }
1065
1186
  const managed = async function* () {
1066
1187
  try {
1067
- yield* upstream;
1188
+ yield* withheld(upstream, scoped.holds);
1068
1189
  } finally {
1069
1190
  scoped.dispose();
1070
1191
  }
@@ -1119,7 +1240,7 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
1119
1240
  }
1120
1241
  return new ComposableBinding({ bound: installBoundary(runnable), config: {} });
1121
1242
  }
1122
- var handlerCleanups, USER_ROLES, DEFERRED_LABELS;
1243
+ var handlerCleanups, handlerHolds, HOLD, MAX_WITHHELD_CHUNKS, USER_ROLES, DEFERRED_LABELS;
1123
1244
  var init_langchain = __esm({
1124
1245
  "src/adapters/langchain.ts"() {
1125
1246
  "use strict";
@@ -1129,7 +1250,11 @@ var init_langchain = __esm({
1129
1250
  init_pending();
1130
1251
  init_extract();
1131
1252
  init_thread_identity();
1253
+ init_verdicts();
1132
1254
  handlerCleanups = /* @__PURE__ */ new WeakMap();
1255
+ handlerHolds = /* @__PURE__ */ new WeakMap();
1256
+ HOLD = "invocation";
1257
+ MAX_WITHHELD_CHUNKS = 1024;
1133
1258
  USER_ROLES = /* @__PURE__ */ new Set(["human", "user"]);
1134
1259
  DEFERRED_LABELS = /* @__PURE__ */ new Set([
1135
1260
  HookLabel.USER_INPUT,
@@ -1223,20 +1348,28 @@ function createMiddleware(firewall, options = {}) {
1223
1348
  const scanOutput = options.scanOutput ?? true;
1224
1349
  const parallel = options.parallel ?? false;
1225
1350
  const requestedMode = validateMode(options.mode) ?? (options.shadowMode === void 0 ? firewall.mode : options.shadowMode ? "shadow" : "block");
1351
+ const background = (requestedMode === "shadow" || requestedMode === "warn") && options.failOpen !== false;
1226
1352
  const classifyOrBlock = async (text, hook, context = { toolName: void 0, toolCallId: void 0 }) => {
1227
1353
  if (!text.trim()) {
1228
1354
  return;
1229
1355
  }
1356
+ const { toolName } = context;
1357
+ const request = {
1358
+ hook,
1359
+ ...toolName !== void 0 ? { toolName } : {},
1360
+ ...requestedMode !== void 0 ? { mode: requestedMode } : {}
1361
+ };
1362
+ if (background) {
1363
+ void firewall.observe(text, request).then((result) => {
1364
+ if (result !== void 0) report(result, text, hook, context);
1365
+ }).catch((error) => reportBackground("onClassify callback threw", error));
1366
+ return;
1367
+ }
1368
+ const classify = () => firewall.classify(text, request);
1369
+ report(await (parallel ? firewall.pending.submit(classify) : classify()), text, hook, context);
1370
+ };
1371
+ const report = (result, text, hook, context) => {
1230
1372
  const { toolName, toolCallId } = context;
1231
- const classify = () => firewall.classify(
1232
- text,
1233
- {
1234
- hook,
1235
- ...toolName !== void 0 ? { toolName } : {},
1236
- ...requestedMode !== void 0 ? { mode: requestedMode } : {}
1237
- }
1238
- );
1239
- const result = await (parallel ? firewall.pending.submit(classify) : classify());
1240
1373
  const threshold = result.threshold;
1241
1374
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
1242
1375
  const effectiveMode = requestedMode ?? result.mode ?? "block";
@@ -1527,7 +1660,8 @@ function sanitizeText(text) {
1527
1660
  }
1528
1661
 
1529
1662
  // src/firewall.ts
1530
- var SDK_VERSION = "0.11.3";
1663
+ init_verdicts();
1664
+ var SDK_VERSION = "0.12.0";
1531
1665
  var DEFAULT_TIMEOUT_MS = 1e4;
1532
1666
  var DEFAULT_MAX_RETRIES = 5;
1533
1667
  var MAX_BACKOFF_SECONDS = 30;
@@ -1905,6 +2039,8 @@ var Firewall = class {
1905
2039
  review;
1906
2040
  /** @internal Shared by adapters so one conversation keeps a single send order. */
1907
2041
  pending;
2042
+ /** @internal Verdicts adapters remember per thread and message, shared across invocations on this client. */
2043
+ verdicts = new Remembered();
1908
2044
  headers;
1909
2045
  constructor(options) {
1910
2046
  if (!options.apiKey) {