@mastra/react 1.7.3-alpha.3 → 1.8.0-alpha.5

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 (510) hide show
  1. package/dist/accumulator-B1MuNX3j.js +1668 -0
  2. package/dist/accumulator-B1MuNX3j.js.map +1 -0
  3. package/dist/accumulator-CsUGDUHk.cjs +1709 -0
  4. package/dist/accumulator-CsUGDUHk.cjs.map +1 -0
  5. package/dist/agent/hooks.d.ts.map +1 -1
  6. package/dist/agent/user-message.d.ts +4 -0
  7. package/dist/agent/user-message.d.ts.map +1 -0
  8. package/dist/chat/index.cjs +3 -0
  9. package/dist/chat/index.d.ts +3 -0
  10. package/dist/chat/index.d.ts.map +1 -0
  11. package/dist/chat/index.js +2 -0
  12. package/dist/feedback-refetch-interval-DLHzQoVV.js +12 -0
  13. package/dist/feedback-refetch-interval-DLHzQoVV.js.map +1 -0
  14. package/dist/feedback-refetch-interval-XD5FVc2k.cjs +17 -0
  15. package/dist/feedback-refetch-interval-XD5FVc2k.cjs.map +1 -0
  16. package/dist/hooks/agents/index.cjs +1012 -0
  17. package/dist/hooks/agents/index.cjs.map +1 -0
  18. package/dist/hooks/agents/index.d.ts +19 -0
  19. package/dist/hooks/agents/index.d.ts.map +1 -0
  20. package/dist/hooks/agents/index.js +975 -0
  21. package/dist/hooks/agents/index.js.map +1 -0
  22. package/dist/hooks/agents/is-model-not-allowed.d.ts +15 -0
  23. package/dist/hooks/agents/is-model-not-allowed.d.ts.map +1 -0
  24. package/dist/hooks/agents/use-agent-messages.d.ts +18 -0
  25. package/dist/hooks/agents/use-agent-messages.d.ts.map +1 -0
  26. package/dist/hooks/agents/use-agent-plan.d.ts +14 -0
  27. package/dist/hooks/agents/use-agent-plan.d.ts.map +1 -0
  28. package/dist/hooks/agents/use-agent-skills.d.ts +2043 -0
  29. package/dist/hooks/agents/use-agent-skills.d.ts.map +1 -0
  30. package/dist/hooks/agents/use-agent-versions.d.ts +72 -0
  31. package/dist/hooks/agents/use-agent-versions.d.ts.map +1 -0
  32. package/dist/hooks/agents/use-agent-working-memory.d.ts +11 -0
  33. package/dist/hooks/agents/use-agent-working-memory.d.ts.map +1 -0
  34. package/dist/hooks/agents/use-agent-workspace.d.ts +2044 -0
  35. package/dist/hooks/agents/use-agent-workspace.d.ts.map +1 -0
  36. package/dist/hooks/agents/use-agent.d.ts +12 -0
  37. package/dist/hooks/agents/use-agent.d.ts.map +1 -0
  38. package/dist/hooks/agents/use-agents-model-providers.d.ts +9 -0
  39. package/dist/hooks/agents/use-agents-model-providers.d.ts.map +1 -0
  40. package/dist/hooks/agents/use-agents.d.ts +28 -0
  41. package/dist/hooks/agents/use-agents.d.ts.map +1 -0
  42. package/dist/hooks/agents/use-background-tasks.d.ts +51 -0
  43. package/dist/hooks/agents/use-background-tasks.d.ts.map +1 -0
  44. package/dist/hooks/agents/use-browser-session-probe.d.ts +34 -0
  45. package/dist/hooks/agents/use-browser-session-probe.d.ts.map +1 -0
  46. package/dist/hooks/agents/use-channels.d.ts +45 -0
  47. package/dist/hooks/agents/use-channels.d.ts.map +1 -0
  48. package/dist/hooks/agents/use-close-browser.d.ts +17 -0
  49. package/dist/hooks/agents/use-close-browser.d.ts.map +1 -0
  50. package/dist/hooks/agents/use-execute-agent-tool.d.ts +14 -0
  51. package/dist/hooks/agents/use-execute-agent-tool.d.ts.map +1 -0
  52. package/dist/hooks/agents/use-preview-instructions.d.ts +20 -0
  53. package/dist/hooks/agents/use-preview-instructions.d.ts.map +1 -0
  54. package/dist/hooks/agents/use-stored-agents.d.ts +8111 -0
  55. package/dist/hooks/agents/use-stored-agents.d.ts.map +1 -0
  56. package/dist/hooks/agents/use-stored-skills.d.ts +8 -0
  57. package/dist/hooks/agents/use-stored-skills.d.ts.map +1 -0
  58. package/dist/hooks/auth/fetch-with-refresh.d.ts +28 -0
  59. package/dist/hooks/auth/fetch-with-refresh.d.ts.map +1 -0
  60. package/dist/hooks/auth/get-client-query-key.d.ts +7 -0
  61. package/dist/hooks/auth/get-client-query-key.d.ts.map +1 -0
  62. package/dist/hooks/auth/index.cjs +492 -0
  63. package/dist/hooks/auth/index.cjs.map +1 -0
  64. package/dist/hooks/auth/index.d.ts +11 -0
  65. package/dist/hooks/auth/index.d.ts.map +1 -0
  66. package/dist/hooks/auth/index.js +474 -0
  67. package/dist/hooks/auth/index.js.map +1 -0
  68. package/dist/hooks/auth/sso-login.d.ts +8 -0
  69. package/dist/hooks/auth/sso-login.d.ts.map +1 -0
  70. package/dist/hooks/auth/types.d.ts +107 -0
  71. package/dist/hooks/auth/types.d.ts.map +1 -0
  72. package/dist/hooks/auth/use-auth-actions.d.ts +99 -0
  73. package/dist/hooks/auth/use-auth-actions.d.ts.map +1 -0
  74. package/dist/hooks/auth/use-auth-capabilities.d.ts +43 -0
  75. package/dist/hooks/auth/use-auth-capabilities.d.ts.map +1 -0
  76. package/dist/hooks/auth/use-credentials-login.d.ts +63 -0
  77. package/dist/hooks/auth/use-credentials-login.d.ts.map +1 -0
  78. package/dist/hooks/auth/use-credentials-signup.d.ts +66 -0
  79. package/dist/hooks/auth/use-credentials-signup.d.ts.map +1 -0
  80. package/dist/hooks/auth/use-current-user.d.ts +40 -0
  81. package/dist/hooks/auth/use-current-user.d.ts.map +1 -0
  82. package/dist/hooks/auth/use-permission-patterns.d.ts +24 -0
  83. package/dist/hooks/auth/use-permission-patterns.d.ts.map +1 -0
  84. package/dist/hooks/capabilities/index.cjs +47 -0
  85. package/dist/hooks/capabilities/index.cjs.map +1 -0
  86. package/dist/hooks/capabilities/index.d.ts +4 -0
  87. package/dist/hooks/capabilities/index.d.ts.map +1 -0
  88. package/dist/hooks/capabilities/index.js +44 -0
  89. package/dist/hooks/capabilities/index.js.map +1 -0
  90. package/dist/hooks/capabilities/use-feedback-available.d.ts +9 -0
  91. package/dist/hooks/capabilities/use-feedback-available.d.ts.map +1 -0
  92. package/dist/hooks/capabilities/use-observability-capabilities.d.ts +9 -0
  93. package/dist/hooks/capabilities/use-observability-capabilities.d.ts.map +1 -0
  94. package/dist/hooks/capabilities/use-trace-query-available.d.ts +9 -0
  95. package/dist/hooks/capabilities/use-trace-query-available.d.ts.map +1 -0
  96. package/dist/hooks/configuration/index.cjs +18 -0
  97. package/dist/hooks/configuration/index.cjs.map +1 -0
  98. package/dist/hooks/configuration/index.d.ts +2 -0
  99. package/dist/hooks/configuration/index.d.ts.map +1 -0
  100. package/dist/hooks/configuration/index.js +17 -0
  101. package/dist/hooks/configuration/index.js.map +1 -0
  102. package/dist/hooks/configuration/use-mastra-packages.d.ts +9 -0
  103. package/dist/hooks/configuration/use-mastra-packages.d.ts.map +1 -0
  104. package/dist/hooks/datasets/index.cjs +615 -0
  105. package/dist/hooks/datasets/index.cjs.map +1 -0
  106. package/dist/hooks/datasets/index.d.ts +10 -0
  107. package/dist/hooks/datasets/index.d.ts.map +1 -0
  108. package/dist/hooks/datasets/index.js +600 -0
  109. package/dist/hooks/datasets/index.js.map +1 -0
  110. package/dist/hooks/datasets/use-compare-experiments.d.ts +23 -0
  111. package/dist/hooks/datasets/use-compare-experiments.d.ts.map +1 -0
  112. package/dist/hooks/datasets/use-dataset-experiments.d.ts +49 -0
  113. package/dist/hooks/datasets/use-dataset-experiments.d.ts.map +1 -0
  114. package/dist/hooks/datasets/use-dataset-item-versions.d.ts +31 -0
  115. package/dist/hooks/datasets/use-dataset-item-versions.d.ts.map +1 -0
  116. package/dist/hooks/datasets/use-dataset-items.d.ts +38 -0
  117. package/dist/hooks/datasets/use-dataset-items.d.ts.map +1 -0
  118. package/dist/hooks/datasets/use-dataset-mutations.d.ts +362 -0
  119. package/dist/hooks/datasets/use-dataset-mutations.d.ts.map +1 -0
  120. package/dist/hooks/datasets/use-dataset-versions.d.ts +23 -0
  121. package/dist/hooks/datasets/use-dataset-versions.d.ts.map +1 -0
  122. package/dist/hooks/datasets/use-datasets.d.ts +44 -0
  123. package/dist/hooks/datasets/use-datasets.d.ts.map +1 -0
  124. package/dist/hooks/datasets/use-experiments.d.ts +16 -0
  125. package/dist/hooks/datasets/use-experiments.d.ts.map +1 -0
  126. package/dist/hooks/datasets/use-workflow-schema.d.ts +16 -0
  127. package/dist/hooks/datasets/use-workflow-schema.d.ts.map +1 -0
  128. package/dist/hooks/embedders/index.cjs +19 -0
  129. package/dist/hooks/embedders/index.cjs.map +1 -0
  130. package/dist/hooks/embedders/index.d.ts +2 -0
  131. package/dist/hooks/embedders/index.d.ts.map +1 -0
  132. package/dist/hooks/embedders/index.js +18 -0
  133. package/dist/hooks/embedders/index.js.map +1 -0
  134. package/dist/hooks/embedders/use-embedders.d.ts +17 -0
  135. package/dist/hooks/embedders/use-embedders.d.ts.map +1 -0
  136. package/dist/hooks/experiments/index.cjs +152 -0
  137. package/dist/hooks/experiments/index.cjs.map +1 -0
  138. package/dist/hooks/experiments/index.d.ts +5 -0
  139. package/dist/hooks/experiments/index.d.ts.map +1 -0
  140. package/dist/hooks/experiments/index.js +146 -0
  141. package/dist/hooks/experiments/index.js.map +1 -0
  142. package/dist/hooks/experiments/use-experiment-metrics.d.ts +30 -0
  143. package/dist/hooks/experiments/use-experiment-metrics.d.ts.map +1 -0
  144. package/dist/hooks/experiments/use-experiment-trace.d.ts +13 -0
  145. package/dist/hooks/experiments/use-experiment-trace.d.ts.map +1 -0
  146. package/dist/hooks/experiments/use-experiments-for-dataset-filter.d.ts +22 -0
  147. package/dist/hooks/experiments/use-experiments-for-dataset-filter.d.ts.map +1 -0
  148. package/dist/hooks/experiments/use-infinite-experiments.d.ts +22 -0
  149. package/dist/hooks/experiments/use-infinite-experiments.d.ts.map +1 -0
  150. package/dist/hooks/feedback/feedback-refetch-interval.d.ts +7 -0
  151. package/dist/hooks/feedback/feedback-refetch-interval.d.ts.map +1 -0
  152. package/dist/hooks/feedback/index.cjs +22 -0
  153. package/dist/hooks/feedback/index.cjs.map +1 -0
  154. package/dist/hooks/feedback/index.d.ts +3 -0
  155. package/dist/hooks/feedback/index.d.ts.map +1 -0
  156. package/dist/hooks/feedback/index.js +20 -0
  157. package/dist/hooks/feedback/index.js.map +1 -0
  158. package/dist/hooks/feedback/use-feedback.d.ts +56 -0
  159. package/dist/hooks/feedback/use-feedback.d.ts.map +1 -0
  160. package/dist/hooks/llm/index.cjs +17 -0
  161. package/dist/hooks/llm/index.cjs.map +1 -0
  162. package/dist/hooks/llm/index.d.ts +2 -0
  163. package/dist/hooks/llm/index.d.ts.map +1 -0
  164. package/dist/hooks/llm/index.js +16 -0
  165. package/dist/hooks/llm/index.js.map +1 -0
  166. package/dist/hooks/llm/use-llm-providers.d.ts +7 -0
  167. package/dist/hooks/llm/use-llm-providers.d.ts.map +1 -0
  168. package/dist/hooks/logs/index.cjs +84 -0
  169. package/dist/hooks/logs/index.cjs.map +1 -0
  170. package/dist/hooks/logs/index.d.ts +4 -0
  171. package/dist/hooks/logs/index.d.ts.map +1 -0
  172. package/dist/hooks/logs/index.js +82 -0
  173. package/dist/hooks/logs/index.js.map +1 -0
  174. package/dist/hooks/logs/types.d.ts +36 -0
  175. package/dist/hooks/logs/types.d.ts.map +1 -0
  176. package/dist/hooks/logs/use-logs.d.ts +79 -0
  177. package/dist/hooks/logs/use-logs.d.ts.map +1 -0
  178. package/dist/hooks/mcps/index.cjs +215 -0
  179. package/dist/hooks/mcps/index.cjs.map +1 -0
  180. package/dist/hooks/mcps/index.d.ts +7 -0
  181. package/dist/hooks/mcps/index.d.ts.map +1 -0
  182. package/dist/hooks/mcps/index.js +208 -0
  183. package/dist/hooks/mcps/index.js.map +1 -0
  184. package/dist/hooks/mcps/use-mcp-app-tools.d.ts +21 -0
  185. package/dist/hooks/mcps/use-mcp-app-tools.d.ts.map +1 -0
  186. package/dist/hooks/mcps/use-mcp-server-tool.d.ts +25 -0
  187. package/dist/hooks/mcps/use-mcp-server-tool.d.ts.map +1 -0
  188. package/dist/hooks/mcps/use-mcp-server-tools-by-id.d.ts +13 -0
  189. package/dist/hooks/mcps/use-mcp-server-tools-by-id.d.ts.map +1 -0
  190. package/dist/hooks/mcps/use-mcp-server-tools.d.ts +9 -0
  191. package/dist/hooks/mcps/use-mcp-server-tools.d.ts.map +1 -0
  192. package/dist/hooks/mcps/use-mcp-servers.d.ts +8 -0
  193. package/dist/hooks/mcps/use-mcp-servers.d.ts.map +1 -0
  194. package/dist/hooks/mcps/use-try-connect-mcp.d.ts +15 -0
  195. package/dist/hooks/mcps/use-try-connect-mcp.d.ts.map +1 -0
  196. package/dist/hooks/memory/index.cjs +328 -0
  197. package/dist/hooks/memory/index.cjs.map +1 -0
  198. package/dist/hooks/memory/index.d.ts +5 -0
  199. package/dist/hooks/memory/index.d.ts.map +1 -0
  200. package/dist/hooks/memory/index.js +312 -0
  201. package/dist/hooks/memory/index.js.map +1 -0
  202. package/dist/hooks/memory/use-memory-status.d.ts +12 -0
  203. package/dist/hooks/memory/use-memory-status.d.ts.map +1 -0
  204. package/dist/hooks/memory/use-memory-thread-messages.d.ts +13 -0
  205. package/dist/hooks/memory/use-memory-thread-messages.d.ts.map +1 -0
  206. package/dist/hooks/memory/use-memory.d.ts +159 -0
  207. package/dist/hooks/memory/use-memory.d.ts.map +1 -0
  208. package/dist/hooks/memory/use-observational-memory.d.ts +13 -0
  209. package/dist/hooks/memory/use-observational-memory.d.ts.map +1 -0
  210. package/dist/hooks/metrics/index.cjs +997 -0
  211. package/dist/hooks/metrics/index.cjs.map +1 -0
  212. package/dist/hooks/metrics/index.d.ts +16 -0
  213. package/dist/hooks/metrics/index.d.ts.map +1 -0
  214. package/dist/hooks/metrics/index.js +981 -0
  215. package/dist/hooks/metrics/index.js.map +1 -0
  216. package/dist/hooks/metrics/metrics-interval.d.ts +8 -0
  217. package/dist/hooks/metrics/metrics-interval.d.ts.map +1 -0
  218. package/dist/hooks/metrics/metrics-query-filters.d.ts +62 -0
  219. package/dist/hooks/metrics/metrics-query-filters.d.ts.map +1 -0
  220. package/dist/hooks/metrics/use-active-resources-kpi-metrics.d.ts +12 -0
  221. package/dist/hooks/metrics/use-active-resources-kpi-metrics.d.ts.map +1 -0
  222. package/dist/hooks/metrics/use-active-threads-kpi-metrics.d.ts +12 -0
  223. package/dist/hooks/metrics/use-active-threads-kpi-metrics.d.ts.map +1 -0
  224. package/dist/hooks/metrics/use-agent-runs-kpi-metrics.d.ts +9 -0
  225. package/dist/hooks/metrics/use-agent-runs-kpi-metrics.d.ts.map +1 -0
  226. package/dist/hooks/metrics/use-latency-metrics.d.ts +23 -0
  227. package/dist/hooks/metrics/use-latency-metrics.d.ts.map +1 -0
  228. package/dist/hooks/metrics/use-model-cost-kpi-metrics.d.ts +14 -0
  229. package/dist/hooks/metrics/use-model-cost-kpi-metrics.d.ts.map +1 -0
  230. package/dist/hooks/metrics/use-model-usage-cost-metrics.d.ts +16 -0
  231. package/dist/hooks/metrics/use-model-usage-cost-metrics.d.ts.map +1 -0
  232. package/dist/hooks/metrics/use-scores-metrics.d.ts +24 -0
  233. package/dist/hooks/metrics/use-scores-metrics.d.ts.map +1 -0
  234. package/dist/hooks/metrics/use-token-usage-by-agent-metrics.d.ts +15 -0
  235. package/dist/hooks/metrics/use-token-usage-by-agent-metrics.d.ts.map +1 -0
  236. package/dist/hooks/metrics/use-token-usage-timeseries.d.ts +22 -0
  237. package/dist/hooks/metrics/use-token-usage-timeseries.d.ts.map +1 -0
  238. package/dist/hooks/metrics/use-top-active-threads-metrics.d.ts +21 -0
  239. package/dist/hooks/metrics/use-top-active-threads-metrics.d.ts.map +1 -0
  240. package/dist/hooks/metrics/use-top-resources-by-threads-metrics.d.ts +20 -0
  241. package/dist/hooks/metrics/use-top-resources-by-threads-metrics.d.ts.map +1 -0
  242. package/dist/hooks/metrics/use-total-tokens-kpi-metrics.d.ts +13 -0
  243. package/dist/hooks/metrics/use-total-tokens-kpi-metrics.d.ts.map +1 -0
  244. package/dist/hooks/metrics/use-trace-volume-metrics.d.ts +17 -0
  245. package/dist/hooks/metrics/use-trace-volume-metrics.d.ts.map +1 -0
  246. package/dist/hooks/processors/index.cjs +43 -0
  247. package/dist/hooks/processors/index.cjs.map +1 -0
  248. package/dist/hooks/processors/index.d.ts +2 -0
  249. package/dist/hooks/processors/index.d.ts.map +1 -0
  250. package/dist/hooks/processors/index.js +40 -0
  251. package/dist/hooks/processors/index.js.map +1 -0
  252. package/dist/hooks/processors/use-processors.d.ts +64 -0
  253. package/dist/hooks/processors/use-processors.d.ts.map +1 -0
  254. package/dist/hooks/prompt-blocks/index.cjs +181 -0
  255. package/dist/hooks/prompt-blocks/index.cjs.map +1 -0
  256. package/dist/hooks/prompt-blocks/index.d.ts +3 -0
  257. package/dist/hooks/prompt-blocks/index.d.ts.map +1 -0
  258. package/dist/hooks/prompt-blocks/index.js +172 -0
  259. package/dist/hooks/prompt-blocks/index.js.map +1 -0
  260. package/dist/hooks/prompt-blocks/use-prompt-block-versions.d.ts +59 -0
  261. package/dist/hooks/prompt-blocks/use-prompt-block-versions.d.ts.map +1 -0
  262. package/dist/hooks/prompt-blocks/use-stored-prompt-blocks.d.ts +180 -0
  263. package/dist/hooks/prompt-blocks/use-stored-prompt-blocks.d.ts.map +1 -0
  264. package/dist/hooks/query/index.cjs +34 -0
  265. package/dist/hooks/query/index.cjs.map +1 -0
  266. package/dist/hooks/query/index.d.ts +4 -0
  267. package/dist/hooks/query/index.d.ts.map +1 -0
  268. package/dist/hooks/query/index.js +25 -0
  269. package/dist/hooks/query/index.js.map +1 -0
  270. package/dist/hooks/query/query-client-provider.d.ts +8 -0
  271. package/dist/hooks/query/query-client-provider.d.ts.map +1 -0
  272. package/dist/hooks/query/query-utils.d.ts +48 -0
  273. package/dist/hooks/query/query-utils.d.ts.map +1 -0
  274. package/dist/hooks/review/index.cjs +89 -0
  275. package/dist/hooks/review/index.cjs.map +1 -0
  276. package/dist/hooks/review/index.d.ts +4 -0
  277. package/dist/hooks/review/index.d.ts.map +1 -0
  278. package/dist/hooks/review/index.js +86 -0
  279. package/dist/hooks/review/index.js.map +1 -0
  280. package/dist/hooks/review/types.d.ts +21 -0
  281. package/dist/hooks/review/types.d.ts.map +1 -0
  282. package/dist/hooks/review/use-dataset-review-items.d.ts +19 -0
  283. package/dist/hooks/review/use-dataset-review-items.d.ts.map +1 -0
  284. package/dist/hooks/review/use-review-summary.d.ts +9 -0
  285. package/dist/hooks/review/use-review-summary.d.ts.map +1 -0
  286. package/dist/hooks/schedules/index.cjs +110 -0
  287. package/dist/hooks/schedules/index.cjs.map +1 -0
  288. package/dist/hooks/schedules/index.d.ts +5 -0
  289. package/dist/hooks/schedules/index.d.ts.map +1 -0
  290. package/dist/hooks/schedules/index.js +106 -0
  291. package/dist/hooks/schedules/index.js.map +1 -0
  292. package/dist/hooks/schedules/use-schedule-triggers.d.ts +18 -0
  293. package/dist/hooks/schedules/use-schedule-triggers.d.ts.map +1 -0
  294. package/dist/hooks/schedules/use-schedule.d.ts +11 -0
  295. package/dist/hooks/schedules/use-schedule.d.ts.map +1 -0
  296. package/dist/hooks/schedules/use-schedules.d.ts +7 -0
  297. package/dist/hooks/schedules/use-schedules.d.ts.map +1 -0
  298. package/dist/hooks/schedules/use-toggle-schedule.d.ts +13 -0
  299. package/dist/hooks/schedules/use-toggle-schedule.d.ts.map +1 -0
  300. package/dist/hooks/scores/index.cjs +339 -0
  301. package/dist/hooks/scores/index.cjs.map +1 -0
  302. package/dist/hooks/scores/index.d.ts +6 -0
  303. package/dist/hooks/scores/index.d.ts.map +1 -0
  304. package/dist/hooks/scores/index.js +323 -0
  305. package/dist/hooks/scores/index.js.map +1 -0
  306. package/dist/hooks/scores/use-scorer-versions.d.ts +71 -0
  307. package/dist/hooks/scores/use-scorer-versions.d.ts.map +1 -0
  308. package/dist/hooks/scores/use-scorers.d.ts +34 -0
  309. package/dist/hooks/scores/use-scorers.d.ts.map +1 -0
  310. package/dist/hooks/scores/use-stored-scorers.d.ts +151 -0
  311. package/dist/hooks/scores/use-stored-scorers.d.ts.map +1 -0
  312. package/dist/hooks/scores/use-trace-span-scores.d.ts +20 -0
  313. package/dist/hooks/scores/use-trace-span-scores.d.ts.map +1 -0
  314. package/dist/hooks/scores/use-trigger-scorer.d.ts +17 -0
  315. package/dist/hooks/scores/use-trigger-scorer.d.ts.map +1 -0
  316. package/dist/hooks/shared/cost.d.ts +7 -0
  317. package/dist/hooks/shared/cost.d.ts.map +1 -0
  318. package/dist/hooks/shared/date-format.d.ts +30 -0
  319. package/dist/hooks/shared/date-format.d.ts.map +1 -0
  320. package/dist/hooks/shared/map.d.ts +2 -0
  321. package/dist/hooks/shared/map.d.ts.map +1 -0
  322. package/dist/hooks/shared/query-options.d.ts +19 -0
  323. package/dist/hooks/shared/query-options.d.ts.map +1 -0
  324. package/dist/hooks/shared/use-in-view.d.ts +23 -0
  325. package/dist/hooks/shared/use-in-view.d.ts.map +1 -0
  326. package/dist/hooks/templates/index.cjs +464 -0
  327. package/dist/hooks/templates/index.cjs.map +1 -0
  328. package/dist/hooks/templates/index.d.ts +2 -0
  329. package/dist/hooks/templates/index.d.ts.map +1 -0
  330. package/dist/hooks/templates/index.js +456 -0
  331. package/dist/hooks/templates/index.js.map +1 -0
  332. package/dist/hooks/templates/use-templates.d.ts +139 -0
  333. package/dist/hooks/templates/use-templates.d.ts.map +1 -0
  334. package/dist/hooks/tool-providers/index.cjs +342 -0
  335. package/dist/hooks/tool-providers/index.cjs.map +1 -0
  336. package/dist/hooks/tool-providers/index.d.ts +10 -0
  337. package/dist/hooks/tool-providers/index.d.ts.map +1 -0
  338. package/dist/hooks/tool-providers/index.js +332 -0
  339. package/dist/hooks/tool-providers/index.js.map +1 -0
  340. package/dist/hooks/tool-providers/use-all-connections.d.ts +41 -0
  341. package/dist/hooks/tool-providers/use-all-connections.d.ts.map +1 -0
  342. package/dist/hooks/tool-providers/use-all-provider-tools.d.ts +25 -0
  343. package/dist/hooks/tool-providers/use-all-provider-tools.d.ts.map +1 -0
  344. package/dist/hooks/tool-providers/use-authorize.d.ts +45 -0
  345. package/dist/hooks/tool-providers/use-authorize.d.ts.map +1 -0
  346. package/dist/hooks/tool-providers/use-disconnect-connection.d.ts +24 -0
  347. package/dist/hooks/tool-providers/use-disconnect-connection.d.ts.map +1 -0
  348. package/dist/hooks/tool-providers/use-existing-connections.d.ts +33 -0
  349. package/dist/hooks/tool-providers/use-existing-connections.d.ts.map +1 -0
  350. package/dist/hooks/tool-providers/use-provider-tools.d.ts +17 -0
  351. package/dist/hooks/tool-providers/use-provider-tools.d.ts.map +1 -0
  352. package/dist/hooks/tool-providers/use-tool-providers.d.ts +23 -0
  353. package/dist/hooks/tool-providers/use-tool-providers.d.ts.map +1 -0
  354. package/dist/hooks/tool-providers/use-toolkits.d.ts +13 -0
  355. package/dist/hooks/tool-providers/use-toolkits.d.ts.map +1 -0
  356. package/dist/hooks/tool-providers/use-update-connection.d.ts +24 -0
  357. package/dist/hooks/tool-providers/use-update-connection.d.ts.map +1 -0
  358. package/dist/hooks/tools/index.cjs +49 -0
  359. package/dist/hooks/tools/index.cjs.map +1 -0
  360. package/dist/hooks/tools/index.d.ts +3 -0
  361. package/dist/hooks/tools/index.d.ts.map +1 -0
  362. package/dist/hooks/tools/index.js +46 -0
  363. package/dist/hooks/tools/index.js.map +1 -0
  364. package/dist/hooks/tools/use-all-tools.d.ts +16 -0
  365. package/dist/hooks/tools/use-all-tools.d.ts.map +1 -0
  366. package/dist/hooks/tools/use-execute-tool.d.ts +13 -0
  367. package/dist/hooks/tools/use-execute-tool.d.ts.map +1 -0
  368. package/dist/hooks/traces/discovery-cache.d.ts +12 -0
  369. package/dist/hooks/traces/discovery-cache.d.ts.map +1 -0
  370. package/dist/hooks/traces/index.cjs +1168 -0
  371. package/dist/hooks/traces/index.cjs.map +1 -0
  372. package/dist/hooks/traces/index.d.ts +22 -0
  373. package/dist/hooks/traces/index.d.ts.map +1 -0
  374. package/dist/hooks/traces/index.js +1129 -0
  375. package/dist/hooks/traces/index.js.map +1 -0
  376. package/dist/hooks/traces/types.d.ts +20 -0
  377. package/dist/hooks/traces/types.d.ts.map +1 -0
  378. package/dist/hooks/traces/use-branch.d.ts +18 -0
  379. package/dist/hooks/traces/use-branch.d.ts.map +1 -0
  380. package/dist/hooks/traces/use-create-feedback.d.ts +21 -0
  381. package/dist/hooks/traces/use-create-feedback.d.ts.map +1 -0
  382. package/dist/hooks/traces/use-delete-feedback.d.ts +21 -0
  383. package/dist/hooks/traces/use-delete-feedback.d.ts.map +1 -0
  384. package/dist/hooks/traces/use-entity-names.d.ts +14 -0
  385. package/dist/hooks/traces/use-entity-names.d.ts.map +1 -0
  386. package/dist/hooks/traces/use-environments.d.ts +10 -0
  387. package/dist/hooks/traces/use-environments.d.ts.map +1 -0
  388. package/dist/hooks/traces/use-service-names.d.ts +10 -0
  389. package/dist/hooks/traces/use-service-names.d.ts.map +1 -0
  390. package/dist/hooks/traces/use-span-detail.d.ts +14 -0
  391. package/dist/hooks/traces/use-span-detail.d.ts.map +1 -0
  392. package/dist/hooks/traces/use-span-feedback.d.ts +19 -0
  393. package/dist/hooks/traces/use-span-feedback.d.ts.map +1 -0
  394. package/dist/hooks/traces/use-tags.d.ts +10 -0
  395. package/dist/hooks/traces/use-tags.d.ts.map +1 -0
  396. package/dist/hooks/traces/use-thread-has-other-traces.d.ts +17 -0
  397. package/dist/hooks/traces/use-thread-has-other-traces.d.ts.map +1 -0
  398. package/dist/hooks/traces/use-trace-column-preferences-storage-key.d.ts +6 -0
  399. package/dist/hooks/traces/use-trace-column-preferences-storage-key.d.ts.map +1 -0
  400. package/dist/hooks/traces/use-trace-feedback.d.ts +16 -0
  401. package/dist/hooks/traces/use-trace-feedback.d.ts.map +1 -0
  402. package/dist/hooks/traces/use-trace-light-spans.d.ts +16 -0
  403. package/dist/hooks/traces/use-trace-light-spans.d.ts.map +1 -0
  404. package/dist/hooks/traces/use-trace-metadata-filter-fields.d.ts +36 -0
  405. package/dist/hooks/traces/use-trace-metadata-filter-fields.d.ts.map +1 -0
  406. package/dist/hooks/traces/use-trace-or-branch-spans.d.ts +39 -0
  407. package/dist/hooks/traces/use-trace-or-branch-spans.d.ts.map +1 -0
  408. package/dist/hooks/traces/use-trace-query.d.ts +57 -0
  409. package/dist/hooks/traces/use-trace-query.d.ts.map +1 -0
  410. package/dist/hooks/traces/use-trace-spans.d.ts +46 -0
  411. package/dist/hooks/traces/use-trace-spans.d.ts.map +1 -0
  412. package/dist/hooks/traces/use-trace-usage.d.ts +10 -0
  413. package/dist/hooks/traces/use-trace-usage.d.ts.map +1 -0
  414. package/dist/hooks/traces/use-traces.d.ts +292 -0
  415. package/dist/hooks/traces/use-traces.d.ts.map +1 -0
  416. package/dist/hooks/vectors/index.cjs +19 -0
  417. package/dist/hooks/vectors/index.cjs.map +1 -0
  418. package/dist/hooks/vectors/index.d.ts +2 -0
  419. package/dist/hooks/vectors/index.d.ts.map +1 -0
  420. package/dist/hooks/vectors/index.js +18 -0
  421. package/dist/hooks/vectors/index.js.map +1 -0
  422. package/dist/hooks/vectors/use-vectors.d.ts +14 -0
  423. package/dist/hooks/vectors/use-vectors.d.ts.map +1 -0
  424. package/dist/hooks/voice/index.cjs +87 -0
  425. package/dist/hooks/voice/index.cjs.map +1 -0
  426. package/dist/hooks/voice/index.d.ts +2 -0
  427. package/dist/hooks/voice/index.d.ts.map +1 -0
  428. package/dist/hooks/voice/index.js +86 -0
  429. package/dist/hooks/voice/index.js.map +1 -0
  430. package/dist/hooks/voice/use-read-aloud.d.ts +20 -0
  431. package/dist/hooks/voice/use-read-aloud.d.ts.map +1 -0
  432. package/dist/hooks/workflows/index.cjs +173 -0
  433. package/dist/hooks/workflows/index.cjs.map +1 -0
  434. package/dist/hooks/workflows/index.d.ts +7 -0
  435. package/dist/hooks/workflows/index.d.ts.map +1 -0
  436. package/dist/hooks/workflows/index.js +157 -0
  437. package/dist/hooks/workflows/index.js.map +1 -0
  438. package/dist/hooks/workflows/use-workflow-runs.d.ts +51 -0
  439. package/dist/hooks/workflows/use-workflow-runs.d.ts.map +1 -0
  440. package/dist/hooks/workflows/use-workflow.d.ts +14 -0
  441. package/dist/hooks/workflows/use-workflow.d.ts.map +1 -0
  442. package/dist/hooks/workflows/use-workflows-run-counts.d.ts +25 -0
  443. package/dist/hooks/workflows/use-workflows-run-counts.d.ts.map +1 -0
  444. package/dist/hooks/workflows/use-workflows.d.ts +10 -0
  445. package/dist/hooks/workflows/use-workflows.d.ts.map +1 -0
  446. package/dist/hooks/workspace/client-utils.d.ts +5 -0
  447. package/dist/hooks/workspace/client-utils.d.ts.map +1 -0
  448. package/dist/hooks/workspace/compatibility.d.ts +22 -0
  449. package/dist/hooks/workspace/compatibility.d.ts.map +1 -0
  450. package/dist/hooks/workspace/file-type.d.ts +7 -0
  451. package/dist/hooks/workspace/file-type.d.ts.map +1 -0
  452. package/dist/hooks/workspace/index.cjs +624 -0
  453. package/dist/hooks/workspace/index.cjs.map +1 -0
  454. package/dist/hooks/workspace/index.d.ts +11 -0
  455. package/dist/hooks/workspace/index.d.ts.map +1 -0
  456. package/dist/hooks/workspace/index.js +594 -0
  457. package/dist/hooks/workspace/index.js.map +1 -0
  458. package/dist/hooks/workspace/types.d.ts +199 -0
  459. package/dist/hooks/workspace/types.d.ts.map +1 -0
  460. package/dist/hooks/workspace/use-skills-sh.d.ts +104 -0
  461. package/dist/hooks/workspace/use-skills-sh.d.ts.map +1 -0
  462. package/dist/hooks/workspace/use-stored-workspaces.d.ts +12 -0
  463. package/dist/hooks/workspace/use-stored-workspaces.d.ts.map +1 -0
  464. package/dist/hooks/workspace/use-workspace-directory.d.ts +13 -0
  465. package/dist/hooks/workspace/use-workspace-directory.d.ts.map +1 -0
  466. package/dist/hooks/workspace/use-workspace-file-content.d.ts +15 -0
  467. package/dist/hooks/workspace/use-workspace-file-content.d.ts.map +1 -0
  468. package/dist/hooks/workspace/use-workspace-search.d.ts +20 -0
  469. package/dist/hooks/workspace/use-workspace-search.d.ts.map +1 -0
  470. package/dist/hooks/workspace/use-workspace-skills.d.ts +23 -0
  471. package/dist/hooks/workspace/use-workspace-skills.d.ts.map +1 -0
  472. package/dist/hooks/workspace/use-workspace.d.ts +56 -0
  473. package/dist/hooks/workspace/use-workspace.d.ts.map +1 -0
  474. package/dist/hooks-BFQK_s4g.js +1231 -0
  475. package/dist/hooks-BFQK_s4g.js.map +1 -0
  476. package/dist/hooks-CMjizg6y.cjs +1248 -0
  477. package/dist/hooks-CMjizg6y.cjs.map +1 -0
  478. package/dist/hooks-CjULNHpJ.js +252 -0
  479. package/dist/hooks-CjULNHpJ.js.map +1 -0
  480. package/dist/hooks-DsDYaJ3T.cjs +269 -0
  481. package/dist/hooks-DsDYaJ3T.cjs.map +1 -0
  482. package/dist/index.cjs +21 -3434
  483. package/dist/index.cjs.map +1 -1
  484. package/dist/index.d.ts +1 -0
  485. package/dist/index.d.ts.map +1 -1
  486. package/dist/index.js +6 -3419
  487. package/dist/index.js.map +1 -1
  488. package/dist/lib/mastra-db/fromCoreUserMessage.d.ts +3 -4
  489. package/dist/lib/mastra-db/fromCoreUserMessage.d.ts.map +1 -1
  490. package/dist/map-CDv4fbu4.js +12 -0
  491. package/dist/map-CDv4fbu4.js.map +1 -0
  492. package/dist/map-wjmL1y5O.cjs +17 -0
  493. package/dist/map-wjmL1y5O.cjs.map +1 -0
  494. package/dist/mastra-client-context-Bx_g84YB.js +50 -0
  495. package/dist/mastra-client-context-Bx_g84YB.js.map +1 -0
  496. package/dist/mastra-client-context-DzX3f0RF.cjs +61 -0
  497. package/dist/mastra-client-context-DzX3f0RF.cjs.map +1 -0
  498. package/dist/query-utils-CcrChYgz.cjs +174 -0
  499. package/dist/query-utils-CcrChYgz.cjs.map +1 -0
  500. package/dist/query-utils-D1NgFnWU.js +127 -0
  501. package/dist/query-utils-D1NgFnWU.js.map +1 -0
  502. package/dist/use-in-view-B6eJO9Zi.cjs +37 -0
  503. package/dist/use-in-view-B6eJO9Zi.cjs.map +1 -0
  504. package/dist/use-in-view-C9sYPGRm.js +32 -0
  505. package/dist/use-in-view-C9sYPGRm.js.map +1 -0
  506. package/dist/voice-BOtUdMi8.cjs +281 -0
  507. package/dist/voice-BOtUdMi8.cjs.map +1 -0
  508. package/dist/voice-DgirjEyH.js +264 -0
  509. package/dist/voice-DgirjEyH.js.map +1 -0
  510. package/package.json +33 -4
package/dist/index.js CHANGED
@@ -1,52 +1,10 @@
1
- import { MastraClient } from "@mastra/client-js";
2
- import { createContext, memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
1
+ import { n as useMastraClient, t as MastraClientProvider } from "./mastra-client-context-Bx_g84YB.js";
2
+ import { a as CLIENT_MESSAGE_ID_KEY, i as mapWorkflowStreamChunkToWatchResult, n as accumulateNetworkChunk, r as finishStreamingAssistantMessage, t as accumulateChunk } from "./accumulator-B1MuNX3j.js";
3
+ import { n as fromCoreUserMessageToMastraDBMessage, r as fromCoreUserMessagesToMastraDBMessage, t as useChat } from "./hooks-BFQK_s4g.js";
4
+ import { n as useCreateWorkflowRun, r as useStreamWorkflow, t as useCancelWorkflowRun } from "./hooks-CjULNHpJ.js";
5
+ import { n as playStreamWithWebAudio, r as recordMicrophoneToFile, t as useSpeechRecognition } from "./voice-DgirjEyH.js";
6
+ import { memo } from "react";
3
7
  import { Fragment as Fragment$1, jsx } from "react/jsx-runtime";
4
- import { v4 } from "@lukeed/uuid";
5
- import { AIV5Adapter } from "@mastra/core/agent/message-list";
6
- //#region src/mastra-client-context.tsx
7
- const MastraClientContext = createContext({});
8
- const MastraClientProvider = ({ children, baseUrl, headers, apiPrefix, credentials = "include", customFetch }) => {
9
- const client = useMemo(() => createMastraClient(baseUrl, headers, apiPrefix, credentials, customFetch), [
10
- baseUrl,
11
- headers,
12
- apiPrefix,
13
- credentials,
14
- customFetch
15
- ]);
16
- return /* @__PURE__ */ jsx(MastraClientContext.Provider, {
17
- value: client,
18
- children
19
- });
20
- };
21
- const useMastraClient = () => useContext(MastraClientContext);
22
- const IPV4_LOOPBACK_RE = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
23
- const isIPv4Loopback = (hostname) => {
24
- const m = IPV4_LOOPBACK_RE.exec(hostname);
25
- if (!m) return false;
26
- return +m[1] <= 255 && +m[2] <= 255 && +m[3] <= 255;
27
- };
28
- const isLocalUrl = (url) => {
29
- if (!url) return true;
30
- try {
31
- const { hostname } = new URL(url);
32
- return hostname === "localhost" || hostname.endsWith(".localhost") || isIPv4Loopback(hostname) || hostname === "::1" || hostname === "[::1]";
33
- } catch {
34
- return false;
35
- }
36
- };
37
- const createMastraClient = (baseUrl, mastraClientHeaders = {}, apiPrefix, credentials = "include", customFetch) => {
38
- return new MastraClient({
39
- baseUrl: baseUrl || "",
40
- headers: isLocalUrl(baseUrl) ? {
41
- ...mastraClientHeaders,
42
- "x-mastra-dev-playground": "true"
43
- } : mastraClientHeaders,
44
- apiPrefix,
45
- credentials,
46
- fetch: customFetch
47
- });
48
- };
49
- //#endregion
50
8
  //#region src/mastra-react-provider.tsx
51
9
  const MastraReactProvider = ({ children, baseUrl, headers, apiPrefix, credentials, customFetch }) => {
52
10
  return /* @__PURE__ */ jsx(MastraClientProvider, {
@@ -59,3118 +17,6 @@ const MastraReactProvider = ({ children, baseUrl, headers, apiPrefix, credential
59
17
  });
60
18
  };
61
19
  //#endregion
62
- //#region src/agent/signal-data.ts
63
- const uint8ArrayToBase64 = (bytes) => {
64
- const chunkSize = 32768;
65
- let binary = "";
66
- for (let i = 0; i < bytes.length; i += chunkSize) binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));
67
- return btoa(binary);
68
- };
69
- function convertSignalDataToBase64String(content) {
70
- if (typeof content === "string") return content;
71
- const bytes = content instanceof ArrayBuffer ? new Uint8Array(content) : content;
72
- return uint8ArrayToBase64(bytes);
73
- }
74
- /** Canonical DB `file` part `data` for optimistic UI and memory-shaped storage. */
75
- function encodeFilePartDataForStorage(data, mimeType) {
76
- if (typeof data === "string") return data;
77
- if (data instanceof URL) return data.toString();
78
- const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
79
- const base64 = uint8ArrayToBase64(bytes);
80
- if (base64.startsWith("data:")) return base64;
81
- return `data:${mimeType};base64,${base64}`;
82
- }
83
- //#endregion
84
- //#region src/lib/mastra-db/formatCompletionFeedback.ts
85
- const formatBaseCompletionFeedback = (result, maxIterationReached, formatScorerHeading, incompleteMessage) => {
86
- const lines = [];
87
- lines.push("#### Completion Check Results");
88
- lines.push("");
89
- lines.push(`Overall: ${result.complete ? "✅ COMPLETE" : "❌ NOT COMPLETE"}`);
90
- lines.push(`Duration: ${result.totalDuration}ms`);
91
- if (result.timedOut) lines.push("⚠️ Scoring timed out");
92
- lines.push("");
93
- for (const scorer of result.scorers) {
94
- lines.push(formatScorerHeading(scorer));
95
- lines.push(`Score: ${scorer.score} ${scorer.passed ? "✅" : "❌"}`);
96
- if (scorer.reason) lines.push(`Reason: ${scorer.reason}`);
97
- lines.push("");
98
- }
99
- if (result.complete) lines.push("✅ The task is complete.");
100
- else if (maxIterationReached) lines.push("⚠️ Max iterations reached.");
101
- else lines.push(incompleteMessage);
102
- return lines.join("\n");
103
- };
104
- const formatCompletionFeedback = (result, maxIterationReached) => {
105
- return formatBaseCompletionFeedback(result, maxIterationReached, (scorer) => `###### ${scorer.scorerName} (${scorer.scorerId})`, "🔄 Will continue working on the task.");
106
- };
107
- const formatStreamCompletionFeedback = (result, maxIterationReached) => {
108
- return formatBaseCompletionFeedback(result, maxIterationReached, (scorer) => `**${scorer.scorerName}** (${scorer.scorerId})`, "🔄 The task is not yet complete. Please continue working based on the feedback above.");
109
- };
110
- //#endregion
111
- //#region src/lib/mastra-db/types.ts
112
- /**
113
- * Canonical metadata block stored under `MastraDBMessage.content.metadata`.
114
- *
115
- * Every UX hint the React accumulator needs to surface lives here. Mode-specific
116
- * fields are all optional so a single record can carry the union without forcing
117
- * narrowing on the consumer side.
118
- */
119
- /**
120
- * Metadata key carrying a client-generated correlation id. The optimistic
121
- * pending user bubble and the outgoing `sendMessage` request both stamp this
122
- * id; the server echoes it back on the `data-user-message` data part so the
123
- * accumulator can reconcile the pending bubble deterministically (decoupled
124
- * from the server-assigned signal id). This is transient client state and is
125
- * stripped once the echo is reconciled and on reload.
126
- */
127
- const CLIENT_MESSAGE_ID_KEY = "clientMessageId";
128
- //#endregion
129
- //#region src/lib/mastra-db/accumulator.ts
130
- function toolErrorText(error) {
131
- if (error && typeof error === "object") {
132
- if ("message" in error && typeof error.message === "string") return error.message;
133
- if ("cause" in error) {
134
- const cause = error.cause;
135
- if (cause && typeof cause === "object") {
136
- if (("id" in cause ? cause.id : "code" in cause ? cause.code : void 0) === "AGENT_AGENT_TOOL_EXECUTION_FAILED" && "message" in cause && typeof cause.message === "string") return cause.message;
137
- }
138
- }
139
- }
140
- return String(error);
141
- }
142
- /**
143
- * Agent-as-tool boundaries wrap progressive chunks in nested `tool-output`
144
- * envelopes. Peel only agent boundaries; workflow/tool envelopes remain the
145
- * leaf so existing child-message accumulation can process them normally.
146
- */
147
- const normalizeNestedAgentOutput = (output) => {
148
- const boundaries = [];
149
- const seen = /* @__PURE__ */ new Set();
150
- let current = output;
151
- while (current !== null && typeof current === "object") {
152
- if (seen.has(current)) return void 0;
153
- seen.add(current);
154
- const chunk = current;
155
- if (chunk.type !== "tool-output") return {
156
- leaf: current,
157
- boundaries
158
- };
159
- const toolCallId = chunk.payload?.toolCallId;
160
- const toolName = chunk.payload?.toolName;
161
- if (typeof toolName !== "string" || !toolName.startsWith("agent-")) return {
162
- leaf: current,
163
- boundaries
164
- };
165
- if (typeof toolCallId !== "string" || !("output" in (chunk.payload ?? {}))) return void 0;
166
- boundaries.push({
167
- toolCallId,
168
- toolName
169
- });
170
- current = chunk.payload?.output;
171
- }
172
- };
173
- const cloneMetadata = (metadata) => metadata ? { ...metadata } : {};
174
- const withParts = (message, parts) => ({
175
- ...message,
176
- content: {
177
- ...message.content,
178
- parts
179
- }
180
- });
181
- const withMetadata = (message, metadata) => ({
182
- ...message,
183
- content: {
184
- ...message.content,
185
- metadata
186
- }
187
- });
188
- const clearPendingStatus = (message) => {
189
- const { status: _status, [CLIENT_MESSAGE_ID_KEY]: _clientMessageId, ...rest } = message.content.metadata ?? {};
190
- return withMetadata(message, rest);
191
- };
192
- const clearPendingStatusKeepClientId = (message) => {
193
- const { status: _status, ...rest } = message.content.metadata ?? {};
194
- return withMetadata(message, rest);
195
- };
196
- const replaceLast = (conversation, message) => [...conversation.slice(0, -1), message];
197
- const replaceAt = (conversation, index, message) => [
198
- ...conversation.slice(0, index),
199
- message,
200
- ...conversation.slice(index + 1)
201
- ];
202
- const newAssistantMessage = (id, parts, metadata) => ({
203
- id,
204
- role: "assistant",
205
- createdAt: /* @__PURE__ */ new Date(),
206
- content: {
207
- format: 2,
208
- parts,
209
- metadata: cloneMetadata(metadata)
210
- }
211
- });
212
- const appendAssistantMessage = (conversation, id, parts, metadata) => [...conversation, newAssistantMessage(id, parts, metadata)];
213
- const isToolPart = (part) => part.type === "tool-invocation";
214
- const partTextId = (part) => part.type === "text" ? part.textId : void 0;
215
- const partState = (part) => part.state;
216
- /**
217
- * Set any streaming text/reasoning parts on the trailing assistant message to
218
- * `state: 'done'`. Mirrors the previous `finishStreamingAssistantMessage` from
219
- * the AI-SDK accumulator.
220
- */
221
- const finishStreamingAssistantMessage = (conversation) => {
222
- const lastMessage = conversation[conversation.length - 1];
223
- if (!lastMessage || lastMessage.role !== "assistant") return conversation;
224
- if (lastMessage.content.parts.length === 0) return conversation.slice(0, -1);
225
- const nextParts = lastMessage.content.parts.map((part) => {
226
- if ((part.type === "text" || part.type === "reasoning") && partState(part) === "streaming") return {
227
- ...part,
228
- state: "done"
229
- };
230
- return part;
231
- });
232
- return replaceLast(conversation, withParts(lastMessage, nextParts));
233
- };
234
- /**
235
- * Locate the assistant message + tool part owning `toolCallId`. Prefers the
236
- * most recent assistant message and walks back up to 10 messages, matching the
237
- * historical accumulator's lookup behavior.
238
- */
239
- const locateToolPart = (messages, toolCallId, allowMetadataOnlyMatch) => {
240
- const findIndex = (parts) => parts.findIndex((part) => isToolPart(part) && part.toolInvocation.toolCallId === toolCallId);
241
- const lastMessage = messages[messages.length - 1];
242
- if (lastMessage && lastMessage.role === "assistant") {
243
- const idx = findIndex(lastMessage.content.parts);
244
- if (idx !== -1) return {
245
- messageIndex: messages.length - 1,
246
- toolPartIndex: idx
247
- };
248
- }
249
- let count = 0;
250
- const maxMessagesBack = 10;
251
- for (let i = messages.length - 1; i >= 0; i--) {
252
- if (count > maxMessagesBack) break;
253
- const message = messages[i];
254
- if (message.role !== "assistant") continue;
255
- const idx = findIndex(message.content.parts);
256
- if (idx !== -1) return {
257
- messageIndex: i,
258
- toolPartIndex: idx
259
- };
260
- count++;
261
- }
262
- if (!allowMetadataOnlyMatch) return null;
263
- for (let i = messages.length - 1; i >= 0; i--) if (messages[i].role === "assistant") return {
264
- messageIndex: i,
265
- toolPartIndex: -1
266
- };
267
- return null;
268
- };
269
- /**
270
- * Merge per-toolCallId background-task bookkeeping onto message metadata.
271
- */
272
- const mergeBgTaskMetadata = (existing, mode, args, otherMetadata) => {
273
- const base = cloneMetadata(existing);
274
- const existingBgTasks = base.backgroundTasks ?? {};
275
- const nextBgTasks = { ...existingBgTasks };
276
- if (args.perTaskEntry) {
277
- const { toolCallId, startedAt, completedAt, taskId, suspendedAt } = args.perTaskEntry;
278
- nextBgTasks[toolCallId] = {
279
- ...existingBgTasks[toolCallId] ?? { taskId },
280
- taskId,
281
- ...startedAt !== void 0 ? { startedAt } : {},
282
- ...completedAt !== void 0 ? { completedAt } : {},
283
- ...suspendedAt !== void 0 ? { suspendedAt } : {}
284
- };
285
- }
286
- const merged = {
287
- ...base,
288
- ...otherMetadata ?? {},
289
- mode,
290
- backgroundTasks: nextBgTasks
291
- };
292
- if (args.resetRunningCount) merged.runningBackgroundTasksCount = void 0;
293
- return merged;
294
- };
295
- /**
296
- * Workflow chunk accumulation. Mirrors
297
- * `mapWorkflowStreamChunkToWatchResult` from the previous accumulator.
298
- */
299
- const mapWorkflowStreamChunkToWatchResult = (prev, chunk) => {
300
- const previous = prev && typeof prev === "object" && prev.steps && typeof prev.steps === "object" ? prev : {
301
- status: "running",
302
- input: void 0,
303
- steps: {}
304
- };
305
- if (chunk.type === "workflow-start") return {
306
- input: previous.input,
307
- status: "running",
308
- steps: previous.steps
309
- };
310
- if (chunk.type === "workflow-canceled") return {
311
- ...previous,
312
- status: "canceled"
313
- };
314
- if (chunk.type === "workflow-paused") return {
315
- ...previous,
316
- status: "paused"
317
- };
318
- if (chunk.type === "workflow-finish") {
319
- const finalStatus = chunk.payload.workflowStatus;
320
- const lastStep = Object.values(previous.steps).pop();
321
- return {
322
- ...previous,
323
- status: chunk.payload.workflowStatus,
324
- ...finalStatus === "success" && lastStep?.status === "success" ? { result: lastStep?.output } : finalStatus === "failed" && lastStep?.status === "failed" ? { error: lastStep?.error } : finalStatus === "tripwire" && chunk.payload.tripwire ? { tripwire: chunk.payload.tripwire } : {}
325
- };
326
- }
327
- const stepId = chunk.payload?.id;
328
- if (stepId === void 0) return previous;
329
- const { stepCallId: _stepCallId, stepName: _stepName, ...newPayload } = chunk.payload;
330
- const newSteps = {
331
- ...previous.steps,
332
- [stepId]: {
333
- ...previous.steps[stepId],
334
- ...newPayload
335
- }
336
- };
337
- if (chunk.type === "workflow-step-start") return {
338
- ...previous,
339
- steps: newSteps
340
- };
341
- if (chunk.type === "workflow-step-suspended") {
342
- const suspended = Object.entries(newSteps).flatMap(([stepId, stepResult]) => {
343
- if (stepResult?.status === "suspended") {
344
- const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
345
- return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
346
- }
347
- return [];
348
- });
349
- return {
350
- ...previous,
351
- status: "suspended",
352
- steps: newSteps,
353
- suspendPayload: chunk.payload.suspendPayload,
354
- suspended
355
- };
356
- }
357
- if (chunk.type === "workflow-step-waiting") return {
358
- ...previous,
359
- status: "waiting",
360
- steps: newSteps
361
- };
362
- if (chunk.type === "workflow-step-progress") return {
363
- ...previous,
364
- steps: {
365
- ...previous.steps,
366
- [stepId]: {
367
- ...previous.steps[stepId],
368
- foreachProgress: {
369
- completedCount: chunk.payload.completedCount,
370
- totalCount: chunk.payload.totalCount,
371
- currentIndex: chunk.payload.currentIndex,
372
- iterationStatus: chunk.payload.iterationStatus,
373
- iterationOutput: chunk.payload.iterationOutput
374
- }
375
- }
376
- }
377
- };
378
- if (chunk.type === "workflow-step-result") return {
379
- ...previous,
380
- steps: newSteps
381
- };
382
- return previous;
383
- };
384
- const signalContentsToUserMessages = (contents, metadata) => {
385
- const makeUserMessage = (parts) => ({
386
- id: `signal-${Date.now()}`,
387
- role: "user",
388
- createdAt: /* @__PURE__ */ new Date(),
389
- content: {
390
- format: 2,
391
- parts,
392
- metadata: cloneMetadata(metadata)
393
- }
394
- });
395
- const toMessagePart = (part) => {
396
- if (!part || typeof part !== "object") return [];
397
- const typedPart = part;
398
- if (typedPart.type === "text" && typeof typedPart.text === "string") return [{
399
- type: "text",
400
- text: typedPart.text
401
- }];
402
- if (typedPart.type === "image") {
403
- const image = typedPart.image;
404
- const mimeType = typeof typedPart.mediaType === "string" ? typedPart.mediaType : typeof typedPart.mimeType === "string" ? typedPart.mimeType : "image/*";
405
- if (typeof image === "string" || image instanceof URL || image instanceof ArrayBuffer || image instanceof Uint8Array) return [{
406
- type: "file",
407
- mimeType,
408
- data: encodeFilePartDataForStorage(image, mimeType)
409
- }];
410
- return [{
411
- type: "file",
412
- mimeType,
413
- data: ""
414
- }];
415
- }
416
- if (typedPart.type === "file") {
417
- const data = typedPart.data;
418
- const mimeType = typeof typedPart.mediaType === "string" ? typedPart.mediaType : typeof typedPart.mimeType === "string" ? typedPart.mimeType : "application/octet-stream";
419
- if (typeof data === "string" || data instanceof URL || data instanceof ArrayBuffer || data instanceof Uint8Array) return [{
420
- type: "file",
421
- mimeType,
422
- data: encodeFilePartDataForStorage(data, mimeType),
423
- ...typeof typedPart.filename === "string" ? { filename: typedPart.filename } : {}
424
- }];
425
- return [{
426
- type: "file",
427
- mimeType,
428
- data: typeof typedPart.url === "string" ? typedPart.url : "",
429
- ...typeof typedPart.filename === "string" ? { filename: typedPart.filename } : {}
430
- }];
431
- }
432
- return [];
433
- };
434
- if (typeof contents === "string") return [makeUserMessage([{
435
- type: "text",
436
- text: contents
437
- }])];
438
- if (Array.isArray(contents)) {
439
- const parts = contents.flatMap(toMessagePart);
440
- return parts.length ? [makeUserMessage(parts)] : contents.flatMap((content) => signalContentsToUserMessages(content, metadata));
441
- }
442
- if (!contents || typeof contents !== "object") return [];
443
- const message = contents;
444
- if (message.role && message.role !== "user") return [];
445
- const content = message.content;
446
- if (typeof content === "string") return [makeUserMessage([{
447
- type: "text",
448
- text: content
449
- }])];
450
- if (!Array.isArray(content)) return [];
451
- const parts = content.flatMap(toMessagePart);
452
- return parts.length ? [makeUserMessage(parts)] : [];
453
- };
454
- const reconcilePendingUserEcho = (message, echoedContents, metadata, options) => {
455
- const echoedParts = signalContentsToUserMessages(echoedContents, metadata)[0]?.content.parts;
456
- let reconciled = typeof options.signalId === "string" ? {
457
- ...message,
458
- id: options.signalId
459
- } : message;
460
- if (echoedParts?.length) reconciled = {
461
- ...reconciled,
462
- content: {
463
- ...reconciled.content,
464
- parts: echoedParts
465
- }
466
- };
467
- return options.keepClientMessageId ? clearPendingStatusKeepClientId(reconciled) : clearPendingStatus(reconciled);
468
- };
469
- const makeToolInvocationPart = (invocation) => ({
470
- type: "tool-invocation",
471
- toolInvocation: invocation
472
- });
473
- /**
474
- * Narrow the chunk to the template-literal passthrough variants from
475
- * `NetworkChunkType`. Encoded as a type guard so the surrounding `switch`
476
- * statement can stay exhaustive over the remaining string-literal cases.
477
- */
478
- const isTemplateLiteralPassthrough = (chunk) => chunk.type.startsWith("agent-execution-event-") || chunk.type.startsWith("workflow-execution-event-");
479
- /**
480
- * Narrow the chunk to the `data-${string}` family. Used so the trailing
481
- * exhaustiveness check can prove the switch covers every remaining variant.
482
- */
483
- const isDataChunk$2 = (chunk) => chunk.type.startsWith("data-");
484
- /**
485
- * Reduce a single stream chunk into the running `MastraDBMessage[]`
486
- * conversation. The accumulator owns the entire chunk→DB mapping for the
487
- * React SDK; consumers downstream (e.g. `toAISdkV5Messages` in the playground)
488
- * translate the result into AI SDK / assistant-ui shapes as needed.
489
- */
490
- const accumulateChunk = ({ chunk, conversation, metadata }) => {
491
- const result = [...conversation];
492
- if (isTemplateLiteralPassthrough(chunk)) return result;
493
- if (isDataChunk$2(chunk)) {
494
- if (chunk.type === "data-user-message" && "data" in chunk && (chunk.data?.type === "user-message" || chunk.data?.type === "user")) {
495
- const signalId = chunk.data.id;
496
- const echoedClientMessageId = chunk.data?.metadata?.[CLIENT_MESSAGE_ID_KEY];
497
- if (typeof echoedClientMessageId === "string" && result.some((message) => message.content.metadata?.status === "pending" && message.content.metadata["clientMessageId"] === echoedClientMessageId)) return finishStreamingAssistantMessage(result.map((message) => message.content.metadata?.status === "pending" && message.content.metadata["clientMessageId"] === echoedClientMessageId ? reconcilePendingUserEcho(message, chunk.data.contents, metadata, {
498
- signalId: typeof signalId === "string" ? signalId : void 0,
499
- keepClientMessageId: true
500
- }) : message));
501
- if (typeof signalId === "string" && result.some((message) => message.id === signalId)) return finishStreamingAssistantMessage(result.map((message) => message.id === signalId && message.content.metadata?.status === "pending" ? reconcilePendingUserEcho(message, chunk.data.contents, metadata, { keepClientMessageId: false }) : message));
502
- const userMessages = signalContentsToUserMessages(chunk.data.contents, metadata);
503
- if (!userMessages.length) return result;
504
- const conversationWithFinishedAssistant = finishStreamingAssistantMessage(result);
505
- const messageIdPrefix = typeof signalId === "string" ? signalId : `signal-${chunk.runId}-${Date.now()}`;
506
- return [...conversationWithFinishedAssistant, ...userMessages.map((message, index) => ({
507
- ...message,
508
- id: index === 0 ? messageIdPrefix : `${messageIdPrefix}-${index}`
509
- }))];
510
- }
511
- const dataPart = {
512
- type: chunk.type,
513
- data: "data" in chunk ? chunk.data : void 0,
514
- ..."id" in chunk && typeof chunk.id === "string" ? { id: chunk.id } : {}
515
- };
516
- const lastMessage = result[result.length - 1];
517
- if (!lastMessage || lastMessage.role !== "assistant") return appendAssistantMessage(result, `data-${chunk.runId}-${Date.now()}`, [dataPart], metadata);
518
- return replaceLast(result, withParts(lastMessage, [...lastMessage.content.parts, dataPart]));
519
- }
520
- switch (chunk.type) {
521
- case "tripwire": {
522
- const newMessage = newAssistantMessage(`tripwire-${chunk.runId + Date.now()}`, [{
523
- type: "text",
524
- text: chunk.payload.reason
525
- }], {
526
- ...metadata,
527
- status: "tripwire",
528
- tripwire: {
529
- reason: chunk.payload.reason,
530
- retry: chunk.payload.retry,
531
- metadata: chunk.payload.metadata,
532
- processorId: chunk.payload.processorId
533
- }
534
- });
535
- return [...result, newMessage];
536
- }
537
- case "start": {
538
- const messageId = typeof chunk.payload?.messageId === "string" ? chunk.payload.messageId : void 0;
539
- if (messageId && result.some((message) => message.id === messageId)) return result;
540
- return [...result, newAssistantMessage(messageId ?? `start-${chunk.runId + Date.now()}`, [], metadata)];
541
- }
542
- case "text-start": {
543
- const lastMessage = result[result.length - 1];
544
- const textId = chunk.payload.id || `text-${Date.now()}`;
545
- const tailPart = lastMessage?.content.parts[lastMessage.content.parts.length - 1];
546
- if (chunk.payload.id && lastMessage?.role === "assistant" && tailPart?.type === "text" && partTextId(tailPart) === textId) return result;
547
- const newTextPart = {
548
- type: "text",
549
- text: "",
550
- state: "streaming",
551
- textId,
552
- providerMetadata: chunk.payload.providerMetadata
553
- };
554
- if (!lastMessage || lastMessage.role !== "assistant") return appendAssistantMessage(result, `start-${chunk.runId}-${Date.now()}`, [newTextPart], metadata);
555
- if (lastMessage.content.metadata?.completionResult) return appendAssistantMessage(result, `start-${chunk.runId}-${Date.now()}`, [newTextPart], metadata);
556
- return replaceLast(result, withParts(lastMessage, [...lastMessage.content.parts, newTextPart]));
557
- }
558
- case "background-task-progress": {
559
- const lastMessage = result[result.length - 1];
560
- if (!lastMessage || lastMessage.role !== "assistant") return result;
561
- return replaceLast(result, withMetadata(lastMessage, {
562
- mode: metadata.mode,
563
- ...lastMessage.content.metadata,
564
- runningBackgroundTasksCount: chunk.payload.runningCount
565
- }));
566
- }
567
- case "text-delta": {
568
- const lastMessage = result[result.length - 1];
569
- const textId = chunk.payload.id;
570
- if (!lastMessage || lastMessage.role !== "assistant") {
571
- const newTextPart = {
572
- type: "text",
573
- text: chunk.payload.text,
574
- state: "streaming",
575
- textId,
576
- providerMetadata: chunk.payload.providerMetadata
577
- };
578
- return appendAssistantMessage(result, `text-${chunk.runId}-${Date.now()}`, [newTextPart], metadata);
579
- }
580
- const parts = [...lastMessage.content.parts];
581
- let textPartIndex = textId ? parts.findLastIndex((part) => part.type === "text" && partTextId(part) === textId) : -1;
582
- if (textPartIndex === -1) textPartIndex = parts.findLastIndex((part) => part.type === "text" && partState(part) === "streaming");
583
- if (textPartIndex !== -1 && parts.some((part, index) => index > textPartIndex && part.type !== "text")) textPartIndex = -1;
584
- if (textPartIndex === -1) {
585
- const newTextPart = {
586
- type: "text",
587
- text: chunk.payload.text,
588
- state: "streaming",
589
- textId,
590
- providerMetadata: chunk.payload.providerMetadata
591
- };
592
- parts.push(newTextPart);
593
- } else {
594
- const textPart = parts[textPartIndex];
595
- parts[textPartIndex] = {
596
- ...textPart,
597
- text: textPart.text + chunk.payload.text,
598
- state: "streaming"
599
- };
600
- }
601
- return replaceLast(result, withParts(lastMessage, parts));
602
- }
603
- case "text-end": return result;
604
- case "reasoning-start": {
605
- const lastMessage = result[result.length - 1];
606
- const newReasoningPart = {
607
- type: "reasoning",
608
- reasoning: "",
609
- state: "streaming",
610
- providerMetadata: chunk.payload.providerMetadata
611
- };
612
- if (!lastMessage || lastMessage.role !== "assistant") return appendAssistantMessage(result, `reasoning-${chunk.runId + Date.now()}`, [newReasoningPart], metadata);
613
- return replaceLast(result, withParts(lastMessage, [...lastMessage.content.parts, newReasoningPart]));
614
- }
615
- case "reasoning-delta": {
616
- const lastMessage = result[result.length - 1];
617
- if (!lastMessage || lastMessage.role !== "assistant") {
618
- const newReasoningPart = {
619
- type: "reasoning",
620
- reasoning: chunk.payload.text,
621
- state: "streaming",
622
- providerMetadata: chunk.payload.providerMetadata
623
- };
624
- return appendAssistantMessage(result, `reasoning-${chunk.runId + Date.now()}`, [newReasoningPart], metadata);
625
- }
626
- const parts = [...lastMessage.content.parts];
627
- const lastIndex = parts.length - 1;
628
- const lastPart = parts[lastIndex];
629
- if (lastPart?.type === "reasoning") {
630
- const reasoningPart = lastPart;
631
- parts[lastIndex] = {
632
- ...reasoningPart,
633
- reasoning: reasoningPart.reasoning + chunk.payload.text,
634
- state: "streaming"
635
- };
636
- } else {
637
- const newReasoningPart = {
638
- type: "reasoning",
639
- reasoning: chunk.payload.text,
640
- state: "streaming",
641
- providerMetadata: chunk.payload.providerMetadata
642
- };
643
- parts.push(newReasoningPart);
644
- }
645
- return replaceLast(result, withParts(lastMessage, parts));
646
- }
647
- case "reasoning-end": {
648
- const lastMessage = result[result.length - 1];
649
- if (!lastMessage || lastMessage.role !== "assistant") return result;
650
- const parts = [...lastMessage.content.parts];
651
- const reasoningIndex = parts.findLastIndex((part) => part.type === "reasoning" && partState(part) === "streaming");
652
- if (reasoningIndex === -1) return result;
653
- const reasoningPart = parts[reasoningIndex];
654
- const existingMeta = reasoningPart.providerMetadata;
655
- const endMeta = chunk.payload.providerMetadata;
656
- parts[reasoningIndex] = {
657
- ...reasoningPart,
658
- state: "done",
659
- ...existingMeta || endMeta ? { providerMetadata: {
660
- ...existingMeta ?? {},
661
- ...endMeta ?? {}
662
- } } : {}
663
- };
664
- return replaceLast(result, withParts(lastMessage, parts));
665
- }
666
- case "reasoning-signature": {
667
- const lastMessage = result[result.length - 1];
668
- if (!lastMessage || lastMessage.role !== "assistant") return result;
669
- const parts = [...lastMessage.content.parts];
670
- const reasoningIndex = parts.findLastIndex((part) => part.type === "reasoning");
671
- if (reasoningIndex === -1) return result;
672
- const reasoningPart = parts[reasoningIndex];
673
- const existingMeta = reasoningPart.providerMetadata;
674
- const sigMeta = chunk.payload.providerMetadata;
675
- parts[reasoningIndex] = {
676
- ...reasoningPart,
677
- ...existingMeta || sigMeta ? { providerMetadata: {
678
- ...existingMeta ?? {},
679
- ...sigMeta ?? {}
680
- } } : {}
681
- };
682
- return replaceLast(result, withParts(lastMessage, parts));
683
- }
684
- case "redacted-reasoning": {
685
- const lastMessage = result[result.length - 1];
686
- const redactedData = chunk.payload.data;
687
- const redactedPart = {
688
- type: "reasoning",
689
- reasoning: typeof redactedData === "string" ? redactedData : "",
690
- state: "done",
691
- redacted: true,
692
- providerMetadata: chunk.payload.providerMetadata
693
- };
694
- if (!lastMessage || lastMessage.role !== "assistant") return appendAssistantMessage(result, `redacted-reasoning-${chunk.runId + Date.now()}`, [redactedPart], metadata);
695
- return replaceLast(result, withParts(lastMessage, [...lastMessage.content.parts, redactedPart]));
696
- }
697
- case "tool-call": {
698
- const invocation = {
699
- state: "call",
700
- toolCallId: chunk.payload.toolCallId,
701
- toolName: chunk.payload.toolName,
702
- args: chunk.payload.args
703
- };
704
- const newPart = {
705
- ...makeToolInvocationPart(invocation),
706
- title: chunk.payload.title,
707
- providerMetadata: chunk.payload.providerMetadata
708
- };
709
- const existing = locateToolPart(result, chunk.payload.toolCallId, false);
710
- if (existing && existing.toolPartIndex >= 0) {
711
- const { messageIndex, toolPartIndex } = existing;
712
- const targetMessage = result[messageIndex];
713
- if (targetMessage && targetMessage.role === "assistant") {
714
- const parts = [...targetMessage.content.parts];
715
- const prev = parts[toolPartIndex];
716
- if (isToolPart(prev)) {
717
- const { argsText: _argsText, ...rest } = prev;
718
- parts[toolPartIndex] = {
719
- ...rest,
720
- toolInvocation: {
721
- ...prev.toolInvocation,
722
- state: "call",
723
- toolName: chunk.payload.toolName,
724
- toolCallId: chunk.payload.toolCallId,
725
- args: chunk.payload.args
726
- },
727
- title: chunk.payload.title ?? prev.title,
728
- providerMetadata: chunk.payload.providerMetadata ?? prev.providerMetadata
729
- };
730
- return replaceAt(result, messageIndex, withParts(targetMessage, parts));
731
- }
732
- }
733
- }
734
- const lastMessage = result[result.length - 1];
735
- if (!lastMessage || lastMessage.role !== "assistant") return appendAssistantMessage(result, `tool-call-${chunk.runId + Date.now()}`, [newPart], metadata);
736
- return replaceLast(result, withParts(lastMessage, [...lastMessage.content.parts, newPart]));
737
- }
738
- case "tool-call-input-streaming-start": {
739
- const lastMessage = result[result.length - 1];
740
- const invocation = {
741
- state: "partial-call",
742
- toolCallId: chunk.payload.toolCallId,
743
- toolName: chunk.payload.toolName,
744
- args: {}
745
- };
746
- const newPart = {
747
- ...makeToolInvocationPart(invocation),
748
- title: chunk.payload.title,
749
- argsText: ""
750
- };
751
- if (!lastMessage || lastMessage.role !== "assistant") return appendAssistantMessage(result, `tool-call-streaming-${chunk.runId + Date.now()}`, [newPart], metadata);
752
- return replaceLast(result, withParts(lastMessage, [...lastMessage.content.parts, newPart]));
753
- }
754
- case "tool-call-delta": {
755
- const location = locateToolPart(result, chunk.payload.toolCallId, false);
756
- if (!location || location.toolPartIndex < 0) return result;
757
- const { messageIndex, toolPartIndex } = location;
758
- const targetMessage = result[messageIndex];
759
- if (!targetMessage || targetMessage.role !== "assistant") return result;
760
- const parts = [...targetMessage.content.parts];
761
- const toolPart = parts[toolPartIndex];
762
- if (!isToolPart(toolPart)) return result;
763
- const nextArgsText = (toolPart.argsText ?? "") + (chunk.payload.argsTextDelta ?? "");
764
- parts[toolPartIndex] = {
765
- ...toolPart,
766
- argsText: nextArgsText,
767
- toolInvocation: {
768
- ...toolPart.toolInvocation,
769
- state: "partial-call"
770
- }
771
- };
772
- return replaceAt(result, messageIndex, withParts(targetMessage, parts));
773
- }
774
- case "tool-call-input-streaming-end": {
775
- const location = locateToolPart(result, chunk.payload.toolCallId, false);
776
- if (!location || location.toolPartIndex < 0) return result;
777
- const { messageIndex, toolPartIndex } = location;
778
- const targetMessage = result[messageIndex];
779
- if (!targetMessage || targetMessage.role !== "assistant") return result;
780
- const parts = [...targetMessage.content.parts];
781
- const toolPart = parts[toolPartIndex];
782
- if (!isToolPart(toolPart)) return result;
783
- let parsedArgs = {};
784
- const argsText = toolPart.argsText;
785
- if (typeof argsText === "string" && argsText.length > 0) try {
786
- const maybe = JSON.parse(argsText);
787
- if (maybe && typeof maybe === "object" && !Array.isArray(maybe)) parsedArgs = maybe;
788
- } catch {
789
- parsedArgs = {};
790
- }
791
- parts[toolPartIndex] = {
792
- ...toolPart,
793
- toolInvocation: {
794
- ...toolPart.toolInvocation,
795
- state: "call",
796
- args: parsedArgs
797
- }
798
- };
799
- return replaceAt(result, messageIndex, withParts(targetMessage, parts));
800
- }
801
- case "tool-output-denied": {
802
- const location = locateToolPart(result, chunk.payload.toolCallId, false);
803
- if (!location || location.toolPartIndex < 0) return result;
804
- const { messageIndex, toolPartIndex } = location;
805
- const targetMessage = result[messageIndex];
806
- if (!targetMessage || targetMessage.role !== "assistant") return result;
807
- const parts = [...targetMessage.content.parts];
808
- const toolPart = parts[toolPartIndex];
809
- if (!isToolPart(toolPart)) return result;
810
- parts[toolPartIndex] = {
811
- ...toolPart,
812
- toolInvocation: {
813
- ...toolPart.toolInvocation,
814
- state: "output-denied",
815
- toolName: chunk.payload.toolName,
816
- args: chunk.payload.args ?? toolPart.toolInvocation.args,
817
- approval: chunk.payload.approval
818
- }
819
- };
820
- return replaceAt(result, messageIndex, withParts(targetMessage, parts));
821
- }
822
- case "tool-error":
823
- case "tool-result":
824
- case "background-task-completed":
825
- case "background-task-failed": {
826
- const isBgTaskEvent = chunk.type === "background-task-completed" || chunk.type === "background-task-failed";
827
- const location = locateToolPart(result, chunk.payload.toolCallId, isBgTaskEvent);
828
- if (!location) return result;
829
- const { messageIndex, toolPartIndex } = location;
830
- const targetMessage = result[messageIndex];
831
- if (!targetMessage || targetMessage.role !== "assistant") return result;
832
- const parts = [...targetMessage.content.parts];
833
- const toolPart = toolPartIndex >= 0 ? parts[toolPartIndex] : void 0;
834
- let payloadResult;
835
- let payloadError;
836
- let payloadIsError = false;
837
- let payloadProviderMetadata;
838
- let payloadCompletedAt;
839
- let payloadTaskId;
840
- switch (chunk.type) {
841
- case "tool-result":
842
- payloadResult = chunk.payload.result;
843
- payloadIsError = Boolean(chunk.payload.isError);
844
- payloadProviderMetadata = chunk.payload.providerMetadata;
845
- break;
846
- case "tool-error":
847
- payloadError = chunk.payload.error;
848
- payloadProviderMetadata = chunk.payload.providerMetadata;
849
- break;
850
- case "background-task-completed":
851
- payloadResult = chunk.payload.result;
852
- payloadCompletedAt = chunk.payload.completedAt;
853
- payloadTaskId = chunk.payload.taskId;
854
- break;
855
- case "background-task-failed":
856
- payloadError = chunk.payload.error;
857
- payloadCompletedAt = chunk.payload.completedAt;
858
- payloadTaskId = chunk.payload.taskId;
859
- break;
860
- }
861
- if (toolPart && isToolPart(toolPart)) {
862
- const { toolName, toolCallId, args } = toolPart.toolInvocation;
863
- const providerMeta = payloadProviderMetadata ?? toolPart.providerMetadata;
864
- if (chunk.type === "tool-error" || chunk.type === "background-task-failed" || payloadIsError) {
865
- const errorText = toolErrorText(chunk.type === "tool-error" || chunk.type === "background-task-failed" ? payloadError : payloadResult);
866
- parts[toolPartIndex] = {
867
- ...toolPart,
868
- providerMetadata: providerMeta,
869
- toolInvocation: {
870
- state: "output-error",
871
- toolCallId,
872
- toolName,
873
- args,
874
- errorText,
875
- ...chunk.from === "AGENT" ? { result: toolPart.toolInvocation.result } : {}
876
- }
877
- };
878
- } else {
879
- const resultObj = payloadResult;
880
- const existingResult = toolPart.toolInvocation.state === "partial-call" || toolPart.toolInvocation.state === "result" ? toolPart.toolInvocation.result : void 0;
881
- const existingLooksLikeWorkflow = Boolean(existingResult && typeof existingResult === "object" && "steps" in existingResult);
882
- const isWorkflow = Boolean(resultObj?.result?.steps) || toolName?.startsWith("workflow-") || existingLooksLikeWorkflow;
883
- const isAgent = chunk.from === "AGENT";
884
- let output;
885
- if (isWorkflow) {
886
- const accumulated = existingLooksLikeWorkflow && existingResult && typeof existingResult === "object" ? existingResult : void 0;
887
- const payloadWorkflow = resultObj?.result && typeof resultObj.result === "object" ? resultObj.result : void 0;
888
- if (accumulated || payloadWorkflow) output = {
889
- ...accumulated ?? {},
890
- ...payloadWorkflow ?? {},
891
- steps: payloadWorkflow?.steps ?? accumulated?.steps ?? [],
892
- status: payloadWorkflow?.status ?? accumulated?.status ?? "success",
893
- output: payloadResult
894
- };
895
- else output = payloadResult;
896
- } else if (isAgent) {
897
- const existingOutput = toolPart.toolInvocation.state === "partial-call" || toolPart.toolInvocation.state === "result" ? toolPart.toolInvocation.result : void 0;
898
- const existingChild = existingOutput?.childMessages;
899
- output = existingOutput ? {
900
- ...payloadResult,
901
- childMessages: existingChild?.length ? existingChild : resultObj?.childMessages
902
- } : payloadResult;
903
- } else output = payloadResult;
904
- parts[toolPartIndex] = {
905
- ...toolPart,
906
- providerMetadata: providerMeta,
907
- toolInvocation: {
908
- state: "result",
909
- toolCallId,
910
- toolName,
911
- args,
912
- result: output
913
- }
914
- };
915
- }
916
- }
917
- const nextMetadata = mergeBgTaskMetadata(targetMessage.content.metadata, metadata.mode, {
918
- resetRunningCount: isBgTaskEvent,
919
- perTaskEntry: isBgTaskEvent && payloadTaskId ? {
920
- toolCallId: chunk.payload.toolCallId,
921
- completedAt: payloadCompletedAt,
922
- taskId: payloadTaskId
923
- } : void 0
924
- });
925
- const nextMessage = {
926
- ...targetMessage,
927
- content: {
928
- ...targetMessage.content,
929
- parts,
930
- metadata: nextMetadata
931
- }
932
- };
933
- return replaceAt(result, messageIndex, nextMessage);
934
- }
935
- case "background-task-running": {
936
- const location = locateToolPart(result, chunk.payload.toolCallId, true);
937
- if (!location) return result;
938
- const { messageIndex } = location;
939
- const targetMessage = result[messageIndex];
940
- if (!targetMessage || targetMessage.role !== "assistant") return result;
941
- const nextMetadata = mergeBgTaskMetadata(targetMessage.content.metadata, metadata.mode, { perTaskEntry: {
942
- toolCallId: chunk.payload.toolCallId,
943
- startedAt: chunk.payload.startedAt,
944
- taskId: chunk.payload.taskId
945
- } });
946
- return replaceAt(result, messageIndex, withMetadata(targetMessage, nextMetadata));
947
- }
948
- case "tool-output":
949
- case "background-task-output": {
950
- const isBgTaskOutput = chunk.type === "background-task-output";
951
- const location = locateToolPart(result, chunk.payload.toolCallId, isBgTaskOutput);
952
- if (!location || location.toolPartIndex < 0) return result;
953
- const { messageIndex, toolPartIndex } = location;
954
- const targetMessage = result[messageIndex];
955
- if (!targetMessage || targetMessage.role !== "assistant") return result;
956
- const parts = [...targetMessage.content.parts];
957
- const toolPart = parts[toolPartIndex];
958
- if (!isToolPart(toolPart)) return result;
959
- const { toolName, toolCallId, args } = toolPart.toolInvocation;
960
- const payloadOutput = chunk.type === "background-task-output" ? chunk.payload.payload.payload.output : chunk.payload.output;
961
- if (payloadOutput?.type?.startsWith("workflow-")) {
962
- const existingWorkflowState = toolPart.toolInvocation.result;
963
- const updated = mapWorkflowStreamChunkToWatchResult(existingWorkflowState, payloadOutput);
964
- parts[toolPartIndex] = {
965
- ...toolPart,
966
- toolInvocation: {
967
- state: "partial-call",
968
- toolCallId,
969
- toolName,
970
- args,
971
- result: updated
972
- }
973
- };
974
- } else if (toolName.startsWith("agent-") || payloadOutput?.from === "AGENT") {
975
- const normalized = normalizeNestedAgentOutput(payloadOutput);
976
- if (!normalized) return result;
977
- const { leaf, boundaries } = normalized;
978
- if (leaf.from === "AGENT" || leaf.type === "tool-output" && leaf.payload?.output?.type?.startsWith("workflow-")) return accumulateAgentChunk(leaf, result, metadata, toolCallId, toolName, boundaries);
979
- return result;
980
- } else {
981
- const currentResult = toolPart.toolInvocation.result;
982
- const existing = Array.isArray(currentResult) ? currentResult : [];
983
- parts[toolPartIndex] = {
984
- ...toolPart,
985
- toolInvocation: {
986
- state: "partial-call",
987
- toolCallId,
988
- toolName,
989
- args,
990
- result: [...existing, payloadOutput]
991
- }
992
- };
993
- }
994
- return replaceAt(result, messageIndex, withParts(targetMessage, parts));
995
- }
996
- case "is-task-complete": {
997
- if (chunk.payload.suppressFeedback) return result;
998
- const feedback = formatStreamCompletionFeedback({
999
- complete: chunk.payload.passed,
1000
- scorers: chunk.payload.results,
1001
- totalDuration: chunk.payload.duration,
1002
- timedOut: chunk.payload.timedOut,
1003
- completionReason: chunk.payload.reason
1004
- }, chunk.payload.maxIterationReached);
1005
- const newMessage = newAssistantMessage(`is-task-complete-${chunk.runId + Date.now()}`, [{
1006
- type: "text",
1007
- text: feedback
1008
- }], {
1009
- ...metadata,
1010
- completionResult: { passed: chunk.payload.passed }
1011
- });
1012
- return [...result, newMessage];
1013
- }
1014
- case "source": {
1015
- const lastMessage = result[result.length - 1];
1016
- if (!lastMessage || lastMessage.role !== "assistant") return result;
1017
- const parts = [...lastMessage.content.parts];
1018
- if (chunk.payload.sourceType === "url") {
1019
- const sourceUrlPart = {
1020
- type: "source-url",
1021
- sourceId: chunk.payload.id,
1022
- url: chunk.payload.url || "",
1023
- title: chunk.payload.title,
1024
- providerMetadata: chunk.payload.providerMetadata
1025
- };
1026
- parts.push(sourceUrlPart);
1027
- } else if (chunk.payload.sourceType === "document") parts.push({
1028
- type: "source-document",
1029
- sourceId: chunk.payload.id,
1030
- mediaType: chunk.payload.mimeType || "application/octet-stream",
1031
- title: chunk.payload.title,
1032
- filename: chunk.payload.filename,
1033
- providerMetadata: chunk.payload.providerMetadata
1034
- });
1035
- return replaceLast(result, withParts(lastMessage, parts));
1036
- }
1037
- case "file": {
1038
- const lastMessage = result[result.length - 1];
1039
- if (!lastMessage || lastMessage.role !== "assistant") return result;
1040
- const parts = [...lastMessage.content.parts];
1041
- let data;
1042
- if (typeof chunk.payload.data === "string") data = chunk.payload.base64 ? `data:${chunk.payload.mimeType};base64,${chunk.payload.data}` : `data:${chunk.payload.mimeType},${encodeURIComponent(chunk.payload.data)}`;
1043
- else {
1044
- const base64 = uint8ArrayToBase64(chunk.payload.data);
1045
- data = `data:${chunk.payload.mimeType};base64,${base64}`;
1046
- }
1047
- parts.push({
1048
- type: "file",
1049
- mimeType: chunk.payload.mimeType,
1050
- data,
1051
- providerMetadata: chunk.payload.providerMetadata
1052
- });
1053
- return replaceLast(result, withParts(lastMessage, parts));
1054
- }
1055
- case "tool-call-approval": {
1056
- const lastMessage = result[result.length - 1];
1057
- if (!lastMessage || lastMessage.role !== "assistant") return result;
1058
- const existingMeta = lastMessage.content.metadata ?? {};
1059
- const lastRequireApproval = existingMeta.mode === "stream" ? existingMeta.requireApprovalMetadata ?? {} : {};
1060
- return replaceLast(result, {
1061
- ...lastMessage,
1062
- content: {
1063
- ...lastMessage.content,
1064
- metadata: {
1065
- ...existingMeta,
1066
- mode: "stream",
1067
- requireApprovalMetadata: {
1068
- ...lastRequireApproval,
1069
- [chunk.payload.toolCallId]: {
1070
- toolCallId: chunk.payload.toolCallId,
1071
- toolName: chunk.payload.toolName,
1072
- args: chunk.payload.args
1073
- }
1074
- }
1075
- }
1076
- }
1077
- });
1078
- }
1079
- case "tool-call-suspended":
1080
- case "background-task-suspended": {
1081
- const isBgTaskEvent = chunk.type === "background-task-suspended";
1082
- let suspToolCallId;
1083
- let suspToolName;
1084
- let suspArgs;
1085
- let suspPayload;
1086
- let suspSuspendedAt;
1087
- let suspTaskId;
1088
- if (chunk.type === "background-task-suspended") {
1089
- suspToolCallId = chunk.payload.toolCallId;
1090
- suspToolName = chunk.payload.toolName;
1091
- suspArgs = chunk.payload.args;
1092
- suspPayload = chunk.payload.suspendPayload;
1093
- suspSuspendedAt = chunk.payload.suspendedAt;
1094
- suspTaskId = chunk.payload.taskId;
1095
- } else {
1096
- suspToolCallId = chunk.payload.toolCallId;
1097
- suspToolName = chunk.payload.toolName;
1098
- suspArgs = chunk.payload.args;
1099
- suspPayload = chunk.payload.suspendPayload;
1100
- }
1101
- const location = isBgTaskEvent ? locateToolPart(result, suspToolCallId, true) : { messageIndex: result.length - 1 };
1102
- if (!location) return result;
1103
- const { messageIndex } = location;
1104
- const targetMessage = result[messageIndex];
1105
- if (!targetMessage || targetMessage.role !== "assistant") return result;
1106
- const existingMeta = targetMessage.content.metadata ?? {};
1107
- const lastSuspendedTools = existingMeta.mode === "stream" ? existingMeta.suspendedTools ?? {} : {};
1108
- const nextMetadata = mergeBgTaskMetadata(existingMeta, "stream", {
1109
- resetRunningCount: isBgTaskEvent,
1110
- perTaskEntry: isBgTaskEvent && suspTaskId ? {
1111
- toolCallId: suspToolCallId,
1112
- suspendedAt: suspSuspendedAt,
1113
- taskId: suspTaskId
1114
- } : void 0
1115
- }, { suspendedTools: {
1116
- ...lastSuspendedTools,
1117
- [suspToolName]: {
1118
- toolCallId: suspToolCallId,
1119
- toolName: suspToolName,
1120
- args: suspArgs,
1121
- suspendPayload: suspPayload,
1122
- runId: chunk.runId
1123
- }
1124
- } });
1125
- return replaceAt(result, messageIndex, withMetadata(targetMessage, nextMetadata));
1126
- }
1127
- case "tool-call-resumed": {
1128
- const resumedToolCallId = chunk.payload.toolCallId;
1129
- for (let i = result.length - 1; i >= 0; i--) {
1130
- const message = result[i];
1131
- if (!message || message.role !== "assistant") continue;
1132
- const meta = message.content.metadata;
1133
- const metadataKeys = chunk.payload.kind === "approval" ? ["pendingToolApprovals", "requireApprovalMetadata"] : ["suspendedTools"];
1134
- let nextMeta;
1135
- for (const metadataKey of metadataKeys) {
1136
- const entries = meta?.[metadataKey];
1137
- if (!entries) continue;
1138
- const key = Object.keys(entries).find((k) => (entries[k]?.toolCallId ?? k) === resumedToolCallId);
1139
- if (!key) continue;
1140
- const { [key]: _removed, ...remaining } = entries;
1141
- nextMeta = {
1142
- ...nextMeta ?? meta,
1143
- [metadataKey]: remaining
1144
- };
1145
- }
1146
- if (nextMeta) return replaceAt(result, i, withMetadata(message, nextMeta));
1147
- }
1148
- return result;
1149
- }
1150
- case "finish":
1151
- case "abort": return finishStreamingAssistantMessage(result);
1152
- case "error": {
1153
- const newMessage = newAssistantMessage(`error-${chunk.runId + Date.now()}`, [{
1154
- type: "text",
1155
- text: typeof chunk.payload.error === "string" ? chunk.payload.error : JSON.stringify(chunk.payload.error)
1156
- }], {
1157
- ...metadata,
1158
- status: "error"
1159
- });
1160
- return [...result, newMessage];
1161
- }
1162
- case "step-start": {
1163
- const stepMessageId = typeof chunk.payload?.messageId === "string" ? chunk.payload.messageId : void 0;
1164
- if (!stepMessageId) return result;
1165
- const lastMessage = result[result.length - 1];
1166
- if (!lastMessage || lastMessage.role !== "assistant") return result;
1167
- if (result.some((message) => message.id === stepMessageId)) return result;
1168
- if (!lastMessage.content.parts.some((part) => !String(part.type).startsWith("data-"))) return replaceLast(result, {
1169
- ...lastMessage,
1170
- id: stepMessageId
1171
- });
1172
- return appendAssistantMessage(finishStreamingAssistantMessage(result), stepMessageId, [], metadata);
1173
- }
1174
- case "step-finish":
1175
- case "step-output":
1176
- case "raw":
1177
- case "watch":
1178
- case "response-metadata": return result;
1179
- case "goal": return result;
1180
- case "object":
1181
- case "object-result": return result;
1182
- case "background-task-started":
1183
- case "background-task-cancelled":
1184
- case "background-task-resumed": return result;
1185
- case "workflow-start":
1186
- case "workflow-finish":
1187
- case "workflow-canceled":
1188
- case "workflow-paused":
1189
- case "workflow-step-start":
1190
- case "workflow-step-finish":
1191
- case "workflow-step-suspended":
1192
- case "workflow-step-waiting":
1193
- case "workflow-step-output":
1194
- case "workflow-step-progress":
1195
- case "workflow-step-result": return result;
1196
- case "agent-execution-start":
1197
- case "agent-execution-approval":
1198
- case "agent-execution-suspended":
1199
- case "agent-execution-end":
1200
- case "agent-execution-abort":
1201
- case "tool-execution-start":
1202
- case "tool-execution-end":
1203
- case "tool-execution-approval":
1204
- case "tool-execution-suspended":
1205
- case "tool-execution-abort":
1206
- case "routing-agent-start":
1207
- case "routing-agent-text-delta":
1208
- case "routing-agent-text-start":
1209
- case "routing-agent-end":
1210
- case "routing-agent-abort":
1211
- case "workflow-execution-start":
1212
- case "workflow-execution-end":
1213
- case "workflow-execution-suspended":
1214
- case "workflow-execution-abort":
1215
- case "network-execution-event-step-finish":
1216
- case "network-execution-event-finish":
1217
- case "network-validation-start":
1218
- case "network-validation-end":
1219
- case "network-object":
1220
- case "network-object-result": return result;
1221
- default: return assertExhaustive(chunk, result);
1222
- }
1223
- };
1224
- /**
1225
- * Compile-time exhaustiveness helper. At runtime, returns the conversation
1226
- * unchanged so unexpected chunk variants never throw inside the React stream
1227
- * pump; TypeScript will fail to compile if `ChunkType` ever grows a new branch
1228
- * that isn't enumerated above.
1229
- */
1230
- const assertExhaustive = (_chunk, fallback) => fallback;
1231
- const findAgentChildToolIndex = (childMessages, toolCallId, toolName) => {
1232
- for (let index = childMessages.length - 1; index >= 0; index--) {
1233
- const message = childMessages[index];
1234
- if (message?.type !== "tool") continue;
1235
- if (toolCallId ? message.toolCallId === toolCallId : toolName && message.toolName === toolName) return index;
1236
- }
1237
- return -1;
1238
- };
1239
- const accumulateAgentChildMessages = (chunk, childMessages) => {
1240
- if (chunk.type === "text-delta") {
1241
- const text = chunk.payload.text;
1242
- const lastChildMessage = childMessages[childMessages.length - 1];
1243
- const textMessage = {
1244
- type: "text",
1245
- content: (lastChildMessage?.type === "text" ? lastChildMessage.content : "") + text
1246
- };
1247
- return lastChildMessage?.type === "text" ? [...childMessages.slice(0, -1), textMessage] : [...childMessages, textMessage];
1248
- }
1249
- if (chunk.type === "tool-call") {
1250
- const existingIndex = findAgentChildToolIndex(childMessages, chunk.payload.toolCallId);
1251
- const toolMessage = {
1252
- ...existingIndex === -1 ? {} : childMessages[existingIndex],
1253
- type: "tool",
1254
- toolCallId: chunk.payload.toolCallId,
1255
- toolName: chunk.payload.toolName,
1256
- args: chunk.payload.args
1257
- };
1258
- if (existingIndex === -1) return [...childMessages, toolMessage];
1259
- const nextMessages = [...childMessages];
1260
- nextMessages[existingIndex] = toolMessage;
1261
- return nextMessages;
1262
- }
1263
- if (chunk.type === "tool-output" && chunk.payload.output?.type?.startsWith("workflow-")) {
1264
- const toolIndex = findAgentChildToolIndex(childMessages, chunk.payload.toolCallId, chunk.payload.toolName);
1265
- if (toolIndex === -1) return childMessages;
1266
- const currentMessage = childMessages[toolIndex];
1267
- if (currentMessage?.type !== "tool") return childMessages;
1268
- const existingWorkflowState = currentMessage.toolOutput && typeof currentMessage.toolOutput === "object" ? currentMessage.toolOutput : {};
1269
- const updated = mapWorkflowStreamChunkToWatchResult(existingWorkflowState, chunk.payload.output);
1270
- const nextMessages = [...childMessages];
1271
- nextMessages[toolIndex] = {
1272
- ...currentMessage,
1273
- toolOutput: {
1274
- ...updated,
1275
- runId: chunk.payload.output.runId
1276
- }
1277
- };
1278
- return nextMessages;
1279
- }
1280
- if (chunk.type === "tool-result") {
1281
- const toolIndex = findAgentChildToolIndex(childMessages, chunk.payload.toolCallId, chunk.payload.toolName);
1282
- if (toolIndex === -1) return childMessages;
1283
- const currentMessage = childMessages[toolIndex];
1284
- if (currentMessage?.type !== "tool") return childMessages;
1285
- const result = chunk.payload.result;
1286
- const nextMessages = [...childMessages];
1287
- nextMessages[toolIndex] = {
1288
- ...currentMessage,
1289
- toolOutput: chunk.payload.toolName?.startsWith("workflow-") ? {
1290
- ...result?.result ?? {},
1291
- runId: result?.runId
1292
- } : chunk.payload.result
1293
- };
1294
- return nextMessages;
1295
- }
1296
- return childMessages;
1297
- };
1298
- const routeAgentChunk = (chunk, childMessages, boundaries) => {
1299
- const [boundary, ...remaining] = boundaries;
1300
- if (!boundary) return accumulateAgentChildMessages(chunk, childMessages);
1301
- let toolIndex = findAgentChildToolIndex(childMessages, boundary.toolCallId, boundary.toolName);
1302
- let nextMessages = childMessages;
1303
- if (toolIndex === -1) {
1304
- toolIndex = childMessages.length;
1305
- nextMessages = [...childMessages, {
1306
- type: "tool",
1307
- toolCallId: boundary.toolCallId,
1308
- toolName: boundary.toolName,
1309
- args: {}
1310
- }];
1311
- }
1312
- const currentMessage = nextMessages[toolIndex];
1313
- if (currentMessage?.type !== "tool" || !currentMessage.toolName.startsWith("agent-")) return childMessages;
1314
- const currentOutput = currentMessage.toolOutput !== null && typeof currentMessage.toolOutput === "object" ? currentMessage.toolOutput : {};
1315
- const nestedMessages = Array.isArray(currentOutput.childMessages) ? currentOutput.childMessages : [];
1316
- const updatedNestedMessages = routeAgentChunk(chunk, nestedMessages, remaining);
1317
- if (updatedNestedMessages === nestedMessages) return childMessages;
1318
- const updatedMessages = [...nextMessages];
1319
- updatedMessages[toolIndex] = {
1320
- ...currentMessage,
1321
- toolOutput: {
1322
- ...currentOutput,
1323
- childMessages: updatedNestedMessages
1324
- }
1325
- };
1326
- return updatedMessages;
1327
- };
1328
- const accumulateAgentChunk = (chunk, conversation, _metadata, parentToolCallId, parentToolName, boundaries = []) => {
1329
- if (!parentToolCallId) return conversation;
1330
- const location = locateToolPart(conversation, parentToolCallId, false);
1331
- if (!location) return conversation;
1332
- const targetMessage = conversation[location.messageIndex];
1333
- if (!targetMessage || targetMessage.role !== "assistant") return conversation;
1334
- const parts = [...targetMessage.content.parts];
1335
- const toolPart = parts[location.toolPartIndex];
1336
- if (!toolPart || !isToolPart(toolPart)) return conversation;
1337
- if (parentToolName && toolPart.toolInvocation.toolName !== parentToolName) return conversation;
1338
- const invocationResult = "result" in toolPart.toolInvocation && toolPart.toolInvocation.result !== null ? toolPart.toolInvocation.result : void 0;
1339
- const existingResult = invocationResult && typeof invocationResult === "object" ? invocationResult : {};
1340
- const childMessages = Array.isArray(existingResult.childMessages) ? existingResult.childMessages : [];
1341
- const updatedChildMessages = routeAgentChunk(chunk, childMessages, boundaries);
1342
- if (updatedChildMessages === childMessages) return conversation;
1343
- parts[location.toolPartIndex] = {
1344
- ...toolPart,
1345
- toolInvocation: {
1346
- ...toolPart.toolInvocation,
1347
- state: "partial-call",
1348
- result: {
1349
- ...existingResult,
1350
- childMessages: updatedChildMessages
1351
- }
1352
- }
1353
- };
1354
- return replaceAt(conversation, location.messageIndex, withParts(targetMessage, parts));
1355
- };
1356
- const networkMode = (metadata) => ({
1357
- ...metadata,
1358
- mode: "network"
1359
- });
1360
- const findPartIndex = (parts, predicate) => parts.findIndex(predicate);
1361
- const isDynamicToolPart = (part) => part.type === "dynamic-tool";
1362
- const lastAssistant = (conversation) => {
1363
- const last = conversation[conversation.length - 1];
1364
- return last && last.role === "assistant" ? last : void 0;
1365
- };
1366
- /**
1367
- * Try to parse the buffered routing-agent text as a JSON object. Returns the
1368
- * parsed object on success, or `null` while the buffer is still incomplete or
1369
- * not JSON at all.
1370
- */
1371
- const tryParseRoutingDecision = (buffered) => {
1372
- const trimmed = buffered.trim();
1373
- if (!trimmed.startsWith("{") && !trimmed.startsWith("[")) return null;
1374
- try {
1375
- const parsed = JSON.parse(trimmed);
1376
- if (parsed && typeof parsed === "object") return parsed;
1377
- return null;
1378
- } catch {
1379
- return null;
1380
- }
1381
- };
1382
- /**
1383
- * Routing-agent text deltas describe the network's routing decision (often a
1384
- * JSON object such as `{ "isNetwork": true, "agentId": "...", ... }`). The raw
1385
- * payload is never useful in the rendered thread, so we buffer it in
1386
- * message-level metadata, promote it to `routingDecision` when it parses as
1387
- * JSON, and fall back to `routingDecisionText` for non-JSON routing models.
1388
- * No visible text part is produced.
1389
- */
1390
- const handleRoutingAgentDelta = (chunk, conversation, metadata) => {
1391
- const delta = chunk.payload?.text ?? "";
1392
- if (!delta) return conversation;
1393
- const lastMessage = lastAssistant(conversation);
1394
- const mergeRoutingMetadata = (existing) => {
1395
- const buffered = (existing.routingDecisionBuffer ?? "") + delta;
1396
- const next = {
1397
- ...cloneMetadata(existing),
1398
- mode: "network"
1399
- };
1400
- const parsed = tryParseRoutingDecision(buffered);
1401
- if (parsed) {
1402
- next.routingDecision = parsed;
1403
- delete next.routingDecisionBuffer;
1404
- delete next.routingDecisionText;
1405
- } else {
1406
- next.routingDecisionBuffer = buffered;
1407
- next.routingDecisionText = buffered;
1408
- }
1409
- return next;
1410
- };
1411
- if (!lastMessage) {
1412
- const seed = mergeRoutingMetadata({});
1413
- return appendAssistantMessage(conversation, `routing-agent-${chunk.payload?.runId ?? "unknown"}-${Date.now()}`, [], {
1414
- ...networkMode(metadata),
1415
- ...seed
1416
- });
1417
- }
1418
- return replaceLast(conversation, withMetadata(lastMessage, mergeRoutingMetadata(lastMessage.content.metadata ?? {})));
1419
- };
1420
- const handleAgentNetworkChunk = (chunk, conversation, metadata) => {
1421
- if (chunk.type === "agent-execution-start") {
1422
- const primitiveId = chunk.payload?.args?.primitiveId;
1423
- const runId = chunk.payload.runId;
1424
- if (!primitiveId || !runId) return conversation;
1425
- const toolPart = {
1426
- type: "dynamic-tool",
1427
- toolName: primitiveId,
1428
- toolCallId: runId,
1429
- state: "input-available",
1430
- input: chunk.payload.args
1431
- };
1432
- return appendAssistantMessage(conversation, `agent-execution-start-${runId}-${Date.now()}`, [toolPart], {
1433
- ...networkMode(metadata),
1434
- selectionReason: chunk.payload?.args?.selectionReason || "",
1435
- agentInput: chunk.payload?.args?.task,
1436
- from: "AGENT"
1437
- });
1438
- }
1439
- if (chunk.type === "agent-execution-end") {
1440
- const lastMessage = lastAssistant(conversation);
1441
- if (!lastMessage) return conversation;
1442
- const parts = [...lastMessage.content.parts];
1443
- const toolPartIndex = findPartIndex(parts, (part) => isDynamicToolPart(part));
1444
- if (toolPartIndex !== -1) {
1445
- const toolPart = parts[toolPartIndex];
1446
- const currentOutput = toolPart.output;
1447
- parts[toolPartIndex] = {
1448
- type: "dynamic-tool",
1449
- toolName: toolPart.toolName,
1450
- toolCallId: toolPart.toolCallId,
1451
- state: "output-available",
1452
- input: toolPart.input,
1453
- output: {
1454
- ...currentOutput,
1455
- result: currentOutput?.result || chunk.payload?.result || ""
1456
- }
1457
- };
1458
- }
1459
- return replaceLast(conversation, withParts(lastMessage, parts));
1460
- }
1461
- if (chunk.type.startsWith("agent-execution-event-")) {
1462
- const lastMessage = lastAssistant(conversation);
1463
- if (!lastMessage) return conversation;
1464
- const agentChunk = chunk.payload;
1465
- const parts = [...lastMessage.content.parts];
1466
- const toolPartIndex = findPartIndex(parts, (part) => isDynamicToolPart(part));
1467
- if (toolPartIndex === -1) return conversation;
1468
- const toolPart = parts[toolPartIndex];
1469
- if (agentChunk.type === "text-delta") {
1470
- const childMessages = toolPart?.output?.childMessages || [];
1471
- const lastChildMessage = childMessages[childMessages.length - 1];
1472
- const textMessage = {
1473
- type: "text",
1474
- content: (lastChildMessage?.content || "") + agentChunk.payload.text
1475
- };
1476
- const nextMessages = lastChildMessage?.type === "text" ? [...childMessages.slice(0, -1), textMessage] : [...childMessages, textMessage];
1477
- parts[toolPartIndex] = {
1478
- ...toolPart,
1479
- output: { childMessages: nextMessages }
1480
- };
1481
- } else if (agentChunk.type === "tool-call") {
1482
- const childMessages = toolPart?.output?.childMessages || [];
1483
- parts[toolPartIndex] = {
1484
- ...toolPart,
1485
- output: {
1486
- ...toolPart?.output,
1487
- childMessages: [...childMessages, {
1488
- type: "tool",
1489
- toolCallId: agentChunk.payload.toolCallId,
1490
- toolName: agentChunk.payload.toolName,
1491
- args: agentChunk.payload.args
1492
- }]
1493
- }
1494
- };
1495
- } else if (agentChunk.type === "tool-output") {
1496
- if (agentChunk.payload?.output?.type?.startsWith("workflow-")) {
1497
- const childMessages = toolPart?.output?.childMessages || [];
1498
- const lastToolIndex = childMessages.length - 1;
1499
- const currentMessage = childMessages[lastToolIndex];
1500
- const actualExistingWorkflowState = currentMessage?.toolOutput || {};
1501
- const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(actualExistingWorkflowState, agentChunk.payload.output);
1502
- if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") parts[toolPartIndex] = {
1503
- ...toolPart,
1504
- output: {
1505
- ...toolPart?.output,
1506
- childMessages: [...childMessages.slice(0, -1), {
1507
- ...currentMessage,
1508
- toolOutput: updatedWorkflowState
1509
- }]
1510
- }
1511
- };
1512
- }
1513
- } else if (agentChunk.type === "tool-result") {
1514
- const childMessages = toolPart?.output?.childMessages || [];
1515
- const lastToolIndex = childMessages.length - 1;
1516
- const isWorkflow = Boolean(agentChunk.payload?.result?.result?.steps);
1517
- if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") parts[toolPartIndex] = {
1518
- ...toolPart,
1519
- output: {
1520
- ...toolPart?.output,
1521
- childMessages: [...childMessages.slice(0, -1), {
1522
- ...childMessages[lastToolIndex],
1523
- toolOutput: isWorkflow ? agentChunk.payload.result.result : agentChunk.payload.result
1524
- }]
1525
- }
1526
- };
1527
- }
1528
- return replaceLast(conversation, withParts(lastMessage, parts));
1529
- }
1530
- return conversation;
1531
- };
1532
- const handleWorkflowNetworkChunk = (chunk, conversation, metadata) => {
1533
- if (chunk.type === "workflow-execution-start") {
1534
- const primitiveId = chunk.payload?.args?.primitiveId;
1535
- const runId = chunk.payload.runId;
1536
- if (!primitiveId || !runId) return conversation;
1537
- let agentInput;
1538
- try {
1539
- agentInput = JSON.parse(chunk.payload?.args?.prompt);
1540
- } catch {
1541
- agentInput = chunk.payload?.args?.prompt;
1542
- }
1543
- const toolPart = {
1544
- type: "dynamic-tool",
1545
- toolName: primitiveId,
1546
- toolCallId: runId,
1547
- state: "input-available",
1548
- input: chunk.payload.args
1549
- };
1550
- return appendAssistantMessage(conversation, `workflow-start-${runId}-${Date.now()}`, [toolPart], {
1551
- ...networkMode(metadata),
1552
- selectionReason: chunk.payload?.args?.selectionReason || "",
1553
- from: "WORKFLOW",
1554
- agentInput
1555
- });
1556
- }
1557
- if (chunk.type === "workflow-execution-suspended") {
1558
- const lastMessage = lastAssistant(conversation);
1559
- if (!lastMessage) return conversation;
1560
- const existing = lastMessage.content.metadata?.suspendedTools ?? {};
1561
- return replaceLast(conversation, withMetadata(lastMessage, {
1562
- ...cloneMetadata(lastMessage.content.metadata),
1563
- mode: "network",
1564
- suspendedTools: {
1565
- ...existing,
1566
- [chunk.payload.toolName]: {
1567
- toolCallId: chunk.payload.toolCallId,
1568
- toolName: chunk.payload.toolName,
1569
- args: chunk.payload.args,
1570
- suspendPayload: chunk.payload.suspendPayload,
1571
- runId: chunk.payload.runId
1572
- }
1573
- }
1574
- }));
1575
- }
1576
- if (chunk.type.startsWith("workflow-execution-event-")) {
1577
- const lastMessage = lastAssistant(conversation);
1578
- if (!lastMessage) return conversation;
1579
- const parts = [...lastMessage.content.parts];
1580
- const toolPartIndex = findPartIndex(parts, (part) => isDynamicToolPart(part));
1581
- if (toolPartIndex === -1) return conversation;
1582
- const toolPart = parts[toolPartIndex];
1583
- const existingWorkflowState = toolPart.output || {};
1584
- const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(existingWorkflowState, chunk.payload);
1585
- parts[toolPartIndex] = {
1586
- ...toolPart,
1587
- output: updatedWorkflowState
1588
- };
1589
- return replaceLast(conversation, withParts(lastMessage, parts));
1590
- }
1591
- return conversation;
1592
- };
1593
- const handleToolNetworkChunk = (chunk, conversation, metadata) => {
1594
- if (chunk.type === "tool-execution-start") {
1595
- const argsData = chunk.payload.args;
1596
- const nestedArgs = argsData.args || {};
1597
- const lastMessage = lastAssistant(conversation);
1598
- const toolPart = {
1599
- type: "dynamic-tool",
1600
- toolName: argsData.toolName || "unknown",
1601
- toolCallId: argsData.toolCallId || "unknown",
1602
- state: "input-available",
1603
- input: nestedArgs
1604
- };
1605
- if (!lastMessage) return appendAssistantMessage(conversation, `tool-start-${chunk.payload.runId}-${Date.now()}`, [toolPart], {
1606
- ...networkMode(metadata),
1607
- selectionReason: metadata.mode === "network" ? metadata.selectionReason || argsData.selectionReason : "",
1608
- agentInput: nestedArgs
1609
- });
1610
- const parts = [...lastMessage.content.parts, toolPart];
1611
- return replaceLast(conversation, withParts(lastMessage, parts));
1612
- }
1613
- if (chunk.type === "tool-execution-approval") {
1614
- const lastMessage = lastAssistant(conversation);
1615
- if (!lastMessage) return conversation;
1616
- const existing = lastMessage.content.metadata?.requireApprovalMetadata ?? {};
1617
- return replaceLast(conversation, withMetadata(lastMessage, {
1618
- ...cloneMetadata(lastMessage.content.metadata),
1619
- mode: "network",
1620
- requireApprovalMetadata: {
1621
- ...existing,
1622
- [chunk.payload.toolName]: {
1623
- toolCallId: chunk.payload.toolCallId,
1624
- toolName: chunk.payload.toolName,
1625
- args: chunk.payload.args,
1626
- runId: chunk.payload.runId
1627
- }
1628
- }
1629
- }));
1630
- }
1631
- if (chunk.type === "tool-execution-suspended") {
1632
- const lastMessage = lastAssistant(conversation);
1633
- if (!lastMessage) return conversation;
1634
- const existing = lastMessage.content.metadata?.suspendedTools ?? {};
1635
- return replaceLast(conversation, withMetadata(lastMessage, {
1636
- ...cloneMetadata(lastMessage.content.metadata),
1637
- mode: "network",
1638
- suspendedTools: {
1639
- ...existing,
1640
- [chunk.payload.toolName]: {
1641
- toolCallId: chunk.payload.toolCallId,
1642
- toolName: chunk.payload.toolName,
1643
- args: chunk.payload.args,
1644
- suspendPayload: chunk.payload.suspendPayload,
1645
- runId: chunk.payload.runId
1646
- }
1647
- }
1648
- }));
1649
- }
1650
- if (chunk.type === "tool-execution-end") {
1651
- const lastMessage = lastAssistant(conversation);
1652
- if (!lastMessage) return conversation;
1653
- const parts = [...lastMessage.content.parts];
1654
- const toolPartIndex = findPartIndex(parts, (part) => isDynamicToolPart(part) && part.toolCallId === chunk.payload.toolCallId);
1655
- if (toolPartIndex !== -1) {
1656
- const toolPart = parts[toolPartIndex];
1657
- const currentOutput = toolPart.output;
1658
- parts[toolPartIndex] = {
1659
- type: "dynamic-tool",
1660
- toolName: toolPart.toolName,
1661
- toolCallId: toolPart.toolCallId,
1662
- state: "output-available",
1663
- input: toolPart.input,
1664
- output: currentOutput?.result || chunk.payload?.result || ""
1665
- };
1666
- }
1667
- return replaceLast(conversation, withParts(lastMessage, parts));
1668
- }
1669
- return conversation;
1670
- };
1671
- /**
1672
- * Reduce a single network-mode chunk into the running `MastraDBMessage[]`
1673
- * conversation. Ports the historical `AISdkNetworkTransformer` so the playground
1674
- * keeps rendering network badges (routing text, agent/workflow/tool execution,
1675
- * suspensions, approvals, completion feedback) until the next major.
1676
- */
1677
- const accumulateNetworkChunk = ({ chunk, conversation, metadata }) => {
1678
- const newConversation = [...conversation];
1679
- if (chunk.type === "routing-agent-text-delta") return handleRoutingAgentDelta(chunk, newConversation, metadata);
1680
- if (chunk.type.startsWith("agent-execution-")) return handleAgentNetworkChunk(chunk, newConversation, metadata);
1681
- if (chunk.type.startsWith("workflow-execution-")) return handleWorkflowNetworkChunk(chunk, newConversation, metadata);
1682
- if (chunk.type.startsWith("tool-execution-")) return handleToolNetworkChunk(chunk, newConversation, metadata);
1683
- if (chunk.type === "network-validation-end") {
1684
- if (chunk.payload.suppressFeedback) return newConversation;
1685
- const textPart = {
1686
- type: "text",
1687
- text: formatCompletionFeedback({
1688
- complete: chunk.payload.passed,
1689
- scorers: chunk.payload.results,
1690
- totalDuration: chunk.payload.duration,
1691
- timedOut: chunk.payload.timedOut,
1692
- completionReason: chunk.payload.reason
1693
- }, chunk.payload.maxIterationReached)
1694
- };
1695
- return appendAssistantMessage(newConversation, `network-validation-end-${chunk.payload.runId}-${Date.now()}`, [textPart], {
1696
- ...networkMode(metadata),
1697
- completionResult: { passed: chunk.payload.passed }
1698
- });
1699
- }
1700
- if (chunk.type === "network-execution-event-step-finish") {
1701
- const lastMessage = lastAssistant(newConversation);
1702
- if (!lastMessage) return newConversation;
1703
- const agentChunk = chunk.payload;
1704
- const parts = [...lastMessage.content.parts];
1705
- const textPartIndex = findPartIndex(parts, (part) => part.type === "text");
1706
- if (textPartIndex === -1) {
1707
- parts.push({
1708
- type: "text",
1709
- text: agentChunk.result,
1710
- state: "done"
1711
- });
1712
- return replaceLast(newConversation, withParts(lastMessage, parts));
1713
- }
1714
- const textPart = parts[textPartIndex];
1715
- if (textPart.type === "text") {
1716
- parts[textPartIndex] = {
1717
- ...textPart,
1718
- state: "done"
1719
- };
1720
- return replaceLast(newConversation, withParts(lastMessage, parts));
1721
- }
1722
- return newConversation;
1723
- }
1724
- return newConversation;
1725
- };
1726
- //#endregion
1727
- //#region src/lib/mastra-db/fromCoreUserMessage.ts
1728
- /**
1729
- * Convert a CoreUserMessage into a canonical `MastraDBMessage` (`format: 2`).
1730
- *
1731
- * Image and file inputs are emitted as the canonical V4 `file` part shape
1732
- * (`{ type: 'file', mimeType, data }`) — the exact shape memory resolves on
1733
- * reload (see `AIV4Adapter`), so optimistic-send and reload render identically.
1734
- *
1735
- * Handles all CoreUserMessage content types:
1736
- * - String content → single text part
1737
- * - Array content with text/image/file parts → corresponding `MastraMessagePart`s
1738
- */
1739
- const coreUserMessageToParts = (coreUserMessage) => typeof coreUserMessage.content === "string" ? [{
1740
- type: "text",
1741
- text: coreUserMessage.content
1742
- }] : coreUserMessage.content.map((part) => {
1743
- switch (part.type) {
1744
- case "text": return {
1745
- type: "text",
1746
- text: part.text
1747
- };
1748
- case "image": {
1749
- const mimeType = part.mimeType ?? "image/*";
1750
- return {
1751
- type: "file",
1752
- mimeType,
1753
- data: encodeFilePartDataForStorage(part.image, mimeType)
1754
- };
1755
- }
1756
- case "file": return {
1757
- type: "file",
1758
- mimeType: part.mimeType,
1759
- data: encodeFilePartDataForStorage(part.data, part.mimeType),
1760
- ...part.filename !== void 0 ? { filename: part.filename } : {}
1761
- };
1762
- default: throw new Error(`Unhandled content part type: ${part.type}`);
1763
- }
1764
- });
1765
- const newUserMessage = (parts) => ({
1766
- id: `user-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
1767
- role: "user",
1768
- createdAt: /* @__PURE__ */ new Date(),
1769
- content: {
1770
- format: 2,
1771
- parts
1772
- }
1773
- });
1774
- const fromCoreUserMessageToMastraDBMessage = (coreUserMessage) => newUserMessage(coreUserMessageToParts(coreUserMessage));
1775
- /**
1776
- * Merge multiple `CoreUserMessage`s into a single canonical `MastraDBMessage`.
1777
- *
1778
- * A user turn that carries attachments arrives as several `CoreUserMessage`s
1779
- * (one for the text, one per attachment). Memory/reload persists and resolves
1780
- * that whole turn as a single multi-part user message, so the optimistic
1781
- * streaming display must do the same — flatten every message's parts into one
1782
- * `parts` array — to render identically (one bubble, not one per message).
1783
- */
1784
- const fromCoreUserMessagesToMastraDBMessage = (coreUserMessages) => newUserMessage(coreUserMessages.flatMap(coreUserMessageToParts));
1785
- //#endregion
1786
- //#region src/agent/extract-tasks.ts
1787
- const TASK_TOOL_NAMES = /* @__PURE__ */ new Set([
1788
- "task_write",
1789
- "task_update",
1790
- "task_complete",
1791
- "task_check"
1792
- ]);
1793
- const TASK_SIGNAL_ID = "tasks";
1794
- const TASK_TAG_NAMES = /* @__PURE__ */ new Set(["current-task-list", "task-list-update"]);
1795
- const TASK_STATUSES = /* @__PURE__ */ new Set([
1796
- "pending",
1797
- "in_progress",
1798
- "completed"
1799
- ]);
1800
- const isDataChunk$1 = (chunk) => typeof chunk.type === "string" && chunk.type.startsWith("data-");
1801
- const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1802
- const isTaskStatus = (value) => typeof value === "string" && TASK_STATUSES.has(value);
1803
- const isTaskItemArray = (value) => Array.isArray(value) && value.every((item) => isRecord$1(item) && typeof item.id === "string" && typeof item.content === "string" && isTaskStatus(item.status) && typeof item.activeForm === "string");
1804
- const isTaskSignal = (value) => {
1805
- if (!isRecord$1(value)) return false;
1806
- return value.id === TASK_SIGNAL_ID || typeof value.tagName === "string" && TASK_TAG_NAMES.has(value.tagName);
1807
- };
1808
- const extractTasksFromSignalData = (data) => {
1809
- if (!isTaskSignal(data) || !isRecord$1(data)) return void 0;
1810
- const metadata = data.metadata;
1811
- if (!isRecord$1(metadata)) return void 0;
1812
- const value = metadata.value;
1813
- if (!isRecord$1(value)) return void 0;
1814
- return isTaskItemArray(value.tasks) ? value.tasks : void 0;
1815
- };
1816
- const parseTasksFromResult = (raw) => {
1817
- if (isRecord$1(raw) && isTaskItemArray(raw.tasks)) return raw.tasks;
1818
- if (typeof raw !== "string") return void 0;
1819
- try {
1820
- const parsed = JSON.parse(raw);
1821
- return isRecord$1(parsed) && isTaskItemArray(parsed.tasks) ? parsed.tasks : void 0;
1822
- } catch {
1823
- return;
1824
- }
1825
- };
1826
- const extractTasksFromSignalChunk = (chunk) => {
1827
- if (!isDataChunk$1(chunk)) return void 0;
1828
- return extractTasksFromSignalData(chunk.data);
1829
- };
1830
- const extractTasksFromToolResultChunk = (chunk) => {
1831
- if (chunk.type !== "tool-result") return void 0;
1832
- const payload = chunk.payload;
1833
- if (!isRecord$1(payload) || typeof payload.toolName !== "string" || !TASK_TOOL_NAMES.has(payload.toolName)) return;
1834
- return parseTasksFromResult(payload.result);
1835
- };
1836
- const extractTasksFromToolInvocationPart = (part) => {
1837
- if (!isRecord$1(part) || part.type !== "tool-invocation" || !isRecord$1(part.toolInvocation)) return void 0;
1838
- const toolInvocation = part.toolInvocation;
1839
- if (typeof toolInvocation.toolName !== "string" || !TASK_TOOL_NAMES.has(toolInvocation.toolName)) return void 0;
1840
- return parseTasksFromResult(toolInvocation.result);
1841
- };
1842
- const extractTasksFromDataPart = (part) => {
1843
- if (!isRecord$1(part) || typeof part.type !== "string" || !part.type.startsWith("data-")) return void 0;
1844
- return extractTasksFromSignalData(part.data);
1845
- };
1846
- const extractTasksFromSignalMessage = (message) => {
1847
- if (message.role !== "signal") return void 0;
1848
- const metadata = message.content?.metadata;
1849
- if (!isRecord$1(metadata)) return void 0;
1850
- return extractTasksFromSignalData(metadata.signal);
1851
- };
1852
- const extractLatestTasksFromMessages = (messages) => {
1853
- let latest;
1854
- for (const message of messages) {
1855
- for (const part of message.content?.parts ?? []) {
1856
- const toolTasks = extractTasksFromToolInvocationPart(part);
1857
- if (toolTasks !== void 0) latest = toolTasks;
1858
- }
1859
- const signalTasks = extractTasksFromSignalMessage(message);
1860
- if (signalTasks !== void 0) latest = signalTasks;
1861
- for (const part of message.content?.parts ?? []) {
1862
- const dataTasks = extractTasksFromDataPart(part);
1863
- if (dataTasks !== void 0) latest = dataTasks;
1864
- }
1865
- }
1866
- return latest ?? [];
1867
- };
1868
- //#endregion
1869
- //#region src/agent/extractRunIdFromMessages.ts
1870
- const isRecord = (value) => value !== null && typeof value === "object";
1871
- const runIdMetadataKeys = [
1872
- "pendingToolApprovals",
1873
- "requireApprovalMetadata",
1874
- "suspendedTools"
1875
- ];
1876
- const isRunIdMetadataSource = (value) => isRecord(value) && Object.values(value).every((entry) => isRecord(entry));
1877
- const getRunIdMetadataSources = (metadata) => {
1878
- if (!isRecord(metadata)) return [];
1879
- const sources = [];
1880
- for (const key of runIdMetadataKeys) {
1881
- const source = metadata[key];
1882
- if (isRunIdMetadataSource(source)) sources.push(source);
1883
- }
1884
- return sources;
1885
- };
1886
- /**
1887
- * Scan initial DB-shape messages for any pending approvals, suspended tools, or
1888
- * `requireApprovalMetadata` entries and return the first non-empty `runId`.
1889
- *
1890
- * Metadata is read off `message.content.metadata`, the canonical location for
1891
- * MastraDBMessage UX hints.
1892
- */
1893
- const extractRunIdFromMessages = (messages) => {
1894
- for (const message of messages) for (const source of getRunIdMetadataSources(message.content?.metadata)) for (const entry of Object.values(source)) if (isRecord(entry) && typeof entry.runId === "string" && entry.runId.length > 0) return entry.runId;
1895
- };
1896
- //#endregion
1897
- //#region src/agent/merge-history.ts
1898
- const liveClientMessageId = (message) => {
1899
- const clientMessageId = message.content.metadata?.[CLIENT_MESSAGE_ID_KEY];
1900
- return typeof clientMessageId === "string" ? clientMessageId : void 0;
1901
- };
1902
- const storedClientMessageId = (message) => {
1903
- const signal = message.content.metadata?.signal;
1904
- const clientMessageId = isRecord$1(signal) && isRecord$1(signal.metadata) ? signal.metadata[CLIENT_MESSAGE_ID_KEY] : void 0;
1905
- return typeof clientMessageId === "string" ? clientMessageId : void 0;
1906
- };
1907
- const mergeHistoryIntoConversation = ({ conversation, history, previousHistory }) => {
1908
- const previousById = new Map(previousHistory.map((message) => [message.id, message]));
1909
- const live = conversation.filter((message) => previousById.get(message.id) !== message);
1910
- const liveById = new Map(live.map((message) => [message.id, message]));
1911
- const liveClientMessageIds = new Set(live.flatMap((message) => liveClientMessageId(message) ?? []));
1912
- const historyIds = new Set(history.map((message) => message.id));
1913
- const storedClientMessageIds = new Set(history.flatMap((message) => storedClientMessageId(message) ?? []));
1914
- const mergedHistory = history.map((message) => {
1915
- const liveCopy = liveById.get(message.id);
1916
- if (liveCopy) return liveCopy;
1917
- const clientMessageId = storedClientMessageId(message);
1918
- if (!clientMessageId || !liveClientMessageIds.has(clientMessageId)) return message;
1919
- return {
1920
- ...message,
1921
- content: {
1922
- ...message.content,
1923
- metadata: {
1924
- ...message.content.metadata,
1925
- [CLIENT_MESSAGE_ID_KEY]: clientMessageId
1926
- }
1927
- }
1928
- };
1929
- });
1930
- const unstoredLive = live.filter((message) => {
1931
- const clientMessageId = liveClientMessageId(message);
1932
- return !historyIds.has(message.id) && !(clientMessageId && storedClientMessageIds.has(clientMessageId));
1933
- });
1934
- return [...mergedHistory, ...unstoredLive];
1935
- };
1936
- //#endregion
1937
- //#region src/agent/hooks.ts
1938
- const extractPendingToolApprovalIdsFromMessages = (messages, runId) => {
1939
- const pendingToolApprovalIds = /* @__PURE__ */ new Set();
1940
- for (const message of messages) {
1941
- const metadata = message.content?.metadata;
1942
- if (!metadata) continue;
1943
- const metadataSources = [
1944
- metadata.pendingToolApprovals,
1945
- metadata.requireApprovalMetadata,
1946
- metadata.suspendedTools
1947
- ];
1948
- for (const source of metadataSources) {
1949
- if (!source || typeof source !== "object") continue;
1950
- for (const suspensionData of Object.values(source)) {
1951
- if (runId && suspensionData?.runId !== runId) continue;
1952
- const toolCallId = suspensionData?.toolCallId;
1953
- if (typeof toolCallId === "string" && toolCallId.length > 0) pendingToolApprovalIds.add(toolCallId);
1954
- }
1955
- }
1956
- }
1957
- return pendingToolApprovalIds;
1958
- };
1959
- const toolCallHasOutput = (parts, toolCallId) => parts.some((part) => {
1960
- if (part.type !== "tool-invocation") return false;
1961
- const invocation = part.toolInvocation;
1962
- if (invocation.toolCallId !== toolCallId) return false;
1963
- return invocation.state === "result" || invocation.result != null;
1964
- });
1965
- const filterUnresolvedApprovals = (entries, parts) => {
1966
- if (!entries || typeof entries !== "object") return void 0;
1967
- const pending = Object.fromEntries(Object.entries(entries).filter(([, approval]) => approval && typeof approval === "object" && typeof approval.toolCallId === "string" && !toolCallHasOutput(parts, approval.toolCallId)));
1968
- return Object.keys(pending).length ? pending : void 0;
1969
- };
1970
- /**
1971
- * Normalize persisted initial messages back into the stream-friendly shape the
1972
- * UI renders from. Mirrors `main`'s `resolveInitialMessages`:
1973
- *
1974
- * - Converts persisted `pendingToolApprovals` (DB shape) into
1975
- * `requireApprovalMetadata` (stream shape) so reloaded threads still render
1976
- * approve/decline buttons, filtering out approvals whose tool already
1977
- * produced output, and marks the message `mode: 'stream'`.
1978
- * - Drops assistant completion messages flagged `suppressFeedback`, which are
1979
- * persisted by the supervisor agent but must stay hidden on reload.
1980
- */
1981
- const resolveInitialMessages = (messages) => messages.filter((message) => {
1982
- const metadata = message.content?.metadata;
1983
- if (metadata?.completionResult?.suppressFeedback || metadata?.isTaskCompleteResult?.suppressFeedback) return false;
1984
- return true;
1985
- }).map((message) => {
1986
- const metadata = message.content?.metadata;
1987
- const normalizedMessage = metadata && (metadata.status === "pending" || "clientMessageId" in metadata) ? (() => {
1988
- const { [CLIENT_MESSAGE_ID_KEY]: _omitClientMessageId, ...rest } = metadata;
1989
- const { status: _omitStatus, ...restWithoutStatus } = rest;
1990
- return {
1991
- ...message,
1992
- content: {
1993
- ...message.content,
1994
- metadata: metadata.status === "pending" ? restWithoutStatus : rest
1995
- }
1996
- };
1997
- })() : message;
1998
- const normalizedMetadata = normalizedMessage.content?.metadata;
1999
- if (!normalizedMetadata?.pendingToolApprovals && !normalizedMetadata?.requireApprovalMetadata && !normalizedMetadata?.suspendedTools) return normalizedMessage;
2000
- const { pendingToolApprovals, requireApprovalMetadata, suspendedTools, ...restMetadata } = normalizedMetadata;
2001
- const parts = normalizedMessage.content.parts;
2002
- const pending = filterUnresolvedApprovals(pendingToolApprovals, parts);
2003
- const required = {
2004
- ...filterUnresolvedApprovals(requireApprovalMetadata, parts),
2005
- ...pending
2006
- };
2007
- const suspended = filterUnresolvedApprovals(suspendedTools, parts);
2008
- return {
2009
- ...normalizedMessage,
2010
- content: {
2011
- ...normalizedMessage.content,
2012
- metadata: {
2013
- ...restMetadata,
2014
- ...pendingToolApprovals ? { mode: "stream" } : {},
2015
- ...pending ? { pendingToolApprovals: pending } : {},
2016
- ...Object.keys(required).length ? { requireApprovalMetadata: required } : {},
2017
- ...suspended ? { suspendedTools: suspended } : {}
2018
- }
2019
- }
2020
- };
2021
- });
2022
- const isObject = (value) => typeof value === "object" && value !== null;
2023
- const getErrorName = (error) => isObject(error) && typeof error.name === "string" ? error.name : void 0;
2024
- const isAbortError = (error) => getErrorName(error) === "AbortError";
2025
- const isThreadSignalUnsupportedError = (error) => {
2026
- if (!isObject(error)) return false;
2027
- const status = error.status;
2028
- if (status === 404 || status === 405 || status === 501) return true;
2029
- return status === 400 && typeof error.message === "string" && error.message.includes("No active agent run found for signal target");
2030
- };
2031
- const isDataChunk = (chunk) => typeof chunk.type === "string" && chunk.type.startsWith("data-");
2032
- /**
2033
- * Convert AI-SDK v5 UIMessages returned by the server (generate mode) into
2034
- * `MastraDBMessage[]`, stamping the supplied metadata onto each message's
2035
- * `content.metadata`. Private helper — `useChat` never exposes the AI-SDK
2036
- * shape to consumers.
2037
- */
2038
- const dbFromServerUiMessages = (uiMessages, metadata) => uiMessages.map((uiMsg) => {
2039
- const dbMsg = AIV5Adapter.fromUIMessage(uiMsg);
2040
- return {
2041
- ...dbMsg,
2042
- content: {
2043
- ...dbMsg.content,
2044
- metadata: {
2045
- ...dbMsg.content.metadata ?? {},
2046
- ...metadata
2047
- }
2048
- }
2049
- };
2050
- });
2051
- const useChat = ({ agentId, resourceId, threadId, initialMessages, requestContext: propsRequestContext, clientTools: hookClientTools, onSignalSent, onSignalEcho, onThreadSignalsUnsupported, enableThreadSignals = false, streamPath, withInitialHistory }) => {
2052
- const threadSignalsDisabled = enableThreadSignals === false;
2053
- const _currentRunId = useRef(void 0);
2054
- const _onChunk = useRef(void 0);
2055
- const _networkRunId = useRef(void 0);
2056
- const _onNetworkChunk = useRef(void 0);
2057
- const _activeContinuation = useRef({ requestContext: propsRequestContext });
2058
- const _streamAbortRef = useRef(null);
2059
- const _threadSubscriptionAbortRef = useRef(null);
2060
- const _threadSubscriptionRef = useRef(null);
2061
- const _threadSubscriptionKeyRef = useRef(void 0);
2062
- const _threadSubscriptionPromiseRef = useRef(null);
2063
- const _threadSignalsUnsupportedRef = useRef(false);
2064
- const [messages, setMessages] = useState([]);
2065
- const [tasks, setTasks] = useState([]);
2066
- const liveTasks = useRef(void 0);
2067
- const [toolCallApprovals, setToolCallApprovals] = useState({});
2068
- const [networkToolCallApprovals, setNetworkToolCallApprovals] = useState({});
2069
- const pendingToolApprovalIdsRef = useRef(/* @__PURE__ */ new Set());
2070
- const liveApprovalIds = useRef(/* @__PURE__ */ new Set());
2071
- const liveRunId = useRef(void 0);
2072
- const liveRunFinished = useRef(false);
2073
- const [isAwaitingToolApproval, setIsAwaitingToolApproval] = useState(false);
2074
- const baseClient = useMastraClient();
2075
- const [isRunning, setIsRunning] = useState(false);
2076
- const [subscriptionHistory, setSubscriptionHistory] = useState(void 0);
2077
- const historyKey = `${agentId}:${resourceId ?? ""}:${threadId ?? ""}`;
2078
- const hydratedMessages = withInitialHistory && subscriptionHistory?.key === historyKey ? subscriptionHistory.messages : initialMessages;
2079
- const lastHydration = useRef(void 0);
2080
- useEffect(() => {
2081
- const previous = lastHydration.current;
2082
- const sameThread = previous?.agentId === agentId && previous.resourceId === resourceId && previous.threadId === threadId;
2083
- if (sameThread && previous.initialMessages === hydratedMessages) return;
2084
- const formattedMessages = resolveInitialMessages(hydratedMessages ?? []);
2085
- lastHydration.current = {
2086
- agentId,
2087
- resourceId,
2088
- threadId,
2089
- initialMessages: hydratedMessages,
2090
- formattedMessages
2091
- };
2092
- if (sameThread) {
2093
- setMessages((current) => mergeHistoryIntoConversation({
2094
- conversation: current,
2095
- history: formattedMessages,
2096
- previousHistory: previous.formattedMessages
2097
- }));
2098
- setTasks(liveTasks.current ?? extractLatestTasksFromMessages(formattedMessages));
2099
- const historyRunId = extractRunIdFromMessages(formattedMessages);
2100
- if (liveRunFinished.current) return;
2101
- if (!liveRunId.current && isRunning && historyRunId !== _currentRunId.current) return;
2102
- } else {
2103
- liveTasks.current = void 0;
2104
- liveApprovalIds.current.clear();
2105
- liveRunId.current = void 0;
2106
- liveRunFinished.current = false;
2107
- if (previous) setIsRunning(false);
2108
- setMessages(formattedMessages);
2109
- setTasks(extractLatestTasksFromMessages(formattedMessages));
2110
- }
2111
- const pendingApprovals = extractPendingToolApprovalIdsFromMessages(formattedMessages, liveRunId.current);
2112
- for (const toolCallId of liveApprovalIds.current) if (pendingToolApprovalIdsRef.current.has(toolCallId)) pendingApprovals.add(toolCallId);
2113
- else pendingApprovals.delete(toolCallId);
2114
- pendingToolApprovalIdsRef.current = pendingApprovals;
2115
- setIsAwaitingToolApproval(pendingApprovals.size > 0);
2116
- _currentRunId.current = liveRunId.current ?? extractRunIdFromMessages(formattedMessages);
2117
- }, [
2118
- agentId,
2119
- resourceId,
2120
- threadId,
2121
- hydratedMessages,
2122
- isRunning,
2123
- isAwaitingToolApproval
2124
- ]);
2125
- useEffect(() => {
2126
- _activeContinuation.current = {
2127
- ..._activeContinuation.current,
2128
- requestContext: propsRequestContext
2129
- };
2130
- }, [propsRequestContext]);
2131
- const normalizeSignalFileData = (data) => {
2132
- if (data instanceof URL) return data.toString();
2133
- return convertSignalDataToBase64String(data);
2134
- };
2135
- const getSignalContents = (coreUserMessages) => {
2136
- const parts = coreUserMessages.reduce((allParts, message) => {
2137
- if (typeof message.content === "string") {
2138
- allParts.push({
2139
- type: "text",
2140
- text: message.content
2141
- });
2142
- return allParts;
2143
- }
2144
- for (const part of message.content) if (part.type === "text") allParts.push({
2145
- type: "text",
2146
- text: part.text
2147
- });
2148
- else if (part.type === "file") allParts.push({
2149
- type: "file",
2150
- data: normalizeSignalFileData(part.data),
2151
- mediaType: part.mimeType,
2152
- ...part.filename ? { filename: part.filename } : {}
2153
- });
2154
- else if (part.type === "image") allParts.push({
2155
- type: "file",
2156
- data: normalizeSignalFileData(part.image),
2157
- mediaType: part.mimeType ?? "image/png"
2158
- });
2159
- return allParts;
2160
- }, []);
2161
- return parts.length === 1 && parts[0]?.type === "text" ? parts[0].text : parts;
2162
- };
2163
- const markThreadSignalsUnsupported = useCallback(() => {
2164
- _threadSignalsUnsupportedRef.current = true;
2165
- onThreadSignalsUnsupported?.();
2166
- }, [onThreadSignalsUnsupported]);
2167
- const getSignalPreview = (coreUserMessages) => {
2168
- return coreUserMessages.flatMap((message) => {
2169
- if (typeof message.content === "string") return [message.content];
2170
- return message.content.map((part) => {
2171
- if (part.type === "text") return part.text;
2172
- if (part.type === "image") return "Image";
2173
- return part.filename ? `File: ${part.filename}` : "File";
2174
- });
2175
- }).join(" ").replace(/\s+/g, " ").trim() || "Attachment";
2176
- };
2177
- const closeThreadSubscription = useCallback(() => {
2178
- const subscription = _threadSubscriptionRef.current;
2179
- if (subscription?.unsubscribe) subscription.unsubscribe();
2180
- else _threadSubscriptionAbortRef.current?.abort();
2181
- _threadSubscriptionRef.current = null;
2182
- _threadSubscriptionAbortRef.current = null;
2183
- _threadSubscriptionKeyRef.current = void 0;
2184
- _threadSubscriptionPromiseRef.current = null;
2185
- }, []);
2186
- const processStreamChunk = useCallback(async (chunk, onChunk) => {
2187
- const isTerminal = chunk.type === "finish" || chunk.type === "abort" || chunk.type === "error";
2188
- if (isTerminal && liveRunId.current && chunk.runId !== liveRunId.current) return;
2189
- const runId = "runId" in chunk && typeof chunk.runId === "string" ? chunk.runId : void 0;
2190
- setMessages((prev) => {
2191
- const metadata = {
2192
- mode: "stream",
2193
- runId
2194
- };
2195
- const next = accumulateChunk({
2196
- chunk,
2197
- conversation: prev,
2198
- metadata
2199
- });
2200
- if ((chunk.type === "start" || chunk.type === "step-start") && chunk.payload?.messageId && runId) return next.map((message) => message.id === chunk.payload.messageId && message.role === "assistant" ? {
2201
- ...message,
2202
- content: {
2203
- ...message.content,
2204
- metadata: {
2205
- ...message.content.metadata,
2206
- ...metadata
2207
- }
2208
- }
2209
- } : message);
2210
- return next;
2211
- });
2212
- const streamedTasks = extractTasksFromToolResultChunk(chunk) ?? extractTasksFromSignalChunk(chunk);
2213
- if (streamedTasks !== void 0) {
2214
- liveTasks.current = streamedTasks;
2215
- setTasks(streamedTasks);
2216
- }
2217
- if (chunk.type === "data-user-message" && isDataChunk(chunk) && (chunk.data?.type === "user-message" || chunk.data?.type === "user") && typeof chunk.data?.id === "string") onSignalEcho?.(chunk.data.id);
2218
- if (chunk.type === "start") {
2219
- setIsRunning(true);
2220
- if ("runId" in chunk && typeof chunk.runId === "string") {
2221
- if (liveRunId.current !== chunk.runId) liveApprovalIds.current.clear();
2222
- liveRunFinished.current = false;
2223
- liveRunId.current = chunk.runId;
2224
- _currentRunId.current = chunk.runId;
2225
- }
2226
- }
2227
- if (chunk.type === "tool-call-approval" || chunk.type === "tool-call-suspended") {
2228
- const toolCallId = chunk.payload?.toolCallId;
2229
- if (typeof toolCallId === "string") {
2230
- liveApprovalIds.current.add(toolCallId);
2231
- pendingToolApprovalIdsRef.current.add(toolCallId);
2232
- setIsAwaitingToolApproval(true);
2233
- }
2234
- if (runId) {
2235
- if (!liveRunId.current || liveRunFinished.current) {
2236
- liveRunId.current = runId;
2237
- liveRunFinished.current = false;
2238
- }
2239
- if (liveRunId.current === runId) _currentRunId.current = runId;
2240
- }
2241
- setIsRunning(false);
2242
- }
2243
- if (chunk.type === "tool-call-resumed") {
2244
- const toolCallId = chunk.payload?.toolCallId;
2245
- if (typeof toolCallId === "string") {
2246
- liveApprovalIds.current.add(toolCallId);
2247
- pendingToolApprovalIdsRef.current.delete(toolCallId);
2248
- setIsAwaitingToolApproval(pendingToolApprovalIdsRef.current.size > 0);
2249
- }
2250
- }
2251
- if (isTerminal) {
2252
- if (chunk.runId === liveRunId.current) liveRunFinished.current = true;
2253
- for (const toolCallId of pendingToolApprovalIdsRef.current) liveApprovalIds.current.add(toolCallId);
2254
- pendingToolApprovalIdsRef.current.clear();
2255
- setIsAwaitingToolApproval(false);
2256
- setIsRunning(false);
2257
- }
2258
- (onChunk ?? _onChunk.current)?.(chunk);
2259
- }, [onSignalEcho]);
2260
- const ensureThreadSubscription = useCallback(async ({ threadId, resourceId }) => {
2261
- const subscriptionKey = `${agentId}:${resourceId ?? ""}:${threadId}:${streamPath ?? ""}`;
2262
- if (_threadSubscriptionKeyRef.current === subscriptionKey && _threadSubscriptionPromiseRef.current) {
2263
- await _threadSubscriptionPromiseRef.current;
2264
- return;
2265
- }
2266
- closeThreadSubscription();
2267
- const subscriptionAbort = new AbortController();
2268
- _threadSubscriptionAbortRef.current = subscriptionAbort;
2269
- _threadSubscriptionKeyRef.current = subscriptionKey;
2270
- const releaseSubscriptionRefs = () => {
2271
- if (_threadSubscriptionAbortRef.current !== subscriptionAbort) return;
2272
- _threadSubscriptionRef.current = null;
2273
- _threadSubscriptionAbortRef.current = null;
2274
- _threadSubscriptionKeyRef.current = void 0;
2275
- _threadSubscriptionPromiseRef.current = null;
2276
- };
2277
- const subscriptionAgent = new MastraClient({
2278
- ...baseClient.options,
2279
- abortSignal: subscriptionAbort.signal
2280
- }).getAgent(agentId, void 0, { stream: streamPath });
2281
- _threadSubscriptionPromiseRef.current = subscriptionAgent.subscribeToThread({
2282
- resourceId,
2283
- threadId,
2284
- ...withInitialHistory ? { withInitialHistory } : {}
2285
- }).then((response) => {
2286
- const subscription = response;
2287
- if (_threadSubscriptionAbortRef.current !== subscriptionAbort) {
2288
- subscription.unsubscribe();
2289
- return;
2290
- }
2291
- _threadSubscriptionRef.current = subscription;
2292
- subscription.processDataStream({ onChunk: (chunk) => {
2293
- if (chunk.type === "thread-history") {
2294
- const history = resolveInitialMessages(chunk.payload.messages);
2295
- const previousHistory = lastHydration.current?.formattedMessages ?? [];
2296
- setMessages((current) => mergeHistoryIntoConversation({
2297
- conversation: current,
2298
- history,
2299
- previousHistory
2300
- }));
2301
- setSubscriptionHistory({
2302
- key: `${agentId}:${resourceId ?? ""}:${threadId}`,
2303
- messages: chunk.payload.messages
2304
- });
2305
- return;
2306
- }
2307
- return processStreamChunk(chunk);
2308
- } }).catch((error) => {
2309
- if (!isAbortError(error)) {
2310
- console.error("[useChat] Thread subscription failed", error);
2311
- setIsRunning(false);
2312
- }
2313
- }).finally(() => {
2314
- if (_threadSubscriptionRef.current === subscription) _threadSubscriptionRef.current = null;
2315
- releaseSubscriptionRefs();
2316
- });
2317
- }).catch((error) => {
2318
- releaseSubscriptionRefs();
2319
- if (isThreadSignalUnsupportedError(error)) {
2320
- markThreadSignalsUnsupported();
2321
- return;
2322
- }
2323
- if (!isAbortError(error)) {
2324
- console.error("[useChat] Thread subscription failed", error);
2325
- setIsRunning(false);
2326
- }
2327
- throw error;
2328
- });
2329
- await _threadSubscriptionPromiseRef.current;
2330
- }, [
2331
- agentId,
2332
- baseClient,
2333
- closeThreadSubscription,
2334
- markThreadSignalsUnsupported,
2335
- processStreamChunk,
2336
- streamPath,
2337
- withInitialHistory
2338
- ]);
2339
- useEffect(() => {
2340
- _threadSignalsUnsupportedRef.current = false;
2341
- return closeThreadSubscription;
2342
- }, [
2343
- agentId,
2344
- resourceId,
2345
- threadId,
2346
- closeThreadSubscription
2347
- ]);
2348
- useEffect(() => {
2349
- if (!threadId || threadSignalsDisabled) {
2350
- closeThreadSubscription();
2351
- return;
2352
- }
2353
- ensureThreadSubscription({
2354
- threadId,
2355
- resourceId: resourceId || agentId
2356
- }).catch((error) => {
2357
- if (!isAbortError(error)) console.error("[useChat] Thread subscription failed", error);
2358
- });
2359
- }, [
2360
- agentId,
2361
- closeThreadSubscription,
2362
- ensureThreadSubscription,
2363
- resourceId,
2364
- threadId,
2365
- threadSignalsDisabled
2366
- ]);
2367
- const generate = async ({ coreUserMessages, model, requestContext, threadId, modelSettings, signal, onFinish, tracingOptions, clientTools, clientToolsResolver }) => {
2368
- const { frequencyPenalty, presencePenalty, maxRetries, maxTokens, temperature, topK, topP, instructions, system, providerOptions, maxSteps, requireToolApproval } = modelSettings || {};
2369
- const resolvedRequestContext = requestContext ?? propsRequestContext;
2370
- const resolvedClientTools = clientTools ?? hookClientTools;
2371
- _activeContinuation.current = {
2372
- model,
2373
- requestContext: resolvedRequestContext
2374
- };
2375
- setIsRunning(true);
2376
- const agent = new MastraClient({
2377
- ...baseClient.options,
2378
- abortSignal: signal
2379
- }).getAgent(agentId, void 0, { stream: streamPath });
2380
- const runId = v4();
2381
- _currentRunId.current = runId;
2382
- const response = await agent.generate(coreUserMessages, {
2383
- model,
2384
- runId,
2385
- maxSteps,
2386
- modelSettings: {
2387
- frequencyPenalty,
2388
- presencePenalty,
2389
- maxRetries,
2390
- maxOutputTokens: maxTokens,
2391
- temperature,
2392
- topK,
2393
- topP
2394
- },
2395
- instructions,
2396
- system,
2397
- requestContext: resolvedRequestContext,
2398
- ...threadId ? { memory: {
2399
- thread: threadId,
2400
- resource: resourceId || agentId
2401
- } } : {},
2402
- providerOptions,
2403
- tracingOptions,
2404
- requireToolApproval,
2405
- clientTools: resolvedClientTools,
2406
- clientToolsResolver
2407
- });
2408
- if (response.finishReason === "suspended" && response.suspendPayload) {
2409
- const { toolCallId, toolName, args } = response.suspendPayload;
2410
- if (response.response?.uiMessages) {
2411
- const dbMessages = dbFromServerUiMessages(response.response.uiMessages, {
2412
- mode: "generate",
2413
- requireApprovalMetadata: { [toolName]: {
2414
- toolCallId,
2415
- toolName,
2416
- args
2417
- } }
2418
- });
2419
- setMessages((prev) => [...prev, ...dbMessages]);
2420
- }
2421
- setIsRunning(false);
2422
- return;
2423
- }
2424
- setIsRunning(false);
2425
- if (response && "uiMessages" in response.response && response.response.uiMessages) {
2426
- const dbMessages = dbFromServerUiMessages(response.response.uiMessages, { mode: "generate" });
2427
- onFinish?.(dbMessages);
2428
- setMessages((prev) => [...prev, ...dbMessages]);
2429
- }
2430
- };
2431
- const stream = async ({ coreUserMessages, model, requestContext, threadId, onChunk, modelSettings, signal, tracingOptions, clientTools, clientToolsResolver, signalId, clientMessageId }) => {
2432
- const { frequencyPenalty, presencePenalty, maxRetries, maxTokens, temperature, topK, topP, instructions, system, providerOptions, maxSteps, requireToolApproval } = modelSettings || {};
2433
- const resolvedRequestContext = requestContext ?? propsRequestContext;
2434
- const resolvedClientTools = clientTools ?? hookClientTools;
2435
- const signalContinuationOptions = {
2436
- model,
2437
- maxSteps,
2438
- modelSettings: {
2439
- frequencyPenalty,
2440
- presencePenalty,
2441
- maxRetries,
2442
- maxOutputTokens: maxTokens,
2443
- temperature,
2444
- topK,
2445
- topP
2446
- },
2447
- instructions,
2448
- system,
2449
- providerOptions,
2450
- requireToolApproval,
2451
- tracingOptions
2452
- };
2453
- _activeContinuation.current = {
2454
- model,
2455
- requestContext: resolvedRequestContext
2456
- };
2457
- setIsRunning(true);
2458
- _streamAbortRef.current?.abort();
2459
- const internalAbort = new AbortController();
2460
- _streamAbortRef.current = internalAbort;
2461
- if (signal) if (signal.aborted) internalAbort.abort();
2462
- else signal.addEventListener("abort", () => internalAbort.abort(), { once: true });
2463
- const agent = new MastraClient({
2464
- ...baseClient.options,
2465
- abortSignal: internalAbort.signal
2466
- }).getAgent(agentId, void 0, { stream: streamPath });
2467
- const streamWithLegacyRoute = async () => {
2468
- const runId = v4();
2469
- const response = await agent.stream(coreUserMessages, {
2470
- model,
2471
- runId,
2472
- maxSteps,
2473
- untilIdle: true,
2474
- modelSettings: {
2475
- frequencyPenalty,
2476
- presencePenalty,
2477
- maxRetries,
2478
- maxOutputTokens: maxTokens,
2479
- temperature,
2480
- topK,
2481
- topP
2482
- },
2483
- instructions,
2484
- system,
2485
- requestContext: resolvedRequestContext,
2486
- ...threadId ? { memory: {
2487
- thread: threadId,
2488
- resource: resourceId || agentId
2489
- } } : {},
2490
- providerOptions,
2491
- requireToolApproval,
2492
- tracingOptions,
2493
- clientTools: resolvedClientTools,
2494
- clientToolsResolver
2495
- });
2496
- _onChunk.current = onChunk;
2497
- _currentRunId.current = runId;
2498
- await response.processDataStream({ onChunk: (chunk) => processStreamChunk(chunk, onChunk) });
2499
- if (_streamAbortRef.current === internalAbort) _streamAbortRef.current = null;
2500
- setIsRunning(false);
2501
- };
2502
- if (!threadId || _threadSignalsUnsupportedRef.current || threadSignalsDisabled) {
2503
- await streamWithLegacyRoute();
2504
- return;
2505
- }
2506
- _onChunk.current = onChunk;
2507
- await ensureThreadSubscription({
2508
- threadId,
2509
- resourceId: resourceId || agentId
2510
- });
2511
- if (_threadSignalsUnsupportedRef.current) {
2512
- await streamWithLegacyRoute();
2513
- return;
2514
- }
2515
- const resolvedSignalId = signalId ?? v4();
2516
- const messageContents = getSignalContents(coreUserMessages);
2517
- const requestContextRecord = resolvedRequestContext;
2518
- const streamOptions = {
2519
- model,
2520
- maxSteps,
2521
- modelSettings: {
2522
- frequencyPenalty,
2523
- presencePenalty,
2524
- maxRetries,
2525
- maxOutputTokens: maxTokens,
2526
- temperature,
2527
- topK,
2528
- topP
2529
- },
2530
- instructions,
2531
- system,
2532
- requestContext: requestContextRecord,
2533
- providerOptions,
2534
- requireToolApproval,
2535
- tracingOptions,
2536
- clientTools: resolvedClientTools,
2537
- clientToolsResolver
2538
- };
2539
- try {
2540
- const result = await agent.sendMessage({
2541
- message: clientMessageId ? {
2542
- contents: messageContents,
2543
- metadata: { [CLIENT_MESSAGE_ID_KEY]: clientMessageId }
2544
- } : messageContents,
2545
- resourceId: resourceId || agentId,
2546
- threadId,
2547
- ifIdle: { streamOptions: {
2548
- ...signalContinuationOptions,
2549
- requestContext: requestContextRecord,
2550
- clientTools: resolvedClientTools,
2551
- clientToolsResolver
2552
- } }
2553
- });
2554
- const echoedSignalId = result.signal && typeof result.signal === "object" && "id" in result.signal && typeof result.signal.id === "string" ? result.signal.id : resolvedSignalId;
2555
- onSignalSent?.(echoedSignalId, getSignalPreview(coreUserMessages));
2556
- if (pendingToolApprovalIdsRef.current.size > 0) setIsRunning(false);
2557
- } catch (error) {
2558
- if (isThreadSignalUnsupportedError(error)) try {
2559
- await agent.sendSignal({
2560
- signal: {
2561
- id: resolvedSignalId,
2562
- type: "user-message",
2563
- contents: messageContents
2564
- },
2565
- resourceId: resourceId || agentId,
2566
- threadId,
2567
- ifIdle: { streamOptions }
2568
- });
2569
- onSignalSent?.(resolvedSignalId, getSignalPreview(coreUserMessages));
2570
- return;
2571
- } catch (signalError) {
2572
- onSignalEcho?.(resolvedSignalId);
2573
- if (isThreadSignalUnsupportedError(signalError)) {
2574
- markThreadSignalsUnsupported();
2575
- setMessages((prev) => [...prev, fromCoreUserMessagesToMastraDBMessage(coreUserMessages)]);
2576
- await streamWithLegacyRoute();
2577
- return;
2578
- }
2579
- throw signalError;
2580
- }
2581
- throw error;
2582
- }
2583
- if (_streamAbortRef.current === internalAbort) _streamAbortRef.current = null;
2584
- };
2585
- const network = async ({ coreUserMessages, model, requestContext, threadId, onNetworkChunk, modelSettings, signal, tracingOptions }) => {
2586
- const { frequencyPenalty, presencePenalty, maxRetries, maxTokens, temperature, topK, topP, maxSteps } = modelSettings || {};
2587
- const resolvedRequestContext = requestContext ?? propsRequestContext;
2588
- _activeContinuation.current = {
2589
- model,
2590
- requestContext: resolvedRequestContext
2591
- };
2592
- setIsRunning(true);
2593
- const agent = new MastraClient({
2594
- ...baseClient.options,
2595
- abortSignal: signal
2596
- }).getAgent(agentId, void 0, { stream: streamPath });
2597
- const runId = v4();
2598
- _currentRunId.current = runId;
2599
- const response = await agent.network(coreUserMessages, {
2600
- model,
2601
- maxSteps,
2602
- modelSettings: {
2603
- frequencyPenalty,
2604
- presencePenalty,
2605
- maxRetries,
2606
- maxOutputTokens: maxTokens,
2607
- temperature,
2608
- topK,
2609
- topP
2610
- },
2611
- runId,
2612
- requestContext: resolvedRequestContext,
2613
- ...threadId ? { memory: {
2614
- thread: threadId,
2615
- resource: resourceId || agentId
2616
- } } : {},
2617
- tracingOptions
2618
- });
2619
- _onNetworkChunk.current = onNetworkChunk;
2620
- _networkRunId.current = runId;
2621
- await response.processDataStream({ onChunk: async (chunk) => {
2622
- setMessages((prev) => accumulateNetworkChunk({
2623
- chunk,
2624
- conversation: prev,
2625
- metadata: {
2626
- mode: "network",
2627
- runId
2628
- }
2629
- }));
2630
- onNetworkChunk?.(chunk);
2631
- } });
2632
- setMessages((prev) => finishStreamingAssistantMessage(prev));
2633
- setIsRunning(false);
2634
- };
2635
- const handleCancelRun = () => {
2636
- _streamAbortRef.current?.abort();
2637
- _streamAbortRef.current = null;
2638
- const threadSubscription = _threadSubscriptionRef.current;
2639
- Promise.resolve(threadSubscription?.abort?.()).catch((error) => {
2640
- console.error("[useChat] Failed to abort thread subscription", error);
2641
- });
2642
- closeThreadSubscription();
2643
- setMessages((prev) => finishStreamingAssistantMessage(prev));
2644
- liveRunFinished.current = true;
2645
- pendingToolApprovalIdsRef.current.clear();
2646
- setIsAwaitingToolApproval(false);
2647
- setIsRunning(false);
2648
- _currentRunId.current = void 0;
2649
- _onChunk.current = void 0;
2650
- _networkRunId.current = void 0;
2651
- _onNetworkChunk.current = void 0;
2652
- _activeContinuation.current = {};
2653
- };
2654
- const approveToolCall = async (toolCallId, resumeData) => {
2655
- const onChunk = _onChunk.current;
2656
- const currentRunId = _currentRunId.current;
2657
- const continuation = _activeContinuation.current;
2658
- if (!currentRunId) return console.info("[approveToolCall] approveToolCall can only be called after a stream has started");
2659
- setIsRunning(true);
2660
- setToolCallApprovals((prev) => ({
2661
- ...prev,
2662
- [toolCallId]: { status: "approved" }
2663
- }));
2664
- const agent = baseClient.getAgent(agentId, void 0, { stream: streamPath });
2665
- if (_threadSubscriptionKeyRef.current && threadId) {
2666
- try {
2667
- await agent.sendToolApproval({
2668
- resourceId: resourceId || agentId,
2669
- threadId,
2670
- toolCallId,
2671
- approved: true,
2672
- ...continuation.model !== void 0 ? { streamOptions: { model: continuation.model } } : {},
2673
- ...resumeData !== void 0 ? { resumeData } : {},
2674
- requestContext: continuation.requestContext
2675
- });
2676
- liveRunId.current ??= currentRunId;
2677
- liveApprovalIds.current.add(toolCallId);
2678
- pendingToolApprovalIdsRef.current.delete(toolCallId);
2679
- setIsAwaitingToolApproval(pendingToolApprovalIdsRef.current.size > 0);
2680
- setIsRunning(false);
2681
- } catch (error) {
2682
- setToolCallApprovals((prev) => {
2683
- const next = { ...prev };
2684
- delete next[toolCallId];
2685
- return next;
2686
- });
2687
- setIsRunning(false);
2688
- throw error;
2689
- }
2690
- return;
2691
- }
2692
- try {
2693
- await (resumeData !== void 0 ? await agent.resumeStream(resumeData, {
2694
- runId: currentRunId,
2695
- toolCallId,
2696
- ...continuation
2697
- }) : await agent.approveToolCall({
2698
- runId: currentRunId,
2699
- toolCallId,
2700
- ...continuation
2701
- })).processDataStream({ onChunk: async (chunk) => {
2702
- await processStreamChunk(chunk, onChunk);
2703
- } });
2704
- setIsRunning(false);
2705
- } catch (error) {
2706
- setToolCallApprovals((prev) => {
2707
- const next = { ...prev };
2708
- delete next[toolCallId];
2709
- return next;
2710
- });
2711
- setIsRunning(false);
2712
- throw error;
2713
- }
2714
- };
2715
- const declineToolCall = async (toolCallId) => {
2716
- const onChunk = _onChunk.current;
2717
- const currentRunId = _currentRunId.current;
2718
- const continuation = _activeContinuation.current;
2719
- if (!currentRunId) return console.info("[declineToolCall] declineToolCall can only be called after a stream has started");
2720
- setIsRunning(true);
2721
- setToolCallApprovals((prev) => ({
2722
- ...prev,
2723
- [toolCallId]: { status: "declined" }
2724
- }));
2725
- const agent = baseClient.getAgent(agentId, void 0, { stream: streamPath });
2726
- if (_threadSubscriptionKeyRef.current && threadId) {
2727
- try {
2728
- await agent.sendToolApproval({
2729
- resourceId: resourceId || agentId,
2730
- threadId,
2731
- toolCallId,
2732
- approved: false,
2733
- ...continuation.model !== void 0 ? { streamOptions: { model: continuation.model } } : {},
2734
- requestContext: continuation.requestContext
2735
- });
2736
- liveRunId.current ??= currentRunId;
2737
- liveApprovalIds.current.add(toolCallId);
2738
- pendingToolApprovalIdsRef.current.delete(toolCallId);
2739
- setIsAwaitingToolApproval(pendingToolApprovalIdsRef.current.size > 0);
2740
- setIsRunning(false);
2741
- } catch (error) {
2742
- setToolCallApprovals((prev) => {
2743
- const next = { ...prev };
2744
- delete next[toolCallId];
2745
- return next;
2746
- });
2747
- setIsRunning(false);
2748
- throw error;
2749
- }
2750
- return;
2751
- }
2752
- await (await agent.declineToolCall({
2753
- runId: currentRunId,
2754
- toolCallId,
2755
- ...continuation
2756
- })).processDataStream({ onChunk: async (chunk) => {
2757
- await processStreamChunk(chunk, onChunk);
2758
- } });
2759
- setIsRunning(false);
2760
- };
2761
- const approveToolCallGenerate = async (toolCallId) => {
2762
- const currentRunId = _currentRunId.current;
2763
- const continuation = _activeContinuation.current;
2764
- if (!currentRunId) return console.info("[approveToolCallGenerate] approveToolCallGenerate can only be called after a generate has started");
2765
- setIsRunning(true);
2766
- setToolCallApprovals((prev) => ({
2767
- ...prev,
2768
- [toolCallId]: { status: "approved" }
2769
- }));
2770
- const response = await baseClient.getAgent(agentId, void 0, { stream: streamPath }).approveToolCallGenerate({
2771
- runId: currentRunId,
2772
- toolCallId,
2773
- ...continuation
2774
- });
2775
- if (response && "uiMessages" in response.response && response.response.uiMessages) {
2776
- const dbMessages = dbFromServerUiMessages(response.response.uiMessages, { mode: "generate" });
2777
- setMessages((prev) => [...prev, ...dbMessages]);
2778
- }
2779
- setIsRunning(false);
2780
- };
2781
- const declineToolCallGenerate = async (toolCallId) => {
2782
- const currentRunId = _currentRunId.current;
2783
- const continuation = _activeContinuation.current;
2784
- if (!currentRunId) return console.info("[declineToolCallGenerate] declineToolCallGenerate can only be called after a generate has started");
2785
- setIsRunning(true);
2786
- setToolCallApprovals((prev) => ({
2787
- ...prev,
2788
- [toolCallId]: { status: "declined" }
2789
- }));
2790
- const response = await baseClient.getAgent(agentId, void 0, { stream: streamPath }).declineToolCallGenerate({
2791
- runId: currentRunId,
2792
- toolCallId,
2793
- ...continuation
2794
- });
2795
- if (response && "uiMessages" in response.response && response.response.uiMessages) {
2796
- const dbMessages = dbFromServerUiMessages(response.response.uiMessages, { mode: "generate" });
2797
- setMessages((prev) => [...prev, ...dbMessages]);
2798
- }
2799
- setIsRunning(false);
2800
- };
2801
- const approveNetworkToolCall = async (toolName, runId) => {
2802
- const onNetworkChunk = _onNetworkChunk.current;
2803
- const networkRunId = runId || _networkRunId.current;
2804
- const continuation = _activeContinuation.current;
2805
- if (!networkRunId) return console.info("[approveNetworkToolCall] approveNetworkToolCall can only be called after a network stream has started");
2806
- _currentRunId.current = networkRunId;
2807
- setIsRunning(true);
2808
- setNetworkToolCallApprovals((prev) => ({
2809
- ...prev,
2810
- [runId ? `${runId}-${toolName}` : toolName]: { status: "approved" }
2811
- }));
2812
- await (await baseClient.getAgent(agentId, void 0, { stream: streamPath }).approveNetworkToolCall({
2813
- runId: networkRunId,
2814
- ...continuation
2815
- })).processDataStream({ onChunk: async (chunk) => {
2816
- setMessages((prev) => accumulateNetworkChunk({
2817
- chunk,
2818
- conversation: prev,
2819
- metadata: {
2820
- mode: "network",
2821
- runId: networkRunId
2822
- }
2823
- }));
2824
- onNetworkChunk?.(chunk);
2825
- } });
2826
- setMessages((prev) => finishStreamingAssistantMessage(prev));
2827
- setIsRunning(false);
2828
- };
2829
- const declineNetworkToolCall = async (toolName, runId) => {
2830
- const onNetworkChunk = _onNetworkChunk.current;
2831
- const networkRunId = runId || _networkRunId.current;
2832
- const continuation = _activeContinuation.current;
2833
- if (!networkRunId) return console.info("[declineNetworkToolCall] declineNetworkToolCall can only be called after a network stream has started");
2834
- _currentRunId.current = networkRunId;
2835
- setIsRunning(true);
2836
- setNetworkToolCallApprovals((prev) => ({
2837
- ...prev,
2838
- [runId ? `${runId}-${toolName}` : toolName]: { status: "declined" }
2839
- }));
2840
- await (await baseClient.getAgent(agentId, void 0, { stream: streamPath }).declineNetworkToolCall({
2841
- runId: networkRunId,
2842
- ...continuation
2843
- })).processDataStream({ onChunk: async (chunk) => {
2844
- setMessages((prev) => accumulateNetworkChunk({
2845
- chunk,
2846
- conversation: prev,
2847
- metadata: {
2848
- mode: "network",
2849
- runId: networkRunId
2850
- }
2851
- }));
2852
- onNetworkChunk?.(chunk);
2853
- } });
2854
- setMessages((prev) => finishStreamingAssistantMessage(prev));
2855
- setIsRunning(false);
2856
- };
2857
- const sendMessage = async ({ mode = "stream", ...args }) => {
2858
- if (!isRunning && !isAwaitingToolApproval) _currentRunId.current = void 0;
2859
- const coreUserMessages = [{
2860
- role: "user",
2861
- content: [{
2862
- type: "text",
2863
- text: args.message
2864
- }]
2865
- }];
2866
- if (args.coreUserMessages) coreUserMessages.push(...args.coreUserMessages);
2867
- const dbUserMessage = fromCoreUserMessagesToMastraDBMessage(coreUserMessages);
2868
- const clientSetId = mode === "stream" && args.threadId && !_threadSignalsUnsupportedRef.current && !threadSignalsDisabled ? `client-set-${v4()}` : void 0;
2869
- const signalId = clientSetId;
2870
- const clientMessageId = clientSetId;
2871
- if (signalId) {
2872
- const metadata = {
2873
- ...dbUserMessage.content.metadata,
2874
- mode: "stream",
2875
- status: "pending",
2876
- [CLIENT_MESSAGE_ID_KEY]: clientMessageId
2877
- };
2878
- const pendingMessage = {
2879
- ...dbUserMessage,
2880
- id: clientSetId,
2881
- content: {
2882
- ...dbUserMessage.content,
2883
- metadata
2884
- }
2885
- };
2886
- setMessages((s) => [...s, pendingMessage]);
2887
- } else setMessages((s) => [...s, dbUserMessage]);
2888
- try {
2889
- if (mode === "generate") await generate({
2890
- ...args,
2891
- coreUserMessages
2892
- });
2893
- else if (mode === "stream") await stream({
2894
- ...args,
2895
- coreUserMessages,
2896
- signalId,
2897
- clientMessageId
2898
- });
2899
- else if (mode === "network") await network({
2900
- ...args,
2901
- coreUserMessages
2902
- });
2903
- } catch (error) {
2904
- setIsRunning(false);
2905
- throw error;
2906
- }
2907
- };
2908
- return {
2909
- setMessages,
2910
- sendMessage,
2911
- isRunning,
2912
- activeRunId: isRunning || isAwaitingToolApproval ? _currentRunId.current : void 0,
2913
- isAwaitingToolApproval,
2914
- messages,
2915
- tasks,
2916
- approveToolCall,
2917
- declineToolCall,
2918
- approveToolCallGenerate,
2919
- declineToolCallGenerate,
2920
- cancelRun: handleCancelRun,
2921
- toolCallApprovals,
2922
- approveNetworkToolCall,
2923
- declineNetworkToolCall,
2924
- networkToolCallApprovals
2925
- };
2926
- };
2927
- //#endregion
2928
- //#region src/lib/use-mutation.ts
2929
- /**
2930
- * Internal helper hook that provides mutation-like functionality without react-query.
2931
- * Tracks pending, success, and error states for async operations.
2932
- */
2933
- function useMutation(mutationFn) {
2934
- const [isPending, setIsPending] = useState(false);
2935
- const [isSuccess, setIsSuccess] = useState(false);
2936
- const [isError, setIsError] = useState(false);
2937
- const [error, setError] = useState(null);
2938
- const [data, setData] = useState(void 0);
2939
- const mutationFnRef = useRef(mutationFn);
2940
- mutationFnRef.current = mutationFn;
2941
- const reset = useCallback(() => {
2942
- setIsPending(false);
2943
- setIsSuccess(false);
2944
- setIsError(false);
2945
- setError(null);
2946
- setData(void 0);
2947
- }, []);
2948
- const mutateAsync = useCallback(async (variables) => {
2949
- setIsPending(true);
2950
- setIsSuccess(false);
2951
- setIsError(false);
2952
- setError(null);
2953
- try {
2954
- const result = await mutationFnRef.current(variables);
2955
- setData(result);
2956
- setIsSuccess(true);
2957
- return result;
2958
- } catch (err) {
2959
- setError(err);
2960
- setIsError(true);
2961
- throw err;
2962
- } finally {
2963
- setIsPending(false);
2964
- }
2965
- }, []);
2966
- return {
2967
- mutate: useCallback((variables) => {
2968
- mutateAsync(variables).catch(() => {});
2969
- }, [mutateAsync]),
2970
- mutateAsync,
2971
- isPending,
2972
- isSuccess,
2973
- isError,
2974
- error,
2975
- data,
2976
- reset
2977
- };
2978
- }
2979
- //#endregion
2980
- //#region src/workflows/use-stream-workflow.ts
2981
- function useStreamWorkflow({ debugMode, tracingOptions, onError }) {
2982
- const client = useMastraClient();
2983
- const [streamResult, setStreamResult] = useState();
2984
- const [isStreaming, setIsStreaming] = useState(false);
2985
- const activeStream = useRef(void 0);
2986
- const isMountedRef = useRef(true);
2987
- const closeActiveStream = useCallback(() => {
2988
- const operation = activeStream.current;
2989
- activeStream.current = void 0;
2990
- if (!operation) return;
2991
- operation.controller.abort();
2992
- operation.reader?.cancel().catch(() => void 0);
2993
- operation.reader?.releaseLock();
2994
- operation.reader = void 0;
2995
- }, []);
2996
- useEffect(() => {
2997
- isMountedRef.current = true;
2998
- return () => {
2999
- isMountedRef.current = false;
3000
- closeActiveStream();
3001
- };
3002
- }, [closeActiveStream]);
3003
- async function consumeStream(openStream, defaultMessage) {
3004
- if (!isMountedRef.current) return;
3005
- closeActiveStream();
3006
- const operation = { controller: new AbortController() };
3007
- activeStream.current = operation;
3008
- const { signal } = operation.controller;
3009
- setIsStreaming(true);
3010
- try {
3011
- const stream = await openStream(signal);
3012
- if (signal.aborted) {
3013
- await stream?.cancel();
3014
- return;
3015
- }
3016
- if (!stream) {
3017
- onError?.(/* @__PURE__ */ new Error("No stream returned"), "No stream returned");
3018
- return;
3019
- }
3020
- const reader = stream.getReader();
3021
- operation.reader = reader;
3022
- while (!signal.aborted) {
3023
- const { done, value } = await reader.read();
3024
- if (done || signal.aborted) break;
3025
- setStreamResult((previous) => mapWorkflowStreamChunkToWatchResult(previous, value));
3026
- if (value.type === "workflow-step-start") setIsStreaming(true);
3027
- if (value.type === "workflow-step-suspended") setIsStreaming(false);
3028
- if (value.type === "workflow-finish" && value.payload.workflowStatus === "failed") throw new Error(value.payload.metadata?.errorMessage || "Workflow execution failed");
3029
- }
3030
- } catch (error) {
3031
- if (!signal.aborted) {
3032
- if (!operation.reader) throw error;
3033
- onError?.(error instanceof Error ? error : new Error(defaultMessage), defaultMessage);
3034
- }
3035
- } finally {
3036
- operation.reader?.releaseLock();
3037
- operation.reader = void 0;
3038
- if (activeStream.current === operation) {
3039
- activeStream.current = void 0;
3040
- setIsStreaming(false);
3041
- }
3042
- }
3043
- }
3044
- const streamWorkflow = useMutation(({ workflowId, runId, inputData, initialState, requestContext, perStep, resourceId }) => {
3045
- setStreamResult({
3046
- status: "pending",
3047
- input: inputData,
3048
- steps: {}
3049
- });
3050
- return consumeStream(async (signal) => {
3051
- const run = await client.getWorkflow(workflowId).createRun({
3052
- runId,
3053
- resourceId
3054
- });
3055
- if (signal.aborted) return;
3056
- return run.stream({
3057
- inputData,
3058
- initialState,
3059
- requestContext,
3060
- closeOnSuspend: true,
3061
- tracingOptions,
3062
- perStep: perStep ?? debugMode,
3063
- resourceId
3064
- });
3065
- }, "Error streaming workflow");
3066
- });
3067
- const observeWorkflowStream = useMutation(async ({ workflowId, runId, storeRunResult }) => {
3068
- if (!isMountedRef.current) return;
3069
- setStreamResult(storeRunResult ?? void 0);
3070
- if (storeRunResult?.status === "suspended") {
3071
- closeActiveStream();
3072
- setIsStreaming(false);
3073
- return;
3074
- }
3075
- await consumeStream(async (signal) => {
3076
- const run = await client.getWorkflow(workflowId).createRun({ runId });
3077
- if (signal.aborted) return;
3078
- return run.observeStream();
3079
- }, "Error observing workflow");
3080
- });
3081
- const resumeWorkflowStream = useMutation(({ workflowId, runId, step, resumeData, requestContext, perStep }) => consumeStream(async (signal) => {
3082
- const run = await client.getWorkflow(workflowId).createRun({ runId });
3083
- if (signal.aborted) return;
3084
- return run.resumeStream({
3085
- step,
3086
- resumeData,
3087
- requestContext,
3088
- tracingOptions,
3089
- perStep: perStep ?? debugMode
3090
- });
3091
- }, "Error resuming workflow stream"));
3092
- const timeTravelWorkflowStream = useMutation(({ workflowId, requestContext, runId, perStep, ...params }) => consumeStream(async (signal) => {
3093
- const run = await client.getWorkflow(workflowId).createRun({ runId });
3094
- if (signal.aborted) return;
3095
- return run.timeTravelStream({
3096
- ...params,
3097
- perStep: perStep ?? debugMode,
3098
- requestContext,
3099
- tracingOptions
3100
- });
3101
- }, "Error time traveling workflow stream"));
3102
- return {
3103
- streamWorkflow,
3104
- streamResult,
3105
- isStreaming,
3106
- observeWorkflowStream,
3107
- closeStreamsAndReset: useCallback(() => {
3108
- closeActiveStream();
3109
- setIsStreaming(false);
3110
- setStreamResult(void 0);
3111
- }, [closeActiveStream]),
3112
- resumeWorkflowStream,
3113
- timeTravelWorkflowStream
3114
- };
3115
- }
3116
- //#endregion
3117
- //#region src/workflows/hooks.ts
3118
- /**
3119
- * Hook for creating workflow runs.
3120
- * Returns a mutation for creating a new workflow run.
3121
- *
3122
- * @example
3123
- * ```tsx
3124
- * const createWorkflowRun = useCreateWorkflowRun();
3125
- *
3126
- * // Create a run
3127
- * const { runId } = await createWorkflowRun.mutateAsync({
3128
- * workflowId: 'my-workflow'
3129
- * });
3130
- * ```
3131
- */
3132
- function useCreateWorkflowRun() {
3133
- const client = useMastraClient();
3134
- return useMutation(async ({ workflowId, prevRunId, resourceId }) => {
3135
- try {
3136
- const { runId: newRunId } = await client.getWorkflow(workflowId).createRun({
3137
- runId: prevRunId,
3138
- resourceId
3139
- });
3140
- return { runId: newRunId };
3141
- } catch (error) {
3142
- console.error("Error creating workflow run:", error);
3143
- throw error;
3144
- }
3145
- });
3146
- }
3147
- /**
3148
- * Hook for canceling workflow runs.
3149
- * Returns a mutation for canceling a running workflow.
3150
- *
3151
- * @example
3152
- * ```tsx
3153
- * const cancelWorkflowRun = useCancelWorkflowRun();
3154
- *
3155
- * // Cancel a run
3156
- * await cancelWorkflowRun.mutateAsync({
3157
- * workflowId: 'my-workflow',
3158
- * runId: 'run-123'
3159
- * });
3160
- * ```
3161
- */
3162
- function useCancelWorkflowRun() {
3163
- const client = useMastraClient();
3164
- return useMutation(async ({ workflowId, runId }) => {
3165
- try {
3166
- return (await client.getWorkflow(workflowId).createRun({ runId })).cancelRun();
3167
- } catch (error) {
3168
- console.error("Error canceling workflow run:", error);
3169
- throw error;
3170
- }
3171
- });
3172
- }
3173
- //#endregion
3174
20
  //#region src/workflows/WorkflowStepFactory/WorkflowStepFactory.tsx
3175
21
  const renderUnknown = (step, UnknownStep) => UnknownStep?.(step) ?? null;
3176
22
  const WorkflowStepFactoryComponent = ({ step, Step, MapStep, AgentStep, ToolStep, ClassifierStep, ForEachStep, ParallelStep, Conditional, LoopStep, SleepStep, SleepUntilStep, NestedWorkflowStep, UnknownStep }) => {
@@ -3192,265 +38,6 @@ const WorkflowStepFactoryComponent = ({ step, Step, MapStep, AgentStep, ToolStep
3192
38
  };
3193
39
  const WorkflowStepFactory = memo(WorkflowStepFactoryComponent);
3194
40
  //#endregion
3195
- //#region src/voice/record-mic-to-file.ts
3196
- async function recordMicrophoneToFile(onFinish) {
3197
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
3198
- const mediaRecorder = new MediaRecorder(stream);
3199
- let chunks = [];
3200
- mediaRecorder.ondataavailable = (e) => {
3201
- chunks.push(e.data);
3202
- };
3203
- mediaRecorder.onstop = () => {
3204
- const blob = new Blob(chunks, { type: "audio/webm" });
3205
- const file = new File([blob], `recording-${Date.now()}.webm`, {
3206
- type: "audio/webm",
3207
- lastModified: Date.now()
3208
- });
3209
- stream.getTracks().forEach((track) => track.stop());
3210
- onFinish(file);
3211
- };
3212
- return mediaRecorder;
3213
- }
3214
- //#endregion
3215
- //#region src/voice/play-stream-with-web-audio.ts
3216
- async function playStreamWithWebAudio(stream, onEnded) {
3217
- const audioContext = new window.AudioContext();
3218
- const reader = stream.getReader();
3219
- const chunks = [];
3220
- try {
3221
- while (true) {
3222
- const { done, value } = await reader.read();
3223
- if (done) break;
3224
- chunks.push(value);
3225
- }
3226
- const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
3227
- const combinedBuffer = new Uint8Array(totalLength);
3228
- let offset = 0;
3229
- for (const chunk of chunks) {
3230
- combinedBuffer.set(chunk, offset);
3231
- offset += chunk.length;
3232
- }
3233
- const audioBuffer = await audioContext.decodeAudioData(combinedBuffer.buffer);
3234
- const source = audioContext.createBufferSource();
3235
- source.buffer = audioBuffer;
3236
- source.onended = onEnded ?? null;
3237
- source.connect(audioContext.destination);
3238
- source.start();
3239
- return () => {
3240
- source.onended = null;
3241
- source.stop();
3242
- audioContext.close();
3243
- };
3244
- } catch (error) {
3245
- await reader.cancel().catch(() => void 0);
3246
- await audioContext.close().catch(() => void 0);
3247
- throw error;
3248
- } finally {
3249
- reader.releaseLock();
3250
- }
3251
- }
3252
- //#endregion
3253
- //#region src/voice/use-speech-recognition.ts
3254
- const useSpeechRecognition = ({ language = "en-US", agentId, requestContext }) => {
3255
- const client = useMastraClient();
3256
- const [agent, setAgent] = useState(null);
3257
- useEffect(() => {
3258
- let cancelled = false;
3259
- if (!agentId) {
3260
- setAgent(null);
3261
- return () => {
3262
- cancelled = true;
3263
- };
3264
- }
3265
- const agent = client.getAgent(agentId);
3266
- const check = async () => {
3267
- try {
3268
- const speakers = await agent.voice.getSpeakers(requestContext);
3269
- if (!cancelled) setAgent(speakers.length > 0 ? agent : null);
3270
- } catch {
3271
- if (!cancelled) setAgent(null);
3272
- }
3273
- };
3274
- check();
3275
- return () => {
3276
- cancelled = true;
3277
- };
3278
- }, [
3279
- agentId,
3280
- client,
3281
- requestContext
3282
- ]);
3283
- const browserSpeechRecognition = useBrowserSpeechRecognition({ language });
3284
- const mastraSpeechRecognition = useMastraSpeechToText({
3285
- agent,
3286
- language
3287
- });
3288
- if (!agent) return browserSpeechRecognition;
3289
- return mastraSpeechRecognition;
3290
- };
3291
- const useBrowserSpeechRecognition = ({ language = "en-US" }) => {
3292
- const speechRecognitionRef = useRef(null);
3293
- const [state, setState] = useState({
3294
- isListening: false,
3295
- transcript: "",
3296
- error: null
3297
- });
3298
- const start = () => {
3299
- if (!speechRecognitionRef.current) return;
3300
- speechRecognitionRef.current.start();
3301
- };
3302
- const stop = () => {
3303
- if (!speechRecognitionRef.current) return;
3304
- speechRecognitionRef.current.stop();
3305
- };
3306
- useEffect(() => {
3307
- if (!("webkitSpeechRecognition" in window) && !("SpeechRecognition" in window)) {
3308
- setState((prev) => ({
3309
- ...prev,
3310
- error: "Speech Recognition not supported in this browser"
3311
- }));
3312
- return;
3313
- }
3314
- const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
3315
- speechRecognitionRef.current = recognition;
3316
- recognition.continuous = true;
3317
- recognition.lang = language;
3318
- recognition.onstart = () => {
3319
- setState((prev) => ({
3320
- ...prev,
3321
- isListening: true,
3322
- error: null,
3323
- transcript: ""
3324
- }));
3325
- };
3326
- recognition.onresult = (event) => {
3327
- let finalTranscript = "";
3328
- for (let i = event.resultIndex; i < event.results.length; i++) {
3329
- const transcript = event.results[i][0].transcript;
3330
- if (event.results[i].isFinal) finalTranscript += transcript + " ";
3331
- }
3332
- if (!finalTranscript) return;
3333
- setState((prev) => ({
3334
- ...prev,
3335
- transcript: prev.transcript + finalTranscript
3336
- }));
3337
- };
3338
- recognition.onerror = (event) => {
3339
- setState((prev) => ({
3340
- ...prev,
3341
- error: `Error: ${event.error}`
3342
- }));
3343
- };
3344
- recognition.onend = () => setState((prev) => ({
3345
- ...prev,
3346
- isListening: false
3347
- }));
3348
- return () => {
3349
- try {
3350
- recognition.stop();
3351
- } catch {}
3352
- recognition.onstart = null;
3353
- recognition.onresult = null;
3354
- recognition.onerror = null;
3355
- recognition.onend = null;
3356
- speechRecognitionRef.current = null;
3357
- };
3358
- }, [language]);
3359
- return {
3360
- ...state,
3361
- start,
3362
- stop
3363
- };
3364
- };
3365
- const useMastraSpeechToText = ({ agent, language }) => {
3366
- const [state, setState] = useState({
3367
- isListening: false,
3368
- transcript: "",
3369
- error: null
3370
- });
3371
- const recorderRef = useRef(null);
3372
- const sessionRef = useRef(0);
3373
- const startInFlightRef = useRef(false);
3374
- useEffect(() => {
3375
- return () => {
3376
- sessionRef.current += 1;
3377
- startInFlightRef.current = false;
3378
- recorderRef.current?.stop();
3379
- recorderRef.current = null;
3380
- };
3381
- }, [agent]);
3382
- const handleFinish = (session) => (file) => {
3383
- if (!agent || session !== sessionRef.current) return;
3384
- recorderRef.current = null;
3385
- setState((prev) => ({
3386
- ...prev,
3387
- isListening: false
3388
- }));
3389
- agent.voice.listen(file, { language }).then((res) => {
3390
- if (session !== sessionRef.current) return;
3391
- setState((prev) => ({
3392
- ...prev,
3393
- transcript: res.text,
3394
- error: null
3395
- }));
3396
- }).catch((error) => {
3397
- if (session !== sessionRef.current) return;
3398
- const message = error instanceof Error ? error.message : "Failed to transcribe speech";
3399
- setState((prev) => ({
3400
- ...prev,
3401
- error: message
3402
- }));
3403
- });
3404
- };
3405
- const start = () => {
3406
- if (!agent || startInFlightRef.current || recorderRef.current) return;
3407
- startInFlightRef.current = true;
3408
- sessionRef.current += 1;
3409
- const session = sessionRef.current;
3410
- recordMicrophoneToFile(handleFinish(session)).then((recorder) => {
3411
- startInFlightRef.current = false;
3412
- if (session !== sessionRef.current) {
3413
- try {
3414
- recorder.stop();
3415
- } catch {}
3416
- return;
3417
- }
3418
- recorderRef.current = recorder;
3419
- setState((prev) => ({
3420
- ...prev,
3421
- isListening: true,
3422
- error: null
3423
- }));
3424
- recorder.start();
3425
- }).catch((error) => {
3426
- startInFlightRef.current = false;
3427
- if (session !== sessionRef.current) return;
3428
- const message = error instanceof Error ? error.message : "Failed to start speech recording";
3429
- setState((prev) => ({
3430
- ...prev,
3431
- isListening: false,
3432
- error: message
3433
- }));
3434
- });
3435
- };
3436
- const stop = () => {
3437
- if (recorderRef.current) {
3438
- recorderRef.current.stop();
3439
- recorderRef.current = null;
3440
- } else if (startInFlightRef.current) sessionRef.current += 1;
3441
- startInFlightRef.current = false;
3442
- setState((prev) => ({
3443
- ...prev,
3444
- isListening: false
3445
- }));
3446
- };
3447
- return {
3448
- ...state,
3449
- start,
3450
- stop
3451
- };
3452
- };
3453
- //#endregion
3454
41
  export { CLIENT_MESSAGE_ID_KEY, MastraReactProvider, WorkflowStepFactory, accumulateChunk, accumulateNetworkChunk, finishStreamingAssistantMessage, fromCoreUserMessageToMastraDBMessage, fromCoreUserMessagesToMastraDBMessage, mapWorkflowStreamChunkToWatchResult, playStreamWithWebAudio, recordMicrophoneToFile, useCancelWorkflowRun, useChat, useCreateWorkflowRun, useMastraClient, useSpeechRecognition, useStreamWorkflow };
3455
42
 
3456
43
  //# sourceMappingURL=index.js.map