@silmaril-security/sdk 0.9.1 → 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.
- package/CHANGELOG.md +30 -0
- package/README.md +107 -19
- package/dist/adapters/deepagents.cjs +73 -36
- package/dist/adapters/deepagents.cjs.map +1 -1
- package/dist/adapters/deepagents.d.cts +3 -1
- package/dist/adapters/deepagents.d.ts +3 -1
- package/dist/adapters/deepagents.js +73 -36
- package/dist/adapters/deepagents.js.map +1 -1
- package/dist/adapters/langchain.cjs +153 -32
- package/dist/adapters/langchain.cjs.map +1 -1
- package/dist/adapters/langchain.d.cts +1 -1
- package/dist/adapters/langchain.d.ts +1 -1
- package/dist/adapters/langchain.js +153 -32
- package/dist/adapters/langchain.js.map +1 -1
- package/dist/adapters/vercel-v4.cjs +30 -7
- package/dist/adapters/vercel-v4.cjs.map +1 -1
- package/dist/adapters/vercel-v4.d.cts +1 -1
- package/dist/adapters/vercel-v4.d.ts +1 -1
- package/dist/adapters/vercel-v4.js +30 -7
- package/dist/adapters/vercel-v4.js.map +1 -1
- package/dist/adapters/vercel.cjs +41 -15
- package/dist/adapters/vercel.cjs.map +1 -1
- package/dist/adapters/vercel.d.cts +1 -1
- package/dist/adapters/vercel.d.ts +1 -1
- package/dist/adapters/vercel.js +41 -15
- package/dist/adapters/vercel.js.map +1 -1
- package/dist/{firewall-Bv5y03P0.d.cts → firewall-BXM2BWEr.d.cts} +60 -1
- package/dist/{firewall-Bv5y03P0.d.ts → firewall-BXM2BWEr.d.ts} +60 -1
- package/dist/index.cjs +451 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +451 -50
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/index.js
CHANGED
|
@@ -178,7 +178,8 @@ var init_hooks = __esm({
|
|
|
178
178
|
FirewallHook.LLM_START,
|
|
179
179
|
FirewallHook.CHAT_MODEL_START,
|
|
180
180
|
FirewallHook.TOOL_START,
|
|
181
|
-
FirewallHook.TOOL_END
|
|
181
|
+
FirewallHook.TOOL_END,
|
|
182
|
+
FirewallHook.LLM_END
|
|
182
183
|
]);
|
|
183
184
|
INPUT_HOOKS = /* @__PURE__ */ new Set([
|
|
184
185
|
FirewallHook.LLM_START,
|
|
@@ -221,6 +222,216 @@ var init_modes = __esm({
|
|
|
221
222
|
}
|
|
222
223
|
});
|
|
223
224
|
|
|
225
|
+
// src/pending.ts
|
|
226
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
227
|
+
function retryBudget(maxRetries) {
|
|
228
|
+
return Math.min(maxRetries, retryLimit.getStore() ?? maxRetries);
|
|
229
|
+
}
|
|
230
|
+
function conversationId(metadata) {
|
|
231
|
+
const value = metadata?.conversationId;
|
|
232
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
233
|
+
}
|
|
234
|
+
function validateLimit(name, value) {
|
|
235
|
+
if (!Number.isSafeInteger(value) || value < 1) {
|
|
236
|
+
throw new Error(`Firewall: ${name} must be a positive integer, got ${value}`);
|
|
237
|
+
}
|
|
238
|
+
return value;
|
|
239
|
+
}
|
|
240
|
+
function reportBackground(message, error) {
|
|
241
|
+
console.warn(`silmaril.firewall: ${message}`, ...error === void 0 ? [] : [error]);
|
|
242
|
+
}
|
|
243
|
+
function settled(gate, signal) {
|
|
244
|
+
return new Promise((resolve, reject) => {
|
|
245
|
+
const onAbort = () => reject(signal?.reason);
|
|
246
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
247
|
+
void gate.then(() => {
|
|
248
|
+
signal?.removeEventListener("abort", onAbort);
|
|
249
|
+
resolve();
|
|
250
|
+
});
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
async function alongside(check, run, discard = () => void 0) {
|
|
254
|
+
const running = Promise.resolve().then(run);
|
|
255
|
+
try {
|
|
256
|
+
const [result] = await Promise.all([running, check]);
|
|
257
|
+
return result;
|
|
258
|
+
} catch (error) {
|
|
259
|
+
running.then(discard, () => void 0);
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
var DEFAULT_MAX_CONCURRENT, DEFAULT_MAX_QUEUED, BACKGROUND_RETRIES, retryLimit, PendingVerdicts, Deferred;
|
|
264
|
+
var init_pending = __esm({
|
|
265
|
+
"src/pending.ts"() {
|
|
266
|
+
"use strict";
|
|
267
|
+
DEFAULT_MAX_CONCURRENT = 32;
|
|
268
|
+
DEFAULT_MAX_QUEUED = 64;
|
|
269
|
+
BACKGROUND_RETRIES = 1;
|
|
270
|
+
retryLimit = new AsyncLocalStorage();
|
|
271
|
+
PendingVerdicts = class {
|
|
272
|
+
constructor(maxConcurrent, maxQueued) {
|
|
273
|
+
this.maxConcurrent = maxConcurrent;
|
|
274
|
+
this.maxQueued = maxQueued;
|
|
275
|
+
}
|
|
276
|
+
maxConcurrent;
|
|
277
|
+
maxQueued;
|
|
278
|
+
gates = /* @__PURE__ */ new Map();
|
|
279
|
+
depths = /* @__PURE__ */ new Map();
|
|
280
|
+
outstanding = /* @__PURE__ */ new Set();
|
|
281
|
+
waiting = [];
|
|
282
|
+
running = 0;
|
|
283
|
+
background = 0;
|
|
284
|
+
/**
|
|
285
|
+
* Start a classification the caller joins by awaiting the returned promise.
|
|
286
|
+
* An aborted signal stops it waiting for its turn; later classifications keep their order.
|
|
287
|
+
*/
|
|
288
|
+
submit(call, conversation, signal) {
|
|
289
|
+
const pending = this.start(call, conversation, signal);
|
|
290
|
+
pending.catch(() => void 0);
|
|
291
|
+
return pending;
|
|
292
|
+
}
|
|
293
|
+
/** Start a classification nobody joins; failures are reported, never thrown. */
|
|
294
|
+
observe(call, conversation) {
|
|
295
|
+
const conversationFull = conversation !== void 0 && (this.depths.get(conversation) ?? 0) >= this.maxQueued;
|
|
296
|
+
if (conversationFull || this.background >= this.maxConcurrent * this.maxQueued) {
|
|
297
|
+
reportBackground("dropped background classification: queue is full");
|
|
298
|
+
return Promise.resolve(void 0);
|
|
299
|
+
}
|
|
300
|
+
this.background++;
|
|
301
|
+
const pending = this.start(() => retryLimit.run(BACKGROUND_RETRIES, call), conversation, void 0);
|
|
302
|
+
const release = () => {
|
|
303
|
+
this.background--;
|
|
304
|
+
};
|
|
305
|
+
pending.then(release, release);
|
|
306
|
+
return pending.catch((error) => {
|
|
307
|
+
reportBackground("background classification failed", error);
|
|
308
|
+
return void 0;
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
/** Wait until every classification started so far has finished. */
|
|
312
|
+
async drain() {
|
|
313
|
+
while (this.outstanding.size > 0) {
|
|
314
|
+
await Promise.allSettled([...this.outstanding]);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
start(call, conversation, signal) {
|
|
318
|
+
const previous = conversation === void 0 ? void 0 : this.gates.get(conversation);
|
|
319
|
+
const pending = this.run(call, previous, signal);
|
|
320
|
+
this.outstanding.add(pending);
|
|
321
|
+
if (conversation !== void 0) {
|
|
322
|
+
const gate = Promise.allSettled([previous, pending]).then(() => void 0);
|
|
323
|
+
this.gates.set(conversation, gate);
|
|
324
|
+
this.depths.set(conversation, (this.depths.get(conversation) ?? 0) + 1);
|
|
325
|
+
void gate.then(() => {
|
|
326
|
+
if (this.gates.get(conversation) === gate) {
|
|
327
|
+
this.gates.delete(conversation);
|
|
328
|
+
}
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
const finish = () => {
|
|
332
|
+
this.outstanding.delete(pending);
|
|
333
|
+
if (conversation === void 0) {
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
const depth = (this.depths.get(conversation) ?? 1) - 1;
|
|
337
|
+
if (depth > 0) {
|
|
338
|
+
this.depths.set(conversation, depth);
|
|
339
|
+
} else {
|
|
340
|
+
this.depths.delete(conversation);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
pending.then(finish, finish);
|
|
344
|
+
return pending;
|
|
345
|
+
}
|
|
346
|
+
async run(call, previous, signal) {
|
|
347
|
+
signal?.throwIfAborted();
|
|
348
|
+
if (previous !== void 0) {
|
|
349
|
+
await settled(previous, signal);
|
|
350
|
+
}
|
|
351
|
+
await this.acquire(signal);
|
|
352
|
+
try {
|
|
353
|
+
return await call();
|
|
354
|
+
} finally {
|
|
355
|
+
const next = this.waiting.shift();
|
|
356
|
+
if (next) {
|
|
357
|
+
next();
|
|
358
|
+
} else {
|
|
359
|
+
this.running--;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
acquire(signal) {
|
|
364
|
+
if (this.running < this.maxConcurrent) {
|
|
365
|
+
this.running++;
|
|
366
|
+
return Promise.resolve();
|
|
367
|
+
}
|
|
368
|
+
return new Promise((resolve, reject) => {
|
|
369
|
+
const onAbort = () => {
|
|
370
|
+
const position = this.waiting.indexOf(grant);
|
|
371
|
+
if (position >= 0) {
|
|
372
|
+
this.waiting.splice(position, 1);
|
|
373
|
+
reject(signal?.reason);
|
|
374
|
+
}
|
|
375
|
+
};
|
|
376
|
+
const grant = () => {
|
|
377
|
+
signal?.removeEventListener("abort", onAbort);
|
|
378
|
+
resolve();
|
|
379
|
+
};
|
|
380
|
+
this.waiting.push(grant);
|
|
381
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
Deferred = class {
|
|
386
|
+
scopes = /* @__PURE__ */ new Map();
|
|
387
|
+
add(scope, promise) {
|
|
388
|
+
const verdict = { promise, passed: false, failed: false, failure: void 0 };
|
|
389
|
+
promise.then(
|
|
390
|
+
() => {
|
|
391
|
+
verdict.passed = true;
|
|
392
|
+
},
|
|
393
|
+
(error) => {
|
|
394
|
+
verdict.failed = true;
|
|
395
|
+
verdict.failure = error;
|
|
396
|
+
}
|
|
397
|
+
);
|
|
398
|
+
const verdicts = this.scopes.get(scope) ?? [];
|
|
399
|
+
verdicts.push(verdict);
|
|
400
|
+
this.scopes.set(scope, verdicts);
|
|
401
|
+
}
|
|
402
|
+
/** Wait for every verdict in the scope and throw the first failure. */
|
|
403
|
+
async join(scope) {
|
|
404
|
+
for (const verdict of [...this.scopes.get(scope) ?? []]) {
|
|
405
|
+
await verdict.promise.catch(() => void 0);
|
|
406
|
+
if (verdict.failed) {
|
|
407
|
+
throw verdict.failure;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const unfinished = (this.scopes.get(scope) ?? []).filter((verdict) => !verdict.passed);
|
|
411
|
+
if (unfinished.length > 0) {
|
|
412
|
+
this.scopes.set(scope, unfinished);
|
|
413
|
+
} else {
|
|
414
|
+
this.scopes.delete(scope);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
/** Throw the failure of a verdict that has already landed, without waiting for the rest. */
|
|
418
|
+
check(scope) {
|
|
419
|
+
const landed = this.scopes.get(scope)?.find((verdict) => verdict.failed);
|
|
420
|
+
if (landed !== void 0) {
|
|
421
|
+
throw landed.failure;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/** Forget a scope once its execution has ended. */
|
|
425
|
+
drop(scope) {
|
|
426
|
+
this.scopes.delete(scope);
|
|
427
|
+
}
|
|
428
|
+
clear() {
|
|
429
|
+
this.scopes.clear();
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
|
|
224
435
|
// src/utils/extract.ts
|
|
225
436
|
function extractTextFromPrompts(prompts) {
|
|
226
437
|
return prompts.map((p) => p.trim()).filter((p) => p.length > 0).join("\n");
|
|
@@ -353,6 +564,19 @@ var init_thread_identity = __esm({
|
|
|
353
564
|
}
|
|
354
565
|
return discarded;
|
|
355
566
|
}
|
|
567
|
+
/** The outermost tracked ancestor, which scopes verdicts deferred by its descendants. */
|
|
568
|
+
root(runId) {
|
|
569
|
+
const visited = /* @__PURE__ */ new Set([runId]);
|
|
570
|
+
let current = runId;
|
|
571
|
+
for (; ; ) {
|
|
572
|
+
const parent = this.runs.get(current)?.parentRunId;
|
|
573
|
+
if (parent === void 0 || visited.has(parent) || !this.runs.has(parent)) {
|
|
574
|
+
return current;
|
|
575
|
+
}
|
|
576
|
+
visited.add(parent);
|
|
577
|
+
current = parent;
|
|
578
|
+
}
|
|
579
|
+
}
|
|
356
580
|
get(runId) {
|
|
357
581
|
const run = this.runs.get(runId);
|
|
358
582
|
return run ? run.threadId : this.boundIdentity?.threadId;
|
|
@@ -430,7 +654,14 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
430
654
|
const { ensureConfig } = await import("@langchain/core/runnables");
|
|
431
655
|
const threads = new RunThreadIdentity(boundIdentity, () => ensureConfig());
|
|
432
656
|
const { BaseTracer } = await import("@langchain/core/tracers/base");
|
|
657
|
+
const deferred = new Deferred();
|
|
658
|
+
const dropScope = (runId) => {
|
|
659
|
+
if (threads.root(runId) === runId) {
|
|
660
|
+
deferred.drop(runId);
|
|
661
|
+
}
|
|
662
|
+
};
|
|
433
663
|
let finishRun = (runId) => {
|
|
664
|
+
dropScope(runId);
|
|
434
665
|
threads.finish(runId);
|
|
435
666
|
};
|
|
436
667
|
const enabledHooks = resolveHooks(options.hooks);
|
|
@@ -451,40 +682,17 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
451
682
|
logger("onClassify callback threw", err);
|
|
452
683
|
}
|
|
453
684
|
};
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
result = await firewall.classify(text, {
|
|
458
|
-
hook: hookLabel,
|
|
459
|
-
metadata: {
|
|
460
|
-
langgraph: { run_id: runId },
|
|
461
|
-
...threads.get(runId) === void 0 ? {} : { conversationId: threads.get(runId) }
|
|
462
|
-
},
|
|
463
|
-
...requestedMode !== void 0 ? { mode: requestedMode } : {},
|
|
464
|
-
...toolName !== void 0 ? { toolName } : {}
|
|
465
|
-
});
|
|
466
|
-
} catch (err) {
|
|
467
|
-
if (isReviewCompatibilityError(err)) {
|
|
468
|
-
throw err;
|
|
469
|
-
}
|
|
470
|
-
if (!failOpen) {
|
|
471
|
-
throw err;
|
|
472
|
-
}
|
|
473
|
-
logger("classification failed, allowing prompt through", err);
|
|
474
|
-
return;
|
|
475
|
-
}
|
|
476
|
-
const threshold = result.threshold;
|
|
685
|
+
const parallel = options.parallel ?? false;
|
|
686
|
+
const background = requestedMode === "shadow" && failOpen;
|
|
687
|
+
const report = (result, text, hookLabel, runId, toolName) => {
|
|
477
688
|
const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
|
|
478
689
|
const effectiveMode = requestedMode ?? result.mode ?? "block";
|
|
479
|
-
|
|
690
|
+
fireOnClassify({
|
|
480
691
|
hook: hookLabel,
|
|
481
692
|
...toolName !== void 0 ? { toolName } : {},
|
|
482
693
|
runId,
|
|
483
694
|
text,
|
|
484
|
-
result
|
|
485
|
-
};
|
|
486
|
-
fireOnClassify({
|
|
487
|
-
...commonEventFields,
|
|
695
|
+
result,
|
|
488
696
|
blocked,
|
|
489
697
|
mode: effectiveMode,
|
|
490
698
|
shadowMode: effectiveMode === "shadow"
|
|
@@ -494,7 +702,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
494
702
|
}
|
|
495
703
|
throw new FirewallBlockedException({
|
|
496
704
|
score: result.score,
|
|
497
|
-
threshold,
|
|
705
|
+
threshold: result.threshold,
|
|
498
706
|
promptText: text,
|
|
499
707
|
runId,
|
|
500
708
|
hook: hookLabel,
|
|
@@ -502,9 +710,63 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
502
710
|
result
|
|
503
711
|
});
|
|
504
712
|
};
|
|
713
|
+
const classifyEvent = async (text, hookLabel, runId, request, toolName) => {
|
|
714
|
+
let result;
|
|
715
|
+
try {
|
|
716
|
+
result = await firewall.classify(text, request);
|
|
717
|
+
} catch (err) {
|
|
718
|
+
if (isReviewCompatibilityError(err)) {
|
|
719
|
+
throw err;
|
|
720
|
+
}
|
|
721
|
+
if (!failOpen) {
|
|
722
|
+
throw err;
|
|
723
|
+
}
|
|
724
|
+
logger("classification failed, allowing prompt through", err);
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
report(result, text, hookLabel, runId, toolName);
|
|
728
|
+
};
|
|
729
|
+
const settle = (runId) => deferred.join(threads.root(runId));
|
|
730
|
+
const settleRoot = async (runId) => {
|
|
731
|
+
if (threads.root(runId) === runId) {
|
|
732
|
+
await settle(runId);
|
|
733
|
+
}
|
|
734
|
+
};
|
|
735
|
+
const checkLanded = (runId) => {
|
|
736
|
+
try {
|
|
737
|
+
deferred.check(threads.root(runId));
|
|
738
|
+
} catch (error) {
|
|
739
|
+
finishRun(runId);
|
|
740
|
+
throw error;
|
|
741
|
+
}
|
|
742
|
+
};
|
|
505
743
|
const classify = async (text, hook, runId, toolName) => {
|
|
744
|
+
const request = {
|
|
745
|
+
hook,
|
|
746
|
+
metadata: {
|
|
747
|
+
langgraph: { run_id: runId },
|
|
748
|
+
...threads.get(runId) === void 0 ? {} : { conversationId: threads.get(runId) }
|
|
749
|
+
},
|
|
750
|
+
...requestedMode !== void 0 ? { mode: requestedMode } : {},
|
|
751
|
+
...toolName !== void 0 ? { toolName } : {}
|
|
752
|
+
};
|
|
753
|
+
const conversation = conversationId(request.metadata);
|
|
754
|
+
const check = () => classifyEvent(text, hook, runId, request, toolName);
|
|
506
755
|
try {
|
|
507
|
-
|
|
756
|
+
if (background) {
|
|
757
|
+
void firewall.observe(text, request).then((result) => {
|
|
758
|
+
if (result !== void 0) {
|
|
759
|
+
report(result, text, hook, runId, toolName);
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
} else if (!parallel) {
|
|
763
|
+
await check();
|
|
764
|
+
} else if (DEFERRED_LABELS.has(hook)) {
|
|
765
|
+
deferred.add(threads.root(runId), firewall.pending.submit(check, conversation));
|
|
766
|
+
} else {
|
|
767
|
+
await settle(runId);
|
|
768
|
+
await firewall.pending.submit(check, conversation);
|
|
769
|
+
}
|
|
508
770
|
} catch (error) {
|
|
509
771
|
finishRun(runId);
|
|
510
772
|
throw error;
|
|
@@ -560,16 +822,19 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
560
822
|
async handleAgentEnd() {
|
|
561
823
|
}
|
|
562
824
|
async handleLLMNewToken(_token, _idx, runId) {
|
|
825
|
+
checkLanded(runId);
|
|
563
826
|
return this.getRunById(runId) ?? this._createRunForLLMStart(serialized(void 0, "llm"), [], runId);
|
|
564
827
|
}
|
|
565
828
|
capture(runId, parentRunId, metadata) {
|
|
566
829
|
for (const id of threads.start(runId, parentRunId, metadata)) {
|
|
830
|
+
deferred.drop(id);
|
|
567
831
|
this.runMap.delete(id);
|
|
568
832
|
this.runTreeMap?.delete(id);
|
|
569
833
|
}
|
|
570
834
|
}
|
|
571
835
|
finishAll() {
|
|
572
836
|
for (const id of [...this.runMap.keys()]) this.finishRun(id);
|
|
837
|
+
deferred.clear();
|
|
573
838
|
this.runTreeMap?.clear();
|
|
574
839
|
}
|
|
575
840
|
finishRun(runId) {
|
|
@@ -664,6 +929,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
664
929
|
async handleLLMEnd(output, runId) {
|
|
665
930
|
try {
|
|
666
931
|
if (!this.getRunById(runId)) this._createRunForLLMStart(serialized(void 0, "llm"), [], runId);
|
|
932
|
+
await settle(runId);
|
|
667
933
|
if (enabledHooks.has(FirewallHook.LLM_END)) {
|
|
668
934
|
const text = extractTextFromLLMResult(output);
|
|
669
935
|
if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.LLM_END], runId);
|
|
@@ -680,6 +946,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
680
946
|
const text = String(output).trim();
|
|
681
947
|
if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.TOOL_END], runId, kwargs?.name);
|
|
682
948
|
}
|
|
949
|
+
await settleRoot(runId);
|
|
683
950
|
return await super.handleToolEnd(output, runId);
|
|
684
951
|
} finally {
|
|
685
952
|
finishRun(runId);
|
|
@@ -692,17 +959,21 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
692
959
|
const text = extractTextFromDocuments(documents);
|
|
693
960
|
if (text) await classify(text, FIREWALL_HOOK_TO_LABEL[FirewallHook.RETRIEVER_END], runId);
|
|
694
961
|
}
|
|
962
|
+
await settleRoot(runId);
|
|
695
963
|
return await super.handleRetrieverEnd(documents, runId);
|
|
696
964
|
} finally {
|
|
697
965
|
finishRun(runId);
|
|
698
966
|
}
|
|
699
967
|
}
|
|
700
968
|
async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) {
|
|
701
|
-
|
|
969
|
+
const run = await super.handleChainStart(serialized(chain, "chain"), inputs, runId, parentRunId, tags, metadata, runType, name);
|
|
970
|
+
checkLanded(runId);
|
|
971
|
+
return run;
|
|
702
972
|
}
|
|
703
973
|
async handleChainEnd(...args) {
|
|
704
974
|
if (!this.getRunById(args[1])) this._createRunForChainStart(serialized(void 0, "chain"), {}, args[1]);
|
|
705
975
|
try {
|
|
976
|
+
await settleRoot(args[1]);
|
|
706
977
|
return await super.handleChainEnd(...args);
|
|
707
978
|
} finally {
|
|
708
979
|
finishRun(args[1]);
|
|
@@ -743,6 +1014,7 @@ async function buildLangChainHandler(firewall, options, boundIdentity) {
|
|
|
743
1014
|
}
|
|
744
1015
|
const handler = new SilmarilFirewallHandler();
|
|
745
1016
|
finishRun = (runId) => {
|
|
1017
|
+
dropScope(runId);
|
|
746
1018
|
handler.finishRun(runId);
|
|
747
1019
|
};
|
|
748
1020
|
handlerCleanups.set(handler, () => handler.finishAll());
|
|
@@ -847,17 +1119,22 @@ async function protectLangChainRunnable(firewall, runnable, options = {}) {
|
|
|
847
1119
|
}
|
|
848
1120
|
return new ComposableBinding({ bound: installBoundary(runnable), config: {} });
|
|
849
1121
|
}
|
|
850
|
-
var handlerCleanups, USER_ROLES;
|
|
1122
|
+
var handlerCleanups, USER_ROLES, DEFERRED_LABELS;
|
|
851
1123
|
var init_langchain = __esm({
|
|
852
1124
|
"src/adapters/langchain.ts"() {
|
|
853
1125
|
"use strict";
|
|
854
1126
|
init_exceptions();
|
|
855
1127
|
init_hooks();
|
|
856
1128
|
init_modes();
|
|
1129
|
+
init_pending();
|
|
857
1130
|
init_extract();
|
|
858
1131
|
init_thread_identity();
|
|
859
1132
|
handlerCleanups = /* @__PURE__ */ new WeakMap();
|
|
860
1133
|
USER_ROLES = /* @__PURE__ */ new Set(["human", "user"]);
|
|
1134
|
+
DEFERRED_LABELS = /* @__PURE__ */ new Set([
|
|
1135
|
+
HookLabel.USER_INPUT,
|
|
1136
|
+
HookLabel.TOOL_RESPONSE
|
|
1137
|
+
]);
|
|
861
1138
|
}
|
|
862
1139
|
});
|
|
863
1140
|
|
|
@@ -868,6 +1145,7 @@ import { randomUUID } from "crypto";
|
|
|
868
1145
|
init_exceptions();
|
|
869
1146
|
init_hooks();
|
|
870
1147
|
init_modes();
|
|
1148
|
+
init_pending();
|
|
871
1149
|
function stringifyToolValue(value) {
|
|
872
1150
|
if (value === null || value === void 0) {
|
|
873
1151
|
return "";
|
|
@@ -942,14 +1220,15 @@ function findLastUserMessage(messages) {
|
|
|
942
1220
|
}
|
|
943
1221
|
function createMiddleware(firewall, options = {}) {
|
|
944
1222
|
const scanInput = options.scanInput ?? true;
|
|
945
|
-
const scanOutput = options.scanOutput ??
|
|
1223
|
+
const scanOutput = options.scanOutput ?? true;
|
|
1224
|
+
const parallel = options.parallel ?? false;
|
|
946
1225
|
const requestedMode = validateMode(options.mode) ?? (options.shadowMode === void 0 ? firewall.mode : options.shadowMode ? "shadow" : "block");
|
|
947
1226
|
const classifyOrBlock = async (text, hook, context = { toolName: void 0, toolCallId: void 0 }) => {
|
|
948
1227
|
if (!text.trim()) {
|
|
949
1228
|
return;
|
|
950
1229
|
}
|
|
951
1230
|
const { toolName, toolCallId } = context;
|
|
952
|
-
const
|
|
1231
|
+
const classify = () => firewall.classify(
|
|
953
1232
|
text,
|
|
954
1233
|
{
|
|
955
1234
|
hook,
|
|
@@ -957,6 +1236,7 @@ function createMiddleware(firewall, options = {}) {
|
|
|
957
1236
|
...requestedMode !== void 0 ? { mode: requestedMode } : {}
|
|
958
1237
|
}
|
|
959
1238
|
);
|
|
1239
|
+
const result = await (parallel ? firewall.pending.submit(classify) : classify());
|
|
960
1240
|
const threshold = result.threshold;
|
|
961
1241
|
const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
|
|
962
1242
|
const effectiveMode = requestedMode ?? result.mode ?? "block";
|
|
@@ -1011,11 +1291,14 @@ function createMiddleware(firewall, options = {}) {
|
|
|
1011
1291
|
await classifyOrBlock(text, HookLabel.USER_INPUT);
|
|
1012
1292
|
};
|
|
1013
1293
|
const scanGenerateResult = async (result) => {
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1294
|
+
const content = Array.isArray(result.content) ? result.content : [];
|
|
1295
|
+
const text = typeof result.text === "string" ? result.text : content.filter((part) => part?.type === "text").map((part) => part.text ?? "").join("");
|
|
1296
|
+
if (scanOutput && text.length > 0) {
|
|
1297
|
+
await classifyOrBlock(text, HookLabel.LLM_OUTPUT);
|
|
1298
|
+
}
|
|
1299
|
+
const toolCalls = Array.isArray(result.toolCalls) ? result.toolCalls : content.filter((part) => part?.type === "tool-call");
|
|
1300
|
+
if (options.scanToolCalls) {
|
|
1301
|
+
for (const call of toolCalls) {
|
|
1019
1302
|
if (!call || typeof call !== "object") {
|
|
1020
1303
|
continue;
|
|
1021
1304
|
}
|
|
@@ -1029,6 +1312,16 @@ function createMiddleware(firewall, options = {}) {
|
|
|
1029
1312
|
}
|
|
1030
1313
|
}
|
|
1031
1314
|
};
|
|
1315
|
+
const guarded = async (prompt, run, discard) => {
|
|
1316
|
+
if (!scanInput) {
|
|
1317
|
+
return run();
|
|
1318
|
+
}
|
|
1319
|
+
if (parallel) {
|
|
1320
|
+
return alongside(scanPrompt(prompt), run, discard);
|
|
1321
|
+
}
|
|
1322
|
+
await scanPrompt(prompt);
|
|
1323
|
+
return run();
|
|
1324
|
+
};
|
|
1032
1325
|
return {
|
|
1033
1326
|
specificationVersion: "v3",
|
|
1034
1327
|
middlewareVersion: "v2",
|
|
@@ -1036,10 +1329,7 @@ function createMiddleware(firewall, options = {}) {
|
|
|
1036
1329
|
params,
|
|
1037
1330
|
doGenerate
|
|
1038
1331
|
}) {
|
|
1039
|
-
|
|
1040
|
-
await scanPrompt(params.prompt ?? []);
|
|
1041
|
-
}
|
|
1042
|
-
const result = await doGenerate();
|
|
1332
|
+
const result = await guarded(params.prompt ?? [], doGenerate);
|
|
1043
1333
|
await scanGenerateResult(result);
|
|
1044
1334
|
return result;
|
|
1045
1335
|
},
|
|
@@ -1047,10 +1337,9 @@ function createMiddleware(firewall, options = {}) {
|
|
|
1047
1337
|
params,
|
|
1048
1338
|
doStream
|
|
1049
1339
|
}) {
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
}
|
|
1053
|
-
const { stream, ...rest } = await doStream();
|
|
1340
|
+
const { stream, ...rest } = await guarded(params.prompt ?? [], doStream, (started) => {
|
|
1341
|
+
void started.stream.cancel().catch(() => void 0);
|
|
1342
|
+
});
|
|
1054
1343
|
if (!scanOutput) {
|
|
1055
1344
|
return { stream, ...rest };
|
|
1056
1345
|
}
|
|
@@ -1088,6 +1377,7 @@ function createMiddleware(firewall, options = {}) {
|
|
|
1088
1377
|
|
|
1089
1378
|
// src/firewall.ts
|
|
1090
1379
|
init_exceptions();
|
|
1380
|
+
init_hooks();
|
|
1091
1381
|
init_modes();
|
|
1092
1382
|
|
|
1093
1383
|
// src/outcomes.ts
|
|
@@ -1196,6 +1486,9 @@ function normalizeHarmfulOutcomeCountMap(values, fieldName) {
|
|
|
1196
1486
|
return out;
|
|
1197
1487
|
}
|
|
1198
1488
|
|
|
1489
|
+
// src/firewall.ts
|
|
1490
|
+
init_pending();
|
|
1491
|
+
|
|
1199
1492
|
// src/sanitization.ts
|
|
1200
1493
|
function isHighSurrogate(code) {
|
|
1201
1494
|
return code >= 55296 && code <= 56319;
|
|
@@ -1223,7 +1516,7 @@ function sanitizeText(text) {
|
|
|
1223
1516
|
}
|
|
1224
1517
|
|
|
1225
1518
|
// src/firewall.ts
|
|
1226
|
-
var SDK_VERSION = "0.
|
|
1519
|
+
var SDK_VERSION = "0.10.0";
|
|
1227
1520
|
var DEFAULT_TIMEOUT_MS = 1e4;
|
|
1228
1521
|
var DEFAULT_MAX_RETRIES = 5;
|
|
1229
1522
|
var MAX_BACKOFF_SECONDS = 30;
|
|
@@ -1306,6 +1599,26 @@ function blockResultFromResponse(data, requestedMode, requestedReview) {
|
|
|
1306
1599
|
}
|
|
1307
1600
|
return Object.freeze(result);
|
|
1308
1601
|
}
|
|
1602
|
+
function wireCopy(value) {
|
|
1603
|
+
const encoded = JSON.stringify(value);
|
|
1604
|
+
return encoded === void 0 ? value : JSON.parse(encoded);
|
|
1605
|
+
}
|
|
1606
|
+
function snapshotRequest(options) {
|
|
1607
|
+
return {
|
|
1608
|
+
...options,
|
|
1609
|
+
...options.metadata === void 0 ? {} : { metadata: wireCopy(options.metadata) },
|
|
1610
|
+
...options.governance === void 0 ? {} : { governance: wireCopy(options.governance) }
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
function outputRequest(input) {
|
|
1614
|
+
return {
|
|
1615
|
+
hook: HookLabel.LLM_OUTPUT,
|
|
1616
|
+
...input.mode === void 0 ? {} : { mode: input.mode },
|
|
1617
|
+
...input.review === void 0 ? {} : { review: input.review },
|
|
1618
|
+
...input.metadata === void 0 ? {} : { metadata: input.metadata },
|
|
1619
|
+
...input.signal === void 0 ? {} : { signal: input.signal }
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1309
1622
|
function isRecord2(value) {
|
|
1310
1623
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1311
1624
|
}
|
|
@@ -1551,6 +1864,8 @@ var Firewall = class {
|
|
|
1551
1864
|
shadowMode;
|
|
1552
1865
|
mode;
|
|
1553
1866
|
review;
|
|
1867
|
+
/** @internal Shared by adapters so one conversation keeps a single send order. */
|
|
1868
|
+
pending;
|
|
1554
1869
|
headers;
|
|
1555
1870
|
constructor(options) {
|
|
1556
1871
|
if (!options.apiKey) {
|
|
@@ -1573,6 +1888,10 @@ var Firewall = class {
|
|
|
1573
1888
|
this.mode = validateMode(options.mode) ?? legacyMode(options.shadowMode);
|
|
1574
1889
|
this.review = validateReview(options.review, "review");
|
|
1575
1890
|
this.shadowMode = this.mode === "shadow";
|
|
1891
|
+
this.pending = new PendingVerdicts(
|
|
1892
|
+
validateLimit("maxConcurrent", options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT),
|
|
1893
|
+
validateLimit("maxQueued", options.maxQueued ?? DEFAULT_MAX_QUEUED)
|
|
1894
|
+
);
|
|
1576
1895
|
this.headers = Object.freeze({
|
|
1577
1896
|
"x-api-key": this.apiKey,
|
|
1578
1897
|
"content-type": "application/json"
|
|
@@ -1582,6 +1901,87 @@ var Firewall = class {
|
|
|
1582
1901
|
const requestId = options.requestId ?? randomUUID();
|
|
1583
1902
|
return this.classifySingle(sanitizeText(text), options, { requestId });
|
|
1584
1903
|
}
|
|
1904
|
+
/**
|
|
1905
|
+
* Run an operation while its input is classified and withhold a blocked result.
|
|
1906
|
+
* The operation's signal aborts when a block arrives before it finishes.
|
|
1907
|
+
*/
|
|
1908
|
+
async protect(operation, options) {
|
|
1909
|
+
const { text, output, ...request } = options;
|
|
1910
|
+
const requestedMode = validateMode(options.mode) ?? this.mode;
|
|
1911
|
+
const controller = new AbortController();
|
|
1912
|
+
if (requestedMode === "shadow" || requestedMode === "warn") {
|
|
1913
|
+
const observed = this.observable(request);
|
|
1914
|
+
if (observed !== void 0) {
|
|
1915
|
+
void this.background(text, observed);
|
|
1916
|
+
}
|
|
1917
|
+
const result2 = await operation(controller.signal);
|
|
1918
|
+
if (observed !== void 0 && output !== void 0) {
|
|
1919
|
+
void this.background(output(result2), outputRequest(observed));
|
|
1920
|
+
}
|
|
1921
|
+
return result2;
|
|
1922
|
+
}
|
|
1923
|
+
const input = snapshotRequest(request);
|
|
1924
|
+
const conversation = conversationId(input.metadata);
|
|
1925
|
+
const outputOptions = outputRequest(input);
|
|
1926
|
+
const verdict = this.pending.submit(() => this.enforce(text, input), conversation, input.signal);
|
|
1927
|
+
const [, result] = await Promise.all([
|
|
1928
|
+
verdict.catch((error) => {
|
|
1929
|
+
controller.abort(error);
|
|
1930
|
+
throw error;
|
|
1931
|
+
}),
|
|
1932
|
+
Promise.resolve().then(() => operation(controller.signal))
|
|
1933
|
+
]);
|
|
1934
|
+
if (output !== void 0) {
|
|
1935
|
+
const generated = output(result);
|
|
1936
|
+
await this.pending.submit(
|
|
1937
|
+
() => this.enforce(generated, outputOptions),
|
|
1938
|
+
conversation,
|
|
1939
|
+
input.signal
|
|
1940
|
+
);
|
|
1941
|
+
}
|
|
1942
|
+
return result;
|
|
1943
|
+
}
|
|
1944
|
+
/** Wait for classifications still running in the background. */
|
|
1945
|
+
flush() {
|
|
1946
|
+
return this.pending.drain();
|
|
1947
|
+
}
|
|
1948
|
+
/**
|
|
1949
|
+
* @internal Classify in the background with one retry; resolves undefined on failure.
|
|
1950
|
+
* The request is copied now and detached from the caller's signal.
|
|
1951
|
+
*/
|
|
1952
|
+
observe(text, options = {}) {
|
|
1953
|
+
const request = this.observable(options);
|
|
1954
|
+
return request === void 0 ? Promise.resolve(void 0) : this.background(text, request);
|
|
1955
|
+
}
|
|
1956
|
+
background(text, request) {
|
|
1957
|
+
return this.pending.observe(() => this.classify(text, request), conversationId(request.metadata));
|
|
1958
|
+
}
|
|
1959
|
+
/** Copy a background request, reporting one that cannot be copied instead of failing the caller. */
|
|
1960
|
+
observable(options) {
|
|
1961
|
+
try {
|
|
1962
|
+
const request = snapshotRequest(options);
|
|
1963
|
+
delete request.signal;
|
|
1964
|
+
return request;
|
|
1965
|
+
} catch (error) {
|
|
1966
|
+
reportBackground("background classification failed", error);
|
|
1967
|
+
return void 0;
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
async enforce(text, options) {
|
|
1971
|
+
const result = await this.classify(text, options);
|
|
1972
|
+
const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
|
|
1973
|
+
if (blocked && (result.mode ?? "block") === "block") {
|
|
1974
|
+
throw new FirewallBlockedException({
|
|
1975
|
+
score: result.score,
|
|
1976
|
+
threshold: result.threshold,
|
|
1977
|
+
promptText: text,
|
|
1978
|
+
...options.hook === void 0 ? {} : { hook: options.hook },
|
|
1979
|
+
...options.toolName === void 0 ? {} : { toolName: options.toolName },
|
|
1980
|
+
result
|
|
1981
|
+
});
|
|
1982
|
+
}
|
|
1983
|
+
return result;
|
|
1984
|
+
}
|
|
1585
1985
|
async classifyBatch(texts, options = {}) {
|
|
1586
1986
|
if (texts.length === 0) {
|
|
1587
1987
|
throw new Error("Firewall: texts must not be empty");
|
|
@@ -1658,7 +2058,8 @@ var Firewall = class {
|
|
|
1658
2058
|
asMiddleware(options = {}) {
|
|
1659
2059
|
return createMiddleware(this, options);
|
|
1660
2060
|
}
|
|
1661
|
-
async postWithRetry(payload, callerSignal
|
|
2061
|
+
async postWithRetry(payload, callerSignal) {
|
|
2062
|
+
const maxRetries = retryBudget(DEFAULT_MAX_RETRIES);
|
|
1662
2063
|
callerSignal?.throwIfAborted();
|
|
1663
2064
|
const body = JSON.stringify(payload);
|
|
1664
2065
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|