@librechat/agents 4.2.9 → 4.2.11

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 (340) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +32 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/harness/fileBindings.cjs +93 -0
  4. package/dist/cjs/harness/fileBindings.cjs.map +1 -0
  5. package/dist/cjs/harness/fileService.cjs +141 -0
  6. package/dist/cjs/harness/fileService.cjs.map +1 -0
  7. package/dist/cjs/harness/fileStream.cjs +76 -0
  8. package/dist/cjs/harness/fileStream.cjs.map +1 -0
  9. package/dist/cjs/harness/files.cjs +106 -0
  10. package/dist/cjs/harness/files.cjs.map +1 -0
  11. package/dist/cjs/harness/index.cjs +3 -0
  12. package/dist/cjs/harness/index.cjs.map +1 -1
  13. package/dist/cjs/llm/google/utils/signatures.cjs +5 -3
  14. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  15. package/dist/cjs/main.cjs +13 -0
  16. package/dist/cjs/runtime/admission.cjs +135 -0
  17. package/dist/cjs/runtime/admission.cjs.map +1 -0
  18. package/dist/cjs/runtime/checkpoint.cjs +40 -0
  19. package/dist/cjs/runtime/checkpoint.cjs.map +1 -0
  20. package/dist/cjs/runtime/client.cjs +435 -0
  21. package/dist/cjs/runtime/client.cjs.map +1 -0
  22. package/dist/cjs/runtime/files.cjs +301 -0
  23. package/dist/cjs/runtime/files.cjs.map +1 -0
  24. package/dist/cjs/runtime/hostTools.cjs +165 -0
  25. package/dist/cjs/runtime/hostTools.cjs.map +1 -0
  26. package/dist/cjs/runtime/index.cjs +11 -0
  27. package/dist/cjs/runtime/model.cjs +303 -0
  28. package/dist/cjs/runtime/model.cjs.map +1 -0
  29. package/dist/cjs/runtime/peer.cjs +209 -0
  30. package/dist/cjs/runtime/peer.cjs.map +1 -0
  31. package/dist/cjs/runtime/policy.cjs +77 -0
  32. package/dist/cjs/runtime/policy.cjs.map +1 -0
  33. package/dist/cjs/runtime/recovery/client.cjs +172 -0
  34. package/dist/cjs/runtime/recovery/client.cjs.map +1 -0
  35. package/dist/cjs/runtime/recovery/log.cjs +47 -0
  36. package/dist/cjs/runtime/recovery/log.cjs.map +1 -0
  37. package/dist/cjs/runtime/recovery/redis.cjs +239 -0
  38. package/dist/cjs/runtime/recovery/redis.cjs.map +1 -0
  39. package/dist/cjs/runtime/recovery/server.cjs +190 -0
  40. package/dist/cjs/runtime/recovery/server.cjs.map +1 -0
  41. package/dist/cjs/runtime/recovery/socket.cjs +298 -0
  42. package/dist/cjs/runtime/recovery/socket.cjs.map +1 -0
  43. package/dist/cjs/runtime/resume.cjs +115 -0
  44. package/dist/cjs/runtime/resume.cjs.map +1 -0
  45. package/dist/cjs/runtime/sealed.cjs +107 -0
  46. package/dist/cjs/runtime/sealed.cjs.map +1 -0
  47. package/dist/cjs/runtime/server.cjs +415 -0
  48. package/dist/cjs/runtime/server.cjs.map +1 -0
  49. package/dist/cjs/runtime/snapshot.cjs +61 -0
  50. package/dist/cjs/runtime/snapshot.cjs.map +1 -0
  51. package/dist/cjs/runtime/types.cjs +20 -0
  52. package/dist/cjs/runtime/types.cjs.map +1 -0
  53. package/dist/cjs/runtime/wire.cjs +84 -0
  54. package/dist/cjs/runtime/wire.cjs.map +1 -0
  55. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +3 -2
  56. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  57. package/dist/cjs/tools/ProgrammaticCallerPolicy.cjs +24 -1
  58. package/dist/cjs/tools/ProgrammaticCallerPolicy.cjs.map +1 -1
  59. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +3 -2
  60. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  61. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +2 -1
  62. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  63. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +15 -3
  64. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  65. package/dist/cjs/tools/subagent/childGraphConfig.cjs +13 -1
  66. package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
  67. package/dist/cjs/tools/subagent/hostArgs.cjs +2 -0
  68. package/dist/cjs/tools/subagent/hostArgs.cjs.map +1 -1
  69. package/dist/esm/agents/AgentContext.mjs +32 -2
  70. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  71. package/dist/esm/harness/fileBindings.mjs +93 -0
  72. package/dist/esm/harness/fileBindings.mjs.map +1 -0
  73. package/dist/esm/harness/fileService.mjs +140 -0
  74. package/dist/esm/harness/fileService.mjs.map +1 -0
  75. package/dist/esm/harness/fileStream.mjs +76 -0
  76. package/dist/esm/harness/fileStream.mjs.map +1 -0
  77. package/dist/esm/harness/files.mjs +97 -0
  78. package/dist/esm/harness/files.mjs.map +1 -0
  79. package/dist/esm/harness/index.mjs +3 -0
  80. package/dist/esm/harness/index.mjs.map +1 -1
  81. package/dist/esm/llm/google/utils/signatures.mjs +5 -3
  82. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  83. package/dist/esm/main.mjs +5 -2
  84. package/dist/esm/runtime/admission.mjs +133 -0
  85. package/dist/esm/runtime/admission.mjs.map +1 -0
  86. package/dist/esm/runtime/checkpoint.mjs +39 -0
  87. package/dist/esm/runtime/checkpoint.mjs.map +1 -0
  88. package/dist/esm/runtime/client.mjs +432 -0
  89. package/dist/esm/runtime/client.mjs.map +1 -0
  90. package/dist/esm/runtime/files.mjs +299 -0
  91. package/dist/esm/runtime/files.mjs.map +1 -0
  92. package/dist/esm/runtime/hostTools.mjs +164 -0
  93. package/dist/esm/runtime/hostTools.mjs.map +1 -0
  94. package/dist/esm/runtime/index.mjs +5 -0
  95. package/dist/esm/runtime/model.mjs +301 -0
  96. package/dist/esm/runtime/model.mjs.map +1 -0
  97. package/dist/esm/runtime/peer.mjs +209 -0
  98. package/dist/esm/runtime/peer.mjs.map +1 -0
  99. package/dist/esm/runtime/policy.mjs +75 -0
  100. package/dist/esm/runtime/policy.mjs.map +1 -0
  101. package/dist/esm/runtime/recovery/client.mjs +172 -0
  102. package/dist/esm/runtime/recovery/client.mjs.map +1 -0
  103. package/dist/esm/runtime/recovery/log.mjs +46 -0
  104. package/dist/esm/runtime/recovery/log.mjs.map +1 -0
  105. package/dist/esm/runtime/recovery/redis.mjs +239 -0
  106. package/dist/esm/runtime/recovery/redis.mjs.map +1 -0
  107. package/dist/esm/runtime/recovery/server.mjs +189 -0
  108. package/dist/esm/runtime/recovery/server.mjs.map +1 -0
  109. package/dist/esm/runtime/recovery/socket.mjs +297 -0
  110. package/dist/esm/runtime/recovery/socket.mjs.map +1 -0
  111. package/dist/esm/runtime/resume.mjs +111 -0
  112. package/dist/esm/runtime/resume.mjs.map +1 -0
  113. package/dist/esm/runtime/sealed.mjs +106 -0
  114. package/dist/esm/runtime/sealed.mjs.map +1 -0
  115. package/dist/esm/runtime/server.mjs +413 -0
  116. package/dist/esm/runtime/server.mjs.map +1 -0
  117. package/dist/esm/runtime/snapshot.mjs +60 -0
  118. package/dist/esm/runtime/snapshot.mjs.map +1 -0
  119. package/dist/esm/runtime/types.mjs +19 -0
  120. package/dist/esm/runtime/types.mjs.map +1 -0
  121. package/dist/esm/runtime/wire.mjs +80 -0
  122. package/dist/esm/runtime/wire.mjs.map +1 -0
  123. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +3 -2
  124. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  125. package/dist/esm/tools/ProgrammaticCallerPolicy.mjs +24 -1
  126. package/dist/esm/tools/ProgrammaticCallerPolicy.mjs.map +1 -1
  127. package/dist/esm/tools/ProgrammaticToolCalling.mjs +3 -2
  128. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  129. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +2 -1
  130. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  131. package/dist/esm/tools/subagent/SubagentExecutor.mjs +15 -3
  132. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  133. package/dist/esm/tools/subagent/childGraphConfig.mjs +13 -1
  134. package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
  135. package/dist/esm/tools/subagent/hostArgs.mjs +2 -1
  136. package/dist/esm/tools/subagent/hostArgs.mjs.map +1 -1
  137. package/dist/types/agents/AgentContext.d.ts +4 -4
  138. package/dist/types/agents/projection.d.ts +1 -1
  139. package/dist/types/events.d.ts +2 -2
  140. package/dist/types/graphs/Graph.d.ts +13 -13
  141. package/dist/types/graphs/MultiAgentGraph.d.ts +2 -2
  142. package/dist/types/graphs/acceptedModelResponse.d.ts +1 -1
  143. package/dist/types/graphs/createGraph.d.ts +4 -4
  144. package/dist/types/graphs/graphFactory.d.ts +1 -1
  145. package/dist/types/graphs/handoff.d.ts +1 -1
  146. package/dist/types/harness/fileBindings.d.ts +13 -0
  147. package/dist/types/harness/fileService.d.ts +37 -0
  148. package/dist/types/harness/fileStream.d.ts +7 -0
  149. package/dist/types/harness/files.d.ts +108 -0
  150. package/dist/types/harness/index.d.ts +8 -2
  151. package/dist/types/harness/model.d.ts +3 -3
  152. package/dist/types/harness/providerText.d.ts +2 -2
  153. package/dist/types/hitl/approvalReview.d.ts +1 -1
  154. package/dist/types/hitl/askUserQuestion.d.ts +1 -1
  155. package/dist/types/hitl/askUserQuestions.d.ts +1 -1
  156. package/dist/types/hitl/askUserQuestionsInterrupt.d.ts +1 -1
  157. package/dist/types/hooks/types.d.ts +2 -2
  158. package/dist/types/instrumentation.d.ts +1 -1
  159. package/dist/types/langfuse.d.ts +3 -3
  160. package/dist/types/langfuseConfig.d.ts +2 -2
  161. package/dist/types/langfuseRuntimeContext.d.ts +1 -1
  162. package/dist/types/langfuseRuntimeScope.d.ts +2 -2
  163. package/dist/types/langfuseSpanRegistry.d.ts +1 -1
  164. package/dist/types/langfuseToolOutputTracing.d.ts +3 -3
  165. package/dist/types/llm/anthropic/index.d.ts +1 -1
  166. package/dist/types/llm/bedrock/index.d.ts +1 -1
  167. package/dist/types/llm/bedrock/toolCache.d.ts +2 -2
  168. package/dist/types/llm/contextOverflowRecovery.d.ts +2 -2
  169. package/dist/types/llm/contextPressureMeter.d.ts +2 -2
  170. package/dist/types/llm/google/index.d.ts +1 -1
  171. package/dist/types/llm/init.d.ts +1 -1
  172. package/dist/types/llm/invoke.d.ts +9 -9
  173. package/dist/types/llm/mistral/index.d.ts +1 -1
  174. package/dist/types/llm/openai/index.d.ts +2 -2
  175. package/dist/types/llm/openrouter/index.d.ts +2 -2
  176. package/dist/types/llm/openrouter/toolCache.d.ts +2 -2
  177. package/dist/types/llm/prepareProviderRequest.d.ts +3 -3
  178. package/dist/types/llm/promptCacheTools.d.ts +1 -1
  179. package/dist/types/llm/providerRegistry.d.ts +1 -1
  180. package/dist/types/llm/providerTextBoundary.d.ts +2 -2
  181. package/dist/types/llm/providerTextControls.d.ts +1 -1
  182. package/dist/types/llm/providers.d.ts +2 -2
  183. package/dist/types/llm/request.d.ts +1 -1
  184. package/dist/types/llm/stream/chunkAdapters.d.ts +1 -1
  185. package/dist/types/llm/streamLimits.d.ts +1 -1
  186. package/dist/types/llm/truncation.d.ts +1 -1
  187. package/dist/types/llm/vertexai/index.d.ts +1 -1
  188. package/dist/types/messages/alternation.d.ts +1 -1
  189. package/dist/types/messages/anthropicToolCache.d.ts +2 -2
  190. package/dist/types/messages/assistantPhase.d.ts +3 -3
  191. package/dist/types/messages/budget.d.ts +1 -1
  192. package/dist/types/messages/cache.d.ts +1 -1
  193. package/dist/types/messages/contextPruning.d.ts +2 -2
  194. package/dist/types/messages/core.d.ts +1 -1
  195. package/dist/types/messages/fading.d.ts +1 -1
  196. package/dist/types/messages/format.d.ts +2 -2
  197. package/dist/types/messages/ids.d.ts +2 -2
  198. package/dist/types/messages/injected.d.ts +1 -1
  199. package/dist/types/messages/langchain.d.ts +1 -1
  200. package/dist/types/messages/prune.d.ts +4 -4
  201. package/dist/types/messages/recency.d.ts +1 -1
  202. package/dist/types/messages/toolResultTypes.d.ts +1 -1
  203. package/dist/types/openai/arguments.d.ts +1 -1
  204. package/dist/types/openai/index.d.ts +1 -1
  205. package/dist/types/openai/toolProjection.d.ts +1 -1
  206. package/dist/types/prompts/activityLabel.d.ts +2 -2
  207. package/dist/types/prompts/reasoningLabel.d.ts +1 -1
  208. package/dist/types/rerank/search.d.ts +1 -1
  209. package/dist/types/responses/index.d.ts +1 -1
  210. package/dist/types/run.d.ts +3 -3
  211. package/dist/types/runtime/admission.d.ts +30 -0
  212. package/dist/types/runtime/checkpoint.d.ts +14 -0
  213. package/dist/types/runtime/client.d.ts +12 -0
  214. package/dist/types/runtime/files.d.ts +75 -0
  215. package/dist/types/runtime/hostTools.d.ts +22 -0
  216. package/dist/types/runtime/identity.d.ts +2 -0
  217. package/dist/types/runtime/index.d.ts +12 -0
  218. package/dist/types/runtime/model.d.ts +42 -0
  219. package/dist/types/runtime/peer.d.ts +55 -0
  220. package/dist/types/runtime/policy.d.ts +43 -0
  221. package/dist/types/runtime/recovery/client.d.ts +12 -0
  222. package/dist/types/runtime/recovery/journal.d.ts +62 -0
  223. package/dist/types/runtime/recovery/log.d.ts +9 -0
  224. package/dist/types/runtime/recovery/redis.d.ts +17 -0
  225. package/dist/types/runtime/recovery/server.d.ts +37 -0
  226. package/dist/types/runtime/recovery/socket.d.ts +72 -0
  227. package/dist/types/runtime/resume.d.ts +66 -0
  228. package/dist/types/runtime/sealed.d.ts +19 -0
  229. package/dist/types/runtime/server.d.ts +21 -0
  230. package/dist/types/runtime/snapshot.d.ts +12 -0
  231. package/dist/types/runtime/types.d.ts +125 -0
  232. package/dist/types/runtime/wire.d.ts +3 -0
  233. package/dist/types/session/handlers.d.ts +1 -1
  234. package/dist/types/session/types.d.ts +1 -1
  235. package/dist/types/stream.d.ts +3 -3
  236. package/dist/types/summarization/index.d.ts +1 -1
  237. package/dist/types/summarization/input.d.ts +1 -1
  238. package/dist/types/summarization/node.d.ts +6 -6
  239. package/dist/types/summarization/retry.d.ts +2 -2
  240. package/dist/types/summarization/semanticIndex.d.ts +2 -2
  241. package/dist/types/summarization/toolBudget.d.ts +1 -1
  242. package/dist/types/summarization/usage.d.ts +1 -1
  243. package/dist/types/tools/ArtifactDelivery.d.ts +1 -1
  244. package/dist/types/tools/ArtifactTruncation.d.ts +1 -1
  245. package/dist/types/tools/BashExecutor.d.ts +2 -2
  246. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +2 -2
  247. package/dist/types/tools/CallerCapabilities.d.ts +1 -1
  248. package/dist/types/tools/CodeExecutor.d.ts +4 -4
  249. package/dist/types/tools/CodeSessionFileSummary.d.ts +1 -1
  250. package/dist/types/tools/ProgrammaticCallerPolicy.d.ts +2 -1
  251. package/dist/types/tools/ProgrammaticToolCalling.d.ts +2 -2
  252. package/dist/types/tools/ReadFile.d.ts +1 -1
  253. package/dist/types/tools/SkillTool.d.ts +1 -1
  254. package/dist/types/tools/SubagentTool.d.ts +3 -3
  255. package/dist/types/tools/ToolNode.d.ts +5 -5
  256. package/dist/types/tools/ToolSearch.d.ts +2 -2
  257. package/dist/types/tools/cloudflare/CloudflareBridgeRuntime.d.ts +1 -1
  258. package/dist/types/tools/cloudflare/CloudflareProgrammaticToolCalling.d.ts +1 -1
  259. package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +2 -2
  260. package/dist/types/tools/cloudflare/CloudflareSandboxTools.d.ts +1 -1
  261. package/dist/types/tools/diagnostics.d.ts +1 -1
  262. package/dist/types/tools/eagerEventExecution.d.ts +1 -1
  263. package/dist/types/tools/handlers.d.ts +3 -3
  264. package/dist/types/tools/intentArg.d.ts +1 -1
  265. package/dist/types/tools/local/CompileCheckTool.d.ts +2 -2
  266. package/dist/types/tools/local/FileCheckpointer.d.ts +1 -1
  267. package/dist/types/tools/local/LocalCodingTools.d.ts +2 -2
  268. package/dist/types/tools/local/LocalExecutionEngine.d.ts +1 -1
  269. package/dist/types/tools/local/LocalExecutionTools.d.ts +1 -1
  270. package/dist/types/tools/local/LocalProgrammaticToolCalling.d.ts +1 -1
  271. package/dist/types/tools/local/bashAst.d.ts +1 -1
  272. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +1 -1
  273. package/dist/types/tools/local/syntaxCheck.d.ts +1 -1
  274. package/dist/types/tools/ptcTimeout.d.ts +1 -1
  275. package/dist/types/tools/runStepResume.d.ts +1 -1
  276. package/dist/types/tools/schema.d.ts +1 -1
  277. package/dist/types/tools/search/anthropic.d.ts +1 -1
  278. package/dist/types/tools/skillCatalog.d.ts +1 -1
  279. package/dist/types/tools/subagent/InMemorySubagentTaskStore.d.ts +1 -1
  280. package/dist/types/tools/subagent/SubagentExecutor.d.ts +5 -5
  281. package/dist/types/tools/subagent/SubagentReplay.d.ts +3 -3
  282. package/dist/types/tools/subagent/childGraphConfig.d.ts +2 -2
  283. package/dist/types/tools/subagent/diagnostics.d.ts +2 -2
  284. package/dist/types/tools/subagent/hostArgs.d.ts +8 -2
  285. package/dist/types/tools/subagent/index.d.ts +1 -1
  286. package/dist/types/tools/toolBatchReplay.d.ts +3 -3
  287. package/dist/types/types/activityLabel.d.ts +2 -2
  288. package/dist/types/types/graph.d.ts +16 -13
  289. package/dist/types/types/llm.d.ts +9 -9
  290. package/dist/types/types/reasoningLabel.d.ts +1 -1
  291. package/dist/types/types/run.d.ts +8 -8
  292. package/dist/types/types/stream.d.ts +5 -5
  293. package/dist/types/types/summarize.d.ts +2 -2
  294. package/dist/types/types/tools.d.ts +8 -8
  295. package/dist/types/utils/errors.d.ts +1 -1
  296. package/dist/types/utils/events.d.ts +3 -3
  297. package/dist/types/utils/handlers.d.ts +3 -3
  298. package/dist/types/utils/llm.d.ts +2 -2
  299. package/dist/types/utils/llmConfig.d.ts +1 -1
  300. package/dist/types/utils/title.d.ts +1 -1
  301. package/dist/types/utils/toolSessions.d.ts +1 -1
  302. package/package.json +22 -3
  303. package/src/agents/AgentContext.ts +68 -2
  304. package/src/harness/fileBindings.ts +156 -0
  305. package/src/harness/fileService.ts +217 -0
  306. package/src/harness/fileStream.ts +99 -0
  307. package/src/harness/files.ts +185 -0
  308. package/src/harness/index.ts +24 -0
  309. package/src/llm/google/utils/signatures.ts +10 -3
  310. package/src/runtime/admission.ts +224 -0
  311. package/src/runtime/checkpoint.ts +66 -0
  312. package/src/runtime/client.ts +674 -0
  313. package/src/runtime/files.ts +503 -0
  314. package/src/runtime/hostTools.ts +243 -0
  315. package/src/runtime/identity.ts +3 -0
  316. package/src/runtime/index.ts +33 -0
  317. package/src/runtime/model.ts +452 -0
  318. package/src/runtime/peer.ts +262 -0
  319. package/src/runtime/policy.ts +150 -0
  320. package/src/runtime/recovery/client.ts +232 -0
  321. package/src/runtime/recovery/journal.ts +88 -0
  322. package/src/runtime/recovery/log.ts +70 -0
  323. package/src/runtime/recovery/redis.ts +342 -0
  324. package/src/runtime/recovery/server.ts +280 -0
  325. package/src/runtime/recovery/socket.ts +422 -0
  326. package/src/runtime/resume.ts +268 -0
  327. package/src/runtime/sealed.ts +144 -0
  328. package/src/runtime/server.ts +653 -0
  329. package/src/runtime/snapshot.ts +87 -0
  330. package/src/runtime/types.ts +184 -0
  331. package/src/runtime/wire.ts +96 -0
  332. package/src/tools/BashProgrammaticToolCalling.ts +5 -2
  333. package/src/tools/ProgrammaticCallerPolicy.ts +42 -3
  334. package/src/tools/ProgrammaticToolCalling.ts +4 -1
  335. package/src/tools/local/LocalProgrammaticToolCalling.ts +4 -0
  336. package/src/tools/subagent/SubagentExecutor.ts +98 -32
  337. package/src/tools/subagent/childGraphConfig.ts +33 -1
  338. package/src/tools/subagent/hostArgs.ts +7 -0
  339. package/src/tools/subagent/index.ts +1 -0
  340. package/src/types/graph.ts +6 -3
@@ -0,0 +1,422 @@
1
+ import { z } from 'zod';
2
+ import { WebSocket } from 'ws';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { EventEmitter } from 'node:events';
5
+
6
+ /** Fixed protocol envelope budget; payload limits continue to apply to the inner SDK frame. */
7
+ export const RECOVERY_HEADER_BYTES = 512;
8
+ const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
9
+ const header = z.discriminatedUnion('kind', [
10
+ z.object({
11
+ version: z.literal(1),
12
+ kind: z.literal('data'),
13
+ connection: z.string().uuid(),
14
+ sequence: counter.positive(),
15
+ }),
16
+ z.object({
17
+ version: z.literal(1),
18
+ kind: z.literal('end'),
19
+ connection: z.string().uuid(),
20
+ sequence: counter.positive(),
21
+ }),
22
+ z.object({
23
+ version: z.literal(1),
24
+ kind: z.literal('failure'),
25
+ connection: z.string().uuid(),
26
+ sequence: counter,
27
+ }),
28
+ z.object({
29
+ version: z.literal(1),
30
+ kind: z.literal('ack'),
31
+ connection: z.string().uuid(),
32
+ sequence: counter,
33
+ }),
34
+ ]);
35
+ export interface RecoveryLog {
36
+ append(id: string, payload: string): Promise<number>;
37
+ appendBatch?(
38
+ id: string,
39
+ payloads: string[]
40
+ ): Promise<{ first: number; last: number }>;
41
+ maxBatchFrames?: number;
42
+ maxBatchBytes?: number;
43
+ read(after: number): Promise<Array<{ sequence: number; payload: string }>>;
44
+ acknowledge(sequence: number): Promise<void>;
45
+ head(): number;
46
+ }
47
+ /** Bounded request-local host log; host-process execution adoption is deliberately not implied. */
48
+ export function createMemoryRecoveryLog(maxBytes: number): RecoveryLog {
49
+ const frames: string[] = [];
50
+ let bytes = 0;
51
+ return {
52
+ append: async (_id, payload): Promise<number> => {
53
+ bytes += Buffer.byteLength(payload);
54
+ if (bytes > maxBytes)
55
+ throw new Error('SDK recovery log capacity exceeded');
56
+ frames.push(payload);
57
+ return frames.length;
58
+ },
59
+ read: async (after): Promise<{ sequence: number; payload: string }[]> => {
60
+ if (after > frames.length)
61
+ throw new Error('SDK recovery cursor is ahead');
62
+ return frames
63
+ .slice(after, after + 128)
64
+ .map((payload, i) => ({ sequence: after + i + 1, payload }));
65
+ },
66
+ acknowledge: async (sequence): Promise<void> => {
67
+ if (sequence > frames.length)
68
+ throw new Error('SDK recovery cursor is ahead');
69
+ },
70
+ head: () => frames.length,
71
+ };
72
+ }
73
+
74
+ /**
75
+ * A physical close detaches only the wire. Frames are committed before publication and duplicate
76
+ * sequence numbers never enter the existing SDK handlers twice. Logical close is an acknowledged,
77
+ * replayable control frame, so cancellation survives a transient wire failure.
78
+ */
79
+ export class RecoverySocket extends EventEmitter {
80
+ private wire?: WebSocket;
81
+ private connection?: string;
82
+ private tail = Promise.resolve();
83
+ private pendingFrames: Array<{
84
+ kind: 'data' | 'end';
85
+ payload: string;
86
+ encoded: string;
87
+ bytes: number;
88
+ }> = [];
89
+
90
+ private scheduled = false;
91
+ private acknowledgement?: Promise<void>;
92
+ private requestedAck = 0;
93
+ private received = 0;
94
+ private acknowledged = 0;
95
+ private queuedBytes = 0;
96
+ private closed = false;
97
+ private ending = false;
98
+ private generation = 0;
99
+ private replaying = false;
100
+ private failure?: Error;
101
+ private endSequence?: number;
102
+ private endResolve?: () => void;
103
+ private readonly ended = new Promise<void>((resolve) => {
104
+ this.endResolve = resolve;
105
+ });
106
+
107
+ constructor(
108
+ private readonly options: {
109
+ log: RecoveryLog;
110
+ maxFrameBytes: number;
111
+ maxBufferedBytes: number;
112
+ onDisconnect: () => void;
113
+ onFailure: (error: unknown) => void;
114
+ terminalFailure?: boolean;
115
+ }
116
+ ) {
117
+ super();
118
+ }
119
+
120
+ get readyState(): number {
121
+ return this.closed ? WebSocket.CLOSED : WebSocket.OPEN;
122
+ }
123
+
124
+ get bufferedAmount(): number {
125
+ return this.queuedBytes + (this.wire?.bufferedAmount ?? 0);
126
+ }
127
+
128
+ get cursor(): number {
129
+ return this.received;
130
+ }
131
+
132
+ get hasWire(): boolean {
133
+ return this.wire?.readyState === WebSocket.OPEN;
134
+ }
135
+
136
+ get isEnding(): boolean {
137
+ return this.ending;
138
+ }
139
+
140
+ private fail = (error: unknown): void => {
141
+ this.failure = new Error('SDK recovery transport failed');
142
+ try {
143
+ this.options.onFailure(error);
144
+ } catch {
145
+ /* Diagnostics cannot prevent cleanup. */
146
+ }
147
+ this.terminate();
148
+ };
149
+
150
+ private publish(
151
+ kind: 'data' | 'end' | 'ack' | 'failure',
152
+ sequence: number,
153
+ payload = ''
154
+ ): void {
155
+ if (
156
+ !this.hasWire ||
157
+ this.connection == null ||
158
+ this.connection.length === 0
159
+ )
160
+ return;
161
+ const data =
162
+ JSON.stringify({
163
+ version: 1,
164
+ kind,
165
+ connection: this.connection,
166
+ sequence,
167
+ }) +
168
+ '\n' +
169
+ payload;
170
+ if (
171
+ this.wire!.bufferedAmount + Buffer.byteLength(data) >
172
+ this.options.maxBufferedBytes
173
+ ) {
174
+ this.wire!.terminate();
175
+ return;
176
+ }
177
+ this.wire!.send(data);
178
+ }
179
+
180
+ private scheduleFlush(): void {
181
+ if (this.scheduled || this.closed || !this.pendingFrames.length) return;
182
+ this.scheduled = true;
183
+ this.tail = this.tail
184
+ .then(async () => {
185
+ const maxFrames = this.options.log.appendBatch
186
+ ? (this.options.log.maxBatchFrames ?? 1)
187
+ : 1;
188
+ const maxBytes =
189
+ this.options.log.maxBatchBytes ?? this.options.maxBufferedBytes;
190
+ let count = 0;
191
+ let bytes = 0;
192
+ for (const frame of this.pendingFrames) {
193
+ if (
194
+ count >= maxFrames ||
195
+ (count > 0 && bytes + frame.bytes > maxBytes)
196
+ )
197
+ break;
198
+ count++;
199
+ bytes += frame.bytes;
200
+ }
201
+ const batch = this.pendingFrames.splice(0, count);
202
+ if (!batch.length) return;
203
+ try {
204
+ const id = randomUUID();
205
+ const range = this.options.log.appendBatch
206
+ ? await this.options.log.appendBatch(
207
+ id,
208
+ batch.map((f) => f.encoded)
209
+ )
210
+ : { first: await this.options.log.append(id, batch[0].encoded) };
211
+ for (let index = 0; index < batch.length; index++) {
212
+ const frame = batch[index];
213
+ const sequence = range.first + index;
214
+ if (frame.kind === 'end') this.endSequence = sequence;
215
+ if (!this.replaying)
216
+ this.publish(frame.kind, sequence, frame.payload);
217
+ }
218
+ } finally {
219
+ this.queuedBytes -= bytes;
220
+ }
221
+ })
222
+ .catch(this.fail)
223
+ .finally(() => {
224
+ this.scheduled = false;
225
+ this.scheduleFlush();
226
+ });
227
+ }
228
+
229
+ private queue(kind: 'data' | 'end', payload: string): void {
230
+ const encoded = JSON.stringify({ kind, payload });
231
+ const bytes = Buffer.byteLength(encoded);
232
+ if (
233
+ Buffer.byteLength(payload) > this.options.maxFrameBytes ||
234
+ this.bufferedAmount + bytes > this.options.maxBufferedBytes
235
+ )
236
+ throw new Error('SDK recovery frame capacity exceeded');
237
+ this.queuedBytes += bytes;
238
+ this.pendingFrames.push({ kind, payload, encoded, bytes });
239
+ this.scheduleFlush();
240
+ }
241
+
242
+ private persistAcknowledgement(): void {
243
+ if (
244
+ this.acknowledgement ||
245
+ this.closed ||
246
+ this.requestedAck <= this.acknowledged
247
+ )
248
+ return;
249
+ this.acknowledgement = Promise.resolve()
250
+ .then(async () => {
251
+ const sequence = this.requestedAck;
252
+ await this.options.log.acknowledge(sequence);
253
+ this.acknowledged = sequence;
254
+ if (this.endSequence != null && sequence >= this.endSequence)
255
+ this.terminate();
256
+ })
257
+ .catch((error) => {
258
+ if (!this.closed) this.fail(error);
259
+ })
260
+ .finally(() => {
261
+ this.acknowledgement = undefined;
262
+ this.persistAcknowledgement();
263
+ });
264
+ }
265
+
266
+ send(data: string): void {
267
+ if (this.closed || this.ending)
268
+ throw new Error('SDK recovery connection closed');
269
+ this.queue('data', data);
270
+ }
271
+
272
+ close(_code?: number): void {
273
+ if (this.closed || this.ending) return;
274
+ this.ending = true;
275
+ try {
276
+ this.queue('end', '');
277
+ } catch (error) {
278
+ this.fail(error);
279
+ }
280
+ }
281
+
282
+ /** Abort is reserved for expiry, shutdown, or a definitively failed journal. */
283
+ terminate(): void {
284
+ if (this.closed) return;
285
+ this.closed = true;
286
+ for (const frame of this.pendingFrames) this.queuedBytes -= frame.bytes;
287
+ this.pendingFrames.length = 0;
288
+ this.generation++;
289
+ this.wire?.terminate();
290
+ this.wire = undefined;
291
+ this.endResolve?.();
292
+ this.emit('close');
293
+ }
294
+
295
+ async flush(): Promise<void> {
296
+ do {
297
+ await this.tail;
298
+ } while (!this.closed && (this.scheduled || this.pendingFrames.length));
299
+ if (this.failure) throw this.failure;
300
+ }
301
+
302
+ waitForClose(): Promise<void> {
303
+ return this.ended;
304
+ }
305
+
306
+ attach(
307
+ wire: WebSocket,
308
+ connection: string,
309
+ after: number,
310
+ ready?: string
311
+ ): void {
312
+ if (this.closed) {
313
+ wire.close(1000);
314
+ return;
315
+ }
316
+ const old = this.wire;
317
+ this.wire = wire;
318
+ this.connection = connection;
319
+ this.replaying = true;
320
+ const generation = ++this.generation;
321
+ old?.close(1000);
322
+ const detached = (): void => {
323
+ if (generation !== this.generation || this.closed || this.wire !== wire)
324
+ return;
325
+ this.wire = undefined;
326
+ this.options.onDisconnect();
327
+ };
328
+ wire.once('close', detached);
329
+ wire.once('error', detached);
330
+ wire.on('message', (raw) => {
331
+ if (generation !== this.generation || this.closed) return;
332
+ // No async receive queue: durable ACK bookkeeping must not retain raw frames or
333
+ // delay cancellation. The SDK peer bounds outstanding event/RPC handler work.
334
+ try {
335
+ const text = raw.toString();
336
+ if (Buffer.byteLength(text) > this.options.maxBufferedBytes)
337
+ throw new Error('SDK recovery receive capacity exceeded');
338
+ const split = text.indexOf('\n');
339
+ if (
340
+ split < 0 ||
341
+ Buffer.byteLength(text.slice(0, split)) > RECOVERY_HEADER_BYTES
342
+ )
343
+ throw new Error('Invalid SDK recovery envelope');
344
+ const frame = header.parse(JSON.parse(text.slice(0, split)));
345
+ const payload = text.slice(split + 1);
346
+ if (
347
+ frame.connection !== this.connection ||
348
+ Buffer.byteLength(payload) > this.options.maxFrameBytes
349
+ )
350
+ throw new Error('Invalid SDK recovery frame');
351
+ if (frame.kind === 'failure') {
352
+ if (frame.sequence !== this.received)
353
+ throw new Error('SDK recovery terminal cursor mismatch');
354
+ this.emit('message', Buffer.from('{"type":"error"}'));
355
+ return;
356
+ }
357
+ if (frame.kind === 'ack') {
358
+ if (frame.sequence > this.options.log.head())
359
+ throw new Error('SDK recovery cursor is ahead');
360
+ this.requestedAck = Math.max(this.requestedAck, frame.sequence);
361
+ this.persistAcknowledgement();
362
+ return;
363
+ }
364
+ if (frame.sequence <= this.received) {
365
+ this.publish('ack', this.received);
366
+ return;
367
+ }
368
+ if (frame.sequence !== this.received + 1)
369
+ throw new Error('SDK recovery sequence gap');
370
+ this.received = frame.sequence;
371
+ if (frame.kind === 'end') {
372
+ this.publish('ack', this.received);
373
+ // Allow the acknowledgement to leave before closing the physical connection.
374
+ this.closed = true;
375
+ this.endResolve?.();
376
+ this.emit('close');
377
+ wire.close(1000);
378
+ } else {
379
+ this.emit('message', Buffer.from(payload));
380
+ this.publish('ack', this.received);
381
+ }
382
+ } catch (error) {
383
+ this.fail(error);
384
+ }
385
+ });
386
+ if (ready != null && ready.length > 0) wire.send(ready);
387
+ // Serialize replay with publication so new live frames cannot overtake its prefix.
388
+ this.tail = this.tail
389
+ .then(async () => {
390
+ if (after > this.options.log.head())
391
+ throw new Error('SDK recovery cursor is ahead');
392
+ let cursor = after;
393
+ const current = (): boolean =>
394
+ generation === this.generation && this.hasWire;
395
+ while (current()) {
396
+ const frames = await this.options.log.read(cursor);
397
+ if (
398
+ generation !== this.generation ||
399
+ !this.hasWire ||
400
+ frames.length === 0
401
+ )
402
+ break;
403
+ for (const frame of frames) {
404
+ const entry = z
405
+ .object({ kind: z.enum(['data', 'end']), payload: z.string() })
406
+ .parse(JSON.parse(frame.payload));
407
+ this.publish(entry.kind, frame.sequence, entry.payload);
408
+ cursor = frame.sequence;
409
+ }
410
+ }
411
+ if (
412
+ generation === this.generation &&
413
+ this.options.terminalFailure === true
414
+ )
415
+ this.publish('failure', cursor);
416
+ })
417
+ .finally(() => {
418
+ if (generation === this.generation) this.replaying = false;
419
+ })
420
+ .catch(this.fail);
421
+ }
422
+ }
@@ -0,0 +1,268 @@
1
+ import type { EventHandler, MessageContentComplex, RunStep } from '@/index';
2
+ import type { RemoteSdkSnapshot } from './types';
3
+ import { ContentTypes, GraphEvents, convertMessagesToContent } from '@/index';
4
+ import { AIMessage, isAIMessage, isToolMessage } from '@/langchain/messages';
5
+
6
+ type ResumableRunStep = {
7
+ id: string;
8
+ index: number;
9
+ stepDetails: {
10
+ type: string;
11
+ tool_calls?: readonly { id?: string }[];
12
+ };
13
+ };
14
+
15
+ export function normalizeResumeRunStepIndices<T extends ResumableRunStep>(
16
+ runSteps: readonly T[],
17
+ seedContent: readonly (
18
+ | { type?: string; tool_call?: { id?: string } }
19
+ | undefined
20
+ )[] = []
21
+ ): T[] {
22
+ const toolCallIndices = new Map<string, number>();
23
+ seedContent.forEach((part, index) => {
24
+ const toolCallId = part?.tool_call?.id;
25
+ if (part?.type === 'tool_call' && typeof toolCallId === 'string') {
26
+ toolCallIndices.set(toolCallId, index);
27
+ }
28
+ });
29
+
30
+ return runSteps.map((runStep) => {
31
+ if (runStep.stepDetails.type !== 'tool_calls') {
32
+ return runStep;
33
+ }
34
+ const contentIndex = runStep.stepDetails.tool_calls
35
+ ?.map((toolCall) =>
36
+ toolCall.id != null && toolCall.id.length > 0
37
+ ? toolCallIndices.get(toolCall.id)
38
+ : undefined
39
+ )
40
+ .find((index) => index != null);
41
+ return contentIndex != null && contentIndex !== runStep.index
42
+ ? { ...runStep, index: contentIndex }
43
+ : runStep;
44
+ });
45
+ }
46
+
47
+ /**
48
+ * Restore the streamed run-step sidecars that a fresh SDK Run cannot recover
49
+ * from the LangGraph checkpoint by itself.
50
+ *
51
+ * Human-review resume can happen in a later request or process. The checkpoint
52
+ * restarts directly inside ToolNode, so it does not replay ON_RUN_STEP before
53
+ * dispatching ON_RUN_STEP_COMPLETED. Seeding both maps lets the ToolNode emit
54
+ * the original step id and lets the content aggregator resolve that id back to
55
+ * the already-rendered tool card.
56
+ */
57
+ export function hydrateResumeRunSteps(
58
+ runSteps: readonly RunStep[],
59
+ stepMap: Map<string, RunStep | undefined> | undefined,
60
+ graph: { toolCallStepIds?: Map<string, string> } | null | undefined,
61
+ seedContent: readonly (
62
+ | { type?: string; tool_call?: { id?: string } }
63
+ | undefined
64
+ )[] = []
65
+ ): void {
66
+ for (const runStep of normalizeResumeRunStepIndices(runSteps, seedContent)) {
67
+ if (runStep.id.length === 0) {
68
+ continue;
69
+ }
70
+ stepMap?.set(runStep.id, runStep);
71
+ const stepDetails: ResumableRunStep['stepDetails'] = runStep.stepDetails;
72
+ if (stepDetails.type !== 'tool_calls') {
73
+ continue;
74
+ }
75
+ for (const toolCall of stepDetails.tool_calls ?? []) {
76
+ if (toolCall.id != null && toolCall.id.length > 0) {
77
+ graph?.toolCallStepIds?.set(toolCall.id, runStep.id);
78
+ }
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Wrap a resume run's event handlers so every content index the rebuilt graph
85
+ * emits is shifted past the pre-pause content.
86
+ *
87
+ * WHY: a resumed run rebuilds the graph from the checkpoint, and the fresh
88
+ * graph assigns content indices from its own empty `contentData` — starting at
89
+ * 0. The host, meanwhile, seeds the (also fresh) content aggregator with the
90
+ * pre-pause parts, which occupy exactly those low indices. Without an offset
91
+ * the resumed model turn collides with the seed: when the types match at an
92
+ * index the new text silently MERGES into a pre-pause part, and when they
93
+ * don't (e.g. a reasoning/`think` part at index 0 with Anthropic models) every
94
+ * delta is dropped with `Content type mismatch` — the entire post-resume
95
+ * output vanishes from both the live stream and the saved message.
96
+ *
97
+ * The index enters the pipeline at exactly one point: `ON_RUN_STEP`'s payload
98
+ * (the `RunStep`, whose `index` every subsequent delta resolves through the
99
+ * aggregator's `stepMap`). `ON_AGENT_UPDATE` carries its own inline index and
100
+ * is offset likewise. All other handlers pass through untouched — same object
101
+ * references, so stateful handler instances keep working.
102
+ */
103
+ export function createContentIndexOffsetHandlers(
104
+ handlers: Record<string, EventHandler> | undefined,
105
+ seedContent: Array<{
106
+ type?: string;
107
+ tool_call?: { id?: string; output?: unknown };
108
+ }> = []
109
+ ): Record<string, EventHandler> | undefined {
110
+ const offset = seedContent.length;
111
+ if (handlers == null || !(offset > 0)) {
112
+ return handlers;
113
+ }
114
+
115
+ /**
116
+ * Resumed tool steps for calls the PAUSED turn already rendered must land
117
+ * back on their seeded slot — not a fresh offset slot — or the original
118
+ * part stays unresolved while a duplicate completed one appears after the
119
+ * seed (and its output never attaches). Map unresolved seeded tool_calls by
120
+ * id so the resume pass's re-execution (approval flows re-run the approved
121
+ * tool; ask re-runs its body) rebinds to the right index.
122
+ */
123
+ const seededToolCallIndex = new Map<string, number>();
124
+ seedContent.forEach((part, index) => {
125
+ const toolCall = part.tool_call;
126
+ /**
127
+ * EVERY seeded id maps — including parts already carrying an output. Tool
128
+ * call ids are minted per call by the provider, so a resumed step bearing
129
+ * a seeded id can only be the interrupted batch re-executing (the resume
130
+ * controller pre-stamps the ask part's answer onto the seed, which must
131
+ * not exile its re-run step to a duplicate offset slot).
132
+ */
133
+ if (part.type === 'tool_call' && typeof toolCall?.id === 'string') {
134
+ seededToolCallIndex.set(toolCall.id, index);
135
+ }
136
+ });
137
+
138
+ const wrapped: Record<string, EventHandler> = { ...handlers };
139
+
140
+ const runStepHandler = (handlers as Partial<typeof handlers>)[
141
+ GraphEvents.ON_RUN_STEP
142
+ ];
143
+ if (runStepHandler) {
144
+ wrapped[GraphEvents.ON_RUN_STEP] = {
145
+ handle: (event, data, metadata, graph): void | Promise<void> => {
146
+ const runStep = data as
147
+ | {
148
+ index?: number;
149
+ stepDetails?: {
150
+ type?: string;
151
+ tool_calls?: Array<{ id?: string }>;
152
+ };
153
+ }
154
+ | undefined;
155
+ if (runStep == null || typeof runStep.index !== 'number') {
156
+ return runStepHandler.handle(event, data, metadata, graph);
157
+ }
158
+ const seededIndex =
159
+ runStep.stepDetails?.type === 'tool_calls'
160
+ ? runStep.stepDetails.tool_calls
161
+ ?.map((call) =>
162
+ call.id != null && call.id.length > 0
163
+ ? seededToolCallIndex.get(call.id)
164
+ : undefined
165
+ )
166
+ .find((index) => index != null)
167
+ : undefined;
168
+ const shifted = {
169
+ ...runStep,
170
+ index: seededIndex ?? runStep.index + offset,
171
+ };
172
+ return runStepHandler.handle(
173
+ event,
174
+ shifted as typeof data,
175
+ metadata,
176
+ graph
177
+ );
178
+ },
179
+ };
180
+ }
181
+
182
+ const agentUpdateHandler = (handlers as Partial<typeof handlers>)[
183
+ GraphEvents.ON_AGENT_UPDATE
184
+ ];
185
+ if (agentUpdateHandler) {
186
+ wrapped[GraphEvents.ON_AGENT_UPDATE] = {
187
+ handle: (event, data, metadata, graph): void | Promise<void> => {
188
+ const update = data as
189
+ | { agent_update?: { index?: number } }
190
+ | undefined;
191
+ const shifted =
192
+ update?.agent_update != null &&
193
+ typeof update.agent_update.index === 'number'
194
+ ? {
195
+ ...update,
196
+ agent_update: {
197
+ ...update.agent_update,
198
+ index: update.agent_update.index + offset,
199
+ },
200
+ }
201
+ : data;
202
+ return agentUpdateHandler.handle(
203
+ event,
204
+ shifted as typeof data,
205
+ metadata,
206
+ graph
207
+ );
208
+ },
209
+ };
210
+ }
211
+
212
+ return wrapped;
213
+ }
214
+
215
+ /** Merge a worker continuation with the host’s already rendered prefix. */
216
+ export function reconcileRemoteResumeContent(
217
+ seededProjection: readonly (MessageContentComplex | undefined)[],
218
+ snapshot: RemoteSdkSnapshot
219
+ ): MessageContentComplex[] {
220
+ const content = seededProjection.filter((part) => part != null);
221
+ const toolSlots = new Map<string, number>();
222
+ for (const [index, part] of content.entries()) {
223
+ if (part.type !== ContentTypes.TOOL_CALL) continue;
224
+ const id = part.tool_call?.id;
225
+ if (id != null && id !== '') toolSlots.set(id, index);
226
+ }
227
+ if (toolSlots.size === 0 || snapshot.messages == null)
228
+ return content.concat(snapshot.content ?? []);
229
+
230
+ let replayed = false;
231
+ const messages: NonNullable<RemoteSdkSnapshot['messages']> = [];
232
+ for (const message of snapshot.messages) {
233
+ if (isAIMessage(message) && message.tool_calls != null) {
234
+ const calls = message.tool_calls.filter(
235
+ (call) => call.id == null || !toolSlots.has(call.id)
236
+ );
237
+ if (calls.length !== message.tool_calls.length) {
238
+ replayed = true;
239
+ // Retain declarations for calls in the replayed batch without a seeded card.
240
+ if (calls.length > 0)
241
+ messages.push(new AIMessage({ content: '', tool_calls: calls }));
242
+ continue;
243
+ }
244
+ }
245
+ if (!isToolMessage(message)) {
246
+ messages.push(message);
247
+ continue;
248
+ }
249
+ const index = toolSlots.get(message.tool_call_id);
250
+ const part = index === undefined ? undefined : content[index];
251
+ if (
252
+ index === undefined ||
253
+ part?.type !== ContentTypes.TOOL_CALL ||
254
+ part.tool_call == null
255
+ ) {
256
+ messages.push(message);
257
+ continue;
258
+ }
259
+ replayed = true;
260
+ content[index] = {
261
+ ...part,
262
+ tool_call: { ...part.tool_call, output: message.content },
263
+ };
264
+ }
265
+ return content.concat(
266
+ replayed ? convertMessagesToContent(messages) : (snapshot.content ?? [])
267
+ );
268
+ }