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