@silmaril-security/sdk 0.8.2 → 0.9.1

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,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.1
4
+
5
+ - Add a separate AI SDK 7 `LanguageModelV4Middleware` export at
6
+ `@silmaril-security/sdk/adapters/vercel-v4`, with content-part generation
7
+ checks, per-ID text/tool-input stream handling, ordered bounded Block-mode
8
+ buffering, final tool-call byte verification/reclassification, and exact
9
+ Node 22 contract coverage. Keep the existing AI SDK 5/6 v3 adapter and
10
+ `Firewall.asMiddleware()` unchanged.
11
+ - Raise the optional `@langchain/core` peer floor to the retained secure
12
+ intervals `>=0.3.80 <1 || >=1.1.8`, and test the 0.3.80 boundary.
13
+ - Resolve released string and qualified 1.16.x model-object profiles before
14
+ protected general-purpose subagent assembly. Preserve disabled/customized
15
+ profiles, parent tools/skills, tool prototypes, and matching static
16
+ middleware overrides without hidden replacement or registry mutation.
17
+ - Bound Deep Agents compatibility to `>=1.16.0 <1.17.0`, and add protected
18
+ compiled-subagent `isolated` / `fork` mode while preserving exact graph,
19
+ Firewall-client, and original-mode ownership checks.
20
+
21
+ ## 0.9.0
22
+
23
+ - Support native remote Deep Agents subagents with parent delegation/result checks
24
+ and independently protected child graphs. Preserve child thread identity, parent
25
+ lineage and async task lifecycle, and inspect background result notifications.
26
+ - Qualify isolated/fork launches, updates, checks, cancellation and failures using
27
+ real framework graphs and SDK transport against a loopback Agent Protocol peer.
28
+
29
+ - Require Deep Agents 1.16.0 or newer within the 1.x line for the qualified
30
+ remote lifecycle contract. Other optional integration ranges remain unchanged.
31
+
3
32
  ## 0.8.2
4
33
 
5
34
  - Omit ambiguous callback-only child conversation attribution when ordinary
package/README.md CHANGED
@@ -34,10 +34,10 @@ This SDK is distributed as an npm package.
34
34
  npm install @silmaril-security/sdk
35
35
  ```
36
36
 
37
- After publication, pin version 0.8.2 for reproducible installs:
37
+ Pin version 0.9.1 for reproducible installs:
38
38
 
39
39
  ```sh
40
- npm install @silmaril-security/sdk@0.8.2
40
+ npm install @silmaril-security/sdk@0.9.1
41
41
  ```
42
42
 
43
43
  Requires Node 20 or later.
@@ -50,23 +50,31 @@ This repository is public and source-available for integration transparency,
50
50
  but the SDK is not permissive open source. See [LICENSE](LICENSE) for the
51
51
  governing terms.
52
52
 
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:
53
+ The core client does not require optional framework peer dependencies. The
54
+ existing `adapters/vercel` middleware remains compatible with Vercel AI SDK v5
55
+ and v6:
55
56
 
56
57
  ```sh
57
58
  npm install ai @ai-sdk/openai
58
59
  ```
59
60
 
61
+ AI SDK 7 applications require Node 22 or later and use the separate
62
+ `adapters/vercel-v4` export documented below. The core SDK and its AI SDK 5/6
63
+ adapter continue to support Node 20.
64
+
60
65
  Optional LangChain.js support:
61
66
 
62
67
  ```sh
63
68
  npm install @langchain/core @langchain/openai
64
69
  ```
65
70
 
66
- Optional Deep Agents support (peer ranges shipped with `0.7.0`):
71
+ The supported secure LangChain.js intervals are
72
+ `@langchain/core >=0.3.80 <1` or `@langchain/core >=1.1.8`.
73
+
74
+ Optional Deep Agents support (including remote subagents):
67
75
 
68
76
  ```sh
69
- npm install "deepagents@^1.14.1" "langchain@^1.5.10" "@langchain/core@>=0.3.0" "@langchain/langgraph@^1.4.10"
77
+ npm install "deepagents@>=1.16.0 <1.17.0" "langchain@^1.5.10" "@langchain/core@^1.2.14" "@langchain/langgraph@^1.4.10"
70
78
  ```
71
79
 
72
80
  ## Configuration
@@ -586,6 +594,61 @@ the consumer has already seen the text by the time an error part is enqueued.
586
594
  Use non-streaming generation if you need to block before the caller observes
587
595
  output.
588
596
 
597
+ ### Vercel AI SDK 7
598
+
599
+ AI SDK 7 uses the `LanguageModelV4Middleware` contract and requires Node 22 or
600
+ later. Import its adapter explicitly; `Firewall.asMiddleware()` intentionally
601
+ retains the AI SDK 5/6 v3 contract.
602
+
603
+ ```ts
604
+ import { generateText, wrapLanguageModel } from "ai";
605
+ import { openai } from "@ai-sdk/openai";
606
+ import { Firewall } from "@silmaril-security/sdk";
607
+ import { createMiddlewareV4 } from "@silmaril-security/sdk/adapters/vercel-v4";
608
+
609
+ const fw = new Firewall({
610
+ apiKey: process.env.SILMARIL_API_KEY!,
611
+ apiUrl: process.env.SILMARIL_API_URL!,
612
+ });
613
+
614
+ const model = wrapLanguageModel({
615
+ model: openai("gpt-5"),
616
+ middleware: createMiddlewareV4(fw, {
617
+ scanOutput: true,
618
+ scanToolCalls: true,
619
+ maxBufferedBytes: 1_048_576,
620
+ }),
621
+ });
622
+
623
+ const result = await generateText({ model, prompt: "Hello" });
624
+ console.log(result.text);
625
+ ```
626
+
627
+ The v4 adapter reads generated text and tool calls from `result.content`, and
628
+ classifies prompt tool-result parts with their tool name and call ID. Reasoning
629
+ parts are passed through unchanged and are not classified.
630
+
631
+ For streaming, text and tool-input sequences are tracked by ID. In effective or
632
+ possible Block mode, the adapter retains original text and tool-input parts in a
633
+ global order queue until each complete sequence has a verdict. Benign parts are
634
+ then emitted unchanged and in their original interleaved order. Blocked parts
635
+ are replaced by an `error` part carrying `FirewallBlockedException`; argument
636
+ deltas and final blocked tool calls are not emitted. Incomplete sequences are
637
+ classified before finish/flush. Abort, cancellation, classifier failures, and
638
+ invalid stream identity do not release pending content.
639
+
640
+ After a streamed tool input is classified, the adapter retains only its bounded
641
+ SHA-256 fingerprint, encoding, tool name, ID, and verdict. A byte-identical
642
+ final `tool-call` reuses that verdict. A different final input—including
643
+ semantically equivalent JSON with different whitespace—is independently
644
+ classified before emission; a newly blocked final call is never exposed for
645
+ execution.
646
+
647
+ The Block-mode queue is bounded by `maxBufferedBytes` (default 1 MiB) and
648
+ `maxBufferedParts` (default 10,000). Exceeding either limit errors the stream
649
+ without releasing pending content. Shadow and Warn retain observation behavior
650
+ without waiting for a Block verdict.
651
+
589
652
  ## LangChain.js
590
653
 
591
654
  Install the optional peer dependencies:
@@ -676,13 +739,38 @@ await agent.invoke(
676
739
  );
677
740
  ```
678
741
 
679
- The constructor installs checks on the root, general-purpose, and declarative
680
- subagents. For a compiled subagent, call
742
+ The constructor installs checks on the root and declarative subagents. For
743
+ string model specs it uses the released public Deep Agents profile resolver.
744
+ For model objects, the qualified `deepagents >=1.16.0 <1.17.0` compatibility
745
+ path mirrors the released 1.16.x hint order: known `getName()` provider
746
+ mappings, `ConfigurableModel._defaultConfig`, `model_name` / `modelName`, exact
747
+ provider-model match, colon-qualified identifier, then provider fallback.
748
+ Those model-object fields are upstream-private compatibility inputs; package
749
+ metadata excludes unqualified future minors, unknown models with no hints use
750
+ the empty profile, and malformed hints fail rather than silently disabling
751
+ profile protection. No Deep Agents internals are imported and the global
752
+ profile registry is not modified by the SDK.
753
+
754
+ The protected general-purpose spec honors `enabled: false`, custom
755
+ `description` / `systemPrompt`, parent tools and skills, profile tool
756
+ description overrides, excluded tools, and matching root overrides for the
757
+ default, skills, and static profile middleware slots. Tool clones retain their
758
+ prototype. Novel root middleware remains root-only, matching upstream default
759
+ behavior. A profile `extraMiddleware` factory combined with custom root
760
+ middleware is not statically observable, so the constructor rejects that
761
+ combination rather than silently dropping a possible named override. The
762
+ released 1.16.x JavaScript profile API has no rename field.
763
+
764
+ For a compiled subagent, call
681
765
  `createProtectedCompiledSubagent(fw, { name: "review", description: "Review",
682
766
  model, tools })` and pass its returned spec through
683
767
  `protectedCompiledSubagents`. That factory installs middleware before
684
768
  compilation. The parent constructor verifies the exact graph and Firewall
685
- client; it rejects arbitrary compiled runnables. Root custom middleware does
769
+ client; it rejects arbitrary compiled runnables and mutated execution modes.
770
+ Set `mode: "isolated"` (default behavior when omitted) or the upstream beta
771
+ `mode: "fork"` on the protected compiled factory. The mode is attached only to
772
+ the returned Deep Agents spec; it is not passed into LangChain `createAgent`.
773
+ Root custom middleware does
686
774
  not automatically reach every subagent. For custom agent construction, import
687
775
  `createDeepAgentsMiddleware` from the same adapter subpath.
688
776
 
@@ -697,6 +785,74 @@ Classification errors allow model and tool execution by default; set
697
785
  `silmaril: { failOpen: false }` to require a successful classification. Already
698
786
  emitted streaming text cannot be recalled.
699
787
 
788
+ ### Remote subagents
789
+
790
+ Remote support requires `deepagents@>=1.16.0 <1.17.0`. Use `createProtectedDeepAgent`
791
+ in **both services**. The remote Agent Protocol service owns its graph, model,
792
+ tools and Firewall client.
793
+
794
+ In the **remote service** (`remote-child.ts`):
795
+
796
+ ```typescript
797
+ import { Firewall } from "@silmaril-security/sdk";
798
+ import { createProtectedDeepAgent } from "@silmaril-security/sdk/adapters/deepagents";
799
+
800
+ const childFirewall = new Firewall({
801
+ apiKey: process.env.SILMARIL_API_KEY!,
802
+ apiUrl: process.env.SILMARIL_API_URL!,
803
+ });
804
+ export const graph = createProtectedDeepAgent(childFirewall, {
805
+ model: process.env.CHILD_MODEL!,
806
+ silmaril: { mode: "block", failOpen: false },
807
+ });
808
+ ```
809
+
810
+ Register `graph` as `research` in the remote service's Agent Protocol configuration.
811
+ Its input, tool-call, tool-result and non-streamed output checks execute inside
812
+ that child. Configure its tools and additional children through the same factory.
813
+
814
+ In the **parent application**:
815
+
816
+ ```typescript
817
+ const parent = createProtectedDeepAgent(parentFirewall, {
818
+ model: parentModel,
819
+ subagents: [{
820
+ name: "research", description: "Background research",
821
+ graphId: "research", url: "https://research.example.com",
822
+ mode: "isolated", // or "fork" to include parent conversation context
823
+ notifyParent: false,
824
+ updateStrategy: "enqueue",
825
+ }],
826
+ silmaril: { mode: "block", failOpen: false },
827
+ });
828
+ const result = await parent.invoke(
829
+ { messages: [{ role: "user", content: "Research this topic" }] },
830
+ { configurable: { thread_id: "parent-conversation" } },
831
+ );
832
+ ```
833
+
834
+ The native `start_async_task`, `check_async_task`, `update_async_task`,
835
+ `cancel_async_task` and `list_async_tasks` tools retain upstream behavior and
836
+ tracked `asyncTasks` state. Parent middleware checks delegation before launch,
837
+ returned tool results and background task notifications before model use.
838
+ Blocked result text is withheld while native task bookkeeping remains available.
839
+ Successful notification checks are reused for unchanged native message IDs within
840
+ a thread using a bounded middleware-local cache. Blocked replacements are applied
841
+ again after checkpoint resume. A new graph/process rechecks retained notifications;
842
+ failed classifications are retried.
843
+ Shadow/Warn preserve content; classification failure behavior follows `failOpen`.
844
+
845
+ The child uses its own native `thread_id` as `metadata.conversationId`.
846
+ Available `parent_thread_id` and `subagent_name` appear under `metadata.langgraph`
847
+ for attribution; they confer no authorization and do not replace child identity.
848
+ Native `headers` authenticate to the remote Agent Protocol service; each service
849
+ configures its Silmaril client separately. Fork mode shares conversation context;
850
+ deploy the child with its own middleware in either mode. The parent cannot install
851
+ middleware into another server or attest its deployment. Set `notifyParent: false`
852
+ for another deployment and check results through the native lifecycle tools.
853
+ Webhook-delivered results consumed by your application require an application-side
854
+ classification boundary. Streaming output retains the limitations described above.
855
+
700
856
  ## Migrating to 0.8.1
701
857
 
702
858
  Remove `conversationId` / `conversation_id` from LangChain handler options and
@@ -756,6 +912,7 @@ IDs must be non-empty; MCP tools also require their canonical server parent ID.
756
912
  The compatibility metadata copy remains attribution only. Caller agent metadata
757
913
  does not supply an authenticated principal.
758
914
 
759
- This source prepares version 0.8.2. Its registry install command becomes
760
- available after the authorized main-branch release workflow publishes the package.
761
- Confirm registry publication before installing this version.
915
+ Published versions are listed on
916
+ [npm](https://www.npmjs.com/package/@silmaril-security/sdk?activeTab=versions) and
917
+ [GitHub Releases](https://github.com/Silmaril-Security/sdk-typescript/releases).
918
+ Version 0.9.0 adds protected remote Deep Agents support.
@@ -141,6 +141,148 @@ var SAFE_OUTPUT_MESSAGE = "Silmaril Firewall blocked this response.";
141
141
  var BLOCKED_TOOL_MARKER = "silmaril-firewall:v1:blocked-tool";
142
142
  var issuedBlockedMessages = /* @__PURE__ */ new WeakSet();
143
143
  var protectedCompiledGraphs = /* @__PURE__ */ new WeakMap();
144
+ var GENERAL_PURPOSE_DEFAULT_MIDDLEWARE = /* @__PURE__ */ new Set([
145
+ "FilesystemMiddleware",
146
+ "SummarizationMiddleware",
147
+ "PatchToolCallsMiddleware"
148
+ ]);
149
+ function isCompiledMode(value) {
150
+ return value === "isolated" || value === "fork";
151
+ }
152
+ function recordValue(value) {
153
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
154
+ }
155
+ function modelCompatName(model) {
156
+ const getName = Reflect.get(model, "getName");
157
+ if (typeof getName !== "function") {
158
+ throw new Error(
159
+ "Protected Deep Agents model-object profiles require a callable getName()"
160
+ );
161
+ }
162
+ const name = Reflect.apply(getName, model, []);
163
+ if (typeof name !== "string" || !name) {
164
+ throw new Error(
165
+ "Protected Deep Agents model-object getName() must return a non-empty string"
166
+ );
167
+ }
168
+ return name;
169
+ }
170
+ function optionalModelHint(record2, key, location) {
171
+ const value = Reflect.get(record2, key);
172
+ if (value === void 0 || value === null) return void 0;
173
+ if (typeof value !== "string") {
174
+ throw new Error(
175
+ `Protected Deep Agents ${location}.${key} profile hint must be a string`
176
+ );
177
+ }
178
+ return value;
179
+ }
180
+ function configurableDefaults(model) {
181
+ const value = Reflect.get(model, "_defaultConfig");
182
+ if (value === void 0 || value === null) return void 0;
183
+ const defaults = recordValue(value);
184
+ if (defaults === void 0) {
185
+ throw new Error(
186
+ "Protected Deep Agents ConfigurableModel._defaultConfig must be an object"
187
+ );
188
+ }
189
+ return defaults;
190
+ }
191
+ function modelProviderHint(model) {
192
+ const name = modelCompatName(model);
193
+ if (name === "ConfigurableModel") {
194
+ const defaults = configurableDefaults(model);
195
+ return defaults === void 0 ? void 0 : optionalModelHint(defaults, "modelProvider", "_defaultConfig");
196
+ }
197
+ const providers = {
198
+ ChatAnthropic: "anthropic",
199
+ ChatOpenAI: "openai",
200
+ ChatGoogleGenerativeAI: "google"
201
+ };
202
+ return providers[name];
203
+ }
204
+ function modelIdentifierHint(model) {
205
+ const name = modelCompatName(model);
206
+ const configurable = name === "ConfigurableModel" ? configurableDefaults(model) : void 0;
207
+ return (configurable === void 0 ? void 0 : optionalModelHint(configurable, "model", "_defaultConfig")) ?? optionalModelHint(model, "model_name", name) ?? optionalModelHint(model, "modelName", name);
208
+ }
209
+ function resolveProtectedHarnessProfile(model) {
210
+ if (typeof model === "string") {
211
+ return (0, import_deepagents.getHarnessProfile)(model);
212
+ }
213
+ if (typeof model !== "object" && typeof model !== "function" || model === null) {
214
+ throw new Error(
215
+ "Protected Deep Agents model must be a string or model object"
216
+ );
217
+ }
218
+ const providerHint = modelProviderHint(model);
219
+ const identifierHint = modelIdentifierHint(model);
220
+ if (providerHint && identifierHint && !identifierHint.includes(":")) {
221
+ const exact = (0, import_deepagents.getHarnessProfile)(`${providerHint}:${identifierHint}`);
222
+ if (exact !== void 0) return exact;
223
+ }
224
+ if (identifierHint?.includes(":")) {
225
+ const exact = (0, import_deepagents.getHarnessProfile)(identifierHint);
226
+ if (exact !== void 0) return exact;
227
+ }
228
+ if (providerHint) {
229
+ const provider = (0, import_deepagents.getHarnessProfile)(providerHint);
230
+ if (provider !== void 0) return provider;
231
+ }
232
+ return import_deepagents.EMPTY_HARNESS_PROFILE;
233
+ }
234
+ function applyProfileToolDescriptions(tools, profile) {
235
+ const overrides = profile?.toolDescriptionOverrides ?? {};
236
+ if (Object.keys(overrides).length === 0) return [...tools];
237
+ return tools.map((tool) => {
238
+ if (typeof tool !== "object" && typeof tool !== "function" || tool === null) {
239
+ return tool;
240
+ }
241
+ const name = Reflect.get(tool, "name");
242
+ if (typeof name !== "string" || !(name in overrides)) return tool;
243
+ return Object.assign(
244
+ Object.create(Object.getPrototypeOf(tool)),
245
+ tool,
246
+ { description: overrides[name] }
247
+ );
248
+ });
249
+ }
250
+ function generalPurposeRootOverrides(profile, middleware) {
251
+ const profileMiddleware = profile?.extraMiddleware ?? [];
252
+ if (typeof profileMiddleware === "function" && middleware.length > 0) {
253
+ throw new Error(
254
+ "Protected Deep Agents cannot preserve root middleware overrides when the active profile uses an extraMiddleware factory; use a static profile middleware array"
255
+ );
256
+ }
257
+ const names = new Set(GENERAL_PURPOSE_DEFAULT_MIDDLEWARE);
258
+ names.add("SkillsMiddleware");
259
+ if (Array.isArray(profileMiddleware)) {
260
+ for (const entry of profileMiddleware) names.add(entry.name);
261
+ }
262
+ for (const excluded of profile?.excludedMiddleware ?? []) {
263
+ names.delete(excluded);
264
+ }
265
+ return middleware.filter((entry) => names.has(entry.name));
266
+ }
267
+ function applyGeneralPurposeProfile(profile) {
268
+ const config = profile?.generalPurposeSubagent;
269
+ if (config?.systemPrompt !== void 0) {
270
+ return {
271
+ description: config.description ?? import_deepagents.GENERAL_PURPOSE_SUBAGENT.description,
272
+ systemPrompt: config.systemPrompt
273
+ };
274
+ }
275
+ let systemPrompt = profile?.baseSystemPrompt ?? import_deepagents.GENERAL_PURPOSE_SUBAGENT.systemPrompt;
276
+ if (profile?.systemPromptSuffix !== void 0) {
277
+ systemPrompt = systemPrompt ? `${systemPrompt}
278
+
279
+ ${profile.systemPromptSuffix}` : profile.systemPromptSuffix;
280
+ }
281
+ return {
282
+ description: config?.description ?? import_deepagents.GENERAL_PURPOSE_SUBAGENT.description,
283
+ systemPrompt
284
+ };
285
+ }
144
286
  function textOf(message) {
145
287
  return typeof message.content === "string" ? message.content : JSON.stringify(message.content);
146
288
  }
@@ -172,6 +314,31 @@ function stripAllowedMarker(result) {
172
314
  }
173
315
  return result;
174
316
  }
317
+ function remoteLineage(config) {
318
+ const record2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
319
+ const native = record2(record2(config).metadata);
320
+ const parent = record2(record2(record2(config).configurable).deepagents_parent);
321
+ const lineage = Object.fromEntries(Object.entries({
322
+ parent_thread_id: native.parent_thread_id ?? parent.thread_id,
323
+ subagent_name: native.subagent_name
324
+ }).filter(([, value]) => typeof value === "string" && value.trim().length > 0));
325
+ return Object.keys(lineage).length ? { langgraph: lineage } : {};
326
+ }
327
+ function remoteNotification(message) {
328
+ const extra = message.additional_kwargs ?? {};
329
+ return typeof extra.lc_source === "string" && extra.lc_source.includes("async_subagent") || extra.deepagents_notification !== null && typeof extra.deepagents_notification === "object";
330
+ }
331
+ async function notificationKey(message, threadId, mode) {
332
+ if (!threadId || !message.id) return void 0;
333
+ try {
334
+ const payload = JSON.stringify([message.content, message.additional_kwargs]);
335
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(payload));
336
+ const hash = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
337
+ return JSON.stringify([threadId, message.id, hash, mode]);
338
+ } catch {
339
+ return void 0;
340
+ }
341
+ }
175
342
  function createDeepAgentsMiddleware(firewall, options = {}) {
176
343
  rejectConversationOptions(options);
177
344
  const maxBlockedAttempts = options.maxBlockedAttempts ?? 3;
@@ -179,6 +346,7 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
179
346
  throw new Error("maxBlockedAttempts must be a positive integer");
180
347
  }
181
348
  const effectiveMode = validateMode(options.mode) ?? firewall.mode;
349
+ const notificationChecks = /* @__PURE__ */ new Map();
182
350
  const classify = async (text, hook, conversationId, toolName) => {
183
351
  if (!text.trim()) return { enforce: false, mode: effectiveMode };
184
352
  try {
@@ -186,7 +354,7 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
186
354
  hook,
187
355
  ...toolName === void 0 ? {} : { toolName },
188
356
  ...effectiveMode === void 0 ? {} : { mode: effectiveMode },
189
- ...conversationId === void 0 ? {} : { metadata: { conversationId } }
357
+ metadata: { ...conversationId === void 0 ? {} : { conversationId }, ...remoteLineage((0, import_runnables.ensureConfig)()) }
190
358
  });
191
359
  const mode = effectiveMode ?? result.mode ?? "block";
192
360
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
@@ -196,7 +364,7 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
196
364
  } catch {
197
365
  }
198
366
  }
199
- return { enforce: blocked && mode === "block", mode };
367
+ return { enforce: blocked && mode === "block", mode, cacheable: true };
200
368
  } catch (error) {
201
369
  if (isReviewCompatibilityError(error)) throw error;
202
370
  if (options.failOpen === false) throw error;
@@ -207,6 +375,28 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
207
375
  name: "SilmarilDeepAgentsMiddleware",
208
376
  wrapModelCall: async (request, handler) => {
209
377
  const conversationId = nativeThreadId(request.runtime, void 0, void 0, (0, import_runnables.ensureConfig)());
378
+ const messages = [];
379
+ for (const message of request.messages) {
380
+ let blocked = false;
381
+ if (remoteNotification(message)) {
382
+ const key = await notificationKey(message, conversationId, effectiveMode);
383
+ const cached = key === void 0 ? void 0 : notificationChecks.get(key);
384
+ if (cached !== void 0) {
385
+ blocked = cached;
386
+ notificationChecks.delete(key);
387
+ notificationChecks.set(key, cached);
388
+ } else {
389
+ const decision = await classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId, "async_subagent");
390
+ blocked = decision.enforce;
391
+ if (key !== void 0 && decision.cacheable) {
392
+ notificationChecks.set(key, blocked);
393
+ while (notificationChecks.size > 1024) notificationChecks.delete(notificationChecks.keys().next().value);
394
+ }
395
+ }
396
+ }
397
+ messages.push(blocked ? new import_messages.HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } }) : message);
398
+ }
399
+ request = { ...request, messages };
210
400
  const history = request.state.messages;
211
401
  let lastUserIndex = -1;
212
402
  for (let i = history.length - 1; i >= 0; i--) {
@@ -258,6 +448,9 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
258
448
  return decision.mode === "block" ? safe() : stripAllowedMarker(result);
259
449
  }
260
450
  if ((await classify(resultText, HookLabel.TOOL_RESPONSE, conversationId, request.toolCall.name)).enforce) {
451
+ 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
+ return new import_langgraph.Command({ update: { messages: [safe()], asyncTasks: result.update.asyncTasks } });
453
+ }
261
454
  return safe();
262
455
  }
263
456
  return stripAllowedMarker(result);
@@ -266,28 +459,63 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
266
459
  }
267
460
  function createProtectedCompiledSubagent(firewall, options) {
268
461
  rejectConversationOptions(options);
269
- const { name, description, silmaril, middleware = [], ...agentOptions } = options;
462
+ const { name, description, mode, silmaril, middleware = [], ...agentOptions } = options;
463
+ if (mode !== void 0 && !isCompiledMode(mode)) {
464
+ throw new Error("Compiled subagent mode must be isolated or fork");
465
+ }
270
466
  const runnable = (0, import_langchain.createAgent)({
271
467
  ...agentOptions,
272
468
  middleware: [...middleware, createDeepAgentsMiddleware(firewall, silmaril)]
273
469
  });
274
- protectedCompiledGraphs.set(runnable, firewall);
275
- return { name, description, runnable };
470
+ protectedCompiledGraphs.set(runnable, { firewall, mode });
471
+ return {
472
+ name,
473
+ description,
474
+ runnable,
475
+ ...mode === void 0 ? {} : { mode }
476
+ };
276
477
  }
277
478
  function createProtectedDeepAgent(firewall, options = {}) {
278
479
  rejectConversationOptions(options);
279
480
  const { silmaril, subagents = [], protectedCompiledSubagents = [], middleware = [], ...agentOptions } = options;
481
+ const model = agentOptions.model ?? "anthropic:claude-sonnet-4-6";
482
+ const harnessProfile = resolveProtectedHarnessProfile(model);
483
+ const parentTools = agentOptions.tools ?? [];
484
+ const effectiveParentTools = applyProfileToolDescriptions(
485
+ parentTools,
486
+ harnessProfile
487
+ );
280
488
  const protectedSubagents = subagents.map((subagent) => {
281
- if ("runnable" in subagent || "graphId" in subagent) {
282
- throw new Error("Compiled or remote subagents must install Silmaril middleware inside their own graph");
489
+ if ("runnable" in subagent) {
490
+ throw new Error("Compiled subagents must use createProtectedCompiledSubagent");
283
491
  }
492
+ if ("graphId" in subagent) return { ...subagent };
284
493
  return { ...subagent, middleware: [...subagent.middleware ?? [], createDeepAgentsMiddleware(firewall, silmaril)] };
285
494
  });
286
- if (!protectedSubagents.some((subagent) => subagent.name === import_deepagents.GENERAL_PURPOSE_SUBAGENT.name)) {
287
- protectedSubagents.unshift({ ...import_deepagents.GENERAL_PURPOSE_SUBAGENT, middleware: [createDeepAgentsMiddleware(firewall, silmaril)] });
495
+ const gpConfig = harnessProfile?.generalPurposeSubagent;
496
+ if (gpConfig?.enabled !== false && !protectedSubagents.some(
497
+ (subagent) => subagent.name === import_deepagents.GENERAL_PURPOSE_SUBAGENT.name
498
+ )) {
499
+ const inheritedMiddleware = generalPurposeRootOverrides(
500
+ harnessProfile,
501
+ middleware
502
+ );
503
+ protectedSubagents.unshift({
504
+ ...import_deepagents.GENERAL_PURPOSE_SUBAGENT,
505
+ ...applyGeneralPurposeProfile(harnessProfile),
506
+ model,
507
+ tools: effectiveParentTools,
508
+ ...agentOptions.skills === void 0 ? {} : { skills: agentOptions.skills },
509
+ middleware: [
510
+ ...inheritedMiddleware,
511
+ createDeepAgentsMiddleware(firewall, silmaril)
512
+ ]
513
+ });
288
514
  }
289
515
  for (const spec of protectedCompiledSubagents) {
290
- if (!spec.runnable || protectedCompiledGraphs.get(spec.runnable) !== firewall) {
516
+ const registration = spec.runnable ? protectedCompiledGraphs.get(spec.runnable) : void 0;
517
+ const candidateMode = spec.mode;
518
+ if (registration?.firewall !== firewall || candidateMode !== void 0 && !isCompiledMode(candidateMode) || candidateMode !== registration.mode) {
291
519
  throw new Error("Compiled subagents must be built with createProtectedCompiledSubagent for this Firewall client");
292
520
  }
293
521
  }