@silmaril-security/sdk 0.8.2 → 0.9.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,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0
4
+
5
+ - Support native remote Deep Agents subagents with parent delegation/result checks
6
+ and independently protected child graphs. Preserve child thread identity, parent
7
+ lineage and async task lifecycle, and inspect background result notifications.
8
+ - Qualify isolated/fork launches, updates, checks, cancellation and failures using
9
+ real framework graphs and SDK transport against a loopback Agent Protocol peer.
10
+
11
+ - Require Deep Agents 1.16.0 or newer within the 1.x line for the qualified
12
+ remote lifecycle contract. Other optional integration ranges remain unchanged.
13
+
3
14
  ## 0.8.2
4
15
 
5
16
  - 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.0 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.0
41
41
  ```
42
42
 
43
43
  Requires Node 20 or later.
@@ -63,10 +63,10 @@ Optional LangChain.js support:
63
63
  npm install @langchain/core @langchain/openai
64
64
  ```
65
65
 
66
- Optional Deep Agents support (peer ranges shipped with `0.7.0`):
66
+ Optional Deep Agents support (including remote subagents):
67
67
 
68
68
  ```sh
69
- npm install "deepagents@^1.14.1" "langchain@^1.5.10" "@langchain/core@>=0.3.0" "@langchain/langgraph@^1.4.10"
69
+ npm install "deepagents@^1.16.0" "langchain@^1.5.10" "@langchain/core@^1.2.14" "@langchain/langgraph@^1.4.10"
70
70
  ```
71
71
 
72
72
  ## Configuration
@@ -697,6 +697,74 @@ Classification errors allow model and tool execution by default; set
697
697
  `silmaril: { failOpen: false }` to require a successful classification. Already
698
698
  emitted streaming text cannot be recalled.
699
699
 
700
+ ### Remote subagents
701
+
702
+ Remote support requires `deepagents@^1.16.0`. Use `createProtectedDeepAgent`
703
+ in **both services**. The remote Agent Protocol service owns its graph, model,
704
+ tools and Firewall client.
705
+
706
+ In the **remote service** (`remote-child.ts`):
707
+
708
+ ```typescript
709
+ import { Firewall } from "@silmaril-security/sdk";
710
+ import { createProtectedDeepAgent } from "@silmaril-security/sdk/adapters/deepagents";
711
+
712
+ const childFirewall = new Firewall({
713
+ apiKey: process.env.SILMARIL_API_KEY!,
714
+ apiUrl: process.env.SILMARIL_API_URL!,
715
+ });
716
+ export const graph = createProtectedDeepAgent(childFirewall, {
717
+ model: process.env.CHILD_MODEL!,
718
+ silmaril: { mode: "block", failOpen: false },
719
+ });
720
+ ```
721
+
722
+ Register `graph` as `research` in the remote service's Agent Protocol configuration.
723
+ Its input, tool-call, tool-result and non-streamed output checks execute inside
724
+ that child. Configure its tools and additional children through the same factory.
725
+
726
+ In the **parent application**:
727
+
728
+ ```typescript
729
+ const parent = createProtectedDeepAgent(parentFirewall, {
730
+ model: parentModel,
731
+ subagents: [{
732
+ name: "research", description: "Background research",
733
+ graphId: "research", url: "https://research.example.com",
734
+ mode: "isolated", // or "fork" to include parent conversation context
735
+ notifyParent: false,
736
+ updateStrategy: "enqueue",
737
+ }],
738
+ silmaril: { mode: "block", failOpen: false },
739
+ });
740
+ const result = await parent.invoke(
741
+ { messages: [{ role: "user", content: "Research this topic" }] },
742
+ { configurable: { thread_id: "parent-conversation" } },
743
+ );
744
+ ```
745
+
746
+ The native `start_async_task`, `check_async_task`, `update_async_task`,
747
+ `cancel_async_task` and `list_async_tasks` tools retain upstream behavior and
748
+ tracked `asyncTasks` state. Parent middleware checks delegation before launch,
749
+ returned tool results and background task notifications before model use.
750
+ Blocked result text is withheld while native task bookkeeping remains available.
751
+ Successful notification checks are reused for unchanged native message IDs within
752
+ a thread using a bounded middleware-local cache. Blocked replacements are applied
753
+ again after checkpoint resume. A new graph/process rechecks retained notifications;
754
+ failed classifications are retried.
755
+ Shadow/Warn preserve content; classification failure behavior follows `failOpen`.
756
+
757
+ The child uses its own native `thread_id` as `metadata.conversationId`.
758
+ Available `parent_thread_id` and `subagent_name` appear under `metadata.langgraph`
759
+ for attribution; they confer no authorization and do not replace child identity.
760
+ Native `headers` authenticate to the remote Agent Protocol service; each service
761
+ configures its Silmaril client separately. Fork mode shares conversation context;
762
+ deploy the child with its own middleware in either mode. The parent cannot install
763
+ middleware into another server or attest its deployment. Set `notifyParent: false`
764
+ for another deployment and check results through the native lifecycle tools.
765
+ Webhook-delivered results consumed by your application require an application-side
766
+ classification boundary. Streaming output retains the limitations described above.
767
+
700
768
  ## Migrating to 0.8.1
701
769
 
702
770
  Remove `conversationId` / `conversation_id` from LangChain handler options and
@@ -756,6 +824,7 @@ IDs must be non-empty; MCP tools also require their canonical server parent ID.
756
824
  The compatibility metadata copy remains attribution only. Caller agent metadata
757
825
  does not supply an authenticated principal.
758
826
 
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.
827
+ Published versions are listed on
828
+ [npm](https://www.npmjs.com/package/@silmaril-security/sdk?activeTab=versions) and
829
+ [GitHub Releases](https://github.com/Silmaril-Security/sdk-typescript/releases).
830
+ Version 0.9.0 adds protected remote Deep Agents support.
@@ -172,6 +172,31 @@ function stripAllowedMarker(result) {
172
172
  }
173
173
  return result;
174
174
  }
175
+ function remoteLineage(config) {
176
+ const record2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : {};
177
+ const native = record2(record2(config).metadata);
178
+ const parent = record2(record2(record2(config).configurable).deepagents_parent);
179
+ const lineage = Object.fromEntries(Object.entries({
180
+ parent_thread_id: native.parent_thread_id ?? parent.thread_id,
181
+ subagent_name: native.subagent_name
182
+ }).filter(([, value]) => typeof value === "string" && value.trim().length > 0));
183
+ return Object.keys(lineage).length ? { langgraph: lineage } : {};
184
+ }
185
+ function remoteNotification(message) {
186
+ const extra = message.additional_kwargs ?? {};
187
+ return typeof extra.lc_source === "string" && extra.lc_source.includes("async_subagent") || extra.deepagents_notification !== null && typeof extra.deepagents_notification === "object";
188
+ }
189
+ async function notificationKey(message, threadId, mode) {
190
+ if (!threadId || !message.id) return void 0;
191
+ try {
192
+ const payload = JSON.stringify([message.content, message.additional_kwargs]);
193
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(payload));
194
+ const hash = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
195
+ return JSON.stringify([threadId, message.id, hash, mode]);
196
+ } catch {
197
+ return void 0;
198
+ }
199
+ }
175
200
  function createDeepAgentsMiddleware(firewall, options = {}) {
176
201
  rejectConversationOptions(options);
177
202
  const maxBlockedAttempts = options.maxBlockedAttempts ?? 3;
@@ -179,6 +204,7 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
179
204
  throw new Error("maxBlockedAttempts must be a positive integer");
180
205
  }
181
206
  const effectiveMode = validateMode(options.mode) ?? firewall.mode;
207
+ const notificationChecks = /* @__PURE__ */ new Map();
182
208
  const classify = async (text, hook, conversationId, toolName) => {
183
209
  if (!text.trim()) return { enforce: false, mode: effectiveMode };
184
210
  try {
@@ -186,7 +212,7 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
186
212
  hook,
187
213
  ...toolName === void 0 ? {} : { toolName },
188
214
  ...effectiveMode === void 0 ? {} : { mode: effectiveMode },
189
- ...conversationId === void 0 ? {} : { metadata: { conversationId } }
215
+ metadata: { ...conversationId === void 0 ? {} : { conversationId }, ...remoteLineage((0, import_runnables.ensureConfig)()) }
190
216
  });
191
217
  const mode = effectiveMode ?? result.mode ?? "block";
192
218
  const blocked = result.prediction === "MALICIOUS" || result.governance?.action === "block";
@@ -196,7 +222,7 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
196
222
  } catch {
197
223
  }
198
224
  }
199
- return { enforce: blocked && mode === "block", mode };
225
+ return { enforce: blocked && mode === "block", mode, cacheable: true };
200
226
  } catch (error) {
201
227
  if (isReviewCompatibilityError(error)) throw error;
202
228
  if (options.failOpen === false) throw error;
@@ -207,6 +233,28 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
207
233
  name: "SilmarilDeepAgentsMiddleware",
208
234
  wrapModelCall: async (request, handler) => {
209
235
  const conversationId = nativeThreadId(request.runtime, void 0, void 0, (0, import_runnables.ensureConfig)());
236
+ const messages = [];
237
+ for (const message of request.messages) {
238
+ let blocked = false;
239
+ if (remoteNotification(message)) {
240
+ const key = await notificationKey(message, conversationId, effectiveMode);
241
+ const cached = key === void 0 ? void 0 : notificationChecks.get(key);
242
+ if (cached !== void 0) {
243
+ blocked = cached;
244
+ notificationChecks.delete(key);
245
+ notificationChecks.set(key, cached);
246
+ } else {
247
+ const decision = await classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId, "async_subagent");
248
+ blocked = decision.enforce;
249
+ if (key !== void 0 && decision.cacheable) {
250
+ notificationChecks.set(key, blocked);
251
+ while (notificationChecks.size > 1024) notificationChecks.delete(notificationChecks.keys().next().value);
252
+ }
253
+ }
254
+ }
255
+ messages.push(blocked ? new import_messages.HumanMessage({ content: SAFE_TOOL_MESSAGE, ...message.id === void 0 ? {} : { id: message.id } }) : message);
256
+ }
257
+ request = { ...request, messages };
210
258
  const history = request.state.messages;
211
259
  let lastUserIndex = -1;
212
260
  for (let i = history.length - 1; i >= 0; i--) {
@@ -258,6 +306,9 @@ function createDeepAgentsMiddleware(firewall, options = {}) {
258
306
  return decision.mode === "block" ? safe() : stripAllowedMarker(result);
259
307
  }
260
308
  if ((await classify(resultText, HookLabel.TOOL_RESPONSE, conversationId, request.toolCall.name)).enforce) {
309
+ 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) {
310
+ return new import_langgraph.Command({ update: { messages: [safe()], asyncTasks: result.update.asyncTasks } });
311
+ }
261
312
  return safe();
262
313
  }
263
314
  return stripAllowedMarker(result);
@@ -278,9 +329,10 @@ function createProtectedDeepAgent(firewall, options = {}) {
278
329
  rejectConversationOptions(options);
279
330
  const { silmaril, subagents = [], protectedCompiledSubagents = [], middleware = [], ...agentOptions } = options;
280
331
  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");
332
+ if ("runnable" in subagent) {
333
+ throw new Error("Compiled subagents must use createProtectedCompiledSubagent");
283
334
  }
335
+ if ("graphId" in subagent) return { ...subagent };
284
336
  return { ...subagent, middleware: [...subagent.middleware ?? [], createDeepAgentsMiddleware(firewall, silmaril)] };
285
337
  });
286
338
  if (!protectedSubagents.some((subagent) => subagent.name === import_deepagents.GENERAL_PURPOSE_SUBAGENT.name)) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/adapters/deepagents.ts","../../src/exceptions.ts","../../src/hooks.ts","../../src/modes.ts","../../src/adapters/thread-identity.ts"],"sourcesContent":["// Copyright (c) 2024-2026 Silmaril Security Inc. All rights reserved.\n\n/** Optional Deep Agents integration. Import from @silmaril-security/sdk/adapters/deepagents. */\nimport { AIMessage, HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { ensureConfig } from \"@langchain/core/runnables\";\nimport { Command } from \"@langchain/langgraph\";\nimport { createDeepAgent, GENERAL_PURPOSE_SUBAGENT, type AnySubAgent, type CompiledSubAgent } from \"deepagents\";\nimport { createAgent, createMiddleware, type CreateAgentParams } from \"langchain\";\n\nimport type { Firewall } from \"../firewall.js\";\nimport { isReviewCompatibilityError } from \"../exceptions.js\";\nimport { HookLabel } from \"../hooks.js\";\nimport { validateMode } from \"../modes.js\";\nimport type { ClassifyEvent, FirewallMode } from \"../types.js\";\n\nimport { nativeThreadId, rejectConversationOptions } from \"./thread-identity.js\";\n\nexport const SAFE_TOOL_MESSAGE = \"Silmaril Firewall blocked this tool interaction. Choose a different safe action.\";\nexport const SAFE_FINAL_MESSAGE = \"Silmaril Firewall stopped this request after repeated unsafe actions.\";\nexport const SAFE_OUTPUT_MESSAGE = \"Silmaril Firewall blocked this response.\";\nconst BLOCKED_TOOL_MARKER = \"silmaril-firewall:v1:blocked-tool\";\nconst issuedBlockedMessages = new WeakSet<ToolMessage>();\n\n// A protected graph is identified by the exact runnable returned by our factory.\nconst protectedCompiledGraphs = new WeakMap<object, Firewall>();\n\nexport interface DeepAgentsMiddlewareOptions {\n mode?: FirewallMode;\n failOpen?: boolean;\n maxBlockedAttempts?: number;\n onClassify?: (event: ClassifyEvent) => void;\n}\n\nfunction textOf(message: { content: unknown }): string {\n return typeof message.content === \"string\" ? message.content : JSON.stringify(message.content);\n}\n\nfunction textOfStructuredValue(value: unknown, seen = new WeakSet<object>()): string {\n if (value == null) return \"\";\n if (typeof value !== \"object\") return String(value);\n if (seen.has(value)) return \"[circular]\";\n seen.add(value);\n if (Array.isArray(value)) return value.map((item) => textOfStructuredValue(item, seen)).join(\"\\n\");\n return Object.entries(value).map(([key, item]) => `${key}: ${textOfStructuredValue(item, seen)}`).join(\"\\n\");\n}\n\nfunction stripAllowedMarker(result: ToolMessage | Command): ToolMessage | Command {\n const strip = (message: ToolMessage): ToolMessage => {\n if (message.additional_kwargs?.silmarilBlocked !== BLOCKED_TOOL_MARKER) return message;\n if (issuedBlockedMessages.has(message)) return message;\n const { silmarilBlocked: _marker, ...additional_kwargs } = message.additional_kwargs;\n // Tool providers may return frozen messages or metadata. Copy rather\n // than mutating a result owned by the caller.\n return new ToolMessage({ ...message, additional_kwargs });\n };\n if (ToolMessage.isInstance(result)) return strip(result);\n if (result instanceof Command) {\n const update = result.update;\n if (update && !Array.isArray(update) && \"messages\" in update && Array.isArray(update.messages)) {\n const originalMessages = update.messages;\n const messages = originalMessages.map((message) => ToolMessage.isInstance(message) ? strip(message) : message);\n if (messages.some((message, index) => message !== originalMessages[index])) {\n return new Command({ ...result, update: { ...update, messages } });\n }\n }\n }\n return result;\n}\n\nexport function createDeepAgentsMiddleware(firewall: Firewall, options: DeepAgentsMiddlewareOptions = {}) {\n rejectConversationOptions(options);\n const maxBlockedAttempts = options.maxBlockedAttempts ?? 3;\n if (!Number.isInteger(maxBlockedAttempts) || maxBlockedAttempts < 1) {\n throw new Error(\"maxBlockedAttempts must be a positive integer\");\n }\n const effectiveMode = validateMode(options.mode) ?? firewall.mode;\n const classify = async (text: string, hook: HookLabel, conversationId: string | undefined, toolName?: string): Promise<{ enforce: boolean; mode: FirewallMode | undefined }> => {\n if (!text.trim()) return { enforce: false, mode: effectiveMode };\n try {\n const result = await firewall.classify(text, {\n hook,\n ...(toolName === undefined ? {} : { toolName }),\n ...(effectiveMode === undefined ? {} : { mode: effectiveMode }),\n ...(conversationId === undefined ? {} : { metadata: { conversationId } }),\n });\n const mode = effectiveMode ?? result.mode ?? \"block\";\n const blocked = result.prediction === \"MALICIOUS\" || result.governance?.action === \"block\";\n if (options.onClassify) {\n try {\n options.onClassify({ hook, ...(toolName === undefined ? {} : { toolName }), text, result, blocked, mode, shadowMode: mode === \"shadow\" });\n } catch {\n // Observation callbacks do not change enforcement.\n }\n }\n return { enforce: blocked && mode === \"block\", mode };\n } catch (error) {\n if (isReviewCompatibilityError(error)) throw error;\n if (options.failOpen === false) throw error;\n return { enforce: false, mode: effectiveMode };\n }\n };\n\n return createMiddleware({\n name: \"SilmarilDeepAgentsMiddleware\",\n wrapModelCall: async (request, handler) => {\n const conversationId = nativeThreadId(request.runtime, undefined, undefined, ensureConfig());\n const history = request.state.messages;\n let lastUserIndex = -1;\n for (let i = history.length - 1; i >= 0; i--) {\n if (HumanMessage.isInstance(history[i])) {\n lastUserIndex = i;\n break;\n }\n }\n const blockedCount = history.slice(lastUserIndex + 1).filter(\n (message) => ToolMessage.isInstance(message) && message.content === SAFE_TOOL_MESSAGE\n && message.additional_kwargs?.silmarilBlocked === BLOCKED_TOOL_MARKER,\n ).length;\n const latestUser = [...request.messages].reverse().find(HumanMessage.isInstance);\n const inputDecision = latestUser\n ? await classify(textOf(latestUser), HookLabel.USER_INPUT, conversationId)\n : undefined;\n if (inputDecision?.enforce) return new AIMessage(SAFE_OUTPUT_MESSAGE);\n const capMode = effectiveMode ?? inputDecision?.mode ?? \"block\";\n // Only genuine prior Block markers count, and the terminal cap requires current effective Block mode.\n if (blockedCount >= maxBlockedAttempts && capMode === \"block\") {\n return new AIMessage(SAFE_FINAL_MESSAGE);\n }\n const response = await handler(request);\n if (response instanceof Command && (await classify(textOfStructuredValue(response.update), HookLabel.LLM_OUTPUT, conversationId)).enforce) {\n return new AIMessage(SAFE_OUTPUT_MESSAGE);\n }\n if (AIMessage.isInstance(response) && (await classify(textOf(response), HookLabel.LLM_OUTPUT, conversationId)).enforce) {\n return new AIMessage(SAFE_OUTPUT_MESSAGE);\n }\n return response;\n },\n wrapToolCall: async (request, handler) => {\n const conversationId = nativeThreadId(request.runtime, undefined, undefined, ensureConfig());\n const safe = () => {\n const message = new ToolMessage({\n content: SAFE_TOOL_MESSAGE,\n tool_call_id: request.toolCall.id ?? \"\",\n name: request.toolCall.name,\n additional_kwargs: { silmarilBlocked: BLOCKED_TOOL_MARKER },\n });\n issuedBlockedMessages.add(message);\n return message;\n };\n if ((await classify(JSON.stringify(request.toolCall.args ?? {}), HookLabel.TOOL_CALL, conversationId, request.toolCall.name)).enforce) {\n return safe();\n }\n const result = await handler(request);\n let resultText: string;\n try {\n resultText = ToolMessage.isInstance(result) ? textOf(result)\n : result instanceof Command ? textOfStructuredValue(result.update) : String(result);\n } catch {\n // Content cannot be inspected, but the backend still resolves the\n // enforcement mode. Observation modes retain the original result.\n const decision = await classify(\"[uninspectable tool result]\", HookLabel.TOOL_RESPONSE, conversationId, request.toolCall.name);\n return decision.mode === \"block\" ? safe() : stripAllowedMarker(result);\n }\n if ((await classify(resultText, HookLabel.TOOL_RESPONSE, conversationId, request.toolCall.name)).enforce) {\n return safe();\n }\n return stripAllowedMarker(result);\n },\n });\n}\n\nexport interface ProtectedCompiledSubagentOptions extends Omit<CreateAgentParams, \"middleware\"> {\n name: string;\n description: string;\n middleware?: CreateAgentParams[\"middleware\"];\n silmaril?: DeepAgentsMiddlewareOptions;\n}\n\n/** Compile a subagent with Silmaril middleware and register that exact graph. */\nexport function createProtectedCompiledSubagent(firewall: Firewall, options: ProtectedCompiledSubagentOptions): CompiledSubAgent {\n rejectConversationOptions(options);\n const { name, description, silmaril, middleware = [], ...agentOptions } = options;\n const runnable = createAgent({\n ...agentOptions,\n middleware: [...middleware, createDeepAgentsMiddleware(firewall, silmaril)] as const,\n });\n protectedCompiledGraphs.set(runnable, firewall);\n return { name, description, runnable };\n}\n\nexport interface ProtectedDeepAgentOptions extends Omit<NonNullable<Parameters<typeof createDeepAgent>[0]>, \"subagents\" | \"middleware\"> {\n subagents?: readonly AnySubAgent[];\n /** Only pass specs returned by createProtectedCompiledSubagent for this client. */\n protectedCompiledSubagents?: readonly CompiledSubAgent[];\n middleware?: NonNullable<Parameters<typeof createDeepAgent>[0]>[\"middleware\"];\n silmaril?: DeepAgentsMiddlewareOptions;\n}\n\n/** Protect root, default general-purpose, and declarative subagents. */\nexport function createProtectedDeepAgent(firewall: Firewall, options: ProtectedDeepAgentOptions = {}) {\n rejectConversationOptions(options);\n const { silmaril, subagents = [], protectedCompiledSubagents = [], middleware = [], ...agentOptions } = options;\n const protectedSubagents = subagents.map((subagent) => {\n if (\"runnable\" in subagent || \"graphId\" in subagent) {\n throw new Error(\"Compiled or remote subagents must install Silmaril middleware inside their own graph\");\n }\n return { ...subagent, middleware: [...(subagent.middleware ?? []), createDeepAgentsMiddleware(firewall, silmaril)] };\n });\n if (!protectedSubagents.some((subagent) => subagent.name === GENERAL_PURPOSE_SUBAGENT.name)) {\n protectedSubagents.unshift({ ...GENERAL_PURPOSE_SUBAGENT, middleware: [createDeepAgentsMiddleware(firewall, silmaril)] });\n }\n for (const spec of protectedCompiledSubagents) {\n if (!spec.runnable || protectedCompiledGraphs.get(spec.runnable) !== firewall) {\n throw new Error(\"Compiled subagents must be built with createProtectedCompiledSubagent for this Firewall client\");\n }\n }\n return createDeepAgent({\n ...agentOptions,\n middleware: [...middleware, createDeepAgentsMiddleware(firewall, silmaril)],\n subagents: [...protectedSubagents, ...protectedCompiledSubagents],\n });\n}\n","// Copyright (c) 2024-2025 Silmaril Security Inc. All rights reserved.\n// PROPRIETARY AND CONFIDENTIAL\n\nimport type { HookLabel } from \"./hooks.js\";\nimport type { BlockResult, ReviewLevel } from \"./types.js\";\n\nconst MAX_PROMPT_DISPLAY_LEN = 100;\n\nexport interface MalformedInputDetails {\n field?: string;\n inputIndex?: number;\n charOffset?: number;\n malformedToken?: string;\n codePoint?: string;\n reason?: string;\n}\n\nexport class FirewallBlockedException extends Error {\n readonly score: number;\n readonly threshold: number;\n readonly promptText: string;\n readonly runId: string | undefined;\n readonly hook: HookLabel | undefined;\n readonly toolName: string | undefined;\n readonly toolCallId: string | undefined;\n readonly result: BlockResult | undefined;\n\n constructor(params: {\n score: number;\n threshold: number;\n promptText: string;\n runId?: string;\n hook?: HookLabel;\n toolName?: string;\n toolCallId?: string;\n result?: BlockResult;\n }) {\n super(FirewallBlockedException.formatMessage(params));\n this.name = \"FirewallBlockedException\";\n this.score = params.score;\n this.threshold = params.threshold;\n this.promptText = params.promptText;\n this.runId = params.runId;\n this.hook = params.hook;\n this.toolName = params.toolName;\n this.toolCallId = params.toolCallId;\n this.result = params.result;\n Object.setPrototypeOf(this, FirewallBlockedException.prototype);\n }\n\n private static formatMessage(params: {\n score: number;\n threshold: number;\n promptText: string;\n result?: BlockResult;\n }): string {\n const truncated =\n params.promptText.length > MAX_PROMPT_DISPLAY_LEN\n ? `${params.promptText.slice(0, MAX_PROMPT_DISPLAY_LEN)}...`\n : params.promptText;\n if (\n params.result?.prediction !== \"MALICIOUS\" &&\n params.result?.governance?.action === \"block\"\n ) {\n return `Request blocked by Silmaril Firewall governance policy: '${truncated}'`;\n }\n return (\n `Request blocked by Silmaril Firewall ` +\n `(score=${params.score.toFixed(4)}, threshold=${params.threshold.toFixed(4)}): ` +\n `'${truncated}'`\n );\n }\n}\n\n/** @deprecated Use FirewallBlockedException instead. */\nexport const PromptBlockedException = FirewallBlockedException;\n/** @deprecated Use FirewallBlockedException instead. */\nexport type PromptBlockedException = FirewallBlockedException;\n\nconst REVIEW_COMPATIBILITY_ERROR_BRAND = Symbol.for(\n \"@silmaril-security/sdk/ReviewCompatibilityError\",\n);\n\nexport class ReviewCompatibilityError extends Error {\n readonly requestedReview: ReviewLevel;\n readonly acknowledgedReview: unknown;\n\n constructor(requestedReview: ReviewLevel, acknowledgedReview: unknown) {\n const detail = acknowledgedReview === undefined\n ? \"the response omitted its acknowledgement\"\n : \"the response acknowledgement did not match\";\n super(`Silmaril review compatibility error: ${detail} for requested ${requestedReview} review`);\n this.name = \"ReviewCompatibilityError\";\n this.requestedReview = requestedReview;\n this.acknowledgedReview = acknowledgedReview;\n Object.defineProperty(this, REVIEW_COMPATIBILITY_ERROR_BRAND, {\n value: true,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n Object.setPrototypeOf(this, ReviewCompatibilityError.prototype);\n }\n}\n\nexport function isReviewCompatibilityError(error: unknown): error is ReviewCompatibilityError {\n if ((typeof error !== \"object\" && typeof error !== \"function\") || error === null) {\n return false;\n }\n try {\n return Object.getOwnPropertyDescriptor(\n error,\n REVIEW_COMPATIBILITY_ERROR_BRAND,\n )?.value === true;\n } catch {\n return false;\n }\n}\n\nexport class SilmarilApiError extends Error {\n readonly status: number;\n readonly statusText: string;\n readonly body: string;\n readonly details: MalformedInputDetails | undefined;\n readonly error: string | undefined;\n readonly apiMessage: string | undefined;\n\n constructor(params: {\n status: number;\n statusText: string;\n body: string;\n details?: MalformedInputDetails;\n error?: string;\n apiMessage?: string;\n }) {\n const statusText = params.statusText ? ` ${params.statusText}` : \"\";\n super(`Silmaril API error ${params.status}${statusText}`);\n this.name = \"SilmarilApiError\";\n this.status = params.status;\n this.statusText = params.statusText;\n this.body = params.body;\n const parsed = parseErrorBody(params.body);\n this.details = params.details ?? parsed.details;\n this.error = params.error ?? parsed.error;\n this.apiMessage = params.apiMessage ?? parsed.apiMessage;\n Object.setPrototypeOf(this, SilmarilApiError.prototype);\n }\n}\n\nfunction parseErrorBody(body: string): {\n details: MalformedInputDetails | undefined;\n error: string | undefined;\n apiMessage: string | undefined;\n} {\n try {\n const parsed = JSON.parse(body) as unknown;\n if (!parsed || typeof parsed !== \"object\") {\n return { details: undefined, error: undefined, apiMessage: undefined };\n }\n const data = parsed as Record<string, unknown>;\n return {\n details:\n data.details && typeof data.details === \"object\"\n ? (data.details as MalformedInputDetails)\n : undefined,\n error: typeof data.error === \"string\" ? data.error : undefined,\n apiMessage: typeof data.message === \"string\" ? data.message : undefined,\n };\n } catch {\n return { details: undefined, error: undefined, apiMessage: undefined };\n }\n}\n","// Copyright (c) 2024-2025 Silmaril Security Inc. All rights reserved.\n// PROPRIETARY AND CONFIDENTIAL\n\nexport const HookLabel = {\n USER_INPUT: \"user_input\",\n SYSTEM_PROMPT: \"system_prompt\",\n TOOL_CALL: \"tool_call\",\n TOOL_RESPONSE: \"tool_response\",\n LLM_OUTPUT: \"llm_output\",\n UNKNOWN: \"unknown\",\n} as const;\n\nexport type HookLabel = (typeof HookLabel)[keyof typeof HookLabel];\n\nexport const FirewallHook = {\n LLM_START: \"on_llm_start\",\n CHAT_MODEL_START: \"on_chat_model_start\",\n TOOL_START: \"on_tool_start\",\n RETRIEVER_START: \"on_retriever_start\",\n LLM_END: \"on_llm_end\",\n TOOL_END: \"on_tool_end\",\n RETRIEVER_END: \"on_retriever_end\",\n} as const;\n\nexport type FirewallHook = (typeof FirewallHook)[keyof typeof FirewallHook];\n\nexport const DEFAULT_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n FirewallHook.LLM_START,\n FirewallHook.CHAT_MODEL_START,\n FirewallHook.TOOL_START,\n FirewallHook.TOOL_END,\n]);\n\nexport const INPUT_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n FirewallHook.LLM_START,\n FirewallHook.CHAT_MODEL_START,\n FirewallHook.TOOL_START,\n FirewallHook.RETRIEVER_START,\n]);\n\nexport const OUTPUT_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n FirewallHook.LLM_END,\n FirewallHook.TOOL_END,\n FirewallHook.RETRIEVER_END,\n]);\n\nexport const ALL_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n ...INPUT_HOOKS,\n ...OUTPUT_HOOKS,\n]);\n\nexport const FIREWALL_HOOK_TO_LABEL: Readonly<Record<FirewallHook, HookLabel>> = {\n [FirewallHook.CHAT_MODEL_START]: HookLabel.USER_INPUT,\n [FirewallHook.LLM_START]: HookLabel.USER_INPUT,\n [FirewallHook.TOOL_START]: HookLabel.TOOL_CALL,\n [FirewallHook.TOOL_END]: HookLabel.TOOL_RESPONSE,\n [FirewallHook.RETRIEVER_START]: HookLabel.TOOL_CALL,\n [FirewallHook.RETRIEVER_END]: HookLabel.TOOL_RESPONSE,\n [FirewallHook.LLM_END]: HookLabel.LLM_OUTPUT,\n};\n\nconst FIREWALL_HOOK_VALUES: ReadonlySet<string> = new Set(Object.values(FirewallHook));\n\nexport function resolveHooks(\n hooks: Iterable<FirewallHook | string> | undefined,\n): ReadonlySet<FirewallHook> {\n if (hooks === undefined) {\n return DEFAULT_HOOKS;\n }\n const resolved = new Set<FirewallHook>();\n for (const h of hooks) {\n if (!FIREWALL_HOOK_VALUES.has(h)) {\n throw new Error(`Invalid FirewallHook value: ${String(h)}`);\n }\n resolved.add(h as FirewallHook);\n }\n return resolved;\n}\n\nexport function prependHook(text: string, hook: HookLabel | string | undefined | null): string {\n if (hook === undefined || hook === null) {\n return text;\n }\n if (hook === HookLabel.UNKNOWN) {\n return text;\n }\n return `[HOOK:${hook}] ${text}`;\n}\n\nexport function prependToolName(text: string, toolName: string | undefined | null): string {\n if (toolName === undefined || toolName === null) {\n return text;\n }\n return `[TOOL:${toolName}] ${text}`;\n}\n","import type { FirewallMode } from \"./types.js\";\n\n/** Validate JavaScript/configuration inputs before any fail-open adapter path. */\nexport function validateMode(value: unknown): FirewallMode | undefined {\n if (value === undefined || value === \"shadow\" || value === \"warn\" || value === \"block\") {\n return value;\n }\n throw new Error(\"Firewall: mode must be shadow, warn, or block\");\n}\n","// Copyright (c) 2026 Silmaril Security Inc. All rights reserved.\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined;\n}\n\nexport function validThreadId(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\nconst NO_THREAD_IDS: readonly string[] = Object.freeze([]);\n\nfunction threadIds(first?: string, second?: string): readonly string[] {\n if (first === undefined) return second === undefined ? NO_THREAD_IDS : Object.freeze([second]);\n return Object.freeze(second === undefined || second === first ? [first] : [first, second]);\n}\n\n/** Native config is authoritative, including an explicitly invalid/empty ID. */\nexport function nativeThreadId(runtime?: unknown, metadata?: unknown, inherited?: string, currentConfig?: unknown): string | undefined {\n const explicit = record(record(runtime)?.configurable);\n const current = record(record(currentConfig)?.configurable);\n for (const candidate of [explicit, current, record(metadata)]) {\n if (candidate && Object.prototype.hasOwnProperty.call(candidate, \"thread_id\")) {\n return validThreadId(candidate.thread_id);\n }\n }\n return inherited;\n}\n\nexport function rejectConversationOptions(options: object): void {\n if (\"conversationId\" in options || \"conversation_id\" in options) {\n throw new TypeError(\"conversationId/conversation_id was removed. Pass the native configurable.thread_id when invoking the agent or runnable instead.\");\n }\n}\n\ninterface RunIdentity {\n threadId: string | undefined;\n /** At most two ordinary candidates deeper children must not re-accept. */\n untrustedThreadIds: readonly string[];\n parentRunId: string | undefined;\n graphProven: boolean;\n}\n\n/** State belongs to callback runs, never to a reusable agent or current user. */\nexport class RunThreadIdentity {\n private readonly runs = new Map<string, RunIdentity>();\n private readonly children = new Map<string, Set<string>>();\n\n constructor(\n private readonly boundIdentity?: { threadId: string | undefined },\n private readonly currentConfig: () => unknown = () => undefined,\n ) {}\n\n start(runId: string, parentRunId?: string, metadata?: unknown): string[] {\n const discarded = this.finish(runId);\n if (this.runs.size >= 4096) {\n const oldestRoot = [...this.runs].find(([, run]) => run.parentRunId === undefined || !this.runs.has(run.parentRunId))?.[0] ?? this.runs.keys().next().value;\n if (oldestRoot !== undefined) discarded.push(...this.finish(oldestRoot));\n }\n const parent = parentRunId === undefined ? undefined : this.runs.get(parentRunId);\n const inherited = parent?.threadId;\n const exposed = record(metadata);\n const hasExposedThread = exposed !== undefined\n && Object.prototype.hasOwnProperty.call(exposed, \"thread_id\");\n const candidate = hasExposedThread ? validThreadId(exposed.thread_id) : undefined;\n // Ordinary callbacks may see a parent's ambient config while a child has a\n // hidden per-call override. Only graph-tagged metadata proves that context.\n let threadId: string | undefined;\n let untrustedThreadIds: readonly string[];\n let graphProven: boolean;\n if (this.boundIdentity && parent === undefined) {\n threadId = this.boundIdentity.threadId;\n untrustedThreadIds = threadIds(threadId, candidate);\n graphProven = false;\n } else if (exposed && (\n typeof exposed.langgraph_node === \"string\"\n || typeof exposed.langgraph_step === \"number\"\n )) {\n threadId = nativeThreadId(undefined, exposed, inherited, this.currentConfig());\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = true;\n } else if (hasExposedThread) {\n if (candidate === undefined) {\n threadId = undefined;\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = false;\n } else if (parent?.graphProven && candidate === inherited) {\n threadId = inherited;\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = true;\n } else if (parent && (\n candidate === inherited || parent.untrustedThreadIds.includes(candidate)\n )) {\n threadId = undefined;\n untrustedThreadIds = parent.untrustedThreadIds;\n graphProven = false;\n } else {\n threadId = candidate;\n untrustedThreadIds = threadIds(candidate);\n graphProven = false;\n }\n } else if (parent?.graphProven) {\n threadId = inherited;\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = true;\n } else {\n threadId = undefined;\n untrustedThreadIds = parent?.untrustedThreadIds ?? NO_THREAD_IDS;\n graphProven = false;\n }\n this.runs.set(runId, { threadId, untrustedThreadIds, parentRunId, graphProven });\n if (parentRunId !== undefined && parentRunId !== runId) {\n const children = this.children.get(parentRunId) ?? new Set<string>();\n children.add(runId);\n this.children.set(parentRunId, children);\n }\n return discarded;\n }\n\n get(runId: string): string | undefined {\n const run = this.runs.get(runId);\n return run ? run.threadId : this.boundIdentity?.threadId;\n }\n\n finish(runId: string): string[] {\n const pending = [runId];\n const seen = new Set<string>();\n while (pending.length) {\n const id = pending.pop()!;\n if (seen.has(id)) continue;\n seen.add(id);\n pending.push(...this.children.get(id) ?? []);\n this.children.delete(id);\n const parent = this.runs.get(id)?.parentRunId;\n this.runs.delete(id);\n if (parent !== undefined) {\n const siblings = this.children.get(parent);\n siblings?.delete(id);\n if (siblings?.size === 0) this.children.delete(parent);\n }\n }\n return [...seen];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,sBAAqD;AACrD,uBAA6B;AAC7B,uBAAwB;AACxB,wBAAmG;AACnG,uBAAsE;;;ACwEtE,IAAM,mCAAmC,uBAAO;AAAA,EAC9C;AACF;AAwBO,SAAS,2BAA2B,OAAmD;AAC5F,MAAK,OAAO,UAAU,YAAY,OAAO,UAAU,cAAe,UAAU,MAAM;AAChF,WAAO;AAAA,EACT;AACA,MAAI;AACF,WAAO,OAAO;AAAA,MACZ;AAAA,MACA;AAAA,IACF,GAAG,UAAU;AAAA,EACf,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;AClHO,IAAM,YAAY;AAAA,EACvB,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,WAAW;AAAA,EACX,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,SAAS;AACX;AAIO,IAAM,eAAe;AAAA,EAC1B,WAAW;AAAA,EACX,kBAAkB;AAAA,EAClB,YAAY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U,QAAQ,CAAC,EAAE;AAAA,EACrH,CAAC;AACD,MAAI,CAAC,mBAAmB,KAAK,CAAC,aAAa,SAAS,SAAS,2CAAyB,IAAI,GAAG;AAC3F,uBAAmB,QAAQ,EAAE,GAAG,4CAA0B,YAAY,CAAC,2BAA2B,UAAU,QAAQ,CAAC,EAAE,CAAC;AAAA,EAC1H;AACA,aAAW,QAAQ,4BAA4B;AAC7C,QAAI,CAAC,KAAK,YAAY,wBAAwB,IAAI,KAAK,QAAQ,MAAM,UAAU;AAC7E,YAAM,IAAI,MAAM,gGAAgG;AAAA,IAClH;AAAA,EACF;AACA,aAAO,mCAAgB;AAAA,IACrB,GAAG;AAAA,IACH,YAAY,CAAC,GAAG,YAAY,2BAA2B,UAAU,QAAQ,CAAC;AAAA,IAC1E,WAAW,CAAC,GAAG,oBAAoB,GAAG,0BAA0B;AAAA,EAClE,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/adapters/deepagents.ts","../../src/exceptions.ts","../../src/hooks.ts","../../src/modes.ts","../../src/adapters/thread-identity.ts"],"sourcesContent":["// Copyright (c) 2024-2026 Silmaril Security Inc. All rights reserved.\n\n/** Optional Deep Agents integration. Import from @silmaril-security/sdk/adapters/deepagents. */\nimport { AIMessage, HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { ensureConfig } from \"@langchain/core/runnables\";\nimport { Command } from \"@langchain/langgraph\";\nimport { createDeepAgent, GENERAL_PURPOSE_SUBAGENT, type AnySubAgent, type CompiledSubAgent } from \"deepagents\";\nimport { createAgent, createMiddleware, type CreateAgentParams } from \"langchain\";\n\nimport type { Firewall } from \"../firewall.js\";\nimport { isReviewCompatibilityError } from \"../exceptions.js\";\nimport { HookLabel } from \"../hooks.js\";\nimport { validateMode } from \"../modes.js\";\nimport type { ClassifyEvent, FirewallMode } from \"../types.js\";\n\nimport { nativeThreadId, rejectConversationOptions } from \"./thread-identity.js\";\n\nexport const SAFE_TOOL_MESSAGE = \"Silmaril Firewall blocked this tool interaction. Choose a different safe action.\";\nexport const SAFE_FINAL_MESSAGE = \"Silmaril Firewall stopped this request after repeated unsafe actions.\";\nexport const SAFE_OUTPUT_MESSAGE = \"Silmaril Firewall blocked this response.\";\nconst BLOCKED_TOOL_MARKER = \"silmaril-firewall:v1:blocked-tool\";\nconst issuedBlockedMessages = new WeakSet<ToolMessage>();\n\n// A protected graph is identified by the exact runnable returned by our factory.\nconst protectedCompiledGraphs = new WeakMap<object, Firewall>();\n\nexport interface DeepAgentsMiddlewareOptions {\n mode?: FirewallMode;\n failOpen?: boolean;\n maxBlockedAttempts?: number;\n onClassify?: (event: ClassifyEvent) => void;\n}\n\nfunction textOf(message: { content: unknown }): string {\n return typeof message.content === \"string\" ? message.content : JSON.stringify(message.content);\n}\n\nfunction textOfStructuredValue(value: unknown, seen = new WeakSet<object>()): string {\n if (value == null) return \"\";\n if (typeof value !== \"object\") return String(value);\n if (seen.has(value)) return \"[circular]\";\n seen.add(value);\n if (Array.isArray(value)) return value.map((item) => textOfStructuredValue(item, seen)).join(\"\\n\");\n return Object.entries(value).map(([key, item]) => `${key}: ${textOfStructuredValue(item, seen)}`).join(\"\\n\");\n}\n\nfunction stripAllowedMarker(result: ToolMessage | Command): ToolMessage | Command {\n const strip = (message: ToolMessage): ToolMessage => {\n if (message.additional_kwargs?.silmarilBlocked !== BLOCKED_TOOL_MARKER) return message;\n if (issuedBlockedMessages.has(message)) return message;\n const { silmarilBlocked: _marker, ...additional_kwargs } = message.additional_kwargs;\n // Tool providers may return frozen messages or metadata. Copy rather\n // than mutating a result owned by the caller.\n return new ToolMessage({ ...message, additional_kwargs });\n };\n if (ToolMessage.isInstance(result)) return strip(result);\n if (result instanceof Command) {\n const update = result.update;\n if (update && !Array.isArray(update) && \"messages\" in update && Array.isArray(update.messages)) {\n const originalMessages = update.messages;\n const messages = originalMessages.map((message) => ToolMessage.isInstance(message) ? strip(message) : message);\n if (messages.some((message, index) => message !== originalMessages[index])) {\n return new Command({ ...result, update: { ...update, messages } });\n }\n }\n }\n return result;\n}\n\nfunction remoteLineage(config: unknown): Record<string, unknown> {\n const record = (v: unknown): Record<string, unknown> => v !== null && typeof v === \"object\" && !Array.isArray(v) ? v as Record<string, unknown> : {};\n const native = record(record(config).metadata);\n const parent = record(record(record(config).configurable).deepagents_parent);\n const lineage = Object.fromEntries(Object.entries({\n parent_thread_id: native.parent_thread_id ?? parent.thread_id,\n subagent_name: native.subagent_name,\n }).filter(([, value]) => typeof value === \"string\" && value.trim().length > 0));\n return Object.keys(lineage).length ? { langgraph: lineage } : {};\n}\n\nfunction remoteNotification(message: { additional_kwargs?: Record<string, unknown> }): boolean {\n const extra = message.additional_kwargs ?? {};\n // Notification metadata selects inspection, never authority.\n return (typeof extra.lc_source === \"string\" && extra.lc_source.includes(\"async_subagent\"))\n || (extra.deepagents_notification !== null && typeof extra.deepagents_notification === \"object\");\n}\n\nasync function notificationKey(message: { id?: string; content: unknown; additional_kwargs?: Record<string, unknown> }, threadId: string | undefined, mode: FirewallMode | undefined): Promise<string | undefined> {\n if (!threadId || !message.id) return undefined;\n try {\n const payload = JSON.stringify([message.content, message.additional_kwargs]);\n const digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(payload));\n const hash = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, \"0\")).join(\"\");\n return JSON.stringify([threadId, message.id, hash, mode]);\n } catch {\n // Unserializable messages or unavailable hashing always receive a fresh check.\n return undefined;\n }\n}\n\nexport function createDeepAgentsMiddleware(firewall: Firewall, options: DeepAgentsMiddlewareOptions = {}) {\n rejectConversationOptions(options);\n const maxBlockedAttempts = options.maxBlockedAttempts ?? 3;\n if (!Number.isInteger(maxBlockedAttempts) || maxBlockedAttempts < 1) {\n throw new Error(\"maxBlockedAttempts must be a positive integer\");\n }\n const effectiveMode = validateMode(options.mode) ?? firewall.mode;\n const notificationChecks = new Map<string, boolean>();\n const classify = async (text: string, hook: HookLabel, conversationId: string | undefined, toolName?: string): Promise<{ enforce: boolean; mode: FirewallMode | undefined; cacheable?: boolean }> => {\n if (!text.trim()) return { enforce: false, mode: effectiveMode };\n try {\n const result = await firewall.classify(text, {\n hook,\n ...(toolName === undefined ? {} : { toolName }),\n ...(effectiveMode === undefined ? {} : { mode: effectiveMode }),\n metadata: { ...(conversationId === undefined ? {} : { conversationId }), ...remoteLineage(ensureConfig()) },\n });\n const mode = effectiveMode ?? result.mode ?? \"block\";\n const blocked = result.prediction === \"MALICIOUS\" || result.governance?.action === \"block\";\n if (options.onClassify) {\n try {\n options.onClassify({ hook, ...(toolName === undefined ? {} : { toolName }), text, result, blocked, mode, shadowMode: mode === \"shadow\" });\n } catch {\n // Observation callbacks do not change enforcement.\n }\n }\n return { enforce: blocked && mode === \"block\", mode, cacheable: true };\n } catch (error) {\n if (isReviewCompatibilityError(error)) throw error;\n if (options.failOpen === false) throw error;\n return { enforce: false, mode: effectiveMode };\n }\n };\n\n return createMiddleware({\n name: \"SilmarilDeepAgentsMiddleware\",\n wrapModelCall: async (request, handler) => {\n const conversationId = nativeThreadId(request.runtime, undefined, undefined, ensureConfig());\n const messages = [];\n for (const message of request.messages) {\n let blocked = false;\n if (remoteNotification(message)) {\n const key = await notificationKey(message, conversationId, effectiveMode);\n const cached = key === undefined ? undefined : notificationChecks.get(key);\n if (cached !== undefined) {\n blocked = cached;\n notificationChecks.delete(key!); notificationChecks.set(key!, cached);\n } else {\n const decision = await classify(textOf(message), HookLabel.TOOL_RESPONSE, conversationId, \"async_subagent\");\n blocked = decision.enforce;\n if (key !== undefined && decision.cacheable) {\n notificationChecks.set(key, blocked);\n while (notificationChecks.size > 1024) notificationChecks.delete(notificationChecks.keys().next().value!);\n }\n }\n }\n messages.push(blocked\n ? new HumanMessage({ content: SAFE_TOOL_MESSAGE, ...(message.id === undefined ? {} : { id: message.id }) })\n : message);\n }\n request = { ...request, messages };\n const history = request.state.messages;\n let lastUserIndex = -1;\n for (let i = history.length - 1; i >= 0; i--) {\n if (HumanMessage.isInstance(history[i])) {\n lastUserIndex = i;\n break;\n }\n }\n const blockedCount = history.slice(lastUserIndex + 1).filter(\n (message) => ToolMessage.isInstance(message) && message.content === SAFE_TOOL_MESSAGE\n && message.additional_kwargs?.silmarilBlocked === BLOCKED_TOOL_MARKER,\n ).length;\n const latestUser = [...request.messages].reverse().find(HumanMessage.isInstance);\n const inputDecision = latestUser\n ? await classify(textOf(latestUser), HookLabel.USER_INPUT, conversationId)\n : undefined;\n if (inputDecision?.enforce) return new AIMessage(SAFE_OUTPUT_MESSAGE);\n const capMode = effectiveMode ?? inputDecision?.mode ?? \"block\";\n // Only genuine prior Block markers count, and the terminal cap requires current effective Block mode.\n if (blockedCount >= maxBlockedAttempts && capMode === \"block\") {\n return new AIMessage(SAFE_FINAL_MESSAGE);\n }\n const response = await handler(request);\n if (response instanceof Command && (await classify(textOfStructuredValue(response.update), HookLabel.LLM_OUTPUT, conversationId)).enforce) {\n return new AIMessage(SAFE_OUTPUT_MESSAGE);\n }\n if (AIMessage.isInstance(response) && (await classify(textOf(response), HookLabel.LLM_OUTPUT, conversationId)).enforce) {\n return new AIMessage(SAFE_OUTPUT_MESSAGE);\n }\n return response;\n },\n wrapToolCall: async (request, handler) => {\n const conversationId = nativeThreadId(request.runtime, undefined, undefined, ensureConfig());\n const safe = () => {\n const message = new ToolMessage({\n content: SAFE_TOOL_MESSAGE,\n tool_call_id: request.toolCall.id ?? \"\",\n name: request.toolCall.name,\n additional_kwargs: { silmarilBlocked: BLOCKED_TOOL_MARKER },\n });\n issuedBlockedMessages.add(message);\n return message;\n };\n if ((await classify(JSON.stringify(request.toolCall.args ?? {}), HookLabel.TOOL_CALL, conversationId, request.toolCall.name)).enforce) {\n return safe();\n }\n const result = await handler(request);\n let resultText: string;\n try {\n resultText = ToolMessage.isInstance(result) ? textOf(result)\n : result instanceof Command ? textOfStructuredValue(result.update) : String(result);\n } catch {\n // Content cannot be inspected, but the backend still resolves the\n // enforcement mode. Observation modes retain the original result.\n const decision = await classify(\"[uninspectable tool result]\", HookLabel.TOOL_RESPONSE, conversationId, request.toolCall.name);\n return decision.mode === \"block\" ? safe() : stripAllowedMarker(result);\n }\n if ((await classify(resultText, HookLabel.TOOL_RESPONSE, conversationId, request.toolCall.name)).enforce) {\n if ([\"start_async_task\", \"check_async_task\", \"update_async_task\", \"cancel_async_task\", \"list_async_tasks\"].includes(request.toolCall.name)\n && result instanceof Command && result.update && !Array.isArray(result.update)\n && \"asyncTasks\" in result.update) {\n return new Command({ update: { messages: [safe()], asyncTasks: result.update.asyncTasks } });\n }\n return safe();\n }\n return stripAllowedMarker(result);\n },\n });\n}\n\nexport interface ProtectedCompiledSubagentOptions extends Omit<CreateAgentParams, \"middleware\"> {\n name: string;\n description: string;\n middleware?: CreateAgentParams[\"middleware\"];\n silmaril?: DeepAgentsMiddlewareOptions;\n}\n\n/** Compile a subagent with Silmaril middleware and register that exact graph. */\nexport function createProtectedCompiledSubagent(firewall: Firewall, options: ProtectedCompiledSubagentOptions): CompiledSubAgent {\n rejectConversationOptions(options);\n const { name, description, silmaril, middleware = [], ...agentOptions } = options;\n const runnable = createAgent({\n ...agentOptions,\n middleware: [...middleware, createDeepAgentsMiddleware(firewall, silmaril)] as const,\n });\n protectedCompiledGraphs.set(runnable, firewall);\n return { name, description, runnable };\n}\n\nexport interface ProtectedDeepAgentOptions extends Omit<NonNullable<Parameters<typeof createDeepAgent>[0]>, \"subagents\" | \"middleware\"> {\n subagents?: readonly AnySubAgent[];\n /** Only pass specs returned by createProtectedCompiledSubagent for this client. */\n protectedCompiledSubagents?: readonly CompiledSubAgent[];\n middleware?: NonNullable<Parameters<typeof createDeepAgent>[0]>[\"middleware\"];\n silmaril?: DeepAgentsMiddlewareOptions;\n}\n\n/** Protect this graph and inline children; support native remote subagents.\n * Deploy each remote graph with this constructor too. Parent checks cover\n * delegation/results; the child's middleware enforces its internal actions.\n */\nexport function createProtectedDeepAgent(firewall: Firewall, options: ProtectedDeepAgentOptions = {}) {\n rejectConversationOptions(options);\n const { silmaril, subagents = [], protectedCompiledSubagents = [], middleware = [], ...agentOptions } = options;\n const protectedSubagents = subagents.map((subagent) => {\n if (\"runnable\" in subagent) {\n throw new Error(\"Compiled subagents must use createProtectedCompiledSubagent\");\n }\n if (\"graphId\" in subagent) return { ...subagent };\n return { ...subagent, middleware: [...(subagent.middleware ?? []), createDeepAgentsMiddleware(firewall, silmaril)] };\n });\n if (!protectedSubagents.some((subagent) => subagent.name === GENERAL_PURPOSE_SUBAGENT.name)) {\n protectedSubagents.unshift({ ...GENERAL_PURPOSE_SUBAGENT, middleware: [createDeepAgentsMiddleware(firewall, silmaril)] });\n }\n for (const spec of protectedCompiledSubagents) {\n if (!spec.runnable || protectedCompiledGraphs.get(spec.runnable) !== firewall) {\n throw new Error(\"Compiled subagents must be built with createProtectedCompiledSubagent for this Firewall client\");\n }\n }\n return createDeepAgent({\n ...agentOptions,\n middleware: [...middleware, createDeepAgentsMiddleware(firewall, silmaril)],\n subagents: [...protectedSubagents, ...protectedCompiledSubagents],\n });\n}\n","// Copyright (c) 2024-2025 Silmaril Security Inc. All rights reserved.\n// PROPRIETARY AND CONFIDENTIAL\n\nimport type { HookLabel } from \"./hooks.js\";\nimport type { BlockResult, ReviewLevel } from \"./types.js\";\n\nconst MAX_PROMPT_DISPLAY_LEN = 100;\n\nexport interface MalformedInputDetails {\n field?: string;\n inputIndex?: number;\n charOffset?: number;\n malformedToken?: string;\n codePoint?: string;\n reason?: string;\n}\n\nexport class FirewallBlockedException extends Error {\n readonly score: number;\n readonly threshold: number;\n readonly promptText: string;\n readonly runId: string | undefined;\n readonly hook: HookLabel | undefined;\n readonly toolName: string | undefined;\n readonly toolCallId: string | undefined;\n readonly result: BlockResult | undefined;\n\n constructor(params: {\n score: number;\n threshold: number;\n promptText: string;\n runId?: string;\n hook?: HookLabel;\n toolName?: string;\n toolCallId?: string;\n result?: BlockResult;\n }) {\n super(FirewallBlockedException.formatMessage(params));\n this.name = \"FirewallBlockedException\";\n this.score = params.score;\n this.threshold = params.threshold;\n this.promptText = params.promptText;\n this.runId = params.runId;\n this.hook = params.hook;\n this.toolName = params.toolName;\n this.toolCallId = params.toolCallId;\n this.result = params.result;\n Object.setPrototypeOf(this, FirewallBlockedException.prototype);\n }\n\n private static formatMessage(params: {\n score: number;\n threshold: number;\n promptText: string;\n result?: BlockResult;\n }): string {\n const truncated =\n params.promptText.length > MAX_PROMPT_DISPLAY_LEN\n ? `${params.promptText.slice(0, MAX_PROMPT_DISPLAY_LEN)}...`\n : params.promptText;\n if (\n params.result?.prediction !== \"MALICIOUS\" &&\n params.result?.governance?.action === \"block\"\n ) {\n return `Request blocked by Silmaril Firewall governance policy: '${truncated}'`;\n }\n return (\n `Request blocked by Silmaril Firewall ` +\n `(score=${params.score.toFixed(4)}, threshold=${params.threshold.toFixed(4)}): ` +\n `'${truncated}'`\n );\n }\n}\n\n/** @deprecated Use FirewallBlockedException instead. */\nexport const PromptBlockedException = FirewallBlockedException;\n/** @deprecated Use FirewallBlockedException instead. */\nexport type PromptBlockedException = FirewallBlockedException;\n\nconst REVIEW_COMPATIBILITY_ERROR_BRAND = Symbol.for(\n \"@silmaril-security/sdk/ReviewCompatibilityError\",\n);\n\nexport class ReviewCompatibilityError extends Error {\n readonly requestedReview: ReviewLevel;\n readonly acknowledgedReview: unknown;\n\n constructor(requestedReview: ReviewLevel, acknowledgedReview: unknown) {\n const detail = acknowledgedReview === undefined\n ? \"the response omitted its acknowledgement\"\n : \"the response acknowledgement did not match\";\n super(`Silmaril review compatibility error: ${detail} for requested ${requestedReview} review`);\n this.name = \"ReviewCompatibilityError\";\n this.requestedReview = requestedReview;\n this.acknowledgedReview = acknowledgedReview;\n Object.defineProperty(this, REVIEW_COMPATIBILITY_ERROR_BRAND, {\n value: true,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n Object.setPrototypeOf(this, ReviewCompatibilityError.prototype);\n }\n}\n\nexport function isReviewCompatibilityError(error: unknown): error is ReviewCompatibilityError {\n if ((typeof error !== \"object\" && typeof error !== \"function\") || error === null) {\n return false;\n }\n try {\n return Object.getOwnPropertyDescriptor(\n error,\n REVIEW_COMPATIBILITY_ERROR_BRAND,\n )?.value === true;\n } catch {\n return false;\n }\n}\n\nexport class SilmarilApiError extends Error {\n readonly status: number;\n readonly statusText: string;\n readonly body: string;\n readonly details: MalformedInputDetails | undefined;\n readonly error: string | undefined;\n readonly apiMessage: string | undefined;\n\n constructor(params: {\n status: number;\n statusText: string;\n body: string;\n details?: MalformedInputDetails;\n error?: string;\n apiMessage?: string;\n }) {\n const statusText = params.statusText ? ` ${params.statusText}` : \"\";\n super(`Silmaril API error ${params.status}${statusText}`);\n this.name = \"SilmarilApiError\";\n this.status = params.status;\n this.statusText = params.statusText;\n this.body = params.body;\n const parsed = parseErrorBody(params.body);\n this.details = params.details ?? parsed.details;\n this.error = params.error ?? parsed.error;\n this.apiMessage = params.apiMessage ?? parsed.apiMessage;\n Object.setPrototypeOf(this, SilmarilApiError.prototype);\n }\n}\n\nfunction parseErrorBody(body: string): {\n details: MalformedInputDetails | undefined;\n error: string | undefined;\n apiMessage: string | undefined;\n} {\n try {\n const parsed = JSON.parse(body) as unknown;\n if (!parsed || typeof parsed !== \"object\") {\n return { details: undefined, error: undefined, apiMessage: undefined };\n }\n const data = parsed as Record<string, unknown>;\n return {\n details:\n data.details && typeof data.details === \"object\"\n ? (data.details as MalformedInputDetails)\n : undefined,\n error: typeof data.error === \"string\" ? data.error : undefined,\n apiMessage: typeof data.message === \"string\" ? data.message : undefined,\n };\n } catch {\n return { details: undefined, error: undefined, apiMessage: undefined };\n }\n}\n","// Copyright (c) 2024-2025 Silmaril Security Inc. All rights reserved.\n// PROPRIETARY AND CONFIDENTIAL\n\nexport const HookLabel = {\n USER_INPUT: \"user_input\",\n SYSTEM_PROMPT: \"system_prompt\",\n TOOL_CALL: \"tool_call\",\n TOOL_RESPONSE: \"tool_response\",\n LLM_OUTPUT: \"llm_output\",\n UNKNOWN: \"unknown\",\n} as const;\n\nexport type HookLabel = (typeof HookLabel)[keyof typeof HookLabel];\n\nexport const FirewallHook = {\n LLM_START: \"on_llm_start\",\n CHAT_MODEL_START: \"on_chat_model_start\",\n TOOL_START: \"on_tool_start\",\n RETRIEVER_START: \"on_retriever_start\",\n LLM_END: \"on_llm_end\",\n TOOL_END: \"on_tool_end\",\n RETRIEVER_END: \"on_retriever_end\",\n} as const;\n\nexport type FirewallHook = (typeof FirewallHook)[keyof typeof FirewallHook];\n\nexport const DEFAULT_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n FirewallHook.LLM_START,\n FirewallHook.CHAT_MODEL_START,\n FirewallHook.TOOL_START,\n FirewallHook.TOOL_END,\n]);\n\nexport const INPUT_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n FirewallHook.LLM_START,\n FirewallHook.CHAT_MODEL_START,\n FirewallHook.TOOL_START,\n FirewallHook.RETRIEVER_START,\n]);\n\nexport const OUTPUT_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n FirewallHook.LLM_END,\n FirewallHook.TOOL_END,\n FirewallHook.RETRIEVER_END,\n]);\n\nexport const ALL_HOOKS: ReadonlySet<FirewallHook> = new Set<FirewallHook>([\n ...INPUT_HOOKS,\n ...OUTPUT_HOOKS,\n]);\n\nexport const FIREWALL_HOOK_TO_LABEL: Readonly<Record<FirewallHook, HookLabel>> = {\n [FirewallHook.CHAT_MODEL_START]: HookLabel.USER_INPUT,\n [FirewallHook.LLM_START]: HookLabel.USER_INPUT,\n [FirewallHook.TOOL_START]: HookLabel.TOOL_CALL,\n [FirewallHook.TOOL_END]: HookLabel.TOOL_RESPONSE,\n [FirewallHook.RETRIEVER_START]: HookLabel.TOOL_CALL,\n [FirewallHook.RETRIEVER_END]: HookLabel.TOOL_RESPONSE,\n [FirewallHook.LLM_END]: HookLabel.LLM_OUTPUT,\n};\n\nconst FIREWALL_HOOK_VALUES: ReadonlySet<string> = new Set(Object.values(FirewallHook));\n\nexport function resolveHooks(\n hooks: Iterable<FirewallHook | string> | undefined,\n): ReadonlySet<FirewallHook> {\n if (hooks === undefined) {\n return DEFAULT_HOOKS;\n }\n const resolved = new Set<FirewallHook>();\n for (const h of hooks) {\n if (!FIREWALL_HOOK_VALUES.has(h)) {\n throw new Error(`Invalid FirewallHook value: ${String(h)}`);\n }\n resolved.add(h as FirewallHook);\n }\n return resolved;\n}\n\nexport function prependHook(text: string, hook: HookLabel | string | undefined | null): string {\n if (hook === undefined || hook === null) {\n return text;\n }\n if (hook === HookLabel.UNKNOWN) {\n return text;\n }\n return `[HOOK:${hook}] ${text}`;\n}\n\nexport function prependToolName(text: string, toolName: string | undefined | null): string {\n if (toolName === undefined || toolName === null) {\n return text;\n }\n return `[TOOL:${toolName}] ${text}`;\n}\n","import type { FirewallMode } from \"./types.js\";\n\n/** Validate JavaScript/configuration inputs before any fail-open adapter path. */\nexport function validateMode(value: unknown): FirewallMode | undefined {\n if (value === undefined || value === \"shadow\" || value === \"warn\" || value === \"block\") {\n return value;\n }\n throw new Error(\"Firewall: mode must be shadow, warn, or block\");\n}\n","// Copyright (c) 2026 Silmaril Security Inc. All rights reserved.\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? value as Record<string, unknown> : undefined;\n}\n\nexport function validThreadId(value: unknown): string | undefined {\n return typeof value === \"string\" && value.trim().length > 0 ? value : undefined;\n}\n\nconst NO_THREAD_IDS: readonly string[] = Object.freeze([]);\n\nfunction threadIds(first?: string, second?: string): readonly string[] {\n if (first === undefined) return second === undefined ? NO_THREAD_IDS : Object.freeze([second]);\n return Object.freeze(second === undefined || second === first ? [first] : [first, second]);\n}\n\n/** Native config is authoritative, including an explicitly invalid/empty ID. */\nexport function nativeThreadId(runtime?: unknown, metadata?: unknown, inherited?: string, currentConfig?: unknown): string | undefined {\n const explicit = record(record(runtime)?.configurable);\n const current = record(record(currentConfig)?.configurable);\n for (const candidate of [explicit, current, record(metadata)]) {\n if (candidate && Object.prototype.hasOwnProperty.call(candidate, \"thread_id\")) {\n return validThreadId(candidate.thread_id);\n }\n }\n return inherited;\n}\n\nexport function rejectConversationOptions(options: object): void {\n if (\"conversationId\" in options || \"conversation_id\" in options) {\n throw new TypeError(\"conversationId/conversation_id was removed. Pass the native configurable.thread_id when invoking the agent or runnable instead.\");\n }\n}\n\ninterface RunIdentity {\n threadId: string | undefined;\n /** At most two ordinary candidates deeper children must not re-accept. */\n untrustedThreadIds: readonly string[];\n parentRunId: string | undefined;\n graphProven: boolean;\n}\n\n/** State belongs to callback runs, never to a reusable agent or current user. */\nexport class RunThreadIdentity {\n private readonly runs = new Map<string, RunIdentity>();\n private readonly children = new Map<string, Set<string>>();\n\n constructor(\n private readonly boundIdentity?: { threadId: string | undefined },\n private readonly currentConfig: () => unknown = () => undefined,\n ) {}\n\n start(runId: string, parentRunId?: string, metadata?: unknown): string[] {\n const discarded = this.finish(runId);\n if (this.runs.size >= 4096) {\n const oldestRoot = [...this.runs].find(([, run]) => run.parentRunId === undefined || !this.runs.has(run.parentRunId))?.[0] ?? this.runs.keys().next().value;\n if (oldestRoot !== undefined) discarded.push(...this.finish(oldestRoot));\n }\n const parent = parentRunId === undefined ? undefined : this.runs.get(parentRunId);\n const inherited = parent?.threadId;\n const exposed = record(metadata);\n const hasExposedThread = exposed !== undefined\n && Object.prototype.hasOwnProperty.call(exposed, \"thread_id\");\n const candidate = hasExposedThread ? validThreadId(exposed.thread_id) : undefined;\n // Ordinary callbacks may see a parent's ambient config while a child has a\n // hidden per-call override. Only graph-tagged metadata proves that context.\n let threadId: string | undefined;\n let untrustedThreadIds: readonly string[];\n let graphProven: boolean;\n if (this.boundIdentity && parent === undefined) {\n threadId = this.boundIdentity.threadId;\n untrustedThreadIds = threadIds(threadId, candidate);\n graphProven = false;\n } else if (exposed && (\n typeof exposed.langgraph_node === \"string\"\n || typeof exposed.langgraph_step === \"number\"\n )) {\n threadId = nativeThreadId(undefined, exposed, inherited, this.currentConfig());\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = true;\n } else if (hasExposedThread) {\n if (candidate === undefined) {\n threadId = undefined;\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = false;\n } else if (parent?.graphProven && candidate === inherited) {\n threadId = inherited;\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = true;\n } else if (parent && (\n candidate === inherited || parent.untrustedThreadIds.includes(candidate)\n )) {\n threadId = undefined;\n untrustedThreadIds = parent.untrustedThreadIds;\n graphProven = false;\n } else {\n threadId = candidate;\n untrustedThreadIds = threadIds(candidate);\n graphProven = false;\n }\n } else if (parent?.graphProven) {\n threadId = inherited;\n untrustedThreadIds = NO_THREAD_IDS;\n graphProven = true;\n } else {\n threadId = undefined;\n untrustedThreadIds = parent?.untrustedThreadIds ?? NO_THREAD_IDS;\n graphProven = false;\n }\n this.runs.set(runId, { threadId, untrustedThreadIds, parentRunId, graphProven });\n if (parentRunId !== undefined && parentRunId !== runId) {\n const children = this.children.get(parentRunId) ?? new Set<string>();\n children.add(runId);\n this.children.set(parentRunId, children);\n }\n return discarded;\n }\n\n get(runId: string): string | undefined {\n const run = this.runs.get(runId);\n return run ? run.threadId : this.boundIdentity?.threadId;\n }\n\n finish(runId: string): string[] {\n const pending = [runId];\n const seen = new Set<string>();\n while (pending.length) {\n const id = pending.pop()!;\n if (seen.has(id)) continue;\n seen.add(id);\n pending.push(...this.children.get(id) ?? []);\n this.children.delete(id);\n const parent = this.runs.get(id)?.parentRunId;\n this.runs.delete(id);\n if (parent !== undefined) {\n const siblings = this.children.get(parent);\n siblings?.delete(id);\n if (siblings?.size === 0) this.children.delete(parent);\n }\n }\n return [...seen];\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,sBAAqD;AACrD,uBAA6B;AAC7B,uBAAwB;AACxB,wBAAmG;AACnG,uBAAsE;;;ACwEtE,IAAM,mCAAmC,uBAAO;AAAA,EA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0BAAwB,IAAI,UAAU,QAAQ;AAC9C,SAAO,EAAE,MAAM,aAAa,SAAS;AACvC;AAcO,SAAS,yBAAyB,UAAoB,UAAqC,CAAC,GAAG;AACpG,4BAA0B,OAAO;AACjC,QAAM,EAAE,UAAU,YAAY,CAAC,GAAG,6BAA6B,CAAC,GAAG,aAAa,CAAC,GAAG,GAAG,aAAa,IAAI;AACxG,QAAM,qBAAqB,UAAU,IAAI,CAAC,aAAa;AACrD,QAAI,cAAc,UAAU;AAC1B,YAAM,IAAI,MAAM,6DAA6D;AAAA,IAC/E;AACA,QAAI,aAAa,SAAU,QAAO,EAAE,GAAG,SAAS;AAChD,WAAO,EAAE,GAAG,UAAU,YAAY,CAAC,GAAI,SAAS,cAAc,CAAC,GAAI,2BAA2B,UAAU,QAAQ,CAAC,EAAE;AAAA,EACrH,CAAC;AACD,MAAI,CAAC,mBAAmB,KAAK,CAAC,aAAa,SAAS,SAAS,2CAAyB,IAAI,GAAG;AAC3F,uBAAmB,QAAQ,EAAE,GAAG,4CAA0B,YAAY,CAAC,2BAA2B,UAAU,QAAQ,CAAC,EAAE,CAAC;AAAA,EAC1H;AACA,aAAW,QAAQ,4BAA4B;AAC7C,QAAI,CAAC,KAAK,YAAY,wBAAwB,IAAI,KAAK,QAAQ,MAAM,UAAU;AAC7E,YAAM,IAAI,MAAM,gGAAgG;AAAA,IAClH;AAAA,EACF;AACA,aAAO,mCAAgB;AAAA,IACrB,GAAG;AAAA,IACH,YAAY,CAAC,GAAG,YAAY,2BAA2B,UAAU,QAAQ,CAAC;AAAA,IAC1E,WAAW,CAAC,GAAG,oBAAoB,GAAG,0BAA0B;AAAA,EAClE,CAAC;AACH;","names":["record"]}
@@ -39,7 +39,10 @@ interface ProtectedDeepAgentOptions extends Omit<NonNullable<Parameters<typeof c
39
39
  middleware?: NonNullable<Parameters<typeof createDeepAgent>[0]>["middleware"];
40
40
  silmaril?: DeepAgentsMiddlewareOptions;
41
41
  }
42
- /** Protect root, default general-purpose, and declarative subagents. */
42
+ /** Protect this graph and inline children; support native remote subagents.
43
+ * Deploy each remote graph with this constructor too. Parent checks cover
44
+ * delegation/results; the child's middleware enforces its internal actions.
45
+ */
43
46
  declare function createProtectedDeepAgent(firewall: Firewall, options?: ProtectedDeepAgentOptions): deepagents.DeepAgent<deepagents.DeepAgentTypeConfig<langchain.ResponseFormatUndefined, _langchain_core_utils_types.InteropZodObject | _langchain_langgraph.AnyStateSchema | undefined, _langchain_core_utils_types.InteropZodObject, readonly [langchain.AgentMiddleware<_langchain_langgraph.StateSchema<{
44
47
  skillsMetadata: zod.ZodOptional<zod.ZodNullable<zod.ZodArray<zod.ZodObject<{
45
48
  name: zod.ZodString;
@@ -51,11 +54,13 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
51
54
  allowedTools: zod.ZodOptional<zod.ZodArray<zod.ZodString>>;
52
55
  module: zod.ZodOptional<zod.ZodString>;
53
56
  }, zod_v4_core.$strip>>>>;
57
+ pinnedSkills: _langchain_langgraph.ReducedValue<string[], string[] | undefined>;
54
58
  files: _langchain_langgraph.ReducedValue<{
55
59
  [x: string]: deepagents.FileData;
56
60
  } | undefined, {
57
61
  [x: string]: deepagents.FileData | null;
58
62
  } | undefined>;
63
+ _skillToolsDisclosed: _langchain_langgraph.ReducedValue<Record<string, string> | undefined, Record<string, string> | undefined>;
59
64
  }>, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>, langchain.AgentMiddleware<_langchain_langgraph.StateSchema<{
60
65
  files: _langchain_langgraph.ReducedValue<{
61
66
  [x: string]: deepagents.FileData;
@@ -114,19 +119,19 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
114
119
  offset: number;
115
120
  limit: number;
116
121
  }, unknown, ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | {
117
- type: string;
118
- text: string;
119
- }[] | {
120
122
  type: string;
121
123
  mimeType: string;
122
124
  data: string;
125
+ }[] | {
126
+ type: string;
127
+ text: string;
123
128
  }[], unknown, "read_file"> | langchain.DynamicStructuredTool<zod.ZodPreprocess<zod.ZodObject<{
124
129
  file_path: zod.ZodString;
125
130
  content: zod.ZodString;
126
131
  }, zod_v4_core.$strip>, unknown>, {
127
132
  file_path: string;
128
133
  content: string;
129
- }, unknown, string | ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
134
+ }, unknown, ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
130
135
  files: Record<string, deepagents.FileData>;
131
136
  messages: ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>[];
132
137
  }, string>, unknown, "write_file"> | langchain.DynamicStructuredTool<zod.ZodPreprocess<zod.ZodObject<{
@@ -139,7 +144,7 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
139
144
  old_string: string;
140
145
  new_string: string;
141
146
  replace_all: boolean;
142
- }, unknown, string | ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
147
+ }, unknown, ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
143
148
  files: Record<string, deepagents.FileData>;
144
149
  messages: ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>[];
145
150
  }, string>, unknown, "edit_file"> | langchain.DynamicStructuredTool<zod.ZodPreprocess<zod.ZodObject<{
@@ -162,10 +167,20 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
162
167
  _summarizationSessionId: zod.ZodOptional<zod.ZodString>;
163
168
  _summarizationEvent: zod.ZodOptional<zod.ZodObject<{
164
169
  cutoffIndex: zod.ZodNumber;
165
- summaryMessage: zod.ZodCustom<HumanMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>, HumanMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>>;
170
+ summaryMessage: zod.ZodInstanceOf<HumanMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>>;
166
171
  filePath: zod.ZodNullable<zod.ZodString>;
167
172
  }, zod_v4_core.$strip>>;
168
173
  }, zod_v4_core.$strip>, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>, langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>, ...langchain.AgentMiddleware<any, any, any, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly (() => _langchain_langgraph.StreamTransformer<any>)[]>[], langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>], readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly (CompiledSubAgent<langchain.ReactAgent<any> | _langchain_core_runnables.Runnable<any, any, _langchain_core_runnables.RunnableConfig<Record<string, any>>>> | {
174
+ name: string;
175
+ description: string;
176
+ graphId: string;
177
+ url?: string;
178
+ headers?: Record<string, string>;
179
+ webhook?: string;
180
+ notifyParent?: boolean;
181
+ updateStrategy?: "interrupt" | "enqueue";
182
+ mode?: "isolated" | "fork";
183
+ } | {
169
184
  middleware: (langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []> | langchain.AgentMiddleware<any, any, any, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly (() => _langchain_langgraph.StreamTransformer<any>)[]>)[];
170
185
  name: string;
171
186
  description: string;
@@ -39,7 +39,10 @@ interface ProtectedDeepAgentOptions extends Omit<NonNullable<Parameters<typeof c
39
39
  middleware?: NonNullable<Parameters<typeof createDeepAgent>[0]>["middleware"];
40
40
  silmaril?: DeepAgentsMiddlewareOptions;
41
41
  }
42
- /** Protect root, default general-purpose, and declarative subagents. */
42
+ /** Protect this graph and inline children; support native remote subagents.
43
+ * Deploy each remote graph with this constructor too. Parent checks cover
44
+ * delegation/results; the child's middleware enforces its internal actions.
45
+ */
43
46
  declare function createProtectedDeepAgent(firewall: Firewall, options?: ProtectedDeepAgentOptions): deepagents.DeepAgent<deepagents.DeepAgentTypeConfig<langchain.ResponseFormatUndefined, _langchain_core_utils_types.InteropZodObject | _langchain_langgraph.AnyStateSchema | undefined, _langchain_core_utils_types.InteropZodObject, readonly [langchain.AgentMiddleware<_langchain_langgraph.StateSchema<{
44
47
  skillsMetadata: zod.ZodOptional<zod.ZodNullable<zod.ZodArray<zod.ZodObject<{
45
48
  name: zod.ZodString;
@@ -51,11 +54,13 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
51
54
  allowedTools: zod.ZodOptional<zod.ZodArray<zod.ZodString>>;
52
55
  module: zod.ZodOptional<zod.ZodString>;
53
56
  }, zod_v4_core.$strip>>>>;
57
+ pinnedSkills: _langchain_langgraph.ReducedValue<string[], string[] | undefined>;
54
58
  files: _langchain_langgraph.ReducedValue<{
55
59
  [x: string]: deepagents.FileData;
56
60
  } | undefined, {
57
61
  [x: string]: deepagents.FileData | null;
58
62
  } | undefined>;
63
+ _skillToolsDisclosed: _langchain_langgraph.ReducedValue<Record<string, string> | undefined, Record<string, string> | undefined>;
59
64
  }>, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>, langchain.AgentMiddleware<_langchain_langgraph.StateSchema<{
60
65
  files: _langchain_langgraph.ReducedValue<{
61
66
  [x: string]: deepagents.FileData;
@@ -114,19 +119,19 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
114
119
  offset: number;
115
120
  limit: number;
116
121
  }, unknown, ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | {
117
- type: string;
118
- text: string;
119
- }[] | {
120
122
  type: string;
121
123
  mimeType: string;
122
124
  data: string;
125
+ }[] | {
126
+ type: string;
127
+ text: string;
123
128
  }[], unknown, "read_file"> | langchain.DynamicStructuredTool<zod.ZodPreprocess<zod.ZodObject<{
124
129
  file_path: zod.ZodString;
125
130
  content: zod.ZodString;
126
131
  }, zod_v4_core.$strip>, unknown>, {
127
132
  file_path: string;
128
133
  content: string;
129
- }, unknown, string | ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
134
+ }, unknown, ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
130
135
  files: Record<string, deepagents.FileData>;
131
136
  messages: ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>[];
132
137
  }, string>, unknown, "write_file"> | langchain.DynamicStructuredTool<zod.ZodPreprocess<zod.ZodObject<{
@@ -139,7 +144,7 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
139
144
  old_string: string;
140
145
  new_string: string;
141
146
  replace_all: boolean;
142
- }, unknown, string | ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
147
+ }, unknown, ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>> | Command<unknown, {
143
148
  files: Record<string, deepagents.FileData>;
144
149
  messages: ToolMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>[];
145
150
  }, string>, unknown, "edit_file"> | langchain.DynamicStructuredTool<zod.ZodPreprocess<zod.ZodObject<{
@@ -162,10 +167,20 @@ declare function createProtectedDeepAgent(firewall: Firewall, options?: Protecte
162
167
  _summarizationSessionId: zod.ZodOptional<zod.ZodString>;
163
168
  _summarizationEvent: zod.ZodOptional<zod.ZodObject<{
164
169
  cutoffIndex: zod.ZodNumber;
165
- summaryMessage: zod.ZodCustom<HumanMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>, HumanMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>>;
170
+ summaryMessage: zod.ZodInstanceOf<HumanMessage<_langchain_core_messages.MessageStructure<_langchain_core_messages.MessageToolSet>>>;
166
171
  filePath: zod.ZodNullable<zod.ZodString>;
167
172
  }, zod_v4_core.$strip>>;
168
173
  }, zod_v4_core.$strip>, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>, langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>, ...langchain.AgentMiddleware<any, any, any, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly (() => _langchain_langgraph.StreamTransformer<any>)[]>[], langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []>], readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly (CompiledSubAgent<langchain.ReactAgent<any> | _langchain_core_runnables.Runnable<any, any, _langchain_core_runnables.RunnableConfig<Record<string, any>>>> | {
174
+ name: string;
175
+ description: string;
176
+ graphId: string;
177
+ url?: string;
178
+ headers?: Record<string, string>;
179
+ webhook?: string;
180
+ notifyParent?: boolean;
181
+ updateStrategy?: "interrupt" | "enqueue";
182
+ mode?: "isolated" | "fork";
183
+ } | {
169
184
  middleware: (langchain.AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly []> | langchain.AgentMiddleware<any, any, any, readonly (_langchain_core_tools.ClientTool | _langchain_core_tools.ServerTool)[], readonly (() => _langchain_langgraph.StreamTransformer<any>)[]>)[];
170
185
  name: string;
171
186
  description: string;