@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/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,35 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.10.0
|
|
4
|
+
|
|
5
|
+
- Classify model output by default: `LLM_END` joins `DEFAULT_HOOKS` for the
|
|
6
|
+
LangChain handler, and `scanOutput` defaults to `true` in both Vercel
|
|
7
|
+
adapters. On AI SDK 7, Block-mode streams now deliver each text block only
|
|
8
|
+
after its verdict unless `scanOutput: false` is passed.
|
|
9
|
+
- Read generated text and tool calls from `content` parts in the AI SDK 5/6
|
|
10
|
+
middleware. Earlier releases read only the legacy `text` and `toolCalls`
|
|
11
|
+
fields, so `scanOutput` and `scanToolCalls` did not run on generate results.
|
|
12
|
+
- Add `Firewall.protect()`, which runs a call while its input is classified,
|
|
13
|
+
withholds the result of a blocked input, and aborts the call's signal when
|
|
14
|
+
the block arrives first.
|
|
15
|
+
- Add a `parallel` option to the LangChain handler,
|
|
16
|
+
`protectLangChainRunnable()`, the Deep Agents middleware, and both Vercel
|
|
17
|
+
adapters. Input and tool-result checks run beside the model call; tool-call
|
|
18
|
+
and model-output checks still wait for their verdict.
|
|
19
|
+
- Classify in the background in Shadow mode for the LangChain handler and Deep
|
|
20
|
+
Agents middleware unless `failOpen` is `false`.
|
|
21
|
+
- Send classifications that share `metadata.conversationId` in the order they
|
|
22
|
+
were started, including the `protect()` output check. Add `maxConcurrent`
|
|
23
|
+
and `maxQueued` client options and `flush()`. Background classifications
|
|
24
|
+
are also capped at `maxConcurrent * maxQueued` across all conversations.
|
|
25
|
+
- Copy `metadata` and `governance` when a queued classification starts, and
|
|
26
|
+
stop a queued classification waiting once its caller's `signal` aborts.
|
|
27
|
+
- With `parallel`, concurrent LangChain tool starts wait for the same pending
|
|
28
|
+
checks, a landed block is raised at every later boundary of the run, and
|
|
29
|
+
the Vercel and Deep Agents adapters send their checks through the client's
|
|
30
|
+
in-flight limit. Shadow-mode Deep Agents caches a remote notification once
|
|
31
|
+
its background classification completes.
|
|
32
|
+
|
|
3
33
|
## 0.9.1
|
|
4
34
|
|
|
5
35
|
- Add a separate AI SDK 7 `LanguageModelV4Middleware` export at
|
package/README.md
CHANGED
|
@@ -23,6 +23,7 @@ This SDK provides the low-level TypeScript interface for that workflow:
|
|
|
23
23
|
- Send each complete sanitized event in one request.
|
|
24
24
|
- On individual `classify()` calls, preserve exact `metadata.conversationId` as sequence identity and add one event ID.
|
|
25
25
|
- Retry API rate-limit responses.
|
|
26
|
+
- Optionally classify in parallel with the model call it protects.
|
|
26
27
|
- Optionally attach the firewall to Vercel AI SDK middleware, LangChain.js
|
|
27
28
|
callback flows, and Deep Agents middleware/constructors.
|
|
28
29
|
|
|
@@ -34,10 +35,10 @@ This SDK is distributed as an npm package.
|
|
|
34
35
|
npm install @silmaril-security/sdk
|
|
35
36
|
```
|
|
36
37
|
|
|
37
|
-
Pin version 0.
|
|
38
|
+
Pin version 0.10.0 for reproducible installs:
|
|
38
39
|
|
|
39
40
|
```sh
|
|
40
|
-
npm install @silmaril-security/sdk@0.
|
|
41
|
+
npm install @silmaril-security/sdk@0.10.0
|
|
41
42
|
```
|
|
42
43
|
|
|
43
44
|
Requires Node 20 or later.
|
|
@@ -296,6 +297,8 @@ interface FirewallOptions {
|
|
|
296
297
|
mode?: "shadow" | "warn" | "block"; // explicit local client default
|
|
297
298
|
review?: "standard" | "deep"; // explicit client review default
|
|
298
299
|
shadowMode?: boolean; // deprecated legacy mapping
|
|
300
|
+
maxConcurrent?: number; // default: 32 classifications in flight beside the host flow
|
|
301
|
+
maxQueued?: number; // default: 64 unjoined background checks per conversation; maxConcurrent * maxQueued in total
|
|
299
302
|
}
|
|
300
303
|
```
|
|
301
304
|
|
|
@@ -548,8 +551,63 @@ sent input. A missing array or mismatched count raises an `Error` before
|
|
|
548
551
|
results are returned or blocking callbacks run. Retries use the original
|
|
549
552
|
payload snapshot, even if caller-owned inputs change while the request is in flight.
|
|
550
553
|
|
|
554
|
+
## Parallel Classification
|
|
555
|
+
|
|
556
|
+
`protect()` runs your call while its input is classified, instead of waiting
|
|
557
|
+
for the verdict first. It takes the same options as `classify()` and returns
|
|
558
|
+
your call's result:
|
|
559
|
+
|
|
560
|
+
```ts
|
|
561
|
+
const answer = await fw.protect((signal) => callModel(prompt, { signal }), {
|
|
562
|
+
text: prompt,
|
|
563
|
+
hook: HookLabel.USER_INPUT,
|
|
564
|
+
metadata: { conversationId },
|
|
565
|
+
output: (response) => response.text,
|
|
566
|
+
});
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
Unlike `classify()`, `protect()` enforces. In Block mode, or when no mode is
|
|
570
|
+
set, the result is withheld until the verdict arrives and a block throws
|
|
571
|
+
`FirewallBlockedException`. The `signal` passed to your call aborts when the
|
|
572
|
+
block lands first; a call that ignores it keeps running and its result is
|
|
573
|
+
discarded. In Shadow and Warn the result is returned immediately and the
|
|
574
|
+
classification finishes in the background. The optional `output` extractor
|
|
575
|
+
classifies the result as `llm_output` before it is returned.
|
|
576
|
+
|
|
577
|
+
Use `protect()` only for calls whose effect can be discarded. Classify the
|
|
578
|
+
arguments of a tool that writes with `classify()` before running it.
|
|
579
|
+
|
|
580
|
+
Classifications that share `metadata.conversationId` are sent in the order
|
|
581
|
+
they were started, so parallel checks keep the backend sequence intact. The
|
|
582
|
+
output check waits in that same order. `maxConcurrent` bounds how many run at
|
|
583
|
+
once, including output checks and every check an adapter makes with
|
|
584
|
+
`parallel: true`. The `metadata` and `governance` you pass are
|
|
585
|
+
copied when the call starts, so changing them afterwards does not change a
|
|
586
|
+
classification that is still waiting.
|
|
587
|
+
|
|
588
|
+
Aborting the `signal` you pass stops a classification that is still waiting
|
|
589
|
+
for its turn, rejects `protect()` with the signal's reason, and aborts your
|
|
590
|
+
operation's signal. Classifications queued after it keep their order.
|
|
591
|
+
|
|
592
|
+
A background classification retries once, never rejects, logs its failure with
|
|
593
|
+
`console.warn`, and does not follow the caller's `signal`. One that would
|
|
594
|
+
exceed `maxQueued` unjoined checks for its conversation, or
|
|
595
|
+
`maxConcurrent * maxQueued` background checks across all conversations
|
|
596
|
+
(2,048 by default), is dropped with a warning. `await fw.flush()` waits for
|
|
597
|
+
background classifications to finish, for example before a serverless handler
|
|
598
|
+
returns.
|
|
599
|
+
|
|
551
600
|
## Migration Notes
|
|
552
601
|
|
|
602
|
+
Version `0.10.0` classifies model output by default. The LangChain handler adds
|
|
603
|
+
`LLM_END` to `DEFAULT_HOOKS`, and both Vercel adapters default `scanOutput` to
|
|
604
|
+
`true`. Pass `hooks` without `FirewallHook.LLM_END`, or `scanOutput: false`,
|
|
605
|
+
to keep the previous behavior. On AI SDK 7 this means Block-mode streams
|
|
606
|
+
deliver each text block only after its verdict; see the Vercel AI SDK 7
|
|
607
|
+
section. Shadow-mode LangChain handlers and Deep Agents middleware now classify
|
|
608
|
+
in the background unless `failOpen` is `false`, so `onClassify` can run after
|
|
609
|
+
the hook returns.
|
|
610
|
+
|
|
553
611
|
Version `0.4.1` is the public npm recovery release for `0.4.x`: the `v0.4.0`
|
|
554
612
|
Git tag exists, but `@silmaril-security/sdk@0.4.0` was not published to npm.
|
|
555
613
|
Use `0.4.1` or later. This release moves all threshold decisions to Firewall
|
|
@@ -580,19 +638,28 @@ const { text } = await generateText({ model, prompt: "Hello" });
|
|
|
580
638
|
console.log(text);
|
|
581
639
|
```
|
|
582
640
|
|
|
583
|
-
Middleware scans input by default (`scanInput`
|
|
584
|
-
that message's tool-result parts
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
output
|
|
641
|
+
Middleware scans input and generated text by default (`scanInput` and
|
|
642
|
+
`scanOutput` default to true). It classifies that message's tool-result parts
|
|
643
|
+
as `tool_response` only when the newest prompt message is a tool message.
|
|
644
|
+
Otherwise it classifies the latest user message as `user_input` and does not
|
|
645
|
+
scan earlier tool results. Set `scanOutput: false` to skip model text, and
|
|
646
|
+
`scanToolCalls: true` to classify tool-call arguments on generate results.
|
|
647
|
+
Generated text and tool calls are read from the `content` parts that AI SDK 5
|
|
648
|
+
and 6 return; releases before 0.10.0 read only the legacy `text` and
|
|
649
|
+
`toolCalls` fields, so those checks did not run on generate results there.
|
|
650
|
+
Infrastructure errors and blocking decisions are fail-closed by default and
|
|
651
|
+
bubble up to the caller.
|
|
652
|
+
|
|
653
|
+
With streaming, output is classified in the stream's `flush` after all deltas
|
|
654
|
+
have been emitted, so blocking is advisory: the consumer has already seen the
|
|
655
|
+
text by the time an error part is enqueued. Use non-streaming generation if
|
|
656
|
+
you need to block before the caller observes output.
|
|
657
|
+
|
|
658
|
+
Set `parallel: true` to run the input check beside the model call. The result,
|
|
659
|
+
or the stream, is withheld until that verdict arrives; a blocked input throws
|
|
660
|
+
and a stream that already started is cancelled. Because this middleware fails
|
|
661
|
+
closed, Shadow and Warn checks are still awaited rather than moved to the
|
|
662
|
+
background, so classification errors keep reaching the caller.
|
|
596
663
|
|
|
597
664
|
### Vercel AI SDK 7
|
|
598
665
|
|
|
@@ -626,7 +693,11 @@ console.log(result.text);
|
|
|
626
693
|
|
|
627
694
|
The v4 adapter reads generated text and tool calls from `result.content`, and
|
|
628
695
|
classifies prompt tool-result parts with their tool name and call ID. Reasoning
|
|
629
|
-
parts are passed through unchanged and are not classified.
|
|
696
|
+
parts are passed through unchanged and are not classified. `scanOutput`
|
|
697
|
+
defaults to true, so in effective or possible Block mode a stream delivers
|
|
698
|
+
each text block only once it is complete and has a verdict, not token by
|
|
699
|
+
token. Pass `scanOutput: false`, or select Shadow or Warn, to keep incremental
|
|
700
|
+
delivery. `parallel: true` behaves as it does for the AI SDK 5/6 middleware.
|
|
630
701
|
|
|
631
702
|
For streaming, text and tool-input sequences are tracked by ID. In effective or
|
|
632
703
|
possible Block mode, the adapter retains original text and tool-input parts in a
|
|
@@ -695,8 +766,18 @@ and the LLM call proceeds. Set `failOpen: false` to make API errors bubble up.
|
|
|
695
766
|
Blocking decisions throw `FirewallBlockedException` only when the effective mode
|
|
696
767
|
is Block; Shadow and Warn preserve the host flow.
|
|
697
768
|
`PromptBlockedException` continues to work as a deprecated alias.
|
|
698
|
-
Model-start, tool-start, and
|
|
699
|
-
|
|
769
|
+
Model-start, tool-start, tool-end, and model-end (`LLM_END`) hooks are enabled
|
|
770
|
+
by default; retriever hooks remain opt-in. With streaming, the model-end check
|
|
771
|
+
runs after tokens are emitted: a block stops the run and cannot recall them.
|
|
772
|
+
Pass `parallel: true` to the handler or to `protectLangChainRunnable()` to run
|
|
773
|
+
the `user_input` and `tool_response` checks beside the model call. They are
|
|
774
|
+
joined when the model call ends, before a tool starts, and when the run ends;
|
|
775
|
+
the `tool_call` and `llm_output` checks always wait for their verdict. Tools
|
|
776
|
+
that start concurrently all wait for the same pending checks. A block that has
|
|
777
|
+
already arrived is thrown at the next callback, including the next streamed
|
|
778
|
+
token, and at every later boundary until the run ends. Callbacks cannot cancel
|
|
779
|
+
a model call, so a late block discards its output. In Shadow mode every check runs in the background and nothing is
|
|
780
|
+
joined, unless `failOpen: false` requires each classification to succeed. The LangChain run ID is sent as
|
|
700
781
|
`metadata.langgraph.run_id`; every classification gets a distinct
|
|
701
782
|
`metadata.silmaril.request_id`. The current native thread ID is sent as
|
|
702
783
|
`metadata.conversationId` without a separate Silmaril conversation option.
|
|
@@ -785,6 +866,13 @@ Classification errors allow model and tool execution by default; set
|
|
|
785
866
|
`silmaril: { failOpen: false }` to require a successful classification. Already
|
|
786
867
|
emitted streaming text cannot be recalled.
|
|
787
868
|
|
|
869
|
+
Set `silmaril: { parallel: true }` to classify user input while the model call
|
|
870
|
+
runs. A blocked input replaces the response without waiting for the model.
|
|
871
|
+
Tool calls and tool results still wait for their verdict, because a denied
|
|
872
|
+
result is replaced before it enters agent state, and the input check waits
|
|
873
|
+
again once `maxBlockedAttempts` is reached. Shadow mode classifies in the
|
|
874
|
+
background unless `failOpen` is `false`.
|
|
875
|
+
|
|
788
876
|
### Remote subagents
|
|
789
877
|
|
|
790
878
|
Remote support requires `deepagents@>=1.16.0 <1.17.0`. Use `createProtectedDeepAgent`
|
|
@@ -873,7 +961,7 @@ checkpoint namespaces do not change the conversation ID. The direct
|
|
|
873
961
|
## Retries
|
|
874
962
|
|
|
875
963
|
HTTP 429 responses are retried with exponential backoff capped at 30s, up to 5
|
|
876
|
-
times. The retried response body is discarded before the wait, and each request
|
|
964
|
+
times, or once for a background classification. The retried response body is discarded before the wait, and each request
|
|
877
965
|
payload is serialized once so every attempt sends the same logical event.
|
|
878
966
|
Redirects are rejected rather than followed; native `fetch` surfaces that
|
|
879
967
|
refusal as a `TypeError` without a reliable redirect status. Actually received
|
|
@@ -74,7 +74,8 @@ var DEFAULT_HOOKS = /* @__PURE__ */ new Set([
|
|
|
74
74
|
FirewallHook.LLM_START,
|
|
75
75
|
FirewallHook.CHAT_MODEL_START,
|
|
76
76
|
FirewallHook.TOOL_START,
|
|
77
|
-
FirewallHook.TOOL_END
|
|
77
|
+
FirewallHook.TOOL_END,
|
|
78
|
+
FirewallHook.LLM_END
|
|
78
79
|
]);
|
|
79
80
|
var INPUT_HOOKS = /* @__PURE__ */ new Set([
|
|
80
81
|
FirewallHook.LLM_START,
|
|
@@ -110,6 +111,14 @@ function validateMode(value) {
|
|
|
110
111
|
throw new Error("Firewall: mode must be shadow, warn, or block");
|
|
111
112
|
}
|
|
112
113
|
|
|
114
|
+
// src/pending.ts
|
|
115
|
+
var import_node_async_hooks = require("async_hooks");
|
|
116
|
+
var retryLimit = new import_node_async_hooks.AsyncLocalStorage();
|
|
117
|
+
function conversationId(metadata) {
|
|
118
|
+
const value = metadata?.conversationId;
|
|
119
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
120
|
+
}
|
|
121
|
+
|
|
113
122
|
// src/adapters/thread-identity.ts
|
|
114
123
|
function record(value) {
|
|
115
124
|
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
@@ -347,50 +356,74 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
|
|
|
347
356
|
}
|
|
348
357
|
const effectiveMode = validateMode(options.mode) ?? firewall.mode;
|
|
349
358
|
const notificationChecks = /* @__PURE__ */ new Map();
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
}
|
|
359
|
-
const mode = effectiveMode ?? result.mode ?? "block";
|
|
360
|
-
const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
|
|
361
|
-
if (options.onClassify) {
|
|
362
|
-
try {
|
|
363
|
-
options.onClassify({ hook, ...toolName === void 0 ? {} : { toolName }, text, result, blocked, mode, shadowMode: mode === "shadow" });
|
|
364
|
-
} catch {
|
|
365
|
-
}
|
|
359
|
+
const parallel = options.parallel ?? false;
|
|
360
|
+
const background = effectiveMode === "shadow" && options.failOpen !== false;
|
|
361
|
+
const decide = (result, text, hook, toolName) => {
|
|
362
|
+
const mode = effectiveMode ?? result.mode ?? "block";
|
|
363
|
+
const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
|
|
364
|
+
if (options.onClassify) {
|
|
365
|
+
try {
|
|
366
|
+
options.onClassify({ hook, ...toolName === void 0 ? {} : { toolName }, text, result, blocked, mode, shadowMode: mode === "shadow" });
|
|
367
|
+
} catch {
|
|
366
368
|
}
|
|
367
|
-
return { enforce: blocked && mode === "block", mode, cacheable: true };
|
|
368
|
-
} catch (error) {
|
|
369
|
-
if (isReviewCompatibilityError(error)) throw error;
|
|
370
|
-
if (options.failOpen === false) throw error;
|
|
371
|
-
return { enforce: false, mode: effectiveMode };
|
|
372
369
|
}
|
|
370
|
+
return { enforce: blocked && mode === "block", mode, cacheable: true };
|
|
371
|
+
};
|
|
372
|
+
const prepare = (text, hook, conversationId2, toolName) => {
|
|
373
|
+
if (!text.trim()) return async () => ({ enforce: false, mode: effectiveMode });
|
|
374
|
+
const request = {
|
|
375
|
+
hook,
|
|
376
|
+
...toolName === void 0 ? {} : { toolName },
|
|
377
|
+
...effectiveMode === void 0 ? {} : { mode: effectiveMode },
|
|
378
|
+
metadata: { ...conversationId2 === void 0 ? {} : { conversationId: conversationId2 }, ...remoteLineage((0, import_runnables.ensureConfig)()) }
|
|
379
|
+
};
|
|
380
|
+
if (background) {
|
|
381
|
+
const observed = firewall.observe(text, request).then((result) => {
|
|
382
|
+
if (result !== void 0) decide(result, text, hook, toolName);
|
|
383
|
+
return result !== void 0;
|
|
384
|
+
});
|
|
385
|
+
return async () => ({ enforce: false, mode: effectiveMode, observed });
|
|
386
|
+
}
|
|
387
|
+
return async () => {
|
|
388
|
+
try {
|
|
389
|
+
return decide(await firewall.classify(text, request), text, hook, toolName);
|
|
390
|
+
} catch (error) {
|
|
391
|
+
if (isReviewCompatibilityError(error)) throw error;
|
|
392
|
+
if (options.failOpen === false) throw error;
|
|
393
|
+
return { enforce: false, mode: effectiveMode };
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
};
|
|
397
|
+
const classify = (text, hook, conversationId2, toolName) => {
|
|
398
|
+
const check = prepare(text, hook, conversationId2, toolName);
|
|
399
|
+
return parallel && !background ? firewall.pending.submit(check, conversationId({ conversationId: conversationId2 })) : check();
|
|
400
|
+
};
|
|
401
|
+
const rememberNotification = (key, blocked) => {
|
|
402
|
+
notificationChecks.set(key, blocked);
|
|
403
|
+
while (notificationChecks.size > 1024) notificationChecks.delete(notificationChecks.keys().next().value);
|
|
373
404
|
};
|
|
374
405
|
return (0, import_langchain.createMiddleware)({
|
|
375
406
|
name: "SilmarilDeepAgentsMiddleware",
|
|
376
407
|
wrapModelCall: async (request, handler) => {
|
|
377
|
-
const
|
|
408
|
+
const conversationId2 = nativeThreadId(request.runtime, void 0, void 0, (0, import_runnables.ensureConfig)());
|
|
378
409
|
const messages = [];
|
|
379
410
|
for (const message of request.messages) {
|
|
380
411
|
let blocked = false;
|
|
381
412
|
if (remoteNotification(message)) {
|
|
382
|
-
const key = await notificationKey(message,
|
|
413
|
+
const key = await notificationKey(message, conversationId2, effectiveMode);
|
|
383
414
|
const cached = key === void 0 ? void 0 : notificationChecks.get(key);
|
|
384
415
|
if (cached !== void 0) {
|
|
385
416
|
blocked = cached;
|
|
386
417
|
notificationChecks.delete(key);
|
|
387
418
|
notificationChecks.set(key, cached);
|
|
388
419
|
} else {
|
|
389
|
-
const decision = await classify(textOf(message), HookLabel.TOOL_RESPONSE,
|
|
420
|
+
const decision = await classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId2, "async_subagent");
|
|
390
421
|
blocked = decision.enforce;
|
|
391
|
-
if (key !== void 0 && decision.cacheable)
|
|
392
|
-
|
|
393
|
-
|
|
422
|
+
if (key !== void 0 && decision.cacheable) rememberNotification(key, blocked);
|
|
423
|
+
if (key !== void 0) {
|
|
424
|
+
void decision.observed?.then((completed) => {
|
|
425
|
+
if (completed) rememberNotification(key, false);
|
|
426
|
+
});
|
|
394
427
|
}
|
|
395
428
|
}
|
|
396
429
|
}
|
|
@@ -409,23 +442,27 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
|
|
|
409
442
|
(message) => import_messages.ToolMessage.isInstance(message) && message.content === SAFE_TOOL_MESSAGE && message.additional_kwargs?.silmarilBlocked === BLOCKED_TOOL_MARKER
|
|
410
443
|
).length;
|
|
411
444
|
const latestUser = [...request.messages].reverse().find(import_messages.HumanMessage.isInstance);
|
|
412
|
-
const
|
|
445
|
+
const racesModel = parallel && !background && blockedCount < maxBlockedAttempts;
|
|
446
|
+
const protectedRequest = request;
|
|
447
|
+
const running = racesModel ? Promise.resolve().then(() => handler(protectedRequest)) : void 0;
|
|
448
|
+
running?.catch(() => void 0);
|
|
449
|
+
const inputDecision = latestUser === void 0 ? void 0 : await classify(textOf(latestUser), HookLabel.USER_INPUT, conversationId2);
|
|
413
450
|
if (inputDecision?.enforce) return new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE);
|
|
414
451
|
const capMode = effectiveMode ?? inputDecision?.mode ?? "block";
|
|
415
452
|
if (blockedCount >= maxBlockedAttempts && capMode === "block") {
|
|
416
453
|
return new import_messages.AIMessage(SAFE_FINAL_MESSAGE);
|
|
417
454
|
}
|
|
418
|
-
const response = await handler(request);
|
|
419
|
-
if (response instanceof import_langgraph.Command && (await classify(textOfStructuredValue(response.update), HookLabel.LLM_OUTPUT,
|
|
455
|
+
const response = await (running ?? handler(request));
|
|
456
|
+
if (response instanceof import_langgraph.Command && (await classify(textOfStructuredValue(response.update), HookLabel.LLM_OUTPUT, conversationId2)).enforce) {
|
|
420
457
|
return new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE);
|
|
421
458
|
}
|
|
422
|
-
if (import_messages.AIMessage.isInstance(response) && (await classify(textOf(response), HookLabel.LLM_OUTPUT,
|
|
459
|
+
if (import_messages.AIMessage.isInstance(response) && (await classify(textOf(response), HookLabel.LLM_OUTPUT, conversationId2)).enforce) {
|
|
423
460
|
return new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE);
|
|
424
461
|
}
|
|
425
462
|
return response;
|
|
426
463
|
},
|
|
427
464
|
wrapToolCall: async (request, handler) => {
|
|
428
|
-
const
|
|
465
|
+
const conversationId2 = nativeThreadId(request.runtime, void 0, void 0, (0, import_runnables.ensureConfig)());
|
|
429
466
|
const safe = () => {
|
|
430
467
|
const message = new import_messages.ToolMessage({
|
|
431
468
|
content: SAFE_TOOL_MESSAGE,
|
|
@@ -436,7 +473,7 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
|
|
|
436
473
|
issuedBlockedMessages.add(message);
|
|
437
474
|
return message;
|
|
438
475
|
};
|
|
439
|
-
if ((await classify(JSON.stringify(request.toolCall.args ?? {}), HookLabel.TOOL_CALL,
|
|
476
|
+
if ((await classify(JSON.stringify(request.toolCall.args ?? {}), HookLabel.TOOL_CALL, conversationId2, request.toolCall.name)).enforce) {
|
|
440
477
|
return safe();
|
|
441
478
|
}
|
|
442
479
|
const result = await handler(request);
|
|
@@ -444,10 +481,10 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
|
|
|
444
481
|
try {
|
|
445
482
|
resultText = import_messages.ToolMessage.isInstance(result) ? textOf(result) : result instanceof import_langgraph.Command ? textOfStructuredValue(result.update) : String(result);
|
|
446
483
|
} catch {
|
|
447
|
-
const decision = await classify("[uninspectable tool result]", HookLabel.TOOL_RESPONSE,
|
|
484
|
+
const decision = await classify("[uninspectable tool result]", HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name);
|
|
448
485
|
return decision.mode === "block" ? safe() : stripAllowedMarker(result);
|
|
449
486
|
}
|
|
450
|
-
if ((await classify(resultText, HookLabel.TOOL_RESPONSE,
|
|
487
|
+
if ((await classify(resultText, HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name)).enforce) {
|
|
451
488
|
if (["start_async_task", "check_async_task", "update_async_task", "cancel_async_task", "list_async_tasks"].includes(request.toolCall.name) && result instanceof import_langgraph.Command && result.update && !Array.isArray(result.update) && "asyncTasks" in result.update) {
|
|
452
489
|
return new import_langgraph.Command({ update: { messages: [safe()], asyncTasks: result.update.asyncTasks } });
|
|
453
490
|
}
|