@silmaril-security/sdk 0.9.0 → 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.
Files changed (35) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +200 -24
  3. package/dist/adapters/deepagents.cjs +255 -42
  4. package/dist/adapters/deepagents.cjs.map +1 -1
  5. package/dist/adapters/deepagents.d.cts +9 -5
  6. package/dist/adapters/deepagents.d.ts +9 -5
  7. package/dist/adapters/deepagents.js +261 -43
  8. package/dist/adapters/deepagents.js.map +1 -1
  9. package/dist/adapters/langchain.cjs +153 -32
  10. package/dist/adapters/langchain.cjs.map +1 -1
  11. package/dist/adapters/langchain.d.cts +1 -1
  12. package/dist/adapters/langchain.d.ts +1 -1
  13. package/dist/adapters/langchain.js +153 -32
  14. package/dist/adapters/langchain.js.map +1 -1
  15. package/dist/adapters/vercel-v4.cjs +700 -0
  16. package/dist/adapters/vercel-v4.cjs.map +1 -0
  17. package/dist/adapters/vercel-v4.d.cts +79 -0
  18. package/dist/adapters/vercel-v4.d.ts +79 -0
  19. package/dist/adapters/vercel-v4.js +670 -0
  20. package/dist/adapters/vercel-v4.js.map +1 -0
  21. package/dist/adapters/vercel.cjs +41 -15
  22. package/dist/adapters/vercel.cjs.map +1 -1
  23. package/dist/adapters/vercel.d.cts +1 -1
  24. package/dist/adapters/vercel.d.ts +1 -1
  25. package/dist/adapters/vercel.js +41 -15
  26. package/dist/adapters/vercel.js.map +1 -1
  27. package/dist/{firewall-Bv5y03P0.d.cts → firewall-BXM2BWEr.d.cts} +60 -1
  28. package/dist/{firewall-Bv5y03P0.d.ts → firewall-BXM2BWEr.d.ts} +60 -1
  29. package/dist/index.cjs +451 -50
  30. package/dist/index.cjs.map +1 -1
  31. package/dist/index.d.cts +2 -2
  32. package/dist/index.d.ts +2 -2
  33. package/dist/index.js +451 -50
  34. package/dist/index.js.map +1 -1
  35. package/package.json +21 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,53 @@
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
+
33
+ ## 0.9.1
34
+
35
+ - Add a separate AI SDK 7 `LanguageModelV4Middleware` export at
36
+ `@silmaril-security/sdk/adapters/vercel-v4`, with content-part generation
37
+ checks, per-ID text/tool-input stream handling, ordered bounded Block-mode
38
+ buffering, final tool-call byte verification/reclassification, and exact
39
+ Node 22 contract coverage. Keep the existing AI SDK 5/6 v3 adapter and
40
+ `Firewall.asMiddleware()` unchanged.
41
+ - Raise the optional `@langchain/core` peer floor to the retained secure
42
+ intervals `>=0.3.80 <1 || >=1.1.8`, and test the 0.3.80 boundary.
43
+ - Resolve released string and qualified 1.16.x model-object profiles before
44
+ protected general-purpose subagent assembly. Preserve disabled/customized
45
+ profiles, parent tools/skills, tool prototypes, and matching static
46
+ middleware overrides without hidden replacement or registry mutation.
47
+ - Bound Deep Agents compatibility to `>=1.16.0 <1.17.0`, and add protected
48
+ compiled-subagent `isolated` / `fork` mode while preserving exact graph,
49
+ Firewall-client, and original-mode ownership checks.
50
+
3
51
  ## 0.9.0
4
52
 
5
53
  - Support native remote Deep Agents subagents with parent delegation/result checks
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.9.0 for reproducible installs:
38
+ Pin version 0.10.0 for reproducible installs:
38
39
 
39
40
  ```sh
40
- npm install @silmaril-security/sdk@0.9.0
41
+ npm install @silmaril-security/sdk@0.10.0
41
42
  ```
42
43
 
43
44
  Requires Node 20 or later.
@@ -50,23 +51,31 @@ This repository is public and source-available for integration transparency,
50
51
  but the SDK is not permissive open source. See [LICENSE](LICENSE) for the
51
52
  governing terms.
52
53
 
53
- The core client does not require optional framework peer dependencies. Optional
54
- Vercel AI SDK middleware support is compatible with Vercel AI SDK v5 and v6:
54
+ The core client does not require optional framework peer dependencies. The
55
+ existing `adapters/vercel` middleware remains compatible with Vercel AI SDK v5
56
+ and v6:
55
57
 
56
58
  ```sh
57
59
  npm install ai @ai-sdk/openai
58
60
  ```
59
61
 
62
+ AI SDK 7 applications require Node 22 or later and use the separate
63
+ `adapters/vercel-v4` export documented below. The core SDK and its AI SDK 5/6
64
+ adapter continue to support Node 20.
65
+
60
66
  Optional LangChain.js support:
61
67
 
62
68
  ```sh
63
69
  npm install @langchain/core @langchain/openai
64
70
  ```
65
71
 
72
+ The supported secure LangChain.js intervals are
73
+ `@langchain/core >=0.3.80 <1` or `@langchain/core >=1.1.8`.
74
+
66
75
  Optional Deep Agents support (including remote subagents):
67
76
 
68
77
  ```sh
69
- npm install "deepagents@^1.16.0" "langchain@^1.5.10" "@langchain/core@^1.2.14" "@langchain/langgraph@^1.4.10"
78
+ npm install "deepagents@>=1.16.0 <1.17.0" "langchain@^1.5.10" "@langchain/core@^1.2.14" "@langchain/langgraph@^1.4.10"
70
79
  ```
71
80
 
72
81
  ## Configuration
@@ -288,6 +297,8 @@ interface FirewallOptions {
288
297
  mode?: "shadow" | "warn" | "block"; // explicit local client default
289
298
  review?: "standard" | "deep"; // explicit client review default
290
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
291
302
  }
292
303
  ```
293
304
 
@@ -540,8 +551,63 @@ sent input. A missing array or mismatched count raises an `Error` before
540
551
  results are returned or blocking callbacks run. Retries use the original
541
552
  payload snapshot, even if caller-owned inputs change while the request is in flight.
542
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
+
543
600
  ## Migration Notes
544
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
+
545
611
  Version `0.4.1` is the public npm recovery release for `0.4.x`: the `v0.4.0`
546
612
  Git tag exists, but `@silmaril-security/sdk@0.4.0` was not published to npm.
547
613
  Use `0.4.1` or later. This release moves all threshold decisions to Firewall
@@ -572,19 +638,87 @@ const { text } = await generateText({ model, prompt: "Hello" });
572
638
  console.log(text);
573
639
  ```
574
640
 
575
- Middleware scans input by default (`scanInput` defaults to true). It classifies
576
- that message's tool-result parts as `tool_response` only when the newest prompt
577
- message is a tool message. Otherwise it classifies the latest user message as
578
- `user_input` and does not scan earlier tool results. Set `scanOutput: true` to
579
- classify model text, and `scanToolCalls: true` to classify tool-call arguments
580
- on generate results. Infrastructure errors and blocking decisions are
581
- fail-closed by default and bubble up to the caller.
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.
663
+
664
+ ### Vercel AI SDK 7
665
+
666
+ AI SDK 7 uses the `LanguageModelV4Middleware` contract and requires Node 22 or
667
+ later. Import its adapter explicitly; `Firewall.asMiddleware()` intentionally
668
+ retains the AI SDK 5/6 v3 contract.
582
669
 
583
- When `scanOutput: true` is combined with streaming, output is classified in the
584
- stream's `flush` after all deltas have been emitted, so blocking is advisory:
585
- the consumer has already seen the text by the time an error part is enqueued.
586
- Use non-streaming generation if you need to block before the caller observes
587
- output.
670
+ ```ts
671
+ import { generateText, wrapLanguageModel } from "ai";
672
+ import { openai } from "@ai-sdk/openai";
673
+ import { Firewall } from "@silmaril-security/sdk";
674
+ import { createMiddlewareV4 } from "@silmaril-security/sdk/adapters/vercel-v4";
675
+
676
+ const fw = new Firewall({
677
+ apiKey: process.env.SILMARIL_API_KEY!,
678
+ apiUrl: process.env.SILMARIL_API_URL!,
679
+ });
680
+
681
+ const model = wrapLanguageModel({
682
+ model: openai("gpt-5"),
683
+ middleware: createMiddlewareV4(fw, {
684
+ scanOutput: true,
685
+ scanToolCalls: true,
686
+ maxBufferedBytes: 1_048_576,
687
+ }),
688
+ });
689
+
690
+ const result = await generateText({ model, prompt: "Hello" });
691
+ console.log(result.text);
692
+ ```
693
+
694
+ The v4 adapter reads generated text and tool calls from `result.content`, and
695
+ classifies prompt tool-result parts with their tool name and call ID. Reasoning
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.
701
+
702
+ For streaming, text and tool-input sequences are tracked by ID. In effective or
703
+ possible Block mode, the adapter retains original text and tool-input parts in a
704
+ global order queue until each complete sequence has a verdict. Benign parts are
705
+ then emitted unchanged and in their original interleaved order. Blocked parts
706
+ are replaced by an `error` part carrying `FirewallBlockedException`; argument
707
+ deltas and final blocked tool calls are not emitted. Incomplete sequences are
708
+ classified before finish/flush. Abort, cancellation, classifier failures, and
709
+ invalid stream identity do not release pending content.
710
+
711
+ After a streamed tool input is classified, the adapter retains only its bounded
712
+ SHA-256 fingerprint, encoding, tool name, ID, and verdict. A byte-identical
713
+ final `tool-call` reuses that verdict. A different final input—including
714
+ semantically equivalent JSON with different whitespace—is independently
715
+ classified before emission; a newly blocked final call is never exposed for
716
+ execution.
717
+
718
+ The Block-mode queue is bounded by `maxBufferedBytes` (default 1 MiB) and
719
+ `maxBufferedParts` (default 10,000). Exceeding either limit errors the stream
720
+ without releasing pending content. Shadow and Warn retain observation behavior
721
+ without waiting for a Block verdict.
588
722
 
589
723
  ## LangChain.js
590
724
 
@@ -632,8 +766,18 @@ and the LLM call proceeds. Set `failOpen: false` to make API errors bubble up.
632
766
  Blocking decisions throw `FirewallBlockedException` only when the effective mode
633
767
  is Block; Shadow and Warn preserve the host flow.
634
768
  `PromptBlockedException` continues to work as a deprecated alias.
635
- Model-start, tool-start, and tool-end hooks are enabled by default; retriever
636
- and model-end (`LLM_END`) hooks remain opt-in. The LangChain run ID is sent as
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
637
781
  `metadata.langgraph.run_id`; every classification gets a distinct
638
782
  `metadata.silmaril.request_id`. The current native thread ID is sent as
639
783
  `metadata.conversationId` without a separate Silmaril conversation option.
@@ -676,13 +820,38 @@ await agent.invoke(
676
820
  );
677
821
  ```
678
822
 
679
- The constructor installs checks on the root, general-purpose, and declarative
680
- subagents. For a compiled subagent, call
823
+ The constructor installs checks on the root and declarative subagents. For
824
+ string model specs it uses the released public Deep Agents profile resolver.
825
+ For model objects, the qualified `deepagents >=1.16.0 <1.17.0` compatibility
826
+ path mirrors the released 1.16.x hint order: known `getName()` provider
827
+ mappings, `ConfigurableModel._defaultConfig`, `model_name` / `modelName`, exact
828
+ provider-model match, colon-qualified identifier, then provider fallback.
829
+ Those model-object fields are upstream-private compatibility inputs; package
830
+ metadata excludes unqualified future minors, unknown models with no hints use
831
+ the empty profile, and malformed hints fail rather than silently disabling
832
+ profile protection. No Deep Agents internals are imported and the global
833
+ profile registry is not modified by the SDK.
834
+
835
+ The protected general-purpose spec honors `enabled: false`, custom
836
+ `description` / `systemPrompt`, parent tools and skills, profile tool
837
+ description overrides, excluded tools, and matching root overrides for the
838
+ default, skills, and static profile middleware slots. Tool clones retain their
839
+ prototype. Novel root middleware remains root-only, matching upstream default
840
+ behavior. A profile `extraMiddleware` factory combined with custom root
841
+ middleware is not statically observable, so the constructor rejects that
842
+ combination rather than silently dropping a possible named override. The
843
+ released 1.16.x JavaScript profile API has no rename field.
844
+
845
+ For a compiled subagent, call
681
846
  `createProtectedCompiledSubagent(fw, { name: "review", description: "Review",
682
847
  model, tools })` and pass its returned spec through
683
848
  `protectedCompiledSubagents`. That factory installs middleware before
684
849
  compilation. The parent constructor verifies the exact graph and Firewall
685
- client; it rejects arbitrary compiled runnables. Root custom middleware does
850
+ client; it rejects arbitrary compiled runnables and mutated execution modes.
851
+ Set `mode: "isolated"` (default behavior when omitted) or the upstream beta
852
+ `mode: "fork"` on the protected compiled factory. The mode is attached only to
853
+ the returned Deep Agents spec; it is not passed into LangChain `createAgent`.
854
+ Root custom middleware does
686
855
  not automatically reach every subagent. For custom agent construction, import
687
856
  `createDeepAgentsMiddleware` from the same adapter subpath.
688
857
 
@@ -697,9 +866,16 @@ Classification errors allow model and tool execution by default; set
697
866
  `silmaril: { failOpen: false }` to require a successful classification. Already
698
867
  emitted streaming text cannot be recalled.
699
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
+
700
876
  ### Remote subagents
701
877
 
702
- Remote support requires `deepagents@^1.16.0`. Use `createProtectedDeepAgent`
878
+ Remote support requires `deepagents@>=1.16.0 <1.17.0`. Use `createProtectedDeepAgent`
703
879
  in **both services**. The remote Agent Protocol service owns its graph, model,
704
880
  tools and Firewall client.
705
881
 
@@ -785,7 +961,7 @@ checkpoint namespaces do not change the conversation ID. The direct
785
961
  ## Retries
786
962
 
787
963
  HTTP 429 responses are retried with exponential backoff capped at 30s, up to 5
788
- 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
789
965
  payload is serialized once so every attempt sends the same logical event.
790
966
  Redirects are rejected rather than followed; native `fetch` surfaces that
791
967
  refusal as a `TypeError` without a reliable redirect status. Actually received