langchain 1.2.24 → 1.2.25

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 (325) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/_virtual/{rolldown_runtime.cjs → _rolldown/runtime.cjs} +24 -13
  3. package/dist/_virtual/_rolldown/runtime.js +36 -0
  4. package/dist/agents/ReactAgent.cjs +52 -65
  5. package/dist/agents/ReactAgent.cjs.map +1 -1
  6. package/dist/agents/ReactAgent.d.cts.map +1 -1
  7. package/dist/agents/ReactAgent.d.ts.map +1 -1
  8. package/dist/agents/ReactAgent.js +11 -24
  9. package/dist/agents/ReactAgent.js.map +1 -1
  10. package/dist/agents/RunnableCallable.cjs +7 -7
  11. package/dist/agents/RunnableCallable.cjs.map +1 -1
  12. package/dist/agents/RunnableCallable.js.map +1 -1
  13. package/dist/agents/annotation.cjs +41 -37
  14. package/dist/agents/annotation.cjs.map +1 -1
  15. package/dist/agents/annotation.js +21 -17
  16. package/dist/agents/annotation.js.map +1 -1
  17. package/dist/agents/constants.d.cts.map +1 -1
  18. package/dist/agents/constants.d.ts.map +1 -1
  19. package/dist/agents/errors.cjs +3 -3
  20. package/dist/agents/errors.cjs.map +1 -1
  21. package/dist/agents/errors.d.cts.map +1 -1
  22. package/dist/agents/errors.d.ts.map +1 -1
  23. package/dist/agents/errors.js.map +1 -1
  24. package/dist/agents/index.cjs.map +1 -1
  25. package/dist/agents/index.d.cts +2 -2
  26. package/dist/agents/index.d.cts.map +1 -1
  27. package/dist/agents/index.d.ts +2 -2
  28. package/dist/agents/index.d.ts.map +1 -1
  29. package/dist/agents/index.js.map +1 -1
  30. package/dist/agents/middleware/constants.cjs +2 -2
  31. package/dist/agents/middleware/constants.cjs.map +1 -1
  32. package/dist/agents/middleware/constants.js.map +1 -1
  33. package/dist/agents/middleware/contextEditing.cjs +14 -27
  34. package/dist/agents/middleware/contextEditing.cjs.map +1 -1
  35. package/dist/agents/middleware/contextEditing.d.cts +2 -3
  36. package/dist/agents/middleware/contextEditing.d.cts.map +1 -1
  37. package/dist/agents/middleware/contextEditing.d.ts +2 -3
  38. package/dist/agents/middleware/contextEditing.d.ts.map +1 -1
  39. package/dist/agents/middleware/contextEditing.js +5 -18
  40. package/dist/agents/middleware/contextEditing.js.map +1 -1
  41. package/dist/agents/middleware/dynamicSystemPrompt.cjs +3 -4
  42. package/dist/agents/middleware/dynamicSystemPrompt.cjs.map +1 -1
  43. package/dist/agents/middleware/dynamicSystemPrompt.d.cts +2 -2
  44. package/dist/agents/middleware/dynamicSystemPrompt.d.cts.map +1 -1
  45. package/dist/agents/middleware/dynamicSystemPrompt.d.ts +2 -2
  46. package/dist/agents/middleware/dynamicSystemPrompt.d.ts.map +1 -1
  47. package/dist/agents/middleware/dynamicSystemPrompt.js +1 -2
  48. package/dist/agents/middleware/dynamicSystemPrompt.js.map +1 -1
  49. package/dist/agents/middleware/error.cjs +2 -2
  50. package/dist/agents/middleware/error.cjs.map +1 -1
  51. package/dist/agents/middleware/error.js.map +1 -1
  52. package/dist/agents/middleware/hitl.cjs +16 -26
  53. package/dist/agents/middleware/hitl.cjs.map +1 -1
  54. package/dist/agents/middleware/hitl.d.cts.map +1 -1
  55. package/dist/agents/middleware/hitl.d.ts.map +1 -1
  56. package/dist/agents/middleware/hitl.js +8 -18
  57. package/dist/agents/middleware/hitl.js.map +1 -1
  58. package/dist/agents/middleware/index.js +2 -0
  59. package/dist/agents/middleware/llmToolSelector.cjs +9 -10
  60. package/dist/agents/middleware/llmToolSelector.cjs.map +1 -1
  61. package/dist/agents/middleware/llmToolSelector.d.cts +4 -4
  62. package/dist/agents/middleware/llmToolSelector.d.cts.map +1 -1
  63. package/dist/agents/middleware/llmToolSelector.d.ts +4 -4
  64. package/dist/agents/middleware/llmToolSelector.d.ts.map +1 -1
  65. package/dist/agents/middleware/llmToolSelector.js +3 -4
  66. package/dist/agents/middleware/llmToolSelector.js.map +1 -1
  67. package/dist/agents/middleware/modelCallLimit.cjs +5 -5
  68. package/dist/agents/middleware/modelCallLimit.cjs.map +1 -1
  69. package/dist/agents/middleware/modelCallLimit.d.cts +2 -2
  70. package/dist/agents/middleware/modelCallLimit.d.cts.map +1 -1
  71. package/dist/agents/middleware/modelCallLimit.d.ts +2 -2
  72. package/dist/agents/middleware/modelCallLimit.d.ts.map +1 -1
  73. package/dist/agents/middleware/modelCallLimit.js.map +1 -1
  74. package/dist/agents/middleware/modelFallback.cjs.map +1 -1
  75. package/dist/agents/middleware/modelFallback.d.cts +0 -1
  76. package/dist/agents/middleware/modelFallback.d.cts.map +1 -1
  77. package/dist/agents/middleware/modelFallback.d.ts +0 -1
  78. package/dist/agents/middleware/modelFallback.d.ts.map +1 -1
  79. package/dist/agents/middleware/modelFallback.js.map +1 -1
  80. package/dist/agents/middleware/modelRetry.cjs +19 -17
  81. package/dist/agents/middleware/modelRetry.cjs.map +1 -1
  82. package/dist/agents/middleware/modelRetry.d.cts +0 -1
  83. package/dist/agents/middleware/modelRetry.d.cts.map +1 -1
  84. package/dist/agents/middleware/modelRetry.d.ts +0 -1
  85. package/dist/agents/middleware/modelRetry.d.ts.map +1 -1
  86. package/dist/agents/middleware/modelRetry.js +15 -13
  87. package/dist/agents/middleware/modelRetry.js.map +1 -1
  88. package/dist/agents/middleware/pii.cjs +21 -32
  89. package/dist/agents/middleware/pii.cjs.map +1 -1
  90. package/dist/agents/middleware/pii.d.cts +0 -1
  91. package/dist/agents/middleware/pii.d.cts.map +1 -1
  92. package/dist/agents/middleware/pii.d.ts +0 -1
  93. package/dist/agents/middleware/pii.d.ts.map +1 -1
  94. package/dist/agents/middleware/pii.js +10 -21
  95. package/dist/agents/middleware/pii.js.map +1 -1
  96. package/dist/agents/middleware/piiRedaction.cjs +22 -28
  97. package/dist/agents/middleware/piiRedaction.cjs.map +1 -1
  98. package/dist/agents/middleware/piiRedaction.d.cts +0 -1
  99. package/dist/agents/middleware/piiRedaction.d.cts.map +1 -1
  100. package/dist/agents/middleware/piiRedaction.d.ts +0 -1
  101. package/dist/agents/middleware/piiRedaction.d.ts.map +1 -1
  102. package/dist/agents/middleware/piiRedaction.js +8 -14
  103. package/dist/agents/middleware/piiRedaction.js.map +1 -1
  104. package/dist/agents/middleware/provider/anthropic/promptCaching.cjs +5 -8
  105. package/dist/agents/middleware/provider/anthropic/promptCaching.cjs.map +1 -1
  106. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts +2 -2
  107. package/dist/agents/middleware/provider/anthropic/promptCaching.d.cts.map +1 -1
  108. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts +2 -2
  109. package/dist/agents/middleware/provider/anthropic/promptCaching.d.ts.map +1 -1
  110. package/dist/agents/middleware/provider/anthropic/promptCaching.js +3 -6
  111. package/dist/agents/middleware/provider/anthropic/promptCaching.js.map +1 -1
  112. package/dist/agents/middleware/provider/openai/moderation.cjs +17 -22
  113. package/dist/agents/middleware/provider/openai/moderation.cjs.map +1 -1
  114. package/dist/agents/middleware/provider/openai/moderation.d.cts +0 -2
  115. package/dist/agents/middleware/provider/openai/moderation.d.cts.map +1 -1
  116. package/dist/agents/middleware/provider/openai/moderation.d.ts +0 -2
  117. package/dist/agents/middleware/provider/openai/moderation.d.ts.map +1 -1
  118. package/dist/agents/middleware/provider/openai/moderation.js +10 -15
  119. package/dist/agents/middleware/provider/openai/moderation.js.map +1 -1
  120. package/dist/agents/middleware/summarization.cjs +39 -62
  121. package/dist/agents/middleware/summarization.cjs.map +1 -1
  122. package/dist/agents/middleware/summarization.d.cts +2 -2
  123. package/dist/agents/middleware/summarization.d.cts.map +1 -1
  124. package/dist/agents/middleware/summarization.d.ts +2 -2
  125. package/dist/agents/middleware/summarization.d.ts.map +1 -1
  126. package/dist/agents/middleware/summarization.js +17 -40
  127. package/dist/agents/middleware/summarization.js.map +1 -1
  128. package/dist/agents/middleware/todoListMiddleware.cjs +21 -27
  129. package/dist/agents/middleware/todoListMiddleware.cjs.map +1 -1
  130. package/dist/agents/middleware/todoListMiddleware.d.cts +4 -4
  131. package/dist/agents/middleware/todoListMiddleware.d.cts.map +1 -1
  132. package/dist/agents/middleware/todoListMiddleware.d.ts +4 -4
  133. package/dist/agents/middleware/todoListMiddleware.d.ts.map +1 -1
  134. package/dist/agents/middleware/todoListMiddleware.js +12 -18
  135. package/dist/agents/middleware/todoListMiddleware.js.map +1 -1
  136. package/dist/agents/middleware/toolCallLimit.cjs +24 -46
  137. package/dist/agents/middleware/toolCallLimit.cjs.map +1 -1
  138. package/dist/agents/middleware/toolCallLimit.d.cts +2 -3
  139. package/dist/agents/middleware/toolCallLimit.d.cts.map +1 -1
  140. package/dist/agents/middleware/toolCallLimit.d.ts +2 -3
  141. package/dist/agents/middleware/toolCallLimit.d.ts.map +1 -1
  142. package/dist/agents/middleware/toolCallLimit.js +17 -39
  143. package/dist/agents/middleware/toolCallLimit.js.map +1 -1
  144. package/dist/agents/middleware/toolEmulator.cjs +8 -13
  145. package/dist/agents/middleware/toolEmulator.cjs.map +1 -1
  146. package/dist/agents/middleware/toolEmulator.d.cts +0 -1
  147. package/dist/agents/middleware/toolEmulator.d.cts.map +1 -1
  148. package/dist/agents/middleware/toolEmulator.d.ts +0 -1
  149. package/dist/agents/middleware/toolEmulator.d.ts.map +1 -1
  150. package/dist/agents/middleware/toolEmulator.js +5 -10
  151. package/dist/agents/middleware/toolEmulator.js.map +1 -1
  152. package/dist/agents/middleware/toolRetry.cjs +19 -17
  153. package/dist/agents/middleware/toolRetry.cjs.map +1 -1
  154. package/dist/agents/middleware/toolRetry.d.cts +0 -1
  155. package/dist/agents/middleware/toolRetry.d.cts.map +1 -1
  156. package/dist/agents/middleware/toolRetry.d.ts +0 -1
  157. package/dist/agents/middleware/toolRetry.d.ts.map +1 -1
  158. package/dist/agents/middleware/toolRetry.js +15 -13
  159. package/dist/agents/middleware/toolRetry.js.map +1 -1
  160. package/dist/agents/middleware/types.cjs.map +1 -1
  161. package/dist/agents/middleware/types.d.cts +33 -33
  162. package/dist/agents/middleware/types.d.cts.map +1 -1
  163. package/dist/agents/middleware/types.d.ts +33 -33
  164. package/dist/agents/middleware/types.d.ts.map +1 -1
  165. package/dist/agents/middleware/types.js.map +1 -1
  166. package/dist/agents/middleware/utils.cjs +8 -8
  167. package/dist/agents/middleware/utils.cjs.map +1 -1
  168. package/dist/agents/middleware/utils.d.cts +0 -1
  169. package/dist/agents/middleware/utils.d.cts.map +1 -1
  170. package/dist/agents/middleware/utils.d.ts +0 -1
  171. package/dist/agents/middleware/utils.d.ts.map +1 -1
  172. package/dist/agents/middleware/utils.js +3 -3
  173. package/dist/agents/middleware/utils.js.map +1 -1
  174. package/dist/agents/middleware.cjs +1 -2
  175. package/dist/agents/middleware.cjs.map +1 -1
  176. package/dist/agents/middleware.d.cts +0 -1
  177. package/dist/agents/middleware.d.cts.map +1 -1
  178. package/dist/agents/middleware.d.ts +0 -1
  179. package/dist/agents/middleware.d.ts.map +1 -1
  180. package/dist/agents/middleware.js +1 -2
  181. package/dist/agents/middleware.js.map +1 -1
  182. package/dist/agents/model.cjs.map +1 -1
  183. package/dist/agents/model.js.map +1 -1
  184. package/dist/agents/nodes/AfterAgentNode.cjs +1 -2
  185. package/dist/agents/nodes/AfterAgentNode.cjs.map +1 -1
  186. package/dist/agents/nodes/AfterAgentNode.js +1 -2
  187. package/dist/agents/nodes/AfterAgentNode.js.map +1 -1
  188. package/dist/agents/nodes/AfterModelNode.cjs +1 -2
  189. package/dist/agents/nodes/AfterModelNode.cjs.map +1 -1
  190. package/dist/agents/nodes/AfterModelNode.js +1 -2
  191. package/dist/agents/nodes/AfterModelNode.js.map +1 -1
  192. package/dist/agents/nodes/AgentNode.cjs +46 -58
  193. package/dist/agents/nodes/AgentNode.cjs.map +1 -1
  194. package/dist/agents/nodes/AgentNode.js +16 -28
  195. package/dist/agents/nodes/AgentNode.js.map +1 -1
  196. package/dist/agents/nodes/BeforeAgentNode.cjs +1 -2
  197. package/dist/agents/nodes/BeforeAgentNode.cjs.map +1 -1
  198. package/dist/agents/nodes/BeforeAgentNode.js +1 -2
  199. package/dist/agents/nodes/BeforeAgentNode.js.map +1 -1
  200. package/dist/agents/nodes/BeforeModelNode.cjs +1 -2
  201. package/dist/agents/nodes/BeforeModelNode.cjs.map +1 -1
  202. package/dist/agents/nodes/BeforeModelNode.js +1 -2
  203. package/dist/agents/nodes/BeforeModelNode.js.map +1 -1
  204. package/dist/agents/nodes/ToolNode.cjs +25 -25
  205. package/dist/agents/nodes/ToolNode.cjs.map +1 -1
  206. package/dist/agents/nodes/ToolNode.js +6 -6
  207. package/dist/agents/nodes/ToolNode.js.map +1 -1
  208. package/dist/agents/nodes/middleware.cjs +3 -3
  209. package/dist/agents/nodes/middleware.cjs.map +1 -1
  210. package/dist/agents/nodes/middleware.js.map +1 -1
  211. package/dist/agents/nodes/types.d.cts +0 -1
  212. package/dist/agents/nodes/types.d.cts.map +1 -1
  213. package/dist/agents/nodes/types.d.ts +0 -1
  214. package/dist/agents/nodes/types.d.ts.map +1 -1
  215. package/dist/agents/nodes/utils.cjs +16 -17
  216. package/dist/agents/nodes/utils.cjs.map +1 -1
  217. package/dist/agents/nodes/utils.js +2 -3
  218. package/dist/agents/nodes/utils.js.map +1 -1
  219. package/dist/agents/responses.cjs +20 -30
  220. package/dist/agents/responses.cjs.map +1 -1
  221. package/dist/agents/responses.d.cts +0 -1
  222. package/dist/agents/responses.d.cts.map +1 -1
  223. package/dist/agents/responses.d.ts +0 -1
  224. package/dist/agents/responses.d.ts.map +1 -1
  225. package/dist/agents/responses.js +12 -22
  226. package/dist/agents/responses.js.map +1 -1
  227. package/dist/agents/runtime.d.cts +0 -1
  228. package/dist/agents/runtime.d.cts.map +1 -1
  229. package/dist/agents/runtime.d.ts +0 -1
  230. package/dist/agents/runtime.d.ts.map +1 -1
  231. package/dist/agents/state.cjs +1 -2
  232. package/dist/agents/state.cjs.map +1 -1
  233. package/dist/agents/state.js +1 -2
  234. package/dist/agents/state.js.map +1 -1
  235. package/dist/agents/tests/utils.cjs +21 -26
  236. package/dist/agents/tests/utils.cjs.map +1 -1
  237. package/dist/agents/tests/utils.d.cts +0 -1
  238. package/dist/agents/tests/utils.d.cts.map +1 -1
  239. package/dist/agents/tests/utils.d.ts +0 -1
  240. package/dist/agents/tests/utils.d.ts.map +1 -1
  241. package/dist/agents/tests/utils.js +12 -17
  242. package/dist/agents/tests/utils.js.map +1 -1
  243. package/dist/agents/types.d.cts +4 -5
  244. package/dist/agents/types.d.cts.map +1 -1
  245. package/dist/agents/types.d.ts +4 -5
  246. package/dist/agents/types.d.ts.map +1 -1
  247. package/dist/agents/utils.cjs +32 -32
  248. package/dist/agents/utils.cjs.map +1 -1
  249. package/dist/agents/utils.js +6 -6
  250. package/dist/agents/utils.js.map +1 -1
  251. package/dist/agents/withAgentName.cjs +5 -5
  252. package/dist/agents/withAgentName.cjs.map +1 -1
  253. package/dist/agents/withAgentName.js.map +1 -1
  254. package/dist/chat_models/universal.cjs +34 -41
  255. package/dist/chat_models/universal.cjs.map +1 -1
  256. package/dist/chat_models/universal.d.cts.map +1 -1
  257. package/dist/chat_models/universal.d.ts.map +1 -1
  258. package/dist/chat_models/universal.js +21 -29
  259. package/dist/chat_models/universal.js.map +1 -1
  260. package/dist/hub/base.cjs +3 -4
  261. package/dist/hub/base.cjs.map +1 -1
  262. package/dist/hub/base.d.cts +0 -1
  263. package/dist/hub/base.d.cts.map +1 -1
  264. package/dist/hub/base.d.ts +0 -1
  265. package/dist/hub/base.d.ts.map +1 -1
  266. package/dist/hub/base.js +1 -2
  267. package/dist/hub/base.js.map +1 -1
  268. package/dist/hub/index.cjs +2 -2
  269. package/dist/hub/index.cjs.map +1 -1
  270. package/dist/hub/index.d.cts +0 -1
  271. package/dist/hub/index.d.cts.map +1 -1
  272. package/dist/hub/index.d.ts +0 -1
  273. package/dist/hub/index.d.ts.map +1 -1
  274. package/dist/hub/index.js +1 -2
  275. package/dist/hub/index.js.map +1 -1
  276. package/dist/hub/node.cjs +7 -13
  277. package/dist/hub/node.cjs.map +1 -1
  278. package/dist/hub/node.d.cts +0 -1
  279. package/dist/hub/node.d.cts.map +1 -1
  280. package/dist/hub/node.d.ts +0 -1
  281. package/dist/hub/node.d.ts.map +1 -1
  282. package/dist/hub/node.js +6 -13
  283. package/dist/hub/node.js.map +1 -1
  284. package/dist/index.cjs +48 -48
  285. package/dist/index.d.cts +2 -1
  286. package/dist/index.d.ts +2 -1
  287. package/dist/index.js +2 -3
  288. package/dist/load/import_constants.cjs.map +1 -1
  289. package/dist/load/import_constants.js.map +1 -1
  290. package/dist/load/import_map.cjs +46 -47
  291. package/dist/load/import_map.cjs.map +1 -1
  292. package/dist/load/import_map.js +2 -3
  293. package/dist/load/import_map.js.map +1 -1
  294. package/dist/load/import_type.d.cts.map +1 -1
  295. package/dist/load/import_type.d.ts.map +1 -1
  296. package/dist/load/index.cjs +13 -3
  297. package/dist/load/index.cjs.map +1 -1
  298. package/dist/load/index.d.cts +9 -1
  299. package/dist/load/index.d.cts.map +1 -1
  300. package/dist/load/index.d.ts +9 -1
  301. package/dist/load/index.d.ts.map +1 -1
  302. package/dist/load/index.js +9 -0
  303. package/dist/load/index.js.map +1 -1
  304. package/dist/load/serializable.cjs +7 -6
  305. package/dist/load/serializable.js +4 -4
  306. package/dist/storage/encoder_backed.cjs +9 -10
  307. package/dist/storage/encoder_backed.cjs.map +1 -1
  308. package/dist/storage/encoder_backed.d.cts +0 -1
  309. package/dist/storage/encoder_backed.d.cts.map +1 -1
  310. package/dist/storage/encoder_backed.d.ts +0 -1
  311. package/dist/storage/encoder_backed.d.ts.map +1 -1
  312. package/dist/storage/encoder_backed.js +4 -6
  313. package/dist/storage/encoder_backed.js.map +1 -1
  314. package/dist/storage/file_system.cjs +12 -11
  315. package/dist/storage/file_system.cjs.map +1 -1
  316. package/dist/storage/file_system.d.cts +0 -1
  317. package/dist/storage/file_system.d.cts.map +1 -1
  318. package/dist/storage/file_system.d.ts +0 -1
  319. package/dist/storage/file_system.d.ts.map +1 -1
  320. package/dist/storage/file_system.js +5 -7
  321. package/dist/storage/file_system.js.map +1 -1
  322. package/dist/storage/in_memory.cjs +5 -5
  323. package/dist/storage/in_memory.js +2 -3
  324. package/package.json +6 -6
  325. package/dist/_virtual/rolldown_runtime.js +0 -25
@@ -1 +1 @@
1
- {"version":3,"file":"toolRetry.js","names":["config: ToolRetryMiddlewareConfig","toolFilter: string[]","toolName: string","error: Error","error","attemptsMade: number","toolCallId: string","content: string"],"sources":["../../../src/agents/middleware/toolRetry.ts"],"sourcesContent":["/**\n * Tool retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Tool Retry Middleware.\n */\nexport const ToolRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Optional list of tools or tool names to apply retry logic to.\n * Can be a list of `BaseTool` instances or tool name strings.\n * If `undefined`, applies to all tools. Default is `undefined`.\n */\n tools: z\n .array(\n z.union([z.custom<ClientTool>(), z.custom<ServerTool>(), z.string()])\n )\n .optional(),\n\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n *\n * Deprecated values:\n * - `\"raise\"`: use `\"error\"` instead.\n * - `\"return_message\"`: use `\"continue\"` instead.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n /**\n * @deprecated Use `\"error\"` instead.\n */\n z.literal(\"raise\"),\n /**\n * @deprecated Use `\"continue\"` instead.\n */\n z.literal(\"return_message\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ToolRetryMiddlewareConfig = z.input<\n typeof ToolRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed tool calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, toolRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [toolRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { toolRetryMiddleware } from \"langchain\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on 5xx errors\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return 500 <= statusCode && statusCode < 600;\n * }\n * return false;\n * }\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Apply to specific tools with custom error handling\n * ```ts\n * const formatError = (error: Error) =>\n * \"Database temporarily unavailable. Please try again later.\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [\"search_database\"],\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Apply to specific tools using BaseTool instances\n * ```ts\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const searchDatabase = tool(\n * async ({ query }) => {\n * // Search implementation\n * return results;\n * },\n * {\n * name: \"search_database\",\n * description: \"Search the database\",\n * schema: z.object({ query: z.string() }),\n * }\n * );\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [searchDatabase], // Pass BaseTool instance\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"raise\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles tool failures with retries\n */\nexport function toolRetryMiddleware(\n config: ToolRetryMiddlewareConfig = {}\n): AgentMiddleware {\n const { success, error, data } =\n ToolRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n tools,\n retryOn,\n onFailure: onFailureConfig,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n let onFailure = onFailureConfig;\n if (onFailureConfig === \"raise\") {\n console.warn(\n \"⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead.\"\n );\n onFailure = \"error\";\n } else if (onFailureConfig === \"return_message\") {\n console.warn(\n \"⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead.\"\n );\n onFailure = \"continue\";\n }\n\n // Extract tool names from BaseTool instances or strings\n const toolFilter: string[] = [];\n for (const tool of tools ?? []) {\n if (typeof tool === \"string\") {\n toolFilter.push(tool);\n } else if (\"name\" in tool && typeof tool.name === \"string\") {\n toolFilter.push(tool.name);\n } else {\n throw new TypeError(\n \"Expected a tool name string or tool instance to be passed to toolRetryMiddleware\"\n );\n }\n }\n\n /**\n * Check if retry logic should apply to this tool.\n */\n const shouldRetryTool = (toolName: string): boolean => {\n if (toolFilter.length === 0) {\n return true;\n }\n return toolFilter.includes(toolName);\n };\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some((ErrorConstructor) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n return error instanceof ErrorConstructor;\n });\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (\n toolName: string,\n error: Error,\n attemptsMade: number\n ): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Tool '${toolName}' failed after ${attemptsMade} ${attemptWord} with ${errorType}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (\n toolName: string,\n toolCallId: string,\n error: Error,\n attemptsMade: number\n ): ToolMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(toolName, error, attemptsMade);\n }\n\n return new ToolMessage({\n content,\n tool_call_id: toolCallId,\n name: toolName,\n status: \"error\",\n });\n };\n\n return createMiddleware({\n name: \"toolRetryMiddleware\",\n contextSchema: ToolRetryMiddlewareOptionsSchema,\n wrapToolCall: async (request, handler) => {\n const toolName = (request.tool?.name ?? request.toolCall.name) as string;\n\n // Check if retry should apply to this tool\n if (!shouldRetryTool(toolName)) {\n return handler(request);\n }\n\n const toolCallId = request.toolCall.id ?? \"\";\n\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected: retry loop completed without returning\");\n },\n });\n}\n"],"mappings":";;;;;;;;;;;AAgBA,MAAa,mCAAmC,EAC7C,OAAO;CAMN,OAAO,EACJ,MACC,EAAE,MAAM;EAAC,EAAE,QAAoB;EAAE,EAAE,QAAoB;EAAE,EAAE,QAAQ;CAAC,EAAC,CACtE,CACA,UAAU;CAcb,WAAW,EACR,MAAM;EACL,EAAE,QAAQ,QAAQ;EAClB,EAAE,QAAQ,WAAW;EAIrB,EAAE,QAAQ,QAAQ;EAIlB,EAAE,QAAQ,iBAAiB;EAC3B,EAAE,UAAU,CAAC,KAAK,EAAE,WAAW,MAAM,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC;CAC3D,EAAC,CACD,QAAQ,WAAW;AACvB,EAAC,CACD,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGrB,SAAgB,oBACdA,SAAoC,CAAE,GACrB;CACjB,MAAM,EAAE,SAAS,OAAO,MAAM,GAC5B,iCAAiC,UAAU,OAAO;AACpD,KAAI,CAAC,QACH,OAAM,IAAI,wBAAwB;CAEpC,MAAM,EACJ,YACA,OACA,SACA,WAAW,iBACX,eACA,gBACA,YACA,QACD,GAAG;CAEJ,IAAI,YAAY;AAChB,KAAI,oBAAoB,SAAS;EAC/B,QAAQ,KACN,2EACD;EACD,YAAY;CACb,WAAU,oBAAoB,kBAAkB;EAC/C,QAAQ,KACN,uFACD;EACD,YAAY;CACb;CAGD,MAAMC,aAAuB,CAAE;AAC/B,MAAK,MAAM,QAAQ,SAAS,CAAE,EAC5B,KAAI,OAAO,SAAS,UAClB,WAAW,KAAK,KAAK;UAC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,MAAM,eAAe,UAAU;IAG/B,MAAM,MACJA,WAAS,OAAOA,YAAU,YAAY,aAAaA,UAC9CA,UACD,IAAI,MAAM,OAAOA,QAAM;AAG7B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,UAAU,YAAY,KAAK,aAAa;AAI/D,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQ,oBAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,GACV,MAAM,MAAM,MAAM;IAGrB,MAEC,QAAO,cAAc,UAAU,YAAY,KAAK,aAAa;GAEhE;AAIH,SAAM,IAAI,MAAM;EACjB;CACF,EAAC;AACH"}
1
+ {"version":3,"file":"toolRetry.js","names":[],"sources":["../../../src/agents/middleware/toolRetry.ts"],"sourcesContent":["/**\n * Tool retry middleware for agents.\n */\nimport { z } from \"zod/v3\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport type { ClientTool, ServerTool } from \"@langchain/core/tools\";\n\nimport { createMiddleware } from \"../middleware.js\";\nimport type { AgentMiddleware } from \"./types.js\";\nimport { sleep, calculateRetryDelay } from \"./utils.js\";\nimport { RetrySchema } from \"./constants.js\";\nimport { InvalidRetryConfigError } from \"./error.js\";\n\n/**\n * Configuration options for the Tool Retry Middleware.\n */\nexport const ToolRetryMiddlewareOptionsSchema = z\n .object({\n /**\n * Optional list of tools or tool names to apply retry logic to.\n * Can be a list of `BaseTool` instances or tool name strings.\n * If `undefined`, applies to all tools. Default is `undefined`.\n */\n tools: z\n .array(\n z.union([z.custom<ClientTool>(), z.custom<ServerTool>(), z.string()])\n )\n .optional(),\n\n /**\n * Behavior when all retries are exhausted. Options:\n * - `\"continue\"` (default): Return an AIMessage with error details, allowing\n * the agent to potentially handle the failure gracefully.\n * - `\"error\"`: Re-raise the exception, stopping agent execution.\n * - Custom function: Function that takes the exception and returns a string\n * for the AIMessage content, allowing custom error formatting.\n *\n * Deprecated values:\n * - `\"raise\"`: use `\"error\"` instead.\n * - `\"return_message\"`: use `\"continue\"` instead.\n */\n onFailure: z\n .union([\n z.literal(\"error\"),\n z.literal(\"continue\"),\n /**\n * @deprecated Use `\"error\"` instead.\n */\n z.literal(\"raise\"),\n /**\n * @deprecated Use `\"continue\"` instead.\n */\n z.literal(\"return_message\"),\n z.function().args(z.instanceof(Error)).returns(z.string()),\n ])\n .default(\"continue\"),\n })\n .merge(RetrySchema);\n\nexport type ToolRetryMiddlewareConfig = z.input<\n typeof ToolRetryMiddlewareOptionsSchema\n>;\n\n/**\n * Middleware that automatically retries failed tool calls with configurable backoff.\n *\n * Supports retrying on specific exceptions and exponential backoff.\n *\n * @example Basic usage with default settings (2 retries, exponential backoff)\n * ```ts\n * import { createAgent, toolRetryMiddleware } from \"langchain\";\n *\n * const agent = createAgent({\n * model: \"openai:gpt-4o\",\n * tools: [searchTool],\n * middleware: [toolRetryMiddleware()],\n * });\n * ```\n *\n * @example Retry specific exceptions only\n * ```ts\n * import { toolRetryMiddleware } from \"langchain\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * retryOn: [TimeoutError, NetworkError],\n * backoffFactor: 1.5,\n * });\n * ```\n *\n * @example Custom exception filtering\n * ```ts\n * function shouldRetry(error: Error): boolean {\n * // Only retry on 5xx errors\n * if (error.name === \"HTTPError\" && \"statusCode\" in error) {\n * const statusCode = (error as any).statusCode;\n * return 500 <= statusCode && statusCode < 600;\n * }\n * return false;\n * }\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 3,\n * retryOn: shouldRetry,\n * });\n * ```\n *\n * @example Apply to specific tools with custom error handling\n * ```ts\n * const formatError = (error: Error) =>\n * \"Database temporarily unavailable. Please try again later.\";\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [\"search_database\"],\n * onFailure: formatError,\n * });\n * ```\n *\n * @example Apply to specific tools using BaseTool instances\n * ```ts\n * import { tool } from \"@langchain/core/tools\";\n * import { z } from \"zod\";\n *\n * const searchDatabase = tool(\n * async ({ query }) => {\n * // Search implementation\n * return results;\n * },\n * {\n * name: \"search_database\",\n * description: \"Search the database\",\n * schema: z.object({ query: z.string() }),\n * }\n * );\n *\n * const retry = toolRetryMiddleware({\n * maxRetries: 4,\n * tools: [searchDatabase], // Pass BaseTool instance\n * });\n * ```\n *\n * @example Constant backoff (no exponential growth)\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 5,\n * backoffFactor: 0.0, // No exponential growth\n * initialDelayMs: 2000, // Always wait 2 seconds\n * });\n * ```\n *\n * @example Raise exception on failure\n * ```ts\n * const retry = toolRetryMiddleware({\n * maxRetries: 2,\n * onFailure: \"raise\", // Re-raise exception instead of returning message\n * });\n * ```\n *\n * @param config - Configuration options for the retry middleware\n * @returns A middleware instance that handles tool failures with retries\n */\nexport function toolRetryMiddleware(\n config: ToolRetryMiddlewareConfig = {}\n): AgentMiddleware {\n const { success, error, data } =\n ToolRetryMiddlewareOptionsSchema.safeParse(config);\n if (!success) {\n throw new InvalidRetryConfigError(error);\n }\n const {\n maxRetries,\n tools,\n retryOn,\n onFailure: onFailureConfig,\n backoffFactor,\n initialDelayMs,\n maxDelayMs,\n jitter,\n } = data;\n\n let onFailure = onFailureConfig;\n if (onFailureConfig === \"raise\") {\n console.warn(\n \"⚠️ `onFailure: 'raise'` is deprecated. Use `onFailure: 'error'` instead.\"\n );\n onFailure = \"error\";\n } else if (onFailureConfig === \"return_message\") {\n console.warn(\n \"⚠️ `onFailure: 'return_message'` is deprecated. Use `onFailure: 'continue'` instead.\"\n );\n onFailure = \"continue\";\n }\n\n // Extract tool names from BaseTool instances or strings\n const toolFilter: string[] = [];\n for (const tool of tools ?? []) {\n if (typeof tool === \"string\") {\n toolFilter.push(tool);\n } else if (\"name\" in tool && typeof tool.name === \"string\") {\n toolFilter.push(tool.name);\n } else {\n throw new TypeError(\n \"Expected a tool name string or tool instance to be passed to toolRetryMiddleware\"\n );\n }\n }\n\n /**\n * Check if retry logic should apply to this tool.\n */\n const shouldRetryTool = (toolName: string): boolean => {\n if (toolFilter.length === 0) {\n return true;\n }\n return toolFilter.includes(toolName);\n };\n\n /**\n * Check if the exception should trigger a retry.\n */\n const shouldRetryException = (error: Error): boolean => {\n if (typeof retryOn === \"function\") {\n return retryOn(error);\n }\n // retryOn is an array of error constructors\n return retryOn.some((ErrorConstructor) => {\n // eslint-disable-next-line no-instanceof/no-instanceof\n return error instanceof ErrorConstructor;\n });\n };\n\n // Use the exported calculateRetryDelay function with our config\n const delayConfig = { backoffFactor, initialDelayMs, maxDelayMs, jitter };\n\n /**\n * Format the failure message when retries are exhausted.\n */\n const formatFailureMessage = (\n toolName: string,\n error: Error,\n attemptsMade: number\n ): string => {\n const errorType = error.constructor.name;\n const attemptWord = attemptsMade === 1 ? \"attempt\" : \"attempts\";\n return `Tool '${toolName}' failed after ${attemptsMade} ${attemptWord} with ${errorType}`;\n };\n\n /**\n * Handle failure when all retries are exhausted.\n */\n const handleFailure = (\n toolName: string,\n toolCallId: string,\n error: Error,\n attemptsMade: number\n ): ToolMessage => {\n if (onFailure === \"error\") {\n throw error;\n }\n\n let content: string;\n if (typeof onFailure === \"function\") {\n content = onFailure(error);\n } else {\n content = formatFailureMessage(toolName, error, attemptsMade);\n }\n\n return new ToolMessage({\n content,\n tool_call_id: toolCallId,\n name: toolName,\n status: \"error\",\n });\n };\n\n return createMiddleware({\n name: \"toolRetryMiddleware\",\n contextSchema: ToolRetryMiddlewareOptionsSchema,\n wrapToolCall: async (request, handler) => {\n const toolName = (request.tool?.name ?? request.toolCall.name) as string;\n\n // Check if retry should apply to this tool\n if (!shouldRetryTool(toolName)) {\n return handler(request);\n }\n\n const toolCallId = request.toolCall.id ?? \"\";\n\n // Initial attempt + retries\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await handler(request);\n } catch (error) {\n const attemptsMade = attempt + 1; // attempt is 0-indexed\n\n // Ensure error is an Error instance\n const err =\n error && typeof error === \"object\" && \"message\" in error\n ? (error as Error)\n : new Error(String(error));\n\n // Check if we should retry this exception\n if (!shouldRetryException(err)) {\n // Exception is not retryable, handle failure immediately\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n\n // Check if we have more retries left\n if (attempt < maxRetries) {\n // Calculate and apply backoff delay\n const delay = calculateRetryDelay(delayConfig, attempt);\n if (delay > 0) {\n await sleep(delay);\n }\n // Continue to next retry\n } else {\n // No more retries, handle failure\n return handleFailure(toolName, toolCallId, err, attemptsMade);\n }\n }\n }\n\n // Unreachable: loop always returns via handler success or handleFailure\n throw new Error(\"Unexpected: retry loop completed without returning\");\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAgBA,MAAa,mCAAmC,EAC7C,OAAO;CAMN,OAAO,EACJ,MACC,EAAE,MAAM;EAAC,EAAE,QAAoB;EAAE,EAAE,QAAoB;EAAE,EAAE,QAAQ;EAAC,CAAC,CACtE,CACA,UAAU;CAcb,WAAW,EACR,MAAM;EACL,EAAE,QAAQ,QAAQ;EAClB,EAAE,QAAQ,WAAW;EAIrB,EAAE,QAAQ,QAAQ;EAIlB,EAAE,QAAQ,iBAAiB;EAC3B,EAAE,UAAU,CAAC,KAAK,EAAE,WAAW,MAAM,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC;EAC3D,CAAC,CACD,QAAQ,WAAW;CACvB,CAAC,CACD,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyGrB,SAAgB,oBACd,SAAoC,EAAE,EACrB;CACjB,MAAM,EAAE,SAAS,OAAO,SACtB,iCAAiC,UAAU,OAAO;AACpD,KAAI,CAAC,QACH,OAAM,IAAI,wBAAwB,MAAM;CAE1C,MAAM,EACJ,YACA,OACA,SACA,WAAW,iBACX,eACA,gBACA,YACA,WACE;CAEJ,IAAI,YAAY;AAChB,KAAI,oBAAoB,SAAS;AAC/B,UAAQ,KACN,2EACD;AACD,cAAY;YACH,oBAAoB,kBAAkB;AAC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AAM,QAAQ,QAAQ;YACtB,OAAO;IACd,MAAM,eAAe,UAAU;IAG/B,MAAM,MACJ,SAAS,OAAO,UAAU,YAAY,aAAa,QAC9C,QACD,IAAI,MAAM,OAAO,MAAM,CAAC;AAG9B,QAAI,CAAC,qBAAqB,IAAI,CAE5B,QAAO,cAAc,UAAU,YAAY,KAAK,aAAa;AAI/D,QAAI,UAAU,YAAY;KAExB,MAAM,QAAQ,oBAAoB,aAAa,QAAQ;AACvD,SAAI,QAAQ,EACV,OAAM,MAAM,MAAM;UAKpB,QAAO,cAAc,UAAU,YAAY,KAAK,aAAa;;AAMnE,SAAM,IAAI,MAAM,qDAAqD;;EAExE,CAAC"}
@@ -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 {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} 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 a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) 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 StateDefinitionInit | undefined =\n | StateDefinitionInit\n | 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 StateDefinitionInit | undefined | never = any,\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<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 * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | 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 (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\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 * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\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 : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<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 * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\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 : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<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 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 ? 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 StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n"],"mappings":";;;;;;;AAmVA,MAAaA,mBAAkC,OAAO,kBAAkB"}
1
+ {"version":3,"file":"types.cjs","names":[],"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 {\n AnnotationRoot,\n StateSchema,\n InferStateSchemaUpdate,\n StateDefinitionInit,\n} 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 a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) 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 StateDefinitionInit | undefined =\n | StateDefinitionInit\n | 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 StateDefinitionInit | undefined | never = any,\n> = [TSchema] extends [never]\n ? AgentBuiltInState\n : TSchema extends InteropZodObject\n ? InferInteropZodOutput<TSchema> & AgentBuiltInState\n : TSchema extends StateDefinitionInit\n ? InferSchemaInput<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 * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | undefined = undefined,\n TContext = unknown,\n> = (\n request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,\n handler: WrapModelCallHandler<TSchema, TContext>\n) => PromiseOrValue<AIMessage | Command>;\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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | 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 StateDefinitionInit | 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 (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\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 * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\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 : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<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 * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\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 : TSchema extends StateDefinitionInit\n ? FilterPrivateProps<InferSchemaInput<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 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 ? 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 StateDefinitionInit> =\n A extends AnyAnnotationRoot\n ? A\n : A extends InteropZodObject\n ? InteropZodToStateDefinition<A>\n : never;\n\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> =\n A extends StateSchema<infer TFields>\n ? InferStateSchemaUpdate<TFields>\n : A extends InteropZodObject\n ? InferInteropZodOutput<A>\n : A extends AnyAnnotationRoot\n ? A[\"State\"]\n : {};\n"],"mappings":";;;;;;;AAmVA,MAAa,mBAAkC,OAAO,kBAAkB"}
@@ -1,5 +1,5 @@
1
1
  import { JumpToTarget } from "../constants.cjs";
2
- import { AgentBuiltInState, Runtime } from "../runtime.cjs";
2
+ import { AgentBuiltInState, Runtime as Runtime$1 } from "../runtime.cjs";
3
3
  import { ModelRequest } from "../nodes/types.cjs";
4
4
  import { AIMessage, SystemMessage, ToolMessage } from "@langchain/core/messages";
5
5
  import { ClientTool, ServerTool } from "@langchain/core/tools";
@@ -39,11 +39,11 @@ type AnyAnnotationRoot = AnnotationRoot<any>;
39
39
  * >;
40
40
  * ```
41
41
  */
42
- interface MiddlewareTypeConfig<TSchema$1 extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContextSchema$1 extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
42
+ interface MiddlewareTypeConfig<TSchema extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
43
43
  /** The middleware state schema type */
44
- Schema: TSchema$1;
44
+ Schema: TSchema;
45
45
  /** The middleware context schema type */
46
- ContextSchema: TContextSchema$1;
46
+ ContextSchema: TContextSchema;
47
47
  /** The full context type */
48
48
  FullContext: TFullContext;
49
49
  /** The tools array type */
@@ -54,7 +54,7 @@ interface MiddlewareTypeConfig<TSchema$1 extends StateDefinitionInit | undefined
54
54
  * Used when no explicit type parameters are provided.
55
55
  */
56
56
  type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;
57
- type NormalizedSchemaInput<TSchema$1 extends StateDefinitionInit | undefined | never = any> = [TSchema$1] extends [never] ? AgentBuiltInState : TSchema$1 extends InteropZodObject ? InferInteropZodOutput<TSchema$1> & AgentBuiltInState : TSchema$1 extends StateDefinitionInit ? InferSchemaInput<TSchema$1> & AgentBuiltInState : AgentBuiltInState;
57
+ type NormalizedSchemaInput<TSchema extends StateDefinitionInit | undefined | never = any> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodOutput<TSchema> & AgentBuiltInState : TSchema extends StateDefinitionInit ? InferSchemaInput<TSchema> & AgentBuiltInState : AgentBuiltInState;
58
58
  /**
59
59
  * Result type for middleware functions.
60
60
  */
@@ -98,18 +98,18 @@ interface ToolCallRequest<TState extends Record<string, unknown> = Record<string
98
98
  /**
99
99
  * The runtime context containing metadata, signal, writer, interrupt, etc.
100
100
  */
101
- runtime: Runtime<TContext>;
101
+ runtime: Runtime$1<TContext>;
102
102
  }
103
103
  /**
104
104
  * Handler function type for wrapping tool calls.
105
105
  * Takes a tool call request and returns the tool result or a command.
106
106
  */
107
- type ToolCallHandler<TSchema$1 extends Record<string, unknown> = AgentBuiltInState, TContext = unknown> = (request: ToolCallRequest<TSchema$1, TContext>) => PromiseOrValue<ToolMessage | Command>;
107
+ type ToolCallHandler<TSchema extends Record<string, unknown> = AgentBuiltInState, TContext = unknown> = (request: ToolCallRequest<TSchema, TContext>) => PromiseOrValue<ToolMessage | Command>;
108
108
  /**
109
109
  * Wrapper function type for the wrapToolCall hook.
110
110
  * Allows middleware to intercept and modify tool execution.
111
111
  */
112
- type WrapToolCallHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ToolCallRequest<NormalizedSchemaInput<TSchema$1>, TContext>, handler: ToolCallHandler<NormalizedSchemaInput<TSchema$1>, TContext>) => PromiseOrValue<ToolMessage | Command>;
112
+ type WrapToolCallHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>) => PromiseOrValue<ToolMessage | Command>;
113
113
  /**
114
114
  * Handler function type for wrapping model calls.
115
115
  * Takes a model request and returns the AI message response.
@@ -117,7 +117,7 @@ type WrapToolCallHook<TSchema$1 extends StateDefinitionInit | undefined = undefi
117
117
  * @param request - The model request containing model, messages, systemPrompt, tools, state, and runtime
118
118
  * @returns The AI message response from the model
119
119
  */
120
- type WrapModelCallHandler<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: Omit<ModelRequest<NormalizedSchemaInput<TSchema$1>, TContext>,
120
+ type WrapModelCallHandler<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: Omit<ModelRequest<NormalizedSchemaInput<TSchema>, TContext>,
121
121
  /**
122
122
  * allow to reset the system prompt or system message
123
123
  */
@@ -138,7 +138,7 @@ type WrapModelCallHandler<TSchema$1 extends StateDefinitionInit | undefined = un
138
138
  * @param handler - The function that invokes the model. Call this with a ModelRequest to get the response
139
139
  * @returns The AI message response from the model (or a modified version)
140
140
  */
141
- type WrapModelCallHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema$1>, TContext>, handler: WrapModelCallHandler<TSchema$1, TContext>) => PromiseOrValue<AIMessage | Command>;
141
+ type WrapModelCallHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: WrapModelCallHandler<TSchema, TContext>) => PromiseOrValue<AIMessage | Command>;
142
142
  /**
143
143
  * Handler function type for the beforeAgent hook.
144
144
  * Called once at the start of agent invocation before any model calls or tool executions.
@@ -147,14 +147,14 @@ type WrapModelCallHook<TSchema$1 extends StateDefinitionInit | undefined = undef
147
147
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
148
148
  * @returns A middleware result containing partial state updates or undefined to pass through
149
149
  */
150
- type BeforeAgentHandler<TSchema$1, TContext> = (state: TSchema$1, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema$1>>>;
150
+ type BeforeAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
151
151
  /**
152
152
  * Hook type for the beforeAgent lifecycle event.
153
153
  * Can be either a handler function or an object with a handler and optional jump targets.
154
154
  * This hook is called once at the start of the agent invocation.
155
155
  */
156
- type BeforeAgentHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema$1>, TContext> | {
157
- hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema$1>, TContext>;
156
+ type BeforeAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {
157
+ hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;
158
158
  canJumpTo?: JumpToTarget[];
159
159
  };
160
160
  /**
@@ -165,14 +165,14 @@ type BeforeAgentHook<TSchema$1 extends StateDefinitionInit | undefined = undefin
165
165
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
166
166
  * @returns A middleware result containing partial state updates or undefined to pass through
167
167
  */
168
- type BeforeModelHandler<TSchema$1, TContext> = (state: TSchema$1, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema$1>>>;
168
+ type BeforeModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
169
169
  /**
170
170
  * Hook type for the beforeModel lifecycle event.
171
171
  * Can be either a handler function or an object with a handler and optional jump targets.
172
172
  * This hook is called before each model invocation.
173
173
  */
174
- type BeforeModelHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema$1>, TContext> | {
175
- hook: BeforeModelHandler<NormalizedSchemaInput<TSchema$1>, TContext>;
174
+ type BeforeModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {
175
+ hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;
176
176
  canJumpTo?: JumpToTarget[];
177
177
  };
178
178
  /**
@@ -184,14 +184,14 @@ type BeforeModelHook<TSchema$1 extends StateDefinitionInit | undefined = undefin
184
184
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
185
185
  * @returns A middleware result containing partial state updates or undefined to pass through
186
186
  */
187
- type AfterModelHandler<TSchema$1, TContext> = (state: TSchema$1, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema$1>>>;
187
+ type AfterModelHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
188
188
  /**
189
189
  * Hook type for the afterModel lifecycle event.
190
190
  * Can be either a handler function or an object with a handler and optional jump targets.
191
191
  * This hook is called after each model invocation.
192
192
  */
193
- type AfterModelHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema$1>, TContext> | {
194
- hook: AfterModelHandler<NormalizedSchemaInput<TSchema$1>, TContext>;
193
+ type AfterModelHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {
194
+ hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;
195
195
  canJumpTo?: JumpToTarget[];
196
196
  };
197
197
  /**
@@ -202,14 +202,14 @@ type AfterModelHook<TSchema$1 extends StateDefinitionInit | undefined = undefine
202
202
  * @param runtime - The runtime context containing metadata, signal, writer, interrupt, etc.
203
203
  * @returns A middleware result containing partial state updates or undefined to pass through
204
204
  */
205
- type AfterAgentHandler<TSchema$1, TContext> = (state: TSchema$1, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema$1>>>;
205
+ type AfterAgentHandler<TSchema, TContext> = (state: TSchema, runtime: Runtime$1<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;
206
206
  /**
207
207
  * Hook type for the afterAgent lifecycle event.
208
208
  * Can be either a handler function or an object with a handler and optional jump targets.
209
209
  * This hook is called once at the end of the agent invocation.
210
210
  */
211
- type AfterAgentHook<TSchema$1 extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema$1>, TContext> | {
212
- hook: AfterAgentHandler<NormalizedSchemaInput<TSchema$1>, TContext>;
211
+ type AfterAgentHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {
212
+ hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;
213
213
  canJumpTo?: JumpToTarget[];
214
214
  };
215
215
  /**
@@ -235,7 +235,7 @@ declare const MIDDLEWARE_BRAND: unique symbol;
235
235
  * });
236
236
  * ```
237
237
  */
238
- interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = any, TContextSchema$1 extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
238
+ interface AgentMiddleware<TSchema extends StateDefinitionInit | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {
239
239
  /**
240
240
  * Brand property to distinguish middleware instances from plain objects or functions.
241
241
  * This is required and prevents accidental assignment of functions to middleware arrays.
@@ -246,7 +246,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
246
246
  * This is a phantom property used only for type inference.
247
247
  * @internal
248
248
  */
249
- readonly "~middlewareTypes"?: MiddlewareTypeConfig<TSchema$1, TContextSchema$1, TFullContext, TTools>;
249
+ readonly "~middlewareTypes"?: MiddlewareTypeConfig<TSchema, TContextSchema, TFullContext, TTools>;
250
250
  /**
251
251
  * The name of the middleware.
252
252
  */
@@ -258,7 +258,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
258
258
  * - An AnnotationRoot
259
259
  * - Undefined
260
260
  */
261
- stateSchema?: TSchema$1;
261
+ stateSchema?: TSchema;
262
262
  /**
263
263
  * The schema of the middleware context. Middleware context is read-only and not persisted between multiple invocations. It can be either:
264
264
  * - A Zod object
@@ -266,7 +266,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
266
266
  * - A Zod default object
267
267
  * - Undefined
268
268
  */
269
- contextSchema?: TContextSchema$1;
269
+ contextSchema?: TContextSchema;
270
270
  /**
271
271
  * Additional tools registered by the middleware.
272
272
  */
@@ -333,7 +333,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
333
333
  * }
334
334
  * ```
335
335
  */
336
- wrapToolCall?: WrapToolCallHook<TSchema$1, TFullContext>;
336
+ wrapToolCall?: WrapToolCallHook<TSchema, TFullContext>;
337
337
  /**
338
338
  * Wraps the model invocation with custom logic. This allows you to:
339
339
  * - Modify the request before calling the model
@@ -362,7 +362,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
362
362
  * }
363
363
  * ```
364
364
  */
365
- wrapModelCall?: WrapModelCallHook<TSchema$1, TFullContext>;
365
+ wrapModelCall?: WrapModelCallHook<TSchema, TFullContext>;
366
366
  /**
367
367
  * The function to run before the agent execution starts. This function is called once at the start of the agent invocation.
368
368
  * It allows to modify the state of the agent before any model calls or tool executions.
@@ -371,7 +371,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
371
371
  * @param runtime - The middleware runtime
372
372
  * @returns The modified middleware state or undefined to pass through
373
373
  */
374
- beforeAgent?: BeforeAgentHook<TSchema$1, TFullContext>;
374
+ beforeAgent?: BeforeAgentHook<TSchema, TFullContext>;
375
375
  /**
376
376
  * The function to run before the model call. This function is called before the model is invoked and before the `wrapModelCall` hook.
377
377
  * It allows to modify the state of the agent.
@@ -380,7 +380,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
380
380
  * @param runtime - The middleware runtime
381
381
  * @returns The modified middleware state or undefined to pass through
382
382
  */
383
- beforeModel?: BeforeModelHook<TSchema$1, TFullContext>;
383
+ beforeModel?: BeforeModelHook<TSchema, TFullContext>;
384
384
  /**
385
385
  * The function to run after the model call. This function is called after the model is invoked and before any tools are called.
386
386
  * It allows to modify the state of the agent after the model is invoked, e.g. to update tool call parameters.
@@ -389,7 +389,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
389
389
  * @param runtime - The middleware runtime
390
390
  * @returns The modified middleware state or undefined to pass through
391
391
  */
392
- afterModel?: AfterModelHook<TSchema$1, TFullContext>;
392
+ afterModel?: AfterModelHook<TSchema, TFullContext>;
393
393
  /**
394
394
  * The function to run after the agent execution completes. This function is called once at the end of the agent invocation.
395
395
  * It allows to modify the final state of the agent after all model calls and tool executions are complete.
@@ -398,7 +398,7 @@ interface AgentMiddleware<TSchema$1 extends StateDefinitionInit | undefined = an
398
398
  * @param runtime - The middleware runtime
399
399
  * @returns The modified middleware state or undefined to pass through
400
400
  */
401
- afterAgent?: AfterAgentHook<TSchema$1, TFullContext>;
401
+ afterAgent?: AfterAgentHook<TSchema, TFullContext>;
402
402
  }
403
403
  /**
404
404
  * Helper type to filter out properties that start with underscore (private properties)
@@ -418,7 +418,7 @@ type ResolveMiddlewareTypeConfig<T> = T extends {
418
418
  * @typeParam T - The MiddlewareTypeConfig or AgentMiddleware to extract from
419
419
  * @typeParam K - The property key to extract ("Schema" | "ContextSchema" | "FullContext" | "Tools")
420
420
  */
421
- type InferMiddlewareType<T, K$1 extends keyof MiddlewareTypeConfig> = ResolveMiddlewareTypeConfig<T>[K$1];
421
+ type InferMiddlewareType<T, K extends keyof MiddlewareTypeConfig> = ResolveMiddlewareTypeConfig<T>[K];
422
422
  /**
423
423
  * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.
424
424
  */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":["InteropZodObject","InteropZodDefault","InteropZodOptional","InferInteropZodInput","InferInteropZodOutput","InteropZodToStateDefinition","AnnotationRoot","StateSchema","InferStateSchemaUpdate","StateDefinitionInit","AIMessage","SystemMessage","ToolMessage","ToolCall","Command","ClientTool","ServerTool","JumpToTarget","Runtime","AgentBuiltInState","ModelRequest","PromiseOrValue","T","Promise","AnyAnnotationRoot","MiddlewareTypeConfig","TSchema","TContextSchema","TFullContext","TTools","DefaultMiddlewareTypeConfig","NormalizedSchemaInput","InferSchemaInput","MiddlewareResult","TState","ToolCallRequest","TContext","Record","ToolCallHandler","WrapToolCallHook","WrapModelCallHandler","Omit","WrapModelCallHook","BeforeAgentHandler","Partial","BeforeAgentHook","BeforeModelHandler","BeforeModelHook","AfterModelHandler","AfterModelHook","AfterAgentHandler","AfterAgentHook","MIDDLEWARE_BRAND","AgentMiddleware","FilterPrivateProps","K","ResolveMiddlewareTypeConfig","Types","InferMiddlewareType","InferMiddlewareSchema","InferMiddlewareContextSchema","InferMiddlewareFullContext","InferMiddlewareToolsFromConfig","InferChannelType","ToAnnotationRoot","InferMiddlewareState","InferMiddlewareInputState","InferMiddlewareStates","First","Rest","InferMiddlewareInputStates","InferMergedState","InferMergedInputState","InferMiddlewareContext","InferMiddlewareContextInput","Inner","InferMiddlewareContexts","MergeContextTypes","A","B","InferMiddlewareContextInputs","InferContextInput","ContextSchema","TFields"],"sources":["../../../src/agents/middleware/types.d.ts"],"sourcesContent":["import type { InteropZodObject, InteropZodDefault, InteropZodOptional, InferInteropZodInput, InferInteropZodOutput } from \"@langchain/core/utils/types\";\nimport type { InteropZodToStateDefinition } from \"@langchain/langgraph/zod\";\nimport type { AnnotationRoot, StateSchema, InferStateSchemaUpdate, StateDefinitionInit } from \"@langchain/langgraph\";\nimport type { AIMessage, SystemMessage, ToolMessage } 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\";\nimport type { JumpToTarget } from \"../constants.js\";\nimport type { Runtime, AgentBuiltInState } from \"../runtime.js\";\nimport type { ModelRequest } from \"../nodes/types.js\";\ntype PromiseOrValue<T> = T | Promise<T>;\nexport type AnyAnnotationRoot = AnnotationRoot<any>;\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 a `StateDefinitionInit`\n * (including `InteropZodObject`, `StateSchema`, or `AnnotationRoot`) 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<TSchema extends StateDefinitionInit | undefined = StateDefinitionInit | undefined, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\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 * Default type configuration for middleware.\n * Used when no explicit type parameters are provided.\n */\nexport type DefaultMiddlewareTypeConfig = MiddlewareTypeConfig;\nexport type NormalizedSchemaInput<TSchema extends StateDefinitionInit | undefined | never = any> = [TSchema] extends [never] ? AgentBuiltInState : TSchema extends InteropZodObject ? InferInteropZodOutput<TSchema> & AgentBuiltInState : TSchema extends StateDefinitionInit ? InferSchemaInput<TSchema> & AgentBuiltInState : AgentBuiltInState;\n/**\n * Result type for middleware functions.\n */\nexport type MiddlewareResult<TState> = (TState & {\n jumpTo?: JumpToTarget;\n}) | void;\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<TState extends Record<string, unknown> = Record<string, unknown>, TContext = unknown> {\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 * This will be `undefined` for dynamically registered tools that aren't\n * declared upfront when creating the agent. In such cases, middleware\n * should provide the tool implementation by spreading the request with\n * the tool property.\n *\n * @example Dynamic tool handling\n * ```ts\n * wrapToolCall: async (request, handler) => {\n * if (request.toolCall.name === \"dynamic_tool\" && !request.tool) {\n * // Provide the tool implementation for dynamically registered tools\n * return handler({ ...request, tool: myDynamicTool });\n * }\n * return handler(request);\n * }\n * ```\n */\n tool: ClientTool | ServerTool | undefined;\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 * 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<TSchema extends Record<string, unknown> = AgentBuiltInState, TContext = unknown> = (request: ToolCallRequest<TSchema, TContext>) => PromiseOrValue<ToolMessage | Command>;\n/**\n * Wrapper function type for the wrapToolCall hook.\n * Allows middleware to intercept and modify tool execution.\n */\nexport type WrapToolCallHook<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ToolCallRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: ToolCallHandler<NormalizedSchemaInput<TSchema>, TContext>) => PromiseOrValue<ToolMessage | Command>;\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<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: Omit<ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, \n/**\n * allow to reset the system prompt or system message\n */\n\"systemPrompt\" | \"systemMessage\"> & {\n systemPrompt?: string;\n systemMessage?: SystemMessage;\n}) => PromiseOrValue<AIMessage>;\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<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = (request: ModelRequest<NormalizedSchemaInput<TSchema>, TContext>, handler: WrapModelCallHandler<TSchema, TContext>) => PromiseOrValue<AIMessage | Command>;\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> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\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<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\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> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\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<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: BeforeModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\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> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\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<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterModelHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\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> = (state: TSchema, runtime: Runtime<TContext>) => PromiseOrValue<MiddlewareResult<Partial<TSchema>>>;\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<TSchema extends StateDefinitionInit | undefined = undefined, TContext = unknown> = AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext> | {\n hook: AfterAgentHandler<NormalizedSchemaInput<TSchema>, TContext>;\n canJumpTo?: JumpToTarget[];\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 declare const MIDDLEWARE_BRAND: unique symbol;\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<TSchema extends StateDefinitionInit | undefined = any, TContextSchema extends InteropZodObject | InteropZodDefault<InteropZodObject> | InteropZodOptional<InteropZodObject> | undefined = any, TFullContext = any, TTools extends readonly (ClientTool | ServerTool)[] = readonly (ClientTool | ServerTool)[]> {\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 * 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<TSchema, TContextSchema, TFullContext, TTools>;\n /**\n * The name of the middleware.\n */\n name: string;\n /**\n * The schema of the middleware state. Middleware state is persisted between multiple invocations. It can be either:\n * - A Zod object (InteropZodObject)\n * - A StateSchema from LangGraph (supports ReducedValue, UntrackedValue)\n * - An AnnotationRoot\n * - Undefined\n */\n stateSchema?: TSchema;\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 * 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 * 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 * 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 * 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 * 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 * 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 * 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 * 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} ? Types extends MiddlewareTypeConfig ? Types : never : T extends MiddlewareTypeConfig ? T : never;\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<T, K extends keyof MiddlewareTypeConfig> = ResolveMiddlewareTypeConfig<T>[K];\n/**\n * Shorthand helper to extract the Schema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareSchema<T> = InferMiddlewareType<T, \"Schema\">;\n/**\n * Shorthand helper to extract the ContextSchema type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareContextSchema<T> = InferMiddlewareType<T, \"ContextSchema\">;\n/**\n * Shorthand helper to extract the FullContext type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareFullContext<T> = InferMiddlewareType<T, \"FullContext\">;\n/**\n * Shorthand helper to extract the Tools type from a MiddlewareTypeConfig or AgentMiddleware.\n */\nexport type InferMiddlewareToolsFromConfig<T> = InferMiddlewareType<T, \"Tools\">;\nexport type InferChannelType<T extends AnyAnnotationRoot | InteropZodObject> = T extends AnyAnnotationRoot ? ToAnnotationRoot<T>[\"State\"] : T extends InteropZodObject ? InferInteropZodInput<T> : {};\n/**\n * Helper type to infer the state schema type from a middleware\n * This filters out private properties (those starting with underscore)\n * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodOutput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaInput<TSchema>> : {} : {};\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 * Supports both Zod schemas (InteropZodObject) and StateSchema from LangGraph\n */\nexport type InferMiddlewareInputState<T extends AgentMiddleware> = T extends AgentMiddleware<infer TSchema, any, any, any> ? TSchema extends InteropZodObject ? FilterPrivateProps<InferInteropZodInput<TSchema>> : TSchema extends StateDefinitionInit ? FilterPrivateProps<InferSchemaInput<TSchema>> : {} : {};\n/**\n * Helper type to infer merged state from an array of middleware (just the middleware states)\n */\nexport type InferMiddlewareStates<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareState<First> & InferMiddlewareStates<Rest> : InferMiddlewareState<First> : {} : {};\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[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareInputState<First> & InferMiddlewareInputStates<Rest> : InferMiddlewareInputState<First> : {} : {};\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[]> = InferMiddlewareStates<T> & AgentBuiltInState;\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[]> = InferMiddlewareInputStates<T> & AgentBuiltInState;\n/**\n * Helper type to infer the context schema type from a middleware\n */\nexport type InferMiddlewareContext<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer TContextSchema, any, any> ? TContextSchema extends InteropZodObject ? InferInteropZodInput<TContextSchema> : {} : {};\n/**\n * Helper type to infer the input context schema type from a middleware (with optional defaults)\n */\nexport type InferMiddlewareContextInput<T extends AgentMiddleware> = T extends AgentMiddleware<any, infer TContextSchema, any, any> ? TContextSchema extends InteropZodOptional<infer Inner> ? InferInteropZodInput<Inner> | undefined : TContextSchema extends InteropZodObject ? InferInteropZodInput<TContextSchema> : {} : {};\n/**\n * Helper type to infer merged context from an array of middleware\n */\nexport type InferMiddlewareContexts<T extends readonly AgentMiddleware[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? InferMiddlewareContext<First> & InferMiddlewareContexts<Rest> : InferMiddlewareContext<First> : {} : {};\n/**\n * Helper to merge two context types, preserving undefined unions\n */\ntype MergeContextTypes<A, B> = [A] extends [undefined] ? [B] extends [undefined] ? undefined : B | undefined : [B] extends [undefined] ? A | undefined : [A] extends [B] ? A : [B] extends [A] ? B : A & B;\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[]> = T extends readonly [] ? {} : T extends readonly [infer First, ...infer Rest] ? First extends AgentMiddleware ? Rest extends readonly AgentMiddleware[] ? MergeContextTypes<InferMiddlewareContextInput<First>, InferMiddlewareContextInputs<Rest>> : InferMiddlewareContextInput<First> : {} : {};\n/**\n * Helper type to extract input type from context schema (with optional defaults)\n */\nexport type InferContextInput<ContextSchema extends AnyAnnotationRoot | InteropZodObject> = ContextSchema extends InteropZodObject ? InferInteropZodInput<ContextSchema> : ContextSchema extends AnyAnnotationRoot ? ToAnnotationRoot<ContextSchema>[\"State\"] : {};\nexport type ToAnnotationRoot<A extends StateDefinitionInit> = A extends AnyAnnotationRoot ? A : A extends InteropZodObject ? InteropZodToStateDefinition<A> : never;\nexport type InferSchemaInput<A extends StateDefinitionInit | undefined> = A extends StateSchema<infer TFields> ? InferStateSchemaUpdate<TFields> : A extends InteropZodObject ? InferInteropZodOutput<A> : A extends AnyAnnotationRoot ? A[\"State\"] : {};\nexport {};\n//# sourceMappingURL=types.d.ts.map"],"mappings":";;;;;;;;;;;KAUKqB,oBAAoBC,IAAIC,QAAQD;AAAhCD,KACOG,iBAAAA,GAAoBlB,cADb,CAAA,GAAA,CAAA;;;;AAAiB;AACpC;AA6BA;;;;;;;;;;;;;;;;;;;;;AAQiB;AAMjB;AACYyB,UAfKN,oBAegBC,CAAAA,kBAfqBjB,mBAerB,GAAA,SAAA,GAfuDA,mBAevD,GAAA,SAAA,EAAA,yBAf+GT,gBAe/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