@illuma-ai/agents 1.5.1 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/README.md +0 -62
  2. package/dist/cjs/agents/AgentContext.cjs +160 -259
  3. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  4. package/dist/cjs/common/enum.cjs +12 -12
  5. package/dist/cjs/common/enum.cjs.map +1 -1
  6. package/dist/cjs/graphs/Graph.cjs +30 -13
  7. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
  9. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  10. package/dist/cjs/graphs/phases/memoryFlushPhase.cjs +1 -1
  11. package/dist/cjs/graphs/phases/memoryFlushPhase.cjs.map +1 -1
  12. package/dist/cjs/hooks/HookRegistry.cjs +1 -1
  13. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  14. package/dist/cjs/hooks/matchers.cjs +2 -2
  15. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  16. package/dist/cjs/hooks/types.cjs +1 -1
  17. package/dist/cjs/hooks/types.cjs.map +1 -1
  18. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -5
  19. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  20. package/dist/cjs/llm/bedrock/index.cjs +33 -61
  21. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  22. package/dist/cjs/llm/openai/index.cjs +1 -1
  23. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  24. package/dist/cjs/llm/openai/utils/index.cjs +10 -27
  25. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  26. package/dist/cjs/main.cjs +3 -84
  27. package/dist/cjs/main.cjs.map +1 -1
  28. package/dist/cjs/memory/citations.cjs +4 -4
  29. package/dist/cjs/memory/citations.cjs.map +1 -1
  30. package/dist/cjs/memory/constants.cjs +17 -17
  31. package/dist/cjs/memory/constants.cjs.map +1 -1
  32. package/dist/cjs/memory/mmr.cjs +1 -1
  33. package/dist/cjs/memory/mmr.cjs.map +1 -1
  34. package/dist/cjs/memory/paths.cjs +1 -1
  35. package/dist/cjs/memory/paths.cjs.map +1 -1
  36. package/dist/cjs/memory/recallTracking.cjs +3 -3
  37. package/dist/cjs/memory/recallTracking.cjs.map +1 -1
  38. package/dist/cjs/memory/temporalDecay.cjs +2 -2
  39. package/dist/cjs/memory/temporalDecay.cjs.map +1 -1
  40. package/dist/cjs/messages/cache.cjs +0 -89
  41. package/dist/cjs/messages/cache.cjs.map +1 -1
  42. package/dist/cjs/messages/format.cjs +13 -71
  43. package/dist/cjs/messages/format.cjs.map +1 -1
  44. package/dist/cjs/tools/BashExecutor.cjs +11 -21
  45. package/dist/cjs/tools/BashExecutor.cjs.map +1 -1
  46. package/dist/cjs/tools/CodeExecutor.cjs +13 -41
  47. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  48. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +11 -16
  49. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  50. package/dist/cjs/tools/ToolNode.cjs +78 -13
  51. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  52. package/dist/cjs/tools/memory/memoryAppendTool.cjs +1 -1
  53. package/dist/cjs/tools/memory/memoryAppendTool.cjs.map +1 -1
  54. package/dist/cjs/tools/memory/memoryGetTool.cjs +2 -2
  55. package/dist/cjs/tools/memory/memoryGetTool.cjs.map +1 -1
  56. package/dist/cjs/tools/memory/memorySearchTool.cjs +3 -3
  57. package/dist/cjs/tools/memory/memorySearchTool.cjs.map +1 -1
  58. package/dist/cjs/tools/memory/shared.cjs +1 -1
  59. package/dist/cjs/tools/memory/shared.cjs.map +1 -1
  60. package/dist/cjs/tools/search/search.cjs +3 -11
  61. package/dist/cjs/tools/search/search.cjs.map +1 -1
  62. package/dist/cjs/tools/search/tool.cjs +4 -28
  63. package/dist/cjs/tools/search/tool.cjs.map +1 -1
  64. package/dist/cjs/tools/search/utils.cjs +3 -10
  65. package/dist/cjs/tools/search/utils.cjs.map +1 -1
  66. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +48 -0
  67. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  68. package/dist/cjs/types/graph.cjs.map +1 -1
  69. package/dist/esm/agents/AgentContext.mjs +160 -259
  70. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  71. package/dist/esm/common/enum.mjs +12 -12
  72. package/dist/esm/common/enum.mjs.map +1 -1
  73. package/dist/esm/graphs/Graph.mjs +30 -13
  74. package/dist/esm/graphs/Graph.mjs.map +1 -1
  75. package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
  76. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  77. package/dist/esm/graphs/phases/memoryFlushPhase.mjs +1 -1
  78. package/dist/esm/graphs/phases/memoryFlushPhase.mjs.map +1 -1
  79. package/dist/esm/hooks/HookRegistry.mjs +1 -1
  80. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  81. package/dist/esm/hooks/matchers.mjs +2 -2
  82. package/dist/esm/hooks/matchers.mjs.map +1 -1
  83. package/dist/esm/hooks/types.mjs +1 -1
  84. package/dist/esm/hooks/types.mjs.map +1 -1
  85. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -5
  86. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  87. package/dist/esm/llm/bedrock/index.mjs +34 -61
  88. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  89. package/dist/esm/llm/openai/index.mjs +1 -1
  90. package/dist/esm/llm/openai/index.mjs.map +1 -1
  91. package/dist/esm/llm/openai/utils/index.mjs +10 -27
  92. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  93. package/dist/esm/main.mjs +1 -5
  94. package/dist/esm/main.mjs.map +1 -1
  95. package/dist/esm/memory/citations.mjs +4 -4
  96. package/dist/esm/memory/citations.mjs.map +1 -1
  97. package/dist/esm/memory/constants.mjs +17 -17
  98. package/dist/esm/memory/constants.mjs.map +1 -1
  99. package/dist/esm/memory/mmr.mjs +1 -1
  100. package/dist/esm/memory/mmr.mjs.map +1 -1
  101. package/dist/esm/memory/paths.mjs +1 -1
  102. package/dist/esm/memory/paths.mjs.map +1 -1
  103. package/dist/esm/memory/recallTracking.mjs +3 -3
  104. package/dist/esm/memory/recallTracking.mjs.map +1 -1
  105. package/dist/esm/memory/temporalDecay.mjs +2 -2
  106. package/dist/esm/memory/temporalDecay.mjs.map +1 -1
  107. package/dist/esm/messages/cache.mjs +0 -89
  108. package/dist/esm/messages/cache.mjs.map +1 -1
  109. package/dist/esm/messages/format.mjs +13 -71
  110. package/dist/esm/messages/format.mjs.map +1 -1
  111. package/dist/esm/tools/BashExecutor.mjs +12 -22
  112. package/dist/esm/tools/BashExecutor.mjs.map +1 -1
  113. package/dist/esm/tools/CodeExecutor.mjs +14 -41
  114. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  115. package/dist/esm/tools/ProgrammaticToolCalling.mjs +12 -17
  116. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  117. package/dist/esm/tools/ToolNode.mjs +78 -13
  118. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  119. package/dist/esm/tools/memory/memoryAppendTool.mjs +1 -1
  120. package/dist/esm/tools/memory/memoryAppendTool.mjs.map +1 -1
  121. package/dist/esm/tools/memory/memoryGetTool.mjs +2 -2
  122. package/dist/esm/tools/memory/memoryGetTool.mjs.map +1 -1
  123. package/dist/esm/tools/memory/memorySearchTool.mjs +3 -3
  124. package/dist/esm/tools/memory/memorySearchTool.mjs.map +1 -1
  125. package/dist/esm/tools/memory/shared.mjs +1 -1
  126. package/dist/esm/tools/memory/shared.mjs.map +1 -1
  127. package/dist/esm/tools/search/search.mjs +3 -11
  128. package/dist/esm/tools/search/search.mjs.map +1 -1
  129. package/dist/esm/tools/search/tool.mjs +4 -28
  130. package/dist/esm/tools/search/tool.mjs.map +1 -1
  131. package/dist/esm/tools/search/utils.mjs +3 -10
  132. package/dist/esm/tools/search/utils.mjs.map +1 -1
  133. package/dist/esm/tools/subagent/SubagentExecutor.mjs +48 -0
  134. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  135. package/dist/esm/types/graph.mjs.map +1 -1
  136. package/dist/types/agents/AgentContext.d.ts +25 -95
  137. package/dist/types/common/enum.d.ts +12 -12
  138. package/dist/types/graphs/Graph.d.ts +2 -2
  139. package/dist/types/graphs/phases/memoryFlushPhase.d.ts +2 -2
  140. package/dist/types/hooks/HookRegistry.d.ts +1 -1
  141. package/dist/types/hooks/matchers.d.ts +2 -2
  142. package/dist/types/hooks/types.d.ts +1 -1
  143. package/dist/types/index.d.ts +0 -1
  144. package/dist/types/llm/bedrock/index.d.ts +1 -54
  145. package/dist/types/llm/openai/index.d.ts +1 -1
  146. package/dist/types/memory/citations.d.ts +4 -4
  147. package/dist/types/memory/constants.d.ts +17 -17
  148. package/dist/types/memory/mmr.d.ts +3 -3
  149. package/dist/types/memory/paths.d.ts +1 -1
  150. package/dist/types/memory/temporalDecay.d.ts +2 -2
  151. package/dist/types/memory/types.d.ts +3 -3
  152. package/dist/types/messages/format.d.ts +2 -5
  153. package/dist/types/tools/CodeExecutor.d.ts +0 -6
  154. package/dist/types/tools/ToolNode.d.ts +3 -3
  155. package/dist/types/tools/memory/shared.d.ts +1 -1
  156. package/dist/types/tools/search/test.d.ts +1 -0
  157. package/dist/types/tools/search/types.d.ts +5 -99
  158. package/dist/types/tools/search/utils.d.ts +2 -2
  159. package/dist/types/tools/subagent/SubagentExecutor.d.ts +29 -0
  160. package/dist/types/types/graph.d.ts +30 -34
  161. package/dist/types/types/index.d.ts +0 -1
  162. package/dist/types/types/messages.d.ts +1 -1
  163. package/dist/types/types/run.d.ts +1 -3
  164. package/dist/types/types/tools.d.ts +5 -14
  165. package/package.json +1 -61
  166. package/src/agents/AgentContext.test.ts +176 -0
  167. package/src/agents/AgentContext.ts +179 -305
  168. package/src/agents/__tests__/AgentContext.test.ts +0 -632
  169. package/src/common/__tests__/enum.test.ts +1 -1
  170. package/src/common/enum.ts +12 -12
  171. package/src/graphs/Graph.ts +32 -13
  172. package/src/graphs/MultiAgentGraph.ts +1 -1
  173. package/src/graphs/gapFeatures.test.ts +1 -1
  174. package/src/graphs/phases/__tests__/memoryFlushPhase.test.ts +1 -1
  175. package/src/graphs/phases/memoryFlushPhase.ts +2 -2
  176. package/src/hooks/HookRegistry.ts +1 -1
  177. package/src/hooks/index.ts +1 -1
  178. package/src/hooks/matchers.ts +2 -2
  179. package/src/hooks/types.ts +1 -1
  180. package/src/index.ts +0 -6
  181. package/src/llm/anthropic/utils/message_inputs.ts +1 -10
  182. package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +18 -166
  183. package/src/llm/bedrock/index.ts +41 -116
  184. package/src/llm/openai/index.ts +2 -2
  185. package/src/llm/openai/utils/index.ts +14 -31
  186. package/src/memory/citations.ts +4 -4
  187. package/src/memory/constants.ts +17 -17
  188. package/src/memory/mmr.ts +3 -3
  189. package/src/memory/paths.ts +1 -1
  190. package/src/memory/recallTracking.ts +3 -3
  191. package/src/memory/temporalDecay.ts +2 -2
  192. package/src/memory/types.ts +3 -3
  193. package/src/messages/cache.test.ts +24 -62
  194. package/src/messages/cache.ts +0 -112
  195. package/src/messages/ensureThinkingBlock.test.ts +1 -1
  196. package/src/messages/format.ts +13 -92
  197. package/src/messages/formatAgentMessages.test.ts +1 -1
  198. package/src/scripts/subagent-configurable-inheritance.ts +263 -0
  199. package/src/scripts/subagent-event-driven-debug.ts +2 -2
  200. package/src/specs/anthropic.simple.test.ts +0 -61
  201. package/src/specs/prune.orphans.test.ts +1 -1
  202. package/src/tools/BashExecutor.ts +13 -37
  203. package/src/tools/CodeExecutor.ts +14 -59
  204. package/src/tools/ProgrammaticToolCalling.ts +14 -29
  205. package/src/tools/ToolNode.ts +75 -14
  206. package/src/tools/__tests__/CodeExecutor.test.ts +3 -3
  207. package/src/tools/__tests__/ProgrammaticToolCalling.test.ts +0 -60
  208. package/src/tools/__tests__/SubagentExecutor.test.ts +157 -0
  209. package/src/tools/memory/memoryAppendTool.ts +1 -1
  210. package/src/tools/memory/memoryGetTool.ts +2 -2
  211. package/src/tools/memory/memorySearchTool.ts +3 -3
  212. package/src/tools/memory/shared.ts +1 -1
  213. package/src/tools/search/output.md +2775 -0
  214. package/src/tools/search/search.ts +2 -12
  215. package/src/tools/search/test.html +884 -0
  216. package/src/tools/search/test.md +643 -0
  217. package/src/tools/search/test.ts +159 -0
  218. package/src/tools/search/tool.ts +2 -36
  219. package/src/tools/search/types.ts +8 -133
  220. package/src/tools/search/utils.ts +5 -13
  221. package/src/tools/subagent/SubagentExecutor.ts +78 -0
  222. package/src/types/graph.ts +27 -34
  223. package/src/types/index.ts +0 -1
  224. package/src/types/messages.ts +1 -1
  225. package/src/types/run.ts +1 -3
  226. package/src/types/tools.ts +5 -14
  227. package/dist/cjs/langchain/google-common.cjs +0 -3
  228. package/dist/cjs/langchain/google-common.cjs.map +0 -1
  229. package/dist/cjs/langchain/index.cjs +0 -86
  230. package/dist/cjs/langchain/index.cjs.map +0 -1
  231. package/dist/cjs/langchain/language_models/chat_models.cjs +0 -3
  232. package/dist/cjs/langchain/language_models/chat_models.cjs.map +0 -1
  233. package/dist/cjs/langchain/messages/tool.cjs +0 -3
  234. package/dist/cjs/langchain/messages/tool.cjs.map +0 -1
  235. package/dist/cjs/langchain/messages.cjs +0 -51
  236. package/dist/cjs/langchain/messages.cjs.map +0 -1
  237. package/dist/cjs/langchain/openai.cjs +0 -3
  238. package/dist/cjs/langchain/openai.cjs.map +0 -1
  239. package/dist/cjs/langchain/prompts.cjs +0 -11
  240. package/dist/cjs/langchain/prompts.cjs.map +0 -1
  241. package/dist/cjs/langchain/runnables.cjs +0 -19
  242. package/dist/cjs/langchain/runnables.cjs.map +0 -1
  243. package/dist/cjs/langchain/tools.cjs +0 -23
  244. package/dist/cjs/langchain/tools.cjs.map +0 -1
  245. package/dist/cjs/langchain/utils/env.cjs +0 -11
  246. package/dist/cjs/langchain/utils/env.cjs.map +0 -1
  247. package/dist/cjs/llm/bedrock/cacheSupport.cjs +0 -55
  248. package/dist/cjs/llm/bedrock/cacheSupport.cjs.map +0 -1
  249. package/dist/cjs/tools/search/tavily-scraper.cjs +0 -189
  250. package/dist/cjs/tools/search/tavily-scraper.cjs.map +0 -1
  251. package/dist/cjs/tools/search/tavily-search.cjs +0 -372
  252. package/dist/cjs/tools/search/tavily-search.cjs.map +0 -1
  253. package/dist/cjs/types/agent-cache.cjs +0 -54
  254. package/dist/cjs/types/agent-cache.cjs.map +0 -1
  255. package/dist/esm/langchain/google-common.mjs +0 -2
  256. package/dist/esm/langchain/google-common.mjs.map +0 -1
  257. package/dist/esm/langchain/index.mjs +0 -5
  258. package/dist/esm/langchain/index.mjs.map +0 -1
  259. package/dist/esm/langchain/language_models/chat_models.mjs +0 -2
  260. package/dist/esm/langchain/language_models/chat_models.mjs.map +0 -1
  261. package/dist/esm/langchain/messages/tool.mjs +0 -2
  262. package/dist/esm/langchain/messages/tool.mjs.map +0 -1
  263. package/dist/esm/langchain/messages.mjs +0 -2
  264. package/dist/esm/langchain/messages.mjs.map +0 -1
  265. package/dist/esm/langchain/openai.mjs +0 -2
  266. package/dist/esm/langchain/openai.mjs.map +0 -1
  267. package/dist/esm/langchain/prompts.mjs +0 -2
  268. package/dist/esm/langchain/prompts.mjs.map +0 -1
  269. package/dist/esm/langchain/runnables.mjs +0 -2
  270. package/dist/esm/langchain/runnables.mjs.map +0 -1
  271. package/dist/esm/langchain/tools.mjs +0 -2
  272. package/dist/esm/langchain/tools.mjs.map +0 -1
  273. package/dist/esm/langchain/utils/env.mjs +0 -2
  274. package/dist/esm/langchain/utils/env.mjs.map +0 -1
  275. package/dist/esm/llm/bedrock/cacheSupport.mjs +0 -52
  276. package/dist/esm/llm/bedrock/cacheSupport.mjs.map +0 -1
  277. package/dist/esm/tools/search/tavily-scraper.mjs +0 -186
  278. package/dist/esm/tools/search/tavily-scraper.mjs.map +0 -1
  279. package/dist/esm/tools/search/tavily-search.mjs +0 -370
  280. package/dist/esm/tools/search/tavily-search.mjs.map +0 -1
  281. package/dist/esm/types/agent-cache.mjs +0 -52
  282. package/dist/esm/types/agent-cache.mjs.map +0 -1
  283. package/dist/types/langchain/google-common.d.ts +0 -1
  284. package/dist/types/langchain/index.d.ts +0 -8
  285. package/dist/types/langchain/language_models/chat_models.d.ts +0 -1
  286. package/dist/types/langchain/messages/tool.d.ts +0 -1
  287. package/dist/types/langchain/messages.d.ts +0 -2
  288. package/dist/types/langchain/openai.d.ts +0 -1
  289. package/dist/types/langchain/prompts.d.ts +0 -1
  290. package/dist/types/langchain/runnables.d.ts +0 -2
  291. package/dist/types/langchain/tools.d.ts +0 -2
  292. package/dist/types/langchain/utils/env.d.ts +0 -1
  293. package/dist/types/llm/bedrock/cacheSupport.d.ts +0 -35
  294. package/dist/types/tools/search/tavily-scraper.d.ts +0 -19
  295. package/dist/types/tools/search/tavily-search.d.ts +0 -4
  296. package/dist/types/tools/subagent/types.d.ts +0 -84
  297. package/dist/types/types/agent-cache.d.ts +0 -71
  298. package/src/agents/__tests__/AgentContext.cacheTtl.live.test.ts +0 -259
  299. package/src/agents/__tests__/AgentContext.crossAgentTier1.live.test.ts +0 -266
  300. package/src/agents/__tests__/AgentContext.crossUserCache.live.test.ts +0 -342
  301. package/src/langchain/google-common.ts +0 -1
  302. package/src/langchain/index.ts +0 -8
  303. package/src/langchain/language_models/chat_models.ts +0 -1
  304. package/src/langchain/messages/tool.ts +0 -5
  305. package/src/langchain/messages.ts +0 -21
  306. package/src/langchain/openai.ts +0 -1
  307. package/src/langchain/prompts.ts +0 -1
  308. package/src/langchain/runnables.ts +0 -7
  309. package/src/langchain/tools.ts +0 -8
  310. package/src/langchain/utils/env.ts +0 -1
  311. package/src/llm/anthropic/utils/server-tool-inputs.test.ts +0 -436
  312. package/src/llm/bedrock/cacheSupport.test.ts +0 -99
  313. package/src/llm/bedrock/cacheSupport.ts +0 -53
  314. package/src/tools/search/tavily-scraper.ts +0 -235
  315. package/src/tools/search/tavily-search.ts +0 -424
  316. package/src/tools/search/tavily.test.ts +0 -965
  317. package/src/tools/subagent/types.test.ts +0 -70
  318. package/src/tools/subagent/types.ts +0 -115
  319. package/src/types/agent-cache.ts +0 -74
@@ -1 +1 @@
1
- {"version":3,"file":"types.cjs","sources":["../../../src/hooks/types.ts"],"sourcesContent":["// src/hooks/types.ts\nimport type { BaseMessage } from '@langchain/core/messages';\n\n/**\n * Closed set of hook lifecycle events supported by the hooks system.\n *\n * These mirror the subset of Claude Code's event surface that makes sense\n * for a library context (no filesystem/CLI-specific events). See\n * `docs/hooks-design-report.md` §3.2 for the mapping to existing\n * `@illuma-ai/agents` emission points.\n */\nexport const HOOK_EVENTS = [\n 'RunStart',\n 'UserPromptSubmit',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PermissionDenied',\n 'SubagentStart',\n 'SubagentStop',\n 'Stop',\n 'StopFailure',\n 'PreCompact',\n 'PostCompact',\n] as const;\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** Tool-gating decision; executeHooks folds with `deny > ask > allow` precedence. */\nexport type ToolDecision = 'allow' | 'deny' | 'ask';\n\n/** Stop-loop decision; `block` means \"do not stop, run another turn\". Any `block` wins. */\nexport type StopDecision = 'continue' | 'block';\n\n/**\n * Fields shared by every `HookInput`. Discriminated by `hook_event_name`.\n *\n * - `runId` identifies the current agent run and is always present.\n * - `threadId` identifies the conversation thread when the host has one.\n * - `agentId` is only set when the hook fires inside a subagent scope.\n */\nexport interface BaseHookInput {\n runId: string;\n threadId?: string;\n agentId?: string;\n}\n\nexport interface RunStartHookInput extends BaseHookInput {\n hook_event_name: 'RunStart';\n messages: BaseMessage[];\n}\n\nexport interface UserPromptSubmitHookInput extends BaseHookInput {\n hook_event_name: 'UserPromptSubmit';\n prompt: string;\n attachments?: BaseMessage[];\n}\n\n/**\n * Fires before a tool is invoked. Hook may return `deny`/`ask`/`allow` and/or\n * an `updatedInput` that replaces the tool arguments before invocation.\n *\n * `toolInput` is intentionally typed as `Record<string, unknown>` because the\n * SDK is tool-agnostic — concrete tool argument shapes are only known at the\n * call site and are narrowed by the host. This is the one escape hatch in\n * the hook type system.\n */\nexport interface PreToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PreToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n /**\n * Number of times this tool has been invoked in prior batches within the\n * current run. Within a single batch of parallel calls, all calls to the\n * same tool share the same turn value — per-call discrimination within a\n * batch is not supported in v1.\n */\n turn?: number;\n}\n\nexport interface PostToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PostToolUseFailureHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUseFailure';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n error: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PermissionDeniedHookInput extends BaseHookInput {\n hook_event_name: 'PermissionDenied';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n reason: string;\n}\n\nexport interface SubagentStartHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStart';\n parentAgentId?: string;\n agentId: string;\n agentType: string;\n inputs: BaseMessage[];\n}\n\nexport interface SubagentStopHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStop';\n agentId: string;\n agentType: string;\n messages: BaseMessage[];\n}\n\nexport interface StopHookInput extends BaseHookInput {\n hook_event_name: 'Stop';\n messages: BaseMessage[];\n stopReason?: string;\n stopHookActive: boolean;\n}\n\nexport interface StopFailureHookInput extends BaseHookInput {\n hook_event_name: 'StopFailure';\n error: string;\n lastAssistantMessage?: BaseMessage;\n}\n\nexport interface PreCompactHookInput extends BaseHookInput {\n hook_event_name: 'PreCompact';\n messagesBeforeCount: number;\n /**\n * What triggered compaction. Matches `SummarizationTrigger.type` from the\n * agent's summarization config. `'default'` means no trigger was\n * configured and compaction fired because messages were pruned.\n */\n trigger:\n | 'token_ratio'\n | 'remaining_tokens'\n | 'messages_to_refine'\n | 'default'\n | (string & {});\n}\n\nexport interface PostCompactHookInput extends BaseHookInput {\n hook_event_name: 'PostCompact';\n summary: string;\n /**\n * Number of messages remaining after compaction. The summarize node\n * returns a `removeAll` signal that clears all messages from state;\n * the summary itself is injected into the system prompt, not as a\n * message. This is `0` at the point of hook dispatch.\n */\n messagesAfterCount: number;\n}\n\n/** Discriminated union of every hook input shape. */\nexport type HookInput =\n | RunStartHookInput\n | UserPromptSubmitHookInput\n | PreToolUseHookInput\n | PostToolUseHookInput\n | PostToolUseFailureHookInput\n | PermissionDeniedHookInput\n | SubagentStartHookInput\n | SubagentStopHookInput\n | StopHookInput\n | StopFailureHookInput\n | PreCompactHookInput\n | PostCompactHookInput;\n\n/** Compile-time map from event name to its input shape. */\nexport type HookInputByEvent = {\n RunStart: RunStartHookInput;\n UserPromptSubmit: UserPromptSubmitHookInput;\n PreToolUse: PreToolUseHookInput;\n PostToolUse: PostToolUseHookInput;\n PostToolUseFailure: PostToolUseFailureHookInput;\n PermissionDenied: PermissionDeniedHookInput;\n SubagentStart: SubagentStartHookInput;\n SubagentStop: SubagentStopHookInput;\n Stop: StopHookInput;\n StopFailure: StopFailureHookInput;\n PreCompact: PreCompactHookInput;\n PostCompact: PostCompactHookInput;\n};\n\n/**\n * Fields common to every hook output. Hooks that have nothing to say simply\n * return `{}` (or omit the fields below).\n */\nexport interface BaseHookOutput {\n /** Context string to inject into the conversation. Accumulated across hooks. */\n additionalContext?: string;\n /** True to prevent the next model turn. Any hook can set this. */\n preventContinuation?: boolean;\n /** Reason reported alongside `preventContinuation`. */\n stopReason?: string;\n}\n\nexport type RunStartHookOutput = BaseHookOutput;\n\nexport interface UserPromptSubmitHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport interface PreToolUseHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n /**\n * Replacement tool input. Merged into the pending tool call by the host.\n *\n * When multiple hooks set `updatedInput` within a single `executeHooks`\n * call, the last writer in registration order wins (outer loop: matcher\n * registration order; inner loop: hook position within the matcher). The\n * winner is deterministic — `Promise.all` preserves input-array order.\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput` to one hook per matcher to avoid confusing precedence.\n */\n updatedInput?: Record<string, unknown>;\n}\n\nexport interface PostToolUseHookOutput extends BaseHookOutput {\n /**\n * Replacement tool output. Flows through the aggregated result so the\n * host can substitute it before appending the tool result message.\n * Ordering semantics match `PreToolUseHookOutput.updatedInput`:\n * last-writer-wins in registration order.\n */\n updatedOutput?: unknown;\n}\n\nexport type PostToolUseFailureHookOutput = BaseHookOutput;\n\nexport type PermissionDeniedHookOutput = BaseHookOutput;\n\nexport interface SubagentStartHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport type SubagentStopHookOutput = BaseHookOutput;\n\nexport interface StopHookOutput extends BaseHookOutput {\n decision?: StopDecision;\n reason?: string;\n}\n\nexport type StopFailureHookOutput = BaseHookOutput;\n\nexport type PreCompactHookOutput = BaseHookOutput;\n\nexport type PostCompactHookOutput = BaseHookOutput;\n\n/** Compile-time map from event name to its output shape. */\nexport type HookOutputByEvent = {\n RunStart: RunStartHookOutput;\n UserPromptSubmit: UserPromptSubmitHookOutput;\n PreToolUse: PreToolUseHookOutput;\n PostToolUse: PostToolUseHookOutput;\n PostToolUseFailure: PostToolUseFailureHookOutput;\n PermissionDenied: PermissionDeniedHookOutput;\n SubagentStart: SubagentStartHookOutput;\n SubagentStop: SubagentStopHookOutput;\n Stop: StopHookOutput;\n StopFailure: StopFailureHookOutput;\n PreCompact: PreCompactHookOutput;\n PostCompact: PostCompactHookOutput;\n};\n\n/** Superset output shape used by the executor's fold loop. */\nexport type HookOutput =\n | RunStartHookOutput\n | UserPromptSubmitHookOutput\n | PreToolUseHookOutput\n | PostToolUseHookOutput\n | PostToolUseFailureHookOutput\n | PermissionDeniedHookOutput\n | SubagentStartHookOutput\n | SubagentStopHookOutput\n | StopHookOutput\n | StopFailureHookOutput\n | PreCompactHookOutput\n | PostCompactHookOutput;\n\n/**\n * A hook callback is a plain async function registered against a specific\n * event. The `signal` is always supplied by `executeHooks` and combines the\n * batch's parent signal with the per-hook timeout — callbacks that perform\n * long-running work should observe it.\n */\nexport type HookCallback<E extends HookEvent = HookEvent> = (\n input: HookInputByEvent[E],\n signal: AbortSignal\n) => HookOutputByEvent[E] | Promise<HookOutputByEvent[E]>;\n\n/**\n * A matcher groups one or more callbacks under a shared regex filter and\n * shared timeout/once/internal flags. The generic `E` ties the callback\n * types to the event the matcher is registered against.\n */\nexport interface HookMatcher<E extends HookEvent = HookEvent> {\n /**\n * Regex pattern matched against the event's primary query string (e.g.\n * the tool name for `PreToolUse`, the agent type for `SubagentStart`).\n *\n * Omitted or empty means \"always match\". For events that do not supply a\n * query string (`RunStart`, `Stop`, etc.), only wildcard matchers fire —\n * a non-empty pattern on such events will never match.\n *\n * Patterns are treated as trusted input: `executeHooks` compiles them\n * with `new RegExp(pattern)` without any sandbox, and a pathological\n * pattern can block the event loop. Host registration code is expected\n * to validate or length-bound patterns that originate from user input.\n */\n pattern?: string;\n /** Callbacks that fire when the matcher hits. Executed in parallel. */\n hooks: HookCallback<E>[];\n /** Per-matcher timeout in ms. Defaults to the executor's batch timeout. */\n timeout?: number;\n /**\n * Atomically remove the matcher before its first dispatch.\n *\n * `executeHooks` claims `once: true` matchers synchronously — between\n * `getMatchers` and its first `await` — so two concurrent calls cannot\n * both dispatch the same matcher. Whichever call runs its sync prefix\n * first wins the matcher; the other sees an empty bucket.\n *\n * Semantics are \"at most one dispatch, ever\" — if every hook in the\n * matcher throws, the matcher is still gone. Use `once` for\n * fire-and-forget bootstrapping (registration, telemetry, setup). Hosts\n * that need retry semantics should register a normal matcher and\n * self-unregister via the callback returned from `registry.register`.\n */\n once?: boolean;\n /** Internal hooks are excluded from telemetry and non-fatal error logging. */\n internal?: boolean;\n}\n\n/**\n * Storage shape for matchers keyed by event. Each event's matcher list is\n * a generic array parameterized by that event type, so lookup via\n * `HooksByEvent[E]` preserves type-safe callback signatures.\n */\nexport type HooksByEvent = {\n [E in HookEvent]?: HookMatcher<E>[];\n};\n\n/**\n * Aggregated result of a single `executeHooks` call. Fields are populated\n * according to the fold rules in `executeHooks.ts`.\n */\nexport interface AggregatedHookResult {\n /** Folded tool-gating decision; `deny > ask > allow`. */\n decision?: ToolDecision;\n /** Folded stop decision; any `block` wins. */\n stopDecision?: StopDecision;\n /** Reason from the hook that set the winning decision. */\n reason?: string;\n /**\n * Replacement tool input from a `PreToolUse` hook.\n *\n * Last-writer-wins in **registration order**: `executeHooks` uses\n * `Promise.all`, which preserves input-array order, so the fold iterates\n * outcomes in the same order they were pushed — outer loop over matchers\n * as they sit in the registry, inner loop over each matcher's `hooks`\n * array. The winner is therefore deterministic but may not match the\n * order in which hooks actually completed. Consumers that want a single\n * authoritative rewrite should still register one `updatedInput`-setting\n * hook per matcher to avoid subtle precedence bugs.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Replacement tool output from a `PostToolUse` hook.\n *\n * Same last-writer-wins-in-registration-order semantics as\n * `updatedInput`. Present only when at least one hook set it; `undefined`\n * means \"use the original tool output\".\n */\n updatedOutput?: unknown;\n /** Accumulated `additionalContext` strings from every hook, in order. */\n additionalContexts: string[];\n /** True if any hook returned `preventContinuation`. */\n preventContinuation?: boolean;\n /**\n * Reason recorded alongside `preventContinuation`. First winner wins:\n * once a hook sets both flags, later hooks that also set\n * `preventContinuation` do not overwrite the reason.\n */\n stopReason?: string;\n /** Error messages from hooks that threw; always present (possibly empty). */\n errors: string[];\n}\n"],"names":[],"mappings":";;AAGA;;;;;;;AAOG;AACI,MAAM,WAAW,GAAG;IACzB,UAAU;IACV,kBAAkB;IAClB,YAAY;IACZ,aAAa;IACb,oBAAoB;IACpB,kBAAkB;IAClB,eAAe;IACf,cAAc;IACd,MAAM;IACN,aAAa;IACb,YAAY;IACZ,aAAa;;;;;"}
1
+ {"version":3,"file":"types.cjs","sources":["../../../src/hooks/types.ts"],"sourcesContent":["// src/hooks/types.ts\nimport type { BaseMessage } from '@langchain/core/messages';\n\n/**\n * Closed set of hook lifecycle events supported by the hooks system.\n *\n * These mirror the subset of Claude Code's event surface that makes sense\n * for a library context (no filesystem/CLI-specific events). See\n * `docs/hooks-design-report.md` §3.2 for the mapping to existing\n * `@librechat/agents` emission points.\n */\nexport const HOOK_EVENTS = [\n 'RunStart',\n 'UserPromptSubmit',\n 'PreToolUse',\n 'PostToolUse',\n 'PostToolUseFailure',\n 'PermissionDenied',\n 'SubagentStart',\n 'SubagentStop',\n 'Stop',\n 'StopFailure',\n 'PreCompact',\n 'PostCompact',\n] as const;\n\nexport type HookEvent = (typeof HOOK_EVENTS)[number];\n\n/** Tool-gating decision; executeHooks folds with `deny > ask > allow` precedence. */\nexport type ToolDecision = 'allow' | 'deny' | 'ask';\n\n/** Stop-loop decision; `block` means \"do not stop, run another turn\". Any `block` wins. */\nexport type StopDecision = 'continue' | 'block';\n\n/**\n * Fields shared by every `HookInput`. Discriminated by `hook_event_name`.\n *\n * - `runId` identifies the current agent run and is always present.\n * - `threadId` identifies the conversation thread when the host has one.\n * - `agentId` is only set when the hook fires inside a subagent scope.\n */\nexport interface BaseHookInput {\n runId: string;\n threadId?: string;\n agentId?: string;\n}\n\nexport interface RunStartHookInput extends BaseHookInput {\n hook_event_name: 'RunStart';\n messages: BaseMessage[];\n}\n\nexport interface UserPromptSubmitHookInput extends BaseHookInput {\n hook_event_name: 'UserPromptSubmit';\n prompt: string;\n attachments?: BaseMessage[];\n}\n\n/**\n * Fires before a tool is invoked. Hook may return `deny`/`ask`/`allow` and/or\n * an `updatedInput` that replaces the tool arguments before invocation.\n *\n * `toolInput` is intentionally typed as `Record<string, unknown>` because the\n * SDK is tool-agnostic — concrete tool argument shapes are only known at the\n * call site and are narrowed by the host. This is the one escape hatch in\n * the hook type system.\n */\nexport interface PreToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PreToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n stepId?: string;\n /**\n * Number of times this tool has been invoked in prior batches within the\n * current run. Within a single batch of parallel calls, all calls to the\n * same tool share the same turn value — per-call discrimination within a\n * batch is not supported in v1.\n */\n turn?: number;\n}\n\nexport interface PostToolUseHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUse';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolOutput: unknown;\n toolUseId: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PostToolUseFailureHookInput extends BaseHookInput {\n hook_event_name: 'PostToolUseFailure';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n error: string;\n stepId?: string;\n turn?: number;\n}\n\nexport interface PermissionDeniedHookInput extends BaseHookInput {\n hook_event_name: 'PermissionDenied';\n toolName: string;\n toolInput: Record<string, unknown>;\n toolUseId: string;\n reason: string;\n}\n\nexport interface SubagentStartHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStart';\n parentAgentId?: string;\n agentId: string;\n agentType: string;\n inputs: BaseMessage[];\n}\n\nexport interface SubagentStopHookInput extends BaseHookInput {\n hook_event_name: 'SubagentStop';\n agentId: string;\n agentType: string;\n messages: BaseMessage[];\n}\n\nexport interface StopHookInput extends BaseHookInput {\n hook_event_name: 'Stop';\n messages: BaseMessage[];\n stopReason?: string;\n stopHookActive: boolean;\n}\n\nexport interface StopFailureHookInput extends BaseHookInput {\n hook_event_name: 'StopFailure';\n error: string;\n lastAssistantMessage?: BaseMessage;\n}\n\nexport interface PreCompactHookInput extends BaseHookInput {\n hook_event_name: 'PreCompact';\n messagesBeforeCount: number;\n /**\n * What triggered compaction. Matches `SummarizationTrigger.type` from the\n * agent's summarization config. `'default'` means no trigger was\n * configured and compaction fired because messages were pruned.\n */\n trigger:\n | 'token_ratio'\n | 'remaining_tokens'\n | 'messages_to_refine'\n | 'default'\n | (string & {});\n}\n\nexport interface PostCompactHookInput extends BaseHookInput {\n hook_event_name: 'PostCompact';\n summary: string;\n /**\n * Number of messages remaining after compaction. The summarize node\n * returns a `removeAll` signal that clears all messages from state;\n * the summary itself is injected into the system prompt, not as a\n * message. This is `0` at the point of hook dispatch.\n */\n messagesAfterCount: number;\n}\n\n/** Discriminated union of every hook input shape. */\nexport type HookInput =\n | RunStartHookInput\n | UserPromptSubmitHookInput\n | PreToolUseHookInput\n | PostToolUseHookInput\n | PostToolUseFailureHookInput\n | PermissionDeniedHookInput\n | SubagentStartHookInput\n | SubagentStopHookInput\n | StopHookInput\n | StopFailureHookInput\n | PreCompactHookInput\n | PostCompactHookInput;\n\n/** Compile-time map from event name to its input shape. */\nexport type HookInputByEvent = {\n RunStart: RunStartHookInput;\n UserPromptSubmit: UserPromptSubmitHookInput;\n PreToolUse: PreToolUseHookInput;\n PostToolUse: PostToolUseHookInput;\n PostToolUseFailure: PostToolUseFailureHookInput;\n PermissionDenied: PermissionDeniedHookInput;\n SubagentStart: SubagentStartHookInput;\n SubagentStop: SubagentStopHookInput;\n Stop: StopHookInput;\n StopFailure: StopFailureHookInput;\n PreCompact: PreCompactHookInput;\n PostCompact: PostCompactHookInput;\n};\n\n/**\n * Fields common to every hook output. Hooks that have nothing to say simply\n * return `{}` (or omit the fields below).\n */\nexport interface BaseHookOutput {\n /** Context string to inject into the conversation. Accumulated across hooks. */\n additionalContext?: string;\n /** True to prevent the next model turn. Any hook can set this. */\n preventContinuation?: boolean;\n /** Reason reported alongside `preventContinuation`. */\n stopReason?: string;\n}\n\nexport type RunStartHookOutput = BaseHookOutput;\n\nexport interface UserPromptSubmitHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport interface PreToolUseHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n /**\n * Replacement tool input. Merged into the pending tool call by the host.\n *\n * When multiple hooks set `updatedInput` within a single `executeHooks`\n * call, the last writer in registration order wins (outer loop: matcher\n * registration order; inner loop: hook position within the matcher). The\n * winner is deterministic — `Promise.all` preserves input-array order.\n * Consumers that need a single authoritative rewrite should still scope\n * `updatedInput` to one hook per matcher to avoid confusing precedence.\n */\n updatedInput?: Record<string, unknown>;\n}\n\nexport interface PostToolUseHookOutput extends BaseHookOutput {\n /**\n * Replacement tool output. Flows through the aggregated result so the\n * host can substitute it before appending the tool result message.\n * Ordering semantics match `PreToolUseHookOutput.updatedInput`:\n * last-writer-wins in registration order.\n */\n updatedOutput?: unknown;\n}\n\nexport type PostToolUseFailureHookOutput = BaseHookOutput;\n\nexport type PermissionDeniedHookOutput = BaseHookOutput;\n\nexport interface SubagentStartHookOutput extends BaseHookOutput {\n decision?: ToolDecision;\n reason?: string;\n}\n\nexport type SubagentStopHookOutput = BaseHookOutput;\n\nexport interface StopHookOutput extends BaseHookOutput {\n decision?: StopDecision;\n reason?: string;\n}\n\nexport type StopFailureHookOutput = BaseHookOutput;\n\nexport type PreCompactHookOutput = BaseHookOutput;\n\nexport type PostCompactHookOutput = BaseHookOutput;\n\n/** Compile-time map from event name to its output shape. */\nexport type HookOutputByEvent = {\n RunStart: RunStartHookOutput;\n UserPromptSubmit: UserPromptSubmitHookOutput;\n PreToolUse: PreToolUseHookOutput;\n PostToolUse: PostToolUseHookOutput;\n PostToolUseFailure: PostToolUseFailureHookOutput;\n PermissionDenied: PermissionDeniedHookOutput;\n SubagentStart: SubagentStartHookOutput;\n SubagentStop: SubagentStopHookOutput;\n Stop: StopHookOutput;\n StopFailure: StopFailureHookOutput;\n PreCompact: PreCompactHookOutput;\n PostCompact: PostCompactHookOutput;\n};\n\n/** Superset output shape used by the executor's fold loop. */\nexport type HookOutput =\n | RunStartHookOutput\n | UserPromptSubmitHookOutput\n | PreToolUseHookOutput\n | PostToolUseHookOutput\n | PostToolUseFailureHookOutput\n | PermissionDeniedHookOutput\n | SubagentStartHookOutput\n | SubagentStopHookOutput\n | StopHookOutput\n | StopFailureHookOutput\n | PreCompactHookOutput\n | PostCompactHookOutput;\n\n/**\n * A hook callback is a plain async function registered against a specific\n * event. The `signal` is always supplied by `executeHooks` and combines the\n * batch's parent signal with the per-hook timeout — callbacks that perform\n * long-running work should observe it.\n */\nexport type HookCallback<E extends HookEvent = HookEvent> = (\n input: HookInputByEvent[E],\n signal: AbortSignal\n) => HookOutputByEvent[E] | Promise<HookOutputByEvent[E]>;\n\n/**\n * A matcher groups one or more callbacks under a shared regex filter and\n * shared timeout/once/internal flags. The generic `E` ties the callback\n * types to the event the matcher is registered against.\n */\nexport interface HookMatcher<E extends HookEvent = HookEvent> {\n /**\n * Regex pattern matched against the event's primary query string (e.g.\n * the tool name for `PreToolUse`, the agent type for `SubagentStart`).\n *\n * Omitted or empty means \"always match\". For events that do not supply a\n * query string (`RunStart`, `Stop`, etc.), only wildcard matchers fire —\n * a non-empty pattern on such events will never match.\n *\n * Patterns are treated as trusted input: `executeHooks` compiles them\n * with `new RegExp(pattern)` without any sandbox, and a pathological\n * pattern can block the event loop. Host registration code is expected\n * to validate or length-bound patterns that originate from user input.\n */\n pattern?: string;\n /** Callbacks that fire when the matcher hits. Executed in parallel. */\n hooks: HookCallback<E>[];\n /** Per-matcher timeout in ms. Defaults to the executor's batch timeout. */\n timeout?: number;\n /**\n * Atomically remove the matcher before its first dispatch.\n *\n * `executeHooks` claims `once: true` matchers synchronously — between\n * `getMatchers` and its first `await` — so two concurrent calls cannot\n * both dispatch the same matcher. Whichever call runs its sync prefix\n * first wins the matcher; the other sees an empty bucket.\n *\n * Semantics are \"at most one dispatch, ever\" — if every hook in the\n * matcher throws, the matcher is still gone. Use `once` for\n * fire-and-forget bootstrapping (registration, telemetry, setup). Hosts\n * that need retry semantics should register a normal matcher and\n * self-unregister via the callback returned from `registry.register`.\n */\n once?: boolean;\n /** Internal hooks are excluded from telemetry and non-fatal error logging. */\n internal?: boolean;\n}\n\n/**\n * Storage shape for matchers keyed by event. Each event's matcher list is\n * a generic array parameterized by that event type, so lookup via\n * `HooksByEvent[E]` preserves type-safe callback signatures.\n */\nexport type HooksByEvent = {\n [E in HookEvent]?: HookMatcher<E>[];\n};\n\n/**\n * Aggregated result of a single `executeHooks` call. Fields are populated\n * according to the fold rules in `executeHooks.ts`.\n */\nexport interface AggregatedHookResult {\n /** Folded tool-gating decision; `deny > ask > allow`. */\n decision?: ToolDecision;\n /** Folded stop decision; any `block` wins. */\n stopDecision?: StopDecision;\n /** Reason from the hook that set the winning decision. */\n reason?: string;\n /**\n * Replacement tool input from a `PreToolUse` hook.\n *\n * Last-writer-wins in **registration order**: `executeHooks` uses\n * `Promise.all`, which preserves input-array order, so the fold iterates\n * outcomes in the same order they were pushed — outer loop over matchers\n * as they sit in the registry, inner loop over each matcher's `hooks`\n * array. The winner is therefore deterministic but may not match the\n * order in which hooks actually completed. Consumers that want a single\n * authoritative rewrite should still register one `updatedInput`-setting\n * hook per matcher to avoid subtle precedence bugs.\n */\n updatedInput?: Record<string, unknown>;\n /**\n * Replacement tool output from a `PostToolUse` hook.\n *\n * Same last-writer-wins-in-registration-order semantics as\n * `updatedInput`. Present only when at least one hook set it; `undefined`\n * means \"use the original tool output\".\n */\n updatedOutput?: unknown;\n /** Accumulated `additionalContext` strings from every hook, in order. */\n additionalContexts: string[];\n /** True if any hook returned `preventContinuation`. */\n preventContinuation?: boolean;\n /**\n * Reason recorded alongside `preventContinuation`. First winner wins:\n * once a hook sets both flags, later hooks that also set\n * `preventContinuation` do not overwrite the reason.\n */\n stopReason?: string;\n /** Error messages from hooks that threw; always present (possibly empty). */\n errors: string[];\n}\n"],"names":[],"mappings":";;AAGA;;;;;;;AAOG;AACI,MAAM,WAAW,GAAG;IACzB,UAAU;IACV,kBAAkB;IAClB,YAAY;IACZ,aAAa;IACb,oBAAoB;IACpB,kBAAkB;IAClB,eAAe;IACf,cAAc;IACd,MAAM;IACN,aAAa;IACb,YAAY;IACZ,aAAa;;;;;"}
@@ -507,11 +507,7 @@ function _formatContent(message) {
507
507
  throw new Error('Unsupported message content format');
508
508
  }
509
509
  });
510
- return contentBlocks.filter((block) => block !== null &&
511
- !(block.type === 'text' &&
512
- 'text' in block &&
513
- typeof block.text === 'string' &&
514
- block.text.trim() === ''));
510
+ return contentBlocks.filter((block) => block !== null);
515
511
  }
516
512
  }
517
513
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"message_inputs.cjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport {\n type BaseMessage,\n type SystemMessage,\n HumanMessage,\n type AIMessage,\n type ToolMessage,\n isAIMessage,\n type StandardContentBlockConverter,\n type StandardTextBlock,\n type StandardImageBlock,\n type StandardFileBlock,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n isAnthropicImageBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicCompactionBlockParam,\n AnthropicToolResponse,\n} from '../types';\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: 'base64',\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n }\n\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\n return {\n type: 'url',\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n // rare case: message.content could be undefined\n ...(message.content != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n return {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: AnthropicTextBlockParam;\n image: AnthropicImageBlockParam;\n file: AnthropicDocumentBlockParam;\n}> = {\n providerName: 'anthropic',\n\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\n return {\n type: 'text',\n text: block.text,\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicTextBlockParam;\n },\n\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: false,\n });\n if (data) {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: data.data,\n media_type: data.mime_type,\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n }\n } else {\n if (block.source_type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n throw new Error(`Unsupported image source type: ${block.source_type}`);\n }\n }\n },\n\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\n const mime_type = (block.mime_type ?? '').split(';')[0];\n\n if (block.source_type === 'url') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n }\n throw new Error(\n `Unsupported file mime type for file url source: ${block.mime_type}`\n );\n } else if (block.source_type === 'text') {\n if (mime_type === 'text/plain' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'text',\n data: block.text,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file text source: ${block.mime_type}`\n );\n }\n } else if (block.source_type === 'base64') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n data: block.data,\n media_type: 'application/pdf',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else if (\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\n mime_type\n )\n ) {\n return {\n type: 'document',\n source: {\n type: 'content',\n content: [\n {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: mime_type as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n },\n },\n ],\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\n );\n }\n } else {\n throw new Error(`Unsupported file source type: ${block.source_type}`);\n }\n },\n};\n\nfunction _formatContent(message: BaseMessage) {\n const toolTypes = [\n 'tool_use',\n 'tool_result',\n 'input_json_delta',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ];\n const textTypes = ['text', 'text_delta'];\n const { content } = message;\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentBlocks = content.map((contentPart) => {\n /**\n * Handle malformed blocks that have server tool fields mixed with text type.\n * These can occur when server_tool_use blocks get mislabeled during aggregation.\n * Correct their type ONLY if we can confirm it's a server tool by checking the ID prefix.\n * Anthropic needs both server_tool_use and web_search_tool_result blocks for citations to work.\n */\n if (\n 'id' in contentPart &&\n 'name' in contentPart &&\n 'input' in contentPart &&\n contentPart.type === 'text'\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const id = rawPart.id as string;\n\n // Only correct if this is definitely a server tool (ID starts with 'srvtoolu_')\n if (id && id.startsWith('srvtoolu_')) {\n let input = rawPart.input;\n\n // Ensure input is an object\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n input = {};\n }\n }\n\n const corrected: AnthropicServerToolUseBlockParam = {\n type: 'server_tool_use',\n id,\n name: 'web_search',\n input: input as Record<string, unknown>,\n };\n\n return corrected;\n }\n\n // If it's not a server tool, skip it (return null to filter it out)\n return null;\n }\n\n /**\n * Handle malformed web_search_tool_result blocks marked as text.\n * These have tool_use_id and nested content - fix their type instead of filtering.\n * Only correct if we can confirm it's a web search result by checking the tool_use_id prefix.\n *\n * Handles both success results (array content) and error results (object with error_code).\n */\n if (\n 'tool_use_id' in contentPart &&\n 'content' in contentPart &&\n contentPart.type === 'text'\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const toolUseId = rawPart.tool_use_id as string;\n const content = rawPart.content;\n\n // Only correct if this is definitely a server tool result (tool_use_id starts with 'srvtoolu_')\n if (toolUseId && toolUseId.startsWith('srvtoolu_')) {\n // Verify content is either an array (success) or error object\n const isValidContent =\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as Record<string, unknown>).type ===\n 'web_search_tool_result_error');\n\n if (isValidContent) {\n const corrected: AnthropicWebSearchToolResultBlockParam = {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content:\n content as AnthropicWebSearchToolResultBlockParam['content'],\n };\n return corrected;\n }\n }\n\n // If it's not a recognized server tool result format, skip it (return null to filter it out)\n return null;\n }\n\n if (isDataContentBlock(contentPart)) {\n return convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n if (typeof contentPart.image_url === 'string') {\n source = _formatImage(contentPart.image_url);\n } else {\n source = _formatImage(contentPart.image_url.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (isAnthropicImageBlockParam(contentPart)) {\n return contentPart;\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'search_result') {\n const block: AnthropicSearchResultBlockParam = {\n type: 'search_result' as const,\n title: contentPart.title,\n source: contentPart.source,\n ...('cache_control' in contentPart && contentPart.cache_control\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...('citations' in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n content: contentPart.content,\n };\n return block;\n } else if (contentPart.type === 'compaction') {\n const block: AnthropicCompactionBlockParam = {\n type: 'compaction' as const,\n content: contentPart.content,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.find((t) => t === contentPart.type) &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n ...('citations' in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n };\n } else if (toolTypes.find((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === 'string') {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n\n /**\n * For multi-turn conversations with citations, we must preserve ALL blocks\n * including server_tool_use, web_search_tool_result, and web_search_result.\n * Citations reference search results by index, so filtering changes indices and breaks references.\n *\n * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.\n */\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (\n 'functionCall' in contentPart &&\n contentPart.functionCall &&\n typeof contentPart.functionCall === 'object' &&\n isAIMessage(message)\n ) {\n const correspondingToolCall = message.tool_calls?.find(\n (toolCall) => toolCall.name === contentPart.functionCall.name\n );\n if (!correspondingToolCall) {\n throw new Error(\n `Could not find tool call for function call ${contentPart.functionCall.name}`\n );\n }\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\n return {\n id: correspondingToolCall.id,\n type: 'tool_use',\n name: correspondingToolCall.name,\n input: contentPart.functionCall.args,\n };\n } else {\n console.error(\n 'Unsupported content part:',\n JSON.stringify(contentPart, null, 2)\n );\n throw new Error('Unsupported message content format');\n }\n });\n return contentBlocks.filter(\n (block) =>\n block !== null &&\n !(\n block.type === 'text' &&\n 'text' in block &&\n typeof block.text === 'string' &&\n block.text.trim() === ''\n )\n );\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n if (typeof message.content === 'string') {\n if (message.content === '') {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: 'text', text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every(\n (toolCall) =>\n !!content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta' ||\n contentPart.type === 'server_tool_use') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\n if (!messages || messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n type ContentBlocks = Exclude<\n AnthropicMessageCreateParams['messages'][number]['content'],\n string\n >;\n const normalizeContent = (\n content: AnthropicMessageCreateParams['messages'][number]['content']\n ): ContentBlocks => {\n if (typeof content === 'string') {\n return [{ type: 'text', text: content }];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"names":["parseBase64DataUrl","messages","HumanMessage","isDataContentBlock","convertToProviderContentBlock","isAnthropicImageBlockParam","isAIMessage"],"mappings":";;;;;AAAA;AACA;AACA;;AAEG;AAiCH,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAGA,2BAAkB,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACxD,IAAI,MAAM,EAAE;QACV,OAAO;AACL,YAAA,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,MAAM,CAAC,SAAS;YAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;SAClB;IACH;AACA,IAAA,IAAI,SAAc;AAElB,IAAA,IAAI;AACF,QAAA,SAAS,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC;IAC/B;AAAE,IAAA,MAAM;QACN,MAAM,IAAI,KAAK,CACb;AACE,YAAA,CAAA,qBAAA,EAAwB,IAAI,CAAC,SAAS,CACpC,QAAQ,CACT,CAAA,6FAAA,CAA+F;YAChG,8CAA8C;YAC9C,wCAAwC;AACzC,SAAA,CAAC,IAAI,CAAC,MAAM,CAAC,CACf;IACH;AAEA,IAAA,IAAI,SAAS,CAAC,QAAQ,KAAK,OAAO,IAAI,SAAS,CAAC,QAAQ,KAAK,QAAQ,EAAE;QACrE,OAAO;AACL,YAAA,IAAI,EAAE,KAAK;AACX,YAAA,GAAG,EAAE,QAAQ;SACd;IACH;IAEA,MAAM,IAAI,KAAK,CACb;QACE,CAAA,4BAAA,EAA+B,IAAI,CAAC,SAAS,CAC3C,SAAS,CAAC,QAAQ,CACnB,CAAA,2GAAA,CAA6G;QAC9G,8CAA8C;QAC9C,wCAAwC;AACzC,KAAA,CAAC,IAAI,CAAC,MAAM,CAAC,CACf;AACH;AAEA,SAAS,sBAAsB,CAC7BC,UAAuB,EAAA;;IAGvB,MAAM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GAAG,CAAC,OAAO,KAAK,QAAQ,EAAE;AACnC,YAAA,OAAO,KAAK;QACd;QAEA,QACE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;AAC1B,YAAA,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,KAAK,aAAa,CAAC;AAE5D,IAAA,CAAC;AAED,IAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE;AAC3C,QAAA,MAAM,WAAW,GAAG,QAAQ,CAAC,CAAC,CAAC;QAE/B,IACE,mBAAmB,CAAC,cAAc,CAAC;AACnC,YAAA,mBAAmB,CAAC,WAAW,CAAC,EAChC;;AAEA,YAAA,cAAc,GAAG;AACf,gBAAA,GAAG,cAAc;AACjB,gBAAA,OAAO,EAAE;AACP,oBAAA,GAAG,gBAAgB,CAAC,cAAc,CAAC,OAAO,CAAC;AAC3C,oBAAA,GAAG,gBAAgB,CAAC,WAAW,CAAC,OAAO,CAAC;AACzC,iBAAA;aACF;QACH;aAAO;AACL,YAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;YAC3B,cAAc,GAAG,WAAW;QAC9B;IACF;AAEA,IAAA,MAAM,CAAC,IAAI,CAAC,cAAc,CAAC;AAC3B,IAAA,OAAO,MAAM;AACf;;;;;"}
1
+ {"version":3,"file":"message_inputs.cjs","sources":["../../../../../src/llm/anthropic/utils/message_inputs.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/explicit-function-return-type */\n/* eslint-disable no-console */\n/**\n * This util file contains functions for converting LangChain messages to Anthropic messages.\n */\nimport {\n type BaseMessage,\n type SystemMessage,\n HumanMessage,\n type AIMessage,\n type ToolMessage,\n isAIMessage,\n type StandardContentBlockConverter,\n type StandardTextBlock,\n type StandardImageBlock,\n type StandardFileBlock,\n MessageContentComplex,\n isDataContentBlock,\n convertToProviderContentBlock,\n parseBase64DataUrl,\n} from '@langchain/core/messages';\nimport { ToolCall } from '@langchain/core/messages/tool';\nimport {\n AnthropicImageBlockParam,\n AnthropicMessageCreateParams,\n AnthropicTextBlockParam,\n AnthropicDocumentBlockParam,\n AnthropicThinkingBlockParam,\n AnthropicRedactedThinkingBlockParam,\n AnthropicServerToolUseBlockParam,\n AnthropicWebSearchToolResultBlockParam,\n isAnthropicImageBlockParam,\n AnthropicSearchResultBlockParam,\n AnthropicCompactionBlockParam,\n AnthropicToolResponse,\n} from '../types';\n\nfunction _formatImage(imageUrl: string) {\n const parsed = parseBase64DataUrl({ dataUrl: imageUrl });\n if (parsed) {\n return {\n type: 'base64',\n media_type: parsed.mime_type,\n data: parsed.data,\n };\n }\n let parsedUrl: URL;\n\n try {\n parsedUrl = new URL(imageUrl);\n } catch {\n throw new Error(\n [\n `Malformed image URL: ${JSON.stringify(\n imageUrl\n )}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n }\n\n if (parsedUrl.protocol === 'http:' || parsedUrl.protocol === 'https:') {\n return {\n type: 'url',\n url: imageUrl,\n };\n }\n\n throw new Error(\n [\n `Invalid image URL protocol: ${JSON.stringify(\n parsedUrl.protocol\n )}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,\n 'Example: data:image/png;base64,/9j/4AAQSk...',\n 'Example: https://example.com/image.jpg',\n ].join('\\n\\n')\n );\n}\n\nfunction _ensureMessageContents(\n messages: BaseMessage[]\n): (SystemMessage | HumanMessage | AIMessage)[] {\n // Merge runs of human/tool messages into single human messages with content blocks.\n const updatedMsgs = [];\n for (const message of messages) {\n if (message._getType() === 'tool') {\n if (typeof message.content === 'string') {\n const previousMessage = updatedMsgs[updatedMsgs.length - 1];\n if (\n previousMessage._getType() === 'human' &&\n Array.isArray(previousMessage.content) &&\n 'type' in previousMessage.content[0] &&\n previousMessage.content[0].type === 'tool_result'\n ) {\n // If the previous message was a tool result, we merge this tool message into it.\n (previousMessage.content as MessageContentComplex[]).push({\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n });\n } else {\n // If not, we create a new human message with the tool result.\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n content: message.content,\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(\n new HumanMessage({\n content: [\n {\n type: 'tool_result',\n // rare case: message.content could be undefined\n ...(message.content != null\n ? { content: _formatContent(message) }\n : {}),\n tool_use_id: (message as ToolMessage).tool_call_id,\n },\n ],\n })\n );\n }\n } else {\n updatedMsgs.push(message);\n }\n }\n return updatedMsgs;\n}\n\nexport function _convertLangChainToolCallToAnthropic(\n toolCall: ToolCall\n): AnthropicToolResponse {\n if (toolCall.id === undefined) {\n throw new Error('Anthropic requires all tool calls to have an \"id\".');\n }\n return {\n type: 'tool_use',\n id: toolCall.id,\n name: toolCall.name,\n input: toolCall.args,\n };\n}\n\nconst standardContentBlockConverter: StandardContentBlockConverter<{\n text: AnthropicTextBlockParam;\n image: AnthropicImageBlockParam;\n file: AnthropicDocumentBlockParam;\n}> = {\n providerName: 'anthropic',\n\n fromStandardTextBlock(block: StandardTextBlock): AnthropicTextBlockParam {\n return {\n type: 'text',\n text: block.text,\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicTextBlockParam;\n },\n\n fromStandardImageBlock(block: StandardImageBlock): AnthropicImageBlockParam {\n if (block.source_type === 'url') {\n const data = parseBase64DataUrl({\n dataUrl: block.url,\n asTypedArray: false,\n });\n if (data) {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: data.data,\n media_type: data.mime_type,\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n return {\n type: 'image',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n }\n } else {\n if (block.source_type === 'base64') {\n return {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n } as AnthropicImageBlockParam;\n } else {\n throw new Error(`Unsupported image source type: ${block.source_type}`);\n }\n }\n },\n\n fromStandardFileBlock(block: StandardFileBlock): AnthropicDocumentBlockParam {\n const mime_type = (block.mime_type ?? '').split(';')[0];\n\n if (block.source_type === 'url') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'url',\n url: block.url,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n }\n throw new Error(\n `Unsupported file mime type for file url source: ${block.mime_type}`\n );\n } else if (block.source_type === 'text') {\n if (mime_type === 'text/plain' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'text',\n data: block.text,\n media_type: block.mime_type ?? '',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file text source: ${block.mime_type}`\n );\n }\n } else if (block.source_type === 'base64') {\n if (mime_type === 'application/pdf' || mime_type === '') {\n return {\n type: 'document',\n source: {\n type: 'base64',\n data: block.data,\n media_type: 'application/pdf',\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else if (\n ['image/jpeg', 'image/png', 'image/gif', 'image/webp'].includes(\n mime_type\n )\n ) {\n return {\n type: 'document',\n source: {\n type: 'content',\n content: [\n {\n type: 'image',\n source: {\n type: 'base64',\n data: block.data,\n media_type: mime_type as\n | 'image/jpeg'\n | 'image/png'\n | 'image/gif'\n | 'image/webp',\n },\n },\n ],\n },\n ...('cache_control' in (block.metadata ?? {})\n ? { cache_control: block.metadata!.cache_control }\n : {}),\n ...('citations' in (block.metadata ?? {})\n ? { citations: block.metadata!.citations }\n : {}),\n ...('context' in (block.metadata ?? {})\n ? { context: block.metadata!.context }\n : {}),\n ...('title' in (block.metadata ?? {})\n ? { title: block.metadata!.title }\n : {}),\n } as AnthropicDocumentBlockParam;\n } else {\n throw new Error(\n `Unsupported file mime type for file base64 source: ${block.mime_type}`\n );\n }\n } else {\n throw new Error(`Unsupported file source type: ${block.source_type}`);\n }\n },\n};\n\nfunction _formatContent(message: BaseMessage) {\n const toolTypes = [\n 'tool_use',\n 'tool_result',\n 'input_json_delta',\n 'server_tool_use',\n 'web_search_tool_result',\n 'web_search_result',\n ];\n const textTypes = ['text', 'text_delta'];\n const { content } = message;\n\n if (typeof content === 'string') {\n return content;\n } else {\n const contentBlocks = content.map((contentPart) => {\n /**\n * Handle malformed blocks that have server tool fields mixed with text type.\n * These can occur when server_tool_use blocks get mislabeled during aggregation.\n * Correct their type ONLY if we can confirm it's a server tool by checking the ID prefix.\n * Anthropic needs both server_tool_use and web_search_tool_result blocks for citations to work.\n */\n if (\n 'id' in contentPart &&\n 'name' in contentPart &&\n 'input' in contentPart &&\n contentPart.type === 'text'\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const id = rawPart.id as string;\n\n // Only correct if this is definitely a server tool (ID starts with 'srvtoolu_')\n if (id && id.startsWith('srvtoolu_')) {\n let input = rawPart.input;\n\n // Ensure input is an object\n if (typeof input === 'string') {\n try {\n input = JSON.parse(input);\n } catch {\n input = {};\n }\n }\n\n const corrected: AnthropicServerToolUseBlockParam = {\n type: 'server_tool_use',\n id,\n name: 'web_search',\n input: input as Record<string, unknown>,\n };\n\n return corrected;\n }\n\n // If it's not a server tool, skip it (return null to filter it out)\n return null;\n }\n\n /**\n * Handle malformed web_search_tool_result blocks marked as text.\n * These have tool_use_id and nested content - fix their type instead of filtering.\n * Only correct if we can confirm it's a web search result by checking the tool_use_id prefix.\n *\n * Handles both success results (array content) and error results (object with error_code).\n */\n if (\n 'tool_use_id' in contentPart &&\n 'content' in contentPart &&\n contentPart.type === 'text'\n ) {\n const rawPart = contentPart as Record<string, unknown>;\n const toolUseId = rawPart.tool_use_id as string;\n const content = rawPart.content;\n\n // Only correct if this is definitely a server tool result (tool_use_id starts with 'srvtoolu_')\n if (toolUseId && toolUseId.startsWith('srvtoolu_')) {\n // Verify content is either an array (success) or error object\n const isValidContent =\n Array.isArray(content) ||\n (content != null &&\n typeof content === 'object' &&\n 'type' in content &&\n (content as Record<string, unknown>).type ===\n 'web_search_tool_result_error');\n\n if (isValidContent) {\n const corrected: AnthropicWebSearchToolResultBlockParam = {\n type: 'web_search_tool_result',\n tool_use_id: toolUseId,\n content:\n content as AnthropicWebSearchToolResultBlockParam['content'],\n };\n return corrected;\n }\n }\n\n // If it's not a recognized server tool result format, skip it (return null to filter it out)\n return null;\n }\n\n if (isDataContentBlock(contentPart)) {\n return convertToProviderContentBlock(\n contentPart,\n standardContentBlockConverter\n );\n }\n\n const cacheControl =\n 'cache_control' in contentPart ? contentPart.cache_control : undefined;\n\n if (contentPart.type === 'image_url') {\n let source;\n if (typeof contentPart.image_url === 'string') {\n source = _formatImage(contentPart.image_url);\n } else {\n source = _formatImage(contentPart.image_url.url);\n }\n return {\n type: 'image' as const, // Explicitly setting the type as \"image\"\n source,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (isAnthropicImageBlockParam(contentPart)) {\n return contentPart;\n } else if (contentPart.type === 'document') {\n // PDF\n return {\n ...contentPart,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n } else if (contentPart.type === 'thinking') {\n const block: AnthropicThinkingBlockParam = {\n type: 'thinking' as const, // Explicitly setting the type as \"thinking\"\n thinking: contentPart.thinking,\n signature: contentPart.signature,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'redacted_thinking') {\n const block: AnthropicRedactedThinkingBlockParam = {\n type: 'redacted_thinking' as const, // Explicitly setting the type as \"redacted_thinking\"\n data: contentPart.data,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (contentPart.type === 'search_result') {\n const block: AnthropicSearchResultBlockParam = {\n type: 'search_result' as const,\n title: contentPart.title,\n source: contentPart.source,\n ...('cache_control' in contentPart && contentPart.cache_control\n ? { cache_control: contentPart.cache_control }\n : {}),\n ...('citations' in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n content: contentPart.content,\n };\n return block;\n } else if (contentPart.type === 'compaction') {\n const block: AnthropicCompactionBlockParam = {\n type: 'compaction' as const,\n content: contentPart.content,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n };\n return block;\n } else if (\n textTypes.find((t) => t === contentPart.type) &&\n 'text' in contentPart\n ) {\n // Assuming contentPart is of type MessageContentText here\n return {\n type: 'text' as const, // Explicitly setting the type as \"text\"\n text: contentPart.text,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n ...('citations' in contentPart && contentPart.citations\n ? { citations: contentPart.citations }\n : {}),\n };\n } else if (toolTypes.find((t) => t === contentPart.type)) {\n const contentPartCopy = { ...contentPart };\n if ('index' in contentPartCopy) {\n // Anthropic does not support passing the index field here, so we remove it.\n delete contentPartCopy.index;\n }\n\n if (contentPartCopy.type === 'input_json_delta') {\n // `input_json_delta` type only represents yielding partial tool inputs\n // and is not a valid type for Anthropic messages.\n contentPartCopy.type = 'tool_use';\n }\n\n if ('input' in contentPartCopy) {\n // Anthropic tool use inputs should be valid objects, when applicable.\n if (typeof contentPartCopy.input === 'string') {\n try {\n contentPartCopy.input = JSON.parse(contentPartCopy.input);\n } catch {\n contentPartCopy.input = {};\n }\n }\n }\n\n /**\n * For multi-turn conversations with citations, we must preserve ALL blocks\n * including server_tool_use, web_search_tool_result, and web_search_result.\n * Citations reference search results by index, so filtering changes indices and breaks references.\n *\n * The ToolNode already handles skipping server tool invocations via the srvtoolu_ prefix check.\n */\n\n // TODO: Fix when SDK types are fixed\n return {\n ...contentPartCopy,\n ...(cacheControl ? { cache_control: cacheControl } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any;\n } else if (\n 'functionCall' in contentPart &&\n contentPart.functionCall &&\n typeof contentPart.functionCall === 'object' &&\n isAIMessage(message)\n ) {\n const correspondingToolCall = message.tool_calls?.find(\n (toolCall) => toolCall.name === contentPart.functionCall.name\n );\n if (!correspondingToolCall) {\n throw new Error(\n `Could not find tool call for function call ${contentPart.functionCall.name}`\n );\n }\n // Google GenAI models include a `functionCall` object inside content. We should ignore it as Anthropic will not support it.\n return {\n id: correspondingToolCall.id,\n type: 'tool_use',\n name: correspondingToolCall.name,\n input: contentPart.functionCall.args,\n };\n } else {\n console.error(\n 'Unsupported content part:',\n JSON.stringify(contentPart, null, 2)\n );\n throw new Error('Unsupported message content format');\n }\n });\n return contentBlocks.filter((block) => block !== null);\n }\n}\n\n/**\n * Formats messages as a prompt for the model.\n * Used in LangSmith, export is important here.\n * @param messages The base messages to format as a prompt.\n * @returns The formatted prompt.\n */\nexport function _convertMessagesToAnthropicPayload(\n messages: BaseMessage[]\n): AnthropicMessageCreateParams {\n const mergedMessages = _ensureMessageContents(messages);\n let system;\n if (mergedMessages.length > 0 && mergedMessages[0]._getType() === 'system') {\n system = messages[0].content;\n }\n const conversationMessages =\n system !== undefined ? mergedMessages.slice(1) : mergedMessages;\n const formattedMessages = conversationMessages.map((message) => {\n let role;\n if (message._getType() === 'human') {\n role = 'user' as const;\n } else if (message._getType() === 'ai') {\n role = 'assistant' as const;\n } else if (message._getType() === 'tool') {\n role = 'user' as const;\n } else if (message._getType() === 'system') {\n throw new Error(\n 'System messages are only permitted as the first passed message.'\n );\n } else {\n throw new Error(`Message type \"${message._getType()}\" is not supported.`);\n }\n if (isAIMessage(message) && !!message.tool_calls?.length) {\n if (typeof message.content === 'string') {\n if (message.content === '') {\n return {\n role,\n content: message.tool_calls.map(\n _convertLangChainToolCallToAnthropic\n ),\n };\n } else {\n return {\n role,\n content: [\n { type: 'text', text: message.content },\n ...message.tool_calls.map(_convertLangChainToolCallToAnthropic),\n ],\n };\n }\n } else {\n const { content } = message;\n const hasMismatchedToolCalls = !message.tool_calls.every(\n (toolCall) =>\n !!content.find(\n (contentPart) =>\n (contentPart.type === 'tool_use' ||\n contentPart.type === 'input_json_delta' ||\n contentPart.type === 'server_tool_use') &&\n contentPart.id === toolCall.id\n )\n );\n if (hasMismatchedToolCalls) {\n console.warn(\n 'The \"tool_calls\" field on a message is only respected if content is a string.'\n );\n }\n return {\n role,\n content: _formatContent(message),\n };\n }\n } else {\n return {\n role,\n content: _formatContent(message),\n };\n }\n });\n return {\n messages: mergeMessages(formattedMessages),\n system,\n } as AnthropicMessageCreateParams;\n}\n\nfunction mergeMessages(messages: AnthropicMessageCreateParams['messages']) {\n if (!messages || messages.length <= 1) {\n return messages;\n }\n\n const result: AnthropicMessageCreateParams['messages'] = [];\n let currentMessage = messages[0];\n\n type ContentBlocks = Exclude<\n AnthropicMessageCreateParams['messages'][number]['content'],\n string\n >;\n const normalizeContent = (\n content: AnthropicMessageCreateParams['messages'][number]['content']\n ): ContentBlocks => {\n if (typeof content === 'string') {\n return [{ type: 'text', text: content }];\n }\n return content;\n };\n\n const isToolResultMessage = (msg: (typeof messages)[0]) => {\n if (msg.role !== 'user') return false;\n\n if (typeof msg.content === 'string') {\n return false;\n }\n\n return (\n Array.isArray(msg.content) &&\n msg.content.every((item) => item.type === 'tool_result')\n );\n };\n\n for (let i = 1; i < messages.length; i += 1) {\n const nextMessage = messages[i];\n\n if (\n isToolResultMessage(currentMessage) &&\n isToolResultMessage(nextMessage)\n ) {\n // Merge the messages by combining their content arrays\n currentMessage = {\n ...currentMessage,\n content: [\n ...normalizeContent(currentMessage.content),\n ...normalizeContent(nextMessage.content),\n ],\n };\n } else {\n result.push(currentMessage);\n currentMessage = nextMessage;\n }\n }\n\n result.push(currentMessage);\n return result;\n}\n"],"names":["parseBase64DataUrl","messages","HumanMessage","isDataContentBlock","convertToProviderContentBlock","isAnthropicImageBlockParam","isAIMessage"],"mappings":";;;;;AAAA;AACA;AACA;;AAEG;AAiCH,SAAS,YAAY,CAAC,QAAgB,EAAA;IACpC,MAAM,MAAM,GAAGA,2BAAkB,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;IACxD,IAAI,MAAM,EAAE;QACV,OAAO;AACL,YAAA,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE,MAAM,CAAC,SAAS;YAC5B,IAAI,EAAE,MAAM,CAAC,IAAI;SAClB;IACH;AACA,IAAA,IAAI,SAAc;AAElB,IAAA,IAAI;AACF,QAAA,SAAS,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC;IAC/B;AAAE,IAAA,MAAM;QACN,MAAM,IAAI,KAAK,CACb;AACE,YAAA,CAAA,qBAAA,EAAwB,IAAI,CAAC,SAAS,CACpC,QAAQ,CACT,CAAA,6FAAA,CAA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4,7 +4,6 @@ var aws = require('@langchain/aws');
4
4
  var clientBedrockRuntime = require('@aws-sdk/client-bedrock-runtime');
5
5
  var messages = require('@langchain/core/messages');
6
6
  var outputs = require('@langchain/core/outputs');
7
- var cacheSupport = require('./cacheSupport.cjs');
8
7
  var message_inputs = require('./utils/message_inputs.cjs');
9
8
  var message_outputs = require('./utils/message_outputs.cjs');
10
9
 
@@ -40,13 +39,6 @@ var message_outputs = require('./utils/message_outputs.cjs');
40
39
  * Cache token extraction is handled in `./utils/message_outputs.ts` and added
41
40
  * to usage_metadata with input_token_details (cacheReadInputTokens/cacheWriteInputTokens).
42
41
  */
43
- /**
44
- * Default group selector — puts all tools in a single group named 'core'.
45
- * Equivalent to 'single' strategy but explicit. Consumers override this
46
- * to enable per-source grouping (e.g. by inspecting tool-name substrings
47
- * to separate stable framework tools from volatile MCP-sourced tools).
48
- */
49
- const DEFAULT_TOOL_GROUP_SELECTOR = () => 'core';
50
42
  class IllumaBedrockConverse extends aws.ChatBedrockConverse {
51
43
  /** Enable Bedrock prompt caching for tool definitions */
52
44
  promptCache;
@@ -54,21 +46,11 @@ class IllumaBedrockConverse extends aws.ChatBedrockConverse {
54
46
  applicationInferenceProfile;
55
47
  /** Service tier for model invocation */
56
48
  serviceTier;
57
- /** Tool cachePoint allocation strategy. */
58
- toolCacheStrategy;
59
- /** Group selector for 'split' strategy. */
60
- toolGroupSelector;
61
- /** Optional consumer extensions to the cache-supported model allowlist. */
62
- bedrockCacheModelPatterns;
63
49
  constructor(fields) {
64
50
  super(fields);
65
51
  this.promptCache = fields?.promptCache ?? false;
66
52
  this.applicationInferenceProfile = fields?.applicationInferenceProfile;
67
53
  this.serviceTier = fields?.serviceTier;
68
- this.toolCacheStrategy = fields?.toolCacheStrategy ?? 'single';
69
- this.toolGroupSelector =
70
- fields?.toolGroupSelector ?? DEFAULT_TOOL_GROUP_SELECTOR;
71
- this.bedrockCacheModelPatterns = fields?.bedrockCacheModelPatterns;
72
54
  // Fix: Force supportsToolChoiceValues for Claude models
73
55
  // The parent constructor checks `model.includes('claude-3')` but this fails when:
74
56
  // 1. Using applicationInferenceProfile ARNs (arn:aws:bedrock:...)
@@ -125,55 +107,46 @@ class IllumaBedrockConverse extends aws.ChatBedrockConverse {
125
107
  }
126
108
  }
127
109
  }
128
- /* Allowlist-based gate (see cacheSupport.ts). Replaces the old
129
- * substring heuristic — same default behavior for Claude/Anthropic/
130
- * Nova models, plus extension via `bedrockCacheModelPatterns`. */
131
- const cacheSupported = cacheSupport.isBedrockCacheSupported(this.model, this.bedrockCacheModelPatterns);
110
+ // Only Claude models support cachePoint - check model name
111
+ const modelId = this.model.toLowerCase();
112
+ const isClaudeModel = modelId.includes('claude') || modelId.includes('anthropic');
132
113
  if (this.promptCache &&
133
- cacheSupported &&
134
- this.toolCacheStrategy !== 'none' &&
114
+ isClaudeModel &&
135
115
  params.toolConfig?.tools &&
136
116
  Array.isArray(params.toolConfig.tools) &&
137
117
  params.toolConfig.tools.length > 0) {
138
- const tools = params.toolConfig.tools;
139
- if (this.toolCacheStrategy === 'single') {
140
- /* SINGLE: one cachePoint at the end of the tools array. Lightest
141
- * budget use; appropriate when the entire tools array is treated
142
- * as one unit and changes together. */
143
- const toolsWithCache = [
144
- ...tools,
145
- { cachePoint: { type: 'default' } },
146
- ];
147
- params.toolConfig.tools = toolsWithCache;
148
- }
149
- else if (this.toolCacheStrategy === 'split') {
150
- /* SPLIT: group tools by `toolGroupSelector` and emit a cachePoint
151
- * after each non-empty group. Group order follows first-encounter
152
- * order in the input. Use when groups have different volatility
153
- * (e.g. stable core tools + volatile MCP tools). */
154
- const groupOrder = [];
155
- const groupMap = new Map();
156
- for (const tool of tools) {
157
- const toolName = tool.toolSpec?.name ?? '';
158
- const groupKey = this.toolGroupSelector(toolName);
159
- let group = groupMap.get(groupKey);
160
- if (!group) {
161
- group = [];
162
- groupMap.set(groupKey, group);
163
- groupOrder.push(groupKey);
164
- }
165
- group.push(tool);
118
+ // Separate core tools from MCP tools
119
+ // MCP tools have '_mcp_' in their name (e.g., 'search_emails_mcp_Google-Workspace')
120
+ const coreTools = [];
121
+ const mcpTools = [];
122
+ for (const tool of params.toolConfig.tools) {
123
+ // Check if tool has a name property with '_mcp_' pattern
124
+ const toolName = tool.toolSpec?.name ?? '';
125
+ if (toolName.includes('_mcp_')) {
126
+ mcpTools.push(tool);
166
127
  }
167
- const toolsWithCache = [];
168
- for (const groupKey of groupOrder) {
169
- const group = groupMap.get(groupKey);
170
- if (!group || group.length === 0)
171
- continue;
172
- toolsWithCache.push(...group);
173
- toolsWithCache.push({ cachePoint: { type: 'default' } });
128
+ else {
129
+ coreTools.push(tool);
174
130
  }
175
- params.toolConfig.tools = toolsWithCache;
176
131
  }
132
+ // Build tools array with strategic cachePoints:
133
+ // [CoreTool1, CoreTool2, cachePoint] + [MCPTool1, MCPTool2, cachePoint]
134
+ const toolsWithCache = [];
135
+ // Add core tools with cachePoint (if any)
136
+ if (coreTools.length > 0) {
137
+ toolsWithCache.push(...coreTools);
138
+ toolsWithCache.push({ cachePoint: { type: 'default' } });
139
+ }
140
+ // Add MCP tools with their own cachePoint (if any)
141
+ if (mcpTools.length > 0) {
142
+ toolsWithCache.push(...mcpTools);
143
+ toolsWithCache.push({ cachePoint: { type: 'default' } });
144
+ }
145
+ // If no tools at all (shouldn't happen but safety check)
146
+ if (toolsWithCache.length === 0) {
147
+ toolsWithCache.push({ cachePoint: { type: 'default' } });
148
+ }
149
+ params.toolConfig.tools = toolsWithCache;
177
150
  }
178
151
  // Add serviceTier support
179
152
  const serviceTierType = options?.serviceTier ?? this.serviceTier;
@@ -348,6 +321,5 @@ class IllumaBedrockConverse extends aws.ChatBedrockConverse {
348
321
  const CustomChatBedrockConverse = IllumaBedrockConverse;
349
322
 
350
323
  exports.CustomChatBedrockConverse = CustomChatBedrockConverse;
351
- exports.DEFAULT_TOOL_GROUP_SELECTOR = DEFAULT_TOOL_GROUP_SELECTOR;
352
324
  exports.IllumaBedrockConverse = IllumaBedrockConverse;
353
325
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../../../src/llm/bedrock/index.ts"],"sourcesContent":["/**\n * Optimized ChatBedrockConverse wrapper that fixes content block merging for\n * streaming responses and adds support for latest @langchain/aws features:\n *\n * - Prompt caching support for Bedrock Converse API (Illuma feature)\n * - Application Inference Profiles (PR #9129)\n * - Service Tiers (Priority/Standard/Flex) (PR #9785) - requires AWS SDK 3.966.0+\n *\n * Bedrock's `@langchain/aws` library does not include an `index` property on content\n * blocks (unlike Anthropic/OpenAI), which causes LangChain's `_mergeLists` to append\n * each streaming chunk as a separate array entry instead of merging by index.\n *\n * This wrapper takes full ownership of the stream by directly interfacing with the\n * AWS SDK client (`this.client`) and using custom handlers from `./utils/` that\n * include `contentBlockIndex` in response_metadata for every delta type. It then\n * promotes `contentBlockIndex` to an `index` property on each content block\n * (mirroring Anthropic's pattern) and strips it from metadata to avoid\n * `_mergeDicts` conflicts.\n *\n * When multiple content block types are present (e.g. reasoning + text), text deltas\n * are promoted from strings to array form with `index` so they merge correctly once\n * the accumulated content is already an array.\n *\n * PROMPT CACHING:\n * When promptCache: true is set, this wrapper adds cachePoint markers to the tools array\n * to enable Bedrock prompt caching for tool definitions. This allows tool schemas to be\n * cached and reused across requests, reducing latency and costs.\n *\n * CACHE TOKEN EXTRACTION:\n * Cache token extraction is handled in `./utils/message_outputs.ts` and added\n * to usage_metadata with input_token_details (cacheReadInputTokens/cacheWriteInputTokens).\n */\n\nimport { ChatBedrockConverse } from '@langchain/aws';\nimport { ConverseStreamCommand } from '@aws-sdk/client-bedrock-runtime';\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { ChatGenerationChunk, ChatResult } from '@langchain/core/outputs';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { ChatBedrockConverseInput } from '@langchain/aws';\nimport { isBedrockCacheSupported } from './cacheSupport';\nimport {\n convertToConverseMessages,\n handleConverseStreamContentBlockStart,\n handleConverseStreamContentBlockDelta,\n handleConverseStreamMetadata,\n} from './utils';\n\n/**\n * Service tier type for Bedrock invocations.\n * Requires AWS SDK >= 3.966.0 to actually work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\nexport type ServiceTierType = 'priority' | 'default' | 'flex' | 'reserved';\n\n/**\n * Tool cachePoint allocation strategy.\n *\n * - 'single': one cachePoint at the END of the tools array (whole array\n * cached as one unit). Lightest budget use (1 cachePoint).\n * - 'split': split tools into groups via `toolGroupSelector`. Each\n * non-empty group gets its own cachePoint. Use when groups\n * have different volatility (e.g. stable core tools vs\n * volatile MCP tools). Costs more cachePoint budget.\n * - 'none': no cachePoint on tools array. Use when tool definitions\n * change every request anyway.\n */\nexport type ToolCacheStrategy = 'single' | 'split' | 'none';\n\n/**\n * Group selector for `toolCacheStrategy: 'split'`. Receives the tool name\n * and returns a stable group key — tools with the same key are grouped\n * together. Group order in the output array follows first-encounter order.\n */\nexport type ToolGroupSelector = (toolName: string) => string;\n\n/**\n * Default group selector — puts all tools in a single group named 'core'.\n * Equivalent to 'single' strategy but explicit. Consumers override this\n * to enable per-source grouping (e.g. by inspecting tool-name substrings\n * to separate stable framework tools from volatile MCP-sourced tools).\n */\nexport const DEFAULT_TOOL_GROUP_SELECTOR: ToolGroupSelector = () => 'core';\n\n/**\n * Extended input interface with additional features:\n * - promptCache: Enable Bedrock prompt caching for tool definitions\n * - applicationInferenceProfile: Use an inference profile ARN instead of model ID\n * - serviceTier: Specify service tier (Priority, Standard, Flex, Reserved)\n * - toolCacheStrategy: How to allocate cachePoints across tools array\n * - toolGroupSelector: Group key resolver for the 'split' strategy\n */\nexport interface IllumaBedrockConverseInput extends ChatBedrockConverseInput {\n /**\n * Enable Bedrock prompt caching for tool definitions.\n * When true, adds cachePoint marker(s) to tools array per\n * `toolCacheStrategy`. Defaults to 'single'.\n */\n promptCache?: boolean;\n\n /**\n * Tool cachePoint allocation. Defaults to 'single' — one cachePoint at\n * the end of the tools array. Set to 'split' (with `toolGroupSelector`)\n * when different tool groups have different volatility.\n */\n toolCacheStrategy?: ToolCacheStrategy;\n\n /**\n * Group selector for 'split' strategy. Receives a tool name, returns\n * a stable group key. Defaults to a one-group selector (equivalent\n * to 'single').\n */\n toolGroupSelector?: ToolGroupSelector;\n\n /**\n * Additional model ID patterns to consider Bedrock-cache-supported.\n * Defaults are in `src/llm/bedrock/cacheSupport.ts`. Use this when\n * AWS adds a new model family before the next library release.\n */\n bedrockCacheModelPatterns?: readonly RegExp[];\n\n /**\n * Application Inference Profile ARN to use for the model.\n * For example, \"arn:aws:bedrock:eu-west-1:123456789102:application-inference-profile/fm16bt65tzgx\"\n * When provided, this ARN will be used for the actual inference calls instead of the model ID.\n * Must still provide `model` as normal modelId to benefit from all the metadata.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-create.html\n */\n applicationInferenceProfile?: string;\n\n /**\n * Service tier for model invocation.\n * Specifies the processing tier type used for serving the request.\n * Supported values are 'priority', 'default', 'flex', and 'reserved'.\n *\n * - 'priority': Prioritized processing for lower latency\n * - 'default': Standard processing tier\n * - 'flex': Flexible processing tier with lower cost\n * - 'reserved': Reserved capacity for consistent performance\n *\n * If not provided, AWS uses the default tier.\n * Note: Requires AWS SDK >= 3.966.0 to work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\n serviceTier?: ServiceTierType;\n}\n\n/**\n * Extended call options with serviceTier override support.\n */\nexport interface IllumaBedrockConverseCallOptions {\n serviceTier?: ServiceTierType;\n}\n\nexport class IllumaBedrockConverse extends ChatBedrockConverse {\n /** Enable Bedrock prompt caching for tool definitions */\n promptCache: boolean;\n\n /** Application Inference Profile ARN to use instead of model ID */\n applicationInferenceProfile?: string;\n\n /** Service tier for model invocation */\n serviceTier?: ServiceTierType;\n\n /** Tool cachePoint allocation strategy. */\n toolCacheStrategy: ToolCacheStrategy;\n\n /** Group selector for 'split' strategy. */\n toolGroupSelector: ToolGroupSelector;\n\n /** Optional consumer extensions to the cache-supported model allowlist. */\n bedrockCacheModelPatterns?: readonly RegExp[];\n\n constructor(fields?: IllumaBedrockConverseInput) {\n super(fields);\n this.promptCache = fields?.promptCache ?? false;\n this.applicationInferenceProfile = fields?.applicationInferenceProfile;\n this.serviceTier = fields?.serviceTier;\n this.toolCacheStrategy = fields?.toolCacheStrategy ?? 'single';\n this.toolGroupSelector =\n fields?.toolGroupSelector ?? DEFAULT_TOOL_GROUP_SELECTOR;\n this.bedrockCacheModelPatterns = fields?.bedrockCacheModelPatterns;\n\n // Fix: Force supportsToolChoiceValues for Claude models\n // The parent constructor checks `model.includes('claude-3')` but this fails when:\n // 1. Using applicationInferenceProfile ARNs (arn:aws:bedrock:...)\n // 2. Using different naming conventions (claude-4, claude-opus-4, etc.)\n // We need to ensure tool_choice is properly set for withStructuredOutput to work\n const modelName = (fields?.model ?? '').toLowerCase();\n const profileName = (\n fields?.applicationInferenceProfile ?? ''\n ).toLowerCase();\n const isClaudeModel =\n modelName.includes('claude') ||\n modelName.includes('anthropic') ||\n profileName.includes('claude') ||\n profileName.includes('anthropic');\n\n if (isClaudeModel && !this.supportsToolChoiceValues?.length) {\n // Claude models support all tool choice values\n this.supportsToolChoiceValues = ['auto', 'any', 'tool'];\n }\n }\n\n static lc_name(): string {\n return 'IllumaBedrockConverse';\n }\n\n /**\n * Get the model ID to use for API calls.\n * Returns applicationInferenceProfile if set, otherwise returns this.model.\n */\n protected getModelId(): string {\n return this.applicationInferenceProfile ?? this.model;\n }\n\n /**\n * Override invocationParams to:\n * 1. Add cachePoint to tools when promptCache is enabled\n * 2. Add serviceTier support\n *\n * CACHING STRATEGY: Separate cachePoints for core tools and MCP tools\n * - Core tools (web_search, execute_code, etc.) are stable → cache first\n * - MCP tools (have '_mcp_' in name) are dynamic → cache separately after\n * - This allows core tools to stay cached when MCP selection changes\n *\n * NOTE: Only Claude models support cachePoint - Nova and other models will reject it.\n */\n override invocationParams(\n options?: this['ParsedCallOptions'] & IllumaBedrockConverseCallOptions\n ): ReturnType<ChatBedrockConverse['invocationParams']> & {\n serviceTier?: { type: ServiceTierType };\n } {\n const params = super.invocationParams(options);\n\n // Add cachePoint to tools array if promptCache is enabled and tools exist\n /**\n * Bedrock requires all toolSpec.description fields to be non-empty strings.\n * Some tools (e.g., MCP-sourced or dynamically created) may have empty or\n * missing descriptions. Patch them here to avoid Bedrock validation errors.\n */\n if (params.toolConfig?.tools && Array.isArray(params.toolConfig.tools)) {\n for (const t of params.toolConfig.tools) {\n const spec = (t as { toolSpec?: { description?: string } }).toolSpec;\n if (spec && (!spec.description || spec.description === '')) {\n spec.description =\n spec.description ||\n `Tool: ${(spec as { name?: string }).name ?? 'unknown'}`;\n }\n }\n }\n\n /* Allowlist-based gate (see cacheSupport.ts). Replaces the old\n * substring heuristic — same default behavior for Claude/Anthropic/\n * Nova models, plus extension via `bedrockCacheModelPatterns`. */\n const cacheSupported = isBedrockCacheSupported(\n this.model,\n this.bedrockCacheModelPatterns,\n );\n\n if (\n this.promptCache &&\n cacheSupported &&\n this.toolCacheStrategy !== 'none' &&\n params.toolConfig?.tools &&\n Array.isArray(params.toolConfig.tools) &&\n params.toolConfig.tools.length > 0\n ) {\n const tools = params.toolConfig.tools;\n\n if (this.toolCacheStrategy === 'single') {\n /* SINGLE: one cachePoint at the end of the tools array. Lightest\n * budget use; appropriate when the entire tools array is treated\n * as one unit and changes together. */\n const toolsWithCache = [\n ...tools,\n { cachePoint: { type: 'default' } } as (typeof tools)[number],\n ];\n params.toolConfig.tools = toolsWithCache;\n } else if (this.toolCacheStrategy === 'split') {\n /* SPLIT: group tools by `toolGroupSelector` and emit a cachePoint\n * after each non-empty group. Group order follows first-encounter\n * order in the input. Use when groups have different volatility\n * (e.g. stable core tools + volatile MCP tools). */\n const groupOrder: string[] = [];\n const groupMap = new Map<string, typeof tools>();\n for (const tool of tools) {\n const toolName =\n (tool as { toolSpec?: { name?: string } }).toolSpec?.name ?? '';\n const groupKey = this.toolGroupSelector(toolName);\n let group = groupMap.get(groupKey);\n if (!group) {\n group = [];\n groupMap.set(groupKey, group);\n groupOrder.push(groupKey);\n }\n group.push(tool);\n }\n\n const toolsWithCache: typeof tools = [];\n for (const groupKey of groupOrder) {\n const group = groupMap.get(groupKey);\n if (!group || group.length === 0) continue;\n toolsWithCache.push(...group);\n toolsWithCache.push(\n { cachePoint: { type: 'default' } } as (typeof tools)[number],\n );\n }\n params.toolConfig.tools = toolsWithCache;\n }\n }\n\n // Add serviceTier support\n const serviceTierType = options?.serviceTier ?? this.serviceTier;\n\n return {\n ...params,\n serviceTier: serviceTierType ? { type: serviceTierType } : undefined,\n };\n }\n\n /**\n * Override _generateNonStreaming to use applicationInferenceProfile as modelId.\n * Uses the same model-swapping pattern as streaming for consistency.\n */\n override async _generateNonStreaming(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & IllumaBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const originalModel = this.model;\n if (\n this.applicationInferenceProfile != null &&\n this.applicationInferenceProfile !== ''\n ) {\n this.model = this.applicationInferenceProfile;\n }\n\n try {\n return await super._generateNonStreaming(messages, options, runManager);\n } finally {\n this.model = originalModel;\n }\n }\n\n /**\n * Own the stream end-to-end so we have direct access to every\n * `contentBlockDelta.contentBlockIndex` from the AWS SDK.\n *\n * This replaces the parent's implementation which strips contentBlockIndex\n * from text and reasoning deltas, making it impossible to merge correctly.\n */\n override async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & IllumaBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const { converseMessages, converseSystem } =\n convertToConverseMessages(messages);\n const params = this.invocationParams(options);\n\n let { streamUsage } = this;\n if ((options as Record<string, unknown>).streamUsage !== undefined) {\n streamUsage = (options as Record<string, unknown>).streamUsage as boolean;\n }\n\n const modelId = this.getModelId();\n\n const command = new ConverseStreamCommand({\n modelId,\n messages: converseMessages,\n system: converseSystem,\n ...(params as Record<string, unknown>),\n });\n\n const response = await this.client.send(command, {\n abortSignal: options.signal,\n });\n\n if (!response.stream) {\n return;\n }\n\n const seenBlockIndices = new Set<number>();\n\n for await (const event of response.stream) {\n if (event.contentBlockStart != null) {\n const startChunk = handleConverseStreamContentBlockStart(\n event.contentBlockStart\n );\n if (startChunk != null) {\n const idx = event.contentBlockStart.contentBlockIndex;\n if (idx != null) {\n seenBlockIndices.add(idx);\n }\n yield this.enrichChunk(startChunk, seenBlockIndices);\n }\n } else if (event.contentBlockDelta != null) {\n const deltaChunk = handleConverseStreamContentBlockDelta(\n event.contentBlockDelta\n );\n\n const idx = event.contentBlockDelta.contentBlockIndex;\n if (idx != null) {\n seenBlockIndices.add(idx);\n }\n\n yield this.enrichChunk(deltaChunk, seenBlockIndices);\n\n await runManager?.handleLLMNewToken(\n deltaChunk.text,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: deltaChunk }\n );\n } else if (event.metadata != null) {\n yield handleConverseStreamMetadata(event.metadata, { streamUsage });\n } else if (event.contentBlockStop != null) {\n const stopIdx = event.contentBlockStop.contentBlockIndex;\n if (stopIdx != null) {\n seenBlockIndices.add(stopIdx);\n }\n } else {\n yield new ChatGenerationChunk({\n text: '',\n message: new AIMessageChunk({\n content: '',\n response_metadata: event,\n }),\n });\n }\n }\n }\n\n /**\n * Inject `index` on content blocks for proper merge behaviour, then strip\n * `contentBlockIndex` from response_metadata to prevent `_mergeDicts` conflicts.\n *\n * Text string content is promoted to array form only when the stream contains\n * multiple content block indices (e.g. reasoning at index 0, text at index 1),\n * ensuring text merges correctly with the already-array accumulated content.\n */\n enrichChunk(\n chunk: ChatGenerationChunk,\n seenBlockIndices: Set<number>\n ): ChatGenerationChunk {\n const message = chunk.message;\n if (!(message instanceof AIMessageChunk)) {\n return chunk;\n }\n\n const metadata = message.response_metadata as Record<string, unknown>;\n const blockIndex = this.extractContentBlockIndex(metadata);\n const hasMetadataIndex = blockIndex != null;\n\n let content: AIMessageChunk['content'] = message.content;\n let contentModified = false;\n\n if (Array.isArray(content) && blockIndex != null) {\n content = content.map((block) =>\n typeof block === 'object' && !('index' in block)\n ? { ...block, index: blockIndex }\n : block\n );\n contentModified = true;\n } else if (\n typeof content === 'string' &&\n content !== '' &&\n blockIndex != null &&\n seenBlockIndices.size > 1\n ) {\n content = [{ type: 'text', text: content, index: blockIndex }];\n contentModified = true;\n }\n\n if (!contentModified && !hasMetadataIndex) {\n return chunk;\n }\n\n const cleanedMetadata = hasMetadataIndex\n ? (this.removeContentBlockIndex(metadata) as Record<string, unknown>)\n : metadata;\n\n return new ChatGenerationChunk({\n text: chunk.text,\n message: new AIMessageChunk({\n ...message,\n content,\n response_metadata: cleanedMetadata,\n }),\n generationInfo: chunk.generationInfo,\n });\n }\n\n /**\n * Extract `contentBlockIndex` from the top level of response_metadata.\n * Our custom handlers always place it at the top level.\n */\n private extractContentBlockIndex(\n metadata: Record<string, unknown>\n ): number | undefined {\n if (\n 'contentBlockIndex' in metadata &&\n typeof metadata.contentBlockIndex === 'number'\n ) {\n return metadata.contentBlockIndex;\n }\n return undefined;\n }\n\n private removeContentBlockIndex(obj: unknown): unknown {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => this.removeContentBlockIndex(item));\n }\n\n if (typeof obj === 'object') {\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (key !== 'contentBlockIndex') {\n cleaned[key] = this.removeContentBlockIndex(value);\n }\n }\n return cleaned;\n }\n\n return obj;\n }\n}\n\n/** @deprecated Use IllumaBedrockConverse. Alias kept for backward compatibility with existing imports. */\nexport const CustomChatBedrockConverse = IllumaBedrockConverse;\n\nexport type { ChatBedrockConverseInput };\n"],"names":["ChatBedrockConverse","isBedrockCacheSupported","messages","convertToConverseMessages","ConverseStreamCommand","handleConverseStreamContentBlockStart","handleConverseStreamContent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nC;AACA,QAAA,OAAO,SAAS;IAClB;AAEQ,IAAA,uBAAuB,CAAC,GAAY,EAAA;QAC1C,IAAI,GAAG,KAAK,IAAI,IAAI,GAAG,KAAK,SAAS,EAAE;AACrC,YAAA,OAAO,GAAG;QACZ;AAEA,QAAA,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;AACtB,YAAA,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC;QAC9D;AAEA,QAAA,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;YAC3B,MAAM,OAAO,GAA4B,EAAE;AAC3C,YAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;AAC9C,gBAAA,IAAI,GAAG,KAAK,mBAAmB,EAAE;oBAC/B,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC;gBACpD;YACF;AACA,YAAA,OAAO,OAAO;QAChB;AAEA,QAAA,OAAO,GAAG;IACZ;AACD;AAED;AACO,MAAM,yBAAyB,GAAG;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../../../../src/llm/bedrock/index.ts"],"sourcesContent":["/**\n * Optimized ChatBedrockConverse wrapper that fixes content block merging for\n * streaming responses and adds support for latest @langchain/aws features:\n *\n * - Prompt caching support for Bedrock Converse API (Illuma feature)\n * - Application Inference Profiles (PR #9129)\n * - Service Tiers (Priority/Standard/Flex) (PR #9785) - requires AWS SDK 3.966.0+\n *\n * Bedrock's `@langchain/aws` library does not include an `index` property on content\n * blocks (unlike Anthropic/OpenAI), which causes LangChain's `_mergeLists` to append\n * each streaming chunk as a separate array entry instead of merging by index.\n *\n * This wrapper takes full ownership of the stream by directly interfacing with the\n * AWS SDK client (`this.client`) and using custom handlers from `./utils/` that\n * include `contentBlockIndex` in response_metadata for every delta type. It then\n * promotes `contentBlockIndex` to an `index` property on each content block\n * (mirroring Anthropic's pattern) and strips it from metadata to avoid\n * `_mergeDicts` conflicts.\n *\n * When multiple content block types are present (e.g. reasoning + text), text deltas\n * are promoted from strings to array form with `index` so they merge correctly once\n * the accumulated content is already an array.\n *\n * PROMPT CACHING:\n * When promptCache: true is set, this wrapper adds cachePoint markers to the tools array\n * to enable Bedrock prompt caching for tool definitions. This allows tool schemas to be\n * cached and reused across requests, reducing latency and costs.\n *\n * CACHE TOKEN EXTRACTION:\n * Cache token extraction is handled in `./utils/message_outputs.ts` and added\n * to usage_metadata with input_token_details (cacheReadInputTokens/cacheWriteInputTokens).\n */\n\nimport { ChatBedrockConverse } from '@langchain/aws';\nimport { ConverseStreamCommand } from '@aws-sdk/client-bedrock-runtime';\nimport { AIMessageChunk } from '@langchain/core/messages';\nimport type { BaseMessage } from '@langchain/core/messages';\nimport { ChatGenerationChunk, ChatResult } from '@langchain/core/outputs';\nimport type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';\nimport type { ChatBedrockConverseInput } from '@langchain/aws';\nimport {\n convertToConverseMessages,\n handleConverseStreamContentBlockStart,\n handleConverseStreamContentBlockDelta,\n handleConverseStreamMetadata,\n} from './utils';\n\n/**\n * Service tier type for Bedrock invocations.\n * Requires AWS SDK >= 3.966.0 to actually work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\nexport type ServiceTierType = 'priority' | 'default' | 'flex' | 'reserved';\n\n/**\n * Extended input interface with additional features:\n * - promptCache: Enable Bedrock prompt caching for tool definitions\n * - applicationInferenceProfile: Use an inference profile ARN instead of model ID\n * - serviceTier: Specify service tier (Priority, Standard, Flex, Reserved)\n */\nexport interface IllumaBedrockConverseInput extends ChatBedrockConverseInput {\n /**\n * Enable Bedrock prompt caching for tool definitions.\n * When true, adds cachePoint markers to tools array.\n */\n promptCache?: boolean;\n\n /**\n * Application Inference Profile ARN to use for the model.\n * For example, \"arn:aws:bedrock:eu-west-1:123456789102:application-inference-profile/fm16bt65tzgx\"\n * When provided, this ARN will be used for the actual inference calls instead of the model ID.\n * Must still provide `model` as normal modelId to benefit from all the metadata.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-create.html\n */\n applicationInferenceProfile?: string;\n\n /**\n * Service tier for model invocation.\n * Specifies the processing tier type used for serving the request.\n * Supported values are 'priority', 'default', 'flex', and 'reserved'.\n *\n * - 'priority': Prioritized processing for lower latency\n * - 'default': Standard processing tier\n * - 'flex': Flexible processing tier with lower cost\n * - 'reserved': Reserved capacity for consistent performance\n *\n * If not provided, AWS uses the default tier.\n * Note: Requires AWS SDK >= 3.966.0 to work.\n * @see https://docs.aws.amazon.com/bedrock/latest/userguide/service-tiers-inference.html\n */\n serviceTier?: ServiceTierType;\n}\n\n/**\n * Extended call options with serviceTier override support.\n */\nexport interface IllumaBedrockConverseCallOptions {\n serviceTier?: ServiceTierType;\n}\n\nexport class IllumaBedrockConverse extends ChatBedrockConverse {\n /** Enable Bedrock prompt caching for tool definitions */\n promptCache: boolean;\n\n /** Application Inference Profile ARN to use instead of model ID */\n applicationInferenceProfile?: string;\n\n /** Service tier for model invocation */\n serviceTier?: ServiceTierType;\n\n constructor(fields?: IllumaBedrockConverseInput) {\n super(fields);\n this.promptCache = fields?.promptCache ?? false;\n this.applicationInferenceProfile = fields?.applicationInferenceProfile;\n this.serviceTier = fields?.serviceTier;\n\n // Fix: Force supportsToolChoiceValues for Claude models\n // The parent constructor checks `model.includes('claude-3')` but this fails when:\n // 1. Using applicationInferenceProfile ARNs (arn:aws:bedrock:...)\n // 2. Using different naming conventions (claude-4, claude-opus-4, etc.)\n // We need to ensure tool_choice is properly set for withStructuredOutput to work\n const modelName = (fields?.model ?? '').toLowerCase();\n const profileName = (\n fields?.applicationInferenceProfile ?? ''\n ).toLowerCase();\n const isClaudeModel =\n modelName.includes('claude') ||\n modelName.includes('anthropic') ||\n profileName.includes('claude') ||\n profileName.includes('anthropic');\n\n if (isClaudeModel && !this.supportsToolChoiceValues?.length) {\n // Claude models support all tool choice values\n this.supportsToolChoiceValues = ['auto', 'any', 'tool'];\n }\n }\n\n static lc_name(): string {\n return 'IllumaBedrockConverse';\n }\n\n /**\n * Get the model ID to use for API calls.\n * Returns applicationInferenceProfile if set, otherwise returns this.model.\n */\n protected getModelId(): string {\n return this.applicationInferenceProfile ?? this.model;\n }\n\n /**\n * Override invocationParams to:\n * 1. Add cachePoint to tools when promptCache is enabled\n * 2. Add serviceTier support\n *\n * CACHING STRATEGY: Separate cachePoints for core tools and MCP tools\n * - Core tools (web_search, execute_code, etc.) are stable → cache first\n * - MCP tools (have '_mcp_' in name) are dynamic → cache separately after\n * - This allows core tools to stay cached when MCP selection changes\n *\n * NOTE: Only Claude models support cachePoint - Nova and other models will reject it.\n */\n override invocationParams(\n options?: this['ParsedCallOptions'] & IllumaBedrockConverseCallOptions\n ): ReturnType<ChatBedrockConverse['invocationParams']> & {\n serviceTier?: { type: ServiceTierType };\n } {\n const params = super.invocationParams(options);\n\n // Add cachePoint to tools array if promptCache is enabled and tools exist\n /**\n * Bedrock requires all toolSpec.description fields to be non-empty strings.\n * Some tools (e.g., MCP-sourced or dynamically created) may have empty or\n * missing descriptions. Patch them here to avoid Bedrock validation errors.\n */\n if (params.toolConfig?.tools && Array.isArray(params.toolConfig.tools)) {\n for (const t of params.toolConfig.tools) {\n const spec = (t as { toolSpec?: { description?: string } }).toolSpec;\n if (spec && (!spec.description || spec.description === '')) {\n spec.description =\n spec.description ||\n `Tool: ${(spec as { name?: string }).name ?? 'unknown'}`;\n }\n }\n }\n\n // Only Claude models support cachePoint - check model name\n const modelId = this.model.toLowerCase();\n const isClaudeModel =\n modelId.includes('claude') || modelId.includes('anthropic');\n\n if (\n this.promptCache &&\n isClaudeModel &&\n params.toolConfig?.tools &&\n Array.isArray(params.toolConfig.tools) &&\n params.toolConfig.tools.length > 0\n ) {\n // Separate core tools from MCP tools\n // MCP tools have '_mcp_' in their name (e.g., 'search_emails_mcp_Google-Workspace')\n const coreTools: typeof params.toolConfig.tools = [];\n const mcpTools: typeof params.toolConfig.tools = [];\n\n for (const tool of params.toolConfig.tools) {\n // Check if tool has a name property with '_mcp_' pattern\n const toolName =\n (tool as { toolSpec?: { name?: string } }).toolSpec?.name ?? '';\n if (toolName.includes('_mcp_')) {\n mcpTools.push(tool);\n } else {\n coreTools.push(tool);\n }\n }\n\n // Build tools array with strategic cachePoints:\n // [CoreTool1, CoreTool2, cachePoint] + [MCPTool1, MCPTool2, cachePoint]\n const toolsWithCache: typeof params.toolConfig.tools = [];\n\n // Add core tools with cachePoint (if any)\n if (coreTools.length > 0) {\n toolsWithCache.push(...coreTools);\n toolsWithCache.push({ cachePoint: { type: 'default' } });\n }\n\n // Add MCP tools with their own cachePoint (if any)\n if (mcpTools.length > 0) {\n toolsWithCache.push(...mcpTools);\n toolsWithCache.push({ cachePoint: { type: 'default' } });\n }\n\n // If no tools at all (shouldn't happen but safety check)\n if (toolsWithCache.length === 0) {\n toolsWithCache.push({ cachePoint: { type: 'default' } });\n }\n\n params.toolConfig.tools = toolsWithCache;\n }\n\n // Add serviceTier support\n const serviceTierType = options?.serviceTier ?? this.serviceTier;\n\n return {\n ...params,\n serviceTier: serviceTierType ? { type: serviceTierType } : undefined,\n };\n }\n\n /**\n * Override _generateNonStreaming to use applicationInferenceProfile as modelId.\n * Uses the same model-swapping pattern as streaming for consistency.\n */\n override async _generateNonStreaming(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & IllumaBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): Promise<ChatResult> {\n const originalModel = this.model;\n if (\n this.applicationInferenceProfile != null &&\n this.applicationInferenceProfile !== ''\n ) {\n this.model = this.applicationInferenceProfile;\n }\n\n try {\n return await super._generateNonStreaming(messages, options, runManager);\n } finally {\n this.model = originalModel;\n }\n }\n\n /**\n * Own the stream end-to-end so we have direct access to every\n * `contentBlockDelta.contentBlockIndex` from the AWS SDK.\n *\n * This replaces the parent's implementation which strips contentBlockIndex\n * from text and reasoning deltas, making it impossible to merge correctly.\n */\n override async *_streamResponseChunks(\n messages: BaseMessage[],\n options: this['ParsedCallOptions'] & IllumaBedrockConverseCallOptions,\n runManager?: CallbackManagerForLLMRun\n ): AsyncGenerator<ChatGenerationChunk> {\n const { converseMessages, converseSystem } =\n convertToConverseMessages(messages);\n const params = this.invocationParams(options);\n\n let { streamUsage } = this;\n if ((options as Record<string, unknown>).streamUsage !== undefined) {\n streamUsage = (options as Record<string, unknown>).streamUsage as boolean;\n }\n\n const modelId = this.getModelId();\n\n const command = new ConverseStreamCommand({\n modelId,\n messages: converseMessages,\n system: converseSystem,\n ...(params as Record<string, unknown>),\n });\n\n const response = await this.client.send(command, {\n abortSignal: options.signal,\n });\n\n if (!response.stream) {\n return;\n }\n\n const seenBlockIndices = new Set<number>();\n\n for await (const event of response.stream) {\n if (event.contentBlockStart != null) {\n const startChunk = handleConverseStreamContentBlockStart(\n event.contentBlockStart\n );\n if (startChunk != null) {\n const idx = event.contentBlockStart.contentBlockIndex;\n if (idx != null) {\n seenBlockIndices.add(idx);\n }\n yield this.enrichChunk(startChunk, seenBlockIndices);\n }\n } else if (event.contentBlockDelta != null) {\n const deltaChunk = handleConverseStreamContentBlockDelta(\n event.contentBlockDelta\n );\n\n const idx = event.contentBlockDelta.contentBlockIndex;\n if (idx != null) {\n seenBlockIndices.add(idx);\n }\n\n yield this.enrichChunk(deltaChunk, seenBlockIndices);\n\n await runManager?.handleLLMNewToken(\n deltaChunk.text,\n undefined,\n undefined,\n undefined,\n undefined,\n { chunk: deltaChunk }\n );\n } else if (event.metadata != null) {\n yield handleConverseStreamMetadata(event.metadata, { streamUsage });\n } else if (event.contentBlockStop != null) {\n const stopIdx = event.contentBlockStop.contentBlockIndex;\n if (stopIdx != null) {\n seenBlockIndices.add(stopIdx);\n }\n } else {\n yield new ChatGenerationChunk({\n text: '',\n message: new AIMessageChunk({\n content: '',\n response_metadata: event,\n }),\n });\n }\n }\n }\n\n /**\n * Inject `index` on content blocks for proper merge behaviour, then strip\n * `contentBlockIndex` from response_metadata to prevent `_mergeDicts` conflicts.\n *\n * Text string content is promoted to array form only when the stream contains\n * multiple content block indices (e.g. reasoning at index 0, text at index 1),\n * ensuring text merges correctly with the already-array accumulated content.\n */\n enrichChunk(\n chunk: ChatGenerationChunk,\n seenBlockIndices: Set<number>\n ): ChatGenerationChunk {\n const message = chunk.message;\n if (!(message instanceof AIMessageChunk)) {\n return chunk;\n }\n\n const metadata = message.response_metadata as Record<string, unknown>;\n const blockIndex = this.extractContentBlockIndex(metadata);\n const hasMetadataIndex = blockIndex != null;\n\n let content: AIMessageChunk['content'] = message.content;\n let contentModified = false;\n\n if (Array.isArray(content) && blockIndex != null) {\n content = content.map((block) =>\n typeof block === 'object' && !('index' in block)\n ? { ...block, index: blockIndex }\n : block\n );\n contentModified = true;\n } else if (\n typeof content === 'string' &&\n content !== '' &&\n blockIndex != null &&\n seenBlockIndices.size > 1\n ) {\n content = [{ type: 'text', text: content, index: blockIndex }];\n contentModified = true;\n }\n\n if (!contentModified && !hasMetadataIndex) {\n return chunk;\n }\n\n const cleanedMetadata = hasMetadataIndex\n ? (this.removeContentBlockIndex(metadata) as Record<string, unknown>)\n : metadata;\n\n return new ChatGenerationChunk({\n text: chunk.text,\n message: new AIMessageChunk({\n ...message,\n content,\n response_metadata: cleanedMetadata,\n }),\n generationInfo: chunk.generationInfo,\n });\n }\n\n /**\n * Extract `contentBlockIndex` from the top level of response_metadata.\n * Our custom handlers always place it at the top level.\n */\n private extractContentBlockIndex(\n metadata: Record<string, unknown>\n ): number | undefined {\n if (\n 'contentBlockIndex' in metadata &&\n typeof metadata.contentBlockIndex === 'number'\n ) {\n return metadata.contentBlockIndex;\n }\n return undefined;\n }\n\n private removeContentBlockIndex(obj: unknown): unknown {\n if (obj === null || obj === undefined) {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => this.removeContentBlockIndex(item));\n }\n\n if (typeof obj === 'object') {\n const cleaned: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n if (key !== 'contentBlockIndex') {\n cleaned[key] = this.removeContentBlockIndex(value);\n }\n }\n return cleaned;\n }\n\n return obj;\n }\n}\n\n/** @deprecated Use IllumaBedrockConverse. Alias kept for backward compatibility with existing imports. */\nexport const CustomChatBedrockConverse = IllumaBedrockConverse;\n\nexport type { ChatBedrockConverseInput };\n"],"names":["ChatBedrockConverse","messages","convertToConverseMessages","ConverseStreamCommand","handleConverseStreamContentBlockStart","handleConverseStreamContentBlockDelta","handleConverseStreamMetadata","ChatGenerationChunk","AIMessageChunk"],"mappings":";;;;;;;;;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BG;AAqEG,MAAO,qBAAsB,SAAQA,uBAAmB,CAAA;;AAE5D,IAAA,WAAW;;AAGX,IAAA,2BAA2B;;AAG3B,IAAA,WAAW;AAEX,IAAA,WAAA,CAAY,MAAmC,EAAA;QAC7C,KAAK,CAAC,MAAM,CAAC;QACb,IAAI,CAAC,WAAW,GAAG,MAAM,EAAE,WAAW,IAAI,KAAK;AAC/C,QAAA,IAAI,CAAC,2BAA2B,GAAG,MAAM,EAAE,2BAA2B;AACtE,QAAA,IAAI,CAAC,WAAW,GAAG,MAAM,EAAE,WAAW;;;;;;AAOtC,QAAA,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,KAAK,IAAI,EAAE,EAAE,WAAW,EAAE;AACrD,QAAA,MAAM,WAAW,GAAG,CAClB,MAAM,EAAE,2BAA2B,IAAI,EAAE,EACzC,WAAW,EAAE;AACf,QAAA,MAAM,aAAa,GACjB,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC;AAC5B,YAAA,SAAS,CAAC,QAAQ,CAAC,WAAW,CAAC;AAC/B,YAAA,WAAW,CAAC,QAAQ,CAAC,QAAQ,CAAC;AAC9B,YAAA,WAAW,CAAC,QAAQ,CAAC,WAAW,CAAC;QAEnC,IAAI,aAAa,IAAI,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K,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC;QAC9D;AAEA,QAAA,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;YAC3B,MAAM,OAAO,GAA4B,EAAE;AAC3C,YAAA,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;AAC9C,gBAAA,IAAI,GAAG,KAAK,mBAAmB,EAAE;oBAC/B,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,uBAAuB,CAAC,KAAK,CAAC;gBACpD;YACF;AACA,YAAA,OAAO,OAAO;QAChB;AAEA,QAAA,OAAO,GAAG;IACZ;AACD;AAED;AACO,MAAM,yBAAyB,GAAG;;;;;"}
@@ -640,7 +640,7 @@ class ChatDeepSeek extends deepseek.ChatDeepSeek {
640
640
  }
641
641
  class ChatMoonshot extends ChatOpenAI {
642
642
  static lc_name() {
643
- return 'IllumaMoonshot';
643
+ return 'LibreChatMoonshot';
644
644
  }
645
645
  _convertMessages(messages) {
646
646
  return index._convertMessagesToOpenAIParams(messages, this.model, {