@illuma-ai/agents 1.5.0 → 1.5.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 (404) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +2 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/common/enum.cjs +12 -12
  4. package/dist/cjs/common/enum.cjs.map +1 -1
  5. package/dist/cjs/graphs/Graph.cjs +5 -5
  6. package/dist/cjs/graphs/Graph.cjs.map +1 -1
  7. package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
  8. package/dist/cjs/graphs/MultiAgentGraph.cjs.map +1 -1
  9. package/dist/cjs/graphs/phases/memoryFlushPhase.cjs +1 -1
  10. package/dist/cjs/graphs/phases/memoryFlushPhase.cjs.map +1 -1
  11. package/dist/cjs/hooks/HookRegistry.cjs +1 -1
  12. package/dist/cjs/hooks/HookRegistry.cjs.map +1 -1
  13. package/dist/cjs/hooks/matchers.cjs +2 -2
  14. package/dist/cjs/hooks/matchers.cjs.map +1 -1
  15. package/dist/cjs/hooks/types.cjs +1 -1
  16. package/dist/cjs/hooks/types.cjs.map +1 -1
  17. package/dist/cjs/llm/bedrock/cacheSupport.cjs +1 -1
  18. package/dist/cjs/llm/bedrock/cacheSupport.cjs.map +1 -1
  19. package/dist/cjs/llm/bedrock/index.cjs +2 -2
  20. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  21. package/dist/cjs/llm/openai/index.cjs +1 -1
  22. package/dist/cjs/llm/openai/index.cjs.map +1 -1
  23. package/dist/cjs/llm/openai/utils/index.cjs +2 -2
  24. package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
  25. package/dist/cjs/memory/citations.cjs +4 -4
  26. package/dist/cjs/memory/citations.cjs.map +1 -1
  27. package/dist/cjs/memory/constants.cjs +17 -17
  28. package/dist/cjs/memory/constants.cjs.map +1 -1
  29. package/dist/cjs/memory/mmr.cjs +1 -1
  30. package/dist/cjs/memory/mmr.cjs.map +1 -1
  31. package/dist/cjs/memory/paths.cjs +1 -1
  32. package/dist/cjs/memory/paths.cjs.map +1 -1
  33. package/dist/cjs/memory/recallTracking.cjs +3 -3
  34. package/dist/cjs/memory/recallTracking.cjs.map +1 -1
  35. package/dist/cjs/memory/temporalDecay.cjs +2 -2
  36. package/dist/cjs/memory/temporalDecay.cjs.map +1 -1
  37. package/dist/cjs/messages/format.cjs +3 -3
  38. package/dist/cjs/messages/format.cjs.map +1 -1
  39. package/dist/cjs/tools/CodeExecutor.cjs +4 -3
  40. package/dist/cjs/tools/CodeExecutor.cjs.map +1 -1
  41. package/dist/cjs/tools/ToolNode.cjs +5 -5
  42. package/dist/cjs/tools/ToolNode.cjs.map +1 -1
  43. package/dist/cjs/tools/memory/memoryAppendTool.cjs +1 -1
  44. package/dist/cjs/tools/memory/memoryAppendTool.cjs.map +1 -1
  45. package/dist/cjs/tools/memory/memoryGetTool.cjs +2 -2
  46. package/dist/cjs/tools/memory/memoryGetTool.cjs.map +1 -1
  47. package/dist/cjs/tools/memory/memorySearchTool.cjs +3 -3
  48. package/dist/cjs/tools/memory/memorySearchTool.cjs.map +1 -1
  49. package/dist/cjs/tools/memory/shared.cjs +1 -1
  50. package/dist/cjs/tools/memory/shared.cjs.map +1 -1
  51. package/dist/cjs/types/agent-cache.cjs +6 -5
  52. package/dist/cjs/types/agent-cache.cjs.map +1 -1
  53. package/dist/cjs/types/graph.cjs.map +1 -1
  54. package/dist/esm/agents/AgentContext.mjs +2 -2
  55. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  56. package/dist/esm/common/enum.mjs +12 -12
  57. package/dist/esm/common/enum.mjs.map +1 -1
  58. package/dist/esm/graphs/Graph.mjs +5 -5
  59. package/dist/esm/graphs/Graph.mjs.map +1 -1
  60. package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
  61. package/dist/esm/graphs/MultiAgentGraph.mjs.map +1 -1
  62. package/dist/esm/graphs/phases/memoryFlushPhase.mjs +1 -1
  63. package/dist/esm/graphs/phases/memoryFlushPhase.mjs.map +1 -1
  64. package/dist/esm/hooks/HookRegistry.mjs +1 -1
  65. package/dist/esm/hooks/HookRegistry.mjs.map +1 -1
  66. package/dist/esm/hooks/matchers.mjs +2 -2
  67. package/dist/esm/hooks/matchers.mjs.map +1 -1
  68. package/dist/esm/hooks/types.mjs +1 -1
  69. package/dist/esm/hooks/types.mjs.map +1 -1
  70. package/dist/esm/llm/bedrock/cacheSupport.mjs +1 -1
  71. package/dist/esm/llm/bedrock/cacheSupport.mjs.map +1 -1
  72. package/dist/esm/llm/bedrock/index.mjs +2 -2
  73. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  74. package/dist/esm/llm/openai/index.mjs +1 -1
  75. package/dist/esm/llm/openai/index.mjs.map +1 -1
  76. package/dist/esm/llm/openai/utils/index.mjs +2 -2
  77. package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
  78. package/dist/esm/memory/citations.mjs +4 -4
  79. package/dist/esm/memory/citations.mjs.map +1 -1
  80. package/dist/esm/memory/constants.mjs +17 -17
  81. package/dist/esm/memory/constants.mjs.map +1 -1
  82. package/dist/esm/memory/mmr.mjs +1 -1
  83. package/dist/esm/memory/mmr.mjs.map +1 -1
  84. package/dist/esm/memory/paths.mjs +1 -1
  85. package/dist/esm/memory/paths.mjs.map +1 -1
  86. package/dist/esm/memory/recallTracking.mjs +3 -3
  87. package/dist/esm/memory/recallTracking.mjs.map +1 -1
  88. package/dist/esm/memory/temporalDecay.mjs +2 -2
  89. package/dist/esm/memory/temporalDecay.mjs.map +1 -1
  90. package/dist/esm/messages/format.mjs +3 -3
  91. package/dist/esm/messages/format.mjs.map +1 -1
  92. package/dist/esm/tools/CodeExecutor.mjs +4 -3
  93. package/dist/esm/tools/CodeExecutor.mjs.map +1 -1
  94. package/dist/esm/tools/ToolNode.mjs +5 -5
  95. package/dist/esm/tools/ToolNode.mjs.map +1 -1
  96. package/dist/esm/tools/memory/memoryAppendTool.mjs +1 -1
  97. package/dist/esm/tools/memory/memoryAppendTool.mjs.map +1 -1
  98. package/dist/esm/tools/memory/memoryGetTool.mjs +2 -2
  99. package/dist/esm/tools/memory/memoryGetTool.mjs.map +1 -1
  100. package/dist/esm/tools/memory/memorySearchTool.mjs +3 -3
  101. package/dist/esm/tools/memory/memorySearchTool.mjs.map +1 -1
  102. package/dist/esm/tools/memory/shared.mjs +1 -1
  103. package/dist/esm/tools/memory/shared.mjs.map +1 -1
  104. package/dist/esm/types/agent-cache.mjs +6 -5
  105. package/dist/esm/types/agent-cache.mjs.map +1 -1
  106. package/dist/esm/types/graph.mjs.map +1 -1
  107. package/dist/types/agents/AgentContext.d.ts +1 -1
  108. package/dist/types/common/enum.d.ts +12 -12
  109. package/dist/types/graphs/Graph.d.ts +2 -2
  110. package/dist/types/graphs/phases/memoryFlushPhase.d.ts +2 -2
  111. package/dist/types/hooks/HookRegistry.d.ts +1 -1
  112. package/dist/types/hooks/matchers.d.ts +2 -2
  113. package/dist/types/hooks/types.d.ts +1 -1
  114. package/dist/types/llm/bedrock/cacheSupport.d.ts +1 -1
  115. package/dist/types/llm/bedrock/index.d.ts +2 -2
  116. package/dist/types/llm/openai/index.d.ts +1 -1
  117. package/dist/types/memory/citations.d.ts +4 -4
  118. package/dist/types/memory/constants.d.ts +17 -17
  119. package/dist/types/memory/mmr.d.ts +3 -3
  120. package/dist/types/memory/paths.d.ts +1 -1
  121. package/dist/types/memory/temporalDecay.d.ts +2 -2
  122. package/dist/types/memory/types.d.ts +3 -3
  123. package/dist/types/messages/format.d.ts +1 -1
  124. package/dist/types/tools/ToolNode.d.ts +3 -3
  125. package/dist/types/tools/memory/shared.d.ts +1 -1
  126. package/dist/types/types/agent-cache.d.ts +6 -5
  127. package/dist/types/types/graph.d.ts +7 -6
  128. package/dist/types/types/messages.d.ts +1 -1
  129. package/dist/types/types/run.d.ts +1 -1
  130. package/dist/types/types/tools.d.ts +5 -5
  131. package/package.json +1 -1
  132. package/src/agents/AgentContext.ts +2 -2
  133. package/src/agents/__tests__/AgentContext.crossAgentTier1.live.test.ts +5 -3
  134. package/src/agents/__tests__/AgentContext.test.ts +1 -1
  135. package/src/common/__tests__/enum.test.ts +1 -1
  136. package/src/common/enum.ts +12 -12
  137. package/src/graphs/Graph.ts +5 -5
  138. package/src/graphs/MultiAgentGraph.ts +1 -1
  139. package/src/graphs/gapFeatures.test.ts +1 -1
  140. package/src/graphs/phases/__tests__/memoryFlushPhase.test.ts +1 -1
  141. package/src/graphs/phases/memoryFlushPhase.ts +2 -2
  142. package/src/hooks/HookRegistry.ts +1 -1
  143. package/src/hooks/index.ts +1 -1
  144. package/src/hooks/matchers.ts +2 -2
  145. package/src/hooks/types.ts +1 -1
  146. package/src/llm/anthropic/utils/server-tool-inputs.test.ts +7 -7
  147. package/src/llm/bedrock/__tests__/bedrock-caching.test.ts +2 -2
  148. package/src/llm/bedrock/cacheSupport.ts +1 -1
  149. package/src/llm/bedrock/index.ts +2 -2
  150. package/src/llm/openai/index.ts +2 -2
  151. package/src/llm/openai/utils/index.ts +2 -2
  152. package/src/memory/citations.ts +4 -4
  153. package/src/memory/constants.ts +17 -17
  154. package/src/memory/mmr.ts +3 -3
  155. package/src/memory/paths.ts +1 -1
  156. package/src/memory/recallTracking.ts +3 -3
  157. package/src/memory/temporalDecay.ts +2 -2
  158. package/src/memory/types.ts +3 -3
  159. package/src/messages/cache.test.ts +1 -1
  160. package/src/messages/ensureThinkingBlock.test.ts +1 -1
  161. package/src/messages/format.ts +4 -4
  162. package/src/messages/formatAgentMessages.test.ts +1 -1
  163. package/src/scripts/subagent-event-driven-debug.ts +2 -2
  164. package/src/specs/anthropic.simple.test.ts +1 -1
  165. package/src/specs/prune.orphans.test.ts +1 -1
  166. package/src/tools/CodeExecutor.ts +4 -3
  167. package/src/tools/ToolNode.ts +6 -6
  168. package/src/tools/__tests__/CodeExecutor.test.ts +3 -3
  169. package/src/tools/memory/memoryAppendTool.ts +1 -1
  170. package/src/tools/memory/memoryGetTool.ts +2 -2
  171. package/src/tools/memory/memorySearchTool.ts +3 -3
  172. package/src/tools/memory/shared.ts +1 -1
  173. package/src/types/agent-cache.ts +6 -5
  174. package/src/types/graph.ts +7 -6
  175. package/src/types/messages.ts +1 -1
  176. package/src/types/run.ts +1 -1
  177. package/src/types/tools.ts +5 -5
  178. package/dist/types/tools/search/test.d.ts +0 -1
  179. package/src/agents/AgentContext.js.map +0 -1
  180. package/src/agents/AgentContext.test.js.map +0 -1
  181. package/src/agents/__tests__/AgentContext.test.js.map +0 -1
  182. package/src/agents/__tests__/resolveStructuredOutputMode.test.js.map +0 -1
  183. package/src/common/enum.js.map +0 -1
  184. package/src/common/index.js.map +0 -1
  185. package/src/events.js.map +0 -1
  186. package/src/graphs/Graph.js.map +0 -1
  187. package/src/graphs/MultiAgentGraph.js.map +0 -1
  188. package/src/graphs/__tests__/structured-output.integration.test.js.map +0 -1
  189. package/src/graphs/__tests__/structured-output.test.js.map +0 -1
  190. package/src/graphs/contextManagement.e2e.test.js.map +0 -1
  191. package/src/graphs/contextManagement.test.js.map +0 -1
  192. package/src/graphs/handoffValidation.test.js.map +0 -1
  193. package/src/graphs/index.js.map +0 -1
  194. package/src/index.js.map +0 -1
  195. package/src/instrumentation.js.map +0 -1
  196. package/src/llm/anthropic/index.js.map +0 -1
  197. package/src/llm/anthropic/types.js.map +0 -1
  198. package/src/llm/anthropic/utils/message_inputs.js.map +0 -1
  199. package/src/llm/anthropic/utils/message_outputs.js.map +0 -1
  200. package/src/llm/anthropic/utils/output_parsers.js.map +0 -1
  201. package/src/llm/anthropic/utils/tools.js.map +0 -1
  202. package/src/llm/bedrock/__tests__/bedrock-caching.test.js.map +0 -1
  203. package/src/llm/bedrock/index.js.map +0 -1
  204. package/src/llm/bedrock/types.js.map +0 -1
  205. package/src/llm/bedrock/utils/index.js.map +0 -1
  206. package/src/llm/bedrock/utils/message_inputs.js.map +0 -1
  207. package/src/llm/bedrock/utils/message_outputs.js.map +0 -1
  208. package/src/llm/fake.js.map +0 -1
  209. package/src/llm/google/index.js.map +0 -1
  210. package/src/llm/google/types.js.map +0 -1
  211. package/src/llm/google/utils/common.js.map +0 -1
  212. package/src/llm/google/utils/tools.js.map +0 -1
  213. package/src/llm/google/utils/zod_to_genai_parameters.js.map +0 -1
  214. package/src/llm/openai/index.js.map +0 -1
  215. package/src/llm/openai/types.js.map +0 -1
  216. package/src/llm/openai/utils/index.js.map +0 -1
  217. package/src/llm/openai/utils/isReasoningModel.test.js.map +0 -1
  218. package/src/llm/openrouter/index.js.map +0 -1
  219. package/src/llm/openrouter/reasoning.test.js.map +0 -1
  220. package/src/llm/providers.js.map +0 -1
  221. package/src/llm/text.js.map +0 -1
  222. package/src/llm/vertexai/index.js.map +0 -1
  223. package/src/messages/__tests__/tools.test.js.map +0 -1
  224. package/src/messages/cache.js.map +0 -1
  225. package/src/messages/cache.test.js.map +0 -1
  226. package/src/messages/content.js.map +0 -1
  227. package/src/messages/content.test.js.map +0 -1
  228. package/src/messages/core.js.map +0 -1
  229. package/src/messages/ensureThinkingBlock.test.js.map +0 -1
  230. package/src/messages/format.js.map +0 -1
  231. package/src/messages/formatAgentMessages.test.js.map +0 -1
  232. package/src/messages/formatAgentMessages.tools.test.js.map +0 -1
  233. package/src/messages/formatMessage.test.js.map +0 -1
  234. package/src/messages/ids.js.map +0 -1
  235. package/src/messages/index.js.map +0 -1
  236. package/src/messages/labelContentByAgent.test.js.map +0 -1
  237. package/src/messages/prune.js.map +0 -1
  238. package/src/messages/reducer.js.map +0 -1
  239. package/src/messages/shiftIndexTokenCountMap.test.js.map +0 -1
  240. package/src/messages/summarize.js.map +0 -1
  241. package/src/messages/summarize.test.js.map +0 -1
  242. package/src/messages/tools.js.map +0 -1
  243. package/src/mockStream.js.map +0 -1
  244. package/src/prompts/collab.js.map +0 -1
  245. package/src/prompts/index.js.map +0 -1
  246. package/src/prompts/taskmanager.js.map +0 -1
  247. package/src/run.js.map +0 -1
  248. package/src/schemas/index.js.map +0 -1
  249. package/src/schemas/schema-preparation.test.js.map +0 -1
  250. package/src/schemas/validate.js.map +0 -1
  251. package/src/schemas/validate.test.js.map +0 -1
  252. package/src/scripts/abort.js.map +0 -1
  253. package/src/scripts/ant_web_search.js.map +0 -1
  254. package/src/scripts/ant_web_search_edge_case.js.map +0 -1
  255. package/src/scripts/ant_web_search_error_edge_case.js.map +0 -1
  256. package/src/scripts/args.js.map +0 -1
  257. package/src/scripts/bedrock-cache-debug.js.map +0 -1
  258. package/src/scripts/bedrock-content-aggregation-test.js.map +0 -1
  259. package/src/scripts/bedrock-merge-test.js.map +0 -1
  260. package/src/scripts/bedrock-parallel-tools-test.js.map +0 -1
  261. package/src/scripts/caching.js.map +0 -1
  262. package/src/scripts/cli.js.map +0 -1
  263. package/src/scripts/cli2.js.map +0 -1
  264. package/src/scripts/cli3.js.map +0 -1
  265. package/src/scripts/cli4.js.map +0 -1
  266. package/src/scripts/cli5.js.map +0 -1
  267. package/src/scripts/code_exec.js.map +0 -1
  268. package/src/scripts/code_exec_files.js.map +0 -1
  269. package/src/scripts/code_exec_multi_session.js.map +0 -1
  270. package/src/scripts/code_exec_ptc.js.map +0 -1
  271. package/src/scripts/code_exec_session.js.map +0 -1
  272. package/src/scripts/code_exec_simple.js.map +0 -1
  273. package/src/scripts/content.js.map +0 -1
  274. package/src/scripts/empty_input.js.map +0 -1
  275. package/src/scripts/handoff-test.js.map +0 -1
  276. package/src/scripts/image.js.map +0 -1
  277. package/src/scripts/memory.js.map +0 -1
  278. package/src/scripts/multi-agent-chain.js.map +0 -1
  279. package/src/scripts/multi-agent-conditional.js.map +0 -1
  280. package/src/scripts/multi-agent-document-review-chain.js.map +0 -1
  281. package/src/scripts/multi-agent-hybrid-flow.js.map +0 -1
  282. package/src/scripts/multi-agent-parallel-start.js.map +0 -1
  283. package/src/scripts/multi-agent-parallel.js.map +0 -1
  284. package/src/scripts/multi-agent-sequence.js.map +0 -1
  285. package/src/scripts/multi-agent-supervisor.js.map +0 -1
  286. package/src/scripts/multi-agent-test.js.map +0 -1
  287. package/src/scripts/parallel-asymmetric-tools-test.js.map +0 -1
  288. package/src/scripts/parallel-full-metadata-test.js.map +0 -1
  289. package/src/scripts/parallel-tools-test.js.map +0 -1
  290. package/src/scripts/programmatic_exec.js.map +0 -1
  291. package/src/scripts/programmatic_exec_agent.js.map +0 -1
  292. package/src/scripts/search.js.map +0 -1
  293. package/src/scripts/sequential-full-metadata-test.js.map +0 -1
  294. package/src/scripts/simple.js.map +0 -1
  295. package/src/scripts/single-agent-metadata-test.js.map +0 -1
  296. package/src/scripts/stream.js.map +0 -1
  297. package/src/scripts/test-custom-prompt-key.js.map +0 -1
  298. package/src/scripts/test-handoff-input.js.map +0 -1
  299. package/src/scripts/test-handoff-preamble.js.map +0 -1
  300. package/src/scripts/test-handoff-steering.js.map +0 -1
  301. package/src/scripts/test-multi-agent-list-handoff.js.map +0 -1
  302. package/src/scripts/test-parallel-agent-labeling.js.map +0 -1
  303. package/src/scripts/test-parallel-handoffs.js.map +0 -1
  304. package/src/scripts/test-thinking-handoff-bedrock.js.map +0 -1
  305. package/src/scripts/test-thinking-handoff.js.map +0 -1
  306. package/src/scripts/test-thinking-to-thinking-handoff-bedrock.js.map +0 -1
  307. package/src/scripts/test-tool-before-handoff-role-order.js.map +0 -1
  308. package/src/scripts/test-tools-before-handoff.js.map +0 -1
  309. package/src/scripts/test_code_api.js.map +0 -1
  310. package/src/scripts/thinking-bedrock.js.map +0 -1
  311. package/src/scripts/thinking-vertexai.js.map +0 -1
  312. package/src/scripts/thinking.js.map +0 -1
  313. package/src/scripts/tool_search.js.map +0 -1
  314. package/src/scripts/tools.js.map +0 -1
  315. package/src/specs/agent-handoffs-bedrock.integration.test.js.map +0 -1
  316. package/src/specs/agent-handoffs.test.js.map +0 -1
  317. package/src/specs/anthropic.simple.test.js.map +0 -1
  318. package/src/specs/azure.simple.test.js.map +0 -1
  319. package/src/specs/cache.simple.test.js.map +0 -1
  320. package/src/specs/custom-event-await.test.js.map +0 -1
  321. package/src/specs/deepseek.simple.test.js.map +0 -1
  322. package/src/specs/emergency-prune.test.js.map +0 -1
  323. package/src/specs/moonshot.simple.test.js.map +0 -1
  324. package/src/specs/observability.integration.test.js.map +0 -1
  325. package/src/specs/openai.simple.test.js.map +0 -1
  326. package/src/specs/openrouter.simple.test.js.map +0 -1
  327. package/src/specs/prune.test.js.map +0 -1
  328. package/src/specs/reasoning.test.js.map +0 -1
  329. package/src/specs/spec.utils.js.map +0 -1
  330. package/src/specs/thinking-handoff.test.js.map +0 -1
  331. package/src/specs/thinking-prune.test.js.map +0 -1
  332. package/src/specs/token-distribution-edge-case.test.js.map +0 -1
  333. package/src/specs/token-memoization.test.js.map +0 -1
  334. package/src/specs/tokens.test.js.map +0 -1
  335. package/src/specs/tool-error.test.js.map +0 -1
  336. package/src/splitStream.js.map +0 -1
  337. package/src/splitStream.test.js.map +0 -1
  338. package/src/stream.js.map +0 -1
  339. package/src/stream.test.js.map +0 -1
  340. package/src/test/mockTools.js.map +0 -1
  341. package/src/tools/BrowserTools.js.map +0 -1
  342. package/src/tools/Calculator.js.map +0 -1
  343. package/src/tools/Calculator.test.js.map +0 -1
  344. package/src/tools/CodeExecutor.js.map +0 -1
  345. package/src/tools/ProgrammaticToolCalling.js.map +0 -1
  346. package/src/tools/StreamingToolCallBuffer.js.map +0 -1
  347. package/src/tools/ToolNode.js.map +0 -1
  348. package/src/tools/ToolSearch.js.map +0 -1
  349. package/src/tools/__tests__/BrowserTools.test.js.map +0 -1
  350. package/src/tools/__tests__/ProgrammaticToolCalling.integration.test.js.map +0 -1
  351. package/src/tools/__tests__/ProgrammaticToolCalling.test.js.map +0 -1
  352. package/src/tools/__tests__/StreamingToolCallBuffer.test.js.map +0 -1
  353. package/src/tools/__tests__/ToolApproval.test.js.map +0 -1
  354. package/src/tools/__tests__/ToolNode.recovery.test.js.map +0 -1
  355. package/src/tools/__tests__/ToolNode.session.test.js.map +0 -1
  356. package/src/tools/__tests__/ToolSearch.integration.test.js.map +0 -1
  357. package/src/tools/__tests__/ToolSearch.test.js.map +0 -1
  358. package/src/tools/__tests__/handlers.test.js.map +0 -1
  359. package/src/tools/__tests__/truncation-recovery.integration.test.js.map +0 -1
  360. package/src/tools/handlers.js.map +0 -1
  361. package/src/tools/schema.js.map +0 -1
  362. package/src/tools/search/anthropic.js.map +0 -1
  363. package/src/tools/search/content.js.map +0 -1
  364. package/src/tools/search/content.test.js.map +0 -1
  365. package/src/tools/search/firecrawl.js.map +0 -1
  366. package/src/tools/search/format.js.map +0 -1
  367. package/src/tools/search/highlights.js.map +0 -1
  368. package/src/tools/search/index.js.map +0 -1
  369. package/src/tools/search/jina-reranker.test.js.map +0 -1
  370. package/src/tools/search/output.md +0 -2775
  371. package/src/tools/search/rerankers.js.map +0 -1
  372. package/src/tools/search/schema.js.map +0 -1
  373. package/src/tools/search/search.js.map +0 -1
  374. package/src/tools/search/serper-scraper.js.map +0 -1
  375. package/src/tools/search/test.html +0 -884
  376. package/src/tools/search/test.js.map +0 -1
  377. package/src/tools/search/test.md +0 -643
  378. package/src/tools/search/test.ts +0 -159
  379. package/src/tools/search/tool.js.map +0 -1
  380. package/src/tools/search/types.js.map +0 -1
  381. package/src/tools/search/utils.js.map +0 -1
  382. package/src/types/graph.js.map +0 -1
  383. package/src/types/graph.test.js.map +0 -1
  384. package/src/types/index.js.map +0 -1
  385. package/src/types/llm.js.map +0 -1
  386. package/src/types/messages.js.map +0 -1
  387. package/src/types/run.js.map +0 -1
  388. package/src/types/stream.js.map +0 -1
  389. package/src/types/tools.js.map +0 -1
  390. package/src/utils/contextAnalytics.js.map +0 -1
  391. package/src/utils/contextAnalytics.test.js.map +0 -1
  392. package/src/utils/events.js.map +0 -1
  393. package/src/utils/graph.js.map +0 -1
  394. package/src/utils/handlers.js.map +0 -1
  395. package/src/utils/index.js.map +0 -1
  396. package/src/utils/llm.js.map +0 -1
  397. package/src/utils/llmConfig.js.map +0 -1
  398. package/src/utils/logging.js.map +0 -1
  399. package/src/utils/misc.js.map +0 -1
  400. package/src/utils/run.js.map +0 -1
  401. package/src/utils/schema.js.map +0 -1
  402. package/src/utils/title.js.map +0 -1
  403. package/src/utils/tokens.js.map +0 -1
  404. package/src/utils/toonFormat.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"paths.mjs","sources":["../../../src/memory/paths.ts"],"sourcesContent":["/**\n * Autonomous memory — canonical path whitelist + tier utilities.\n *\n * Single source of truth for the 8 stable memory documents. Every write\n * goes through {@link assertWritablePath}; every reader can ask\n * {@link getTierForPath} what a row belongs to. Adding or removing a\n * path means editing this file — and exactly this file.\n *\n * ## Why a whitelist?\n *\n * Earlier upstream-faithful designs used date-keyed files\n * (`memory/YYYY-MM-DD.md`), which have three problems for a persistent\n * multi-user agent:\n *\n * 1. **Unbounded growth** — one row per day per agent per user, forever.\n * 2. **LLM routing ambiguity** — \"which date file do I read?\" has no\n * good answer, so the model reads (and ranks against) all of them.\n * 3. **No natural deduplication** — the same fact written across three\n * days returns three near-identical hits.\n *\n * With 8 stable canonical documents the LLM knows *exactly* where to\n * write (\"is this a preference? → `memory/user/preferences.md`\") and\n * each row accumulates via UPSERT instead of piling up new rows.\n *\n * ## Two tiers\n *\n * - **Agent tier** (`memory/agent/*`) — operational knowledge that\n * every caller of the agent benefits from. Stored with `user_id = NULL`.\n * Shared across all users of a collaborative agent; the only tier that\n * exists for isolated/autonomous agents with no invoker.\n *\n * - **User tier** (`memory/user/*`) — per-invoker personalization.\n * Stored with `user_id = <caller>`. Read path filters so User A never\n * sees User B's rows, even for the same agent. Not writable unless the\n * flush scope carries a non-empty `userId`.\n *\n * The tier of a path is a function of its prefix (`memory/agent/` vs\n * `memory/user/`), so adding a new document is one line here + the\n * constant array entry; no store or route code has to change.\n */\n\nimport { MEMORY_PATH_PREFIX } from './constants';\nimport type { MemoryScope } from './types';\n\n/** Tier discriminator — the two kinds of memory a row can belong to. */\nexport type MemoryTier = 'agent' | 'user';\n\n/** Every canonical document the flush phase is allowed to write. */\nexport interface MemoryPathDescriptor {\n /** Full path including the `memory/` prefix. */\n path: string;\n /** Which tier the path lives under. */\n tier: MemoryTier;\n /** Short label shown in UI tier badges and the flush prompt rubric. */\n label: string;\n /** One-line description — fed to the LLM to make routing unambiguous. */\n description: string;\n}\n\n/** Agent-tier documents — shared across all users of the agent. */\nexport const MEMORY_AGENT_PATHS: readonly MemoryPathDescriptor[] =\n Object.freeze([\n Object.freeze({\n path: 'memory/agent/playbook.md',\n tier: 'agent' as const,\n label: 'Playbook',\n description:\n 'Successful task patterns and workflows that have worked for this agent — ' +\n 'reusable recipes, known-good tool sequences, approaches that consistently ' +\n 'produce the right result.',\n }),\n Object.freeze({\n path: 'memory/agent/pitfalls.md',\n tier: 'agent' as const,\n label: 'Pitfalls',\n description:\n 'Tool failures, error recoveries, schema mistakes, and invalid argument ' +\n 'shapes the agent has seen — so the same mistake is not repeated on future ' +\n 'turns. One note per distinct failure mode.',\n }),\n Object.freeze({\n path: 'memory/agent/domain.md',\n tier: 'agent' as const,\n label: 'Domain',\n description:\n 'Durable facts about the systems, APIs, data models, and business rules ' +\n 'this agent operates on — things that are true independent of any one user ' +\n 'and that the agent repeatedly needs to know.',\n }),\n Object.freeze({\n path: 'memory/agent/style.md',\n tier: 'agent' as const,\n label: 'Style',\n description:\n 'Tone, formatting, and response-shape conventions the agent has converged ' +\n 'on across the whole user base. Do NOT write user-specific preferences here ' +\n '(those belong under the user tier).',\n }),\n ]);\n\n/** User-tier documents — per-invoker, never shared across users. */\nexport const MEMORY_USER_PATHS: readonly MemoryPathDescriptor[] = Object.freeze(\n [\n Object.freeze({\n path: 'memory/user/profile.md',\n tier: 'user' as const,\n label: 'Profile',\n description:\n \"This specific user's identity — name, role, team, sign-off name, \" +\n 'responsibilities, stable facts about who they are. Only facts ' +\n 'volunteered by the user themselves.',\n }),\n Object.freeze({\n path: 'memory/user/preferences.md',\n tier: 'user' as const,\n label: 'Preferences',\n description:\n 'How THIS user wants things done — preferred formats, verbosity, tone, ' +\n 'cadence, output length, language conventions. Explicit corrections they ' +\n 'have given count as preferences.',\n }),\n Object.freeze({\n path: 'memory/user/projects.md',\n tier: 'user' as const,\n label: 'Projects',\n description:\n \"This user's current initiatives, ongoing work, deadlines, and active \" +\n 'project context. Include dates in the prose when relevant. Retire entries ' +\n 'by overwriting them on future flushes when the user indicates a project is done.',\n }),\n Object.freeze({\n path: 'memory/user/references.md',\n tier: 'user' as const,\n label: 'References',\n description:\n 'External systems, dashboards, accounts, links, channels, and resources ' +\n \"THIS user has pointed the agent at — the 'where to look' pointers that \" +\n 'make later turns more efficient.',\n }),\n ]\n);\n\n/** All 8 canonical documents in display order: agent tier first, user tier second. */\nexport const MEMORY_ALL_PATHS: readonly MemoryPathDescriptor[] = Object.freeze([\n ...MEMORY_AGENT_PATHS,\n ...MEMORY_USER_PATHS,\n]);\n\n/** Fast O(1) lookup map: path → descriptor. */\nconst PATH_INDEX: ReadonlyMap<string, MemoryPathDescriptor> = new Map(\n MEMORY_ALL_PATHS.map((p) => [p.path, p])\n);\n\n/** Set of all whitelisted paths — for `has()` lookups. */\nexport const MEMORY_WRITABLE_PATHS: ReadonlySet<string> = new Set(\n MEMORY_ALL_PATHS.map((p) => p.path)\n);\n\n/** Returns the descriptor for a canonical path, or `undefined` if not on the whitelist. */\nexport function getPathDescriptor(\n path: string\n): MemoryPathDescriptor | undefined {\n return PATH_INDEX.get(path);\n}\n\n/**\n * Returns the tier a given path belongs to.\n *\n * For unknown paths (e.g. legacy date-keyed rows that predate this schema),\n * falls back to inspecting the `memory/agent/` or `memory/user/` prefix.\n * Anything that matches neither is classified as `agent` — it will surface\n * in the admin UI under the agent-tier header and stay read-only there.\n */\nexport function getTierForPath(path: string): MemoryTier {\n const descriptor = PATH_INDEX.get(path);\n if (descriptor) return descriptor.tier;\n if (path.startsWith('memory/user/')) return 'user';\n return 'agent';\n}\n\n/**\n * Paths that are legal to write **for this caller's scope**.\n *\n * If `scope.userId` is absent (isolated/autonomous agent), the user-tier\n * paths are dropped. This is the list the flush prompt renders into its\n * rubric — the LLM never sees paths it cannot write to.\n */\nexport function getWritablePathsForScope(\n scope: Pick<MemoryScope, 'userId'>\n): readonly MemoryPathDescriptor[] {\n if (scope.userId == null || scope.userId === '') {\n return MEMORY_AGENT_PATHS;\n }\n return MEMORY_ALL_PATHS;\n}\n\n/**\n * Validates a write path against the whitelist AND the caller's scope.\n *\n * Throws with an actionable message when:\n * - the path is missing the `memory/` prefix\n * - the path is not on the 8-doc whitelist\n * - the path is user-tier but `scope.userId` is missing\n *\n * The store's append() is the single call site; other callers should\n * never hit this directly. Kept as a standalone function for testability.\n */\nexport function assertWritablePath(\n path: string,\n scope: Pick<MemoryScope, 'userId'>\n): MemoryPathDescriptor {\n if (!path || !path.startsWith(MEMORY_PATH_PREFIX)) {\n throw new Error(\n `memory_append path must start with \"${MEMORY_PATH_PREFIX}\" (received \"${path}\")`\n );\n }\n const descriptor = PATH_INDEX.get(path);\n if (!descriptor) {\n throw new Error(\n `memory_append path \"${path}\" is not on the canonical whitelist. ` +\n `Allowed: ${MEMORY_ALL_PATHS.map((p) => p.path).join(', ')}`\n );\n }\n if (\n descriptor.tier === 'user' &&\n (scope.userId == null || scope.userId === '')\n ) {\n throw new Error(\n `memory_append to user-tier path \"${path}\" requires a caller userId in scope, ` +\n `but scope.userId is missing. This path is private to a specific user and ` +\n `cannot be written from an isolated/autonomous context.`\n );\n }\n return descriptor;\n}\n\n/**\n * Renders the whitelist as a compact bullet list, used inside the flush\n * prompt so the LLM sees the authoritative rubric at inference time.\n *\n * Output shape:\n * - memory/agent/playbook.md [Playbook, shared] — <description>\n * - memory/agent/pitfalls.md [Pitfalls, shared] — <description>\n * ...\n *\n * The `[Label, shared|private]` tag tells the model whether the doc is\n * visible to all users (agent tier) or only to the caller (user tier).\n * Filtered to only the paths writable for the given scope.\n */\nexport function renderPathsRubric(scope: Pick<MemoryScope, 'userId'>): string {\n const writable = getWritablePathsForScope(scope);\n return writable\n .map((p) => {\n const visibility = p.tier === 'agent' ? 'shared' : 'private';\n return `- ${p.path} [${p.label}, ${visibility}] — ${p.description}`;\n })\n .join('\\n');\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCG;AAoBH;AACO,MAAM,kBAAkB,GAC7B,MAAM,CAAC,MAAM,CAAC;IACZ,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,0BAA0B;AAChC,QAAA,IAAI,EAAE,OAAgB;AACtB,QAAA,KAAK,EAAE,UAAU;AACjB,QAAA,WAAW,EACT,2EAA2E;YAC3E,4EAA4E;YAC5E,2BAA2B;KAC9B,CAAC;IACF,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,0BAA0B;AAChC,QAAA,IAAI,EAAE,OAAgB;AACtB,QAAA,KAAK,EAAE,UAAU;AACjB,QAAA,WAAW,EACT,yEAAyE;YACzE,4EAA4E;YAC5E,4CAA4C;KAC/C,CAAC;IACF,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,wBAAwB;AAC9B,QAAA,IAAI,EAAE,OAAgB;AACtB,QAAA,KAAK,EAAE,QAAQ;AACf,QAAA,WAAW,EACT,yEAAyE;YACzE,4EAA4E;YAC5E,8CAA8C;KACjD,CAAC;IACF,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,uBAAuB;AAC7B,QAAA,IAAI,EAAE,OAAgB;AACtB,QAAA,KAAK,EAAE,OAAO;AACd,QAAA,WAAW,EACT,2EAA2E;YAC3E,6EAA6E;YAC7E,qCAAqC;KACxC,CAAC;AACH,CAAA;AAEH;AACO,MAAM,iBAAiB,GAAoC,MAAM,CAAC,MAAM,CAC7E;IACE,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,wBAAwB;AAC9B,QAAA,IAAI,EAAE,MAAe;AACrB,QAAA,KAAK,EAAE,SAAS;AAChB,QAAA,WAAW,EACT,mEAAmE;Y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DAAA,CAAwD,CAC3D;IACH;AACA,IAAA,OAAO,UAAU;AACnB;AAEA;;;;;;;;;;;;AAYG;AACG,SAAU,iBAAiB,CAAC,KAAkC,EAAA;AAClE,IAAA,MAAM,QAAQ,GAAG,wBAAwB,CAAC,KAAK,CAAC;AAChD,IAAA,OAAO;AACJ,SAAA,GAAG,CAAC,CAAC,CAAC,KAAI;AACT,QAAA,MAAM,UAAU,GAAG,CAAC,CAAC,IAAI,KAAK,OAAO,GAAG,QAAQ,GAAG,SAAS;AAC5D,QAAA,OAAO,CAAA,EAAA,EAAK,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,KAAK,CAAA,EAAA,EAAK,UAAU,CAAA,IAAA,EAAO,CAAC,CAAC,WAAW,EAAE;AACrE,IAAA,CAAC;SACA,IAAI,CAAC,IAAI,CAAC;AACf;;;;"}
1
+ {"version":3,"file":"paths.mjs","sources":["../../../src/memory/paths.ts"],"sourcesContent":["/**\n * Autonomous memory — canonical path whitelist + tier utilities.\n *\n * Single source of truth for the 8 stable memory documents. Every write\n * goes through {@link assertWritablePath}; every reader can ask\n * {@link getTierForPath} what a row belongs to. Adding or removing a\n * path means editing this file — and exactly this file.\n *\n * ## Why a whitelist?\n *\n * Earlier historical designs used date-keyed files\n * (`memory/YYYY-MM-DD.md`), which have three problems for a persistent\n * multi-user agent:\n *\n * 1. **Unbounded growth** — one row per day per agent per user, forever.\n * 2. **LLM routing ambiguity** — \"which date file do I read?\" has no\n * good answer, so the model reads (and ranks against) all of them.\n * 3. **No natural deduplication** — the same fact written across three\n * days returns three near-identical hits.\n *\n * With 8 stable canonical documents the LLM knows *exactly* where to\n * write (\"is this a preference? → `memory/user/preferences.md`\") and\n * each row accumulates via UPSERT instead of piling up new rows.\n *\n * ## Two tiers\n *\n * - **Agent tier** (`memory/agent/*`) — operational knowledge that\n * every caller of the agent benefits from. Stored with `user_id = NULL`.\n * Shared across all users of a collaborative agent; the only tier that\n * exists for isolated/autonomous agents with no invoker.\n *\n * - **User tier** (`memory/user/*`) — per-invoker personalization.\n * Stored with `user_id = <caller>`. Read path filters so User A never\n * sees User B's rows, even for the same agent. Not writable unless the\n * flush scope carries a non-empty `userId`.\n *\n * The tier of a path is a function of its prefix (`memory/agent/` vs\n * `memory/user/`), so adding a new document is one line here + the\n * constant array entry; no store or route code has to change.\n */\n\nimport { MEMORY_PATH_PREFIX } from './constants';\nimport type { MemoryScope } from './types';\n\n/** Tier discriminator — the two kinds of memory a row can belong to. */\nexport type MemoryTier = 'agent' | 'user';\n\n/** Every canonical document the flush phase is allowed to write. */\nexport interface MemoryPathDescriptor {\n /** Full path including the `memory/` prefix. */\n path: string;\n /** Which tier the path lives under. */\n tier: MemoryTier;\n /** Short label shown in UI tier badges and the flush prompt rubric. */\n label: string;\n /** One-line description — fed to the LLM to make routing unambiguous. */\n description: string;\n}\n\n/** Agent-tier documents — shared across all users of the agent. */\nexport const MEMORY_AGENT_PATHS: readonly MemoryPathDescriptor[] =\n Object.freeze([\n Object.freeze({\n path: 'memory/agent/playbook.md',\n tier: 'agent' as const,\n label: 'Playbook',\n description:\n 'Successful task patterns and workflows that have worked for this agent — ' +\n 'reusable recipes, known-good tool sequences, approaches that consistently ' +\n 'produce the right result.',\n }),\n Object.freeze({\n path: 'memory/agent/pitfalls.md',\n tier: 'agent' as const,\n label: 'Pitfalls',\n description:\n 'Tool failures, error recoveries, schema mistakes, and invalid argument ' +\n 'shapes the agent has seen — so the same mistake is not repeated on future ' +\n 'turns. One note per distinct failure mode.',\n }),\n Object.freeze({\n path: 'memory/agent/domain.md',\n tier: 'agent' as const,\n label: 'Domain',\n description:\n 'Durable facts about the systems, APIs, data models, and business rules ' +\n 'this agent operates on — things that are true independent of any one user ' +\n 'and that the agent repeatedly needs to know.',\n }),\n Object.freeze({\n path: 'memory/agent/style.md',\n tier: 'agent' as const,\n label: 'Style',\n description:\n 'Tone, formatting, and response-shape conventions the agent has converged ' +\n 'on across the whole user base. Do NOT write user-specific preferences here ' +\n '(those belong under the user tier).',\n }),\n ]);\n\n/** User-tier documents — per-invoker, never shared across users. */\nexport const MEMORY_USER_PATHS: readonly MemoryPathDescriptor[] = Object.freeze(\n [\n Object.freeze({\n path: 'memory/user/profile.md',\n tier: 'user' as const,\n label: 'Profile',\n description:\n \"This specific user's identity — name, role, team, sign-off name, \" +\n 'responsibilities, stable facts about who they are. Only facts ' +\n 'volunteered by the user themselves.',\n }),\n Object.freeze({\n path: 'memory/user/preferences.md',\n tier: 'user' as const,\n label: 'Preferences',\n description:\n 'How THIS user wants things done — preferred formats, verbosity, tone, ' +\n 'cadence, output length, language conventions. Explicit corrections they ' +\n 'have given count as preferences.',\n }),\n Object.freeze({\n path: 'memory/user/projects.md',\n tier: 'user' as const,\n label: 'Projects',\n description:\n \"This user's current initiatives, ongoing work, deadlines, and active \" +\n 'project context. Include dates in the prose when relevant. Retire entries ' +\n 'by overwriting them on future flushes when the user indicates a project is done.',\n }),\n Object.freeze({\n path: 'memory/user/references.md',\n tier: 'user' as const,\n label: 'References',\n description:\n 'External systems, dashboards, accounts, links, channels, and resources ' +\n \"THIS user has pointed the agent at — the 'where to look' pointers that \" +\n 'make later turns more efficient.',\n }),\n ]\n);\n\n/** All 8 canonical documents in display order: agent tier first, user tier second. */\nexport const MEMORY_ALL_PATHS: readonly MemoryPathDescriptor[] = Object.freeze([\n ...MEMORY_AGENT_PATHS,\n ...MEMORY_USER_PATHS,\n]);\n\n/** Fast O(1) lookup map: path → descriptor. */\nconst PATH_INDEX: ReadonlyMap<string, MemoryPathDescriptor> = new Map(\n MEMORY_ALL_PATHS.map((p) => [p.path, p])\n);\n\n/** Set of all whitelisted paths — for `has()` lookups. */\nexport const MEMORY_WRITABLE_PATHS: ReadonlySet<string> = new Set(\n MEMORY_ALL_PATHS.map((p) => p.path)\n);\n\n/** Returns the descriptor for a canonical path, or `undefined` if not on the whitelist. */\nexport function getPathDescriptor(\n path: string\n): MemoryPathDescriptor | undefined {\n return PATH_INDEX.get(path);\n}\n\n/**\n * Returns the tier a given path belongs to.\n *\n * For unknown paths (e.g. legacy date-keyed rows that predate this schema),\n * falls back to inspecting the `memory/agent/` or `memory/user/` prefix.\n * Anything that matches neither is classified as `agent` — it will surface\n * in the admin UI under the agent-tier header and stay read-only there.\n */\nexport function getTierForPath(path: string): MemoryTier {\n const descriptor = PATH_INDEX.get(path);\n if (descriptor) return descriptor.tier;\n if (path.startsWith('memory/user/')) return 'user';\n return 'agent';\n}\n\n/**\n * Paths that are legal to write **for this caller's scope**.\n *\n * If `scope.userId` is absent (isolated/autonomous agent), the user-tier\n * paths are dropped. This is the list the flush prompt renders into its\n * rubric — the LLM never sees paths it cannot write to.\n */\nexport function getWritablePathsForScope(\n scope: Pick<MemoryScope, 'userId'>\n): readonly MemoryPathDescriptor[] {\n if (scope.userId == null || scope.userId === '') {\n return MEMORY_AGENT_PATHS;\n }\n return MEMORY_ALL_PATHS;\n}\n\n/**\n * Validates a write path against the whitelist AND the caller's scope.\n *\n * Throws with an actionable message when:\n * - the path is missing the `memory/` prefix\n * - the path is not on the 8-doc whitelist\n * - the path is user-tier but `scope.userId` is missing\n *\n * The store's append() is the single call site; other callers should\n * never hit this directly. Kept as a standalone function for testability.\n */\nexport function assertWritablePath(\n path: string,\n scope: Pick<MemoryScope, 'userId'>\n): MemoryPathDescriptor {\n if (!path || !path.startsWith(MEMORY_PATH_PREFIX)) {\n throw new Error(\n `memory_append path must start with \"${MEMORY_PATH_PREFIX}\" (received \"${path}\")`\n );\n }\n const descriptor = PATH_INDEX.get(path);\n if (!descriptor) {\n throw new Error(\n `memory_append path \"${path}\" is not on the canonical whitelist. ` +\n `Allowed: ${MEMORY_ALL_PATHS.map((p) => p.path).join(', ')}`\n );\n }\n if (\n descriptor.tier === 'user' &&\n (scope.userId == null || scope.userId === '')\n ) {\n throw new Error(\n `memory_append to user-tier path \"${path}\" requires a caller userId in scope, ` +\n `but scope.userId is missing. This path is private to a specific user and ` +\n `cannot be written from an isolated/autonomous context.`\n );\n }\n return descriptor;\n}\n\n/**\n * Renders the whitelist as a compact bullet list, used inside the flush\n * prompt so the LLM sees the authoritative rubric at inference time.\n *\n * Output shape:\n * - memory/agent/playbook.md [Playbook, shared] — <description>\n * - memory/agent/pitfalls.md [Pitfalls, shared] — <description>\n * ...\n *\n * The `[Label, shared|private]` tag tells the model whether the doc is\n * visible to all users (agent tier) or only to the caller (user tier).\n * Filtered to only the paths writable for the given scope.\n */\nexport function renderPathsRubric(scope: Pick<MemoryScope, 'userId'>): string {\n const writable = getWritablePathsForScope(scope);\n return writable\n .map((p) => {\n const visibility = p.tier === 'agent' ? 'shared' : 'private';\n return `- ${p.path} [${p.label}, ${visibility}] — ${p.description}`;\n })\n .join('\\n');\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCG;AAoBH;AACO,MAAM,kBAAkB,GAC7B,MAAM,CAAC,MAAM,CAAC;IACZ,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,0BAA0B;AAChC,QAAA,IAAI,EAAE,OAAgB;AACtB,QAAA,KAAK,EAAE,UAAU;AACjB,QAAA,WAAW,EACT,2EAA2E;YAC3E,4EAA4E;YAC5E,2BAA2B;KAC9B,CAAC;IACF,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,0BAA0B;AAChC,QAAA,IAAI,EAAE,OAAgB;AACtB,QAAA,KAAK,EAAE,UAAU;AACjB,QAAA,WAAW,EACT,yEAAyE;YACzE,4EAA4E;YAC5E,4CAA4C;KAC/C,CAAC;IACF,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,wBAAwB;AAC9B,QAAA,IAAI,EAAE,OAAgB;AACtB,QAAA,KAAK,EAAE,QAAQ;AACf,QAAA,WAAW,EACT,yEAAyE;YACzE,4EAA4E;YAC5E,8CAA8C;KACjD,CAAC;IACF,MAAM,CAAC,MAAM,CAAC;AACZ,QAAA,IAAI,EAAE,uBAAuB;AAC7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AC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA,CAAE,CAC/D;IACH;AACA,IAAA,IACE,UAAU,CAAC,IAAI,KAAK,MAAM;AAC1B,SAAC,KAAK,CAAC,MAAM,IAAI,IAAI,IAAI,KAAK,CAAC,MAAM,KAAK,EAAE,CAAC,EAC7C;AACA,QAAA,MAAM,IAAI,KAAK,CACb,CAAA,iCAAA,EAAoC,IAAI,CAAA,qCAAA,CAAuC;YAC7E,CAAA,yEAAA,CAA2E;AAC3E,YAAA,CAAA,sDAAA,CAAwD,CAC3D;IACH;AACA,IAAA,OAAO,UAAU;AACnB;AAEA;;;;;;;;;;;;AAYG;AACG,SAAU,iBAAiB,CAAC,KAAkC,EAAA;AAClE,IAAA,MAAM,QAAQ,GAAG,wBAAwB,CAAC,KAAK,CAAC;AAChD,IAAA,OAAO;AACJ,SAAA,GAAG,CAAC,CAAC,CAAC,KAAI;AACT,QAAA,MAAM,UAAU,GAAG,CAAC,CAAC,IAAI,KAAK,OAAO,GAAG,QAAQ,GAAG,SAAS;AAC5D,QAAA,OAAO,CAAA,EAAA,EAAK,CAAC,CAAC,IAAI,KAAK,CAAC,CAAC,KAAK,CAAA,EAAA,EAAK,UAAU,CAAA,IAAA,EAAO,CAAC,CAAC,WAAW,EAAE;AACrE,IAAA,CAAC;SACA,IAAI,CAAC,IAAI,CAAC;AACf;;;;"}
@@ -3,9 +3,9 @@ import { createHash } from 'crypto';
3
3
  /**
4
4
  * Recall tracking — Phase 2.
5
5
  *
6
- * Lightweight adaptation of upstream
6
+ * Lightweight adaptation of an external recall-tracking module
7
7
  * `extensions/memory-core/src/short-term-promotion.ts::recordShortTermRecalls`.
8
- * Upstream stores recalls in a JSON file under `memory/.dreams/`; we store
8
+ * The reference implementation stores recalls in a JSON file under `memory/.dreams/`; we store
9
9
  * them in a Postgres table `agent_memory_recalls`. Schema captures what the
10
10
  * future Phase 3 dreaming/promotion algorithm will need:
11
11
  * - which memory row was surfaced (`memory_id`)
@@ -65,7 +65,7 @@ class PgvectorRecallTracker {
65
65
  const qhash = hashQuery(params.query);
66
66
  const bucket = dayBucket(nowMs);
67
67
  // [recall-tracking] debug: upsert one row per (agent, memory, query, day)
68
- // Upstream dedupes per-day per-query so repeated searches don't inflate counts.
68
+ // The reference implementation dedupes per-day per-query so repeated searches don't inflate counts.
69
69
  const values = [];
70
70
  const args = [];
71
71
  let i = 1;
@@ -1 +1 @@
1
- {"version":3,"file":"recallTracking.mjs","sources":["../../../src/memory/recallTracking.ts"],"sourcesContent":["/**\n * Recall tracking — Phase 2.\n *\n * Lightweight adaptation of upstream\n * `extensions/memory-core/src/short-term-promotion.ts::recordShortTermRecalls`.\n * Upstream stores recalls in a JSON file under `memory/.dreams/`; we store\n * them in a Postgres table `agent_memory_recalls`. Schema captures what the\n * future Phase 3 dreaming/promotion algorithm will need:\n * - which memory row was surfaced (`memory_id`)\n * - the query that surfaced it (raw + SHA-256 hash for dedupe)\n * - hybrid score at the time of recall\n * - the day bucket (for per-day dedupe / frequency counting)\n * - the recorded timestamp\n *\n * Best-effort: failures never block memory_search. The caller fires\n * {@link RecallTracker.record} without awaiting the result and ignores errors.\n */\nimport { createHash } from 'crypto';\nimport type { Pool } from 'pg';\n\nexport interface RecallTracker {\n /** Record that the given memory ids were surfaced to the model for a query. */\n record(params: RecallRecordParams): Promise<void>;\n /** Backend-specific schema migration. Idempotent. */\n migrate(): Promise<void>;\n}\n\nexport interface RecallRecordParams {\n agentId: string;\n query: string;\n hits: Array<{ id: string; path: string; score: number }>;\n nowMs?: number;\n}\n\nexport const RECALL_TABLE = 'agent_memory_recalls';\n\nfunction hashQuery(query: string): string {\n return createHash('sha256')\n .update(query.trim().toLowerCase())\n .digest('hex')\n .slice(0, 32);\n}\n\nfunction dayBucket(nowMs: number): string {\n const d = new Date(nowMs);\n const y = d.getUTCFullYear();\n const m = String(d.getUTCMonth() + 1).padStart(2, '0');\n const day = String(d.getUTCDate()).padStart(2, '0');\n return `${y}-${m}-${day}`;\n}\n\nexport class PgvectorRecallTracker implements RecallTracker {\n constructor(\n private readonly pool: Pool,\n private readonly table: string = RECALL_TABLE\n ) {}\n\n async migrate(): Promise<void> {\n // [recall-tracking] debug: create table + indexes if missing\n await this.pool.query(`\n CREATE TABLE IF NOT EXISTS ${this.table} (\n id BIGSERIAL PRIMARY KEY,\n agent_id TEXT NOT NULL,\n memory_id TEXT NOT NULL,\n memory_path TEXT NOT NULL,\n query TEXT NOT NULL,\n query_hash TEXT NOT NULL,\n score DOUBLE PRECISION NOT NULL,\n day_bucket TEXT NOT NULL,\n recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n )\n `);\n await this.pool.query(\n `CREATE INDEX IF NOT EXISTS ${this.table}_agent_day_idx ON ${this.table} (agent_id, day_bucket)`\n );\n await this.pool.query(\n `CREATE INDEX IF NOT EXISTS ${this.table}_memory_idx ON ${this.table} (agent_id, memory_id)`\n );\n await this.pool.query(\n `CREATE UNIQUE INDEX IF NOT EXISTS ${this.table}_dedupe_idx\n ON ${this.table} (agent_id, memory_id, query_hash, day_bucket)`\n );\n }\n\n async record(params: RecallRecordParams): Promise<void> {\n if (!params.agentId || !params.query.trim() || params.hits.length === 0)\n return;\n const nowMs = params.nowMs ?? Date.now();\n const qhash = hashQuery(params.query);\n const bucket = dayBucket(nowMs);\n\n // [recall-tracking] debug: upsert one row per (agent, memory, query, day)\n // Upstream dedupes per-day per-query so repeated searches don't inflate counts.\n const values: string[] = [];\n const args: unknown[] = [];\n let i = 1;\n for (const hit of params.hits) {\n values.push(\n `($${i++}, $${i++}, $${i++}, $${i++}, $${i++}, $${i++}, $${i++}, NOW())`\n );\n args.push(\n params.agentId,\n hit.id,\n hit.path,\n params.query,\n qhash,\n hit.score,\n bucket\n );\n }\n const sql = `\n INSERT INTO ${this.table}\n (agent_id, memory_id, memory_path, query, query_hash, score, day_bucket, recorded_at)\n VALUES ${values.join(', ')}\n ON CONFLICT (agent_id, memory_id, query_hash, day_bucket) DO UPDATE\n SET score = GREATEST(${this.table}.score, EXCLUDED.score),\n recorded_at = NOW()\n `;\n await this.pool.query(sql, args);\n }\n}\n\n/** No-op tracker — used when recall tracking is disabled or the backend isn't pgvector. */\nexport class NullRecallTracker implements RecallTracker {\n async record(): Promise<void> {}\n async migrate(): Promise<void> {}\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;AAgBG;AAkBI,MAAM,YAAY,GAAG;AAE5B,SAAS,SAAS,CAAC,KAAa,EAAA;IAC9B,OAAO,UAAU,CAAC,QAAQ;SACvB,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE;SACjC,MAAM,CAAC,KAAK;AACZ,SAAA,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;AACjB;AAEA,SAAS,SAAS,CAAC,KAAa,EAAA;AAC9B,IAAA,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC;AACzB,IAAA,MAAM,CAAC,GAAG,CAAC,CAAC,cAAc,EAAE;AAC5B,IAAA,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;AACtD,IAAA,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;AACnD,IAAA,OAAO,GAAG,CAAC,CAAA,CAAA,EAAI,CAAC,CAAA,CAAA,EAAI,GAAG,EAAE;AAC3B;MAEa,qBAAqB,CAAA;AAEb,IAAA,IAAA;AACA,IAAA,KAAA;IAFnB,WAAA,CACmB,IAAU,EACV,KAAA,GAAgB,YAAY,EAAA;QAD5B,IAAA,CAAA,IAAI,GAAJ,IAAI;QACJ,IAAA,CAAA,KAAK,GAAL,KAAK;IACrB;AAEH,IAAA,MAAM,OAAO,GAAA;;AAEX,QAAA,MAAM,IAAI,CAAC,I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AA,EAAM,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,QAAA,CAAU,CACzE;YACD,IAAI,CAAC,IAAI,CACP,MAAM,CAAC,OAAO,EACd,GAAG,CAAC,EAAE,EACN,GAAG,CAAC,IAAI,EACR,MAAM,CAAC,KAAK,EACZ,KAAK,EACL,GAAG,CAAC,KAAK,EACT,MAAM,CACP;QACH;AACA,QAAA,MAAM,GAAG,GAAG;AACI,kBAAA,EAAA,IAAI,CAAC,KAAK;;AAEf,aAAA,EAAA,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;;AAEG,iCAAA,EAAA,IAAI,CAAC,KAAK,CAAA;;KAExC;QACD,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;IAClC;AACD;AAED;MACa,iBAAiB,CAAA;IAC5B,MAAM,MAAM,GAAA,EAAmB;IAC/B,MAAM,OAAO,GAAA,EAAmB;AACjC;;;;"}
1
+ {"version":3,"file":"recallTracking.mjs","sources":["../../../src/memory/recallTracking.ts"],"sourcesContent":["/**\n * Recall tracking — Phase 2.\n *\n * Lightweight adaptation of an external recall-tracking module\n * `extensions/memory-core/src/short-term-promotion.ts::recordShortTermRecalls`.\n * The reference implementation stores recalls in a JSON file under `memory/.dreams/`; we store\n * them in a Postgres table `agent_memory_recalls`. Schema captures what the\n * future Phase 3 dreaming/promotion algorithm will need:\n * - which memory row was surfaced (`memory_id`)\n * - the query that surfaced it (raw + SHA-256 hash for dedupe)\n * - hybrid score at the time of recall\n * - the day bucket (for per-day dedupe / frequency counting)\n * - the recorded timestamp\n *\n * Best-effort: failures never block memory_search. The caller fires\n * {@link RecallTracker.record} without awaiting the result and ignores errors.\n */\nimport { createHash } from 'crypto';\nimport type { Pool } from 'pg';\n\nexport interface RecallTracker {\n /** Record that the given memory ids were surfaced to the model for a query. */\n record(params: RecallRecordParams): Promise<void>;\n /** Backend-specific schema migration. Idempotent. */\n migrate(): Promise<void>;\n}\n\nexport interface RecallRecordParams {\n agentId: string;\n query: string;\n hits: Array<{ id: string; path: string; score: number }>;\n nowMs?: number;\n}\n\nexport const RECALL_TABLE = 'agent_memory_recalls';\n\nfunction hashQuery(query: string): string {\n return createHash('sha256')\n .update(query.trim().toLowerCase())\n .digest('hex')\n .slice(0, 32);\n}\n\nfunction dayBucket(nowMs: number): string {\n const d = new Date(nowMs);\n const y = d.getUTCFullYear();\n const m = String(d.getUTCMonth() + 1).padStart(2, '0');\n const day = String(d.getUTCDate()).padStart(2, '0');\n return `${y}-${m}-${day}`;\n}\n\nexport class PgvectorRecallTracker implements RecallTracker {\n constructor(\n private readonly pool: Pool,\n private readonly table: string = RECALL_TABLE\n ) {}\n\n async migrate(): Promise<void> {\n // [recall-tracking] debug: create table + indexes if missing\n await this.pool.query(`\n CREATE TABLE IF NOT EXISTS ${this.table} (\n id BIGSERIAL PRIMARY KEY,\n agent_id TEXT NOT NULL,\n memory_id TEXT NOT NULL,\n memory_path TEXT NOT NULL,\n query TEXT NOT NULL,\n query_hash TEXT NOT NULL,\n score DOUBLE PRECISION NOT NULL,\n day_bucket TEXT NOT NULL,\n recorded_at TIMESTAMPTZ NOT NULL DEFAULT NOW()\n )\n `);\n await this.pool.query(\n `CREATE INDEX IF NOT EXISTS ${this.table}_agent_day_idx ON ${this.table} (agent_id, day_bucket)`\n );\n await this.pool.query(\n `CREATE INDEX IF NOT EXISTS ${this.table}_memory_idx ON ${this.table} (agent_id, memory_id)`\n );\n await this.pool.query(\n `CREATE UNIQUE INDEX IF NOT EXISTS ${this.table}_dedupe_idx\n ON ${this.table} (agent_id, memory_id, query_hash, day_bucket)`\n );\n }\n\n async record(params: RecallRecordParams): Promise<void> {\n if (!params.agentId || !params.query.trim() || params.hits.length === 0)\n return;\n const nowMs = params.nowMs ?? Date.now();\n const qhash = hashQuery(params.query);\n const bucket = dayBucket(nowMs);\n\n // [recall-tracking] debug: upsert one row per (agent, memory, query, day)\n // The reference implementation dedupes per-day per-query so repeated searches don't inflate counts.\n const values: string[] = [];\n const args: unknown[] = [];\n let i = 1;\n for (const hit of params.hits) {\n values.push(\n `($${i++}, $${i++}, $${i++}, $${i++}, $${i++}, $${i++}, $${i++}, NOW())`\n );\n args.push(\n params.agentId,\n hit.id,\n hit.path,\n params.query,\n qhash,\n hit.score,\n bucket\n );\n }\n const sql = `\n INSERT INTO ${this.table}\n (agent_id, memory_id, memory_path, query, query_hash, score, day_bucket, recorded_at)\n VALUES ${values.join(', ')}\n ON CONFLICT (agent_id, memory_id, query_hash, day_bucket) DO UPDATE\n SET score = GREATEST(${this.table}.score, EXCLUDED.score),\n recorded_at = NOW()\n `;\n await this.pool.query(sql, args);\n }\n}\n\n/** No-op tracker — used when recall tracking is disabled or the backend isn't pgvector. */\nexport class NullRecallTracker implements RecallTracker {\n async record(): Promise<void> {}\n async migrate(): Promise<void> {}\n}\n"],"names":[],"mappings":";;AAAA;;;;;;;;;;;;;;;;AAgBG;AAkBI,MAAM,YAAY,GAAG;AAE5B,SAAS,SAAS,CAAC,KAAa,EAAA;IAC9B,OAAO,UAAU,CAAC,QAAQ;SACvB,MAAM,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE;SACjC,MAAM,CAAC,KAAK;AACZ,SAAA,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC;AACjB;AAEA,SAAS,SAAS,CAAC,KAAa,EAAA;AAC9B,IAAA,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC;AACzB,IAAA,MAAM,CAAC,GAAG,CAAC,CAAC,cAAc,EAAE;AAC5B,IAAA,MAAM,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC;AACtD,IAAA,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,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,MAAM,MAAM,GAAG,SAAS,CAAC,KAAK,CAAC;;;QAI/B,MAAM,MAAM,GAAa,EAAE;QAC3B,MAAM,IAAI,GAAc,EAAE;QAC1B,IAAI,CAAC,GAAG,CAAC;AACT,QAAA,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,EAAE;YAC7B,MAAM,CAAC,IAAI,CACT,CAAA,EAAA,EAAK,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,GAAA,EAAM,CAAC,EAAE,CAAA,QAAA,CAAU,CACzE;YACD,IAAI,CAAC,IAAI,CACP,MAAM,CAAC,OAAO,EACd,GAAG,CAAC,EAAE,EACN,GAAG,CAAC,IAAI,EACR,MAAM,CAAC,KAAK,EACZ,KAAK,EACL,GAAG,CAAC,KAAK,EACT,MAAM,CACP;QACH;AACA,QAAA,MAAM,GAAG,GAAG;AACI,kBAAA,EAAA,IAAI,CAAC,KAAK;;AAEf,aAAA,EAAA,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC;;AAEG,iCAAA,EAAA,IAAI,CAAC,KAAK,CAAA;;KAExC;QACD,MAAM,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC;IAClC;AACD;AAED;MACa,iBAAiB,CAAA;IAC5B,MAAM,MAAM,GAAA,EAAmB;IAC/B,MAAM,OAAO,GAAA,EAAmB;AACjC;;;;"}
@@ -1,14 +1,14 @@
1
1
  /**
2
2
  * Temporal decay — Phase 2.
3
3
  *
4
- * Ported from upstream `extensions/memory-core/src/memory/temporal-decay.ts`.
4
+ * Ported from a reference implementation `extensions/memory-core/src/memory/temporal-decay.ts`.
5
5
  * Ages dated memory files (`memory/YYYY-MM-DD.md`) using exponential decay
6
6
  * `multiplier = exp(-ln(2) / halfLifeDays * ageInDays)`. At half-life, the
7
7
  * score is exactly halved.
8
8
  *
9
9
  * Evergreen files (MEMORY.md, memory/topics.md, any non-dated file inside
10
10
  * memory/) do NOT decay — they represent durable knowledge and should stay
11
- * hot regardless of age. This mirrors upstream's `isEvergreenMemoryPath`.
11
+ * hot regardless of age. This mirrors the standard `isEvergreenMemoryPath`.
12
12
  *
13
13
  * Since our pgvector rows carry `createdAt`, we don't need filesystem stat
14
14
  * fallback — the row timestamp is authoritative for any file without a
@@ -1 +1 @@
1
- {"version":3,"file":"temporalDecay.mjs","sources":["../../../src/memory/temporalDecay.ts"],"sourcesContent":["/**\n * Temporal decay — Phase 2.\n *\n * Ported from upstream `extensions/memory-core/src/memory/temporal-decay.ts`.\n * Ages dated memory files (`memory/YYYY-MM-DD.md`) using exponential decay\n * `multiplier = exp(-ln(2) / halfLifeDays * ageInDays)`. At half-life, the\n * score is exactly halved.\n *\n * Evergreen files (MEMORY.md, memory/topics.md, any non-dated file inside\n * memory/) do NOT decay — they represent durable knowledge and should stay\n * hot regardless of age. This mirrors upstream's `isEvergreenMemoryPath`.\n *\n * Since our pgvector rows carry `createdAt`, we don't need filesystem stat\n * fallback — the row timestamp is authoritative for any file without a\n * date in the path.\n */\n\nexport interface TemporalDecayConfig {\n enabled: boolean;\n halfLifeDays: number;\n}\n\nexport const DEFAULT_TEMPORAL_DECAY_CONFIG: TemporalDecayConfig = {\n enabled: false,\n halfLifeDays: 30,\n};\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\nconst DATED_MEMORY_PATH_RE = /(?:^|\\/)memory\\/(\\d{4})-(\\d{2})-(\\d{2})\\.md$/;\n\nexport function toDecayLambda(halfLifeDays: number): number {\n if (!Number.isFinite(halfLifeDays) || halfLifeDays <= 0) return 0;\n return Math.LN2 / halfLifeDays;\n}\n\nexport function calculateTemporalDecayMultiplier(params: {\n ageInDays: number;\n halfLifeDays: number;\n}): number {\n const lambda = toDecayLambda(params.halfLifeDays);\n const age = Math.max(0, params.ageInDays);\n if (lambda <= 0 || !Number.isFinite(age)) return 1;\n return Math.exp(-lambda * age);\n}\n\nexport function applyTemporalDecayToScore(params: {\n score: number;\n ageInDays: number;\n halfLifeDays: number;\n}): number {\n return params.score * calculateTemporalDecayMultiplier(params);\n}\n\nfunction normalizePath(p: string): string {\n return (p ?? '').replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Parse a date out of `memory/YYYY-MM-DD.md` — returns null on non-match or invalid date. */\nexport function parseMemoryDateFromPath(filePath: string): Date | null {\n const m = DATED_MEMORY_PATH_RE.exec(normalizePath(filePath));\n if (!m) return null;\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n if (!Number.isInteger(y) || !Number.isInteger(mo) || !Number.isInteger(d))\n return null;\n const ts = Date.UTC(y, mo - 1, d);\n const parsed = new Date(ts);\n if (\n parsed.getUTCFullYear() !== y ||\n parsed.getUTCMonth() !== mo - 1 ||\n parsed.getUTCDate() !== d\n ) {\n return null;\n }\n return parsed;\n}\n\n/**\n * Evergreen = durable knowledge file that should not decay.\n * - `MEMORY.md` / `memory.md` at root\n * - anything inside `memory/` that is NOT a dated `YYYY-MM-DD.md` file\n */\nexport function isEvergreenMemoryPath(filePath: string): boolean {\n const n = normalizePath(filePath);\n if (n === 'MEMORY.md' || n === 'memory.md') return true;\n if (!n.startsWith('memory/')) return false;\n return !DATED_MEMORY_PATH_RE.test(n);\n}\n\nfunction ageInDays(timestamp: Date, nowMs: number): number {\n return Math.max(0, nowMs - timestamp.getTime()) / DAY_MS;\n}\n\nexport interface DecayCandidate {\n path: string;\n score: number;\n createdAt?: Date;\n}\n\n/**\n * Apply temporal decay to a list of memory hits.\n *\n * Priority for the effective timestamp:\n * 1. Dated path (`memory/YYYY-MM-DD.md`) — use the date in the path\n * 2. Otherwise, if the path is evergreen — NO decay\n * 3. Otherwise, use the row's `createdAt`\n */\nexport function applyTemporalDecayToHits<T extends DecayCandidate>(\n hits: T[],\n config: Partial<TemporalDecayConfig> = {},\n nowMs: number = Date.now()\n): T[] {\n const merged = { ...DEFAULT_TEMPORAL_DECAY_CONFIG, ...config };\n if (!merged.enabled) return [...hits];\n\n return hits.map((h) => {\n const datedTs = parseMemoryDateFromPath(h.path);\n let ts: Date | null = datedTs;\n if (!ts) {\n if (isEvergreenMemoryPath(h.path)) return h;\n ts = h.createdAt ?? null;\n }\n if (!ts) return h;\n return {\n ...h,\n score: applyTemporalDecayToScore({\n score: h.score,\n ageInDays: ageInDays(ts, nowMs),\n halfLifeDays: merged.halfLifeDays,\n }),\n };\n });\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;AAeG;AAOI,MAAM,6BAA6B,GAAwB;AAChE,IAAA,OAAO,EAAE,KAAK;AACd,IAAA,YAAY,EAAE,EAAE;;AAGlB,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;AAClC,MAAM,oBAAoB,GAAG,8CAA8C;AAErE,SAAU,aAAa,CAAC,YAAoB,EAAA;IAChD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,YAAY,IAAI,CAAC;AAAE,QAAA,OAAO,CAAC;AACjE,IAAA,OAAO,IAAI,CAAC,GAAG,GAAG,YAAY;AAChC;AAEM,SAAU,gCAAgC,CAAC,MAGhD,EAAA;IACC,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,YAAY,CAAC;AACjD,IAAA,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC;IACzC,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;AAAE,QAAA,OAAO,CAAC;IAClD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,GAAG,CAAC;AAChC;AAEM,SAAU,yBAAyB,CAAC,MAIzC,EAAA;IACC,OAAO,MAAM,CAAC,KAAK,GAAG,gCAAgC,CAA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AC;gBAC/B,YAAY,EAAE,MAAM,CAAC,YAAY;aAClC,CAAC;SACH;AACH,IAAA,CAAC,CAAC;AACJ;;;;"}
1
+ {"version":3,"file":"temporalDecay.mjs","sources":["../../../src/memory/temporalDecay.ts"],"sourcesContent":["/**\n * Temporal decay — Phase 2.\n *\n * Ported from a reference implementation `extensions/memory-core/src/memory/temporal-decay.ts`.\n * Ages dated memory files (`memory/YYYY-MM-DD.md`) using exponential decay\n * `multiplier = exp(-ln(2) / halfLifeDays * ageInDays)`. At half-life, the\n * score is exactly halved.\n *\n * Evergreen files (MEMORY.md, memory/topics.md, any non-dated file inside\n * memory/) do NOT decay — they represent durable knowledge and should stay\n * hot regardless of age. This mirrors the standard `isEvergreenMemoryPath`.\n *\n * Since our pgvector rows carry `createdAt`, we don't need filesystem stat\n * fallback — the row timestamp is authoritative for any file without a\n * date in the path.\n */\n\nexport interface TemporalDecayConfig {\n enabled: boolean;\n halfLifeDays: number;\n}\n\nexport const DEFAULT_TEMPORAL_DECAY_CONFIG: TemporalDecayConfig = {\n enabled: false,\n halfLifeDays: 30,\n};\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\nconst DATED_MEMORY_PATH_RE = /(?:^|\\/)memory\\/(\\d{4})-(\\d{2})-(\\d{2})\\.md$/;\n\nexport function toDecayLambda(halfLifeDays: number): number {\n if (!Number.isFinite(halfLifeDays) || halfLifeDays <= 0) return 0;\n return Math.LN2 / halfLifeDays;\n}\n\nexport function calculateTemporalDecayMultiplier(params: {\n ageInDays: number;\n halfLifeDays: number;\n}): number {\n const lambda = toDecayLambda(params.halfLifeDays);\n const age = Math.max(0, params.ageInDays);\n if (lambda <= 0 || !Number.isFinite(age)) return 1;\n return Math.exp(-lambda * age);\n}\n\nexport function applyTemporalDecayToScore(params: {\n score: number;\n ageInDays: number;\n halfLifeDays: number;\n}): number {\n return params.score * calculateTemporalDecayMultiplier(params);\n}\n\nfunction normalizePath(p: string): string {\n return (p ?? '').replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Parse a date out of `memory/YYYY-MM-DD.md` — returns null on non-match or invalid date. */\nexport function parseMemoryDateFromPath(filePath: string): Date | null {\n const m = DATED_MEMORY_PATH_RE.exec(normalizePath(filePath));\n if (!m) return null;\n const y = Number(m[1]);\n const mo = Number(m[2]);\n const d = Number(m[3]);\n if (!Number.isInteger(y) || !Number.isInteger(mo) || !Number.isInteger(d))\n return null;\n const ts = Date.UTC(y, mo - 1, d);\n const parsed = new Date(ts);\n if (\n parsed.getUTCFullYear() !== y ||\n parsed.getUTCMonth() !== mo - 1 ||\n parsed.getUTCDate() !== d\n ) {\n return null;\n }\n return parsed;\n}\n\n/**\n * Evergreen = durable knowledge file that should not decay.\n * - `MEMORY.md` / `memory.md` at root\n * - anything inside `memory/` that is NOT a dated `YYYY-MM-DD.md` file\n */\nexport function isEvergreenMemoryPath(filePath: string): boolean {\n const n = normalizePath(filePath);\n if (n === 'MEMORY.md' || n === 'memory.md') return true;\n if (!n.startsWith('memory/')) return false;\n return !DATED_MEMORY_PATH_RE.test(n);\n}\n\nfunction ageInDays(timestamp: Date, nowMs: number): number {\n return Math.max(0, nowMs - timestamp.getTime()) / DAY_MS;\n}\n\nexport interface DecayCandidate {\n path: string;\n score: number;\n createdAt?: Date;\n}\n\n/**\n * Apply temporal decay to a list of memory hits.\n *\n * Priority for the effective timestamp:\n * 1. Dated path (`memory/YYYY-MM-DD.md`) — use the date in the path\n * 2. Otherwise, if the path is evergreen — NO decay\n * 3. Otherwise, use the row's `createdAt`\n */\nexport function applyTemporalDecayToHits<T extends DecayCandidate>(\n hits: T[],\n config: Partial<TemporalDecayConfig> = {},\n nowMs: number = Date.now()\n): T[] {\n const merged = { ...DEFAULT_TEMPORAL_DECAY_CONFIG, ...config };\n if (!merged.enabled) return [...hits];\n\n return hits.map((h) => {\n const datedTs = parseMemoryDateFromPath(h.path);\n let ts: Date | null = datedTs;\n if (!ts) {\n if (isEvergreenMemoryPath(h.path)) return h;\n ts = h.createdAt ?? null;\n }\n if (!ts) return h;\n return {\n ...h,\n score: applyTemporalDecayToScore({\n score: h.score,\n ageInDays: ageInDays(ts, nowMs),\n halfLifeDays: merged.halfLifeDays,\n }),\n };\n });\n}\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;AAeG;AAOI,MAAM,6BAA6B,GAAwB;AAChE,IAAA,OAAO,EAAE,KAAK;AACd,IAAA,YAAY,EAAE,EAAE;;AAGlB,MAAM,MAAM,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI;AAClC,MAAM,oBAAoB,GAAG,8CAA8C;AAErE,SAAU,aAAa,CAAC,YAAoB,EAAA;IAChD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,YAAY,IAAI,CAAC;AAAE,QAAA,OAAO,CAAC;AACjE,IAAA,OAAO,IAAI,CAAC,GAAG,GAAG,YAAY;AAChC;AAEM,SAAU,gCAAgC,CAAC,MAGhD,EAAA;IACC,MAAM,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,YAAY,CAAC;AACjD,IAAA,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,SAAS,CAAC;IACzC,IAAI,MAAM,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;AAAE,QAAA,OAAO,CAAC;IAClD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,GAAG,GAAG,CAAC;AAChC;AAEM,SAAU,yBAAyB,CAAC,MAIzC,EAAA;IACC,OAAO,MAAM,CAAC,KAAK,GAAG,gCAAgC,CAAC,MAAM,CAAC;AAChE;AAEA,SAAS,aAAa,CAAC,CAAS,EAAA;AAC9B,IAAA,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC;AAC3D;AAEA;AACM,SAAU,uBAAu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AAC,IAAI,CAAC,CAAC,CAAC;AACtC;AAEA,SAAS,SAAS,CAAC,SAAe,EAAE,KAAa,EAAA;AAC/C,IAAA,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC,GAAG,MAAM;AAC1D;AAQA;;;;;;;AAOG;AACG,SAAU,wBAAwB,CACtC,IAAS,EACT,MAAA,GAAuC,EAAE,EACzC,KAAA,GAAgB,IAAI,CAAC,GAAG,EAAE,EAAA;IAE1B,MAAM,MAAM,GAAG,EAAE,GAAG,6BAA6B,EAAE,GAAG,MAAM,EAAE;IAC9D,IAAI,CAAC,MAAM,CAAC,OAAO;AAAE,QAAA,OAAO,CAAC,GAAG,IAAI,CAAC;AAErC,IAAA,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAI;QACpB,MAAM,OAAO,GAAG,uBAAuB,CAAC,CAAC,CAAC,IAAI,CAAC;QAC/C,IAAI,EAAE,GAAgB,OAAO;QAC7B,IAAI,CAAC,EAAE,EAAE;AACP,YAAA,IAAI,qBAAqB,CAAC,CAAC,CAAC,IAAI,CAAC;AAAE,gBAAA,OAAO,CAAC;AAC3C,YAAA,EAAE,GAAG,CAAC,CAAC,SAAS,IAAI,IAAI;QAC1B;AACA,QAAA,IAAI,CAAC,EAAE;AAAE,YAAA,OAAO,CAAC;QACjB,OAAO;AACL,YAAA,GAAG,CAAC;YACJ,KAAK,EAAE,yBAAyB,CAAC;gBAC/B,KAAK,EAAE,CAAC,CAAC,KAAK;AACd,gBAAA,SAAS,EAAE,SAAS,CAAC,EAAE,EAAE,KAAK,CAAC;gBAC/B,YAAY,EAAE,MAAM,CAAC,YAAY;aAClC,CAAC;SACH;AACH,IAAA,CAAC,CAAC;AACJ;;;;"}
@@ -564,7 +564,7 @@ function extractSkillName(args) {
564
564
  * When SkillTool is invoked, the body is injected as a HumanMessage into LangGraph state
565
565
  * but NOT persisted to conversation history. On follow-up runs the skill body is lost.
566
566
  * Pass `skills` to reconstruct the HumanMessage at the right position after each skill
567
- * ToolMessage. Upstream PRs #96 / #97.
567
+ * ToolMessage. PRs #96 / #97.
568
568
  * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.
569
569
  */
570
570
  const formatAgentMessages = (payload, indexTokenCountMap, tools, skills, options) => {
@@ -645,7 +645,7 @@ const formatAgentMessages = (payload, indexTokenCountMap, tools, skills, options
645
645
  if (discoveredTools.has(toolName)) {
646
646
  /** Valid tool - keep it */
647
647
  filteredContent.push(part);
648
- // Skill body reconstruction (upstream PRs #96/#97): when a
648
+ // Skill body reconstruction (PRs #96/#97): when a
649
649
  // SkillTool tool_call is present in this assistant turn, mark
650
650
  // the skill name so we can reconstruct the body HumanMessage
651
651
  // after the assistant turn has been pushed.
@@ -737,7 +737,7 @@ const formatAgentMessages = (payload, indexTokenCountMap, tools, skills, options
737
737
  messages.push(...formattedMessages);
738
738
  // Capture index range BEFORE skill body injection so injected
739
739
  // HumanMessages are excluded from the assistant's token distribution
740
- // (upstream PR #97 fix).
740
+ // (PR #97 fix).
741
741
  const endMessageIndex = messages.length;
742
742
  if (pendingSkillNames?.size) {
743
743
  for (const skillName of pendingSkillNames) {
@@ -1 +1 @@
1
- {"version":3,"file":"format.mjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ExtendedMessageContent,\n MessageContentComplex,\n ReasoningContentText,\n ToolCallContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport { Providers, ContentTypes, Constants } from '@/common';\nimport { processToolOutput } from '@/utils/toonFormat';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | HumanMessage\n | AIMessage\n | SystemMessage => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\n/* DeepSeek reasoning roundtrip: when active, accumulate reasoning text\n * from THINK/THINKING/REASONING blocks and attach to the next AI message\n * as `additional_kwargs.reasoning_content` so it survives multi-turn\n * replays through the OpenAI-compatible DeepSeek API. Upstream PR #136. */\ninterface FormatAssistantMessageOptions {\n preserveReasoningContent?: boolean;\n}\n\ninterface FormatAgentMessagesOptions {\n provider?: Providers;\n}\n\nfunction extractReasoningContent(\n part: MessageContentComplex | undefined | null\n): string {\n if (part == null || typeof part !== 'object') return '';\n if (part.type === ContentTypes.THINK) {\n const think = (part as ReasoningContentText).think;\n return typeof think === 'string' ? think : '';\n }\n if (part.type === ContentTypes.THINKING) {\n const thinking = (part as { thinking?: string }).thinking;\n return typeof thinking === 'string' ? thinking : '';\n }\n if (part.type === ContentTypes.REASONING) {\n const reasoning = (part as { reasoning?: string }).reasoning;\n return typeof reasoning === 'string' ? reasoning : '';\n }\n if (part.type === ContentTypes.REASONING_CONTENT) {\n /* Bedrock/Google nested shape: { reasoningContent: { text: ... } } */\n const nested = (part as { reasoningContent?: { text?: string } })\n .reasoningContent;\n if (nested && typeof nested.text === 'string') return nested.text;\n }\n return '';\n}\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @param options Optional formatting options (e.g. DeepSeek reasoning roundtrip)\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>,\n options?: FormatAssistantMessageOptions\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n let pendingReasoningContent = '';\n const shouldPreserveReasoningContent =\n options?.preserveReasoningContent === true;\n\n const takePendingReasoningContent = (): string | undefined => {\n if (!shouldPreserveReasoningContent || !pendingReasoningContent) {\n return undefined;\n }\n const reasoningContent = pendingReasoningContent;\n pendingReasoningContent = '';\n return reasoningContent;\n };\n\n const createAIMessage = (\n content: string | MessageContentComplex[]\n ): AIMessage => {\n const reasoningContent = takePendingReasoningContent();\n return new AIMessage({\n content,\n ...(reasoningContent != null && {\n additional_kwargs: { reasoning_content: reasoningContent },\n }),\n });\n };\n\n const attachPendingReasoningContent = (aiMessage: AIMessage): void => {\n const reasoningContent = takePendingReasoningContent();\n if (reasoningContent == null) return;\n aiMessage.additional_kwargs.reasoning_content =\n typeof aiMessage.additional_kwargs.reasoning_content === 'string'\n ? `${aiMessage.additional_kwargs.reasoning_content}${reasoningContent}`\n : reasoningContent;\n };\n\n if (Array.isArray(message.content)) {\n for (const part of message.content as Array<\n MessageContentComplex | undefined | null\n >) {\n if (part == null) {\n continue;\n }\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = createAIMessage(content);\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = createAIMessage(\n part.text != null ? part.text : ''\n );\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = createAIMessage('');\n formattedMessages.push(lastAIMessage);\n } else {\n attachPendingReasoningContent(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n // Apply TOON compression to historical tool outputs for context efficiency\n // processToolOutput handles: JSON→TOON conversion, already-TOON detection (skip), truncation\n // Skip TOON for content_tool — its output is line-numbered source code that must stay verbatim\n // for accurate edit (str_replace) matching.\n const processedOutput =\n output != null\n ? processToolOutput(output, {\n enableToon: tool_call.name !== 'content_tool',\n }).content\n : '';\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: processedOutput,\n })\n );\n } else if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n hasReasoning = true;\n pendingReasoningContent += extractReasoningContent(part);\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE\n ) {\n continue;\n } else {\n if (\n part.type === ContentTypes.TEXT &&\n !String(part.text ?? '').trim()\n ) {\n continue;\n }\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(createAIMessage(content));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(createAIMessage(currentContent));\n }\n\n return formattedMessages;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/** Extracts tool names from a tool_search output JSON string. */\nfunction extractToolNamesFromSearchOutput(output: string): string[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{ name?: string }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /** Output may have warnings prepended, try to find JSON within it */\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const parsed: unknown = JSON.parse(jsonMatch[0]);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{\n name?: string;\n }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /* ignore */\n }\n }\n }\n return [];\n}\n\n/** Extracts the skillName from a skill tool_call's args (string or object). */\nfunction extractSkillName(args: unknown): string | undefined {\n let parsed: Record<string, unknown> | undefined;\n if (typeof args === 'string') {\n try {\n parsed = JSON.parse(args) as Record<string, unknown>;\n } catch {\n /* malformed args — skip */\n }\n } else {\n parsed = args as Record<string, unknown> | undefined;\n }\n const name = parsed?.skillName;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.\n * When SkillTool is invoked, the body is injected as a HumanMessage into LangGraph state\n * but NOT persisted to conversation history. On follow-up runs the skill body is lost.\n * Pass `skills` to reconstruct the HumanMessage at the right position after each skill\n * ToolMessage. Upstream PRs #96 / #97.\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>,\n skills?: Map<string, string>,\n options?: FormatAgentMessagesOptions\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n\n /**\n * Create a mutable copy of the tools set that can be expanded dynamically.\n * When we encounter tool_search results, we add discovered tools to this set,\n * making their subsequent tool calls valid.\n */\n const discoveredTools = tools ? new Set(tools) : undefined;\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message.content = [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ];\n }\n if (message.role !== 'assistant') {\n messages.push(\n formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage\n );\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n /**\n * If tools set is provided, process tool_calls:\n * - Keep valid tool_calls (tools in the set or dynamically discovered)\n * - Convert invalid tool_calls to string representation for context preservation\n * - Dynamically expand the set when tool_search results are encountered\n */\n let processedMessage = message;\n let pendingSkillNames: Set<string> | undefined;\n if (discoveredTools) {\n const content = message.content;\n if (content && Array.isArray(content)) {\n const filteredContent: typeof content = [];\n const invalidToolCallIds = new Set<string>();\n const invalidToolStrings: string[] = [];\n\n for (const part of content) {\n if (part.type !== ContentTypes.TOOL_CALL) {\n filteredContent.push(part);\n continue;\n }\n\n /** Skip malformed tool_call entries */\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n if (\n typeof part.tool_call?.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n continue;\n }\n\n const toolName = part.tool_call.name;\n\n /**\n * If this is a tool_search result with output, extract discovered tool names\n * and add them to the discoveredTools set for subsequent validation.\n */\n if (\n toolName === Constants.TOOL_SEARCH &&\n typeof part.tool_call.output === 'string' &&\n part.tool_call.output !== ''\n ) {\n const extracted = extractToolNamesFromSearchOutput(\n part.tool_call.output\n );\n for (const name of extracted) {\n discoveredTools.add(name);\n }\n }\n\n if (discoveredTools.has(toolName)) {\n /** Valid tool - keep it */\n filteredContent.push(part);\n // Skill body reconstruction (upstream PRs #96/#97): when a\n // SkillTool tool_call is present in this assistant turn, mark\n // the skill name so we can reconstruct the body HumanMessage\n // after the assistant turn has been pushed.\n if (toolName === Constants.SKILL_TOOL && skills?.size) {\n const skillName = extractSkillName(part.tool_call.args);\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n } else {\n /** Invalid tool - convert to string for context preservation */\n if (\n typeof part.tool_call.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n const output = part.tool_call.output ?? '';\n invalidToolStrings.push(`Tool: ${toolName}, ${output}`);\n }\n }\n\n /** Remove tool_call_ids references to invalid tools from text parts */\n if (invalidToolCallIds.size > 0) {\n for (const part of filteredContent) {\n if (\n part.type === ContentTypes.TEXT &&\n Array.isArray(part.tool_call_ids)\n ) {\n part.tool_call_ids = part.tool_call_ids.filter(\n (id: string) => !invalidToolCallIds.has(id)\n );\n if (part.tool_call_ids.length === 0) {\n delete part.tool_call_ids;\n }\n }\n }\n }\n\n /** Append invalid tool strings to the content for context preservation */\n if (invalidToolStrings.length > 0) {\n /** Find the last text part or create one */\n let lastTextPartIndex = -1;\n for (let j = filteredContent.length - 1; j >= 0; j--) {\n if (filteredContent[j].type === ContentTypes.TEXT) {\n lastTextPartIndex = j;\n break;\n }\n }\n\n const invalidToolText = invalidToolStrings.join('\\n');\n if (lastTextPartIndex >= 0) {\n const lastTextPart = filteredContent[lastTextPartIndex] as {\n type: string;\n [ContentTypes.TEXT]?: string;\n text?: string;\n };\n const existingText =\n lastTextPart[ContentTypes.TEXT] ?? lastTextPart.text ?? '';\n filteredContent[lastTextPartIndex] = {\n ...lastTextPart,\n [ContentTypes.TEXT]: existingText\n ? `${existingText}\\n${invalidToolText}`\n : invalidToolText,\n };\n } else {\n /** No text part exists, create one */\n filteredContent.push({\n type: ContentTypes.TEXT,\n [ContentTypes.TEXT]: invalidToolText,\n });\n }\n }\n\n /** Use filtered content if we made any changes */\n if (\n filteredContent.length !== content.length ||\n invalidToolStrings.length > 0\n ) {\n processedMessage = { ...message, content: filteredContent };\n }\n }\n }\n\n // When tools filtering is off, still detect skill tool_calls for body reconstruction.\n if (!discoveredTools && skills?.size) {\n const content = processedMessage.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part.type !== ContentTypes.TOOL_CALL ||\n part.tool_call?.name !== Constants.SKILL_TOOL\n ) {\n continue;\n }\n const skillName = extractSkillName(part.tool_call.args);\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n }\n }\n\n // Process the assistant message using the helper function\n const formattedMessages = formatAssistantMessage(processedMessage, {\n preserveReasoningContent: options?.provider === Providers.DEEPSEEK,\n });\n messages.push(...formattedMessages);\n\n // Capture index range BEFORE skill body injection so injected\n // HumanMessages are excluded from the assistant's token distribution\n // (upstream PR #97 fix).\n const endMessageIndex = messages.length;\n\n if (pendingSkillNames?.size) {\n for (const skillName of pendingSkillNames) {\n const body = skills?.get(skillName);\n if (body) {\n messages.push(\n new HumanMessage({\n content: body,\n additional_kwargs: {\n role: 'user',\n isMeta: true,\n source: 'skill',\n skillName,\n },\n })\n );\n }\n }\n }\n\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount === undefined) {\n continue;\n }\n\n const msgCount = resultIndices.length;\n if (msgCount === 1) {\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n continue;\n }\n\n if (msgCount < 2) {\n continue;\n }\n\n let totalLength = 0;\n const lastIdx = msgCount - 1;\n const lengths = new Array<number>(msgCount);\n for (let k = 0; k < msgCount; k++) {\n const msg = messages[resultIndices[k]];\n const { content } = msg;\n let len = 0;\n if (typeof content === 'string') {\n len = content.length;\n } else if (Array.isArray(content)) {\n for (const part of content as Array<\n Record<string, unknown> | string | undefined\n >) {\n if (typeof part === 'string') {\n len += part.length;\n } else if (part != null && typeof part === 'object') {\n const val = part.text ?? part.content;\n if (typeof val === 'string') {\n len += val.length;\n }\n }\n }\n }\n const toolCalls = (msg as AIMessage).tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const tc of toolCalls as Array<Record<string, unknown>>) {\n if (typeof tc.name === 'string') {\n len += tc.name.length;\n }\n const { args } = tc;\n if (typeof args === 'string') {\n len += args.length;\n } else if (args != null) {\n len += JSON.stringify(args).length;\n }\n }\n }\n lengths[k] = len;\n totalLength += len;\n }\n\n if (totalLength === 0) {\n const countPerMessage = Math.floor(tokenCount / msgCount);\n for (let k = 0; k < lastIdx; k++) {\n updatedIndexTokenCountMap[resultIndices[k]] = countPerMessage;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - countPerMessage * lastIdx;\n } else {\n let distributed = 0;\n for (let k = 0; k < lastIdx; k++) {\n const share = Math.floor((lengths[k] / totalLength) * tokenCount);\n updatedIndexTokenCountMap[resultIndices[k]] = share;\n distributed += share;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - distributed;\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/** Block types that contain binary image data and must be preserved structurally. */\nconst IMAGE_BLOCK_TYPES = new Set(['image_url', 'image']);\n\n/** Checks whether a BaseMessage is a tool-role message. */\nconst isToolMessage = (m: BaseMessage): boolean =>\n m instanceof ToolMessage || ('role' in m && (m as any).role === 'tool');\n\n/** Flushes accumulated text chunks into `parts` as a single text block. */\nfunction flushTextChunks(\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n if (textChunks.length === 0) {\n return;\n }\n parts.push({\n type: ContentTypes.TEXT,\n text: textChunks.join('\\n'),\n } as MessageContentComplex);\n textChunks.length = 0;\n}\n\n/**\n * Appends a single message's content to the running `textChunks` / `parts`\n * accumulators. Image blocks are shallow-copied into `parts` as-is so that\n * binary data (base64 images) never becomes text tokens. All other block\n * types are serialized to text — unrecognized types are JSON-serialized\n * rather than silently dropped.\n *\n * When `content` is an array containing tool_use blocks, `tool_calls` is NOT\n * additionally serialized (avoiding double output). `tool_calls` is used as\n * a fallback when `content` is a plain string or an array with no tool_use.\n */\nfunction appendMessageContent(\n msg: BaseMessage,\n role: string,\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n const { content } = msg;\n\n if (typeof content === 'string') {\n if (content) {\n textChunks.push(`${role}: ${content}`);\n }\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n if (!Array.isArray(content)) {\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n let hasToolUseBlock = false;\n\n for (const block of content as ExtendedMessageContent[]) {\n if (IMAGE_BLOCK_TYPES.has(block.type ?? '')) {\n flushTextChunks(textChunks, parts);\n parts.push({ ...block } as MessageContentComplex);\n continue;\n }\n\n if (block.type === 'tool_use') {\n hasToolUseBlock = true;\n textChunks.push(\n `${role}: [tool_use] ${String(block.name ?? '')} ${JSON.stringify(block.input ?? {})}`\n );\n continue;\n }\n\n const text = block.text ?? block.input;\n if (typeof text === 'string' && text) {\n textChunks.push(`${role}: ${text}`);\n continue;\n }\n\n // Fallback: serialize unrecognized block types to preserve context\n if (block.type != null && block.type !== '') {\n textChunks.push(`${role}: [${block.type}] ${JSON.stringify(block)}`);\n }\n }\n\n // If content array had no tool_use blocks, fall back to tool_calls metadata\n // (handles edge case: empty content array with tool_calls populated)\n if (!hasToolUseBlock) {\n appendToolCalls(msg, role, textChunks);\n }\n}\n\nfunction appendToolCalls(\n msg: BaseMessage,\n role: string,\n textChunks: string[]\n): void {\n if (role !== 'AI') {\n return;\n }\n const aiMsg = msg as AIMessage;\n if (!aiMsg.tool_calls || aiMsg.tool_calls.length === 0) {\n return;\n }\n for (const tc of aiMsg.tool_calls) {\n textChunks.push(`AI: [tool_call] ${tc.name}(${JSON.stringify(tc.args)})`);\n }\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers\n): BaseMessage[] {\n if (messages.length === 0) {\n return messages;\n }\n\n // If the last message is already a HumanMessage, there is no trailing tool\n // sequence to convert — return early to preserve prompt caching and avoid\n // redundant token overhead from re-processing the entire history.\n const lastMsg = messages[messages.length - 1];\n const lastIsHuman =\n lastMsg instanceof HumanMessage ||\n ('role' in lastMsg && (lastMsg as any).role === 'user');\n if (lastIsHuman) {\n return messages;\n }\n\n const result: BaseMessage[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n /** Detect AI messages by instanceof OR by role, in case cache-control cloning\n produced a plain object that lost the LangChain prototype. */\n const isAI =\n msg instanceof AIMessage ||\n msg instanceof AIMessageChunk ||\n ('role' in msg && (msg as any).role === 'assistant');\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let hasThinkingBlock = false;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n for (const c of aiMsg.content as ExtendedMessageContent[]) {\n if (typeof c !== 'object') {\n continue;\n }\n if (c.type === 'tool_use') {\n hasToolUse = true;\n } else if (\n c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking'\n ) {\n hasThinkingBlock = true;\n }\n if (hasToolUse && hasThinkingBlock) {\n break;\n }\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs (may not be in content array)\n if (\n !hasThinkingBlock &&\n aiMsg.additional_kwargs.reasoning_content != null\n ) {\n hasThinkingBlock = true;\n }\n\n // If message has tool use but no thinking block, check whether this is a\n // continuation of a thinking-enabled agent's chain before converting.\n // Bedrock reasoning models can produce multiple AI→Tool rounds after an\n // initial reasoning response: the first AI message has reasoning_content,\n // but follow-ups have content: \"\" with only tool_calls. These are the\n // same agent's turn and must NOT be converted to HumanMessages.\n if (hasToolUse && !hasThinkingBlock) {\n // Walk backwards — if an earlier AI message in the same chain (before\n // the nearest HumanMessage) has a thinking/reasoning block, this is a\n // continuation of a thinking-enabled turn, not a non-thinking handoff.\n if (chainHasThinkingBlock(messages, i)) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Build structured content in a single pass over the AI + following\n // ToolMessages — preserves image blocks as-is to avoid serializing\n // binary data as text (which caused 174× token amplification).\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = ['[Previous agent context]'];\n\n appendMessageContent(msg, 'AI', textChunks, parts);\n\n let j = i + 1;\n while (j < messages.length && isToolMessage(messages[j])) {\n appendMessageContent(messages[j], 'Tool', textChunks, parts);\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n result.push(new HumanMessage({ content: parts }));\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n\n/**\n * Walks backwards from `currentIndex` through the message array to check\n * whether an earlier AI message in the same \"chain\" (no HumanMessage boundary)\n * contains a thinking/reasoning block.\n *\n * A \"chain\" is a contiguous sequence of AI + Tool messages with no intervening\n * HumanMessage. Bedrock reasoning models produce reasoning on the first AI\n * response, then issue follow-up tool calls with `content: \"\"` and no\n * reasoning block. These follow-ups are part of the same thinking-enabled\n * turn and should not be converted.\n */\nfunction chainHasThinkingBlock(\n messages: BaseMessage[],\n currentIndex: number\n): boolean {\n for (let k = currentIndex - 1; k >= 0; k--) {\n const prev = messages[k];\n\n // HumanMessage = turn boundary — stop searching\n if (\n prev instanceof HumanMessage ||\n ('role' in prev && (prev as any).role === 'user')\n ) {\n return false;\n }\n\n // Check AI messages for thinking/reasoning blocks\n const isPrevAI =\n prev instanceof AIMessage ||\n prev instanceof AIMessageChunk ||\n ('role' in prev && (prev as any).role === 'assistant');\n\n if (isPrevAI) {\n const prevAiMsg = prev as AIMessage | AIMessageChunk;\n\n if (Array.isArray(prevAiMsg.content) && prevAiMsg.content.length > 0) {\n const content = prevAiMsg.content as ExtendedMessageContent[];\n if (\n content.some(\n (c) =>\n typeof c === 'object' &&\n (c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking')\n )\n ) {\n return true;\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs\n if (prevAiMsg.additional_kwargs.reasoning_content != null) {\n return true;\n }\n }\n\n // ToolMessages are part of the chain — keep walking back\n }\n\n return false;\n}\n"],"names":[],"mappings":";;;;;AAAA;AAkCA;;;;;AAKG;AACI,MAAM,kBAAkB,GAAG,CAAC,EACjC,OAAO,EACP,QAAQ,EACR,UAAU,GACS,KAKjB;;AAEF,IAAA,MAAM,MAAM,GAKR;AACF,QAAA,GAAG,OAAO;AACV,QAAA,OAAO,EAAE,EAA6B;KACvC;AAED,IAAA,IAAI,QAAQ,KAAK,SAAS,CAAC,SAAS,EAAE;QACpC,MAAM,CAAC,OAAO,GAAG;AACf,YAAA,GAAG,UAAU;YACb,EAAE,IAAI,EAAE,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,OAAO,EAAE;SACxB;AAC5B,QAAA,OAAO,MAAM;IACf;IAEA,MAAM,CAAC,OAAO,GAAG;QACf,EAAE,IAAI,EAAE,YAAY,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC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iB,CAAC,iBAAiB,IAAI,IAAI,EAAE;AACzD,gBAAA,OAAO,IAAI;YACb;QACF;;IAGF;AAEA,IAAA,OAAO,KAAK;AACd;;;;"}
1
+ {"version":3,"file":"format.mjs","sources":["../../../src/messages/format.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n AIMessage,\n AIMessageChunk,\n ToolMessage,\n BaseMessage,\n HumanMessage,\n SystemMessage,\n} from '@langchain/core/messages';\nimport type { MessageContentImageUrl } from '@langchain/core/messages';\nimport type { ToolCall } from '@langchain/core/messages/tool';\nimport type {\n ExtendedMessageContent,\n MessageContentComplex,\n ReasoningContentText,\n ToolCallContent,\n ToolCallPart,\n TPayload,\n TMessage,\n} from '@/types';\nimport { Providers, ContentTypes, Constants } from '@/common';\nimport { processToolOutput } from '@/utils/toonFormat';\n\ninterface MediaMessageParams {\n message: {\n role: string;\n content: string;\n name?: string;\n [key: string]: any;\n };\n mediaParts: MessageContentComplex[];\n endpoint?: Providers;\n}\n\n/**\n * Formats a message with media content (images, documents, videos, audios) to API payload format.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMediaMessage = ({\n message,\n endpoint,\n mediaParts,\n}: MediaMessageParams): {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n} => {\n // Create a new object to avoid mutating the input\n const result: {\n role: string;\n content: MessageContentComplex[];\n name?: string;\n [key: string]: any;\n } = {\n ...message,\n content: [] as MessageContentComplex[],\n };\n\n if (endpoint === Providers.ANTHROPIC) {\n result.content = [\n ...mediaParts,\n { type: ContentTypes.TEXT, text: message.content },\n ] as MessageContentComplex[];\n return result;\n }\n\n result.content = [\n { type: ContentTypes.TEXT, text: message.content },\n ...mediaParts,\n ] as MessageContentComplex[];\n\n return result;\n};\n\ninterface MessageInput {\n role?: string;\n _name?: string;\n sender?: string;\n text?: string;\n content?: string | MessageContentComplex[];\n image_urls?: MessageContentImageUrl[];\n documents?: MessageContentComplex[];\n videos?: MessageContentComplex[];\n audios?: MessageContentComplex[];\n lc_id?: string[];\n [key: string]: any;\n}\n\ninterface FormatMessageParams {\n message: MessageInput;\n userName?: string;\n assistantName?: string;\n endpoint?: Providers;\n langChain?: boolean;\n}\n\ninterface FormattedMessage {\n role: string;\n content: string | MessageContentComplex[];\n name?: string;\n [key: string]: any;\n}\n\n/**\n * Formats a message to OpenAI payload format based on the provided options.\n *\n * @param params - The parameters for formatting.\n * @returns - The formatted message.\n */\nexport const formatMessage = ({\n message,\n userName,\n endpoint,\n assistantName,\n langChain = false,\n}: FormatMessageParams):\n | FormattedMessage\n | HumanMessage\n | AIMessage\n | SystemMessage => {\n // eslint-disable-next-line prefer-const\n let { role: _role, _name, sender, text, content: _content, lc_id } = message;\n if (lc_id && lc_id[2] && !langChain) {\n const roleMapping: Record<string, string> = {\n SystemMessage: 'system',\n HumanMessage: 'user',\n AIMessage: 'assistant',\n };\n _role = roleMapping[lc_id[2]] || _role;\n }\n const role =\n _role ??\n (sender != null && sender && sender.toLowerCase() === 'user'\n ? 'user'\n : 'assistant');\n const content = _content ?? text ?? '';\n const formattedMessage: FormattedMessage = {\n role,\n content,\n };\n\n // Set name fields first\n if (_name != null && _name) {\n formattedMessage.name = _name;\n }\n\n if (userName != null && userName && formattedMessage.role === 'user') {\n formattedMessage.name = userName;\n }\n\n if (\n assistantName != null &&\n assistantName &&\n formattedMessage.role === 'assistant'\n ) {\n formattedMessage.name = assistantName;\n }\n\n if (formattedMessage.name != null && formattedMessage.name) {\n // Conform to API regex: ^[a-zA-Z0-9_-]{1,64}$\n // https://community.openai.com/t/the-format-of-the-name-field-in-the-documentation-is-incorrect/175684/2\n formattedMessage.name = formattedMessage.name.replace(\n /[^a-zA-Z0-9_-]/g,\n '_'\n );\n\n if (formattedMessage.name.length > 64) {\n formattedMessage.name = formattedMessage.name.substring(0, 64);\n }\n }\n\n const { image_urls, documents, videos, audios } = message;\n const mediaParts: MessageContentComplex[] = [];\n\n if (Array.isArray(documents) && documents.length > 0) {\n mediaParts.push(...documents);\n }\n\n if (Array.isArray(videos) && videos.length > 0) {\n mediaParts.push(...videos);\n }\n\n if (Array.isArray(audios) && audios.length > 0) {\n mediaParts.push(...audios);\n }\n\n if (Array.isArray(image_urls) && image_urls.length > 0) {\n mediaParts.push(...image_urls);\n }\n\n if (mediaParts.length > 0 && role === 'user') {\n const mediaMessage = formatMediaMessage({\n message: {\n ...formattedMessage,\n content:\n typeof formattedMessage.content === 'string'\n ? formattedMessage.content\n : '',\n },\n mediaParts,\n endpoint,\n });\n\n if (!langChain) {\n return mediaMessage;\n }\n\n return new HumanMessage(mediaMessage);\n }\n\n if (!langChain) {\n return formattedMessage;\n }\n\n if (role === 'user') {\n return new HumanMessage(formattedMessage);\n } else if (role === 'assistant') {\n return new AIMessage(formattedMessage);\n } else {\n return new SystemMessage(formattedMessage);\n }\n};\n\n/**\n * Formats an array of messages for LangChain.\n *\n * @param messages - The array of messages to format.\n * @param formatOptions - The options for formatting each message.\n * @returns - The array of formatted LangChain messages.\n */\nexport const formatLangChainMessages = (\n messages: Array<MessageInput>,\n formatOptions: Omit<FormatMessageParams, 'message' | 'langChain'>\n): Array<HumanMessage | AIMessage | SystemMessage> => {\n return messages.map((msg) => {\n const formatted = formatMessage({\n ...formatOptions,\n message: msg,\n langChain: true,\n });\n return formatted as HumanMessage | AIMessage | SystemMessage;\n });\n};\n\ninterface LangChainMessage {\n lc_kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n kwargs?: {\n additional_kwargs?: Record<string, any>;\n [key: string]: any;\n };\n [key: string]: any;\n}\n\n/**\n * Formats a LangChain message object by merging properties from `lc_kwargs` or `kwargs` and `additional_kwargs`.\n *\n * @param message - The message object to format.\n * @returns - The formatted LangChain message.\n */\nexport const formatFromLangChain = (\n message: LangChainMessage\n): Record<string, any> => {\n const kwargs = message.lc_kwargs ?? message.kwargs ?? {};\n const { additional_kwargs = {}, ...message_kwargs } = kwargs;\n return {\n ...message_kwargs,\n ...additional_kwargs,\n };\n};\n\n/* DeepSeek reasoning roundtrip: when active, accumulate reasoning text\n * from THINK/THINKING/REASONING blocks and attach to the next AI message\n * as `additional_kwargs.reasoning_content` so it survives multi-turn\n * replays through the OpenAI-compatible DeepSeek API. PR #136. */\ninterface FormatAssistantMessageOptions {\n preserveReasoningContent?: boolean;\n}\n\ninterface FormatAgentMessagesOptions {\n provider?: Providers;\n}\n\nfunction extractReasoningContent(\n part: MessageContentComplex | undefined | null\n): string {\n if (part == null || typeof part !== 'object') return '';\n if (part.type === ContentTypes.THINK) {\n const think = (part as ReasoningContentText).think;\n return typeof think === 'string' ? think : '';\n }\n if (part.type === ContentTypes.THINKING) {\n const thinking = (part as { thinking?: string }).thinking;\n return typeof thinking === 'string' ? thinking : '';\n }\n if (part.type === ContentTypes.REASONING) {\n const reasoning = (part as { reasoning?: string }).reasoning;\n return typeof reasoning === 'string' ? reasoning : '';\n }\n if (part.type === ContentTypes.REASONING_CONTENT) {\n /* Bedrock/Google nested shape: { reasoningContent: { text: ... } } */\n const nested = (part as { reasoningContent?: { text?: string } })\n .reasoningContent;\n if (nested && typeof nested.text === 'string') return nested.text;\n }\n return '';\n}\n\n/**\n * Helper function to format an assistant message\n * @param message The message to format\n * @param options Optional formatting options (e.g. DeepSeek reasoning roundtrip)\n * @returns Array of formatted messages\n */\nfunction formatAssistantMessage(\n message: Partial<TMessage>,\n options?: FormatAssistantMessageOptions\n): Array<AIMessage | ToolMessage> {\n const formattedMessages: Array<AIMessage | ToolMessage> = [];\n let currentContent: MessageContentComplex[] = [];\n let lastAIMessage: AIMessage | null = null;\n let hasReasoning = false;\n let pendingReasoningContent = '';\n const shouldPreserveReasoningContent =\n options?.preserveReasoningContent === true;\n\n const takePendingReasoningContent = (): string | undefined => {\n if (!shouldPreserveReasoningContent || !pendingReasoningContent) {\n return undefined;\n }\n const reasoningContent = pendingReasoningContent;\n pendingReasoningContent = '';\n return reasoningContent;\n };\n\n const createAIMessage = (\n content: string | MessageContentComplex[]\n ): AIMessage => {\n const reasoningContent = takePendingReasoningContent();\n return new AIMessage({\n content,\n ...(reasoningContent != null && {\n additional_kwargs: { reasoning_content: reasoningContent },\n }),\n });\n };\n\n const attachPendingReasoningContent = (aiMessage: AIMessage): void => {\n const reasoningContent = takePendingReasoningContent();\n if (reasoningContent == null) return;\n aiMessage.additional_kwargs.reasoning_content =\n typeof aiMessage.additional_kwargs.reasoning_content === 'string'\n ? `${aiMessage.additional_kwargs.reasoning_content}${reasoningContent}`\n : reasoningContent;\n };\n\n if (Array.isArray(message.content)) {\n for (const part of message.content as Array<\n MessageContentComplex | undefined | null\n >) {\n if (part == null) {\n continue;\n }\n if (part.type === ContentTypes.TEXT && part.tool_call_ids) {\n /*\n If there's pending content, it needs to be aggregated as a single string to prepare for tool calls.\n For Anthropic models, the \"tool_calls\" field on a message is only respected if content is a string.\n */\n if (currentContent.length > 0) {\n let content = currentContent.reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '');\n content =\n `${content}\\n${part[ContentTypes.TEXT] ?? part.text ?? ''}`.trim();\n lastAIMessage = createAIMessage(content);\n formattedMessages.push(lastAIMessage);\n currentContent = [];\n continue;\n }\n // Create a new AIMessage with this text and prepare for tool calls\n lastAIMessage = createAIMessage(\n part.text != null ? part.text : ''\n );\n formattedMessages.push(lastAIMessage);\n } else if (part.type === ContentTypes.TOOL_CALL) {\n // Skip malformed tool call entries without tool_call property\n if (part.tool_call == null) {\n continue;\n }\n\n // Note: `tool_calls` list is defined when constructed by `AIMessage` class, and outputs should be excluded from it\n const {\n output,\n args: _args,\n ..._tool_call\n } = part.tool_call as ToolCallPart;\n\n // Skip invalid tool calls that have no name AND no output\n if (\n _tool_call.name == null ||\n (_tool_call.name === '' && (output == null || output === ''))\n ) {\n continue;\n }\n\n if (!lastAIMessage) {\n // \"Heal\" the payload by creating an AIMessage to precede the tool call\n lastAIMessage = createAIMessage('');\n formattedMessages.push(lastAIMessage);\n } else {\n attachPendingReasoningContent(lastAIMessage);\n }\n\n const tool_call: ToolCallPart = _tool_call;\n // TODO: investigate; args as dictionary may need to be providers-or-tool-specific\n let args: any = _args;\n try {\n if (typeof _args === 'string') {\n args = JSON.parse(_args);\n }\n } catch {\n if (typeof _args === 'string') {\n args = { input: _args };\n }\n }\n\n tool_call.args = args;\n if (!lastAIMessage.tool_calls) {\n lastAIMessage.tool_calls = [];\n }\n lastAIMessage.tool_calls.push(tool_call as ToolCall);\n\n // Apply TOON compression to historical tool outputs for context efficiency\n // processToolOutput handles: JSON→TOON conversion, already-TOON detection (skip), truncation\n // Skip TOON for content_tool — its output is line-numbered source code that must stay verbatim\n // for accurate edit (str_replace) matching.\n const processedOutput =\n output != null\n ? processToolOutput(output, {\n enableToon: tool_call.name !== 'content_tool',\n }).content\n : '';\n\n formattedMessages.push(\n new ToolMessage({\n tool_call_id: tool_call.id ?? '',\n name: tool_call.name,\n content: processedOutput,\n })\n );\n } else if (\n part.type === ContentTypes.THINK ||\n part.type === ContentTypes.THINKING ||\n part.type === ContentTypes.REASONING ||\n part.type === ContentTypes.REASONING_CONTENT ||\n part.type === 'redacted_thinking'\n ) {\n hasReasoning = true;\n pendingReasoningContent += extractReasoningContent(part);\n continue;\n } else if (\n part.type === ContentTypes.ERROR ||\n part.type === ContentTypes.AGENT_UPDATE\n ) {\n continue;\n } else {\n if (\n part.type === ContentTypes.TEXT &&\n !String(part.text ?? '').trim()\n ) {\n continue;\n }\n currentContent.push(part);\n }\n }\n }\n\n if (hasReasoning && currentContent.length > 0) {\n const content = currentContent\n .reduce((acc, curr) => {\n if (curr.type === ContentTypes.TEXT) {\n return `${acc}${String(curr[ContentTypes.TEXT] ?? '')}\\n`;\n }\n return acc;\n }, '')\n .trim();\n\n if (content) {\n formattedMessages.push(createAIMessage(content));\n }\n } else if (currentContent.length > 0) {\n formattedMessages.push(createAIMessage(currentContent));\n }\n\n return formattedMessages;\n}\n\n/**\n * Labels all agent content for parallel patterns (fan-out/fan-in)\n * Groups consecutive content by agent and wraps with clear labels\n */\nfunction labelAllAgentContent(\n contentParts: MessageContentComplex[],\n agentIdMap: Record<number, string>,\n agentNames?: Record<string, string>\n): MessageContentComplex[] {\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n if (currentAgentId != null && currentAgentId !== '') {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n const thinkContent = (part as ReasoningContentText).think || '';\n if (thinkContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: thinkContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(`${agentName}: ${textContent}`);\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} ---`);\n\n // Create a single text content part with all agent content\n result.push({\n type: ContentTypes.TEXT,\n text: formattedParts.join('\\n\\n'),\n } as MessageContentComplex);\n } else {\n // No agent ID, pass through as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n agentContentBuffer.push(part);\n }\n\n // Flush any remaining content\n flushAgentBuffer();\n\n return result;\n}\n\n/**\n * Groups content parts by agent and formats them with agent labels\n * This preprocesses multi-agent content to prevent identity confusion\n *\n * @param contentParts - The content parts from a run\n * @param agentIdMap - Map of content part index to agent ID\n * @param agentNames - Optional map of agent ID to display name\n * @param options - Configuration options\n * @param options.labelNonTransferContent - If true, labels all agent transitions (for parallel patterns)\n * @returns Modified content parts with agent labels where appropriate\n */\nexport const labelContentByAgent = (\n contentParts: MessageContentComplex[],\n agentIdMap?: Record<number, string>,\n agentNames?: Record<string, string>,\n options?: { labelNonTransferContent?: boolean }\n): MessageContentComplex[] => {\n if (!agentIdMap || Object.keys(agentIdMap).length === 0) {\n return contentParts;\n }\n\n // If labelNonTransferContent is true, use a different strategy for parallel patterns\n if (options?.labelNonTransferContent === true) {\n return labelAllAgentContent(contentParts, agentIdMap, agentNames);\n }\n\n const result: MessageContentComplex[] = [];\n let currentAgentId: string | undefined;\n let agentContentBuffer: MessageContentComplex[] = [];\n let transferToolCallIndex: number | undefined;\n let transferToolCallId: string | undefined;\n\n const flushAgentBuffer = (): void => {\n if (agentContentBuffer.length === 0) {\n return;\n }\n\n // If this is content from a transferred agent, format it specially\n if (\n currentAgentId != null &&\n currentAgentId !== '' &&\n transferToolCallIndex !== undefined\n ) {\n const agentName = (agentNames?.[currentAgentId] ?? '') || currentAgentId;\n const formattedParts: string[] = [];\n\n formattedParts.push(`--- Transfer to ${agentName} ---`);\n\n for (const part of agentContentBuffer) {\n if (part.type === ContentTypes.THINK) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'think',\n think: (part as ReasoningContentText).think,\n })}`\n );\n } else if ('text' in part && part.type === ContentTypes.TEXT) {\n const textContent: string = part.text ?? '';\n if (textContent) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'text',\n text: textContent,\n })}`\n );\n }\n } else if (part.type === ContentTypes.TOOL_CALL) {\n formattedParts.push(\n `${agentName}: ${JSON.stringify({\n type: 'tool_call',\n tool_call: (part as ToolCallContent).tool_call,\n })}`\n );\n }\n }\n\n formattedParts.push(`--- End of ${agentName} response ---`);\n\n // Find the tool call that triggered this transfer and update its output\n if (transferToolCallIndex < result.length) {\n const transferToolCall = result[transferToolCallIndex];\n if (\n transferToolCall.type === ContentTypes.TOOL_CALL &&\n transferToolCall.tool_call?.id === transferToolCallId\n ) {\n transferToolCall.tool_call.output = formattedParts.join('\\n\\n');\n }\n }\n } else {\n // Not from a transfer, add as-is\n result.push(...agentContentBuffer);\n }\n\n agentContentBuffer = [];\n transferToolCallIndex = undefined;\n transferToolCallId = undefined;\n };\n\n for (let i = 0; i < contentParts.length; i++) {\n const part = contentParts[i];\n const agentId = agentIdMap[i];\n\n // Check if this is a transfer tool call\n const isTransferTool =\n (part.type === ContentTypes.TOOL_CALL &&\n (part as ToolCallContent).tool_call?.name?.startsWith(\n 'lc_transfer_to_'\n )) ??\n false;\n\n // If agent changed, flush previous buffer\n if (agentId !== currentAgentId && currentAgentId !== undefined) {\n flushAgentBuffer();\n }\n\n currentAgentId = agentId;\n\n if (isTransferTool) {\n // Flush any existing buffer first\n flushAgentBuffer();\n // Add the transfer tool call to result\n result.push(part);\n // Mark that the next agent's content should be captured\n transferToolCallIndex = result.length - 1;\n transferToolCallId = (part as ToolCallContent).tool_call?.id;\n currentAgentId = undefined; // Reset to capture the next agent\n } else {\n agentContentBuffer.push(part);\n }\n }\n\n flushAgentBuffer();\n\n return result;\n};\n\n/** Extracts tool names from a tool_search output JSON string. */\nfunction extractToolNamesFromSearchOutput(output: string): string[] {\n try {\n const parsed: unknown = JSON.parse(output);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{ name?: string }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /** Output may have warnings prepended, try to find JSON within it */\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n try {\n const parsed: unknown = JSON.parse(jsonMatch[0]);\n if (\n typeof parsed === 'object' &&\n parsed !== null &&\n Array.isArray((parsed as Record<string, unknown>).tools)\n ) {\n return (\n (parsed as Record<string, unknown>).tools as Array<{\n name?: string;\n }>\n )\n .map((t) => t.name)\n .filter((name): name is string => typeof name === 'string');\n }\n } catch {\n /* ignore */\n }\n }\n }\n return [];\n}\n\n/** Extracts the skillName from a skill tool_call's args (string or object). */\nfunction extractSkillName(args: unknown): string | undefined {\n let parsed: Record<string, unknown> | undefined;\n if (typeof args === 'string') {\n try {\n parsed = JSON.parse(args) as Record<string, unknown>;\n } catch {\n /* malformed args — skip */\n }\n } else {\n parsed = args as Record<string, unknown> | undefined;\n }\n const name = parsed?.skillName;\n return typeof name === 'string' && name !== '' ? name : undefined;\n}\n\n/**\n * Formats an array of messages for LangChain, handling tool calls and creating ToolMessage instances.\n *\n * @param payload - The array of messages to format.\n * @param indexTokenCountMap - Optional map of message indices to token counts.\n * @param tools - Optional set of tool names that are allowed in the request.\n * @param skills - Optional map of skill name to body for reconstructing skill HumanMessages.\n * When SkillTool is invoked, the body is injected as a HumanMessage into LangGraph state\n * but NOT persisted to conversation history. On follow-up runs the skill body is lost.\n * Pass `skills` to reconstruct the HumanMessage at the right position after each skill\n * ToolMessage. PRs #96 / #97.\n * @returns - Object containing formatted messages and updated indexTokenCountMap if provided.\n */\nexport const formatAgentMessages = (\n payload: TPayload,\n indexTokenCountMap?: Record<number, number | undefined>,\n tools?: Set<string>,\n skills?: Map<string, string>,\n options?: FormatAgentMessagesOptions\n): {\n messages: Array<HumanMessage | AIMessage | SystemMessage | ToolMessage>;\n indexTokenCountMap?: Record<number, number>;\n} => {\n const messages: Array<\n HumanMessage | AIMessage | SystemMessage | ToolMessage\n > = [];\n // If indexTokenCountMap is provided, create a new map to track the updated indices\n const updatedIndexTokenCountMap: Record<number, number> = {};\n // Keep track of the mapping from original payload indices to result indices\n const indexMapping: Record<number, number[] | undefined> = {};\n\n /**\n * Create a mutable copy of the tools set that can be expanded dynamically.\n * When we encounter tool_search results, we add discovered tools to this set,\n * making their subsequent tool calls valid.\n */\n const discoveredTools = tools ? new Set(tools) : undefined;\n\n // Process messages with tool conversion if tools set is provided\n for (let i = 0; i < payload.length; i++) {\n const message = payload[i];\n // Q: Store the current length of messages to track where this payload message starts in the result?\n // const startIndex = messages.length;\n if (typeof message.content === 'string') {\n message.content = [\n { type: ContentTypes.TEXT, [ContentTypes.TEXT]: message.content },\n ];\n }\n if (message.role !== 'assistant') {\n messages.push(\n formatMessage({\n message: message as MessageInput,\n langChain: true,\n }) as HumanMessage | AIMessage | SystemMessage\n );\n\n // Update the index mapping for this message\n indexMapping[i] = [messages.length - 1];\n continue;\n }\n\n // For assistant messages, track the starting index before processing\n const startMessageIndex = messages.length;\n\n /**\n * If tools set is provided, process tool_calls:\n * - Keep valid tool_calls (tools in the set or dynamically discovered)\n * - Convert invalid tool_calls to string representation for context preservation\n * - Dynamically expand the set when tool_search results are encountered\n */\n let processedMessage = message;\n let pendingSkillNames: Set<string> | undefined;\n if (discoveredTools) {\n const content = message.content;\n if (content && Array.isArray(content)) {\n const filteredContent: typeof content = [];\n const invalidToolCallIds = new Set<string>();\n const invalidToolStrings: string[] = [];\n\n for (const part of content) {\n if (part.type !== ContentTypes.TOOL_CALL) {\n filteredContent.push(part);\n continue;\n }\n\n /** Skip malformed tool_call entries */\n if (\n part.tool_call == null ||\n part.tool_call.name == null ||\n part.tool_call.name === ''\n ) {\n if (\n typeof part.tool_call?.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n continue;\n }\n\n const toolName = part.tool_call.name;\n\n /**\n * If this is a tool_search result with output, extract discovered tool names\n * and add them to the discoveredTools set for subsequent validation.\n */\n if (\n toolName === Constants.TOOL_SEARCH &&\n typeof part.tool_call.output === 'string' &&\n part.tool_call.output !== ''\n ) {\n const extracted = extractToolNamesFromSearchOutput(\n part.tool_call.output\n );\n for (const name of extracted) {\n discoveredTools.add(name);\n }\n }\n\n if (discoveredTools.has(toolName)) {\n /** Valid tool - keep it */\n filteredContent.push(part);\n // Skill body reconstruction (PRs #96/#97): when a\n // SkillTool tool_call is present in this assistant turn, mark\n // the skill name so we can reconstruct the body HumanMessage\n // after the assistant turn has been pushed.\n if (toolName === Constants.SKILL_TOOL && skills?.size) {\n const skillName = extractSkillName(part.tool_call.args);\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n } else {\n /** Invalid tool - convert to string for context preservation */\n if (\n typeof part.tool_call.id === 'string' &&\n part.tool_call.id !== ''\n ) {\n invalidToolCallIds.add(part.tool_call.id);\n }\n const output = part.tool_call.output ?? '';\n invalidToolStrings.push(`Tool: ${toolName}, ${output}`);\n }\n }\n\n /** Remove tool_call_ids references to invalid tools from text parts */\n if (invalidToolCallIds.size > 0) {\n for (const part of filteredContent) {\n if (\n part.type === ContentTypes.TEXT &&\n Array.isArray(part.tool_call_ids)\n ) {\n part.tool_call_ids = part.tool_call_ids.filter(\n (id: string) => !invalidToolCallIds.has(id)\n );\n if (part.tool_call_ids.length === 0) {\n delete part.tool_call_ids;\n }\n }\n }\n }\n\n /** Append invalid tool strings to the content for context preservation */\n if (invalidToolStrings.length > 0) {\n /** Find the last text part or create one */\n let lastTextPartIndex = -1;\n for (let j = filteredContent.length - 1; j >= 0; j--) {\n if (filteredContent[j].type === ContentTypes.TEXT) {\n lastTextPartIndex = j;\n break;\n }\n }\n\n const invalidToolText = invalidToolStrings.join('\\n');\n if (lastTextPartIndex >= 0) {\n const lastTextPart = filteredContent[lastTextPartIndex] as {\n type: string;\n [ContentTypes.TEXT]?: string;\n text?: string;\n };\n const existingText =\n lastTextPart[ContentTypes.TEXT] ?? lastTextPart.text ?? '';\n filteredContent[lastTextPartIndex] = {\n ...lastTextPart,\n [ContentTypes.TEXT]: existingText\n ? `${existingText}\\n${invalidToolText}`\n : invalidToolText,\n };\n } else {\n /** No text part exists, create one */\n filteredContent.push({\n type: ContentTypes.TEXT,\n [ContentTypes.TEXT]: invalidToolText,\n });\n }\n }\n\n /** Use filtered content if we made any changes */\n if (\n filteredContent.length !== content.length ||\n invalidToolStrings.length > 0\n ) {\n processedMessage = { ...message, content: filteredContent };\n }\n }\n }\n\n // When tools filtering is off, still detect skill tool_calls for body reconstruction.\n if (!discoveredTools && skills?.size) {\n const content = processedMessage.content;\n if (Array.isArray(content)) {\n for (const part of content) {\n if (\n part.type !== ContentTypes.TOOL_CALL ||\n part.tool_call?.name !== Constants.SKILL_TOOL\n ) {\n continue;\n }\n const skillName = extractSkillName(part.tool_call.args);\n if (skillName) {\n (pendingSkillNames ??= new Set()).add(skillName);\n }\n }\n }\n }\n\n // Process the assistant message using the helper function\n const formattedMessages = formatAssistantMessage(processedMessage, {\n preserveReasoningContent: options?.provider === Providers.DEEPSEEK,\n });\n messages.push(...formattedMessages);\n\n // Capture index range BEFORE skill body injection so injected\n // HumanMessages are excluded from the assistant's token distribution\n // (PR #97 fix).\n const endMessageIndex = messages.length;\n\n if (pendingSkillNames?.size) {\n for (const skillName of pendingSkillNames) {\n const body = skills?.get(skillName);\n if (body) {\n messages.push(\n new HumanMessage({\n content: body,\n additional_kwargs: {\n role: 'user',\n isMeta: true,\n source: 'skill',\n skillName,\n },\n })\n );\n }\n }\n }\n\n const resultIndices = [];\n for (let j = startMessageIndex; j < endMessageIndex; j++) {\n resultIndices.push(j);\n }\n indexMapping[i] = resultIndices;\n }\n\n if (indexTokenCountMap) {\n for (\n let originalIndex = 0;\n originalIndex < payload.length;\n originalIndex++\n ) {\n const resultIndices = indexMapping[originalIndex] || [];\n const tokenCount = indexTokenCountMap[originalIndex];\n\n if (tokenCount === undefined) {\n continue;\n }\n\n const msgCount = resultIndices.length;\n if (msgCount === 1) {\n updatedIndexTokenCountMap[resultIndices[0]] = tokenCount;\n continue;\n }\n\n if (msgCount < 2) {\n continue;\n }\n\n let totalLength = 0;\n const lastIdx = msgCount - 1;\n const lengths = new Array<number>(msgCount);\n for (let k = 0; k < msgCount; k++) {\n const msg = messages[resultIndices[k]];\n const { content } = msg;\n let len = 0;\n if (typeof content === 'string') {\n len = content.length;\n } else if (Array.isArray(content)) {\n for (const part of content as Array<\n Record<string, unknown> | string | undefined\n >) {\n if (typeof part === 'string') {\n len += part.length;\n } else if (part != null && typeof part === 'object') {\n const val = part.text ?? part.content;\n if (typeof val === 'string') {\n len += val.length;\n }\n }\n }\n }\n const toolCalls = (msg as AIMessage).tool_calls;\n if (Array.isArray(toolCalls)) {\n for (const tc of toolCalls as Array<Record<string, unknown>>) {\n if (typeof tc.name === 'string') {\n len += tc.name.length;\n }\n const { args } = tc;\n if (typeof args === 'string') {\n len += args.length;\n } else if (args != null) {\n len += JSON.stringify(args).length;\n }\n }\n }\n lengths[k] = len;\n totalLength += len;\n }\n\n if (totalLength === 0) {\n const countPerMessage = Math.floor(tokenCount / msgCount);\n for (let k = 0; k < lastIdx; k++) {\n updatedIndexTokenCountMap[resultIndices[k]] = countPerMessage;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - countPerMessage * lastIdx;\n } else {\n let distributed = 0;\n for (let k = 0; k < lastIdx; k++) {\n const share = Math.floor((lengths[k] / totalLength) * tokenCount);\n updatedIndexTokenCountMap[resultIndices[k]] = share;\n distributed += share;\n }\n updatedIndexTokenCountMap[resultIndices[lastIdx]] =\n tokenCount - distributed;\n }\n }\n }\n\n return {\n messages,\n indexTokenCountMap: indexTokenCountMap\n ? updatedIndexTokenCountMap\n : undefined,\n };\n};\n\n/**\n * Adds a value at key 0 for system messages and shifts all key indices by one in an indexTokenCountMap.\n * This is useful when adding a system message at the beginning of a conversation.\n *\n * @param indexTokenCountMap - The original map of message indices to token counts\n * @param instructionsTokenCount - The token count for the system message to add at index 0\n * @returns A new map with the system message at index 0 and all other indices shifted by 1\n */\nexport function shiftIndexTokenCountMap(\n indexTokenCountMap: Record<number, number>,\n instructionsTokenCount: number\n): Record<number, number> {\n // Create a new map to avoid modifying the original\n const shiftedMap: Record<number, number> = {};\n shiftedMap[0] = instructionsTokenCount;\n\n // Shift all existing indices by 1\n for (const [indexStr, tokenCount] of Object.entries(indexTokenCountMap)) {\n const index = Number(indexStr);\n shiftedMap[index + 1] = tokenCount;\n }\n\n return shiftedMap;\n}\n\n/** Block types that contain binary image data and must be preserved structurally. */\nconst IMAGE_BLOCK_TYPES = new Set(['image_url', 'image']);\n\n/** Checks whether a BaseMessage is a tool-role message. */\nconst isToolMessage = (m: BaseMessage): boolean =>\n m instanceof ToolMessage || ('role' in m && (m as any).role === 'tool');\n\n/** Flushes accumulated text chunks into `parts` as a single text block. */\nfunction flushTextChunks(\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n if (textChunks.length === 0) {\n return;\n }\n parts.push({\n type: ContentTypes.TEXT,\n text: textChunks.join('\\n'),\n } as MessageContentComplex);\n textChunks.length = 0;\n}\n\n/**\n * Appends a single message's content to the running `textChunks` / `parts`\n * accumulators. Image blocks are shallow-copied into `parts` as-is so that\n * binary data (base64 images) never becomes text tokens. All other block\n * types are serialized to text — unrecognized types are JSON-serialized\n * rather than silently dropped.\n *\n * When `content` is an array containing tool_use blocks, `tool_calls` is NOT\n * additionally serialized (avoiding double output). `tool_calls` is used as\n * a fallback when `content` is a plain string or an array with no tool_use.\n */\nfunction appendMessageContent(\n msg: BaseMessage,\n role: string,\n textChunks: string[],\n parts: MessageContentComplex[]\n): void {\n const { content } = msg;\n\n if (typeof content === 'string') {\n if (content) {\n textChunks.push(`${role}: ${content}`);\n }\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n if (!Array.isArray(content)) {\n appendToolCalls(msg, role, textChunks);\n return;\n }\n\n let hasToolUseBlock = false;\n\n for (const block of content as ExtendedMessageContent[]) {\n if (IMAGE_BLOCK_TYPES.has(block.type ?? '')) {\n flushTextChunks(textChunks, parts);\n parts.push({ ...block } as MessageContentComplex);\n continue;\n }\n\n if (block.type === 'tool_use') {\n hasToolUseBlock = true;\n textChunks.push(\n `${role}: [tool_use] ${String(block.name ?? '')} ${JSON.stringify(block.input ?? {})}`\n );\n continue;\n }\n\n const text = block.text ?? block.input;\n if (typeof text === 'string' && text) {\n textChunks.push(`${role}: ${text}`);\n continue;\n }\n\n // Fallback: serialize unrecognized block types to preserve context\n if (block.type != null && block.type !== '') {\n textChunks.push(`${role}: [${block.type}] ${JSON.stringify(block)}`);\n }\n }\n\n // If content array had no tool_use blocks, fall back to tool_calls metadata\n // (handles edge case: empty content array with tool_calls populated)\n if (!hasToolUseBlock) {\n appendToolCalls(msg, role, textChunks);\n }\n}\n\nfunction appendToolCalls(\n msg: BaseMessage,\n role: string,\n textChunks: string[]\n): void {\n if (role !== 'AI') {\n return;\n }\n const aiMsg = msg as AIMessage;\n if (!aiMsg.tool_calls || aiMsg.tool_calls.length === 0) {\n return;\n }\n for (const tc of aiMsg.tool_calls) {\n textChunks.push(`AI: [tool_call] ${tc.name}(${JSON.stringify(tc.args)})`);\n }\n}\n\n/**\n * Ensures compatibility when switching from a non-thinking agent to a thinking-enabled agent.\n * Converts AI messages with tool calls (that lack thinking/reasoning blocks) into buffer strings,\n * avoiding the thinking block signature requirement.\n *\n * Recognizes the following as valid thinking/reasoning blocks:\n * - ContentTypes.THINKING (Anthropic)\n * - ContentTypes.REASONING_CONTENT (Bedrock)\n * - ContentTypes.REASONING (VertexAI / Google)\n * - 'redacted_thinking'\n *\n * @param messages - Array of messages to process\n * @param provider - The provider being used (unused but kept for future compatibility)\n * @returns The messages array with tool sequences converted to buffer strings if necessary\n */\nexport function ensureThinkingBlockInMessages(\n messages: BaseMessage[],\n _provider: Providers\n): BaseMessage[] {\n if (messages.length === 0) {\n return messages;\n }\n\n // If the last message is already a HumanMessage, there is no trailing tool\n // sequence to convert — return early to preserve prompt caching and avoid\n // redundant token overhead from re-processing the entire history.\n const lastMsg = messages[messages.length - 1];\n const lastIsHuman =\n lastMsg instanceof HumanMessage ||\n ('role' in lastMsg && (lastMsg as any).role === 'user');\n if (lastIsHuman) {\n return messages;\n }\n\n const result: BaseMessage[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n /** Detect AI messages by instanceof OR by role, in case cache-control cloning\n produced a plain object that lost the LangChain prototype. */\n const isAI =\n msg instanceof AIMessage ||\n msg instanceof AIMessageChunk ||\n ('role' in msg && (msg as any).role === 'assistant');\n\n if (!isAI) {\n result.push(msg);\n i++;\n continue;\n }\n\n const aiMsg = msg as AIMessage | AIMessageChunk;\n const hasToolCalls = aiMsg.tool_calls && aiMsg.tool_calls.length > 0;\n const contentIsArray = Array.isArray(aiMsg.content);\n\n // Check if the message has tool calls or tool_use content\n let hasToolUse = hasToolCalls ?? false;\n let hasThinkingBlock = false;\n\n if (contentIsArray && aiMsg.content.length > 0) {\n for (const c of aiMsg.content as ExtendedMessageContent[]) {\n if (typeof c !== 'object') {\n continue;\n }\n if (c.type === 'tool_use') {\n hasToolUse = true;\n } else if (\n c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking'\n ) {\n hasThinkingBlock = true;\n }\n if (hasToolUse && hasThinkingBlock) {\n break;\n }\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs (may not be in content array)\n if (\n !hasThinkingBlock &&\n aiMsg.additional_kwargs.reasoning_content != null\n ) {\n hasThinkingBlock = true;\n }\n\n // If message has tool use but no thinking block, check whether this is a\n // continuation of a thinking-enabled agent's chain before converting.\n // Bedrock reasoning models can produce multiple AI→Tool rounds after an\n // initial reasoning response: the first AI message has reasoning_content,\n // but follow-ups have content: \"\" with only tool_calls. These are the\n // same agent's turn and must NOT be converted to HumanMessages.\n if (hasToolUse && !hasThinkingBlock) {\n // Walk backwards — if an earlier AI message in the same chain (before\n // the nearest HumanMessage) has a thinking/reasoning block, this is a\n // continuation of a thinking-enabled turn, not a non-thinking handoff.\n if (chainHasThinkingBlock(messages, i)) {\n result.push(msg);\n i++;\n continue;\n }\n\n // Build structured content in a single pass over the AI + following\n // ToolMessages — preserves image blocks as-is to avoid serializing\n // binary data as text (which caused 174× token amplification).\n const parts: MessageContentComplex[] = [];\n const textChunks: string[] = ['[Previous agent context]'];\n\n appendMessageContent(msg, 'AI', textChunks, parts);\n\n let j = i + 1;\n while (j < messages.length && isToolMessage(messages[j])) {\n appendMessageContent(messages[j], 'Tool', textChunks, parts);\n j++;\n }\n\n flushTextChunks(textChunks, parts);\n result.push(new HumanMessage({ content: parts }));\n i = j;\n } else {\n // Keep the message as is\n result.push(msg);\n i++;\n }\n }\n\n return result;\n}\n\n/**\n * Walks backwards from `currentIndex` through the message array to check\n * whether an earlier AI message in the same \"chain\" (no HumanMessage boundary)\n * contains a thinking/reasoning block.\n *\n * A \"chain\" is a contiguous sequence of AI + Tool messages with no intervening\n * HumanMessage. Bedrock reasoning models produce reasoning on the first AI\n * response, then issue follow-up tool calls with `content: \"\"` and no\n * reasoning block. These follow-ups are part of the same thinking-enabled\n * turn and should not be converted.\n */\nfunction chainHasThinkingBlock(\n messages: BaseMessage[],\n currentIndex: number\n): boolean {\n for (let k = currentIndex - 1; k >= 0; k--) {\n const prev = messages[k];\n\n // HumanMessage = turn boundary — stop searching\n if (\n prev instanceof HumanMessage ||\n ('role' in prev && (prev as any).role === 'user')\n ) {\n return false;\n }\n\n // Check AI messages for thinking/reasoning blocks\n const isPrevAI =\n prev instanceof AIMessage ||\n prev instanceof AIMessageChunk ||\n ('role' in prev && (prev as any).role === 'assistant');\n\n if (isPrevAI) {\n const prevAiMsg = prev as AIMessage | AIMessageChunk;\n\n if (Array.isArray(prevAiMsg.content) && prevAiMsg.content.length > 0) {\n const content = prevAiMsg.content as ExtendedMessageContent[];\n if (\n content.some(\n (c) =>\n typeof c === 'object' &&\n (c.type === ContentTypes.THINKING ||\n c.type === ContentTypes.REASONING_CONTENT ||\n c.type === ContentTypes.REASONING ||\n c.type === 'redacted_thinking')\n )\n ) {\n return true;\n }\n }\n\n // Bedrock also stores reasoning in additional_kwargs\n if (prevAiMsg.additional_kwargs.reasoning_content != null) {\n return true;\n }\n }\n\n // ToolMessages are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