@librechat/agents 4.2.12 → 4.2.14

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 (357) hide show
  1. package/dist/cjs/graphs/Graph.cjs +56 -6
  2. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  3. package/dist/cjs/harness/providerText.cjs +1 -0
  4. package/dist/cjs/harness/providerText.cjs.map +1 -1
  5. package/dist/cjs/llm/anthropic/index.cjs +4 -3
  6. package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
  7. package/dist/cjs/llm/anthropic/utils/container.cjs +37 -0
  8. package/dist/cjs/llm/anthropic/utils/container.cjs.map +1 -0
  9. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +25 -23
  10. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  11. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs +15 -21
  12. package/dist/cjs/llm/anthropic/utils/message_outputs.cjs.map +1 -1
  13. package/dist/cjs/llm/anthropic/utils/stream_events.cjs +16 -14
  14. package/dist/cjs/llm/anthropic/utils/stream_events.cjs.map +1 -1
  15. package/dist/cjs/llm/bedrock/index.cjs +1 -1
  16. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  17. package/dist/cjs/llm/bedrock/toolCache.cjs +1 -1
  18. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs +19 -13
  19. package/dist/cjs/llm/bedrock/utils/message_inputs.cjs.map +1 -1
  20. package/dist/cjs/llm/google/utils/common.cjs +59 -13
  21. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  22. package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
  23. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  24. package/dist/cjs/llm/init.cjs +12 -2
  25. package/dist/cjs/llm/init.cjs.map +1 -1
  26. package/dist/cjs/llm/invoke.cjs +122 -13
  27. package/dist/cjs/llm/invoke.cjs.map +1 -1
  28. package/dist/cjs/llm/openai/index.cjs +9 -3
  29. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  30. package/dist/cjs/llm/openai/typedContent.cjs +94 -0
  31. package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
  32. package/dist/cjs/llm/openrouter/toolCache.cjs +1 -1
  33. package/dist/cjs/llm/prepareProviderRequest.cjs +81 -4
  34. package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
  35. package/dist/cjs/llm/providerTextBatch.cjs +128 -0
  36. package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
  37. package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
  38. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  39. package/dist/cjs/main.cjs +8 -3
  40. package/dist/cjs/messages/alternation.cjs +1 -1
  41. package/dist/cjs/messages/anthropicServerTools.cjs +20 -0
  42. package/dist/cjs/messages/anthropicServerTools.cjs.map +1 -0
  43. package/dist/cjs/messages/budget.cjs +1 -1
  44. package/dist/cjs/messages/core.cjs +3 -2
  45. package/dist/cjs/messages/core.cjs.map +1 -1
  46. package/dist/cjs/messages/format.cjs +2 -2
  47. package/dist/cjs/messages/index.cjs +1 -1
  48. package/dist/cjs/messages/prune.cjs +1 -1
  49. package/dist/cjs/messages/recency.cjs +1 -1
  50. package/dist/cjs/messages/toolResultTypes.cjs +21 -45
  51. package/dist/cjs/messages/toolResultTypes.cjs.map +1 -1
  52. package/dist/cjs/protection/providerText.cjs +60 -6
  53. package/dist/cjs/protection/providerText.cjs.map +1 -1
  54. package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
  55. package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
  56. package/dist/cjs/protection/toolResult.cjs +119 -0
  57. package/dist/cjs/protection/toolResult.cjs.map +1 -0
  58. package/dist/cjs/run.cjs +14 -3
  59. package/dist/cjs/run.cjs.map +1 -1
  60. package/dist/cjs/runtime/client.cjs +4 -0
  61. package/dist/cjs/runtime/client.cjs.map +1 -1
  62. package/dist/cjs/stream.cjs +10 -2
  63. package/dist/cjs/stream.cjs.map +1 -1
  64. package/dist/cjs/summarization/node.cjs +1 -1
  65. package/dist/cjs/tools/ToolNode.cjs +46 -13
  66. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  67. package/dist/cjs/tools/handlers.cjs +47 -1
  68. package/dist/cjs/tools/handlers.cjs.map +1 -1
  69. package/dist/cjs/tools/search/citations.cjs +194 -0
  70. package/dist/cjs/tools/search/citations.cjs.map +1 -0
  71. package/dist/cjs/tools/search/content.cjs +163 -42
  72. package/dist/cjs/tools/search/content.cjs.map +1 -1
  73. package/dist/cjs/tools/search/firecrawl.cjs +4 -9
  74. package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
  75. package/dist/cjs/tools/search/google.cjs +68 -0
  76. package/dist/cjs/tools/search/google.cjs.map +1 -0
  77. package/dist/cjs/tools/search/openai.cjs +80 -0
  78. package/dist/cjs/tools/search/openai.cjs.map +1 -0
  79. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +4 -0
  80. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  81. package/dist/cjs/utils/tokens.cjs +12 -2
  82. package/dist/cjs/utils/tokens.cjs.map +1 -1
  83. package/dist/esm/graphs/Graph.mjs +57 -7
  84. package/dist/esm/graphs/Graph.mjs.map +1 -1
  85. package/dist/esm/harness/providerText.mjs +1 -0
  86. package/dist/esm/harness/providerText.mjs.map +1 -1
  87. package/dist/esm/llm/anthropic/index.mjs +4 -3
  88. package/dist/esm/llm/anthropic/index.mjs.map +1 -1
  89. package/dist/esm/llm/anthropic/utils/container.mjs +37 -0
  90. package/dist/esm/llm/anthropic/utils/container.mjs.map +1 -0
  91. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +25 -23
  92. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  93. package/dist/esm/llm/anthropic/utils/message_outputs.mjs +15 -21
  94. package/dist/esm/llm/anthropic/utils/message_outputs.mjs.map +1 -1
  95. package/dist/esm/llm/anthropic/utils/stream_events.mjs +16 -14
  96. package/dist/esm/llm/anthropic/utils/stream_events.mjs.map +1 -1
  97. package/dist/esm/llm/bedrock/index.mjs +2 -2
  98. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  99. package/dist/esm/llm/bedrock/toolCache.mjs +1 -1
  100. package/dist/esm/llm/bedrock/utils/message_inputs.mjs +19 -14
  101. package/dist/esm/llm/bedrock/utils/message_inputs.mjs.map +1 -1
  102. package/dist/esm/llm/google/utils/common.mjs +59 -13
  103. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  104. package/dist/esm/llm/google/utils/signatures.mjs +22 -14
  105. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  106. package/dist/esm/llm/init.mjs +12 -2
  107. package/dist/esm/llm/init.mjs.map +1 -1
  108. package/dist/esm/llm/invoke.mjs +124 -15
  109. package/dist/esm/llm/invoke.mjs.map +1 -1
  110. package/dist/esm/llm/openai/index.mjs +9 -3
  111. package/dist/esm/llm/openai/index.mjs.map +1 -1
  112. package/dist/esm/llm/openai/typedContent.mjs +93 -0
  113. package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
  114. package/dist/esm/llm/openrouter/toolCache.mjs +1 -1
  115. package/dist/esm/llm/prepareProviderRequest.mjs +81 -4
  116. package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
  117. package/dist/esm/llm/providerTextBatch.mjs +128 -0
  118. package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
  119. package/dist/esm/llm/providerTextBoundary.mjs +81 -12
  120. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  121. package/dist/esm/main.mjs +7 -6
  122. package/dist/esm/messages/alternation.mjs +1 -1
  123. package/dist/esm/messages/anthropicServerTools.mjs +18 -0
  124. package/dist/esm/messages/anthropicServerTools.mjs.map +1 -0
  125. package/dist/esm/messages/budget.mjs +1 -1
  126. package/dist/esm/messages/core.mjs +3 -2
  127. package/dist/esm/messages/core.mjs.map +1 -1
  128. package/dist/esm/messages/format.mjs +2 -2
  129. package/dist/esm/messages/index.mjs +1 -1
  130. package/dist/esm/messages/prune.mjs +1 -1
  131. package/dist/esm/messages/recency.mjs +1 -1
  132. package/dist/esm/messages/toolResultTypes.mjs +21 -45
  133. package/dist/esm/messages/toolResultTypes.mjs.map +1 -1
  134. package/dist/esm/protection/providerText.mjs +58 -7
  135. package/dist/esm/protection/providerText.mjs.map +1 -1
  136. package/dist/esm/protection/providerTextAdmission.mjs +5 -0
  137. package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
  138. package/dist/esm/protection/toolResult.mjs +114 -0
  139. package/dist/esm/protection/toolResult.mjs.map +1 -0
  140. package/dist/esm/run.mjs +14 -3
  141. package/dist/esm/run.mjs.map +1 -1
  142. package/dist/esm/runtime/client.mjs +4 -0
  143. package/dist/esm/runtime/client.mjs.map +1 -1
  144. package/dist/esm/stream.mjs +10 -2
  145. package/dist/esm/stream.mjs.map +1 -1
  146. package/dist/esm/summarization/node.mjs +1 -1
  147. package/dist/esm/tools/ToolNode.mjs +46 -13
  148. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  149. package/dist/esm/tools/handlers.mjs +47 -2
  150. package/dist/esm/tools/handlers.mjs.map +1 -1
  151. package/dist/esm/tools/search/citations.mjs +190 -0
  152. package/dist/esm/tools/search/citations.mjs.map +1 -0
  153. package/dist/esm/tools/search/content.mjs +163 -42
  154. package/dist/esm/tools/search/content.mjs.map +1 -1
  155. package/dist/esm/tools/search/firecrawl.mjs +4 -9
  156. package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
  157. package/dist/esm/tools/search/google.mjs +67 -0
  158. package/dist/esm/tools/search/google.mjs.map +1 -0
  159. package/dist/esm/tools/search/openai.mjs +80 -0
  160. package/dist/esm/tools/search/openai.mjs.map +1 -0
  161. package/dist/esm/tools/subagent/SubagentExecutor.mjs +4 -0
  162. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  163. package/dist/esm/utils/tokens.mjs +12 -2
  164. package/dist/esm/utils/tokens.mjs.map +1 -1
  165. package/dist/types/common/index.d.ts +2 -2
  166. package/dist/types/decisions/breaker.d.ts +2 -2
  167. package/dist/types/decisions/core.d.ts +13 -13
  168. package/dist/types/decisions/dialect.d.ts +1 -1
  169. package/dist/types/decisions/http.d.ts +2 -2
  170. package/dist/types/decisions/index.d.ts +5 -5
  171. package/dist/types/decisions/node.d.ts +2 -2
  172. package/dist/types/decisions/presets.d.ts +2 -2
  173. package/dist/types/decisions/probe.d.ts +1 -1
  174. package/dist/types/decisions/questions.d.ts +1 -1
  175. package/dist/types/decisions/structuredChat.d.ts +2 -2
  176. package/dist/types/decisions/transport.d.ts +1 -1
  177. package/dist/types/eventActor/EventActorExecutor.d.ts +1 -1
  178. package/dist/types/eventActor/index.d.ts +2 -2
  179. package/dist/types/graphs/Graph.d.ts +18 -2
  180. package/dist/types/graphs/MultiAgentGraph.d.ts +1 -1
  181. package/dist/types/graphs/applyGraphRuntimeConfig.d.ts +1 -1
  182. package/dist/types/graphs/graphFactory.d.ts +1 -1
  183. package/dist/types/graphs/index.d.ts +5 -5
  184. package/dist/types/harness/fileBindings.d.ts +2 -2
  185. package/dist/types/harness/fileService.d.ts +2 -2
  186. package/dist/types/harness/fileStream.d.ts +1 -1
  187. package/dist/types/harness/index.d.ts +15 -15
  188. package/dist/types/harness/model.d.ts +1 -1
  189. package/dist/types/harness/modelService.d.ts +2 -2
  190. package/dist/types/harness/modelStreamCallbacks.d.ts +1 -1
  191. package/dist/types/harness/providerText.d.ts +1 -1
  192. package/dist/types/hitl/index.d.ts +3 -3
  193. package/dist/types/hooks/HookRegistry.d.ts +1 -1
  194. package/dist/types/hooks/createToolPolicyHook.d.ts +1 -1
  195. package/dist/types/hooks/createWorkspacePolicyHook.d.ts +1 -1
  196. package/dist/types/hooks/executeHooks.d.ts +2 -2
  197. package/dist/types/hooks/index.d.ts +11 -11
  198. package/dist/types/index.d.ts +62 -60
  199. package/dist/types/langchain/index.d.ts +8 -8
  200. package/dist/types/llm/anthropic/utils/container.d.ts +4 -0
  201. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -1
  202. package/dist/types/llm/anthropic/utils/message_outputs.d.ts +1 -1
  203. package/dist/types/llm/anthropic/utils/stream_events.d.ts +1 -1
  204. package/dist/types/llm/bedrock/index.d.ts +2 -3
  205. package/dist/types/llm/bedrock/utils/harmony.d.ts +1 -1
  206. package/dist/types/llm/bedrock/utils/index.d.ts +2 -2
  207. package/dist/types/llm/bedrock/utils/message_inputs.d.ts +3 -12
  208. package/dist/types/llm/bedrock/utils/message_outputs.d.ts +1 -1
  209. package/dist/types/llm/google/index.d.ts +2 -2
  210. package/dist/types/llm/google/utils/common.d.ts +1 -1
  211. package/dist/types/llm/google/utils/tools.d.ts +1 -1
  212. package/dist/types/llm/openai/index.d.ts +1 -1
  213. package/dist/types/llm/openai/typedContent.d.ts +14 -0
  214. package/dist/types/llm/providerRegistry.d.ts +1 -1
  215. package/dist/types/llm/providerTextBatch.d.ts +26 -0
  216. package/dist/types/llm/providerTextBoundary.d.ts +7 -1
  217. package/dist/types/llm/providers.d.ts +1 -1
  218. package/dist/types/messages/anthropicServerTools.d.ts +13 -0
  219. package/dist/types/messages/contextPruning.d.ts +1 -1
  220. package/dist/types/messages/core.d.ts +4 -4
  221. package/dist/types/messages/format.d.ts +1 -1
  222. package/dist/types/messages/index.d.ts +21 -21
  223. package/dist/types/messages/prune.d.ts +1 -1
  224. package/dist/types/openai/index.d.ts +2 -2
  225. package/dist/types/openai/toolProjection.d.ts +1 -1
  226. package/dist/types/prompts/index.d.ts +2 -2
  227. package/dist/types/protection/providerText.d.ts +32 -2
  228. package/dist/types/protection/providerTextAdmission.d.ts +1 -0
  229. package/dist/types/protection/toolResult.d.ts +69 -0
  230. package/dist/types/provider-registration.d.ts +1 -1
  231. package/dist/types/rerank/bm25.d.ts +1 -1
  232. package/dist/types/rerank/core.d.ts +17 -17
  233. package/dist/types/rerank/crossEncoder.d.ts +3 -3
  234. package/dist/types/rerank/fallback.d.ts +1 -1
  235. package/dist/types/rerank/index.d.ts +2 -2
  236. package/dist/types/rerank/outcome.d.ts +2 -2
  237. package/dist/types/rerank/pin.d.ts +2 -2
  238. package/dist/types/rerank/search.d.ts +1 -1
  239. package/dist/types/rerank/systemone.d.ts +4 -4
  240. package/dist/types/rerank/types.d.ts +1 -1
  241. package/dist/types/run.d.ts +1 -0
  242. package/dist/types/runtime/admission.d.ts +1 -1
  243. package/dist/types/runtime/checkpoint.d.ts +1 -1
  244. package/dist/types/runtime/client.d.ts +2 -2
  245. package/dist/types/runtime/files.d.ts +3 -3
  246. package/dist/types/runtime/hostTools.d.ts +2 -2
  247. package/dist/types/runtime/index.d.ts +12 -12
  248. package/dist/types/runtime/model.d.ts +5 -5
  249. package/dist/types/runtime/policy.d.ts +3 -3
  250. package/dist/types/runtime/recovery/client.d.ts +3 -3
  251. package/dist/types/runtime/recovery/log.d.ts +2 -2
  252. package/dist/types/runtime/recovery/redis.d.ts +1 -1
  253. package/dist/types/runtime/recovery/server.d.ts +3 -3
  254. package/dist/types/runtime/resume.d.ts +1 -1
  255. package/dist/types/runtime/server.d.ts +3 -3
  256. package/dist/types/runtime/snapshot.d.ts +1 -1
  257. package/dist/types/runtime/types.d.ts +2 -2
  258. package/dist/types/session/AgentSession.d.ts +2 -2
  259. package/dist/types/session/JsonlSessionStore.d.ts +1 -1
  260. package/dist/types/session/deriveMessages.d.ts +1 -1
  261. package/dist/types/session/handlers.d.ts +1 -1
  262. package/dist/types/session/index.d.ts +7 -7
  263. package/dist/types/session/messageSerialization.d.ts +1 -1
  264. package/dist/types/session/sessionProjection.d.ts +3 -3
  265. package/dist/types/summarization/index.d.ts +2 -2
  266. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +1 -1
  267. package/dist/types/tools/GitHubCompare.d.ts +6 -6
  268. package/dist/types/tools/ProgrammaticToolCalling.d.ts +1 -1
  269. package/dist/types/tools/ReadFile.d.ts +6 -6
  270. package/dist/types/tools/SkillTool.d.ts +6 -6
  271. package/dist/types/tools/ToolNode.d.ts +5 -1
  272. package/dist/types/tools/cloudflare/index.d.ts +4 -4
  273. package/dist/types/tools/handlers.d.ts +13 -0
  274. package/dist/types/tools/local/FileCheckpointer.d.ts +1 -1
  275. package/dist/types/tools/local/LocalExecutionEngine.d.ts +1 -1
  276. package/dist/types/tools/local/attachments.d.ts +1 -1
  277. package/dist/types/tools/local/index.d.ts +12 -12
  278. package/dist/types/tools/search/anthropic.d.ts +1 -1
  279. package/dist/types/tools/search/citations.d.ts +88 -0
  280. package/dist/types/tools/search/content.d.ts +38 -1
  281. package/dist/types/tools/search/crw-scraper.d.ts +1 -1
  282. package/dist/types/tools/search/crw-search.d.ts +1 -1
  283. package/dist/types/tools/search/firecrawl.d.ts +4 -2
  284. package/dist/types/tools/search/format.d.ts +1 -1
  285. package/dist/types/tools/search/google.d.ts +11 -0
  286. package/dist/types/tools/search/highlights.d.ts +1 -1
  287. package/dist/types/tools/search/index.d.ts +3 -3
  288. package/dist/types/tools/search/keenable-scraper.d.ts +1 -1
  289. package/dist/types/tools/search/keenable-search.d.ts +1 -1
  290. package/dist/types/tools/search/metrics.d.ts +1 -1
  291. package/dist/types/tools/search/openai.d.ts +3 -0
  292. package/dist/types/tools/search/rerankers.d.ts +1 -1
  293. package/dist/types/tools/search/schema.d.ts +6 -6
  294. package/dist/types/tools/search/search.d.ts +1 -1
  295. package/dist/types/tools/search/serper-scraper.d.ts +1 -1
  296. package/dist/types/tools/search/tavily-scraper.d.ts +1 -1
  297. package/dist/types/tools/search/tavily-search.d.ts +1 -1
  298. package/dist/types/tools/search/tool.d.ts +3 -3
  299. package/dist/types/tools/search/types.d.ts +26 -2
  300. package/dist/types/tools/search/utils.d.ts +3 -3
  301. package/dist/types/tools/subagent/SubagentExecutionRegistry.d.ts +1 -1
  302. package/dist/types/tools/subagent/SubagentExecutor.d.ts +6 -3
  303. package/dist/types/tools/subagent/diagnostics.d.ts +1 -1
  304. package/dist/types/tools/subagent/index.d.ts +7 -7
  305. package/dist/types/types/attachments.d.ts +1 -1
  306. package/dist/types/types/graph.d.ts +4 -1
  307. package/dist/types/types/index.d.ts +14 -14
  308. package/dist/types/types/llm.d.ts +2 -2
  309. package/dist/types/types/run.d.ts +3 -1
  310. package/dist/types/types/stream.d.ts +12 -0
  311. package/dist/types/types/subagentTasks.d.ts +2 -2
  312. package/dist/types/types/tools.d.ts +6 -3
  313. package/dist/types/utils/index.d.ts +10 -10
  314. package/dist/types/utils/tokens.d.ts +2 -0
  315. package/package.json +3 -2
  316. package/src/graphs/Graph.ts +125 -3
  317. package/src/harness/providerText.ts +1 -0
  318. package/src/index.ts +10 -0
  319. package/src/llm/anthropic/index.ts +11 -3
  320. package/src/llm/anthropic/utils/container.ts +63 -0
  321. package/src/llm/anthropic/utils/message_inputs.ts +57 -51
  322. package/src/llm/anthropic/utils/message_outputs.ts +12 -39
  323. package/src/llm/anthropic/utils/stream_events.ts +17 -12
  324. package/src/llm/bedrock/index.ts +7 -5
  325. package/src/llm/bedrock/utils/message_inputs.ts +28 -35
  326. package/src/llm/google/utils/common.ts +88 -36
  327. package/src/llm/google/utils/signatures.ts +52 -36
  328. package/src/llm/init.ts +35 -3
  329. package/src/llm/invoke.ts +160 -16
  330. package/src/llm/openai/index.ts +18 -5
  331. package/src/llm/openai/typedContent.ts +110 -0
  332. package/src/llm/prepareProviderRequest.ts +154 -4
  333. package/src/llm/providerTextBatch.ts +158 -0
  334. package/src/llm/providerTextBoundary.ts +119 -13
  335. package/src/messages/anthropicServerTools.ts +24 -0
  336. package/src/messages/core.ts +12 -11
  337. package/src/messages/toolResultTypes.ts +80 -88
  338. package/src/protection/providerText.ts +222 -46
  339. package/src/protection/providerTextAdmission.ts +6 -0
  340. package/src/protection/toolResult.ts +272 -0
  341. package/src/run.ts +37 -5
  342. package/src/runtime/client.ts +6 -0
  343. package/src/stream.ts +23 -2
  344. package/src/tools/ToolNode.ts +112 -17
  345. package/src/tools/handlers.ts +110 -5
  346. package/src/tools/search/citations.ts +375 -0
  347. package/src/tools/search/content.ts +282 -62
  348. package/src/tools/search/firecrawl.ts +13 -16
  349. package/src/tools/search/google.ts +122 -0
  350. package/src/tools/search/openai.ts +118 -0
  351. package/src/tools/search/types.ts +21 -0
  352. package/src/tools/subagent/SubagentExecutor.ts +6 -0
  353. package/src/types/graph.ts +3 -0
  354. package/src/types/run.ts +3 -0
  355. package/src/types/stream.ts +9 -0
  356. package/src/types/tools.ts +3 -0
  357. package/src/utils/tokens.ts +37 -2
package/src/llm/invoke.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { concat } from '@langchain/core/utils/stream';
2
2
  import { AIMessageChunk } from '@langchain/core/messages';
3
3
  import { BaseCallbackHandler } from '@langchain/core/callbacks/base';
4
- import { getCallbackManagerForConfig } from '@langchain/core/runnables';
4
+ import { ensureConfig, getCallbackManagerForConfig } from '@langchain/core/runnables';
5
5
  import type { Serialized } from '@langchain/core/load/serializable';
6
6
  import type { RunnableConfig } from '@langchain/core/runnables';
7
7
  import type { ChatGeneration } from '@langchain/core/outputs';
@@ -25,8 +25,10 @@ import {
25
25
  STREAM_LIMIT_ATTEMPT_KEY,
26
26
  } from '@/llm/streamLimits';
27
27
  import {
28
+ BATCHED_PROVIDER_EVENT_OWNER,
28
29
  validateProviderTextProtection,
29
30
  ProviderTextProtectionError,
31
+ ProviderTextAttempt,
30
32
  createProviderTextRestartCancellation,
31
33
  isProviderTextRestartCancellation,
32
34
  } from '@/protection/providerText';
@@ -208,6 +210,74 @@ function withModelStartHandler({
208
210
  };
209
211
  }
210
212
 
213
+ /** Publication errors must not start a second attempt after text was committed. */
214
+ async function dispatchBatchEvent(
215
+ attempt: ProviderTextAttempt,
216
+ dispatch: () => void | Promise<void>
217
+ ): Promise<void> {
218
+ attempt.check();
219
+ try {
220
+ const pending = dispatch();
221
+ if (pending != null) await attempt.wait(pending, false);
222
+ attempt.check();
223
+ } catch (error) {
224
+ attempt.check();
225
+ if (error instanceof StreamLimitExceededError || error instanceof PreparedSubagentError) {
226
+ throw error;
227
+ }
228
+ const failure = new ProviderTextProtectionError('unavailable');
229
+ attempt.stop(failure);
230
+ throw failure;
231
+ }
232
+ }
233
+
234
+ function withBatchCloseDeadline(
235
+ stream: AsyncIterable<AIMessageChunk>,
236
+ attempt: ProviderTextAttempt
237
+ ): AsyncIterable<AIMessageChunk> {
238
+ return {
239
+ [Symbol.asyncIterator](): AsyncIterator<AIMessageChunk> {
240
+ const iterator = stream[Symbol.asyncIterator]();
241
+ return {
242
+ next: iterator.next.bind(iterator),
243
+ async return(): Promise<IteratorResult<AIMessageChunk>> {
244
+ // LangChain's iterator close can wait on an in-flight native callback.
245
+ const closing = iterator.return?.();
246
+ if (closing != null) await attempt.wait(closing, false).catch(() => {});
247
+ return { done: true, value: undefined };
248
+ },
249
+ };
250
+ },
251
+ };
252
+ }
253
+
254
+ function captureBatchStart(context: InvokeContext | undefined): {
255
+ callback: BaseCallbackHandler;
256
+ dispatch: (attempt: ProviderTextAttempt) => Promise<void>;
257
+ } | undefined {
258
+ const handler = context?.handlerRegistry?.getHandler(GraphEvents.CHAT_MODEL_START);
259
+ if (handler == null) return;
260
+ let start: { messages: BaseMessage[][]; metadata?: Record<string, unknown> } | undefined;
261
+ const callback = BaseCallbackHandler.fromMethods({
262
+ handleChatModelStart(_llm, messages, _runId, _parentId, _extra, _tags, metadata): void {
263
+ start = { messages, metadata };
264
+ },
265
+ });
266
+ callback.name = 'batched-provider-start';
267
+ callback.awaitHandlers = true;
268
+ return {
269
+ callback,
270
+ dispatch: (attempt): Promise<void> => {
271
+ const event = start;
272
+ start = undefined;
273
+ if (event == null) throw new ProviderTextProtectionError('incompatible');
274
+ return dispatchBatchEvent(attempt, () => handler.handle(
275
+ GraphEvents.CHAT_MODEL_START, { input: { messages: event.messages } }, event.metadata, context
276
+ ));
277
+ },
278
+ };
279
+ }
280
+
211
281
  function getManualToolStreamNormalizationProvider(
212
282
  provider: t.ProviderName
213
283
  ): t.ProviderName {
@@ -665,6 +735,9 @@ export async function attemptInvoke(
665
735
  const policy =
666
736
  params.providerTextProtection ?? params.context?.providerTextProtection;
667
737
  if (policy != null) validateProviderTextProtection(policy);
738
+ if (policy?.batching != null && params.context?.preemption != null) {
739
+ throw new ProviderTextProtectionError('unsupported');
740
+ }
668
741
  const provider = resolveAttemptProvider(params);
669
742
  const providerStampedConfig: RunnableConfig = {
670
743
  ...config,
@@ -676,12 +749,36 @@ export async function attemptInvoke(
676
749
  },
677
750
  };
678
751
  const preparedRequest = resolveAttemptRequest(params, providerStampedConfig);
752
+ const batchConfig = policy?.batching == null ? undefined : ensureConfig(providerStampedConfig);
753
+ const batchStart = batchConfig == null ? undefined : captureBatchStart(params.context);
754
+ let batchAttempt: ProviderTextAttempt | undefined;
755
+ let unbindBatchSignal: (() => void) | undefined;
756
+ let batchEntered = false;
757
+ let finishBatch: (() => void) | undefined;
758
+ const batchInvocation = batchConfig == null ? undefined : {
759
+ getAttempt(signal?: AbortSignal): ProviderTextAttempt {
760
+ const attempt = batchAttempt;
761
+ if (attempt == null || batchEntered) throw new ProviderTextProtectionError('incompatible');
762
+ attempt.signal.throwIfAborted();
763
+ attempt.check();
764
+ unbindBatchSignal = attempt.followSignal(signal);
765
+ batchEntered = true;
766
+ finishBatch = attempt.holdFinish();
767
+ return attempt;
768
+ },
769
+ dispatchStart: batchStart?.dispatch,
770
+ };
679
771
  const request =
680
772
  policy == null
681
773
  ? preparedRequest
682
774
  : {
683
775
  ...preparedRequest,
684
- model: withProviderTextBoundary(preparedRequest.model, policy, provider),
776
+ model: withProviderTextBoundary(
777
+ preparedRequest.model,
778
+ policy,
779
+ provider,
780
+ batchInvocation
781
+ ),
685
782
  };
686
783
  const configuredModel =
687
784
  providerStampedConfig.metadata?.[Constants.INVOKED_MODEL];
@@ -689,9 +786,10 @@ export async function attemptInvoke(
689
786
  request.modelId ??
690
787
  (typeof configuredModel === 'string' ? configuredModel : undefined);
691
788
  const stampedConfig: RunnableConfig = {
692
- ...providerStampedConfig,
789
+ ...(batchConfig ?? providerStampedConfig),
790
+ ...(batchStart != null && { callbacks: appendCallbacks(batchConfig?.callbacks, [batchStart.callback]) }),
693
791
  metadata: {
694
- ...providerStampedConfig.metadata,
792
+ ...(batchConfig ?? providerStampedConfig).metadata,
695
793
  ...(modelId == null
696
794
  ? {}
697
795
  : {
@@ -708,6 +806,7 @@ export async function attemptInvoke(
708
806
  * rebuild that already attributes the serving provider.
709
807
  */
710
808
  [STREAM_LIMIT_ATTEMPT_KEY]: ++streamLimitAttemptSeq,
809
+ ...(batchInvocation != null && { [BATCHED_PROVIDER_EVENT_OWNER]: true }),
711
810
  },
712
811
  };
713
812
  const rawLeaseTarget = params.context ?? params.streamLimitState;
@@ -732,6 +831,12 @@ export async function attemptInvoke(
732
831
  const preparedAttempt = resolveGenerationKey(stampedConfig.metadata);
733
832
  prepared?.begin(preparedAttempt, stampedConfig);
734
833
  try {
834
+ if (batchConfig != null && policy != null) {
835
+ batchAttempt = new ProviderTextAttempt(policy, batchConfig.signal);
836
+ const attempt = batchAttempt;
837
+ finishBatch = (): void => attempt.finish();
838
+ stampedConfig.signal = attempt.signal;
839
+ }
735
840
  const result = await attemptInvokeBody(
736
841
  {
737
842
  request,
@@ -740,9 +845,11 @@ export async function attemptInvoke(
740
845
  onModelComplete: params.onModelComplete,
741
846
  preemptAgentId: params.preemptAgentId,
742
847
  providerTextProtection: policy,
848
+ ...(batchInvocation != null && { batchAttempt: (): ProviderTextAttempt | undefined => batchAttempt }),
743
849
  },
744
850
  stampedConfig
745
851
  );
852
+ batchAttempt?.check();
746
853
  const calls = collectAttemptToolCalls(result.messages);
747
854
  prepared?.finish(preparedAttempt, calls);
748
855
  return result;
@@ -757,9 +864,30 @@ export async function attemptInvoke(
757
864
  prepared?.finish(preparedAttempt, undefined, cancelled);
758
865
  throw cancelled;
759
866
  }
760
- prepared?.finish(preparedAttempt, undefined, error);
761
- throw error;
867
+ let failure = error;
868
+ if (
869
+ !(error instanceof StreamLimitExceededError) &&
870
+ !(error instanceof PreparedSubagentError)
871
+ ) {
872
+ // An awaited native error callback can replace the provider's error.
873
+ if (batchAttempt != null) {
874
+ try {
875
+ batchAttempt.check();
876
+ if (batchAttempt.hasPublishedText && !(error instanceof ProviderTextProtectionError)) {
877
+ const unavailable = new ProviderTextProtectionError('unavailable');
878
+ batchAttempt.stop(unavailable);
879
+ failure = unavailable;
880
+ }
881
+ } catch (abort) {
882
+ failure = abort;
883
+ }
884
+ }
885
+ }
886
+ prepared?.finish(preparedAttempt, undefined, failure);
887
+ throw failure;
762
888
  } finally {
889
+ unbindBatchSignal?.();
890
+ finishBatch?.();
763
891
  const chunks = params.context?.eagerEventToolCallChunks;
764
892
  if (prepared != null && chunks != null) {
765
893
  const prefix = `prepared:${preparedAttempt}\u0000`;
@@ -783,6 +911,7 @@ async function attemptInvokeBody(
783
911
  onModelComplete,
784
912
  preemptAgentId,
785
913
  providerTextProtection,
914
+ batchAttempt,
786
915
  }: Pick<
787
916
  AttemptInvokeCommonParams,
788
917
  | 'context'
@@ -792,6 +921,7 @@ async function attemptInvokeBody(
792
921
  | 'providerTextProtection'
793
922
  > & {
794
923
  request: PreparedProviderRequest;
924
+ batchAttempt?: () => ProviderTextAttempt | undefined;
795
925
  },
796
926
  config: RunnableConfig
797
927
  ): Promise<Partial<t.BaseGraphState>> {
@@ -1095,7 +1225,11 @@ async function attemptInvokeBody(
1095
1225
  * close below is conditional.
1096
1226
  */
1097
1227
  if (!evaluatePreemptRestart()) {
1098
- const stream = await model.stream(messagesForProvider, streamConfig);
1228
+ const nativeStream = await model.stream(messagesForProvider, streamConfig);
1229
+ const attempt = batchAttempt?.();
1230
+ const stream = attempt == null
1231
+ ? nativeStream
1232
+ : withBatchCloseDeadline(nativeStream, attempt);
1099
1233
  if (onChunk) {
1100
1234
  const attemptMetadata = config.metadata as
1101
1235
  | Record<string, unknown>
@@ -1115,18 +1249,23 @@ async function attemptInvokeBody(
1115
1249
  chunk,
1116
1250
  });
1117
1251
  }
1118
- await onChunk(chunk, attemptMetadata);
1252
+ const attempt = batchAttempt?.();
1253
+ if (attempt == null) await onChunk(chunk, attemptMetadata);
1254
+ else await dispatchBatchEvent(attempt, () => onChunk(chunk, attemptMetadata));
1119
1255
  finalChunk = appendStreamChunk({
1120
1256
  current: finalChunk,
1121
1257
  next: chunk,
1122
1258
  provider,
1123
1259
  });
1124
1260
  }
1125
- } else if (registeredStreamHandler == null) {
1261
+ } else if (registeredStreamHandler == null || batchAttempt != null) {
1126
1262
  const metadata = config.metadata as
1127
1263
  | Record<string, unknown>
1128
1264
  | undefined;
1129
- const streamHandler = new ChatModelStreamHandler();
1265
+ const streamHandler = registeredStreamHandler ?? new ChatModelStreamHandler();
1266
+ const observer = batchAttempt != null && registeredStreamHandler == null
1267
+ ? context?.handlerRegistry?.getHandler(GraphEvents.CHAT_MODEL_STREAM)
1268
+ : undefined;
1130
1269
  for await (const rawChunk of stream) {
1131
1270
  throwIfBreakerTripped();
1132
1271
  const chunk = snapshotValidatedModelChunk(rawChunk);
@@ -1150,12 +1289,16 @@ async function attemptInvokeBody(
1150
1289
  if (handlingChunk != null) {
1151
1290
  dispatchingChunk = true;
1152
1291
  try {
1153
- await streamHandler.handle(
1154
- GraphEvents.CHAT_MODEL_STREAM,
1155
- { chunk: handlingChunk },
1156
- metadata,
1157
- context
1158
- );
1292
+ const attempt = batchAttempt?.();
1293
+ if (attempt == null) {
1294
+ await streamHandler.handle(GraphEvents.CHAT_MODEL_STREAM, { chunk: handlingChunk }, metadata, context);
1295
+ } else {
1296
+ const data = { chunk: handlingChunk };
1297
+ await dispatchBatchEvent(attempt, () => streamHandler.handle(GraphEvents.CHAT_MODEL_STREAM, data, metadata, context));
1298
+ if (observer != null) {
1299
+ await dispatchBatchEvent(attempt, () => observer.handle(GraphEvents.CHAT_MODEL_STREAM, data, metadata, context));
1300
+ }
1301
+ }
1159
1302
  } finally {
1160
1303
  dispatchingChunk = false;
1161
1304
  }
@@ -1456,6 +1599,7 @@ async function attemptInvokeBody(
1456
1599
  );
1457
1600
  }
1458
1601
 
1602
+ batchAttempt?.()?.check();
1459
1603
  if (finalChunk == null) {
1460
1604
  throw new Error(EMPTY_PROVIDER_RESPONSE_MESSAGE);
1461
1605
  }
@@ -62,6 +62,10 @@ import {
62
62
  hasToolCallChunks,
63
63
  getReasoningKwargsText,
64
64
  } from '@/llm/stream/chunkAdapters';
65
+ import {
66
+ splitTypedDeltaContent,
67
+ flattenTypedMessageContent,
68
+ } from './typedContent';
65
69
  import { registerProviderTextChunkConstructor } from '@/llm/providerTextChunk';
66
70
  import { createResponsesToolArgumentConverter } from './responseToolArguments';
67
71
  import { isReasoningModel, _convertMessagesToOpenAIParams } from './utils';
@@ -1398,7 +1402,14 @@ async function* filterOpenAIChatCompletionStream(
1398
1402
  if (chunk == null) {
1399
1403
  continue;
1400
1404
  }
1401
- yield chunk;
1405
+ const pieces = splitTypedDeltaContent(chunk);
1406
+ if (pieces == null) {
1407
+ yield chunk;
1408
+ continue;
1409
+ }
1410
+ for (const piece of pieces) {
1411
+ yield piece;
1412
+ }
1402
1413
  }
1403
1414
  }
1404
1415
 
@@ -1408,10 +1419,12 @@ async function completionWithFilteredOpenAIStream(
1408
1419
  completionWithRetry: OpenAIChatCompletionRetry
1409
1420
  ): Promise<OpenAIChatCompletionResult> {
1410
1421
  if (request.stream !== true) {
1411
- return (await completionWithRetry(
1412
- request,
1413
- requestOptions
1414
- )) as OpenAIChatCompletion;
1422
+ return flattenTypedMessageContent(
1423
+ (await completionWithRetry(
1424
+ request,
1425
+ requestOptions
1426
+ )) as OpenAIChatCompletion
1427
+ );
1415
1428
  }
1416
1429
 
1417
1430
  const stream = await completionWithRetry(request, requestOptions);
@@ -0,0 +1,110 @@
1
+ import type { OpenAIClient } from '@langchain/openai';
2
+
3
+ type Chunk = OpenAIClient.Chat.Completions.ChatCompletionChunk;
4
+ type Completion = OpenAIClient.Chat.Completions.ChatCompletion;
5
+ type Choice = Chunk['choices'][number];
6
+ type Delta = Choice['delta'] & { reasoning_content?: string };
7
+ /** Usage-only chunks carry no choice, Azure content-filter chunks no delta. */
8
+ type StreamChoice = Omit<Choice, 'delta'> & { delta?: Delta };
9
+ type Message = Completion['choices'][number]['message'] & {
10
+ reasoning_content?: string;
11
+ };
12
+ type TextPart = { type: 'text'; text?: string };
13
+ /**
14
+ * Mistral reasoning models send Chat Completions `content` as a list of typed
15
+ * parts instead of a string: `thinking` parts, each holding a list of `text`
16
+ * parts, carry the reasoning, and `text` parts carry the answer. Other part
17
+ * types are read as neither.
18
+ */
19
+ type ContentPart = TextPart | { type: 'thinking'; thinking?: TextPart[] };
20
+ type TypedText = { text: string; reasoning: string };
21
+
22
+ function readTypedContent(content: ContentPart[]): TypedText {
23
+ let text = '';
24
+ let reasoning = '';
25
+ for (const part of content) {
26
+ if (part.type === 'text' && typeof part.text === 'string') {
27
+ text += part.text;
28
+ continue;
29
+ }
30
+ if (part.type !== 'thinking' || !Array.isArray(part.thinking)) {
31
+ continue;
32
+ }
33
+ for (const thought of part.thinking) {
34
+ if (typeof thought.text === 'string') {
35
+ reasoning += thought.text;
36
+ }
37
+ }
38
+ }
39
+ return { text, reasoning };
40
+ }
41
+
42
+ /**
43
+ * Rewrites a streamed chunk whose `delta.content` is a typed list as string
44
+ * content with the reasoning in `reasoning_content`, or returns `undefined`
45
+ * when the content is not a list. The chunk that closes the reasoning also
46
+ * opens the answer or a tool call, so it splits in two: the reasoning first,
47
+ * then the rest of the delta.
48
+ */
49
+ export function splitTypedDeltaContent(chunk: Chunk): Chunk[] | undefined {
50
+ const choice = chunk.choices[0] as StreamChoice | undefined;
51
+ const delta = choice?.delta;
52
+ const content: unknown = delta?.content;
53
+ if (choice == null || delta == null || !Array.isArray(content)) {
54
+ return undefined;
55
+ }
56
+ const { text, reasoning } = readTypedContent(content);
57
+ const rest: Delta = { ...delta, content: text };
58
+ const others = chunk.choices.slice(1);
59
+ const continues = text !== '' || (rest.tool_calls?.length ?? 0) > 0;
60
+ if (reasoning === '' || !continues) {
61
+ if (reasoning !== '') {
62
+ rest.reasoning_content = reasoning;
63
+ }
64
+ return [{ ...chunk, choices: [{ ...choice, delta: rest }, ...others] }];
65
+ }
66
+ const thought: Delta = { content: '', reasoning_content: reasoning };
67
+ if (rest.role != null) {
68
+ thought.role = rest.role;
69
+ }
70
+ return [
71
+ {
72
+ ...chunk,
73
+ choices: [
74
+ { ...choice, delta: thought, finish_reason: null, logprobs: null },
75
+ ],
76
+ },
77
+ { ...chunk, choices: [{ ...choice, delta: rest }, ...others] },
78
+ ];
79
+ }
80
+
81
+ function flattenMessage(message: Message | undefined): Message | undefined {
82
+ const content: unknown = message?.content;
83
+ if (message == null || !Array.isArray(content)) {
84
+ return undefined;
85
+ }
86
+ const { text, reasoning } = readTypedContent(content);
87
+ const flat: Message = { ...message, content: text };
88
+ if (reasoning !== '') {
89
+ flat.reasoning_content = reasoning;
90
+ }
91
+ return flat;
92
+ }
93
+
94
+ /** Rewrites the typed `message.content` lists of a non-streamed completion. */
95
+ export function flattenTypedMessageContent(completion: Completion): Completion {
96
+ if (!Array.isArray(completion.choices)) {
97
+ return completion;
98
+ }
99
+ let choices: Completion['choices'] | undefined;
100
+ for (let i = 0; i < completion.choices.length; i++) {
101
+ const choice = completion.choices[i];
102
+ const message = flattenMessage(choice.message);
103
+ if (message == null) {
104
+ continue;
105
+ }
106
+ choices ??= [...completion.choices];
107
+ choices[i] = { ...choice, message };
108
+ }
109
+ return choices == null ? completion : { ...completion, choices };
110
+ }
@@ -331,6 +331,134 @@ function canProjectBedrockDocument(
331
331
  return false;
332
332
  }
333
333
 
334
+ /** How one provider request takes audio and video. */
335
+ type TimedMediaInput = 'gemini' | 'openai' | 'none';
336
+
337
+ /**
338
+ * Gemini and Vertex read audio and video as `media` parts. OpenAI-compatible
339
+ * Chat Completions endpoints read `input_audio` and `video_url` parts, where
340
+ * the endpoint and model accept them, which only the host can tell. Claude,
341
+ * Bedrock's Converse converter and the Responses API read none of them.
342
+ */
343
+ function getTimedMediaInput(
344
+ provider: t.ProviderName,
345
+ projectionMode: ProviderMessageProjectionMode
346
+ ): TimedMediaInput {
347
+ if (isGoogleLike(provider)) {
348
+ return 'gemini';
349
+ }
350
+ const family = getProviderFamily(provider);
351
+ if (
352
+ projectionMode === 'openai-responses' ||
353
+ provider === Providers.ANTHROPIC ||
354
+ family === 'anthropic' ||
355
+ provider === Providers.BEDROCK ||
356
+ family === 'bedrock'
357
+ ) {
358
+ return 'none';
359
+ }
360
+ return 'openai';
361
+ }
362
+
363
+ /** The audio or video MIME type a block names, normalized; `undefined` for anything else. */
364
+ function getTimedMediaMimeType(mimeType: unknown): string | undefined {
365
+ if (typeof mimeType !== 'string') {
366
+ return undefined;
367
+ }
368
+ const normalized = mimeType.split(';', 1)[0].trim().toLowerCase();
369
+ return normalized.startsWith('audio/') || normalized.startsWith('video/')
370
+ ? normalized
371
+ : undefined;
372
+ }
373
+
374
+ /** Gemini's MIME type for each `input_audio` format it plays; raw PCM names no sample rate. */
375
+ const GEMINI_AUDIO_MIME_TYPES: Readonly<Partial<Record<string, string>>> = {
376
+ aac: 'audio/aac',
377
+ aiff: 'audio/aiff',
378
+ flac: 'audio/flac',
379
+ m4a: 'audio/mp4',
380
+ mp3: 'audio/mp3',
381
+ ogg: 'audio/ogg',
382
+ wav: 'audio/wav',
383
+ webm: 'audio/webm',
384
+ };
385
+
386
+ /** The MIME type and payload of a base64 `data:` URL. */
387
+ function parseDataUrl(
388
+ url: string
389
+ ): { mimeType: string; data: string } | undefined {
390
+ const comma = url.indexOf(',');
391
+ if (!url.startsWith('data:') || comma < 0) {
392
+ return undefined;
393
+ }
394
+ const [mimeType, ...parameters] = url.slice(5, comma).split(';');
395
+ if (parameters.at(-1)?.trim().toLowerCase() !== 'base64') {
396
+ return undefined;
397
+ }
398
+ const data = url.slice(comma + 1);
399
+ return data === '' ? undefined : { mimeType, data };
400
+ }
401
+
402
+ /** An OpenAI-compatible audio or video part as Gemini inline media, when it carries its bytes. */
403
+ function toGeminiMedia(
404
+ block: ProviderContentBlock
405
+ ): ProviderContentBlock | null {
406
+ if (block.type === 'input_audio') {
407
+ const audio = (
408
+ block as { input_audio?: { data?: unknown; format?: unknown } }
409
+ ).input_audio;
410
+ const mimeType =
411
+ typeof audio?.format === 'string'
412
+ ? GEMINI_AUDIO_MIME_TYPES[audio.format.toLowerCase()]
413
+ : undefined;
414
+ return mimeType != null &&
415
+ typeof audio?.data === 'string' &&
416
+ audio.data !== ''
417
+ ? { type: 'media', mimeType, data: audio.data }
418
+ : null;
419
+ }
420
+ const video = (block as { video_url?: string | { url?: unknown } | null })
421
+ .video_url;
422
+ const url = typeof video === 'string' ? video : video?.url;
423
+ const parsed = typeof url === 'string' ? parseDataUrl(url) : undefined;
424
+ const mimeType = getTimedMediaMimeType(parsed?.mimeType);
425
+ return parsed != null && mimeType != null
426
+ ? { type: 'media', mimeType, data: parsed.data }
427
+ : null;
428
+ }
429
+
430
+ /**
431
+ * The part a request that takes `input` gets for an audio or video part: the
432
+ * part itself when its provider reads it, Gemini inline media rewritten from
433
+ * an OpenAI-compatible part, or `null` to leave it out. `undefined` for any
434
+ * other block.
435
+ */
436
+ function projectTimedMedia(
437
+ block: ProviderContentBlock,
438
+ input: TimedMediaInput
439
+ ): ProviderContentBlock | null | undefined {
440
+ if (block.type === 'media') {
441
+ const media = block as { mimeType?: unknown; mime_type?: unknown };
442
+ if (getTimedMediaMimeType(media.mimeType ?? media.mime_type) == null) {
443
+ return undefined;
444
+ }
445
+ return input === 'gemini' ? block : null;
446
+ }
447
+ if (block.type === 'input_audio' || block.type === 'video_url') {
448
+ if (input === 'openai') {
449
+ return block;
450
+ }
451
+ return input === 'gemini' ? toGeminiMedia(block) : null;
452
+ }
453
+ if (
454
+ isStandardFileBlock(block) &&
455
+ getTimedMediaMimeType(block.mime_type) != null
456
+ ) {
457
+ return input === 'gemini' ? block : null;
458
+ }
459
+ return undefined;
460
+ }
461
+
334
462
  function isBlankTextBlock(block: ProviderContentBlock): boolean {
335
463
  return (
336
464
  block.type === 'text' &&
@@ -369,24 +497,26 @@ function anchorCacheControl(
369
497
 
370
498
  /**
371
499
  * Resolves referenced attachments and reprojects persisted provider-native
372
- * ones, in one pass and without changing history.
500
+ * ones, in one pass and without changing history. Audio and video reach each
501
+ * provider in the part it reads, or not at all (`projectTimedMedia`); tool
502
+ * results keep their own tool-output projection.
373
503
  */
374
504
  function projectAttachmentsForProvider(
375
505
  messages: BaseMessage[],
376
506
  provider: t.ProviderName,
507
+ projectionMode: ProviderMessageProjectionMode,
377
508
  resolve?: ResolveReference
378
509
  ): BaseMessage[] {
379
510
  const native =
380
511
  provider === Providers.BEDROCK || getProviderFamily(provider) === 'bedrock';
381
- if (native && resolve == null) {
382
- return messages;
383
- }
512
+ const timedMediaInput = getTimedMediaInput(provider, projectionMode);
384
513
  let projected: BaseMessage[] | undefined;
385
514
  for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
386
515
  const message = messages[messageIndex];
387
516
  if (!Array.isArray(message.content)) {
388
517
  continue;
389
518
  }
519
+ const projectsTimedMedia = message.getType() !== 'tool';
390
520
  const sourceContent = message.content as ProviderContentBlock[];
391
521
  let content: ProviderContentBlock[] | undefined;
392
522
  let displaced: ReturnType<typeof getCacheControl>;
@@ -406,6 +536,25 @@ function projectAttachmentsForProvider(
406
536
  }
407
537
  continue;
408
538
  }
539
+ const media = projectsTimedMedia
540
+ ? projectTimedMedia(block, timedMediaInput)
541
+ : undefined;
542
+ if (media === block) {
543
+ content?.push(block);
544
+ continue;
545
+ }
546
+ if (media !== undefined) {
547
+ content ??= copyUsableContentPrefix(sourceContent, blockIndex);
548
+ const marker = getCacheControl(block);
549
+ if (media === null) {
550
+ displaced = marker ?? displaced;
551
+ } else {
552
+ content.push(
553
+ marker == null ? media : withCacheControl(media, marker)
554
+ );
555
+ }
556
+ continue;
557
+ }
409
558
  if (native) {
410
559
  if (content != null && !isBlankTextBlock(block)) {
411
560
  content.push(block);
@@ -475,6 +624,7 @@ function projectMessagesForProviderMode(
475
624
  toolHistory
476
625
  ),
477
626
  provider,
627
+ projectionMode,
478
628
  resolve
479
629
  );
480
630
  if (nativeOpenAIResponses) {