@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/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.0
4
+
5
+ - Make `parallel` behave the same across integrations. Deep Agents now runs
6
+ tool-result checks beside the next model call, joins them when that call or
7
+ the run ends, and replaces a blocked result in agent state before running the
8
+ model again on the safe history. A resumed run checks tool results whose
9
+ verdict was never joined, and late denials count toward `maxBlockedAttempts`.
10
+ Tools that return a `Command` keep their check before the update applies.
11
+ - The `Firewall` client remembers allowed user messages and async-subagent
12
+ notification verdicts by thread ID, message ID, content and mode. The Deep
13
+ Agents middleware and LangChain adapters share that memory, so later model
14
+ calls do not classify the same message again. Only completed
15
+ classifications are remembered, so a failed or dropped check runs again.
16
+ - `protectLangChainRunnable()` streams withhold chunks until the model start
17
+ and every check started so far have passed, and stop reading from the model
18
+ while 1,024 chunks are held.
19
+ - Shadow and Warn classify in the background in the Vercel AI SDK middleware,
20
+ the LangChain handler and the Deep Agents middleware. The Vercel middleware
21
+ gains `failOpen`, and `failOpen: false` keeps those checks inline so
22
+ classification errors reach the caller.
23
+
24
+ ## 0.11.4
25
+
26
+ - Cancel the Node HTTP example on premature response closure.
27
+
3
28
  ## 0.11.3
4
29
 
5
30
  - Reject `protect()` with the caller's abort reason when the operation or output
package/README.md CHANGED
@@ -35,10 +35,10 @@ This SDK is distributed as an npm package.
35
35
  npm install @silmaril-security/sdk
36
36
  ```
37
37
 
38
- Pin version 0.11.3 for reproducible installs:
38
+ Pin version 0.12.0 for reproducible installs:
39
39
 
40
40
  ```sh
41
- npm install @silmaril-security/sdk@0.11.3
41
+ npm install @silmaril-security/sdk@0.12.0
42
42
  ```
43
43
 
44
44
  Requires Node 20 or later.
@@ -203,11 +203,16 @@ Events that belong to one conversation are not independent. Send them with
203
203
  ordered individual `classify()` calls that share `metadata.conversationId`, and
204
204
  wait for each call before sending the next event for that conversation.
205
205
 
206
- Pass a `signal` to cancel one call without touching its siblings:
206
+ Pass a `signal` to cancel one call without touching its siblings. In Node's
207
+ HTTP server, listen for the outgoing response closing before it finishes:
207
208
 
208
209
  ```ts
209
210
  const controller = new AbortController();
210
- request.on("close", () => controller.abort());
211
+ const abortIfDisconnected = () => {
212
+ if (!response.writableFinished) controller.abort();
213
+ };
214
+ response.once("close", abortIfDisconnected);
215
+ if (response.destroyed) abortIfDisconnected();
211
216
 
212
217
  try {
213
218
  const result = await fw.classify(userInput, {
@@ -220,6 +225,8 @@ try {
220
225
  return; // caller went away
221
226
  }
222
227
  throw err;
228
+ } finally {
229
+ response.off("close", abortIfDisconnected);
223
230
  }
224
231
  ```
225
232
 
@@ -669,10 +676,13 @@ text by the time an error part is enqueued. Use non-streaming generation if
669
676
  you need to block before the caller observes output.
670
677
 
671
678
  Set `parallel: true` to run the input check beside the model call. The result,
672
- or the stream, is withheld until that verdict arrives; a blocked input throws
673
- and a stream that already started is cancelled. Because this middleware fails
674
- closed, Shadow and Warn checks are still awaited rather than moved to the
675
- background, so classification errors keep reaching the caller.
679
+ or the stream, is withheld until that verdict arrives. A blocked input throws,
680
+ and a stream that already started is cancelled. Because the newest tool
681
+ results are checked as the next call's input, they run beside that call too.
682
+
683
+ In Shadow and Warn the middleware classifies in the background and reports
684
+ each decision through `onClassify`, as `protect()` does. Set `failOpen: false`
685
+ to keep those checks inline so classification errors reach the caller.
676
686
 
677
687
  ### Vercel AI SDK 7
678
688
 
@@ -788,13 +798,28 @@ by default; retriever hooks remain opt-in. With streaming, the model-end check
788
798
  runs after tokens are emitted: a block stops the run and cannot recall them.
789
799
  Pass `parallel: true` to the handler or to `protectLangChainRunnable()` to run
790
800
  the `user_input` and `tool_response` checks beside the model call. They are
791
- joined when the model call ends, before a tool starts, and when the run ends;
792
- the `tool_call` and `llm_output` checks always wait for their verdict. Tools
801
+ joined when the model call ends, before a tool starts, and when the run ends.
802
+ The `tool_call` and `llm_output` checks always wait for their verdict. Tools
793
803
  that start concurrently all wait for the same pending checks. A block that has
794
804
  already arrived is thrown at the next callback, including the next streamed
795
805
  token, and at every later boundary until the run ends. Callbacks cannot cancel
796
- a model call, so a late block discards its output. In Shadow mode every check runs in the background and nothing is
797
- joined, unless `failOpen: false` requires each classification to succeed. The LangChain run ID is sent as
806
+ a model call, so a late block discards its output.
807
+
808
+ `protectLangChainRunnable()` streams hold every chunk until the model start
809
+ and every check started so far have passed, while the model keeps generating.
810
+ Once 1,024 chunks are held, the stream stops reading from the model until those
811
+ checks finish, so a slow check never grows memory without bound. A bare handler, and
812
+ `streamEvents()` consumers, can see tokens before a pending verdict arrives,
813
+ so use the runnable wrapper when streamed output must wait for it.
814
+
815
+ The `Firewall` client remembers each allowed user message by thread ID and
816
+ message ID, so later model calls in that conversation do not classify the same
817
+ message again, even across separate invocations of a protected runnable. Only
818
+ a completed classification is remembered, so a check that fails or is dropped
819
+ runs again on the next model call. A message without an ID is classified on
820
+ every model call.
821
+ In Shadow and Warn every check runs in the background and nothing is joined,
822
+ unless `failOpen: false` requires each classification to succeed. The LangChain run ID is sent as
798
823
  `metadata.langgraph.run_id`; every classification gets a distinct
799
824
  `metadata.silmaril.request_id`. The current native thread ID is sent as
800
825
  `metadata.conversationId` without a separate Silmaril conversation option.
@@ -883,12 +908,27 @@ Classification errors allow model and tool execution by default; set
883
908
  `silmaril: { failOpen: false }` to require a successful classification. Already
884
909
  emitted streaming text cannot be recalled.
885
910
 
886
- Set `silmaril: { parallel: true }` to classify user input while the model call
887
- runs. A blocked input replaces the response without waiting for the model.
888
- Tool calls and tool results still wait for their verdict, because a denied
889
- result is replaced before it enters agent state, and the input check waits
890
- again once `maxBlockedAttempts` is reached. Shadow mode classifies in the
891
- background unless `failOpen` is `false`.
911
+ Set `silmaril: { parallel: true }` to classify user input and tool results
912
+ while the next model call runs. A blocked input replaces the response without
913
+ waiting for the model. A tool result that is a plain `ToolMessage` returns to
914
+ the agent at once, and its
915
+ check is joined when the next model call ends, or when the run ends if the
916
+ tool returned directly. When that check blocks, the middleware replaces the
917
+ result in agent state with the safe tool message, discards the model response
918
+ and runs the model again on the safe history, so the agent sees what it would
919
+ have seen without `parallel`. Late denials count toward `maxBlockedAttempts`.
920
+ Tool calls and model output always wait for their verdict, and the input check
921
+ waits again once `maxBlockedAttempts` is reached. A resumed run checks any tool
922
+ result whose verdict was never joined before the model call uses it. A tool
923
+ that returns a `Command` is still checked before its state update is applied,
924
+ because that update can change more than the message list.
925
+
926
+ The `Firewall` client remembers each allowed user message by thread ID and
927
+ message ID, so later model calls in that conversation do not classify it again.
928
+ Only a completed classification is remembered. Shadow and
929
+ Warn classify in the background unless `failOpen` is `false`. LangGraph
930
+ `messages` streams can show tokens from a model call whose response is later
931
+ discarded.
892
932
 
893
933
  ### Remote subagents
894
934
 
@@ -143,6 +143,40 @@ function rejectConversationOptions(options) {
143
143
  }
144
144
  }
145
145
 
146
+ // src/verdicts.ts
147
+ var REMEMBERED_LIMIT = 1024;
148
+ var Remembered = class {
149
+ entries = /* @__PURE__ */ new Map();
150
+ get(key) {
151
+ if (key === void 0 || !this.entries.has(key)) return void 0;
152
+ const value = this.entries.get(key);
153
+ this.set(key, value);
154
+ return value;
155
+ }
156
+ set(key, value) {
157
+ this.entries.delete(key);
158
+ this.entries.set(key, value);
159
+ while (this.entries.size > REMEMBERED_LIMIT) this.entries.delete(this.entries.keys().next().value);
160
+ }
161
+ take(key) {
162
+ const value = this.entries.get(key);
163
+ this.entries.delete(key);
164
+ return value;
165
+ }
166
+ };
167
+ async function digest(text) {
168
+ const bytes = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
169
+ return Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
170
+ }
171
+ async function verdictKey(message, threadId, mode) {
172
+ if (!threadId || !message.id) return void 0;
173
+ try {
174
+ return JSON.stringify([threadId, message.id, await digest(JSON.stringify([message.content, message.additional_kwargs])), mode]);
175
+ } catch {
176
+ return void 0;
177
+ }
178
+ }
179
+
146
180
  // src/adapters/deepagents.ts
147
181
  var SAFE_TOOL_MESSAGE = "Silmaril Firewall blocked this tool interaction. Choose a different safe action.";
148
182
  var SAFE_FINAL_MESSAGE = "Silmaril Firewall stopped this request after repeated unsafe actions.";
@@ -337,16 +371,44 @@ function remoteNotification(message) {
337
371
  const extra = message.additional_kwargs ?? {};
338
372
  return typeof extra.lc_source === "string" && extra.lc_source.includes("async_subagent") || extra.deepagents_notification !== null && typeof extra.deepagents_notification === "object";
339
373
  }
340
- async function notificationKey(message, threadId, mode) {
341
- if (!threadId || !message.id) return void 0;
342
- try {
343
- const payload = JSON.stringify([message.content, message.additional_kwargs]);
344
- const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(payload));
345
- const hash = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
346
- return JSON.stringify([threadId, message.id, hash, mode]);
347
- } catch {
348
- return void 0;
374
+ var ASYNC_TASK_TOOLS = /* @__PURE__ */ new Set([
375
+ "start_async_task",
376
+ "check_async_task",
377
+ "update_async_task",
378
+ "cancel_async_task",
379
+ "list_async_tasks"
380
+ ]);
381
+ function lastIndexWhere(items, predicate) {
382
+ for (let index = items.length - 1; index >= 0; index--) {
383
+ if (predicate(items[index])) return index;
349
384
  }
385
+ return -1;
386
+ }
387
+ function blockedToolMessage(toolCallId, name, id) {
388
+ const message = new import_messages.ToolMessage({
389
+ content: SAFE_TOOL_MESSAGE,
390
+ tool_call_id: toolCallId,
391
+ ...name === void 0 ? {} : { name },
392
+ ...id === void 0 ? {} : { id },
393
+ additional_kwargs: { silmarilBlocked: BLOCKED_TOOL_MARKER }
394
+ });
395
+ issuedBlockedMessages.add(message);
396
+ return message;
397
+ }
398
+ function isBlockedToolMessage(message) {
399
+ return import_messages.ToolMessage.isInstance(message) && message.content === SAFE_TOOL_MESSAGE && message.additional_kwargs?.silmarilBlocked === BLOCKED_TOOL_MARKER;
400
+ }
401
+ function rewriteInPlace(message, content) {
402
+ const { tool_calls: _toolCalls, function_call: _functionCall, ...additional_kwargs } = message.additional_kwargs ?? {};
403
+ const safe = {
404
+ content,
405
+ tool_calls: [],
406
+ invalid_tool_calls: [],
407
+ additional_kwargs,
408
+ ..."tool_call_chunks" in message ? { tool_call_chunks: [] } : {}
409
+ };
410
+ Object.assign(message, safe);
411
+ Object.assign(message.lc_kwargs, safe);
350
412
  }
351
413
  function createDeepAgentsMiddleware(firewall, options = {}) {
352
414
  rejectConversationOptions(options);
@@ -355,9 +417,10 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
355
417
  throw new Error("maxBlockedAttempts must be a positive integer");
356
418
  }
357
419
  const effectiveMode = validateMode(options.mode) ?? firewall.mode;
358
- const notificationChecks = /* @__PURE__ */ new Map();
420
+ const toolResultChecks = new Remembered();
359
421
  const parallel = options.parallel ?? false;
360
- const background = effectiveMode === "shadow" && options.failOpen !== false;
422
+ const background = (effectiveMode === "shadow" || effectiveMode === "warn") && options.failOpen !== false;
423
+ const queued = parallel && !background;
361
424
  const decide = (result, text, hook, toolName) => {
362
425
  const mode = effectiveMode ?? result.mode ?? "block";
363
426
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
@@ -396,83 +459,120 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
396
459
  };
397
460
  const classify = (text, hook, conversationId2, toolName) => {
398
461
  const check = prepare(text, hook, conversationId2, toolName);
399
- return parallel && !background ? firewall.pending.submit(check, conversationId({ conversationId: conversationId2 })) : check();
462
+ const decision = queued ? firewall.pending.submit(check, conversationId({ conversationId: conversationId2 })) : check();
463
+ decision.catch(() => void 0);
464
+ return decision;
465
+ };
466
+ const toolResultKey = async (conversationId2, toolCallId, text) => JSON.stringify([conversationId2 ?? null, toolCallId, await digest(text)]);
467
+ const unverifiedToolResults = async (messages, conversationId2) => {
468
+ const lastModelTurn = lastIndexWhere(messages, (message) => import_messages.AIMessage.isInstance(message));
469
+ const results = [];
470
+ for (const [index, message] of messages.entries()) {
471
+ if (index <= lastModelTurn || !import_messages.ToolMessage.isInstance(message) || isBlockedToolMessage(message)) continue;
472
+ const text = textOf(message);
473
+ const decision = toolResultChecks.take(await toolResultKey(conversationId2, message.tool_call_id, text)) ?? classify(text, HookLabel.TOOL_RESPONSE, conversationId2, message.name);
474
+ results.push({ index, message, decision });
475
+ }
476
+ return results;
400
477
  };
401
- const rememberNotification = (key, blocked) => {
402
- notificationChecks.set(key, blocked);
403
- while (notificationChecks.size > 1024) notificationChecks.delete(notificationChecks.keys().next().value);
478
+ const rememberAllowed = (key, decision) => {
479
+ if (key === void 0) return;
480
+ if (decision.cacheable && !decision.enforce) firewall.verdicts.set(key, false);
481
+ void decision.observed?.then((completed) => {
482
+ if (completed) firewall.verdicts.set(key, false);
483
+ });
404
484
  };
405
485
  return (0, import_langchain.createMiddleware)({
406
486
  name: "SilmarilDeepAgentsMiddleware",
407
487
  wrapModelCall: async (request, handler) => {
408
488
  const conversationId2 = nativeThreadId(request.runtime, void 0, void 0, (0, import_runnables.ensureConfig)());
409
- const messages = [];
410
- for (const message of request.messages) {
411
- let blocked = false;
412
- if (remoteNotification(message)) {
413
- const key = await notificationKey(message, conversationId2, effectiveMode);
414
- const cached = key === void 0 ? void 0 : notificationChecks.get(key);
415
- if (cached !== void 0) {
416
- blocked = cached;
417
- notificationChecks.delete(key);
418
- notificationChecks.set(key, cached);
419
- } else {
420
- const decision = await classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId2, "async_subagent");
421
- blocked = decision.enforce;
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
- });
427
- }
428
- }
489
+ const messages = [...request.messages];
490
+ const notifications = [];
491
+ for (const [index, message] of request.messages.entries()) {
492
+ if (!remoteNotification(message)) continue;
493
+ const key = await verdictKey(message, conversationId2, effectiveMode);
494
+ const cached = firewall.verdicts.get(key);
495
+ if (cached !== void 0) {
496
+ if (cached) messages[index] = new import_messages.HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } });
497
+ continue;
429
498
  }
430
- messages.push(blocked ? new import_messages.HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } }) : message);
499
+ const decision = classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId2, "async_subagent");
500
+ if (!queued) await decision;
501
+ notifications.push({ index, key, decision });
431
502
  }
432
- request = { ...request, messages };
503
+ const toolResults = queued ? await unverifiedToolResults(request.messages, conversationId2) : [];
433
504
  const history = request.state.messages;
434
- let lastUserIndex = -1;
435
- for (let i = history.length - 1; i >= 0; i--) {
436
- if (import_messages.HumanMessage.isInstance(history[i])) {
437
- lastUserIndex = i;
438
- break;
439
- }
440
- }
441
- const blockedCount = history.slice(lastUserIndex + 1).filter(
442
- (message) => import_messages.ToolMessage.isInstance(message) && message.content === SAFE_TOOL_MESSAGE && message.additional_kwargs?.silmarilBlocked === BLOCKED_TOOL_MARKER
443
- ).length;
444
- const latestUser = [...request.messages].reverse().find(import_messages.HumanMessage.isInstance);
445
- const racesModel = parallel && !background && blockedCount < maxBlockedAttempts;
446
- const protectedRequest = request;
447
- const running = racesModel ? Promise.resolve().then(() => handler(protectedRequest)) : void 0;
505
+ const lastUserIndex = lastIndexWhere(history, (message) => import_messages.HumanMessage.isInstance(message));
506
+ const blockedCount = history.slice(lastUserIndex + 1).filter(isBlockedToolMessage).length;
507
+ const latestUserIndex = lastIndexWhere(request.messages, (message) => import_messages.HumanMessage.isInstance(message) && !remoteNotification(message));
508
+ const latestUser = latestUserIndex < 0 ? void 0 : request.messages[latestUserIndex];
509
+ const inputKey = latestUser === void 0 ? void 0 : await verdictKey(latestUser, conversationId2, effectiveMode);
510
+ const checksInput = latestUser !== void 0 && (blockedCount >= maxBlockedAttempts || firewall.verdicts.get(inputKey) !== false);
511
+ const racesModel = queued && blockedCount < maxBlockedAttempts;
512
+ const firstRequest = { ...request, messages: [...messages] };
513
+ const running = racesModel ? Promise.resolve().then(() => handler(firstRequest)) : void 0;
448
514
  running?.catch(() => void 0);
449
- const inputDecision = latestUser === void 0 ? void 0 : await classify(textOf(latestUser), HookLabel.USER_INPUT, conversationId2);
515
+ const inputDecision = checksInput ? await classify(textOf(latestUser), HookLabel.USER_INPUT, conversationId2) : void 0;
450
516
  if (inputDecision?.enforce) return new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE);
517
+ if (inputDecision !== void 0) rememberAllowed(inputKey, inputDecision);
518
+ let changed = false;
519
+ for (const { index, key, decision } of notifications) {
520
+ const verdict = await decision;
521
+ if (key !== void 0 && verdict.cacheable) firewall.verdicts.set(key, verdict.enforce);
522
+ rememberAllowed(key, verdict);
523
+ if (verdict.enforce) {
524
+ const message = request.messages[index];
525
+ messages[index] = new import_messages.HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } });
526
+ changed = true;
527
+ }
528
+ }
529
+ const replacements = [];
530
+ let lateDenials = 0;
531
+ for (const { index, message, decision } of toolResults) {
532
+ if (!(await decision).enforce) continue;
533
+ const replacement = blockedToolMessage(message.tool_call_id, message.name, message.id);
534
+ messages[index] = replacement;
535
+ if (message.id !== void 0) replacements.push(replacement);
536
+ lateDenials += 1;
537
+ changed = true;
538
+ }
451
539
  const capMode = effectiveMode ?? inputDecision?.mode ?? "block";
452
- if (blockedCount >= maxBlockedAttempts && capMode === "block") {
453
- return new import_messages.AIMessage(SAFE_FINAL_MESSAGE);
540
+ const discarded = changed && running !== void 0 ? await running.then((result) => result, () => void 0) : void 0;
541
+ const withState = (final, raw) => {
542
+ if (replacements.length === 0) return final;
543
+ if (!import_messages.AIMessage.isInstance(final) || final === raw) return new import_langgraph.Command({ update: { messages: replacements } });
544
+ if (import_messages.AIMessage.isInstance(raw)) {
545
+ rewriteInPlace(raw, final.content);
546
+ return new import_langgraph.Command({ update: { messages: replacements } });
547
+ }
548
+ return new import_langgraph.Command({ update: { messages: [...replacements, final] } });
549
+ };
550
+ if (blockedCount + lateDenials >= maxBlockedAttempts && capMode === "block") {
551
+ return withState(new import_messages.AIMessage(SAFE_FINAL_MESSAGE), discarded);
454
552
  }
455
- const response = await (running ?? handler(request));
553
+ const response = changed || running === void 0 ? await handler({ ...request, messages }) : await running;
456
554
  if (response instanceof import_langgraph.Command && (await classify(textOfStructuredValue(response.update), HookLabel.LLM_OUTPUT, conversationId2)).enforce) {
457
- return new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE);
555
+ return withState(new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE), response);
458
556
  }
459
557
  if (import_messages.AIMessage.isInstance(response) && (await classify(textOf(response), HookLabel.LLM_OUTPUT, conversationId2)).enforce) {
460
- return new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE);
558
+ return withState(new import_messages.AIMessage(SAFE_OUTPUT_MESSAGE), response);
461
559
  }
462
- return response;
560
+ return withState(response, response);
561
+ },
562
+ afterAgent: async (state, runtime) => {
563
+ if (!queued) return void 0;
564
+ const conversationId2 = nativeThreadId(runtime, void 0, void 0, (0, import_runnables.ensureConfig)());
565
+ const replacements = [];
566
+ for (const { message, decision } of await unverifiedToolResults(state.messages, conversationId2)) {
567
+ if ((await decision).enforce && message.id !== void 0) {
568
+ replacements.push(blockedToolMessage(message.tool_call_id, message.name, message.id));
569
+ }
570
+ }
571
+ return replacements.length === 0 ? void 0 : { messages: replacements };
463
572
  },
464
573
  wrapToolCall: async (request, handler) => {
465
574
  const conversationId2 = nativeThreadId(request.runtime, void 0, void 0, (0, import_runnables.ensureConfig)());
466
- const safe = () => {
467
- const message = new import_messages.ToolMessage({
468
- content: SAFE_TOOL_MESSAGE,
469
- tool_call_id: request.toolCall.id ?? "",
470
- name: request.toolCall.name,
471
- additional_kwargs: { silmarilBlocked: BLOCKED_TOOL_MARKER }
472
- });
473
- issuedBlockedMessages.add(message);
474
- return message;
475
- };
575
+ const safe = () => blockedToolMessage(request.toolCall.id ?? "", request.toolCall.name);
476
576
  if ((await classify(JSON.stringify(request.toolCall.args ?? {}), HookLabel.TOOL_CALL, conversationId2, request.toolCall.name)).enforce) {
477
577
  return safe();
478
578
  }
@@ -481,11 +581,16 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
481
581
  try {
482
582
  resultText = import_messages.ToolMessage.isInstance(result) ? textOf(result) : result instanceof import_langgraph.Command ? textOfStructuredValue(result.update) : String(result);
483
583
  } catch {
484
- const decision = await classify("[uninspectable tool result]", HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name);
485
- return decision.mode === "block" ? safe() : stripAllowedMarker(result);
584
+ const decision2 = await classify("[uninspectable tool result]", HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name);
585
+ return decision2.mode === "block" ? safe() : stripAllowedMarker(result);
586
+ }
587
+ const decision = classify(resultText, HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name);
588
+ if (queued && request.toolCall.id && import_messages.ToolMessage.isInstance(result)) {
589
+ toolResultChecks.set(await toolResultKey(conversationId2, request.toolCall.id, resultText), decision);
590
+ return stripAllowedMarker(result);
486
591
  }
487
- if ((await classify(resultText, HookLabel.TOOL_RESPONSE, conversationId2, request.toolCall.name)).enforce) {
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) {
592
+ if ((await decision).enforce) {
593
+ if (ASYNC_TASK_TOOLS.has(request.toolCall.name) && result instanceof import_langgraph.Command && result.update && !Array.isArray(result.update) && "asyncTasks" in result.update) {
489
594
  return new import_langgraph.Command({ update: { messages: [safe()], asyncTasks: result.update.asyncTasks } });
490
595
  }
491
596
  return safe();