langchain 1.2.0 → 2.0.0-dev-1765937705265

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 (104) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/agents/ReactAgent.cjs +28 -0
  3. package/dist/agents/ReactAgent.cjs.map +1 -1
  4. package/dist/agents/ReactAgent.d.cts +50 -14
  5. package/dist/agents/ReactAgent.d.cts.map +1 -1
  6. package/dist/agents/ReactAgent.d.ts +50 -14
  7. package/dist/agents/ReactAgent.d.ts.map +1 -1
  8. package/dist/agents/ReactAgent.js +28 -0
  9. package/dist/agents/ReactAgent.js.map +1 -1
  10. package/dist/agents/index.cjs.map +1 -1
  11. package/dist/agents/index.d.cts +41 -29
  12. package/dist/agents/index.d.cts.map +1 -1
  13. package/dist/agents/index.d.ts +41 -29
  14. package/dist/agents/index.d.ts.map +1 -1
  15. package/dist/agents/index.js.map +1 -1
  16. package/dist/agents/middleware/contextEditing.d.cts +2 -1
  17. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  18. package/dist/agents/middleware/contextEditing.d.ts +2 -1
  19. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  20. package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -1
  21. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
  22. package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -1
  23. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  24. package/dist/agents/middleware/hitl.d.cts +9 -1
  25. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  26. package/dist/agents/middleware/hitl.d.ts +9 -1
  27. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  28. package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
  29. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  30. package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
  31. package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
  32. package/dist/agents/middleware/modelCallLimit.d.cts +6 -1
  33. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
  34. package/dist/agents/middleware/modelCallLimit.d.ts +6 -1
  35. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
  36. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +7 -1
  37. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
  38. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +7 -1
  39. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
  40. package/dist/agents/middleware/summarization.d.cts +30 -7
  41. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  42. package/dist/agents/middleware/summarization.d.ts +30 -7
  43. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  44. package/dist/agents/middleware/todoListMiddleware.d.cts +42 -1
  45. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  46. package/dist/agents/middleware/todoListMiddleware.d.ts +42 -1
  47. package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
  48. package/dist/agents/middleware/toolCallLimit.d.cts +2 -1
  49. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  50. package/dist/agents/middleware/toolCallLimit.d.ts +2 -1
  51. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  52. package/dist/agents/middleware/types.cjs.map +1 -1
  53. package/dist/agents/middleware/types.d.cts +125 -32
  54. package/dist/agents/middleware/types.d.cts.map +1 -1
  55. package/dist/agents/middleware/types.d.ts +125 -32
  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/middleware.cjs +1 -1
  59. package/dist/agents/middleware.cjs.map +1 -1
  60. package/dist/agents/middleware.d.cts +4 -4
  61. package/dist/agents/middleware.d.cts.map +1 -1
  62. package/dist/agents/middleware.d.ts +4 -4
  63. package/dist/agents/middleware.d.ts.map +1 -1
  64. package/dist/agents/middleware.js +1 -1
  65. package/dist/agents/middleware.js.map +1 -1
  66. package/dist/agents/types.d.cts +254 -8
  67. package/dist/agents/types.d.cts.map +1 -1
  68. package/dist/agents/types.d.ts +254 -8
  69. package/dist/agents/types.d.ts.map +1 -1
  70. package/dist/index.d.cts +3 -3
  71. package/dist/index.d.ts +3 -3
  72. package/package.json +5 -5
  73. package/chat_models/universal.cjs +0 -1
  74. package/chat_models/universal.d.cts +0 -1
  75. package/chat_models/universal.d.ts +0 -1
  76. package/chat_models/universal.js +0 -1
  77. package/hub/node.cjs +0 -1
  78. package/hub/node.d.cts +0 -1
  79. package/hub/node.d.ts +0 -1
  80. package/hub/node.js +0 -1
  81. package/hub.cjs +0 -1
  82. package/hub.d.cts +0 -1
  83. package/hub.d.ts +0 -1
  84. package/hub.js +0 -1
  85. package/load/serializable.cjs +0 -1
  86. package/load/serializable.d.cts +0 -1
  87. package/load/serializable.d.ts +0 -1
  88. package/load/serializable.js +0 -1
  89. package/load.cjs +0 -1
  90. package/load.d.cts +0 -1
  91. package/load.d.ts +0 -1
  92. package/load.js +0 -1
  93. package/storage/encoder_backed.cjs +0 -1
  94. package/storage/encoder_backed.d.cts +0 -1
  95. package/storage/encoder_backed.d.ts +0 -1
  96. package/storage/encoder_backed.js +0 -1
  97. package/storage/file_system.cjs +0 -1
  98. package/storage/file_system.d.cts +0 -1
  99. package/storage/file_system.d.ts +0 -1
  100. package/storage/file_system.js +0 -1
  101. package/storage/in_memory.cjs +0 -1
  102. package/storage/in_memory.d.cts +0 -1
  103. package/storage/in_memory.d.ts +0 -1
  104. package/storage/in_memory.js +0 -1
@@ -1,4 +1,8 @@
1
1
  import { AgentMiddleware } from "./types.js";
2
+ import * as _langchain_core_messages26 from "@langchain/core/messages";
3
+ import { ToolMessage } from "@langchain/core/messages";
4
+ import * as _langchain_core_tools11 from "@langchain/core/tools";
5
+ import { Command } from "@langchain/langgraph";
2
6
  import { z } from "zod/v3";
3
7
 
4
8
  //#region src/agents/middleware/todoListMiddleware.d.ts
@@ -69,7 +73,44 @@ declare function todoListMiddleware(options?: TodoListMiddlewareOptions): AgentM
69
73
  content: string;
70
74
  status: "completed" | "in_progress" | "pending";
71
75
  }[] | undefined;
72
- }>, undefined, any>;
76
+ }>, undefined, unknown, readonly [_langchain_core_tools11.DynamicStructuredTool<z.ZodObject<{
77
+ todos: z.ZodArray<z.ZodObject<{
78
+ content: z.ZodString;
79
+ status: z.ZodEnum<["pending", "in_progress", "completed"]>;
80
+ }, "strip", z.ZodTypeAny, {
81
+ content: string;
82
+ status: "completed" | "in_progress" | "pending";
83
+ }, {
84
+ content: string;
85
+ status: "completed" | "in_progress" | "pending";
86
+ }>, "many">;
87
+ }, "strip", z.ZodTypeAny, {
88
+ todos: {
89
+ content: string;
90
+ status: "completed" | "in_progress" | "pending";
91
+ }[];
92
+ }, {
93
+ todos: {
94
+ content: string;
95
+ status: "completed" | "in_progress" | "pending";
96
+ }[];
97
+ }>, {
98
+ todos: {
99
+ content: string;
100
+ status: "completed" | "in_progress" | "pending";
101
+ }[];
102
+ }, {
103
+ todos: {
104
+ content: string;
105
+ status: "completed" | "in_progress" | "pending";
106
+ }[];
107
+ }, Command<unknown, {
108
+ todos: {
109
+ content: string;
110
+ status: "completed" | "in_progress" | "pending";
111
+ }[];
112
+ messages: ToolMessage<_langchain_core_messages26.MessageStructure<_langchain_core_messages26.MessageToolSet>>[];
113
+ }, string>, "write_todos">]>;
73
114
  //#endregion
74
115
  export { TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT, TodoListMiddlewareOptions, todoListMiddleware };
75
116
  //# sourceMappingURL=todoListMiddleware.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"todoListMiddleware.d.ts","names":["z","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","__types_js12","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nexport declare const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = \"## `write_todos`\\n\\nYou have access to the `write_todos` tool to help you manage and plan complex objectives. \\nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\\n\\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\\n\\n## Important To-Do List Usage Notes to Remember\\n- The `write_todos` tool should never be called multiple times in parallel.\\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, any>;\nexport {};\n//# sourceMappingURL=todoListMiddleware.d.ts.map"],"mappings":";;;;cACqBC,kCAAAA;UAwBJU,yBAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA6COC,kBAAAA,WAA6BD,4CAAiEX,CAAAA,CAAEM;SAC7GN,CAAAA,CAAEQ,WAAWR,CAAAA,CAAEO,SAASP,CAAAA,CAAEM;aACpBN,CAAAA,CAAEG;YACHH,CAAAA,CAAEI;cACFJ,CAAAA,CAAEK;;;;;;;YAONL,CAAAA,CAAEK"}
1
+ {"version":3,"file":"todoListMiddleware.d.ts","names":["_langchain_core_tools11","__types_js13","z","Command","ToolMessage","TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT","stateSchema","ZodString","ZodEnum","ZodTypeAny","ZodObject","ZodArray","ZodDefault","TodoMiddlewareState","infer","TodoListMiddlewareOptions","todoListMiddleware","_langchain_core_messages26","MessageToolSet","MessageStructure","DynamicStructuredTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/todoListMiddleware.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport { Command } from \"@langchain/langgraph\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nexport declare const TODO_LIST_MIDDLEWARE_SYSTEM_PROMPT = \"## `write_todos`\\n\\nYou have access to the `write_todos` tool to help you manage and plan complex objectives. \\nUse this tool for complex objectives to ensure that you are tracking each necessary step and giving the user visibility into your progress.\\nThis tool is very helpful for planning complex objectives, and for breaking down these larger complex objectives into smaller steps.\\n\\nIt is critical that you mark todos as completed as soon as you are done with a step. Do not batch up multiple steps before marking them as completed.\\nFor simple objectives that only require a few steps, it is better to just complete the objective directly and NOT use this tool.\\nWriting todos takes time and tokens, use it when it is helpful for managing complex many-step problems! But not for simple few-step requests.\\n\\n## Important To-Do List Usage Notes to Remember\\n- The `write_todos` tool should never be called multiple times in parallel.\\n- Don't be afraid to revise the To-Do list as you go. New information may reveal new tasks that need to be done, or old tasks that are irrelevant.\";\ndeclare const stateSchema: z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>;\nexport type TodoMiddlewareState = z.infer<typeof stateSchema>;\nexport interface TodoListMiddlewareOptions {\n /**\n * Custom system prompt to guide the agent on using the todo tool.\n * If not provided, uses the default {@link PLANNING_MIDDLEWARE_SYSTEM_PROMPT}.\n */\n systemPrompt?: string;\n /**\n * Custom description for the {@link writeTodos} tool.\n * If not provided, uses the default {@link WRITE_TODOS_DESCRIPTION}.\n */\n toolDescription?: string;\n}\n/**\n * Creates a middleware that provides todo list management capabilities to agents.\n *\n * This middleware adds a `write_todos` tool that allows agents to create and manage\n * structured task lists for complex multi-step operations. It's designed to help\n * agents track progress, organize complex tasks, and provide users with visibility\n * into task completion status.\n *\n * The middleware automatically injects system prompts that guide the agent on when\n * and how to use the todo functionality effectively.\n *\n * @example\n * ```typescript\n * import { todoListMiddleware, createAgent } from 'langchain';\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [todoListMiddleware()],\n * });\n *\n * // Agent now has access to write_todos tool and todo state tracking\n * const result = await agent.invoke({\n * messages: [new HumanMessage(\"Help me refactor my codebase\")]\n * });\n *\n * console.log(result.todos); // Array of todo items with status tracking\n * ```\n *\n * @returns A configured middleware instance that provides todo management capabilities\n *\n * @see {@link TodoMiddlewareState} for the state schema\n * @see {@link writeTodos} for the tool implementation\n */\nexport declare function todoListMiddleware(options?: TodoListMiddlewareOptions): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n todos: z.ZodDefault<z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">>;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos?: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[] | undefined;\n}>, undefined, unknown, readonly [import(\"@langchain/core/tools\").DynamicStructuredTool<z.ZodObject<{\n todos: z.ZodArray<z.ZodObject<{\n content: z.ZodString;\n status: z.ZodEnum<[\"pending\", \"in_progress\", \"completed\"]>;\n }, \"strip\", z.ZodTypeAny, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }, {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }>, \"many\">;\n}, \"strip\", z.ZodTypeAny, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}>, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n}, Command<unknown, {\n todos: {\n content: string;\n status: \"completed\" | \"in_progress\" | \"pending\";\n }[];\n messages: ToolMessage<import(\"@langchain/core/messages\").MessageStructure<import(\"@langchain/core/messages\").MessageToolSet>>[];\n}, string>, \"write_todos\">]>;\nexport {};\n//# sourceMappingURL=todoListMiddleware.d.ts.map"],"mappings":";;;;;;;;cAGqBK,kCAAAA;AA0F8EY,UAlElFF,yBAAAA,CAsGgGG;EAAcD;;;;;EAzDV;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAA7FD,kBAAAA,WAA6BD,4CAAiEb,CAAAA,CAAEQ;SAC7GR,CAAAA,CAAEU,WAAWV,CAAAA,CAAES,SAAST,CAAAA,CAAEQ;aACpBR,CAAAA,CAAEK;YACHL,CAAAA,CAAEM;cACFN,CAAAA,CAAEO;;;;;;;YAONP,CAAAA,CAAEO;;;;;;;;;;kCAyCJT,uBAAAA,CA/BwDoB,sBAAsBlB,CAAAA,CAAEQ;SAC/ER,CAAAA,CAAES,SAAST,CAAAA,CAAEQ;aACPR,CAAAA,CAAEK;YACHL,CAAAA,CAAEM;cACFN,CAAAA,CAAEO;;;;;;;YAONP,CAAAA,CAAEO;;;;;;;;;;;;;;;;;;;;GAoBXN;;;;;YAKWC,YAAiHa,0BAAAA,CAAlEE,iBApCsCF,0BAAAA,CAoCcC,cAAAA"}
@@ -1,4 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.cjs";
2
+ import * as _langchain_core_tools7 from "@langchain/core/tools";
2
3
  import { InferInteropZodInput } from "@langchain/core/utils/types";
3
4
  import { z } from "zod/v3";
4
5
 
@@ -163,7 +164,7 @@ declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): AgentMid
163
164
  }, {
164
165
  threadToolCallCount?: Record<string, number> | undefined;
165
166
  runToolCallCount?: Record<string, number> | undefined;
166
- }>, undefined, any>;
167
+ }>, undefined, unknown, readonly (_langchain_core_tools7.ServerTool | _langchain_core_tools7.ClientTool)[]>;
167
168
  //#endregion
168
169
  export { ToolCallLimitConfig, ToolCallLimitExceededError, toolCallLimitMiddleware };
169
170
  //# sourceMappingURL=toolCallLimit.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"toolCallLimit.d.cts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js11","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAIgBM,cA9BKJ,0BAAAA,SAAmCC,KAAK,CA8B7CG;EAKiBC;;;EAKjBD,WAAAA,EAAAA,MAAAA;EAWiBE;;;EAzBkBG,QAAAA,EAAAA,MAAAA;EAAS;AAqC5D;AAiFA;EAAyDC,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACLP;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACsBJ;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACVC,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAHwGC,cAtHjGP,0BAsHiGO,EAtHrEX,CAAAA,CAAEW,SAsHmEA,CAAAA;;AAAH;;YAlHrGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;;;;;eAKbL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA"}
1
+ {"version":3,"file":"toolCallLimit.d.cts","names":["__types_js11","z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","_langchain_core_tools7","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;;;AAQA;AA0BA;AAI8BM,cA9BTH,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAdC;;;EAUcC,WAAAA,EAAAA,MAAAA;EAAdD;;;EAYFI,QAAAA,EAAAA,MAAAA;EA1BqCC;AAAS;AAqC5D;EAiFwBE,WAAAA,EAAAA,MAAAA,GAAAA,SAAuB;EAAUD;;;EACjBE,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL;;;EACUK,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAMDM,cA9HFX,0BA8HEW,EA9H0Bf,CAAAA,CAAEW,SA8H5BI,CAAAA;EAR+FJ;;;YAlHxGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;EAkHqF;;;;eA7GlGL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA;kCARwGC,sBAAAA,CAS7DC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
@@ -1,4 +1,5 @@
1
1
  import { AgentMiddleware } from "./types.js";
2
+ import * as _langchain_core_tools7 from "@langchain/core/tools";
2
3
  import { z } from "zod/v3";
3
4
  import { InferInteropZodInput } from "@langchain/core/utils/types";
4
5
 
@@ -163,7 +164,7 @@ declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): AgentMid
163
164
  }, {
164
165
  threadToolCallCount?: Record<string, number> | undefined;
165
166
  runToolCallCount?: Record<string, number> | undefined;
166
- }>, undefined, any>;
167
+ }>, undefined, unknown, readonly (_langchain_core_tools7.ServerTool | _langchain_core_tools7.ClientTool)[]>;
167
168
  //#endregion
168
169
  export { ToolCallLimitConfig, ToolCallLimitExceededError, toolCallLimitMiddleware };
169
170
  //# sourceMappingURL=toolCallLimit.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"toolCallLimit.d.ts","names":["z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","__types_js11","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, any>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;AAQA;AA0BA;;AAIgBM,cA9BKJ,0BAAAA,SAAmCC,KAAK,CA8B7CG;EAKiBC;;;EAKjBD,WAAAA,EAAAA,MAAAA;EAWiBE;;;EAzBkBG,QAAAA,EAAAA,MAAAA;EAAS;AAqC5D;AAiFA;EAAyDC,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACLP;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACsBJ;;;EAAzBI,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EACVC,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAHwGC,cAtHjGP,0BAsHiGO,EAtHrEX,CAAAA,CAAEW,SAsHmEA,CAAAA;;AAAH;;YAlHrGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;;;;;eAKbL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA"}
1
+ {"version":3,"file":"toolCallLimit.d.ts","names":["__types_js11","z","InferInteropZodInput","ToolCallLimitExceededError","Error","ToolCallLimitOptionsSchema","ZodString","ZodOptional","ZodNumber","ZodEnum","ZodDefault","ZodTypeAny","ZodObject","ToolCallLimitConfig","toolCallLimitMiddleware","ZodRecord","Record","_langchain_core_tools7","ServerTool","ClientTool","AgentMiddleware"],"sources":["../../../src/agents/middleware/toolCallLimit.d.ts"],"sourcesContent":["import { z } from \"zod/v3\";\nimport type { InferInteropZodInput } from \"@langchain/core/utils/types\";\n/**\n * Exception raised when tool call limits are exceeded.\n *\n * This exception is raised when the configured exit behavior is 'error'\n * and either the thread or run tool call limit has been exceeded.\n */\nexport declare class ToolCallLimitExceededError extends Error {\n /**\n * Current thread tool call count.\n */\n threadCount: number;\n /**\n * Current run tool call count.\n */\n runCount: number;\n /**\n * Thread tool call limit (if set).\n */\n threadLimit: number | undefined;\n /**\n * Run tool call limit (if set).\n */\n runLimit: number | undefined;\n /**\n * Tool name being limited (if specific tool), or undefined for all tools.\n */\n toolName: string | undefined;\n constructor(threadCount: number, runCount: number, threadLimit: number | undefined, runLimit: number | undefined, toolName?: string | undefined);\n}\n/**\n * Options for configuring the Tool Call Limit middleware.\n */\nexport declare const ToolCallLimitOptionsSchema: z.ZodObject<{\n /**\n * Name of the specific tool to limit. If undefined, limits apply to all tools.\n */\n toolName: z.ZodOptional<z.ZodString>;\n /**\n * Maximum number of tool calls allowed per thread.\n * undefined means no limit.\n */\n threadLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * Maximum number of tool calls allowed per run.\n * undefined means no limit.\n */\n runLimit: z.ZodOptional<z.ZodNumber>;\n /**\n * What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately, injecting a ToolMessage and an AI message\n * for the single tool call that exceeded the limit. Raises NotImplementedError\n * if there are multiple tool calls.\n *\n * @default \"continue\"\n */\n exitBehavior: z.ZodDefault<z.ZodEnum<[\"continue\", \"error\", \"end\"]>>;\n}, \"strip\", z.ZodTypeAny, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior: \"continue\" | \"end\" | \"error\";\n}, {\n toolName?: string | undefined;\n threadLimit?: number | undefined;\n runLimit?: number | undefined;\n exitBehavior?: \"continue\" | \"end\" | \"error\" | undefined;\n}>;\nexport type ToolCallLimitConfig = InferInteropZodInput<typeof ToolCallLimitOptionsSchema>;\n/**\n * Middleware that tracks tool call counts and enforces limits.\n *\n * This middleware monitors the number of tool calls made during agent execution\n * and can terminate the agent when specified limits are reached. It supports\n * both thread-level and run-level call counting with configurable exit behaviors.\n *\n * Thread-level: The middleware counts all tool calls in the entire message history\n * and persists this count across multiple runs (invocations) of the agent.\n *\n * Run-level: The middleware counts tool calls made after the last HumanMessage,\n * representing the current run (invocation) of the agent.\n *\n * @param options - Configuration options for the middleware\n * @param options.toolName - Name of the specific tool to limit. If undefined, limits apply to all tools.\n * @param options.threadLimit - Maximum number of tool calls allowed per thread. undefined means no limit.\n * @param options.runLimit - Maximum number of tool calls allowed per run. undefined means no limit.\n * @param options.exitBehavior - What to do when limits are exceeded.\n * - \"continue\": Block exceeded tools with error messages, let other tools continue. Model decides when to end. (default)\n * - \"error\": Raise a ToolCallLimitExceededError exception\n * - \"end\": Stop execution immediately with a ToolMessage + AI message for the single tool call that exceeded the limit. Raises NotImplementedError if there are multiple tool calls.\n *\n * @throws {Error} If both limits are undefined, if exitBehavior is invalid, or if runLimit exceeds threadLimit.\n * @throws {NotImplementedError} If exitBehavior is \"end\" and there are multiple tool calls.\n *\n * @example Continue execution with blocked tools (default)\n * ```ts\n * import { toolCallLimitMiddleware } from \"@langchain/langchain/agents/middleware\";\n * import { createAgent } from \"@langchain/langchain/agents\";\n *\n * // Block exceeded tools but let other tools and model continue\n * const limiter = toolCallLimitMiddleware({\n * threadLimit: 20,\n * runLimit: 10,\n * exitBehavior: \"continue\", // default\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Stop immediately when limit exceeded\n * ```ts\n * // End execution immediately with an AI message\n * const limiter = toolCallLimitMiddleware({\n * runLimit: 5,\n * exitBehavior: \"end\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n * ```\n *\n * @example Raise exception on limit\n * ```ts\n * // Strict limit with exception handling\n * const limiter = toolCallLimitMiddleware({\n * toolName: \"search\",\n * threadLimit: 5,\n * exitBehavior: \"error\"\n * });\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * middleware: [limiter]\n * });\n *\n * try {\n * const result = await agent.invoke({ messages: [new HumanMessage(\"Task\")] });\n * } catch (error) {\n * if (error instanceof ToolCallLimitExceededError) {\n * console.log(`Search limit exceeded: ${error}`);\n * }\n * }\n * ```\n */\nexport declare function toolCallLimitMiddleware(options: ToolCallLimitConfig): import(\"./types.js\").AgentMiddleware<z.ZodObject<{\n threadToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n runToolCallCount: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNumber>>;\n}, \"strip\", z.ZodTypeAny, {\n threadToolCallCount: Record<string, number>;\n runToolCallCount: Record<string, number>;\n}, {\n threadToolCallCount?: Record<string, number> | undefined;\n runToolCallCount?: Record<string, number> | undefined;\n}>, undefined, unknown, readonly (import(\"@langchain/core/tools\").ServerTool | import(\"@langchain/core/tools\").ClientTool)[]>;\n//# sourceMappingURL=toolCallLimit.d.ts.map"],"mappings":";;;;;;;;;;;AAQA;AA0BA;AAI8BM,cA9BTH,0BAAAA,SAAmCC,KAAK,CA8B/BE;EAAdC;;;EAUcC,WAAAA,EAAAA,MAAAA;EAAdD;;;EAYFI,QAAAA,EAAAA,MAAAA;EA1BqCC;AAAS;AAqC5D;EAiFwBE,WAAAA,EAAAA,MAAAA,GAAAA,SAAuB;EAAUD;;;EACjBE,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL;;;EACUK,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA;EAAbL,WAAAA,CAAAA,WAAAA,EAAAA,MAAAA,EAAAA,QAAAA,EAAAA,MAAAA,EAAAA,WAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,EAAAA,MAAAA,GAAAA,SAAAA,EAAAA,QAAAA,CAAAA,EAAAA,MAAAA,GAAAA,SAAAA;;;;;AAMDM,cA9HFX,0BA8HEW,EA9H0Bf,CAAAA,CAAEW,SA8H5BI,CAAAA;EAR+FJ;;;YAlHxGX,CAAAA,CAAEM,YAAYN,CAAAA,CAAEK;EAkHqF;;;;eA7GlGL,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;YAKnBP,CAAAA,CAAEM,YAAYN,CAAAA,CAAEO;;;;;;;;;;;gBAWZP,CAAAA,CAAES,WAAWT,CAAAA,CAAEQ;YACrBR,CAAAA,CAAEU;;;;;;;;;;;KAWFE,mBAAAA,GAAsBX,4BAA4BG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiFtCS,uBAAAA,UAAiCD,sCAA2DZ,CAAAA,CAAEW;uBAC7FX,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;oBAC3CP,CAAAA,CAAES,WAAWT,CAAAA,CAAEc,UAAUd,CAAAA,CAAEK,WAAWL,CAAAA,CAAEO;YAClDP,CAAAA,CAAEU;uBACWK;oBACHA;;wBAEIA;qBACHA;kCARwGC,sBAAAA,CAS7DC,UAAAA,GAAUD,sBAAAA,CAAmCE"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","names":["MIDDLEWARE_BRAND: unique symbol"],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot } from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\nexport type NormalizedSchemaInput<\n TSchema extends InteropZodObject | undefined | never = any\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends Record<string, unknown>\n ? TSchema & AgentBuiltInState\n : AgentBuiltInState;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n */\n tool: ClientTool | ServerTool;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n */\nexport interface AgentMiddleware<\n TSchema extends InteropZodObject | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: (ClientTool | ServerTool)[];\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer S, any, any>\n ? S extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<S>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer S, any, any>\n ? S extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<S>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T = AgentMiddleware[]> = T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer C, any>\n ? C extends InteropZodObject\n ? InferInteropZodInput<C>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer C, any>\n ? C extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : C extends InteropZodObject\n ? InferInteropZodInput<C>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? AnnotationRoot<InteropZodToStateDefinition<A>>\n : never;\n\nexport type InferSchemaInput<\n A extends AnyAnnotationRoot | InteropZodObject | undefined\n> = A extends AnyAnnotationRoot | InteropZodObject\n ? ToAnnotationRoot<A>[\"State\"]\n : {};\n"],"mappings":";;;;;;;AA+PA,MAAaA,mBAAkC,OAAO,kBAAkB"}
1
+ {"version":3,"file":"types.cjs","names":["MIDDLEWARE_BRAND: unique symbol"],"sources":["../../../src/agents/middleware/types.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport type {\n InteropZodObject,\n InteropZodDefault,\n InteropZodOptional,\n InferInteropZodInput,\n InferInteropZodOutput,\n} from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot } from \"@langchain/langgraph\";\nimport type {\n AIMessage,\n SystemMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport type { ToolCall } from \"@langchain/core/messages/tool\";\nimport type { Command } from \"@langchain/langgraph\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\n\ntype PromiseOrValue<T> = T | Promise<T>;\n\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\n\n/**\n * Type bag that encapsulates all middleware type parameters.\n *\n * This interface bundles all the generic type parameters used throughout the middleware system\n * into a single configuration object. This pattern simplifies type signatures and makes\n * it easier to add new type parameters without changing multiple function signatures.\n *\n * @typeParam TSchema - The middleware state schema type. Can be an `InteropZodObject` or `undefined`.\n *\n * @typeParam TContextSchema - The middleware context schema type. Can be an `InteropZodObject`,\n * `InteropZodDefault`, `InteropZodOptional`, or `undefined`.\n *\n * @typeParam TFullContext - The full context type available to middleware hooks.\n *\n * @typeParam TTools - The tools array type registered by the middleware.\n *\n * @example\n * ```typescript\n * // Define a type configuration\n * type MyMiddlewareTypes = MiddlewareTypeConfig<\n * typeof myStateSchema,\n * typeof myContextSchema,\n * MyContextType,\n * typeof myTools\n * >;\n * ```\n */\nexport interface MiddlewareTypeConfig<\n TSchema extends InteropZodObject | undefined = InteropZodObject | undefined,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined =\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n> {\n /** The middleware state schema type */\n Schema: TSchema;\n /** The middleware context schema type */\n ContextSchema: TContextSchema;\n /** The full context type */\n FullContext: TFullContext;\n /** The tools array type */\n Tools: TTools;\n}\n\n/**\n * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\n\nexport type NormalizedSchemaInput<\n TSchema extends InteropZodObject | undefined | never = any\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends Record<string, unknown>\n ? TSchema & AgentBuiltInState\n : AgentBuiltInState;\n\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> =\n | (TState & {\n jumpTo?: JumpToTarget;\n })\n | void;\n\n/**\n * Represents a tool call request for the wrapToolCall hook.\n * Contains the tool call information along with the agent's current state and runtime.\n */\nexport interface ToolCallRequest<\n TState extends Record<string, unknown> = Record<string, unknown>,\n TContext = unknown\n> {\n /**\n * The tool call to be executed\n */\n toolCall: ToolCall;\n /**\n * The BaseTool instance being invoked.\n * Provides access to tool metadata like name, description, schema, etc.\n */\n tool: ClientTool | ServerTool;\n /**\n * The current agent state (includes both middleware state and built-in state).\n */\n state: TState & AgentBuiltInState;\n /**\n * The runtime context containing metadata, signal, writer, interrupt, etc.\n */\n runtime: Runtime<TContext>;\n}\n\n/**\n * Handler function type for wrapping tool calls.\n * Takes a tool call request and returns the tool result or a command.\n */\nexport type ToolCallHandler<\n TSchema extends Record<string, unknown> = AgentBuiltInState,\n TContext = unknown\n> = (\n request: ToolCallRequest<TSchema, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> = (\n request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>\n) => PromiseOrValue<ToolMessage | Command>;\n\n/**\n * Handler function type for wrapping model calls.\n * Takes a model request and returns the AI message response.\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime\n * @returns The AI message response from the model\n */\nexport type WrapModelCallHandler<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> = (\n request: Omit<\n ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n /**\n * allow to reset the system prompt or system message\n */\n \"systemPrompt\" | \"systemMessage\"\n > & { systemPrompt?: string; systemMessage?: SystemMessage }\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Wrapper function type for the wrapModelCall hook.\n * Allows middleware to intercept and modify model execution.\n * This enables you to:\n * - Modify the request before calling the model (e.g., change system prompt, add/remove tools)\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing all parameters needed for the model call\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response\n * @returns The AI message response from the model (or a modified version)\n */\nexport type WrapModelCallHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage>;\n\n/**\n * Handler function type for the beforeAgent hook.\n * Called once at the start of agent invocation before any model calls or tool executions.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the start of the agent invocation.\n */\nexport type BeforeAgentHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the beforeModel hook.\n * Called before the model is invoked and before the wrapModelCall hook.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype BeforeModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the beforeModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called before each model invocation.\n */\nexport type BeforeModelHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterModel hook.\n * Called after the model is invoked and before any tools are called.\n * Allows modifying the agent state after model invocation, e.g., to update tool call parameters.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterModelHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterModel lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called after each model invocation.\n */\nexport type AfterModelHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Handler function type for the afterAgent hook.\n * Called once at the end of agent invocation after all model calls and tool executions are complete.\n *\n * @param state - The current agent state (includes both middleware state and built-in state)\n * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.\n * @returns A middleware result containing partial state updates or undefined to pass through\n */\ntype AfterAgentHandler<TSchema, TContext> = (\n state: TSchema,\n runtime: Runtime<TContext>\n) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\n\n/**\n * Hook type for the afterAgent lifecycle event.\n * Can be either a handler function or an object with a handler and optional jump targets.\n * This hook is called once at the end of the agent invocation.\n */\nexport type AfterAgentHook<\n TSchema extends InteropZodObject | undefined = undefined,\n TContext = unknown\n> =\n | AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>\n | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\n };\n\n/**\n * Unique symbol used to brand middleware instances.\n * This prevents functions from being accidentally assignable to AgentMiddleware\n * since functions have a 'name' property that would otherwise make them structurally compatible.\n */\nexport const MIDDLEWARE_BRAND: unique symbol = Symbol(\"AgentMiddleware\");\n\n/**\n * Base middleware interface.\n *\n * @typeParam TSchema - The middleware state schema type\n * @typeParam TContextSchema - The middleware context schema type\n * @typeParam TFullContext - The full context type available to hooks\n * @typeParam TTools - The tools array type registered by the middleware\n *\n * @example\n * ```typescript\n * const middleware = createMiddleware({\n * name: \"myMiddleware\",\n * stateSchema: z.object({ count: z.number() }),\n * tools: [myTool],\n * });\n * ```\n */\nexport interface AgentMiddleware<\n TSchema extends InteropZodObject | undefined = any,\n TContextSchema extends\n | InteropZodObject\n | InteropZodDefault<InteropZodObject>\n | InteropZodOptional<InteropZodObject>\n | undefined = any,\n TFullContext = any,\n TTools extends readonly (ClientTool | ServerTool)[] = readonly (\n | ClientTool\n | ServerTool\n )[]\n> {\n /**\n * Brand property to distinguish middleware instances from plain objects or functions.\n * This is required and prevents accidental assignment of functions to middleware arrays.\n */\n readonly [MIDDLEWARE_BRAND]: true;\n\n /**\n * Type marker for extracting the MiddlewareTypeConfig from a middleware instance.\n * This is a phantom property used only for type inference.\n * @internal\n */\n readonly \"~middlewareTypes\"?: MiddlewareTypeConfig<\n TSchema,\n TContextSchema,\n TFullContext,\n TTools\n >;\n\n /**\n * The name of the middleware.\n */\n name: string;\n\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n stateSchema?: TSchema;\n\n /**\n * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:\n * - A Zod object\n * - A Zod optional object\n * - A Zod default object\n * - Undefined\n */\n contextSchema?: TContextSchema;\n\n /**\n * Additional tools registered by the middleware.\n */\n tools?: TTools;\n /**\n * Wraps tool execution with custom logic. This allows you to:\n * - Modify tool call parameters before execution\n * - Handle errors and retry with different parameters\n * - Post-process tool results\n * - Implement caching, logging, authentication, or other cross-cutting concerns\n * - Return Command objects for advanced control flow\n *\n * The handler receives a ToolCallRequest containing the tool call, state, and runtime,\n * along with a handler function to execute the actual tool.\n *\n * @param request - The tool call request containing toolCall, state, and runtime.\n * @param handler - The function that executes the tool. Call this with a ToolCallRequest to get the result.\n * @returns The tool result as a ToolMessage or a Command for advanced control flow.\n *\n * @example\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * console.log(`Calling tool: ${request.tool.name}`);\n * console.log(`Tool description: ${request.tool.description}`);\n *\n * try {\n * // Execute the tool\n * const result = await handler(request);\n * console.log(`Tool ${request.tool.name} succeeded`);\n * return result;\n * } catch (error) {\n * console.error(`Tool ${request.tool.name} failed:`, error);\n * // Could return a custom error message or retry\n * throw error;\n * }\n * }\n * ```\n *\n * @example Authentication\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * // Check if user is authorized for this tool\n * if (!request.runtime.context.isAuthorized(request.tool.name)) {\n * return new ToolMessage({\n * content: \"Unauthorized to call this tool\",\n * tool_call_id: request.toolCall.id,\n * });\n * }\n * return handler(request);\n * }\n * ```\n *\n * @example Caching\n * ```ts\n * const cache = new Map();\n * wrapToolCall: async (request, handler) => {\n * const cacheKey = `${request.tool.name}:${JSON.stringify(request.toolCall.args)}`;\n * if (cache.has(cacheKey)) {\n * return cache.get(cacheKey);\n * }\n * const result = await handler(request);\n * cache.set(cacheKey, result);\n * return result;\n * }\n * ```\n */\n wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;\n\n /**\n * Wraps the model invocation with custom logic. This allows you to:\n * - Modify the request before calling the model\n * - Handle errors and retry with different parameters\n * - Post-process the response\n * - Implement custom caching, logging, or other cross-cutting concerns\n *\n * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime.\n * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response.\n * @returns The response from the model (or a modified version).\n *\n * @example\n * ```ts\n * wrapModelCall: async (request, handler) => {\n * // Modify request before calling\n * const modifiedRequest = { ...request, systemPrompt: \"You are helpful\" };\n *\n * try {\n * // Call the model\n * return await handler(modifiedRequest);\n * } catch (error) {\n * // Handle errors and retry with fallback\n * const fallbackRequest = { ...request, model: fallbackModel };\n * return await handler(fallbackRequest);\n * }\n * }\n * ```\n */\n wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.\n * It allows to modify the state of the agent before any model calls or tool executions.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;\n\n /**\n * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.\n * It allows to modify the state of the agent.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n beforeModel?: BeforeModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the model call. This function is called after the model is invoked and before any tools are called.\n * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterModel?: AfterModelHook<TSchema, TFullContext>;\n\n /**\n * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.\n * It allows to modify the final state of the agent after all model calls and tool executions are complete.\n *\n * @param state - The middleware state\n * @param runtime - The middleware runtime\n * @returns The modified middleware state or undefined to pass through\n */\n afterAgent?: AfterAgentHook<TSchema, TFullContext>;\n}\n\n/**\n * Helper type to filter out properties that start with underscore (private properties)\n */\ntype FilterPrivateProps<T> = {\n [K in keyof T as K extends `_${string}` ? never : K]: T[K];\n};\n\n/**\n * Helper type to resolve a MiddlewareTypeConfig from either:\n * - A MiddlewareTypeConfig directly\n * - An AgentMiddleware instance (using `typeof middleware`)\n */\nexport type ResolveMiddlewareTypeConfig<T> = T extends {\n \"~middlewareTypes\"?: infer Types;\n}\n ? Types extends MiddlewareTypeConfig\n ? Types\n : never\n : T extends MiddlewareTypeConfig\n ? T\n : never;\n\n/**\n * Helper type to extract any property from a MiddlewareTypeConfig or AgentMiddleware.\n *\n * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from\n * @typeParam K - The property key to extract (\"Schema\" | \"ContextSchema\" | \"FullContext\" | \"Tools\")\n */\nexport type InferMiddlewareType<\n T,\n K extends keyof MiddlewareTypeConfig\n> = ResolveMiddlewareTypeConfig<T>[K];\n\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<\n T,\n \"ContextSchema\"\n>;\n\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<\n T,\n \"FullContext\"\n>;\n\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\n\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> =\n T extends AnyAnnotationRoot\n ? ToAnnotationRoot<T>[\"State\"]\n : T extends InteropZodObject\n ? InferInteropZodInput<T>\n : {};\n\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodOutput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer the input state schema type from a middleware (all properties optional)\n * This filters out private properties (those starting with underscore)\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> =\n T extends AgentMiddleware<infer TSchema, any, any, any>\n ? TSchema extends InteropZodObject\n ? FilterPrivateProps<InferInteropZodInput<TSchema>>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T = AgentMiddleware[]> = T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareState<First> & InferMiddlewareStates<Rest>\n : InferMiddlewareState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged input state from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareInputStates<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest>\n : InferMiddlewareInputState<First>\n : {}\n : {};\n\n/**\n * Helper type to infer merged state from an array of middleware (includes built-in state)\n */\nexport type InferMergedState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer merged input state from an array of middleware (includes built-in state)\n */\nexport type InferMergedInputState<T extends readonly AgentMiddleware[]> =\n InferMiddlewareInputStates<T> & AgentBuiltInState;\n\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> =\n T extends AgentMiddleware<any, infer TContextSchema, any, any>\n ? TContextSchema extends InteropZodOptional<infer Inner>\n ? InferInteropZodInput<Inner> | undefined\n : TContextSchema extends InteropZodObject\n ? InferInteropZodInput<TContextSchema>\n : {}\n : {};\n\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest>\n : InferMiddlewareContext<First>\n : {}\n : {};\n\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined]\n ? [B] extends [undefined]\n ? undefined\n : B | undefined\n : [B] extends [undefined]\n ? A | undefined\n : [A] extends [B]\n ? A\n : [B] extends [A]\n ? B\n : A & B;\n\n/**\n * Helper type to infer merged input context from an array of middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInputs<T extends readonly AgentMiddleware[]> =\n T extends readonly []\n ? {}\n : T extends readonly [infer First, ...infer Rest]\n ? First extends AgentMiddleware\n ? Rest extends readonly AgentMiddleware[]\n ? MergeContextTypes<\n InferMiddlewareContextInput<First>,\n InferMiddlewareContextInputs<Rest>\n >\n : InferMiddlewareContextInput<First>\n : {}\n : {};\n\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<\n ContextSchema extends AnyAnnotationRoot | InteropZodObject\n> = ContextSchema extends InteropZodObject\n ? InferInteropZodInput<ContextSchema>\n : ContextSchema extends AnyAnnotationRoot\n ? ToAnnotationRoot<ContextSchema>[\"State\"]\n : {};\n\nexport type ToAnnotationRoot<A extends AnyAnnotationRoot | InteropZodObject> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? AnnotationRoot<InteropZodToStateDefinition<A>>\n : never;\n\nexport type InferSchemaInput<\n A extends AnyAnnotationRoot | InteropZodObject | undefined\n> = A extends AnyAnnotationRoot | InteropZodObject\n ? ToAnnotationRoot<A>[\"State\"]\n : {};\n"],"mappings":";;;;;;;AA2TA,MAAaA,mBAAkC,OAAO,kBAAkB"}