langchain 1.2.26 → 1.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/agents/ReactAgent.cjs.map +1 -1
  3. package/dist/agents/ReactAgent.d.cts +2 -2
  4. package/dist/agents/ReactAgent.d.ts +2 -2
  5. package/dist/agents/ReactAgent.js.map +1 -1
  6. package/dist/agents/index.d.cts +1 -1
  7. package/dist/agents/index.d.ts +1 -1
  8. package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
  9. package/dist/agents/middleware/llmToolSelector.d.cts +37 -2
  10. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  11. package/dist/agents/middleware/llmToolSelector.d.ts +37 -2
  12. package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
  13. package/dist/agents/middleware/llmToolSelector.js.map +1 -1
  14. package/dist/agents/middleware/modelFallback.cjs.map +1 -1
  15. package/dist/agents/middleware/modelFallback.d.cts +2 -1
  16. package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
  17. package/dist/agents/middleware/modelFallback.d.ts +2 -1
  18. package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
  19. package/dist/agents/middleware/modelFallback.js.map +1 -1
  20. package/dist/agents/middleware/modelRetry.cjs.map +1 -1
  21. package/dist/agents/middleware/modelRetry.d.cts +43 -1
  22. package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
  23. package/dist/agents/middleware/modelRetry.d.ts +43 -1
  24. package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
  25. package/dist/agents/middleware/modelRetry.js.map +1 -1
  26. package/dist/agents/middleware/pii.cjs +7 -4
  27. package/dist/agents/middleware/pii.cjs.map +1 -1
  28. package/dist/agents/middleware/pii.d.cts +28 -2
  29. package/dist/agents/middleware/pii.d.cts.map +1 -1
  30. package/dist/agents/middleware/pii.d.ts +28 -2
  31. package/dist/agents/middleware/pii.d.ts.map +1 -1
  32. package/dist/agents/middleware/pii.js +7 -4
  33. package/dist/agents/middleware/pii.js.map +1 -1
  34. package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
  35. package/dist/agents/middleware/piiRedaction.d.cts +15 -2
  36. package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
  37. package/dist/agents/middleware/piiRedaction.d.ts +15 -2
  38. package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
  39. package/dist/agents/middleware/piiRedaction.js.map +1 -1
  40. package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
  41. package/dist/agents/middleware/toolEmulator.d.cts +2 -2
  42. package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
  43. package/dist/agents/middleware/toolEmulator.d.ts +2 -2
  44. package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
  45. package/dist/agents/middleware/toolEmulator.js.map +1 -1
  46. package/dist/agents/middleware/toolRetry.cjs.map +1 -1
  47. package/dist/agents/middleware/toolRetry.d.cts +55 -1
  48. package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
  49. package/dist/agents/middleware/toolRetry.d.ts +55 -1
  50. package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
  51. package/dist/agents/middleware/toolRetry.js.map +1 -1
  52. package/dist/agents/middleware/types.cjs.map +1 -1
  53. package/dist/agents/middleware/types.d.cts +22 -18
  54. package/dist/agents/middleware/types.d.cts.map +1 -1
  55. package/dist/agents/middleware/types.d.ts +22 -18
  56. package/dist/agents/middleware/types.d.ts.map +1 -1
  57. package/dist/agents/middleware/types.js.map +1 -1
  58. package/dist/agents/types.d.cts +3 -3
  59. package/dist/agents/types.d.cts.map +1 -1
  60. package/dist/agents/types.d.ts +3 -3
  61. package/dist/agents/types.d.ts.map +1 -1
  62. package/dist/index.d.cts +2 -2
  63. package/dist/index.d.ts +2 -2
  64. package/package.json +5 -5
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.cjs","names":["createMiddleware","initChatModel"],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAOA,oCAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAMC,4CAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;MACD,CAAC;aACK,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;;;;;AAQZ,UAAM;;;EAGX,CAAC"}
1
+ {"version":3,"file":"modelFallback.cjs","names":["createMiddleware","initChatModel"],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n) {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,wBAId,GAAG,gBACH;AACA,QAAOA,oCAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAMC,4CAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;MACD,CAAC;aACK,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;;;;;AAQZ,UAAM;;;EAGX,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { AgentMiddleware } from "./types.cjs";
2
2
  import { LanguageModelLike } from "@langchain/core/language_models/base";
3
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
3
4
 
4
5
  //#region src/agents/middleware/modelFallback.d.ts
5
6
  /**
@@ -38,7 +39,7 @@ declare function modelFallbackMiddleware(
38
39
  /**
39
40
  * The fallback models to try, in order.
40
41
  */
41
- ...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware;
42
+ ...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
42
43
  //#endregion
43
44
  export { modelFallbackMiddleware };
44
45
  //# sourceMappingURL=modelFallback.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.d.cts","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"mappings":";;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,uBAAA;;;;GAIX,cAAA,YAA0B,iBAAA,MAC5B,eAAA"}
1
+ {"version":3,"file":"modelFallback.d.cts","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"mappings":";;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,uBAAA;;;;GAIX,cAAA,YAA0B,iBAAA,MAAoB,eAAA,0CAAH,sBAAA,CAAG,UAAA,GAAA,sBAAA,CAAA,UAAA"}
@@ -1,4 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.js";
2
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
2
3
  import { LanguageModelLike } from "@langchain/core/language_models/base";
3
4
 
4
5
  //#region src/agents/middleware/modelFallback.d.ts
@@ -38,7 +39,7 @@ declare function modelFallbackMiddleware(
38
39
  /**
39
40
  * The fallback models to try, in order.
40
41
  */
41
- ...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware;
42
+ ...fallbackModels: (string | LanguageModelLike)[]): AgentMiddleware<undefined, undefined, unknown, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
42
43
  //#endregion
43
44
  export { modelFallbackMiddleware };
44
45
  //# sourceMappingURL=modelFallback.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.d.ts","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"mappings":";;;;;;AAqCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,uBAAA;;;;GAIX,cAAA,YAA0B,iBAAA,MAC5B,eAAA"}
1
+ {"version":3,"file":"modelFallback.d.ts","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"mappings":";;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,uBAAA;;;;GAIX,cAAA,YAA0B,iBAAA,MAAoB,eAAA,0CAAH,sBAAA,CAAG,UAAA,GAAA,sBAAA,CAAA,UAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"modelFallback.js","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n): AgentMiddleware {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAgB,wBAId,GAAG,gBACc;AACjB,QAAO,iBAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAM,cAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;MACD,CAAC;aACK,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;;;;;AAQZ,UAAM;;;EAGX,CAAC"}
1
+ {"version":3,"file":"modelFallback.js","names":[],"sources":["../../../src/agents/middleware/modelFallback.ts"],"sourcesContent":["import type { LanguageModelLike } from \"@langchain/core/language_models/base\";\nimport { initChatModel } from \"../../chat_models/universal.js\";\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Middleware that provides automatic model fallback on errors.\n *\n * This middleware attempts to retry failed model calls with alternative models\n * in sequence. When a model call fails, it tries the next model in the fallback\n * list until either a call succeeds or all models have been exhausted.\n *\n * @example\n * ```ts\n * import { createAgent, modelFallbackMiddleware } from \"langchain\";\n *\n * // Create middleware with fallback models (not including primary)\n * const fallback = modelFallbackMiddleware(\n * \"openai:gpt-4o-mini\", // First fallback\n * \"anthropic:claude-sonnet-4-5-20250929\", // Second fallback\n * );\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\", // Primary model\n * middleware: [fallback],\n * tools: [],\n * });\n *\n * // If gpt-4o fails, automatically tries gpt-4o-mini, then claude\n * const result = await agent.invoke({\n * messages: [{ role: \"user\", content: \"Hello\" }]\n * });\n * ```\n *\n * @param fallbackModels - The fallback models to try, in order.\n * @returns A middleware instance that handles model failures with fallbacks\n */\nexport function modelFallbackMiddleware(\n /**\n * The fallback models to try, in order.\n */\n ...fallbackModels: (string | LanguageModelLike)[]\n) {\n return createMiddleware({\n name: \"modelFallbackMiddleware\",\n wrapModelCall: async (request, handler) => {\n /**\n * Try the primary model first\n */\n try {\n return await handler(request);\n } catch (error) {\n /**\n * If primary model fails, try fallback models in sequence\n */\n for (let i = 0; i < fallbackModels.length; i++) {\n try {\n const fallbackModel = fallbackModels[i];\n const model =\n typeof fallbackModel === \"string\"\n ? await initChatModel(fallbackModel)\n : fallbackModel;\n\n return await handler({\n ...request,\n model,\n });\n } catch (fallbackError) {\n /**\n * If this is the last fallback, throw the error\n */\n if (i === fallbackModels.length - 1) {\n throw fallbackError;\n }\n // Otherwise, continue to next fallback\n }\n }\n /**\n * If no fallbacks were provided, re-throw the original error\n */\n throw error;\n }\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,wBAId,GAAG,gBACH;AACA,QAAO,iBAAiB;EACtB,MAAM;EACN,eAAe,OAAO,SAAS,YAAY;;;;AAIzC,OAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;;;;AAId,SAAK,IAAI,IAAI,GAAG,IAAI,eAAe,QAAQ,IACzC,KAAI;KACF,MAAM,gBAAgB,eAAe;KACrC,MAAM,QACJ,OAAO,kBAAkB,WACrB,MAAM,cAAc,cAAc,GAClC;AAEN,YAAO,MAAM,QAAQ;MACnB,GAAG;MACH;MACD,CAAC;aACK,eAAe;;;;AAItB,SAAI,MAAM,eAAe,SAAS,EAChC,OAAM;;;;;AAQZ,UAAM;;;EAGX,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"modelRetry.cjs","names":["z","RetrySchema","InvalidRetryConfigError","AIMessage","createMiddleware","calculateRetryDelay","sleep"],"sources":["../../../src/agents/middleware/modelRetry.ts"],"sourcesContent":["/**\n * Model retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Model Retry Middleware.\n */\nexport const ModelRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ModelRetryMiddlewareConfig = z.input<\n typeof ModelRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed model calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, modelRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [modelRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { modelRetryMiddleware } from \"langchain\";\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on rate limit errors\n * if (error.name === \"RateLimitError\") {\n * return true;\n * }\n * // Or check for specific HTTP status codes\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return statusCode === 429 || statusCode === 503;\n * }\n * return false;\n * }\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Return error message instead of raising\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: \"continue\", // Return AIMessage with error instead of throwing\n * });\n * ```\n *\n * @example Custom error message formatting\n * ```ts\n * const formatError = (error: Error) =>\n * `Model call failed: ${error.message}. Please try again later.`;\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"error\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles model failures with retries\n */\nexport function modelRetryMiddleware(\n config: ModelRetryMiddlewareConfig = {}\n): AgentMiddleware {\n const { success, error, data } =\n ModelRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n retryOn,\n onFailure,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some(\n (ErrorConstructor) => error.constructor === ErrorConstructor\n );\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (error: Error, attemptsMade: number): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Model call failed after ${attemptsMade} ${attemptWord} with ${errorType}: ${error.message}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (error: Error, attemptsMade: number): AIMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(error, attemptsMade);\n }\n\n return new AIMessage({\n content,\n });\n };\n\n return createMiddleware({\n name: \"modelRetryMiddleware\",\n contextSchema: ModelRetryMiddlewareOptionsSchema,\n wrapModelCall: async (request, handler) => {\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via hand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EACtB,MAAM;EACN,eAAe;EACf,eAAe,OAAO,SAAS,YAAY;AAEzC,QAAK,IAAI,UAAU,GAAG,WAAW,YAAY,UAC3C,KAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;IACd,MAAM,eAAe,UAAU;IAG/B,MAAM,MACJ,SAAS,OAAO,UAAU,YAAY,aAAa,QAC9C,QACD,IAAI,MAAM,OAAO,MAAM,CAAC;AAG9B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,KAAK,aAAa;AAIzC,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQC,kCAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,EACV,OAAMC,oBAAM,MAAM;UAKpB,QAAO,cAAc,KAAK,aAAa;;AAM7C,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
1
+ {"version":3,"file":"modelRetry.cjs","names":["z","RetrySchema","InvalidRetryConfigError","AIMessage","createMiddleware","calculateRetryDelay","sleep"],"sources":["../../../src/agents/middleware/modelRetry.ts"],"sourcesContent":["/**\n * Model retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Model Retry Middleware.\n */\nexport const ModelRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ModelRetryMiddlewareConfig = z.input<\n typeof ModelRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed model calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, modelRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [modelRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { modelRetryMiddleware } from \"langchain\";\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on rate limit errors\n * if (error.name === \"RateLimitError\") {\n * return true;\n * }\n * // Or check for specific HTTP status codes\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return statusCode === 429 || statusCode === 503;\n * }\n * return false;\n * }\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Return error message instead of raising\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: \"continue\", // Return AIMessage with error instead of throwing\n * });\n * ```\n *\n * @example Custom error message formatting\n * ```ts\n * const formatError = (error: Error) =>\n * `Model call failed: ${error.message}. Please try again later.`;\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"error\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles model failures with retries\n */\nexport function modelRetryMiddleware(config: ModelRetryMiddlewareConfig = {}) {\n const { success, error, data } =\n ModelRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n retryOn,\n onFailure,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some(\n (ErrorConstructor) => error.constructor === ErrorConstructor\n );\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (error: Error, attemptsMade: number): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Model call failed after ${attemptsMade} ${attemptWord} with ${errorType}: ${error.message}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (error: Error, attemptsMade: number): AIMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(error, attemptsMade);\n }\n\n return new AIMessage({\n content,\n });\n };\n\n return createMiddleware({\n name: \"modelRetryMiddleware\",\n contextSchema: ModelRetryMiddlewareOptionsSchema,\n wrapModelCall: async (request, handler) => {\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected: retry loop completed without returning\");\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,MAAa,oCAAoCA,SAC9C,OAAO,EASN,WAAWA,SACR,MAAM;CACLA,SAAE,QAAQ,QAAQ;CAClBA,SAAE,QAAQ,WAAW;CACrBA,SAAE,UAAU,CAAC,KAAKA,SAAE,WAAW,MAAM,CAAC,CAAC,QAAQA,SAAE,QAAQ,CAAC;CAC3D,CAAC,CACD,QAAQ,WAAW,EACvB,CAAC,CACD,MAAMC,8BAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6FrB,SAAgB,qBAAqB,SAAqC,EAAE,EAAE;CAC5E,MAAM,EAAE,SAAS,OAAO,SACtB,kCAAkC,UAAU,OAAO;AACrD,KAAI,CAAC,QACH,OAAM,IAAIC,sCAAwB,MAAM;CAE1C,MAAM,EACJ,YACA,SACA,WACA,eACA,gBACA,YACA,WACE;;;;CAKJ,MAAM,wBAAwB,UAA0B;AACtD,MAAI,OAAO,YAAY,WACrB,QAAO,QAAQ,MAAM;AAGvB,SAAO,QAAQ,MACZ,qBAAqB,MAAM,gBAAgB,iBAC7C;;CAIH,MAAM,cAAc;EAAE;EAAe;EAAgB;EAAY;EAAQ;;;;CAKzE,MAAM,wBAAwB,OAAc,iBAAiC;EAC3E,MAAM,YAAY,MAAM,YAAY;AAEpC,SAAO,2BAA2B,aAAa,GAD3B,iBAAiB,IAAI,YAAY,WACS,QAAQ,UAAU,IAAI,MAAM;;;;;CAM5F,MAAM,iBAAiB,OAAc,iBAAoC;AACvE,MAAI,cAAc,QAChB,OAAM;EAGR,IAAI;AACJ,MAAI,OAAO,cAAc,WACvB,WAAU,UAAU,MAAM;MAE1B,WAAU,qBAAqB,OAAO,aAAa;AAGrD,SAAO,IAAIC,mCAAU,EACnB,SACD,CAAC;;AAGJ,QAAOC,oCAAiB;EACtB,MAAM;EACN,eAAe;EACf,eAAe,OAAO,SAAS,YAAY;AAEzC,QAAK,IAAI,UAAU,GAAG,WAAW,YAAY,UAC3C,KAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;IACd,MAAM,eAAe,UAAU;IAG/B,MAAM,MACJ,SAAS,OAAO,UAAU,YAAY,aAAa,QAC9C,QACD,IAAI,MAAM,OAAO,MAAM,CAAC;AAG9B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,KAAK,aAAa;AAIzC,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQC,kCAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,EACV,OAAMC,oBAAM,MAAM;UAKpB,QAAO,cAAc,KAAK,aAAa;;AAM7C,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.cjs";
2
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
2
3
  import { z } from "zod/v3";
3
4
 
4
5
  //#region src/agents/middleware/modelRetry.d.ts
@@ -127,7 +128,48 @@ type ModelRetryMiddlewareConfig = z.input<typeof ModelRetryMiddlewareOptionsSche
127
128
  * @param config - Configuration options for the retry middleware
128
129
  * @returns A middleware instance that handles model failures with retries
129
130
  */
130
- declare function modelRetryMiddleware(config?: ModelRetryMiddlewareConfig): AgentMiddleware;
131
+ declare function modelRetryMiddleware(config?: ModelRetryMiddlewareConfig): AgentMiddleware<undefined, z.ZodObject<{
132
+ /**
133
+ * Behavior when all retries are exhausted. Options:
134
+ * - `"continue"` (default): Return an AIMessage with error details, allowing
135
+ * the agent to potentially handle the failure gracefully.
136
+ * - `"error"`: Re-raise the exception, stopping agent execution.
137
+ * - Custom function: Function that takes the exception and returns a string
138
+ * for the AIMessage content, allowing custom error formatting.
139
+ */
140
+ onFailure: z.ZodDefault<z.ZodUnion<[z.ZodLiteral<"error">, z.ZodLiteral<"continue">, z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodString>]>>;
141
+ } & {
142
+ maxRetries: z.ZodDefault<z.ZodNumber>;
143
+ retryOn: z.ZodDefault<z.ZodUnion<[z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodBoolean>, z.ZodArray<z.ZodType<new (...args: any[]) => Error, z.ZodTypeDef, new (...args: any[]) => Error>, "many">]>>;
144
+ backoffFactor: z.ZodDefault<z.ZodNumber>;
145
+ initialDelayMs: z.ZodDefault<z.ZodNumber>;
146
+ maxDelayMs: z.ZodDefault<z.ZodNumber>;
147
+ jitter: z.ZodDefault<z.ZodBoolean>;
148
+ }, "strip", z.ZodTypeAny, {
149
+ maxRetries: number;
150
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
151
+ backoffFactor: number;
152
+ initialDelayMs: number;
153
+ maxDelayMs: number;
154
+ jitter: boolean;
155
+ onFailure: "continue" | "error" | ((args_0: Error, ...args: unknown[]) => string);
156
+ }, {
157
+ maxRetries?: number | undefined;
158
+ retryOn?: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean) | undefined;
159
+ backoffFactor?: number | undefined;
160
+ initialDelayMs?: number | undefined;
161
+ maxDelayMs?: number | undefined;
162
+ jitter?: boolean | undefined;
163
+ onFailure?: "continue" | "error" | ((args_0: Error, ...args: unknown[]) => string) | undefined;
164
+ }>, {
165
+ maxRetries: number;
166
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
167
+ backoffFactor: number;
168
+ initialDelayMs: number;
169
+ maxDelayMs: number;
170
+ jitter: boolean;
171
+ onFailure: "continue" | "error" | ((args_0: Error, ...args: unknown[]) => string);
172
+ }, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
131
173
  //#endregion
132
174
  export { ModelRetryMiddlewareConfig, modelRetryMiddleware };
133
175
  //# sourceMappingURL=modelRetry.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"modelRetry.d.cts","names":[],"sources":["../../../src/agents/middleware/modelRetry.ts"],"mappings":";;;;;;;cAea,iCAAA,EAAiC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoBlC,0BAAA,GAA6B,CAAA,CAAE,KAAA,QAClC,iCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0FO,oBAAA,CACd,MAAA,GAAQ,0BAAA,GACP,eAAA"}
1
+ {"version":3,"file":"modelRetry.d.cts","names":[],"sources":["../../../src/agents/middleware/modelRetry.ts"],"mappings":";;;;;;AAcA;;cAAa,iCAAA,EAAiC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoBlC,0BAAA,GAA6B,CAAA,CAAE,KAAA,QAClC,iCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0FO,oBAAA,CAAqB,MAAA,GAAQ,0BAAA,8BAA+B,CAAA,CAAA,SAAA"}
@@ -1,4 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.js";
2
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
2
3
  import { z } from "zod/v3";
3
4
 
4
5
  //#region src/agents/middleware/modelRetry.d.ts
@@ -127,7 +128,48 @@ type ModelRetryMiddlewareConfig = z.input<typeof ModelRetryMiddlewareOptionsSche
127
128
  * @param config - Configuration options for the retry middleware
128
129
  * @returns A middleware instance that handles model failures with retries
129
130
  */
130
- declare function modelRetryMiddleware(config?: ModelRetryMiddlewareConfig): AgentMiddleware;
131
+ declare function modelRetryMiddleware(config?: ModelRetryMiddlewareConfig): AgentMiddleware<undefined, z.ZodObject<{
132
+ /**
133
+ * Behavior when all retries are exhausted. Options:
134
+ * - `"continue"` (default): Return an AIMessage with error details, allowing
135
+ * the agent to potentially handle the failure gracefully.
136
+ * - `"error"`: Re-raise the exception, stopping agent execution.
137
+ * - Custom function: Function that takes the exception and returns a string
138
+ * for the AIMessage content, allowing custom error formatting.
139
+ */
140
+ onFailure: z.ZodDefault<z.ZodUnion<[z.ZodLiteral<"error">, z.ZodLiteral<"continue">, z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodString>]>>;
141
+ } & {
142
+ maxRetries: z.ZodDefault<z.ZodNumber>;
143
+ retryOn: z.ZodDefault<z.ZodUnion<[z.ZodFunction<z.ZodTuple<[z.ZodType<Error, z.ZodTypeDef, Error>], z.ZodUnknown>, z.ZodBoolean>, z.ZodArray<z.ZodType<new (...args: any[]) => Error, z.ZodTypeDef, new (...args: any[]) => Error>, "many">]>>;
144
+ backoffFactor: z.ZodDefault<z.ZodNumber>;
145
+ initialDelayMs: z.ZodDefault<z.ZodNumber>;
146
+ maxDelayMs: z.ZodDefault<z.ZodNumber>;
147
+ jitter: z.ZodDefault<z.ZodBoolean>;
148
+ }, "strip", z.ZodTypeAny, {
149
+ maxRetries: number;
150
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
151
+ backoffFactor: number;
152
+ initialDelayMs: number;
153
+ maxDelayMs: number;
154
+ jitter: boolean;
155
+ onFailure: "continue" | "error" | ((args_0: Error, ...args: unknown[]) => string);
156
+ }, {
157
+ maxRetries?: number | undefined;
158
+ retryOn?: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean) | undefined;
159
+ backoffFactor?: number | undefined;
160
+ initialDelayMs?: number | undefined;
161
+ maxDelayMs?: number | undefined;
162
+ jitter?: boolean | undefined;
163
+ onFailure?: "continue" | "error" | ((args_0: Error, ...args: unknown[]) => string) | undefined;
164
+ }>, {
165
+ maxRetries: number;
166
+ retryOn: (new (...args: any[]) => Error)[] | ((args_0: Error, ...args: unknown[]) => boolean);
167
+ backoffFactor: number;
168
+ initialDelayMs: number;
169
+ maxDelayMs: number;
170
+ jitter: boolean;
171
+ onFailure: "continue" | "error" | ((args_0: Error, ...args: unknown[]) => string);
172
+ }, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
131
173
  //#endregion
132
174
  export { ModelRetryMiddlewareConfig, modelRetryMiddleware };
133
175
  //# sourceMappingURL=modelRetry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"modelRetry.d.ts","names":[],"sources":["../../../src/agents/middleware/modelRetry.ts"],"mappings":";;;;;;;cAea,iCAAA,EAAiC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoBlC,0BAAA,GAA6B,CAAA,CAAE,KAAA,QAClC,iCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0FO,oBAAA,CACd,MAAA,GAAQ,0BAAA,GACP,eAAA"}
1
+ {"version":3,"file":"modelRetry.d.ts","names":[],"sources":["../../../src/agents/middleware/modelRetry.ts"],"mappings":";;;;;;AAcA;;cAAa,iCAAA,EAAiC,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAoBlC,0BAAA,GAA6B,CAAA,CAAE,KAAA,QAClC,iCAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA0FO,oBAAA,CAAqB,MAAA,GAAQ,0BAAA,8BAA+B,CAAA,CAAA,SAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"modelRetry.js","names":[],"sources":["../../../src/agents/middleware/modelRetry.ts"],"sourcesContent":["/**\n * Model retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Model Retry Middleware.\n */\nexport const ModelRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ModelRetryMiddlewareConfig = z.input<\n typeof ModelRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed model calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, modelRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [modelRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { modelRetryMiddleware } from \"langchain\";\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on rate limit errors\n * if (error.name === \"RateLimitError\") {\n * return true;\n * }\n * // Or check for specific HTTP status codes\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return statusCode === 429 || statusCode === 503;\n * }\n * return false;\n * }\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Return error message instead of raising\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: \"continue\", // Return AIMessage with error instead of throwing\n * });\n * ```\n *\n * @example Custom error message formatting\n * ```ts\n * const formatError = (error: Error) =>\n * `Model call failed: ${error.message}. Please try again later.`;\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"error\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles model failures with retries\n */\nexport function modelRetryMiddleware(\n config: ModelRetryMiddlewareConfig = {}\n): AgentMiddleware {\n const { success, error, data } =\n ModelRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n retryOn,\n onFailure,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some(\n (ErrorConstructor) => error.constructor === ErrorConstructor\n );\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (error: Error, attemptsMade: number): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Model call failed after ${attemptsMade} ${attemptWord} with ${errorType}: ${error.message}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (error: Error, attemptsMade: number): AIMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(error, attemptsMade);\n }\n\n return new AIMessage({\n content,\n });\n };\n\n return createMiddleware({\n name: \"modelRetryMiddleware\",\n contextSchema: ModelRetryMiddlewareOptionsSchema,\n wrapModelCall: async (request, handler) => {\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected: retry loop completed without returning\");\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAa,oCAAoC,EAC9C,OAAO,EASN,WAAW,EACR,MAAM;CACL,EAAE,QA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Ae,UAAU;IAG/B,MAAM,MACJ,SAAS,OAAO,UAAU,YAAY,aAAa,QAC9C,QACD,IAAI,MAAM,OAAO,MAAM,CAAC;AAG9B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,KAAK,aAAa;AAIzC,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQ,oBAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,EACV,OAAM,MAAM,MAAM;UAKpB,QAAO,cAAc,KAAK,aAAa;;AAM7C,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
1
+ {"version":3,"file":"modelRetry.js","names":[],"sources":["../../../src/agents/middleware/modelRetry.ts"],"sourcesContent":["/**\n * Model retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { AIMessage } from \"@langchain/core/messages\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Model Retry Middleware.\n */\nexport const ModelRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ModelRetryMiddlewareConfig = z.input<\n typeof ModelRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed model calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, modelRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [modelRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { modelRetryMiddleware } from \"langchain\";\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on rate limit errors\n * if (error.name === \"RateLimitError\") {\n * return true;\n * }\n * // Or check for specific HTTP status codes\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return statusCode === 429 || statusCode === 503;\n * }\n * return false;\n * }\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Return error message instead of raising\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: \"continue\", // Return AIMessage with error instead of throwing\n * });\n * ```\n *\n * @example Custom error message formatting\n * ```ts\n * const formatError = (error: Error) =>\n * `Model call failed: ${error.message}. Please try again later.`;\n *\n * const retry = modelRetryMiddleware({\n * maxRetries: 4,\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = modelRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"error\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles model failures with retries\n */\nexport function modelRetryMiddleware(config: ModelRetryMiddlewareConfig = {}) {\n const { success, error, data } =\n ModelRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n retryOn,\n onFailure,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some(\n (ErrorConstructor) => error.constructor === ErrorConstructor\n );\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (error: Error, attemptsMade: number): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Model call failed after ${attemptsMade} ${attemptWord} with ${errorType}: ${error.message}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (error: Error, attemptsMade: number): AIMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(error, attemptsMade);\n }\n\n return new AIMessage({\n content,\n });\n };\n\n return createMiddleware({\n name: \"modelRetryMiddleware\",\n contextSchema: ModelRetryMiddlewareOptionsSchema,\n wrapModelCall: async (request, handler) => {\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected: retry loop completed without returning\");\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAcA,MAAa,oCAAoC,EAC9C,OAAO,EASN,WAAW,EACR,MAAM;CACL,EAAE,QAAQ,QAAQ;CAClB,EAAE,QAAQ,WAAW;CACrB,EAAE,UAAU,CAAC,KAAK,EAAE,WAAW,MAAM,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC;CAC3D,CAAC,CACD,QAAQ,WAAW,EACvB,CAAC,CACD,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6FrB,SAAgB,qBAAqB,SAAqC,EAAE,EAAE;CAC5E,MAAM,EAAE,SAAS,OAAO,SACtB,kCAAkC,UAAU,OAAO;AACrD,KAAI,CAAC,QACH,OAAM,IAAI,wBAAwB,MAAM;CAE1C,MAAM,EACJ,YACA,SACA,WACA,eACA,gBACA,YACA,WACE;;;;CAKJ,MAAM,wBAAwB,UAA0B;AACtD,MAAI,OAAO,YAAY,WACrB,QAAO,QAAQ,MAAM;AAGvB,SAAO,QAAQ,MACZ,qBAAqB,MAAM,gBAAgB,iBAC7C;;CAIH,MAAM,cAAc;EAAE;EAAe;EAAgB;EAAY;EAAQ;;;;CAKzE,MAAM,wBAAwB,OAAc,iBAAiC;EAC3E,MAAM,YAAY,MAAM,YAAY;AAEpC,SAAO,2BAA2B,aAAa,GAD3B,iBAAiB,IAAI,YAAY,WACS,QAAQ,UAAU,IAAI,MAAM;;;;;CAM5F,MAAM,iBAAiB,OAAc,iBAAoC;AACvE,MAAI,cAAc,QAChB,OAAM;EAGR,IAAI;AACJ,MAAI,OAAO,cAAc,WACvB,WAAU,UAAU,MAAM;MAE1B,WAAU,qBAAqB,OAAO,aAAa;AAGrD,SAAO,IAAI,UAAU,EACnB,SACD,CAAC;;AAGJ,QAAO,iBAAiB;EACtB,MAAM;EACN,eAAe;EACf,eAAe,OAAO,SAAS,YAAY;AAEzC,QAAK,IAAI,UAAU,GAAG,WAAW,YAAY,UAC3C,KAAI;AACF,WAAO,MAAM,QAAQ,QAAQ;YACtB,OAAO;IACd,MAAM,eAAe,UAAU;IAG/B,MAAM,MACJ,SAAS,OAAO,UAAU,YAAY,aAAa,QAC9C,QACD,IAAI,MAAM,OAAO,MAAM,CAAC;AAG9B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,KAAK,aAAa;AAIzC,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQ,oBAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,EACV,OAAM,MAAM,MAAM;UAKpB,QAAO,cAAc,KAAK,aAAa;;AAM7C,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
@@ -400,10 +400,13 @@ function piiMiddleware(piiType, options = {}) {
400
400
  if (!messages || messages.length === 0) return;
401
401
  let lastAiIdx = null;
402
402
  let lastAiMsg = null;
403
- for (let i = messages.length - 1; i >= 0; i--) if (_langchain_core_messages.AIMessage.isInstance(messages[i])) {
404
- lastAiMsg = messages[i];
405
- lastAiIdx = i;
406
- break;
403
+ for (let i = messages.length - 1; i >= 0; i--) {
404
+ const msg = messages[i];
405
+ if (_langchain_core_messages.AIMessage.isInstance(msg)) {
406
+ lastAiMsg = msg;
407
+ lastAiIdx = i;
408
+ break;
409
+ }
407
410
  }
408
411
  if (lastAiIdx === null || !lastAiMsg || !lastAiMsg.content) return;
409
412
  const { content: newContent, matches } = processContent(String(lastAiMsg.content), resolvedRule);
@@ -1 +1 @@
1
- {"version":3,"file":"pii.cjs","names":["z","createMiddleware","HumanMessage","AIMessage","ToolMessage"],"sources":["../../../src/agents/middleware/pii.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { sha256 } from \"@langchain/core/utils/hash\";\nimport { AIMessage, HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Represents a detected PII match in content\n */\nexport interface PIIMatch {\n /**\n * The matched text\n */\n text: string;\n /**\n * The start index of the match\n */\n start: number;\n /**\n * The end index of the match\n */\n end: number;\n}\n\n/**\n * Error thrown when PII is detected and strategy is 'block'\n */\nexport class PIIDetectionError extends Error {\n constructor(\n public readonly piiType: string,\n public readonly matches: PIIMatch[]\n ) {\n super(`PII detected: ${piiType} found ${matches.length} occurrence(s)`);\n this.name = \"PIIDetectionError\";\n }\n}\n\n/**\n * Strategy for handling detected PII\n */\nexport type PIIStrategy = \"block\" | \"redact\" | \"mask\" | \"hash\";\n\n/**\n * Built-in PII types\n */\nexport type BuiltInPIIType =\n | \"email\"\n | \"credit_card\"\n | \"ip\"\n | \"mac_address\"\n | \"url\";\n\n/**\n * Custom detector function that takes content and returns matches\n */\nexport type PIIDetector = (content: string) => PIIMatch[];\nexport type Detector = PIIDetector | RegExp | string;\n\n/**\n * Configuration for a redaction rule\n */\nexport interface RedactionRuleConfig {\n /**\n * Type of PII to detect (built-in or custom name)\n */\n piiType: BuiltInPIIType | string;\n /**\n * Strategy for handling detected PII\n */\n strategy: PIIStrategy;\n /**\n * Custom detector function or regex pattern string\n */\n detector?: Detector;\n}\n\n/**\n * Resolved redaction rule with a concrete detector function\n */\nexport interface ResolvedRedactionRule {\n piiType: string;\n strategy: PIIStrategy;\n detector: PIIDetector;\n}\n\n/**\n * Email detection regex pattern\n */\nconst EMAIL_PATTERN = /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g;\n\n/**\n * Credit card detection regex pattern (basic, will be validated with Luhn)\n */\nconst CREDIT_CARD_PATTERN = /\\b(?:\\d{4}[-\\s]?){3}\\d{4}\\b/g;\n\n/**\n * IP address detection regex pattern\n */\nconst IP_PATTERN =\n /\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/g;\n\n/**\n * MAC address detection regex pattern\n */\nconst MAC_ADDRESS_PATTERN = /\\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\\b/g;\n\n/**\n * URL detection regex pattern\n */\nconst URL_PATTERN = /(?:https?:\\/\\/|www\\.)[^\\s<>\"{}|\\\\^`[\\]]+/gi;\n\n/**\n * Luhn algorithm for credit card validation\n */\nfunction luhnCheck(cardNumber: string): boolean {\n const digits = cardNumber.replace(/\\D/g, \"\");\n let sum = 0;\n let isEven = false;\n\n for (let i = digits.length - 1; i >= 0; i--) {\n let digit = parseInt(digits[i], 10);\n\n if (isEven) {\n digit *= 2;\n if (digit > 9) {\n digit -= 9;\n }\n }\n\n sum += digit;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n}\n\n/**\n * Convert regex match to PIIMatch\n */\nfunction regexMatchToPIIMatch(match: RegExpMatchArray): PIIMatch {\n return {\n text: match[0],\n start: match.index ?? 0,\n end: (match.index ?? 0) + match[0].length,\n };\n}\n\n/**\n * Detect email addresses in content\n */\nexport function detectEmail(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(EMAIL_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Detect credit card numbers in content (validated with Luhn algorithm)\n */\nexport function detectCreditCard(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(CREDIT_CARD_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n const cardNumber = match[0].replace(/\\D/g, \"\");\n // Credit cards are typically 13-19 digits\n if (\n cardNumber.length >= 13 &&\n cardNumber.length <= 19 &&\n luhnCheck(cardNumber)\n ) {\n matches.push(regexMatchToPIIMatch(match));\n }\n }\n\n return matches;\n}\n\n/**\n * Detect IP addresses in content (validated)\n */\nexport function detectIP(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(IP_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n const ip = match[0];\n // Additional validation: each octet should be 0-255\n const parts = ip.split(\".\");\n if (\n parts.length === 4 &&\n parts.every((part) => {\n const num = parseInt(part, 10);\n return num >= 0 && num <= 255;\n })\n ) {\n matches.push(regexMatchToPIIMatch(match));\n }\n }\n\n return matches;\n}\n\n/**\n * Detect MAC addresses in content\n */\nexport function detectMacAddress(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(MAC_ADDRESS_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Detect URLs in content\n */\nexport function detectUrl(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(URL_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Built-in detector map\n */\nconst BUILT_IN_DETECTORS: Record<BuiltInPIIType, PIIDetector> = {\n email: detectEmail,\n credit_card: detectCreditCard,\n ip: detectIP,\n mac_address: detectMacAddress,\n url: detectUrl,\n};\n\n/**\n * Resolve a redaction rule to a concrete detector function\n */\nexport function resolveRedactionRule(\n config: RedactionRuleConfig\n): ResolvedRedactionRule {\n let detector: PIIDetector;\n\n if (config.detector) {\n if (typeof config.detector === \"string\") {\n // Regex pattern string\n const regex = new RegExp(config.detector, \"g\");\n detector = (content: string) => {\n const matches: PIIMatch[] = [];\n let match: RegExpMatchArray | null;\n const regexCopy = new RegExp(regex);\n\n while ((match = regexCopy.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n };\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (config.detector instanceof RegExp) {\n detector = (content: string) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (!(config.detector instanceof RegExp)) {\n throw new Error(\"Detector is required\");\n }\n const matches: PIIMatch[] = [];\n let match: RegExpMatchArray | null;\n while ((match = config.detector.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n };\n } else {\n detector = config.detector;\n }\n } else {\n // Use built-in detector\n const builtInType = config.piiType as BuiltInPIIType;\n if (!BUILT_IN_DETECTORS[builtInType]) {\n throw new Error(\n `Unknown PII type: ${config.piiType}. Must be one of: ${Object.keys(\n BUILT_IN_DETECTORS\n ).join(\", \")}, or provide a custom detector.`\n );\n }\n detector = BUILT_IN_DETECTORS[builtInType];\n }\n\n return {\n piiType: config.piiType,\n strategy: config.strategy,\n detector,\n };\n}\n\n/**\n * Apply redact strategy: replace with [REDACTED_TYPE]\n */\nfunction applyRedactStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const replacement = `[REDACTED_${piiType.toUpperCase()}]`;\n result =\n result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply mask strategy: partially mask PII (show last few characters)\n */\nfunction applyMaskStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const text = match.text;\n let masked: string;\n\n if (piiType === \"credit_card\") {\n // Show last 4 digits: ****-****-****-1234\n const digits = text.replace(/\\D/g, \"\");\n const last4 = digits.slice(-4);\n masked = `****-****-****-${last4}`;\n } else if (piiType === \"email\") {\n // Show first char and domain: j***@example.com\n const [local, domain] = text.split(\"@\");\n if (local && domain) {\n masked = `${local[0]}***@${domain}`;\n } else {\n masked = \"***\";\n }\n } else {\n // Default: show last 4 characters\n const visibleChars = Math.min(4, text.length);\n masked = `${\"*\".repeat(\n Math.max(0, text.length - visibleChars)\n )}${text.slice(-visibleChars)}`;\n }\n\n result = result.slice(0, match.start) + masked + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply hash strategy: replace with deterministic hash\n */\nfunction applyHashStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const hash = sha256(match.text).slice(0, 8);\n const replacement = `<${piiType}_hash:${hash}>`;\n result =\n result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply strategy to content based on matches\n */\nexport function applyStrategy(\n content: string,\n matches: PIIMatch[],\n strategy: PIIStrategy,\n piiType: string\n): string {\n if (matches.length === 0) {\n return content;\n }\n\n switch (strategy) {\n case \"block\":\n throw new PIIDetectionError(piiType, matches);\n case \"redact\":\n return applyRedactStrategy(content, matches, piiType);\n case \"mask\":\n return applyMaskStrategy(content, matches, piiType);\n case \"hash\":\n return applyHashStrategy(content, matches, piiType);\n default:\n throw new Error(`Unknown strategy: ${strategy}`);\n }\n}\n\n/**\n * Configuration schema for PII middleware\n */\nconst contextSchema = z.object({\n /**\n * Whether to check user messages before model call\n */\n applyToInput: z.boolean().optional(),\n /**\n * Whether to check AI messages after model call\n */\n applyToOutput: z.boolean().optional(),\n /**\n * Whether to check tool result messages after tool execution\n */\n applyToToolResults: z.boolean().optional(),\n});\n\nexport type PIIMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n\n/**\n * Process content for PII detection and apply strategy\n */\nfunction processContent(\n content: string,\n rule: ResolvedRedactionRule\n): { content: string; matches: PIIMatch[] } {\n const matches = rule.detector(content);\n if (matches.length === 0) {\n return { content, matches: [] };\n }\n\n const sanitized = applyStrategy(\n content,\n matches,\n rule.strategy,\n rule.piiType\n );\n return { content: sanitized, matches };\n}\n\n/**\n * Creates a middleware that detects and handles personally identifiable information (PII)\n * in conversations.\n *\n * This middleware detects common PII types and applies configurable strategies to handle them.\n * It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input\n * and agent output.\n *\n * Built-in PII types:\n * - `email`: Email addresses\n * - `credit_card`: Credit card numbers (validated with Luhn algorithm)\n * - `ip`: IP addresses (validated)\n * - `mac_address`: MAC addresses\n * - `url`: URLs (both `http`/`https` and bare URLs)\n *\n * Strategies:\n * - `block`: Raise an exception when PII is detected\n * - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders\n * - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)\n * - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)\n *\n * Strategy Selection Guide:\n * | Strategy | Preserves Identity? | Best For |\n * | -------- | ------------------- | --------------------------------------- |\n * | `block` | N/A | Avoid PII completely |\n * | `redact` | No | General compliance, log sanitization |\n * | `mask` | No | Human readability, customer service UIs |\n * | `hash` | Yes (pseudonymous) | Analytics, debugging |\n *\n * @param piiType - Type of PII to detect. Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`, `url`) or a custom type name.\n * @param options - Configuration options\n * @param options.strategy - How to handle detected PII. Defaults to `\"redact\"`.\n * @param options.detector - Custom detector function or regex pattern string. If not provided, uses built-in detector for the `piiType`.\n * @param options.applyToInput - Whether to check user messages before model call. Defaults to `true`.\n * @param options.applyToOutput - Whether to check AI messages after model call. Defaults to `false`.\n * @param options.applyToToolResults - Whether to check tool result messages after tool execution. Defaults to `false`.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @throws {PIIDetectionError} When PII is detected and strategy is `'block'`\n * @throws {Error} If `piiType` is not built-in and no detector is provided\n *\n * @example Basic usage\n * ```typescript\n * import { piiMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Redact all emails in user input\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"email\", { strategy: \"redact\" }),\n * ],\n * });\n * ```\n *\n * @example Different strategies for different PII types\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [\n * piiMiddleware(\"credit_card\", { strategy: \"mask\" }),\n * piiMiddleware(\"url\", { strategy: \"redact\" }),\n * piiMiddleware(\"ip\", { strategy: \"hash\" }),\n * ],\n * });\n * ```\n *\n * @example Custom PII type with regex\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"api_key\", {\n * detector: \"sk-[a-zA-Z0-9]{32}\",\n * strategy: \"block\",\n * }),\n * ],\n * });\n * ```\n *\n * @public\n */\nexport function piiMiddleware(\n piiType: BuiltInPIIType | string,\n options: {\n strategy?: PIIStrategy;\n detector?: Detector;\n applyToInput?: boolean;\n applyToOutput?: boolean;\n applyToToolResults?: boolean;\n } = {}\n): ReturnType<typeof createMiddleware> {\n const { strategy = \"redact\", detector } = options;\n const resolvedRule = resolveRedactionRule({\n piiType,\n strategy,\n detector,\n });\n\n const middlewareName = `PIIMiddleware[${resolvedRule.piiType}]`;\n\n return createMiddleware({\n name: middlewareName,\n contextSchema,\n beforeModel: async (state, runtime) => {\n const applyToInput =\n runtime.context.applyToInput ?? options.applyToInput ?? true;\n const applyToToolResults =\n runtime.context.applyToToolResults ??\n options.applyToToolResults ??\n false;\n\n if (!applyToInput && !applyToToolResults) {\n return;\n }\n\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return;\n }\n\n const newMessages = [...messages];\n let anyModified = false;\n\n // Check user input if enabled\n if (applyToInput) {\n // Get last user message\n let lastUserIdx: number | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (HumanMessage.isInstance(messages[i])) {\n lastUserIdx = i;\n break;\n }\n }\n\n if (lastUserIdx !== null) {\n const lastUserMsg = messages[lastUserIdx];\n if (lastUserMsg && lastUserMsg.content) {\n const content = String(lastUserMsg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length > 0) {\n newMessages[lastUserIdx] = new HumanMessage({\n content: newContent,\n id: lastUserMsg.id,\n name: lastUserMsg.name,\n });\n anyModified = true;\n }\n }\n }\n }\n\n // Check tool results if enabled\n if (applyToToolResults) {\n // Find the last AIMessage, then process all ToolMessage objects after it\n let lastAiIdx: number | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (AIMessage.isInstance(messages[i])) {\n lastAiIdx = i;\n break;\n }\n }\n\n if (lastAiIdx !== null) {\n // Get all tool messages after the last AI message\n for (let i = lastAiIdx + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (ToolMessage.isInstance(msg)) {\n if (!msg.content) {\n continue;\n }\n\n const content = String(msg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length > 0) {\n newMessages[i] = new ToolMessage({\n content: newContent,\n id: msg.id,\n name: msg.name,\n tool_call_id: msg.tool_call_id,\n });\n anyModified = true;\n }\n }\n }\n }\n }\n\n if (anyModified) {\n return { messages: newMessages };\n }\n\n return;\n },\n afterModel: async (state, runtime) => {\n const applyToOutput =\n runtime.context.applyToOutput ?? options.applyToOutput ?? false;\n\n if (!applyToOutput) {\n return;\n }\n\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return;\n }\n\n // Get last AI message\n let lastAiIdx: number | null = null;\n let lastAiMsg: AIMessage | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (AIMessage.isInstance(messages[i])) {\n lastAiMsg = messages[i];\n lastAiIdx = i;\n break;\n }\n }\n\n if (lastAiIdx === null || !lastAiMsg || !lastAiMsg.content) {\n return;\n }\n\n // Detect PII in message content\n const content = String(lastAiMsg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length === 0) {\n return;\n }\n\n // Create updated message\n const updatedMessage = new AIMessage({\n content: newContent,\n id: lastAiMsg.id,\n name: lastAiMsg.name,\n tool_calls: lastAiMsg.tool_calls,\n });\n\n // Return updated messages\n const newMessages = [...messages];\n newMessages[lastAiIdx] = updatedMessage;\n return { messages: newMessages };\n },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;EAEnC,CAAC"}
1
+ {"version":3,"file":"pii.cjs","names":["z","createMiddleware","HumanMessage","AIMessage","ToolMessage"],"sources":["../../../src/agents/middleware/pii.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { sha256 } from \"@langchain/core/utils/hash\";\nimport { AIMessage, HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n\nimport { createMiddleware } from \"../middleware.js\";\n\n/**\n * Represents a detected PII match in content\n */\nexport interface PIIMatch {\n /**\n * The matched text\n */\n text: string;\n /**\n * The start index of the match\n */\n start: number;\n /**\n * The end index of the match\n */\n end: number;\n}\n\n/**\n * Error thrown when PII is detected and strategy is 'block'\n */\nexport class PIIDetectionError extends Error {\n constructor(\n public readonly piiType: string,\n public readonly matches: PIIMatch[]\n ) {\n super(`PII detected: ${piiType} found ${matches.length} occurrence(s)`);\n this.name = \"PIIDetectionError\";\n }\n}\n\n/**\n * Strategy for handling detected PII\n */\nexport type PIIStrategy = \"block\" | \"redact\" | \"mask\" | \"hash\";\n\n/**\n * Built-in PII types\n */\nexport type BuiltInPIIType =\n | \"email\"\n | \"credit_card\"\n | \"ip\"\n | \"mac_address\"\n | \"url\";\n\n/**\n * Custom detector function that takes content and returns matches\n */\nexport type PIIDetector = (content: string) => PIIMatch[];\nexport type Detector = PIIDetector | RegExp | string;\n\n/**\n * Configuration for a redaction rule\n */\nexport interface RedactionRuleConfig {\n /**\n * Type of PII to detect (built-in or custom name)\n */\n piiType: BuiltInPIIType | string;\n /**\n * Strategy for handling detected PII\n */\n strategy: PIIStrategy;\n /**\n * Custom detector function or regex pattern string\n */\n detector?: Detector;\n}\n\n/**\n * Resolved redaction rule with a concrete detector function\n */\nexport interface ResolvedRedactionRule {\n piiType: string;\n strategy: PIIStrategy;\n detector: PIIDetector;\n}\n\n/**\n * Email detection regex pattern\n */\nconst EMAIL_PATTERN = /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g;\n\n/**\n * Credit card detection regex pattern (basic, will be validated with Luhn)\n */\nconst CREDIT_CARD_PATTERN = /\\b(?:\\d{4}[-\\s]?){3}\\d{4}\\b/g;\n\n/**\n * IP address detection regex pattern\n */\nconst IP_PATTERN =\n /\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/g;\n\n/**\n * MAC address detection regex pattern\n */\nconst MAC_ADDRESS_PATTERN = /\\b(?:[0-9A-Fa-f]{2}[:-]){5}(?:[0-9A-Fa-f]{2})\\b/g;\n\n/**\n * URL detection regex pattern\n */\nconst URL_PATTERN = /(?:https?:\\/\\/|www\\.)[^\\s<>\"{}|\\\\^`[\\]]+/gi;\n\n/**\n * Luhn algorithm for credit card validation\n */\nfunction luhnCheck(cardNumber: string): boolean {\n const digits = cardNumber.replace(/\\D/g, \"\");\n let sum = 0;\n let isEven = false;\n\n for (let i = digits.length - 1; i >= 0; i--) {\n let digit = parseInt(digits[i], 10);\n\n if (isEven) {\n digit *= 2;\n if (digit > 9) {\n digit -= 9;\n }\n }\n\n sum += digit;\n isEven = !isEven;\n }\n\n return sum % 10 === 0;\n}\n\n/**\n * Convert regex match to PIIMatch\n */\nfunction regexMatchToPIIMatch(match: RegExpMatchArray): PIIMatch {\n return {\n text: match[0],\n start: match.index ?? 0,\n end: (match.index ?? 0) + match[0].length,\n };\n}\n\n/**\n * Detect email addresses in content\n */\nexport function detectEmail(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(EMAIL_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Detect credit card numbers in content (validated with Luhn algorithm)\n */\nexport function detectCreditCard(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(CREDIT_CARD_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n const cardNumber = match[0].replace(/\\D/g, \"\");\n // Credit cards are typically 13-19 digits\n if (\n cardNumber.length >= 13 &&\n cardNumber.length <= 19 &&\n luhnCheck(cardNumber)\n ) {\n matches.push(regexMatchToPIIMatch(match));\n }\n }\n\n return matches;\n}\n\n/**\n * Detect IP addresses in content (validated)\n */\nexport function detectIP(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(IP_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n const ip = match[0];\n // Additional validation: each octet should be 0-255\n const parts = ip.split(\".\");\n if (\n parts.length === 4 &&\n parts.every((part) => {\n const num = parseInt(part, 10);\n return num >= 0 && num <= 255;\n })\n ) {\n matches.push(regexMatchToPIIMatch(match));\n }\n }\n\n return matches;\n}\n\n/**\n * Detect MAC addresses in content\n */\nexport function detectMacAddress(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(MAC_ADDRESS_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Detect URLs in content\n */\nexport function detectUrl(content: string): PIIMatch[] {\n const matches: PIIMatch[] = [];\n const regex = new RegExp(URL_PATTERN);\n let match: RegExpMatchArray | null;\n\n while ((match = regex.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n}\n\n/**\n * Built-in detector map\n */\nconst BUILT_IN_DETECTORS: Record<BuiltInPIIType, PIIDetector> = {\n email: detectEmail,\n credit_card: detectCreditCard,\n ip: detectIP,\n mac_address: detectMacAddress,\n url: detectUrl,\n};\n\n/**\n * Resolve a redaction rule to a concrete detector function\n */\nexport function resolveRedactionRule(\n config: RedactionRuleConfig\n): ResolvedRedactionRule {\n let detector: PIIDetector;\n\n if (config.detector) {\n if (typeof config.detector === \"string\") {\n // Regex pattern string\n const regex = new RegExp(config.detector, \"g\");\n detector = (content: string) => {\n const matches: PIIMatch[] = [];\n let match: RegExpMatchArray | null;\n const regexCopy = new RegExp(regex);\n\n while ((match = regexCopy.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n };\n // eslint-disable-next-line no-instanceof/no-instanceof\n } else if (config.detector instanceof RegExp) {\n detector = (content: string) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n if (!(config.detector instanceof RegExp)) {\n throw new Error(\"Detector is required\");\n }\n const matches: PIIMatch[] = [];\n let match: RegExpMatchArray | null;\n while ((match = config.detector.exec(content)) !== null) {\n matches.push(regexMatchToPIIMatch(match));\n }\n\n return matches;\n };\n } else {\n detector = config.detector;\n }\n } else {\n // Use built-in detector\n const builtInType = config.piiType as BuiltInPIIType;\n if (!BUILT_IN_DETECTORS[builtInType]) {\n throw new Error(\n `Unknown PII type: ${config.piiType}. Must be one of: ${Object.keys(\n BUILT_IN_DETECTORS\n ).join(\", \")}, or provide a custom detector.`\n );\n }\n detector = BUILT_IN_DETECTORS[builtInType];\n }\n\n return {\n piiType: config.piiType,\n strategy: config.strategy,\n detector,\n };\n}\n\n/**\n * Apply redact strategy: replace with [REDACTED_TYPE]\n */\nfunction applyRedactStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const replacement = `[REDACTED_${piiType.toUpperCase()}]`;\n result =\n result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply mask strategy: partially mask PII (show last few characters)\n */\nfunction applyMaskStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const text = match.text;\n let masked: string;\n\n if (piiType === \"credit_card\") {\n // Show last 4 digits: ****-****-****-1234\n const digits = text.replace(/\\D/g, \"\");\n const last4 = digits.slice(-4);\n masked = `****-****-****-${last4}`;\n } else if (piiType === \"email\") {\n // Show first char and domain: j***@example.com\n const [local, domain] = text.split(\"@\");\n if (local && domain) {\n masked = `${local[0]}***@${domain}`;\n } else {\n masked = \"***\";\n }\n } else {\n // Default: show last 4 characters\n const visibleChars = Math.min(4, text.length);\n masked = `${\"*\".repeat(\n Math.max(0, text.length - visibleChars)\n )}${text.slice(-visibleChars)}`;\n }\n\n result = result.slice(0, match.start) + masked + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply hash strategy: replace with deterministic hash\n */\nfunction applyHashStrategy(\n content: string,\n matches: PIIMatch[],\n piiType: string\n): string {\n let result = content;\n // Process matches in reverse order to preserve indices\n for (let i = matches.length - 1; i >= 0; i--) {\n const match = matches[i];\n const hash = sha256(match.text).slice(0, 8);\n const replacement = `<${piiType}_hash:${hash}>`;\n result =\n result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n return result;\n}\n\n/**\n * Apply strategy to content based on matches\n */\nexport function applyStrategy(\n content: string,\n matches: PIIMatch[],\n strategy: PIIStrategy,\n piiType: string\n): string {\n if (matches.length === 0) {\n return content;\n }\n\n switch (strategy) {\n case \"block\":\n throw new PIIDetectionError(piiType, matches);\n case \"redact\":\n return applyRedactStrategy(content, matches, piiType);\n case \"mask\":\n return applyMaskStrategy(content, matches, piiType);\n case \"hash\":\n return applyHashStrategy(content, matches, piiType);\n default:\n throw new Error(`Unknown strategy: ${strategy}`);\n }\n}\n\n/**\n * Configuration schema for PII middleware\n */\nconst contextSchema = z.object({\n /**\n * Whether to check user messages before model call\n */\n applyToInput: z.boolean().optional(),\n /**\n * Whether to check AI messages after model call\n */\n applyToOutput: z.boolean().optional(),\n /**\n * Whether to check tool result messages after tool execution\n */\n applyToToolResults: z.boolean().optional(),\n});\n\nexport type PIIMiddlewareConfig = InferInteropZodInput<typeof contextSchema>;\n\n/**\n * Process content for PII detection and apply strategy\n */\nfunction processContent(\n content: string,\n rule: ResolvedRedactionRule\n): { content: string; matches: PIIMatch[] } {\n const matches = rule.detector(content);\n if (matches.length === 0) {\n return { content, matches: [] };\n }\n\n const sanitized = applyStrategy(\n content,\n matches,\n rule.strategy,\n rule.piiType\n );\n return { content: sanitized, matches };\n}\n\n/**\n * Creates a middleware that detects and handles personally identifiable information (PII)\n * in conversations.\n *\n * This middleware detects common PII types and applies configurable strategies to handle them.\n * It can detect emails, credit cards, IP addresses, MAC addresses, and URLs in both user input\n * and agent output.\n *\n * Built-in PII types:\n * - `email`: Email addresses\n * - `credit_card`: Credit card numbers (validated with Luhn algorithm)\n * - `ip`: IP addresses (validated)\n * - `mac_address`: MAC addresses\n * - `url`: URLs (both `http`/`https` and bare URLs)\n *\n * Strategies:\n * - `block`: Raise an exception when PII is detected\n * - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders\n * - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)\n * - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)\n *\n * Strategy Selection Guide:\n * | Strategy | Preserves Identity? | Best For |\n * | -------- | ------------------- | --------------------------------------- |\n * | `block` | N/A | Avoid PII completely |\n * | `redact` | No | General compliance, log sanitization |\n * | `mask` | No | Human readability, customer service UIs |\n * | `hash` | Yes (pseudonymous) | Analytics, debugging |\n *\n * @param piiType - Type of PII to detect. Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`, `url`) or a custom type name.\n * @param options - Configuration options\n * @param options.strategy - How to handle detected PII. Defaults to `\"redact\"`.\n * @param options.detector - Custom detector function or regex pattern string. If not provided, uses built-in detector for the `piiType`.\n * @param options.applyToInput - Whether to check user messages before model call. Defaults to `true`.\n * @param options.applyToOutput - Whether to check AI messages after model call. Defaults to `false`.\n * @param options.applyToToolResults - Whether to check tool result messages after tool execution. Defaults to `false`.\n *\n * @returns Middleware instance for use with `createAgent`\n *\n * @throws {PIIDetectionError} When PII is detected and strategy is `'block'`\n * @throws {Error} If `piiType` is not built-in and no detector is provided\n *\n * @example Basic usage\n * ```typescript\n * import { piiMiddleware } from \"langchain\";\n * import { createAgent } from \"langchain\";\n *\n * // Redact all emails in user input\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"email\", { strategy: \"redact\" }),\n * ],\n * });\n * ```\n *\n * @example Different strategies for different PII types\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [\n * piiMiddleware(\"credit_card\", { strategy: \"mask\" }),\n * piiMiddleware(\"url\", { strategy: \"redact\" }),\n * piiMiddleware(\"ip\", { strategy: \"hash\" }),\n * ],\n * });\n * ```\n *\n * @example Custom PII type with regex\n * ```typescript\n * const agent = createAgent({\n * model: \"openai:gpt-4\",\n * middleware: [\n * piiMiddleware(\"api_key\", {\n * detector: \"sk-[a-zA-Z0-9]{32}\",\n * strategy: \"block\",\n * }),\n * ],\n * });\n * ```\n *\n * @public\n */\nexport function piiMiddleware(\n piiType: BuiltInPIIType | string,\n options: {\n strategy?: PIIStrategy;\n detector?: Detector;\n applyToInput?: boolean;\n applyToOutput?: boolean;\n applyToToolResults?: boolean;\n } = {}\n) {\n const { strategy = \"redact\", detector } = options;\n const resolvedRule = resolveRedactionRule({\n piiType,\n strategy,\n detector,\n });\n\n const middlewareName = `PIIMiddleware[${resolvedRule.piiType}]`;\n\n return createMiddleware({\n name: middlewareName,\n contextSchema,\n beforeModel: async (state, runtime) => {\n const applyToInput =\n runtime.context.applyToInput ?? options.applyToInput ?? true;\n const applyToToolResults =\n runtime.context.applyToToolResults ??\n options.applyToToolResults ??\n false;\n\n if (!applyToInput && !applyToToolResults) {\n return;\n }\n\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return;\n }\n\n const newMessages = [...messages];\n let anyModified = false;\n\n // Check user input if enabled\n if (applyToInput) {\n // Get last user message\n let lastUserIdx: number | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (HumanMessage.isInstance(messages[i])) {\n lastUserIdx = i;\n break;\n }\n }\n\n if (lastUserIdx !== null) {\n const lastUserMsg = messages[lastUserIdx];\n if (lastUserMsg && lastUserMsg.content) {\n const content = String(lastUserMsg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length > 0) {\n newMessages[lastUserIdx] = new HumanMessage({\n content: newContent,\n id: lastUserMsg.id,\n name: lastUserMsg.name,\n });\n anyModified = true;\n }\n }\n }\n }\n\n // Check tool results if enabled\n if (applyToToolResults) {\n // Find the last AIMessage, then process all ToolMessage objects after it\n let lastAiIdx: number | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (AIMessage.isInstance(messages[i])) {\n lastAiIdx = i;\n break;\n }\n }\n\n if (lastAiIdx !== null) {\n // Get all tool messages after the last AI message\n for (let i = lastAiIdx + 1; i < messages.length; i++) {\n const msg = messages[i];\n if (ToolMessage.isInstance(msg)) {\n if (!msg.content) {\n continue;\n }\n\n const content = String(msg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length > 0) {\n newMessages[i] = new ToolMessage({\n content: newContent,\n id: msg.id,\n name: msg.name,\n tool_call_id: msg.tool_call_id,\n });\n anyModified = true;\n }\n }\n }\n }\n }\n\n if (anyModified) {\n return { messages: newMessages };\n }\n\n return;\n },\n afterModel: async (state, runtime) => {\n const applyToOutput =\n runtime.context.applyToOutput ?? options.applyToOutput ?? false;\n\n if (!applyToOutput) {\n return;\n }\n\n const messages = state.messages;\n if (!messages || messages.length === 0) {\n return;\n }\n\n // Get last AI message\n let lastAiIdx: number | null = null;\n let lastAiMsg: AIMessage | null = null;\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (AIMessage.isInstance(msg)) {\n lastAiMsg = msg;\n lastAiIdx = i;\n break;\n }\n }\n\n if (lastAiIdx === null || !lastAiMsg || !lastAiMsg.content) {\n return;\n }\n\n // Detect PII in message content\n const content = String(lastAiMsg.content);\n const { content: newContent, matches } = processContent(\n content,\n resolvedRule\n );\n\n if (matches.length === 0) {\n return;\n }\n\n // Create updated message\n const updatedMessage = new AIMessage({\n content: newContent,\n id: lastAiMsg.id,\n name: lastAiMsg.name,\n tool_calls: lastAiMsg.tool_calls,\n });\n\n // Return updated messages\n const newMessages = [...messages];\n newMessages[lastAiIdx] = updatedMessage;\n return { messages: newMessages };\n },\n });\n}\n"],"mappings":";;;;;;;;;;AA4BA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YACE,AAAgB,SAChB,AAAgB,SAChB;AACA,QAAM,iBAAiB,QAAQ,SAAS,QAAQ,OAAO,gBAAgB;EAHvD;EACA;AAGhB,OAAK,OAAO;;;;;;AAuDhB,MAAM,gBAAgB;;;;AAKtB,MAAM,sBAAsB;;;;AAK5B,MAAM,aACJ;;;;AAKF,MAAM,sBAAsB;;;;AAK5B,MAAM,cAAc;;;;AAKpB,SAAS,UAAU,YAA6B;CAC9C,MAAM,SAAS,WAAW,QAAQ,OAAO,GAAG;CAC5C,IAAI,MAAM;CACV,IAAI,SAAS;AAEb,MAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;EAC3C,IAAI,QAAQ,SAAS,OAAO,IAAI,GAAG;AAEnC,MAAI,QAAQ;AACV,YAAS;AACT,OAAI,QAAQ,EACV,UAAS;;AAIb,SAAO;AACP,WAAS,CAAC;;AAGZ,QAAO,MAAM,OAAO;;;;;AAMtB,SAAS,qBAAqB,OAAmC;AAC/D,QAAO;EACL,MAAM,MAAM;EACZ,OAAO,MAAM,SAAS;EACtB,MAAM,MAAM,SAAS,KAAK,MAAM,GAAG;EACpC;;;;;AAMH,SAAgB,YAAY,SAA6B;CACvD,MAAM,UAAsB,EAAE;CAC9B,MAAM,QAAQ,IAAI,OAAO,cAAc;CACvC,IAAI;AAEJ,SAAQ,QAAQ,MAAM,KAAK,QAAQ,MAAM,KACvC,SAAQ,KAAK,qBAAqB,MAAM,CAAC;AAG3C,QAAO;;;;;AAMT,SAAgB,iBA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AQ,EAGvC,aACD;AAED,OAAI,QAAQ,WAAW,EACrB;GAIF,MAAM,iBAAiB,IAAIA,mCAAU;IACnC,SAAS;IACT,IAAI,UAAU;IACd,MAAM,UAAU;IAChB,YAAY,UAAU;IACvB,CAAC;GAGF,MAAM,cAAc,CAAC,GAAG,SAAS;AACjC,eAAY,aAAa;AACzB,UAAO,EAAE,UAAU,aAAa;;EAEnC,CAAC"}
@@ -1,4 +1,5 @@
1
- import { createMiddleware } from "../middleware.cjs";
1
+ import { AgentMiddleware } from "./types.cjs";
2
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
2
3
  import { InferInteropZodInput } from "@langchain/core/utils/types";
3
4
  import { z } from "zod/v3";
4
5
 
@@ -209,7 +210,32 @@ declare function piiMiddleware(piiType: BuiltInPIIType | string, options?: {
209
210
  applyToInput?: boolean;
210
211
  applyToOutput?: boolean;
211
212
  applyToToolResults?: boolean;
212
- }): ReturnType<typeof createMiddleware>;
213
+ }): AgentMiddleware<undefined, z.ZodObject<{
214
+ /**
215
+ * Whether to check user messages before model call
216
+ */
217
+ applyToInput: z.ZodOptional<z.ZodBoolean>;
218
+ /**
219
+ * Whether to check AI messages after model call
220
+ */
221
+ applyToOutput: z.ZodOptional<z.ZodBoolean>;
222
+ /**
223
+ * Whether to check tool result messages after tool execution
224
+ */
225
+ applyToToolResults: z.ZodOptional<z.ZodBoolean>;
226
+ }, "strip", z.ZodTypeAny, {
227
+ applyToInput?: boolean | undefined;
228
+ applyToOutput?: boolean | undefined;
229
+ applyToToolResults?: boolean | undefined;
230
+ }, {
231
+ applyToInput?: boolean | undefined;
232
+ applyToOutput?: boolean | undefined;
233
+ applyToToolResults?: boolean | undefined;
234
+ }>, {
235
+ applyToInput?: boolean | undefined;
236
+ applyToOutput?: boolean | undefined;
237
+ applyToToolResults?: boolean | undefined;
238
+ }, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
213
239
  //#endregion
214
240
  export { BuiltInPIIType, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIStrategy, RedactionRuleConfig, ResolvedRedactionRule, applyStrategy, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, piiMiddleware, resolveRedactionRule };
215
241
  //# sourceMappingURL=pii.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pii.d.cts","names":[],"sources":["../../../src/agents/middleware/pii.ts"],"mappings":";;;;;;;AAUA;UAAiB,QAAA;;;;EAIf,IAAA;EAQA;;;EAJA,KAAA;EAU6B;;;EAN7B,GAAA;AAAA;;;;cAMW,iBAAA,SAA0B,KAAA;EAAA,SAEnB,OAAA;EAAA,SACA,OAAA,EAAS,QAAA;EAF3B,WAAA,CACkB,OAAA,UACA,OAAA,EAAS,QAAA;AAAA;;;;KAUjB,WAAA;AAAZ;;;AAAA,KAKY,cAAA;;AAAZ;;KAUY,WAAA,IAAe,OAAA,aAAoB,QAAA;AAAA,KACnC,QAAA,GAAW,WAAA,GAAc,MAAA;;AADrC;;UAMiB,mBAAA;EANU;;AAC3B;EASE,OAAA,EAAS,cAAA;;;;EAIT,QAAA,EAAU,WAAA;EARwB;;;EAYlC,QAAA,GAAW,QAAA;AAAA;;;;UAMI,qBAAA;EACf,OAAA;EACA,QAAA,EAAU,WAAA;EACV,QAAA,EAAU,WAAA;AAAA;;;AAHZ;iBAuEgB,WAAA,CAAY,OAAA,WAAkB,QAAA;;;;iBAe9B,gBAAA,CAAiB,OAAA,WAAkB,QAAA;;;;iBAuBnC,QAAA,CAAS,OAAA,WAAkB,QAAA;;AAtC3C;;iBAgEgB,gBAAA,CAAiB,OAAA,WAAkB,QAAA;;;AAjDnD;iBAgEgB,SAAA,CAAU,OAAA,WAAkB,QAAA;;;;iBA0B5B,oBAAA,CACd,MAAA,EAAQ,mBAAA,GACP,qBAAA;;;;iBA2Ia,aAAA,CACd,OAAA,UACA,OAAA,EAAS,QAAA,IACT,QAAA,EAAU,WAAA,EACV,OAAA;AA1LF;;;AAAA,cAiNM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AAA,CAAU,OAAA,WAAkB,QAAA;AAhE5C;;;AAAA,iBA0FgB,oBAAA,CACd,MAAA,EAAQ,mBAAA,GACP,qBAAA;;AArEH;;iBAgNgB,aAAA,CACd,OAAA,UACA,OAAA,EAAS,QAAA,IACT,QAAA,EAAU,WAAA,EACV,OAAA;;;AA1LF;cAiNM,aAAA,EAAa,CAAA,CAAA,SAAA;;;;;EAlMM;;;;EA0BT;;;;;;;;;;;;;KAuLJ,mBAAA,GAAsB,oBAAA,QAA4B,aAAA;;;;;;;;AApB7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBD;;;;;AA0GA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,aAAA,CACd,OAAA,EAAS,cAAA,WACT,OAAA;EACE,QAAA,GAAW,WAAA;EACX,QAAA,GAAW,QAAA;EACX,YAAA;EACA,aAAA;EACA,kBAAA;AAAA,+BACI,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;aAAA,sBAAA,CAAA,UAAA"}
@@ -1,4 +1,5 @@
1
- import { createMiddleware } from "../middleware.js";
1
+ import { AgentMiddleware } from "./types.js";
2
+ import * as _langchain_core_tools0 from "@langchain/core/tools";
2
3
  import { InferInteropZodInput } from "@langchain/core/utils/types";
3
4
  import { z } from "zod/v3";
4
5
 
@@ -209,7 +210,32 @@ declare function piiMiddleware(piiType: BuiltInPIIType | string, options?: {
209
210
  applyToInput?: boolean;
210
211
  applyToOutput?: boolean;
211
212
  applyToToolResults?: boolean;
212
- }): ReturnType<typeof createMiddleware>;
213
+ }): AgentMiddleware<undefined, z.ZodObject<{
214
+ /**
215
+ * Whether to check user messages before model call
216
+ */
217
+ applyToInput: z.ZodOptional<z.ZodBoolean>;
218
+ /**
219
+ * Whether to check AI messages after model call
220
+ */
221
+ applyToOutput: z.ZodOptional<z.ZodBoolean>;
222
+ /**
223
+ * Whether to check tool result messages after tool execution
224
+ */
225
+ applyToToolResults: z.ZodOptional<z.ZodBoolean>;
226
+ }, "strip", z.ZodTypeAny, {
227
+ applyToInput?: boolean | undefined;
228
+ applyToOutput?: boolean | undefined;
229
+ applyToToolResults?: boolean | undefined;
230
+ }, {
231
+ applyToInput?: boolean | undefined;
232
+ applyToOutput?: boolean | undefined;
233
+ applyToToolResults?: boolean | undefined;
234
+ }>, {
235
+ applyToInput?: boolean | undefined;
236
+ applyToOutput?: boolean | undefined;
237
+ applyToToolResults?: boolean | undefined;
238
+ }, readonly (_langchain_core_tools0.ServerTool | _langchain_core_tools0.ClientTool)[]>;
213
239
  //#endregion
214
240
  export { BuiltInPIIType, PIIDetectionError, PIIDetector, PIIMatch, PIIMiddlewareConfig, PIIStrategy, RedactionRuleConfig, ResolvedRedactionRule, applyStrategy, detectCreditCard, detectEmail, detectIP, detectMacAddress, detectUrl, piiMiddleware, resolveRedactionRule };
215
241
  //# sourceMappingURL=pii.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pii.d.ts","names":[],"sources":["../../../src/agents/middleware/pii.ts"],"mappings":";;;;;;;AAUA;UAAiB,QAAA;;;;EAIf,IAAA;EAQA;;;EAJA,KAAA;EAU6B;;;EAN7B,GAAA;AAAA;;;;cAMW,iBAAA,SAA0B,KAAA;EAAA,SAEnB,OAAA;EAAA,SACA,OAAA,EAAS,QAAA;EAF3B,WAAA,CACkB,OAAA,UACA,OAAA,EAAS,QAAA;AAAA;;;;KAUjB,WAAA;AAAZ;;;AAAA,KAKY,cAAA;;AAAZ;;KAUY,WAAA,IAAe,OAAA,aAAoB,QAAA;AAAA,KACnC,QAAA,GAAW,WAAA,GAAc,MAAA;;AADrC;;UAMiB,mBAAA;EANU;;AAC3B;EASE,OAAA,EAAS,cAAA;;;;EAIT,QAAA,EAAU,WAAA;EARwB;;;EAYlC,QAAA,GAAW,QAAA;AAAA;;;;UAMI,qBAAA;EACf,OAAA;EACA,QAAA,EAAU,WAAA;EACV,QAAA,EAAU,WAAA;AAAA;;;AAHZ;iBAuEgB,WAAA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EAUrB,OAAA,EAAS,cAAA;EATC;;;EAaV,QAAA,EAAU,WAAA;EAb+B;AAK3C;;EAYE,QAAA,GAAW,QAAA;AAAA;;;;UAMI,qBAAA;EACf,OAAA;EACA,QAAA,EAAU,WAAA;EACV,QAAA,EAAU,WAAA;AAAA;;;;iBAoEI,WAAA,CAAY,OAAA,WAAkB,QAAA;AAvE9C;;;AAAA,iBAsFgB,gBAAA,CAAiB,OAAA,WAAkB,QAAA;;;;iBAuBnC,QAAA,CAAS,OAAA,WAAkB,QAAA;;;;iBA0B3B,gBAAA,CAAiB,OAAA,WAAkB,QAAA;;;;iBAenC,SAAA,CAAU,OAAA,WAAkB,QAAA;AAhE5C;;;AAAA,iBA0FgB,oBAAA,CACd,MAAA,EAAQ,mBAAA,GACP,qBAAA;;AArEH;;iBAgNgB,aAAA,CACd,OAAA,UACA,OAAA,EAAS,QAAA,IACT,QAAA,EAAU,WAAA,EACV,OAAA;;;AA1LF;cAiNM,aAAA,EAAa,CAAA,CAAA,SAAA;;;;;EAlMM;;;;EA0BT;;;;;;;;;;;;;KAuLJ,mBAAA,GAAsB,oBAAA,QAA4B,aAAA;;;;;;;;AApB7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBD;;;;;AA0GA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAAgB,aAAA,CACd,OAAA,EAAS,cAAA,WACT,OAAA;EACE,QAAA,GAAW,WAAA;EACX,QAAA,GAAW,QAAA;EACX,YAAA;EACA,aAAA;EACA,kBAAA;AAAA,+BACI,CAAA,CAAA,SAAA;;;;;;;;;;;;;;;;;;;;;;;;;aAAA,sBAAA,CAAA,UAAA"}
@@ -399,10 +399,13 @@ function piiMiddleware(piiType, options = {}) {
399
399
  if (!messages || messages.length === 0) return;
400
400
  let lastAiIdx = null;
401
401
  let lastAiMsg = null;
402
- for (let i = messages.length - 1; i >= 0; i--) if (AIMessage.isInstance(messages[i])) {
403
- lastAiMsg = messages[i];
404
- lastAiIdx = i;
405
- break;
402
+ for (let i = messages.length - 1; i >= 0; i--) {
403
+ const msg = messages[i];
404
+ if (AIMessage.isInstance(msg)) {
405
+ lastAiMsg = msg;
406
+ lastAiIdx = i;
407
+ break;
408
+ }
406
409
  }
407
410
  if (lastAiIdx === null || !lastAiMsg || !lastAiMsg.content) return;
408
411
  const { content: newContent, matches } = processContent(String(lastAiMsg.content), resolvedRule);