@copilotkit/react-core 1.10.7-next.0 → 1.50.0-beta.0

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 (334) hide show
  1. package/CHANGELOG.md +0 -7
  2. package/dist/chunk-24SCZAB4.mjs +143 -0
  3. package/dist/chunk-24SCZAB4.mjs.map +1 -0
  4. package/dist/chunk-36KQV2NA.mjs +1 -0
  5. package/dist/{chunk-U7QULEVO.mjs → chunk-3GURHDG7.mjs} +3 -3
  6. package/dist/{chunk-OAGAFMUM.mjs → chunk-3R423LZT.mjs} +6 -5
  7. package/dist/{chunk-OAGAFMUM.mjs.map → chunk-3R423LZT.mjs.map} +1 -1
  8. package/dist/chunk-5X5DJRQQ.mjs +71 -0
  9. package/dist/chunk-5X5DJRQQ.mjs.map +1 -0
  10. package/dist/{chunk-N4WEHORG.mjs → chunk-6PUNP7CD.mjs} +4 -4
  11. package/dist/chunk-6PUNP7CD.mjs.map +1 -0
  12. package/dist/chunk-7BYHZLPL.mjs +32 -0
  13. package/dist/chunk-7BYHZLPL.mjs.map +1 -0
  14. package/dist/chunk-7DTB7S5V.mjs +83 -0
  15. package/dist/chunk-7DTB7S5V.mjs.map +1 -0
  16. package/dist/chunk-A6NKSGH3.mjs +1 -0
  17. package/dist/{chunk-GT5WI3AF.mjs → chunk-BR5YEYZJ.mjs} +7 -9
  18. package/dist/chunk-BR5YEYZJ.mjs.map +1 -0
  19. package/dist/chunk-CB7CRBDG.mjs +48 -0
  20. package/dist/chunk-CB7CRBDG.mjs.map +1 -0
  21. package/dist/chunk-CYDWEPFL.mjs +1 -0
  22. package/dist/{chunk-BBUQMG45.mjs → chunk-D3QSYDJR.mjs} +3 -3
  23. package/dist/{chunk-BBUQMG45.mjs.map → chunk-D3QSYDJR.mjs.map} +1 -1
  24. package/dist/chunk-DCHSCK62.mjs +549 -0
  25. package/dist/chunk-DCHSCK62.mjs.map +1 -0
  26. package/dist/{chunk-ZLQVRPDS.mjs → chunk-DMLQZG75.mjs} +1 -1
  27. package/dist/chunk-DMLQZG75.mjs.map +1 -0
  28. package/dist/chunk-F555TVE4.mjs +33 -0
  29. package/dist/chunk-F555TVE4.mjs.map +1 -0
  30. package/dist/{chunk-C6IANC2R.mjs → chunk-FBD24VEH.mjs} +7 -43
  31. package/dist/chunk-FBD24VEH.mjs.map +1 -0
  32. package/dist/chunk-FD6FGKYY.mjs +1 -0
  33. package/dist/chunk-FDOMAPJY.mjs +59 -0
  34. package/dist/chunk-FDOMAPJY.mjs.map +1 -0
  35. package/dist/{chunk-E3624YDU.mjs → chunk-GMI4KO4X.mjs} +8 -6
  36. package/dist/{chunk-E3624YDU.mjs.map → chunk-GMI4KO4X.mjs.map} +1 -1
  37. package/dist/chunk-IUSKVYUI.mjs +13 -0
  38. package/dist/chunk-IUSKVYUI.mjs.map +1 -0
  39. package/dist/chunk-JD7BAH7U.mjs +1 -0
  40. package/dist/{chunk-EDBI5PCJ.mjs → chunk-JRT5BJF3.mjs} +2 -2
  41. package/dist/{chunk-N4VN2B5S.mjs → chunk-LHERIF3L.mjs} +2 -2
  42. package/dist/{chunk-DXEQPN43.mjs → chunk-LHKZJ2ND.mjs} +3 -3
  43. package/dist/chunk-NB2FKV2V.mjs +1 -0
  44. package/dist/chunk-NBK4KBLX.mjs +54 -0
  45. package/dist/chunk-NBK4KBLX.mjs.map +1 -0
  46. package/dist/chunk-NG26QEGF.mjs +46 -0
  47. package/dist/chunk-NG26QEGF.mjs.map +1 -0
  48. package/dist/chunk-NROJOTQP.mjs +163 -0
  49. package/dist/chunk-NROJOTQP.mjs.map +1 -0
  50. package/dist/{chunk-MGWRDFBE.mjs → chunk-OVYFRPSN.mjs} +2 -2
  51. package/dist/{chunk-MQYWH4E6.mjs → chunk-QU6NONOD.mjs} +2 -2
  52. package/dist/chunk-R4MR43UQ.mjs +101 -0
  53. package/dist/chunk-R4MR43UQ.mjs.map +1 -0
  54. package/dist/chunk-SPCZTZCY.mjs +1 -0
  55. package/dist/chunk-SPCZTZCY.mjs.map +1 -0
  56. package/dist/chunk-TXI72QHK.mjs +80 -0
  57. package/dist/chunk-TXI72QHK.mjs.map +1 -0
  58. package/dist/chunk-UJBV5GAG.mjs +767 -0
  59. package/dist/chunk-UJBV5GAG.mjs.map +1 -0
  60. package/dist/{chunk-OKCYPO4I.mjs → chunk-WMJVBMUX.mjs} +3 -3
  61. package/dist/{chunk-EUX2P2E7.mjs → chunk-WVLHXIFP.mjs} +11 -9
  62. package/dist/chunk-WVLHXIFP.mjs.map +1 -0
  63. package/dist/{chunk-5FHSUKQL.mjs → chunk-YYN33GSG.mjs} +5 -2
  64. package/dist/chunk-YYN33GSG.mjs.map +1 -0
  65. package/dist/chunk-ZVF5Q6IH.mjs +29 -0
  66. package/dist/chunk-ZVF5Q6IH.mjs.map +1 -0
  67. package/dist/components/CopilotListeners.d.ts +3 -0
  68. package/dist/components/CopilotListeners.js +234 -0
  69. package/dist/components/CopilotListeners.js.map +1 -0
  70. package/dist/components/CopilotListeners.mjs +14 -0
  71. package/dist/components/CopilotListeners.mjs.map +1 -0
  72. package/dist/components/copilot-provider/copilot-messages.js +14 -48
  73. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  74. package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
  75. package/dist/components/copilot-provider/copilotkit-props.d.ts +9 -2
  76. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  77. package/dist/components/copilot-provider/copilotkit.d.ts +2 -1
  78. package/dist/components/copilot-provider/copilotkit.js +528 -370
  79. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  80. package/dist/components/copilot-provider/copilotkit.mjs +15 -10
  81. package/dist/components/copilot-provider/index.d.ts +2 -1
  82. package/dist/components/copilot-provider/index.js +528 -370
  83. package/dist/components/copilot-provider/index.js.map +1 -1
  84. package/dist/components/copilot-provider/index.mjs +16 -10
  85. package/dist/components/dev-console/console-trigger.js +10 -8
  86. package/dist/components/dev-console/console-trigger.js.map +1 -1
  87. package/dist/components/dev-console/console-trigger.mjs +4 -4
  88. package/dist/components/dev-console/developer-console-modal.js +10 -8
  89. package/dist/components/dev-console/developer-console-modal.js.map +1 -1
  90. package/dist/components/dev-console/developer-console-modal.mjs +3 -3
  91. package/dist/components/error-boundary/error-boundary.d.ts +7 -7
  92. package/dist/components/error-boundary/error-boundary.js +3 -3
  93. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  94. package/dist/components/error-boundary/error-boundary.mjs +2 -2
  95. package/dist/components/error-boundary/error-utils.d.ts +1 -1
  96. package/dist/components/error-boundary/error-utils.js +3 -3
  97. package/dist/components/error-boundary/error-utils.js.map +1 -1
  98. package/dist/components/error-boundary/error-utils.mjs +1 -1
  99. package/dist/components/index.d.ts +2 -1
  100. package/dist/components/index.js +528 -370
  101. package/dist/components/index.js.map +1 -1
  102. package/dist/components/index.mjs +17 -10
  103. package/dist/components/toast/exclamation-mark-icon.d.ts +2 -2
  104. package/dist/components/toast/toast-provider.d.ts +3 -3
  105. package/dist/components/usage-banner.d.ts +2 -2
  106. package/dist/context/coagent-state-renders-context.d.ts +24 -0
  107. package/dist/context/coagent-state-renders-context.js +91 -0
  108. package/dist/context/coagent-state-renders-context.js.map +1 -0
  109. package/dist/context/coagent-state-renders-context.mjs +12 -0
  110. package/dist/context/coagent-state-renders-context.mjs.map +1 -0
  111. package/dist/context/copilot-context.d.ts +1 -1
  112. package/dist/context/copilot-context.js +10 -8
  113. package/dist/context/copilot-context.js.map +1 -1
  114. package/dist/context/copilot-context.mjs +1 -1
  115. package/dist/context/copilot-messages-context.d.ts +18 -11
  116. package/dist/context/copilot-messages-context.js.map +1 -1
  117. package/dist/context/copilot-messages-context.mjs +1 -1
  118. package/dist/context/index.d.ts +6 -2
  119. package/dist/context/index.js +110 -10
  120. package/dist/context/index.js.map +1 -1
  121. package/dist/context/index.mjs +20 -4
  122. package/dist/context/threads-context.d.ts +16 -0
  123. package/dist/context/threads-context.js +59 -0
  124. package/dist/context/threads-context.js.map +1 -0
  125. package/dist/context/threads-context.mjs +12 -0
  126. package/dist/context/threads-context.mjs.map +1 -0
  127. package/dist/{copilot-context-cf9de848.d.ts → copilot-context-1cd70a3f.d.ts} +36 -32
  128. package/dist/hooks/index.d.ts +9 -6
  129. package/dist/hooks/index.js +1445 -1839
  130. package/dist/hooks/index.js.map +1 -1
  131. package/dist/hooks/index.mjs +47 -56
  132. package/dist/hooks/use-coagent-state-render-bridge.d.ts +100 -0
  133. package/dist/hooks/use-coagent-state-render-bridge.js +211 -0
  134. package/dist/hooks/use-coagent-state-render-bridge.js.map +1 -0
  135. package/dist/hooks/use-coagent-state-render-bridge.mjs +15 -0
  136. package/dist/hooks/use-coagent-state-render-bridge.mjs.map +1 -0
  137. package/dist/hooks/use-coagent-state-render.js +31 -20
  138. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  139. package/dist/hooks/use-coagent-state-render.mjs +3 -2
  140. package/dist/hooks/use-coagent.d.ts +2 -14
  141. package/dist/hooks/use-coagent.js +109 -1906
  142. package/dist/hooks/use-coagent.js.map +1 -1
  143. package/dist/hooks/use-coagent.mjs +1 -30
  144. package/dist/hooks/use-configure-chat-suggestions.d.ts +36 -0
  145. package/dist/hooks/use-configure-chat-suggestions.js +210 -0
  146. package/dist/hooks/use-configure-chat-suggestions.js.map +1 -0
  147. package/dist/hooks/use-configure-chat-suggestions.mjs +13 -0
  148. package/dist/hooks/use-configure-chat-suggestions.mjs.map +1 -0
  149. package/dist/hooks/use-copilot-action.d.ts +8 -45
  150. package/dist/hooks/use-copilot-action.js +207 -349
  151. package/dist/hooks/use-copilot-action.js.map +1 -1
  152. package/dist/hooks/use-copilot-action.mjs +4 -5
  153. package/dist/hooks/use-copilot-additional-instructions.js +10 -8
  154. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  155. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  156. package/dist/hooks/use-copilot-authenticated-action.js +224 -248
  157. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  158. package/dist/hooks/use-copilot-authenticated-action.mjs +6 -6
  159. package/dist/hooks/use-copilot-chat-headless_c.d.ts +2 -10
  160. package/dist/hooks/use-copilot-chat-headless_c.js +973 -1369
  161. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  162. package/dist/hooks/use-copilot-chat-headless_c.mjs +12 -22
  163. package/dist/hooks/use-copilot-chat.d.ts +2 -10
  164. package/dist/hooks/use-copilot-chat.js +967 -1388
  165. package/dist/hooks/use-copilot-chat.js.map +1 -1
  166. package/dist/hooks/use-copilot-chat.mjs +12 -22
  167. package/dist/hooks/use-copilot-chat_internal.d.ts +38 -14
  168. package/dist/hooks/use-copilot-chat_internal.js +965 -1362
  169. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  170. package/dist/hooks/use-copilot-chat_internal.mjs +13 -23
  171. package/dist/hooks/use-copilot-readable.d.ts +1 -1
  172. package/dist/hooks/use-copilot-readable.js +6 -157
  173. package/dist/hooks/use-copilot-readable.js.map +1 -1
  174. package/dist/hooks/use-copilot-readable.mjs +1 -2
  175. package/dist/hooks/use-default-tool.js +204 -349
  176. package/dist/hooks/use-default-tool.js.map +1 -1
  177. package/dist/hooks/use-default-tool.mjs +5 -6
  178. package/dist/hooks/use-flat-category-store.js +4 -1
  179. package/dist/hooks/use-flat-category-store.js.map +1 -1
  180. package/dist/hooks/use-flat-category-store.mjs +1 -1
  181. package/dist/hooks/use-frontend-tool.d.ts +3 -3
  182. package/dist/hooks/use-frontend-tool.js +30 -370
  183. package/dist/hooks/use-frontend-tool.js.map +1 -1
  184. package/dist/hooks/use-frontend-tool.mjs +1 -6
  185. package/dist/hooks/use-human-in-the-loop.d.ts +4 -3
  186. package/dist/hooks/use-human-in-the-loop.js +61 -393
  187. package/dist/hooks/use-human-in-the-loop.js.map +1 -1
  188. package/dist/hooks/use-human-in-the-loop.mjs +1 -6
  189. package/dist/hooks/use-langgraph-interrupt-render.d.ts +3 -2
  190. package/dist/hooks/use-langgraph-interrupt-render.js +92 -36
  191. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  192. package/dist/hooks/use-langgraph-interrupt-render.mjs +6 -4
  193. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  194. package/dist/hooks/use-langgraph-interrupt.js +24 -1642
  195. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  196. package/dist/hooks/use-langgraph-interrupt.mjs +2 -23
  197. package/dist/hooks/use-lazy-tool-renderer.d.ts +6 -0
  198. package/dist/hooks/use-lazy-tool-renderer.js +53 -0
  199. package/dist/hooks/use-lazy-tool-renderer.js.map +1 -0
  200. package/dist/hooks/use-lazy-tool-renderer.mjs +8 -0
  201. package/dist/hooks/use-lazy-tool-renderer.mjs.map +1 -0
  202. package/dist/hooks/use-make-copilot-document-readable.js +11 -9
  203. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  204. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  205. package/dist/hooks/use-render-tool-call.d.ts +7 -6
  206. package/dist/hooks/use-render-tool-call.js +36 -386
  207. package/dist/hooks/use-render-tool-call.js.map +1 -1
  208. package/dist/hooks/use-render-tool-call.mjs +1 -6
  209. package/dist/index.d.ts +11 -6
  210. package/dist/index.js +1841 -2056
  211. package/dist/index.js.map +1 -1
  212. package/dist/index.mjs +78 -59
  213. package/dist/lib/copilot-task.d.ts +1 -1
  214. package/dist/lib/copilot-task.js +1 -0
  215. package/dist/lib/copilot-task.js.map +1 -1
  216. package/dist/lib/copilot-task.mjs +18 -11
  217. package/dist/lib/index.d.ts +1 -1
  218. package/dist/lib/index.js +1 -0
  219. package/dist/lib/index.js.map +1 -1
  220. package/dist/lib/index.mjs +18 -11
  221. package/dist/setupTests.d.ts +2 -2
  222. package/dist/types/frontend-action.d.ts +5 -5
  223. package/dist/types/index.d.ts +4 -0
  224. package/dist/types/index.js.map +1 -1
  225. package/dist/types/index.mjs +2 -1
  226. package/dist/types/interrupt-action.d.ts +1 -1
  227. package/dist/types/interrupt-action.js.map +1 -1
  228. package/dist/types/interrupt-action.mjs +1 -0
  229. package/dist/utils/index.d.ts +0 -12
  230. package/dist/utils/index.js +6 -325
  231. package/dist/utils/index.js.map +1 -1
  232. package/dist/utils/index.mjs +1 -21
  233. package/dist/utils/utils.js.map +1 -1
  234. package/dist/v2/index.d.ts +2 -0
  235. package/dist/v2/index.js +27 -0
  236. package/dist/v2/index.js.map +1 -0
  237. package/dist/v2/index.mjs +4 -0
  238. package/dist/v2/index.mjs.map +1 -0
  239. package/package.json +34 -23
  240. package/src/components/CopilotListeners.tsx +82 -0
  241. package/src/components/copilot-provider/copilot-messages.tsx +46 -47
  242. package/src/components/copilot-provider/copilotkit-props.tsx +8 -1
  243. package/src/components/copilot-provider/copilotkit.tsx +177 -144
  244. package/src/components/error-boundary/error-utils.tsx +3 -3
  245. package/src/context/coagent-state-renders-context.tsx +76 -0
  246. package/src/context/copilot-context.tsx +21 -21
  247. package/src/context/copilot-messages-context.tsx +3 -3
  248. package/src/context/index.ts +8 -0
  249. package/src/context/threads-context.tsx +41 -0
  250. package/src/hooks/index.ts +7 -3
  251. package/src/hooks/use-coagent-state-render-bridge.tsx +293 -0
  252. package/src/hooks/use-coagent-state-render.ts +4 -7
  253. package/src/hooks/use-coagent.ts +129 -249
  254. package/src/hooks/use-configure-chat-suggestions.tsx +85 -0
  255. package/src/hooks/use-copilot-action.ts +88 -199
  256. package/src/hooks/use-copilot-chat-headless_c.ts +2 -1
  257. package/src/hooks/use-copilot-chat.ts +4 -1
  258. package/src/hooks/use-copilot-chat_internal.ts +349 -258
  259. package/src/hooks/use-copilot-readable.ts +6 -26
  260. package/src/hooks/use-flat-category-store.ts +4 -3
  261. package/src/hooks/use-frontend-tool.ts +67 -8
  262. package/src/hooks/use-human-in-the-loop.ts +111 -13
  263. package/src/hooks/use-langgraph-interrupt-render.ts +90 -40
  264. package/src/hooks/use-langgraph-interrupt.ts +18 -47
  265. package/src/hooks/use-lazy-tool-renderer.tsx +30 -0
  266. package/src/hooks/use-make-copilot-document-readable.ts +1 -1
  267. package/src/hooks/use-render-tool-call.ts +73 -13
  268. package/src/types/index.ts +1 -0
  269. package/src/types/interrupt-action.ts +8 -4
  270. package/src/utils/index.ts +0 -3
  271. package/src/utils/utils.ts +7 -0
  272. package/src/v2/index.ts +2 -0
  273. package/src/v2/styles.css +1 -0
  274. package/tsup.config.ts +1 -1
  275. package/dist/chunk-5FHSUKQL.mjs.map +0 -1
  276. package/dist/chunk-6GPVUMBU.mjs +0 -13
  277. package/dist/chunk-6GPVUMBU.mjs.map +0 -1
  278. package/dist/chunk-AKR2SSUJ.mjs +0 -22
  279. package/dist/chunk-AKR2SSUJ.mjs.map +0 -1
  280. package/dist/chunk-BXXJQ2BL.mjs +0 -239
  281. package/dist/chunk-BXXJQ2BL.mjs.map +0 -1
  282. package/dist/chunk-C6IANC2R.mjs.map +0 -1
  283. package/dist/chunk-DZTU6PGS.mjs +0 -1
  284. package/dist/chunk-EUX2P2E7.mjs.map +0 -1
  285. package/dist/chunk-EVVO67QO.mjs +0 -25
  286. package/dist/chunk-EVVO67QO.mjs.map +0 -1
  287. package/dist/chunk-GGLAHG3I.mjs +0 -804
  288. package/dist/chunk-GGLAHG3I.mjs.map +0 -1
  289. package/dist/chunk-GT5WI3AF.mjs.map +0 -1
  290. package/dist/chunk-HDOG2RTM.mjs +0 -37
  291. package/dist/chunk-HDOG2RTM.mjs.map +0 -1
  292. package/dist/chunk-MIXSWZSB.mjs +0 -71
  293. package/dist/chunk-MIXSWZSB.mjs.map +0 -1
  294. package/dist/chunk-N4WEHORG.mjs.map +0 -1
  295. package/dist/chunk-NSBAWITG.mjs +0 -332
  296. package/dist/chunk-NSBAWITG.mjs.map +0 -1
  297. package/dist/chunk-OT5NHMEC.mjs +0 -723
  298. package/dist/chunk-OT5NHMEC.mjs.map +0 -1
  299. package/dist/chunk-T3376SZS.mjs +0 -142
  300. package/dist/chunk-T3376SZS.mjs.map +0 -1
  301. package/dist/chunk-YPBKY4KY.mjs +0 -1
  302. package/dist/chunk-YPSGKPDA.mjs +0 -1
  303. package/dist/chunk-ZLQVRPDS.mjs.map +0 -1
  304. package/dist/chunk-ZVOLWJCY.mjs +0 -47
  305. package/dist/chunk-ZVOLWJCY.mjs.map +0 -1
  306. package/dist/hooks/use-chat.d.ts +0 -145
  307. package/dist/hooks/use-chat.js +0 -1129
  308. package/dist/hooks/use-chat.js.map +0 -1
  309. package/dist/hooks/use-chat.mjs +0 -14
  310. package/dist/index-1f5b66ac.d.ts +0 -36
  311. package/dist/utils/extract.d.ts +0 -43
  312. package/dist/utils/extract.js +0 -208
  313. package/dist/utils/extract.js.map +0 -1
  314. package/dist/utils/extract.mjs +0 -25
  315. package/dist/utils/suggestions.d.ts +0 -11
  316. package/dist/utils/suggestions.js +0 -343
  317. package/dist/utils/suggestions.js.map +0 -1
  318. package/dist/utils/suggestions.mjs +0 -25
  319. package/src/hooks/use-chat.ts +0 -1142
  320. package/src/utils/extract.ts +0 -215
  321. package/src/utils/suggestions.ts +0 -208
  322. /package/dist/{chunk-DZTU6PGS.mjs.map → chunk-36KQV2NA.mjs.map} +0 -0
  323. /package/dist/{chunk-U7QULEVO.mjs.map → chunk-3GURHDG7.mjs.map} +0 -0
  324. /package/dist/{chunk-YPBKY4KY.mjs.map → chunk-A6NKSGH3.mjs.map} +0 -0
  325. /package/dist/{chunk-YPSGKPDA.mjs.map → chunk-CYDWEPFL.mjs.map} +0 -0
  326. /package/dist/{hooks/use-chat.mjs.map → chunk-FD6FGKYY.mjs.map} +0 -0
  327. /package/dist/{utils/extract.mjs.map → chunk-JD7BAH7U.mjs.map} +0 -0
  328. /package/dist/{chunk-EDBI5PCJ.mjs.map → chunk-JRT5BJF3.mjs.map} +0 -0
  329. /package/dist/{chunk-N4VN2B5S.mjs.map → chunk-LHERIF3L.mjs.map} +0 -0
  330. /package/dist/{chunk-DXEQPN43.mjs.map → chunk-LHKZJ2ND.mjs.map} +0 -0
  331. /package/dist/{utils/suggestions.mjs.map → chunk-NB2FKV2V.mjs.map} +0 -0
  332. /package/dist/{chunk-MGWRDFBE.mjs.map → chunk-OVYFRPSN.mjs.map} +0 -0
  333. /package/dist/{chunk-MQYWH4E6.mjs.map → chunk-QU6NONOD.mjs.map} +0 -0
  334. /package/dist/{chunk-OKCYPO4I.mjs.map → chunk-WMJVBMUX.mjs.map} +0 -0
@@ -80,10 +80,10 @@ var __async = (__this, __arguments, generator) => {
80
80
  var use_copilot_chat_internal_exports = {};
81
81
  __export(use_copilot_chat_internal_exports, {
82
82
  defaultSystemMessage: () => defaultSystemMessage,
83
- useCopilotChat: () => useCopilotChat
83
+ useCopilotChatInternal: () => useCopilotChatInternal
84
84
  });
85
85
  module.exports = __toCommonJS(use_copilot_chat_internal_exports);
86
- var import_react9 = require("react");
86
+ var import_react12 = require("react");
87
87
 
88
88
  // src/context/copilot-context.tsx
89
89
  var import_react = __toESM(require("react"));
@@ -93,10 +93,8 @@ var emptyCopilotContext = {
93
93
  },
94
94
  removeAction: () => {
95
95
  },
96
- coAgentStateRenders: {},
97
- setCoAgentStateRender: () => {
98
- },
99
- removeCoAgentStateRender: () => {
96
+ setRegisteredActions: () => "",
97
+ removeRegisteredAction: () => {
100
98
  },
101
99
  chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
102
100
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
@@ -116,7 +114,6 @@ var emptyCopilotContext = {
116
114
  addDocumentContext: () => returnAndThrowInDebug(""),
117
115
  removeDocumentContext: () => {
118
116
  },
119
- runtimeClient: {},
120
117
  copilotApiConfig: new class {
121
118
  get chatApiEndpoint() {
122
119
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
@@ -156,10 +153,15 @@ var emptyCopilotContext = {
156
153
  extensions: {},
157
154
  setExtensions: () => {
158
155
  },
159
- langGraphInterruptAction: null,
160
- setLangGraphInterruptAction: () => {
156
+ interruptActions: {},
157
+ setInterruptAction: () => {
158
+ },
159
+ removeInterruptAction: () => {
160
+ },
161
+ interruptEventQueue: {},
162
+ addInterruptEvent: () => {
161
163
  },
162
- removeLangGraphInterruptAction: () => {
164
+ removeInterruptEvent: () => {
163
165
  },
164
166
  onError: () => {
165
167
  },
@@ -184,186 +186,22 @@ function returnAndThrowInDebug(_value) {
184
186
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
185
187
  }
186
188
 
187
- // src/context/copilot-messages-context.tsx
188
- var import_react2 = __toESM(require("react"));
189
- var emptyCopilotContext2 = {
190
- messages: [],
191
- setMessages: () => [],
192
- // suggestions state
193
- suggestions: [],
194
- setSuggestions: () => []
195
- };
196
- var CopilotMessagesContext = import_react2.default.createContext(emptyCopilotContext2);
197
- function useCopilotMessagesContext() {
198
- const context = import_react2.default.useContext(CopilotMessagesContext);
199
- if (context === emptyCopilotContext2) {
200
- throw new Error(
201
- "A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`"
202
- );
203
- }
204
- return context;
205
- }
206
-
207
- // src/hooks/use-chat.ts
208
- var import_react6 = require("react");
209
- var import_react_dom = require("react-dom");
210
- var import_shared4 = require("@copilotkit/shared");
211
- var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
212
-
213
- // src/types/frontend-action.ts
214
- var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
215
- var import_shared = require("@copilotkit/shared");
216
- function processActionsForRuntimeRequest(actions) {
217
- const filteredActions = actions.filter(
218
- (action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
219
- ).map((action) => {
220
- let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
221
- if (action.disabled) {
222
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
223
- } else if (action.available === "disabled") {
224
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
225
- } else if (action.available === "remote") {
226
- available = import_runtime_client_gql.ActionInputAvailability.Remote;
227
- }
228
- return {
229
- name: action.name,
230
- description: action.description || "",
231
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
232
- available
233
- };
234
- });
235
- return filteredActions;
236
- }
237
-
238
- // src/hooks/use-copilot-runtime-client.ts
239
- var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
189
+ // src/components/error-boundary/error-utils.tsx
190
+ var import_react3 = require("react");
240
191
 
241
192
  // src/components/toast/toast-provider.tsx
242
- var import_react3 = require("react");
243
- var import_shared2 = require("@copilotkit/shared");
193
+ var import_react2 = require("react");
194
+ var import_shared = require("@copilotkit/shared");
244
195
  var import_jsx_runtime = require("react/jsx-runtime");
245
- var ToastContext = (0, import_react3.createContext)(void 0);
196
+ var ToastContext = (0, import_react2.createContext)(void 0);
246
197
  function useToast() {
247
- const context = (0, import_react3.useContext)(ToastContext);
198
+ const context = (0, import_react2.useContext)(ToastContext);
248
199
  if (!context) {
249
200
  throw new Error("useToast must be used within a ToastProvider");
250
201
  }
251
202
  return context;
252
203
  }
253
204
 
254
- // src/hooks/use-copilot-runtime-client.ts
255
- var import_react4 = require("react");
256
- var import_shared3 = require("@copilotkit/shared");
257
- var useCopilotRuntimeClient = (options) => {
258
- const { setBannerError } = useToast();
259
- const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
260
- const lastStructuredErrorRef = (0, import_react4.useRef)(null);
261
- const traceUIError = (error, originalError) => __async(void 0, null, function* () {
262
- try {
263
- const errorEvent = {
264
- type: "error",
265
- timestamp: Date.now(),
266
- context: {
267
- source: "ui",
268
- request: {
269
- operation: "runtimeClient",
270
- url: runtimeOptions.url,
271
- startTime: Date.now()
272
- },
273
- technical: {
274
- environment: "browser",
275
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
276
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
277
- }
278
- },
279
- error
280
- };
281
- yield onError(errorEvent);
282
- } catch (error2) {
283
- console.error("Error in onError handler:", error2);
284
- }
285
- });
286
- const runtimeClient = (0, import_react4.useMemo)(() => {
287
- return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
288
- handleGQLErrors: (error) => {
289
- var _a2;
290
- if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
291
- const graphQLErrors = error.graphQLErrors;
292
- const routeError = (gqlError) => {
293
- const extensions = gqlError.extensions;
294
- const visibility = extensions == null ? void 0 : extensions.visibility;
295
- if (visibility === import_shared3.ErrorVisibility.SILENT) {
296
- console.error("CopilotKit Silent Error:", gqlError.message);
297
- return;
298
- }
299
- const now = Date.now();
300
- const errorMessage = gqlError.message;
301
- if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
302
- return;
303
- }
304
- lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
305
- const ckError = createStructuredError(gqlError);
306
- if (ckError) {
307
- setBannerError(ckError);
308
- traceUIError(ckError, gqlError);
309
- } else {
310
- const fallbackError = new import_shared3.CopilotKitError({
311
- message: gqlError.message,
312
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
313
- });
314
- setBannerError(fallbackError);
315
- traceUIError(fallbackError, gqlError);
316
- }
317
- };
318
- graphQLErrors.forEach(routeError);
319
- } else {
320
- const fallbackError = new import_shared3.CopilotKitError({
321
- message: (error == null ? void 0 : error.message) || String(error),
322
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
323
- });
324
- setBannerError(fallbackError);
325
- traceUIError(fallbackError, error);
326
- }
327
- },
328
- handleGQLWarning: (message) => {
329
- console.warn(message);
330
- const warningError = new import_shared3.CopilotKitError({
331
- message,
332
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
333
- });
334
- setBannerError(warningError);
335
- }
336
- }));
337
- }, [runtimeOptions, setBannerError, onError]);
338
- return runtimeClient;
339
- };
340
- function createStructuredError(gqlError) {
341
- var _a, _b, _c;
342
- const extensions = gqlError.extensions;
343
- const originalError = extensions == null ? void 0 : extensions.originalError;
344
- const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
345
- const code = extensions == null ? void 0 : extensions.code;
346
- if (code) {
347
- return new import_shared3.CopilotKitError({ message, code });
348
- }
349
- if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
350
- return new import_shared3.CopilotKitApiDiscoveryError({ message });
351
- }
352
- if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
353
- return new import_shared3.CopilotKitRemoteEndpointDiscoveryError({ message });
354
- }
355
- if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
356
- return new import_shared3.CopilotKitAgentDiscoveryError({
357
- agentName: "",
358
- availableAgents: []
359
- });
360
- }
361
- return null;
362
- }
363
-
364
- // src/components/error-boundary/error-utils.tsx
365
- var import_react5 = require("react");
366
-
367
205
  // src/components/toast/exclamation-mark-icon.tsx
368
206
  var import_jsx_runtime2 = require("react/jsx-runtime");
369
207
  var ExclamationMarkIcon = ({
@@ -445,9 +283,9 @@ function ErrorToast({ errors }) {
445
283
  }
446
284
  function useErrorToast() {
447
285
  const { addToast } = useToast();
448
- return (0, import_react5.useCallback)(
449
- (error) => {
450
- const errorId = error.map((err) => {
286
+ return (0, import_react3.useCallback)(
287
+ (errors) => {
288
+ const errorId = errors.map((err) => {
451
289
  var _a, _b;
452
290
  const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
453
291
  const stack = err.stack || "";
@@ -457,7 +295,7 @@ function useErrorToast() {
457
295
  type: "error",
458
296
  id: errorId,
459
297
  // Toast libraries typically dedupe by id
460
- message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
298
+ message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors })
461
299
  });
462
300
  },
463
301
  [addToast]
@@ -465,7 +303,7 @@ function useErrorToast() {
465
303
  }
466
304
  function useAsyncCallback(callback, deps) {
467
305
  const addErrorToast = useErrorToast();
468
- return (0, import_react5.useCallback)((...args) => __async(this, null, function* () {
306
+ return (0, import_react3.useCallback)((...args) => __async(this, null, function* () {
469
307
  try {
470
308
  return yield callback(...args);
471
309
  } catch (error) {
@@ -476,1173 +314,880 @@ function useAsyncCallback(callback, deps) {
476
314
  }), deps);
477
315
  }
478
316
 
479
- // src/hooks/use-chat.ts
480
- function useChat(options) {
317
+ // src/hooks/use-copilot-chat_internal.ts
318
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
319
+
320
+ // src/context/coagent-state-renders-context.tsx
321
+ var import_react4 = require("react");
322
+ var import_jsx_runtime4 = require("react/jsx-runtime");
323
+ var CoAgentStateRendersContext = (0, import_react4.createContext)(
324
+ void 0
325
+ );
326
+ function useCoAgentStateRenders() {
327
+ const context = (0, import_react4.useContext)(CoAgentStateRendersContext);
328
+ if (!context) {
329
+ throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
330
+ }
331
+ return context;
332
+ }
333
+
334
+ // src/hooks/use-langgraph-interrupt-render.ts
335
+ var import_react5 = __toESM(require("react"));
336
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
337
+ var import_shared2 = require("@copilotkit/shared");
338
+ var InterruptRenderer = ({ event, result, render, resolve }) => {
339
+ return render({ event, result, resolve });
340
+ };
341
+ function useLangGraphInterruptRender(agent) {
481
342
  const {
482
- messages,
483
- setMessages,
484
- makeSystemMessageCallback,
485
- copilotConfig,
486
- setIsLoading,
487
- initialMessages,
488
- isLoading,
489
- actions,
490
- onFunctionCall,
491
- onCoAgentStateRender,
492
- setCoagentStatesWithRef,
493
- coagentStatesRef,
343
+ interruptActions,
494
344
  agentSession,
495
- setAgentSession,
496
345
  threadId,
497
- setThreadId,
498
- runId,
499
- setRunId,
500
- chatAbortControllerRef,
501
- agentLock,
502
- extensions,
503
- setExtensions,
504
- langGraphInterruptAction,
505
- setLangGraphInterruptAction,
506
- disableSystemMessage = false
507
- } = options;
508
- const runChatCompletionRef = (0, import_react6.useRef)();
509
- const addErrorToast = useErrorToast();
510
- const { setBannerError } = useToast();
511
- const { onError, showDevConsole, getAllContext } = useCopilotContext();
512
- const copilotReadableContext = getAllContext();
513
- const context = (0, import_react6.useMemo)(
514
- () => copilotReadableContext.map((contextItem) => {
515
- const [description, ...valueParts] = contextItem.value.split(":");
516
- return {
517
- description: description.trim(),
518
- value: valueParts.join(":").trim()
519
- };
520
- }),
521
- [copilotReadableContext]
522
- );
523
- const traceUIError = (error, originalError) => __async(this, null, function* () {
524
- try {
525
- const traceEvent = {
526
- type: "error",
527
- timestamp: Date.now(),
528
- context: {
529
- source: "ui",
530
- request: {
531
- operation: "useChatCompletion",
532
- url: copilotConfig.chatApiEndpoint,
533
- startTime: Date.now()
534
- },
535
- technical: {
536
- environment: "browser",
537
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
538
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
539
- }
540
- },
541
- error
542
- };
543
- yield onError(traceEvent);
544
- } catch (traceError) {
545
- console.error("Error in use-chat onError handler:", traceError);
546
- }
547
- });
548
- const agentSessionRef = (0, import_react6.useRef)(agentSession);
549
- agentSessionRef.current = agentSession;
550
- const runIdRef = (0, import_react6.useRef)(runId);
551
- runIdRef.current = runId;
552
- const extensionsRef = (0, import_react6.useRef)(extensions);
553
- extensionsRef.current = extensions;
554
- const publicApiKey = copilotConfig.publicApiKey;
555
- const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared4.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
556
- const runtimeClient = useCopilotRuntimeClient({
557
- url: copilotConfig.chatApiEndpoint,
558
- publicApiKey: copilotConfig.publicApiKey,
559
- headers,
560
- credentials: copilotConfig.credentials,
561
- showDevConsole,
562
- onError
563
- });
564
- const pendingAppendsRef = (0, import_react6.useRef)([]);
565
- const runChatCompletion = useAsyncCallback(
566
- (previousMessages) => __async(this, null, function* () {
567
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
568
- setIsLoading(true);
569
- const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
570
- if ((interruptEvent == null ? void 0 : interruptEvent.name) === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent && (interruptEvent == null ? void 0 : interruptEvent.value) && !(interruptEvent == null ? void 0 : interruptEvent.response) && agentSessionRef.current) {
571
- addErrorToast([
572
- new Error(
573
- "A message was sent while interrupt is active. This will cause failure on the agent side"
574
- )
575
- ]);
576
- }
577
- let newMessages = [
578
- new import_runtime_client_gql3.TextMessage({
579
- content: "",
580
- role: import_runtime_client_gql3.Role.Assistant
581
- })
582
- ];
583
- chatAbortControllerRef.current = new AbortController();
584
- setMessages([...previousMessages, ...newMessages]);
585
- const messagesWithContext = disableSystemMessage ? [...initialMessages || [], ...previousMessages] : [makeSystemMessageCallback(), ...initialMessages || [], ...previousMessages];
586
- const finalProperties = __spreadValues({}, copilotConfig.properties || {});
587
- let mcpServersToUse = null;
588
- if (copilotConfig.mcpServers && Array.isArray(copilotConfig.mcpServers) && copilotConfig.mcpServers.length > 0) {
589
- mcpServersToUse = copilotConfig.mcpServers;
590
- } else if (((_a = copilotConfig.properties) == null ? void 0 : _a.mcpServers) && Array.isArray(copilotConfig.properties.mcpServers) && copilotConfig.properties.mcpServers.length > 0) {
591
- mcpServersToUse = copilotConfig.properties.mcpServers;
592
- }
593
- if (mcpServersToUse) {
594
- finalProperties.mcpServers = mcpServersToUse;
595
- copilotConfig.mcpServers = mcpServersToUse;
596
- }
597
- const isAgentRun = agentSessionRef.current !== null;
598
- const stream = runtimeClient.asStream(
599
- runtimeClient.generateCopilotResponse({
600
- data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
601
- frontend: {
602
- actions: processActionsForRuntimeRequest(actions),
603
- url: window.location.href
604
- },
346
+ interruptEventQueue,
347
+ addInterruptEvent,
348
+ removeInterruptEvent
349
+ } = useCopilotContext();
350
+ (0, import_react5.useEffect)(() => {
351
+ if (!agent)
352
+ return;
353
+ const subscriber = {
354
+ onCustomEvent: ({ event }) => {
355
+ if (event.name === "on_interrupt") {
356
+ const eventData = {
357
+ name: import_runtime_client_gql.MetaEventName.LangGraphInterruptEvent,
358
+ type: event.type,
359
+ value: (0, import_shared2.parseJson)(event.value, event.value)
360
+ };
361
+ const eventId = (0, import_shared2.dataToUUID)(JSON.stringify(eventData), "interruptEvents");
362
+ addInterruptEvent({
363
+ eventId,
605
364
  threadId,
606
- runId: runIdRef.current,
607
- extensions: extensionsRef.current,
608
- metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event]),
609
- messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)((0, import_runtime_client_gql3.filterAgentStateMessages)(messagesWithContext))
610
- }, copilotConfig.cloud ? {
611
- cloud: __spreadValues({}, ((_d = (_c = (_b = copilotConfig.cloud.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic) == null ? void 0 : _d.enabled) ? {
612
- guardrails: {
613
- inputValidationRules: {
614
- allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
615
- denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
616
- }
617
- }
618
- } : {})
619
- } : {}), {
620
- metadata: {
621
- requestType: import_runtime_client_gql3.CopilotRequestType.Chat
622
- }
623
- }), agentSessionRef.current ? {
624
- agentSession: agentSessionRef.current
625
- } : {}), {
626
- agentStates: Object.values(coagentStatesRef.current).map((state) => {
627
- const stateObject = {
628
- agentName: state.name,
629
- state: JSON.stringify(state.state)
630
- };
631
- if (state.config !== void 0) {
632
- stateObject.config = JSON.stringify(state.config);
633
- }
634
- return stateObject;
635
- }),
636
- forwardedParameters: options.forwardedParameters || {},
637
- context
638
- }),
639
- properties: finalProperties,
640
- signal: (_e = chatAbortControllerRef.current) == null ? void 0 : _e.signal
641
- })
642
- );
643
- const guardrailsEnabled = ((_h = (_g = (_f = copilotConfig.cloud) == null ? void 0 : _f.guardrails) == null ? void 0 : _g.input) == null ? void 0 : _h.restrictToTopic.enabled) || false;
644
- const reader = stream.getReader();
645
- let executedCoAgentStateRenders = [];
646
- let followUp = void 0;
647
- let messages2 = [];
648
- let syncedMessages = [];
649
- let interruptMessages = [];
650
- try {
651
- while (true) {
652
- let done, value;
653
- try {
654
- const readResult = yield reader.read();
655
- done = readResult.done;
656
- value = readResult.value;
657
- } catch (readError) {
658
- break;
659
- }
660
- if (done) {
661
- if (chatAbortControllerRef.current.signal.aborted) {
662
- return [];
663
- }
664
- break;
665
- }
666
- if (!(value == null ? void 0 : value.generateCopilotResponse)) {
667
- continue;
668
- }
669
- runIdRef.current = value.generateCopilotResponse.runId || null;
670
- extensionsRef.current = import_runtime_client_gql3.CopilotRuntimeClient.removeGraphQLTypename(
671
- value.generateCopilotResponse.extensions || {}
672
- );
673
- setRunId(runIdRef.current);
674
- setExtensions(extensionsRef.current);
675
- let rawMessagesResponse = value.generateCopilotResponse.messages;
676
- const metaEvents = (_j = (_i = value.generateCopilotResponse) == null ? void 0 : _i.metaEvents) != null ? _j : [];
677
- (metaEvents != null ? metaEvents : []).forEach((ev) => {
678
- if (ev.name === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent) {
679
- let eventValue = (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev).value;
680
- eventValue = (0, import_shared4.parseJson)(eventValue, eventValue);
681
- setLangGraphInterruptAction(threadId, {
682
- event: __spreadProps(__spreadValues({}, (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev)), {
683
- value: eventValue
684
- })
685
- });
686
- }
687
- if (ev.name === import_runtime_client_gql3.MetaEventName.CopilotKitLangGraphInterruptEvent) {
688
- const data = ev.data;
689
- rawMessagesResponse = [...rawMessagesResponse, ...data.messages];
690
- interruptMessages = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
691
- // @ts-ignore
692
- (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(data.messages)
693
- );
694
- }
365
+ event: eventData
695
366
  });
696
- messages2 = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
697
- (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(rawMessagesResponse)
698
- );
699
- newMessages = [];
700
- if (((_k = value.generateCopilotResponse.status) == null ? void 0 : _k.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
701
- const guardrailsReason = ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || "";
702
- newMessages = [
703
- new import_runtime_client_gql3.TextMessage({
704
- role: import_runtime_client_gql3.MessageRole.Assistant,
705
- content: guardrailsReason
706
- })
707
- ];
708
- const guardrailsError = new import_shared4.CopilotKitError({
709
- message: `Guardrails validation failed: ${guardrailsReason}`,
710
- code: import_shared4.CopilotKitErrorCode.MISUSE
711
- });
712
- yield traceUIError(guardrailsError, {
713
- statusReason: value.generateCopilotResponse.status.reason,
714
- statusDetails: value.generateCopilotResponse.status.details
715
- });
716
- setMessages([...previousMessages, ...newMessages]);
717
- break;
718
- }
719
- if (((_m = value.generateCopilotResponse.status) == null ? void 0 : _m.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "UNKNOWN_ERROR") {
720
- const errorMessage = ((_n = value.generateCopilotResponse.status.details) == null ? void 0 : _n.description) || "An unknown error occurred";
721
- const statusDetails = value.generateCopilotResponse.status.details;
722
- const originalError = (statusDetails == null ? void 0 : statusDetails.originalError) || (statusDetails == null ? void 0 : statusDetails.error);
723
- const originalCode = (originalError == null ? void 0 : originalError.code) || ((_o = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _o.code);
724
- const originalSeverity = (originalError == null ? void 0 : originalError.severity) || ((_p = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _p.severity);
725
- const originalVisibility = (originalError == null ? void 0 : originalError.visibility) || ((_q = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _q.visibility);
726
- let errorCode = import_shared4.CopilotKitErrorCode.NETWORK_ERROR;
727
- if (originalCode && Object.values(import_shared4.CopilotKitErrorCode).includes(originalCode)) {
728
- errorCode = originalCode;
729
- }
730
- const structuredError = new import_shared4.CopilotKitError({
731
- message: errorMessage,
732
- code: errorCode,
733
- severity: originalSeverity,
734
- visibility: originalVisibility
735
- });
736
- setBannerError(structuredError);
737
- yield traceUIError(structuredError, {
738
- statusReason: value.generateCopilotResponse.status.reason,
739
- statusDetails: value.generateCopilotResponse.status.details,
740
- originalErrorCode: originalCode,
741
- preservedStructure: !!originalCode
742
- });
743
- setIsLoading(false);
744
- throw new Error(structuredError.message);
745
- } else if (messages2.length > 0) {
746
- newMessages = [...messages2];
747
- for (const message of messages2) {
748
- if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
749
- if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
750
- break;
751
- }
752
- yield onCoAgentStateRender({
753
- name: message.agentName,
754
- nodeName: message.nodeName,
755
- state: message.state
756
- });
757
- executedCoAgentStateRenders.push(message.id);
758
- }
759
- }
760
- const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
761
- if (lastAgentStateMessage) {
762
- if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
763
- syncedMessages = (0, import_runtime_client_gql3.loadMessagesFromJsonRepresentation)(
764
- lastAgentStateMessage.state.messages
765
- );
766
- }
767
- setCoagentStatesWithRef((prevAgentStates) => {
768
- var _a2;
769
- return __spreadProps(__spreadValues({}, prevAgentStates), {
770
- [lastAgentStateMessage.agentName]: {
771
- name: lastAgentStateMessage.agentName,
772
- state: lastAgentStateMessage.state,
773
- running: lastAgentStateMessage.running,
774
- active: lastAgentStateMessage.active,
775
- threadId: lastAgentStateMessage.threadId,
776
- nodeName: lastAgentStateMessage.nodeName,
777
- runId: lastAgentStateMessage.runId,
778
- // Preserve existing config from previous state
779
- config: (_a2 = prevAgentStates[lastAgentStateMessage.agentName]) == null ? void 0 : _a2.config
780
- }
781
- });
782
- });
783
- if (lastAgentStateMessage.running) {
784
- setAgentSession({
785
- threadId: lastAgentStateMessage.threadId,
786
- agentName: lastAgentStateMessage.agentName,
787
- nodeName: lastAgentStateMessage.nodeName
788
- });
789
- } else {
790
- if (agentLock) {
791
- setAgentSession({
792
- threadId: (0, import_shared4.randomId)(),
793
- agentName: agentLock,
794
- nodeName: void 0
795
- });
796
- } else {
797
- setAgentSession(null);
798
- }
799
- }
800
- }
801
- }
802
- if (newMessages.length > 0) {
803
- setMessages([...previousMessages, ...newMessages]);
804
- }
805
367
  }
806
- let finalMessages = constructFinalMessages(
807
- [...syncedMessages, ...interruptMessages],
808
- previousMessages,
809
- newMessages
810
- );
811
- let didExecuteAction = false;
812
- const executeActionFromMessage = (currentAction, actionMessage) => __async(this, null, function* () {
813
- var _a2;
814
- const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);
815
- followUp = (_a2 = currentAction == null ? void 0 : currentAction.followUp) != null ? _a2 : !isInterruptAction;
816
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
817
- currentAction._setActivatingMessageId(actionMessage.id);
818
- }
819
- const resultMessage = yield executeAction({
820
- onFunctionCall,
821
- message: actionMessage,
822
- chatAbortControllerRef,
823
- onError: (error) => {
824
- addErrorToast([error]);
825
- console.error(`Failed to execute action ${actionMessage.name}: ${error}`);
826
- },
827
- setMessages,
828
- getFinalMessages: () => finalMessages,
829
- isRenderAndWait: (currentAction == null ? void 0 : currentAction._isRenderAndWait) || false
830
- });
831
- didExecuteAction = true;
832
- const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);
833
- finalMessages.splice(messageIndex + 1, 0, resultMessage);
834
- if (currentAction == null ? void 0 : currentAction._isRenderAndWait) {
835
- const messagesForImmediateUpdate = [...finalMessages];
836
- (0, import_react_dom.flushSync)(() => {
837
- setMessages(messagesForImmediateUpdate);
838
- });
839
- }
840
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
841
- currentAction._setActivatingMessageId(null);
842
- }
843
- return resultMessage;
844
- });
845
- if (onFunctionCall) {
846
- const lastMessages = [];
847
- for (let i = finalMessages.length - 1; i >= 0; i--) {
848
- const message = finalMessages[i];
849
- if ((message.isActionExecutionMessage() || message.isResultMessage()) && message.status.code !== import_runtime_client_gql3.MessageStatusCode.Pending) {
850
- lastMessages.unshift(message);
851
- } else if (!message.isAgentStateMessage()) {
852
- break;
853
- }
854
- }
855
- for (const message of lastMessages) {
856
- setMessages(finalMessages);
857
- const action = actions.find(
858
- (action2) => action2.name === message.name
859
- );
860
- if (action && action.available === "frontend") {
861
- continue;
862
- }
863
- const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
864
- if (action && message.isActionExecutionMessage()) {
865
- const isRenderAndWaitAction = (action == null ? void 0 : action._isRenderAndWait) || false;
866
- const alreadyProcessed = isRenderAndWaitAction && finalMessages.some(
867
- (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
868
- );
869
- if (alreadyProcessed) {
870
- } else {
871
- const resultMessage = yield executeActionFromMessage(
872
- action,
873
- message
874
- );
875
- const pairedFeAction = getPairedFeAction(actions, resultMessage);
876
- if (pairedFeAction) {
877
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
878
- name: pairedFeAction.name,
879
- arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
880
- status: message.status,
881
- createdAt: message.createdAt,
882
- parentMessageId: message.parentMessageId
883
- });
884
- yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
885
- }
886
- }
887
- } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
888
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
889
- name: currentResultMessagePairedFeAction.name,
890
- arguments: (0, import_shared4.parseJson)(message.result, message.result),
891
- status: message.status,
892
- createdAt: message.createdAt
893
- });
894
- finalMessages.push(newExecutionMessage);
895
- yield executeActionFromMessage(
896
- currentResultMessagePairedFeAction,
897
- newExecutionMessage
898
- );
899
- }
900
- }
901
- setMessages(finalMessages);
902
- }
903
- if (followUp !== false && (didExecuteAction || // the last message is a server side result
904
- !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
905
- !((_r = chatAbortControllerRef.current) == null ? void 0 : _r.signal.aborted)) {
906
- yield new Promise((resolve) => setTimeout(resolve, 10));
907
- return yield runChatCompletionRef.current(finalMessages);
908
- } else if ((_s = chatAbortControllerRef.current) == null ? void 0 : _s.signal.aborted) {
909
- const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
910
- if (message.isActionExecutionMessage()) {
911
- return finalMessages.find(
912
- (msg, resultIndex) => msg.isResultMessage() && msg.actionExecutionId === message.id && resultIndex === actionExecutionIndex + 1
913
- );
914
- }
915
- return true;
916
- });
917
- const repairedMessageIds = repairedMessages.map((message) => message.id);
918
- setMessages(repairedMessages);
919
- if ((_t = agentSessionRef.current) == null ? void 0 : _t.nodeName) {
920
- setAgentSession({
921
- threadId: agentSessionRef.current.threadId,
922
- agentName: agentSessionRef.current.agentName,
923
- nodeName: "__end__"
924
- });
925
- }
926
- return newMessages.filter((message) => repairedMessageIds.includes(message.id));
927
- } else {
928
- return newMessages.slice();
929
- }
930
- } finally {
931
- setIsLoading(false);
932
368
  }
933
- }),
934
- [
935
- messages,
936
- setMessages,
937
- makeSystemMessageCallback,
938
- copilotConfig,
939
- setIsLoading,
940
- initialMessages,
941
- isLoading,
942
- actions,
943
- onFunctionCall,
944
- onCoAgentStateRender,
945
- setCoagentStatesWithRef,
946
- coagentStatesRef,
947
- agentSession,
948
- setAgentSession,
949
- disableSystemMessage,
950
- context
951
- ]
952
- );
953
- runChatCompletionRef.current = runChatCompletion;
954
- const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
955
- (messages2) => __async(this, null, function* () {
956
- yield runChatCompletionRef.current(messages2);
957
- }),
958
- [messages]
959
- );
960
- (0, import_react6.useEffect)(() => {
961
- if (!isLoading && pendingAppendsRef.current.length > 0) {
962
- const pending = pendingAppendsRef.current.splice(0);
963
- const followUp = pending.some((p) => p.followUp);
964
- const newMessages = [...messages, ...pending.map((p) => p.message)];
965
- setMessages(newMessages);
966
- if (followUp) {
967
- runChatCompletionAndHandleFunctionCall(newMessages);
968
- }
969
- }
970
- }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
971
- const composeAndFlushMetaEventsInput = (0, import_react6.useCallback)(
972
- (metaEvents) => {
973
- return metaEvents.reduce((acc, event) => {
974
- if (!event)
975
- return acc;
976
- switch (event.name) {
977
- case import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent:
978
- if (event.response) {
979
- setLangGraphInterruptAction(threadId, null);
980
- const value = event.value;
981
- return [
982
- ...acc,
983
- {
984
- name: event.name,
985
- value: typeof value === "string" ? value : JSON.stringify(value),
986
- response: typeof event.response === "string" ? event.response : JSON.stringify(event.response)
987
- }
988
- ];
989
- }
990
- return acc;
991
- default:
992
- return acc;
369
+ };
370
+ const { unsubscribe } = agent.subscribe(subscriber);
371
+ return () => {
372
+ unsubscribe();
373
+ };
374
+ }, [agent, threadId]);
375
+ const handleResolve = (0, import_react5.useCallback)(
376
+ (eventId, response) => {
377
+ agent == null ? void 0 : agent.runAgent({
378
+ forwardedProps: {
379
+ command: {
380
+ resume: response
381
+ }
993
382
  }
994
- }, []);
383
+ });
384
+ removeInterruptEvent(threadId, eventId);
995
385
  },
996
- [setLangGraphInterruptAction]
386
+ // eslint-disable-next-line react-hooks/exhaustive-deps
387
+ [agent, threadId]
997
388
  );
998
- const append = useAsyncCallback(
999
- (message, options2) => __async(this, null, function* () {
1000
- var _a;
1001
- const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
1002
- if (isLoading) {
1003
- pendingAppendsRef.current.push({ message, followUp });
1004
- return;
1005
- }
1006
- const newMessages = [...messages, message];
1007
- setMessages(newMessages);
1008
- if (followUp) {
1009
- return runChatCompletionAndHandleFunctionCall(newMessages);
1010
- }
1011
- }),
1012
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1013
- );
1014
- const reload = useAsyncCallback(
1015
- (reloadMessageId) => __async(this, null, function* () {
1016
- if (isLoading || messages.length === 0) {
1017
- return;
1018
- }
1019
- const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
1020
- if (reloadMessageIndex === -1) {
1021
- console.warn(`Message with id ${reloadMessageId} not found`);
1022
- return;
1023
- }
1024
- const reloadMessageRole = messages[reloadMessageIndex].role;
1025
- if (reloadMessageRole !== import_runtime_client_gql3.MessageRole.Assistant) {
1026
- console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
1027
- return;
1028
- }
1029
- let historyCutoff = [messages[0]];
1030
- if (messages.length > 2 && reloadMessageIndex !== 0) {
1031
- const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
1032
- (msg) => (
1033
- // @ts-expect-error -- message has role
1034
- msg.role === import_runtime_client_gql3.MessageRole.User
1035
- )
1036
- );
1037
- const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1038
- (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1039
- );
1040
- historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1041
- } else if (messages.length > 2 && reloadMessageIndex === 0) {
1042
- historyCutoff = [messages[0], messages[1]];
1043
- }
1044
- setMessages(historyCutoff);
1045
- return runChatCompletionAndHandleFunctionCall(historyCutoff);
1046
- }),
1047
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1048
- );
1049
- const stop = () => {
1050
- var _a;
1051
- (_a = chatAbortControllerRef.current) == null ? void 0 : _a.abort("Stop was called");
1052
- };
1053
- return {
1054
- append,
1055
- reload,
1056
- stop,
1057
- runChatCompletion: () => runChatCompletionRef.current(messages)
1058
- };
1059
- }
1060
- function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
1061
- const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
1062
- if (syncedMessages.length > 0) {
1063
- const messagesWithAgentState = [...previousMessages, ...newMessages];
1064
- let previousMessageId = void 0;
1065
- for (const message of messagesWithAgentState) {
1066
- if (message.isAgentStateMessage()) {
1067
- const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
1068
- if (index !== -1) {
1069
- finalMessages.splice(index + 1, 0, message);
1070
- }
1071
- }
1072
- previousMessageId = message.id;
1073
- }
1074
- }
1075
- return finalMessages;
1076
- }
1077
- function executeAction(_0) {
1078
- return __async(this, arguments, function* ({
1079
- onFunctionCall,
1080
- message,
1081
- chatAbortControllerRef,
1082
- onError,
1083
- setMessages,
1084
- getFinalMessages,
1085
- isRenderAndWait
1086
- }) {
1087
- let result;
1088
- let error = null;
1089
- const currentMessagesForHandler = getFinalMessages();
1090
- const handlerReturnedPromise = onFunctionCall({
1091
- messages: currentMessagesForHandler,
1092
- name: message.name,
1093
- args: message.arguments
389
+ return (0, import_react5.useMemo)(() => {
390
+ const eventQueue = interruptEventQueue[threadId] || [];
391
+ const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);
392
+ if (!currentQueuedEvent)
393
+ return null;
394
+ const allActions = Object.values(interruptActions);
395
+ const matchingAction = allActions.find((action) => {
396
+ if (!action.enabled)
397
+ return true;
398
+ return action.enabled({
399
+ eventValue: currentQueuedEvent.event.value,
400
+ agentMetadata: agentSession
401
+ });
1094
402
  });
1095
- if (isRenderAndWait) {
1096
- const currentMessagesForRender = getFinalMessages();
1097
- (0, import_react_dom.flushSync)(() => {
1098
- setMessages([...currentMessagesForRender]);
403
+ if (!matchingAction)
404
+ return null;
405
+ const { render, handler } = matchingAction;
406
+ const resolveInterrupt = (response) => {
407
+ handleResolve(currentQueuedEvent.eventId, response);
408
+ };
409
+ let result = null;
410
+ if (handler) {
411
+ result = handler({
412
+ event: currentQueuedEvent.event,
413
+ resolve: resolveInterrupt
1099
414
  });
1100
415
  }
1101
- try {
1102
- result = yield Promise.race([
1103
- handlerReturnedPromise,
1104
- // Await the promise returned by the handler
1105
- new Promise(
1106
- (resolve) => {
1107
- var _a;
1108
- return (_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.addEventListener(
1109
- "abort",
1110
- () => resolve("Operation was aborted by the user")
1111
- );
1112
- }
1113
- ),
1114
- // if the user stopped generation, we also abort consecutive actions
1115
- new Promise((resolve) => {
1116
- var _a;
1117
- if ((_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.aborted) {
1118
- resolve("Operation was aborted by the user");
1119
- }
1120
- })
1121
- ]);
1122
- } catch (e) {
1123
- onError(e);
1124
- }
1125
- return new import_runtime_client_gql3.ResultMessage({
1126
- id: "result-" + message.id,
1127
- result: import_runtime_client_gql3.ResultMessage.encodeResult(
1128
- error ? {
1129
- content: result,
1130
- error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
1131
- } : result
1132
- ),
1133
- actionExecutionId: message.id,
1134
- actionName: message.name
416
+ if (!render)
417
+ return null;
418
+ return import_react5.default.createElement(InterruptRenderer, {
419
+ event: currentQueuedEvent.event,
420
+ result,
421
+ render,
422
+ resolve: resolveInterrupt
1135
423
  });
1136
- });
424
+ }, [interruptActions, interruptEventQueue, threadId, agentSession, handleResolve]);
1137
425
  }
1138
- function getPairedFeAction(actions, message) {
1139
- let actionName = null;
1140
- if (message.isActionExecutionMessage()) {
1141
- actionName = message.name;
1142
- } else if (message.isResultMessage()) {
1143
- actionName = message.actionName;
1144
- }
1145
- return actions.find(
1146
- (action) => action.name === actionName && action.available === "frontend" || action.pairedAction === actionName
426
+
427
+ // src/hooks/use-copilot-chat_internal.ts
428
+ var import_react13 = require("@copilotkitnext/react");
429
+
430
+ // src/hooks/use-lazy-tool-renderer.tsx
431
+ var import_react6 = require("@copilotkitnext/react");
432
+ var import_react7 = require("react");
433
+ function useLazyToolRenderer() {
434
+ const renderToolCall = (0, import_react6.useRenderToolCall)();
435
+ return (0, import_react7.useCallback)(
436
+ (message, messages) => {
437
+ var _a;
438
+ if (!((_a = message == null ? void 0 : message.toolCalls) == null ? void 0 : _a.length))
439
+ return null;
440
+ const toolCall = message.toolCalls[0];
441
+ if (!toolCall)
442
+ return null;
443
+ const toolMessage = messages == null ? void 0 : messages.find(
444
+ (m) => m.role === "tool" && m.toolCallId === toolCall.id
445
+ );
446
+ return () => renderToolCall({
447
+ toolCall,
448
+ toolMessage
449
+ });
450
+ },
451
+ [renderToolCall]
1147
452
  );
1148
453
  }
1149
454
 
1150
- // src/components/copilot-provider/copilotkit.tsx
1151
- var import_react7 = require("react");
1152
- var import_react_dom2 = require("react-dom");
1153
- var import_shared7 = require("@copilotkit/shared");
455
+ // src/hooks/use-configure-chat-suggestions.tsx
456
+ var import_react8 = require("@copilotkitnext/react");
457
+ var import_react9 = require("react");
458
+ function useConfigureChatSuggestions(config, dependencies = []) {
459
+ const { agentSession } = useCopilotContext();
460
+ const { copilotkit } = (0, import_react8.useCopilotKit)();
461
+ const available = config.available === "enabled" ? "always" : config.available;
462
+ const finalSuggestionConfig = __spreadProps(__spreadValues({}, config), {
463
+ available,
464
+ consumerAgentId: agentSession == null ? void 0 : agentSession.agentName
465
+ // Use chatConfig.agentId here
466
+ });
467
+ (0, import_react8.useConfigureSuggestions)(finalSuggestionConfig, { deps: dependencies });
468
+ const result = (0, import_react8.useSuggestions)({ agentId: agentSession == null ? void 0 : agentSession.agentName });
469
+ (0, import_react9.useEffect)(() => {
470
+ if (finalSuggestionConfig.available === "disabled")
471
+ return;
472
+ const subscription = copilotkit.subscribe({
473
+ onAgentsChanged: () => {
474
+ const agent = copilotkit.getAgent(agentSession == null ? void 0 : agentSession.agentName);
475
+ if (agent && !agent.isRunning && !result.suggestions.length) {
476
+ copilotkit.reloadSuggestions(agentSession == null ? void 0 : agentSession.agentName);
477
+ }
478
+ }
479
+ });
480
+ return () => {
481
+ subscription.unsubscribe();
482
+ };
483
+ }, []);
484
+ return result;
485
+ }
486
+
487
+ // ../../node_modules/.pnpm/@ag-ui+core@0.0.42-alpha.1/node_modules/@ag-ui/core/dist/index.mjs
488
+ var import_zod = require("zod");
489
+ var import_zod2 = require("zod");
490
+ var FunctionCallSchema = import_zod.z.object({
491
+ name: import_zod.z.string(),
492
+ arguments: import_zod.z.string()
493
+ });
494
+ var ToolCallSchema = import_zod.z.object({
495
+ id: import_zod.z.string(),
496
+ type: import_zod.z.literal("function"),
497
+ function: FunctionCallSchema
498
+ });
499
+ var BaseMessageSchema = import_zod.z.object({
500
+ id: import_zod.z.string(),
501
+ role: import_zod.z.string(),
502
+ content: import_zod.z.string().optional(),
503
+ name: import_zod.z.string().optional()
504
+ });
505
+ var TextInputContentSchema = import_zod.z.object({
506
+ type: import_zod.z.literal("text"),
507
+ text: import_zod.z.string()
508
+ });
509
+ var BinaryInputContentObjectSchema = import_zod.z.object({
510
+ type: import_zod.z.literal("binary"),
511
+ mimeType: import_zod.z.string(),
512
+ id: import_zod.z.string().optional(),
513
+ url: import_zod.z.string().optional(),
514
+ data: import_zod.z.string().optional(),
515
+ filename: import_zod.z.string().optional()
516
+ });
517
+ var ensureBinaryPayload = (value, ctx) => {
518
+ if (!value.id && !value.url && !value.data) {
519
+ ctx.addIssue({
520
+ code: import_zod.z.ZodIssueCode.custom,
521
+ message: "BinaryInputContent requires at least one of id, url, or data.",
522
+ path: ["id"]
523
+ });
524
+ }
525
+ };
526
+ var BinaryInputContentSchema = BinaryInputContentObjectSchema.superRefine((value, ctx) => {
527
+ ensureBinaryPayload(value, ctx);
528
+ });
529
+ var InputContentBaseSchema = import_zod.z.discriminatedUnion("type", [
530
+ TextInputContentSchema,
531
+ BinaryInputContentObjectSchema
532
+ ]);
533
+ var InputContentSchema = InputContentBaseSchema.superRefine((value, ctx) => {
534
+ if (value.type === "binary") {
535
+ ensureBinaryPayload(value, ctx);
536
+ }
537
+ });
538
+ var DeveloperMessageSchema = BaseMessageSchema.extend({
539
+ role: import_zod.z.literal("developer"),
540
+ content: import_zod.z.string()
541
+ });
542
+ var SystemMessageSchema = BaseMessageSchema.extend({
543
+ role: import_zod.z.literal("system"),
544
+ content: import_zod.z.string()
545
+ });
546
+ var AssistantMessageSchema = BaseMessageSchema.extend({
547
+ role: import_zod.z.literal("assistant"),
548
+ content: import_zod.z.string().optional(),
549
+ toolCalls: import_zod.z.array(ToolCallSchema).optional()
550
+ });
551
+ var UserMessageSchema = BaseMessageSchema.extend({
552
+ role: import_zod.z.literal("user"),
553
+ content: import_zod.z.union([import_zod.z.string(), import_zod.z.array(InputContentSchema)])
554
+ });
555
+ var ToolMessageSchema = import_zod.z.object({
556
+ id: import_zod.z.string(),
557
+ content: import_zod.z.string(),
558
+ role: import_zod.z.literal("tool"),
559
+ toolCallId: import_zod.z.string(),
560
+ error: import_zod.z.string().optional()
561
+ });
562
+ var ActivityMessageSchema = import_zod.z.object({
563
+ id: import_zod.z.string(),
564
+ role: import_zod.z.literal("activity"),
565
+ activityType: import_zod.z.string(),
566
+ content: import_zod.z.record(import_zod.z.any())
567
+ });
568
+ var MessageSchema = import_zod.z.discriminatedUnion("role", [
569
+ DeveloperMessageSchema,
570
+ SystemMessageSchema,
571
+ AssistantMessageSchema,
572
+ UserMessageSchema,
573
+ ToolMessageSchema,
574
+ ActivityMessageSchema
575
+ ]);
576
+ var RoleSchema = import_zod.z.union([
577
+ import_zod.z.literal("developer"),
578
+ import_zod.z.literal("system"),
579
+ import_zod.z.literal("assistant"),
580
+ import_zod.z.literal("user"),
581
+ import_zod.z.literal("tool"),
582
+ import_zod.z.literal("activity")
583
+ ]);
584
+ var ContextSchema = import_zod.z.object({
585
+ description: import_zod.z.string(),
586
+ value: import_zod.z.string()
587
+ });
588
+ var ToolSchema = import_zod.z.object({
589
+ name: import_zod.z.string(),
590
+ description: import_zod.z.string(),
591
+ parameters: import_zod.z.any()
592
+ // JSON Schema for the tool parameters
593
+ });
594
+ var RunAgentInputSchema = import_zod.z.object({
595
+ threadId: import_zod.z.string(),
596
+ runId: import_zod.z.string(),
597
+ parentRunId: import_zod.z.string().optional(),
598
+ state: import_zod.z.any(),
599
+ messages: import_zod.z.array(MessageSchema),
600
+ tools: import_zod.z.array(ToolSchema),
601
+ context: import_zod.z.array(ContextSchema),
602
+ forwardedProps: import_zod.z.any()
603
+ });
604
+ var StateSchema = import_zod.z.any();
605
+ var AGUIError = class extends Error {
606
+ constructor(message) {
607
+ super(message);
608
+ }
609
+ };
610
+ var AGUIConnectNotImplementedError = class extends AGUIError {
611
+ constructor() {
612
+ super("Connect not implemented. This method is not supported by the current agent.");
613
+ }
614
+ };
615
+ var TextMessageRoleSchema = import_zod2.z.union([
616
+ import_zod2.z.literal("developer"),
617
+ import_zod2.z.literal("system"),
618
+ import_zod2.z.literal("assistant"),
619
+ import_zod2.z.literal("user")
620
+ ]);
621
+ var EventType = /* @__PURE__ */ ((EventType2) => {
622
+ EventType2["TEXT_MESSAGE_START"] = "TEXT_MESSAGE_START";
623
+ EventType2["TEXT_MESSAGE_CONTENT"] = "TEXT_MESSAGE_CONTENT";
624
+ EventType2["TEXT_MESSAGE_END"] = "TEXT_MESSAGE_END";
625
+ EventType2["TEXT_MESSAGE_CHUNK"] = "TEXT_MESSAGE_CHUNK";
626
+ EventType2["THINKING_TEXT_MESSAGE_START"] = "THINKING_TEXT_MESSAGE_START";
627
+ EventType2["THINKING_TEXT_MESSAGE_CONTENT"] = "THINKING_TEXT_MESSAGE_CONTENT";
628
+ EventType2["THINKING_TEXT_MESSAGE_END"] = "THINKING_TEXT_MESSAGE_END";
629
+ EventType2["TOOL_CALL_START"] = "TOOL_CALL_START";
630
+ EventType2["TOOL_CALL_ARGS"] = "TOOL_CALL_ARGS";
631
+ EventType2["TOOL_CALL_END"] = "TOOL_CALL_END";
632
+ EventType2["TOOL_CALL_CHUNK"] = "TOOL_CALL_CHUNK";
633
+ EventType2["TOOL_CALL_RESULT"] = "TOOL_CALL_RESULT";
634
+ EventType2["THINKING_START"] = "THINKING_START";
635
+ EventType2["THINKING_END"] = "THINKING_END";
636
+ EventType2["STATE_SNAPSHOT"] = "STATE_SNAPSHOT";
637
+ EventType2["STATE_DELTA"] = "STATE_DELTA";
638
+ EventType2["MESSAGES_SNAPSHOT"] = "MESSAGES_SNAPSHOT";
639
+ EventType2["ACTIVITY_SNAPSHOT"] = "ACTIVITY_SNAPSHOT";
640
+ EventType2["ACTIVITY_DELTA"] = "ACTIVITY_DELTA";
641
+ EventType2["RAW"] = "RAW";
642
+ EventType2["CUSTOM"] = "CUSTOM";
643
+ EventType2["RUN_STARTED"] = "RUN_STARTED";
644
+ EventType2["RUN_FINISHED"] = "RUN_FINISHED";
645
+ EventType2["RUN_ERROR"] = "RUN_ERROR";
646
+ EventType2["STEP_STARTED"] = "STEP_STARTED";
647
+ EventType2["STEP_FINISHED"] = "STEP_FINISHED";
648
+ return EventType2;
649
+ })(EventType || {});
650
+ var BaseEventSchema = import_zod2.z.object({
651
+ type: import_zod2.z.nativeEnum(EventType),
652
+ timestamp: import_zod2.z.number().optional(),
653
+ rawEvent: import_zod2.z.any().optional()
654
+ });
655
+ var TextMessageStartEventSchema = BaseEventSchema.extend({
656
+ type: import_zod2.z.literal(
657
+ "TEXT_MESSAGE_START"
658
+ /* TEXT_MESSAGE_START */
659
+ ),
660
+ messageId: import_zod2.z.string(),
661
+ role: TextMessageRoleSchema.default("assistant")
662
+ });
663
+ var TextMessageContentEventSchema = BaseEventSchema.extend({
664
+ type: import_zod2.z.literal(
665
+ "TEXT_MESSAGE_CONTENT"
666
+ /* TEXT_MESSAGE_CONTENT */
667
+ ),
668
+ messageId: import_zod2.z.string(),
669
+ delta: import_zod2.z.string().refine((s) => s.length > 0, "Delta must not be an empty string")
670
+ });
671
+ var TextMessageEndEventSchema = BaseEventSchema.extend({
672
+ type: import_zod2.z.literal(
673
+ "TEXT_MESSAGE_END"
674
+ /* TEXT_MESSAGE_END */
675
+ ),
676
+ messageId: import_zod2.z.string()
677
+ });
678
+ var TextMessageChunkEventSchema = BaseEventSchema.extend({
679
+ type: import_zod2.z.literal(
680
+ "TEXT_MESSAGE_CHUNK"
681
+ /* TEXT_MESSAGE_CHUNK */
682
+ ),
683
+ messageId: import_zod2.z.string().optional(),
684
+ role: TextMessageRoleSchema.optional(),
685
+ delta: import_zod2.z.string().optional()
686
+ });
687
+ var ThinkingTextMessageStartEventSchema = BaseEventSchema.extend({
688
+ type: import_zod2.z.literal(
689
+ "THINKING_TEXT_MESSAGE_START"
690
+ /* THINKING_TEXT_MESSAGE_START */
691
+ )
692
+ });
693
+ var ThinkingTextMessageContentEventSchema = TextMessageContentEventSchema.omit({
694
+ messageId: true,
695
+ type: true
696
+ }).extend({
697
+ type: import_zod2.z.literal(
698
+ "THINKING_TEXT_MESSAGE_CONTENT"
699
+ /* THINKING_TEXT_MESSAGE_CONTENT */
700
+ )
701
+ });
702
+ var ThinkingTextMessageEndEventSchema = BaseEventSchema.extend({
703
+ type: import_zod2.z.literal(
704
+ "THINKING_TEXT_MESSAGE_END"
705
+ /* THINKING_TEXT_MESSAGE_END */
706
+ )
707
+ });
708
+ var ToolCallStartEventSchema = BaseEventSchema.extend({
709
+ type: import_zod2.z.literal(
710
+ "TOOL_CALL_START"
711
+ /* TOOL_CALL_START */
712
+ ),
713
+ toolCallId: import_zod2.z.string(),
714
+ toolCallName: import_zod2.z.string(),
715
+ parentMessageId: import_zod2.z.string().optional()
716
+ });
717
+ var ToolCallArgsEventSchema = BaseEventSchema.extend({
718
+ type: import_zod2.z.literal(
719
+ "TOOL_CALL_ARGS"
720
+ /* TOOL_CALL_ARGS */
721
+ ),
722
+ toolCallId: import_zod2.z.string(),
723
+ delta: import_zod2.z.string()
724
+ });
725
+ var ToolCallEndEventSchema = BaseEventSchema.extend({
726
+ type: import_zod2.z.literal(
727
+ "TOOL_CALL_END"
728
+ /* TOOL_CALL_END */
729
+ ),
730
+ toolCallId: import_zod2.z.string()
731
+ });
732
+ var ToolCallResultEventSchema = BaseEventSchema.extend({
733
+ messageId: import_zod2.z.string(),
734
+ type: import_zod2.z.literal(
735
+ "TOOL_CALL_RESULT"
736
+ /* TOOL_CALL_RESULT */
737
+ ),
738
+ toolCallId: import_zod2.z.string(),
739
+ content: import_zod2.z.string(),
740
+ role: import_zod2.z.literal("tool").optional()
741
+ });
742
+ var ToolCallChunkEventSchema = BaseEventSchema.extend({
743
+ type: import_zod2.z.literal(
744
+ "TOOL_CALL_CHUNK"
745
+ /* TOOL_CALL_CHUNK */
746
+ ),
747
+ toolCallId: import_zod2.z.string().optional(),
748
+ toolCallName: import_zod2.z.string().optional(),
749
+ parentMessageId: import_zod2.z.string().optional(),
750
+ delta: import_zod2.z.string().optional()
751
+ });
752
+ var ThinkingStartEventSchema = BaseEventSchema.extend({
753
+ type: import_zod2.z.literal(
754
+ "THINKING_START"
755
+ /* THINKING_START */
756
+ ),
757
+ title: import_zod2.z.string().optional()
758
+ });
759
+ var ThinkingEndEventSchema = BaseEventSchema.extend({
760
+ type: import_zod2.z.literal(
761
+ "THINKING_END"
762
+ /* THINKING_END */
763
+ )
764
+ });
765
+ var StateSnapshotEventSchema = BaseEventSchema.extend({
766
+ type: import_zod2.z.literal(
767
+ "STATE_SNAPSHOT"
768
+ /* STATE_SNAPSHOT */
769
+ ),
770
+ snapshot: StateSchema
771
+ });
772
+ var StateDeltaEventSchema = BaseEventSchema.extend({
773
+ type: import_zod2.z.literal(
774
+ "STATE_DELTA"
775
+ /* STATE_DELTA */
776
+ ),
777
+ delta: import_zod2.z.array(import_zod2.z.any())
778
+ // JSON Patch (RFC 6902)
779
+ });
780
+ var MessagesSnapshotEventSchema = BaseEventSchema.extend({
781
+ type: import_zod2.z.literal(
782
+ "MESSAGES_SNAPSHOT"
783
+ /* MESSAGES_SNAPSHOT */
784
+ ),
785
+ messages: import_zod2.z.array(MessageSchema)
786
+ });
787
+ var ActivitySnapshotEventSchema = BaseEventSchema.extend({
788
+ type: import_zod2.z.literal(
789
+ "ACTIVITY_SNAPSHOT"
790
+ /* ACTIVITY_SNAPSHOT */
791
+ ),
792
+ messageId: import_zod2.z.string(),
793
+ activityType: import_zod2.z.string(),
794
+ content: import_zod2.z.record(import_zod2.z.any()),
795
+ replace: import_zod2.z.boolean().optional().default(true)
796
+ });
797
+ var ActivityDeltaEventSchema = BaseEventSchema.extend({
798
+ type: import_zod2.z.literal(
799
+ "ACTIVITY_DELTA"
800
+ /* ACTIVITY_DELTA */
801
+ ),
802
+ messageId: import_zod2.z.string(),
803
+ activityType: import_zod2.z.string(),
804
+ patch: import_zod2.z.array(import_zod2.z.any())
805
+ });
806
+ var RawEventSchema = BaseEventSchema.extend({
807
+ type: import_zod2.z.literal(
808
+ "RAW"
809
+ /* RAW */
810
+ ),
811
+ event: import_zod2.z.any(),
812
+ source: import_zod2.z.string().optional()
813
+ });
814
+ var CustomEventSchema = BaseEventSchema.extend({
815
+ type: import_zod2.z.literal(
816
+ "CUSTOM"
817
+ /* CUSTOM */
818
+ ),
819
+ name: import_zod2.z.string(),
820
+ value: import_zod2.z.any()
821
+ });
822
+ var RunStartedEventSchema = BaseEventSchema.extend({
823
+ type: import_zod2.z.literal(
824
+ "RUN_STARTED"
825
+ /* RUN_STARTED */
826
+ ),
827
+ threadId: import_zod2.z.string(),
828
+ runId: import_zod2.z.string(),
829
+ parentRunId: import_zod2.z.string().optional(),
830
+ input: RunAgentInputSchema.optional()
831
+ });
832
+ var RunFinishedEventSchema = BaseEventSchema.extend({
833
+ type: import_zod2.z.literal(
834
+ "RUN_FINISHED"
835
+ /* RUN_FINISHED */
836
+ ),
837
+ threadId: import_zod2.z.string(),
838
+ runId: import_zod2.z.string(),
839
+ result: import_zod2.z.any().optional()
840
+ });
841
+ var RunErrorEventSchema = BaseEventSchema.extend({
842
+ type: import_zod2.z.literal(
843
+ "RUN_ERROR"
844
+ /* RUN_ERROR */
845
+ ),
846
+ message: import_zod2.z.string(),
847
+ code: import_zod2.z.string().optional()
848
+ });
849
+ var StepStartedEventSchema = BaseEventSchema.extend({
850
+ type: import_zod2.z.literal(
851
+ "STEP_STARTED"
852
+ /* STEP_STARTED */
853
+ ),
854
+ stepName: import_zod2.z.string()
855
+ });
856
+ var StepFinishedEventSchema = BaseEventSchema.extend({
857
+ type: import_zod2.z.literal(
858
+ "STEP_FINISHED"
859
+ /* STEP_FINISHED */
860
+ ),
861
+ stepName: import_zod2.z.string()
862
+ });
863
+ var EventSchemas = import_zod2.z.discriminatedUnion("type", [
864
+ TextMessageStartEventSchema,
865
+ TextMessageContentEventSchema,
866
+ TextMessageEndEventSchema,
867
+ TextMessageChunkEventSchema,
868
+ ThinkingStartEventSchema,
869
+ ThinkingEndEventSchema,
870
+ ThinkingTextMessageStartEventSchema,
871
+ ThinkingTextMessageContentEventSchema,
872
+ ThinkingTextMessageEndEventSchema,
873
+ ToolCallStartEventSchema,
874
+ ToolCallArgsEventSchema,
875
+ ToolCallEndEventSchema,
876
+ ToolCallChunkEventSchema,
877
+ ToolCallResultEventSchema,
878
+ StateSnapshotEventSchema,
879
+ StateDeltaEventSchema,
880
+ MessagesSnapshotEventSchema,
881
+ ActivitySnapshotEventSchema,
882
+ ActivityDeltaEventSchema,
883
+ RawEventSchema,
884
+ CustomEventSchema,
885
+ RunStartedEventSchema,
886
+ RunFinishedEventSchema,
887
+ RunErrorEventSchema,
888
+ StepStartedEventSchema,
889
+ StepFinishedEventSchema
890
+ ]);
1154
891
 
1155
- // src/utils/extract.ts
1156
- var import_shared5 = require("@copilotkit/shared");
1157
- var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
1158
- var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
1159
- function extract(_0) {
1160
- return __async(this, arguments, function* ({
1161
- context,
1162
- instructions,
1163
- parameters,
1164
- include,
1165
- data,
1166
- abortSignal,
1167
- stream,
1168
- requestType = import_runtime_client_gql4.CopilotRequestType.Task,
1169
- forwardedParameters
1170
- }) {
1171
- var _a, _b;
1172
- const { messages } = context;
1173
- const action = {
1174
- name: "extract",
1175
- description: instructions,
1176
- parameters,
1177
- handler: (args) => {
892
+ // src/hooks/use-coagent-state-render-bridge.tsx
893
+ var import_react10 = require("@copilotkitnext/react");
894
+ var import_react11 = require("react");
895
+ var import_shared3 = require("@copilotkit/shared");
896
+ function getStateWithoutConstantKeys(state) {
897
+ const _a = state, { messages, tools, copilotkit } = _a, stateWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]);
898
+ return stateWithoutConstantKeys;
899
+ }
900
+ function areStatesEquals(a, b) {
901
+ if (a && !b || !a && b)
902
+ return false;
903
+ const _a = a, { messages, tools, copilotkit } = _a, aWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]);
904
+ const _b = b, {
905
+ messages: bMessages,
906
+ tools: bTools,
907
+ copilotkit: bCopilotkit
908
+ } = _b, bWithoutConstantKeys = __objRest(_b, [
909
+ "messages",
910
+ "tools",
911
+ "copilotkit"
912
+ ]);
913
+ return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
914
+ }
915
+ function useCoagentStateRenderBridge(agentId, props) {
916
+ var _a;
917
+ const { stateSnapshot, messageIndexInRun, message } = props;
918
+ const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
919
+ const { agent } = (0, import_react10.useAgent)({ agentId });
920
+ const [nodeName, setNodeName] = (0, import_react11.useState)(void 0);
921
+ const runId = (_a = props.runId) != null ? _a : message.runId;
922
+ const effectiveRunId = runId || "pending";
923
+ (0, import_react11.useEffect)(() => {
924
+ if (!agent)
925
+ return;
926
+ const subscriber = {
927
+ onStepStartedEvent: ({ event }) => {
928
+ if (event.stepName !== nodeName) {
929
+ setNodeName(event.stepName);
930
+ }
931
+ },
932
+ onStepFinishedEvent: ({ event }) => {
933
+ if (event.stepName === nodeName) {
934
+ setNodeName(void 0);
935
+ }
1178
936
  }
1179
937
  };
1180
- const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
1181
- const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
1182
- let contextString = "";
1183
- if (data) {
1184
- contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
1185
- }
1186
- if (includeReadable) {
1187
- contextString += context.getContextString([], defaultCopilotContextCategories);
938
+ const { unsubscribe } = agent.subscribe(subscriber);
939
+ return () => {
940
+ unsubscribe();
941
+ };
942
+ }, [agentId, nodeName]);
943
+ if (messageIndexInRun !== 0) {
944
+ return null;
945
+ }
946
+ const getStateRender = (0, import_react11.useCallback)(
947
+ (messageId) => {
948
+ return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
949
+ if (claimsRef.current[messageId]) {
950
+ return stateRenderId === claimsRef.current[messageId].stateRenderId;
951
+ }
952
+ const matchingAgentName = stateRender.name === agentId;
953
+ const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
954
+ return matchingAgentName && matchesNodeContext;
955
+ });
956
+ },
957
+ [coAgentStateRenders, nodeName, agentId]
958
+ );
959
+ const handleRenderRequest = ({
960
+ stateRenderId,
961
+ messageId,
962
+ runId: runId2,
963
+ stateSnapshot: renderSnapshot
964
+ }) => {
965
+ if (claimsRef.current[messageId]) {
966
+ const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;
967
+ if (canRender && runId2 && (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === "pending")) {
968
+ claimsRef.current[messageId].runId = runId2;
969
+ }
970
+ return canRender;
1188
971
  }
1189
- const systemMessage = new import_runtime_client_gql4.TextMessage({
1190
- content: makeSystemMessage(contextString, instructions),
1191
- role: import_runtime_client_gql4.Role.System
1192
- });
1193
- const instructionsMessage = new import_runtime_client_gql4.TextMessage({
1194
- content: makeInstructionsMessage(instructions),
1195
- role: import_runtime_client_gql4.Role.User
1196
- });
1197
- const response = context.runtimeClient.asStream(
1198
- context.runtimeClient.generateCopilotResponse({
1199
- data: {
1200
- frontend: {
1201
- actions: [
1202
- {
1203
- name: action.name,
1204
- description: action.description || "",
1205
- jsonSchema: JSON.stringify((0, import_shared5.actionParametersToJsonSchema)(action.parameters || []))
1206
- }
1207
- ],
1208
- url: window.location.href
1209
- },
1210
- messages: (0, import_runtime_client_gql5.convertMessagesToGqlInput)(
1211
- includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql5.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
1212
- ),
1213
- metadata: {
1214
- requestType
1215
- },
1216
- forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
1217
- toolChoice: "function",
1218
- toolChoiceFunctionName: action.name
1219
- })
1220
- },
1221
- properties: context.copilotApiConfig.properties,
1222
- signal: abortSignal
1223
- })
972
+ const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(
973
+ (c) => c.stateRenderId === stateRenderId && (0, import_shared3.dataToUUID)(JSON.stringify(getStateWithoutConstantKeys(c.stateSnapshot))) === (0, import_shared3.dataToUUID)(JSON.stringify(getStateWithoutConstantKeys(renderSnapshot)))
1224
974
  );
1225
- const reader = response.getReader();
1226
- let isInitial = true;
1227
- let actionExecutionMessage = void 0;
1228
- while (true) {
1229
- const { done, value } = yield reader.read();
1230
- if (done) {
1231
- break;
975
+ if (renderClaimedByOtherMessage) {
976
+ if (renderSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)) {
977
+ claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
978
+ return true;
1232
979
  }
1233
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
1234
- throw new Error("Aborted");
1235
- }
1236
- actionExecutionMessage = (0, import_runtime_client_gql4.convertGqlOutputToMessages)(
1237
- value.generateCopilotResponse.messages
1238
- ).find((msg) => msg.isActionExecutionMessage());
1239
- if (!actionExecutionMessage) {
1240
- continue;
980
+ return false;
981
+ }
982
+ if (!runId2) {
983
+ return false;
984
+ }
985
+ claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
986
+ return true;
987
+ };
988
+ return (0, import_react11.useMemo)(() => {
989
+ var _a2, _b, _c;
990
+ const [stateRenderId, stateRender] = (_a2 = getStateRender(message.id)) != null ? _a2 : [];
991
+ if (!stateRender || !stateRenderId) {
992
+ return null;
993
+ }
994
+ const snapshot = stateSnapshot ? (0, import_shared3.parseJson)(stateSnapshot, stateSnapshot) : agent == null ? void 0 : agent.state;
995
+ const canRender = handleRenderRequest({
996
+ stateRenderId,
997
+ messageId: message.id,
998
+ runId: effectiveRunId,
999
+ stateSnapshot: snapshot
1000
+ });
1001
+ if (!canRender) {
1002
+ return null;
1003
+ }
1004
+ if (snapshot && !claimsRef.current[message.id].locked) {
1005
+ if (stateSnapshot) {
1006
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1007
+ claimsRef.current[message.id].locked = true;
1008
+ } else {
1009
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1241
1010
  }
1242
- stream == null ? void 0 : stream({
1243
- status: isInitial ? "initial" : "inProgress",
1244
- args: actionExecutionMessage.arguments
1011
+ }
1012
+ if (stateRender.handler) {
1013
+ stateRender.handler({
1014
+ state: stateSnapshot ? (0, import_shared3.parseJson)(stateSnapshot, stateSnapshot) : (_b = agent == null ? void 0 : agent.state) != null ? _b : {},
1015
+ nodeName: nodeName != null ? nodeName : ""
1245
1016
  });
1246
- isInitial = false;
1247
1017
  }
1248
- if (!actionExecutionMessage) {
1249
- throw new Error("extract() failed: No function call occurred");
1018
+ if (stateRender.render) {
1019
+ const status = (agent == null ? void 0 : agent.isRunning) ? "inProgress" : "complete";
1020
+ if (typeof stateRender.render === "string")
1021
+ return stateRender.render;
1022
+ return stateRender.render({
1023
+ status,
1024
+ // Always use state from claim, to make sure the state does not seem "wiped" for a fraction of a second
1025
+ state: (_c = claimsRef.current[message.id].stateSnapshot) != null ? _c : {},
1026
+ nodeName: nodeName != null ? nodeName : ""
1027
+ });
1250
1028
  }
1251
- stream == null ? void 0 : stream({
1252
- status: "complete",
1253
- args: actionExecutionMessage.arguments
1254
- });
1255
- return actionExecutionMessage.arguments;
1256
- });
1029
+ }, [
1030
+ getStateRender,
1031
+ stateSnapshot,
1032
+ agent == null ? void 0 : agent.state,
1033
+ agent == null ? void 0 : agent.isRunning,
1034
+ nodeName,
1035
+ effectiveRunId,
1036
+ message.id
1037
+ ]);
1257
1038
  }
1258
- function makeInstructionsMessage(instructions) {
1259
- return `
1260
- The user has given you the following task to complete:
1261
-
1262
- \`\`\`
1263
- ${instructions}
1264
- \`\`\`
1265
-
1266
- Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
1267
- `;
1039
+ function CoAgentStateRenderBridge(props) {
1040
+ return useCoagentStateRenderBridge(props.agentId, props);
1268
1041
  }
1269
- function makeSystemMessage(contextString, instructions) {
1270
- return `
1271
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1272
1042
 
1273
- Help the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.
1274
- Always be polite and respectful, and prefer brevity over verbosity.
1275
-
1276
- The user has provided you with the following context:
1277
- \`\`\`
1278
- ${contextString}
1279
- \`\`\`
1280
-
1281
- They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
1282
-
1283
- Please assist them as best you can.
1284
-
1285
- This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
1286
- `;
1287
- }
1288
-
1289
- // src/utils/suggestions.ts
1290
- var import_shared6 = require("@copilotkit/shared");
1291
- var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
1292
- var reloadSuggestions = (context, chatSuggestionConfiguration, setCurrentSuggestions, abortControllerRef) => __async(void 0, null, function* () {
1293
- const abortController = abortControllerRef.current;
1294
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1295
- return;
1043
+ // src/hooks/use-copilot-chat_internal.ts
1044
+ function useConfigureSuggestions2(suggestions) {
1045
+ let suggestionsConfig;
1046
+ if (Array.isArray(suggestions)) {
1047
+ suggestionsConfig = {
1048
+ suggestions,
1049
+ available: "always"
1050
+ };
1051
+ } else if (suggestions === "auto") {
1052
+ suggestionsConfig = {
1053
+ available: suggestions === "auto" ? "always" : "disabled",
1054
+ instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls."
1055
+ };
1056
+ } else {
1057
+ suggestionsConfig = { available: "disabled" };
1296
1058
  }
1297
- const setSuggestionsIfNotAborted = (suggestions) => {
1298
- if (!(abortController == null ? void 0 : abortController.signal.aborted) && abortControllerRef.current === abortController) {
1299
- setCurrentSuggestions(suggestions);
1300
- }
1301
- };
1302
- try {
1303
- const tools = JSON.stringify(
1304
- Object.values(context.actions).map((action) => ({
1305
- name: action.name,
1306
- description: action.description,
1307
- jsonSchema: JSON.stringify((0, import_shared6.actionParametersToJsonSchema)(action.parameters))
1308
- }))
1309
- );
1310
- const allSuggestions = [];
1311
- let hasSuccessfulSuggestions = false;
1312
- let hasErrors = false;
1313
- let lastError = null;
1314
- const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(
1315
- (config) => config.instructions && config.instructions.trim().length > 0
1316
- );
1317
- if (enabledConfigs.length === 0) {
1318
- return;
1319
- }
1320
- setSuggestionsIfNotAborted([]);
1321
- for (const config of enabledConfigs) {
1322
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1323
- setSuggestionsIfNotAborted([]);
1324
- return;
1325
- }
1059
+ useConfigureChatSuggestions(suggestionsConfig);
1060
+ }
1061
+ function useCopilotChatInternal({
1062
+ suggestions
1063
+ } = {}) {
1064
+ var _a, _b, _c, _d;
1065
+ const { copilotkit } = (0, import_react13.useCopilotKit)();
1066
+ const { threadId, agentSession } = useCopilotContext();
1067
+ const existingConfig = (0, import_react13.useCopilotChatConfiguration)();
1068
+ const [agentAvailable, setAgentAvailable] = (0, import_react12.useState)(false);
1069
+ useConfigureSuggestions2(suggestions);
1070
+ const resolvedAgentId = (_b = (_a = agentSession == null ? void 0 : agentSession.agentName) != null ? _a : existingConfig == null ? void 0 : existingConfig.agentId) != null ? _b : "default";
1071
+ const { agent } = (0, import_react13.useAgent)({ agentId: resolvedAgentId });
1072
+ (0, import_react12.useEffect)(() => {
1073
+ const connect = (agent2) => __async(this, null, function* () {
1074
+ setAgentAvailable(false);
1326
1075
  try {
1327
- const result = yield extract({
1328
- context,
1329
- instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. ",
1330
- data: `${config.instructions}
1331
-
1332
- Available tools: ${tools}
1333
-
1334
- `,
1335
- requestType: import_runtime_client_gql6.CopilotRequestType.Task,
1336
- parameters: [
1337
- {
1338
- name: "suggestions",
1339
- type: "object[]",
1340
- attributes: [
1341
- {
1342
- name: "title",
1343
- description: "The title of the suggestion. This is shown as a button and should be short.",
1344
- type: "string"
1345
- },
1346
- {
1347
- name: "message",
1348
- description: "The message to send when the suggestion is clicked. This should be a clear, complete sentence and will be sent as an instruction to the AI.",
1349
- type: "string"
1350
- }
1351
- ]
1352
- }
1353
- ],
1354
- include: {
1355
- messages: true,
1356
- readable: true
1357
- },
1358
- abortSignal: abortController == null ? void 0 : abortController.signal,
1359
- stream: ({ status, args }) => {
1360
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1361
- return;
1362
- }
1363
- const suggestions = args.suggestions || [];
1364
- const newSuggestions = [];
1365
- for (let i = 0; i < suggestions.length; i++) {
1366
- if (config.maxSuggestions !== void 0 && i >= config.maxSuggestions) {
1367
- break;
1368
- }
1369
- const suggestion = suggestions[i];
1370
- if (!suggestion || typeof suggestion !== "object") {
1371
- continue;
1372
- }
1373
- const { title, message } = suggestion;
1374
- const hasValidTitle = title && typeof title === "string" && title.trim().length > 0;
1375
- const hasValidMessage = message && typeof message === "string" && message.trim().length > 0;
1376
- if (!hasValidTitle) {
1377
- continue;
1378
- }
1379
- const partial = i === suggestions.length - 1 && status !== "complete";
1380
- newSuggestions.push({
1381
- title: title.trim(),
1382
- message: hasValidMessage ? message.trim() : "",
1383
- // Use title as fallback
1384
- partial,
1385
- className: config.className
1386
- });
1387
- }
1388
- setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);
1389
- }
1390
- });
1391
- if ((result == null ? void 0 : result.suggestions) && Array.isArray(result.suggestions)) {
1392
- const validSuggestions = result.suggestions.filter(
1393
- (suggestion) => suggestion && typeof suggestion.title === "string" && suggestion.title.trim().length > 0
1394
- ).map((suggestion) => ({
1395
- title: suggestion.title.trim(),
1396
- message: suggestion.message && typeof suggestion.message === "string" && suggestion.message.trim() ? suggestion.message.trim() : suggestion.title.trim()
1397
- }));
1398
- if (validSuggestions.length > 0) {
1399
- allSuggestions.push(...validSuggestions);
1400
- hasSuccessfulSuggestions = true;
1401
- }
1402
- }
1076
+ yield copilotkit.connectAgent({ agent: agent2 });
1077
+ setAgentAvailable(true);
1403
1078
  } catch (error) {
1404
- hasErrors = true;
1405
- lastError = error instanceof Error ? error : new Error(String(error));
1079
+ if (error instanceof AGUIConnectNotImplementedError) {
1080
+ } else {
1081
+ throw error;
1082
+ }
1406
1083
  }
1084
+ });
1085
+ if (agent && (existingConfig == null ? void 0 : existingConfig.threadId) && agent.threadId !== existingConfig.threadId) {
1086
+ agent.threadId = existingConfig.threadId;
1087
+ connect(agent);
1407
1088
  }
1408
- if (hasSuccessfulSuggestions && allSuggestions.length > 0) {
1409
- const uniqueSuggestions = allSuggestions.filter(
1410
- (suggestion, index, self) => index === self.findIndex((s) => s.message === suggestion.message)
1089
+ return () => {
1090
+ };
1091
+ }, [existingConfig == null ? void 0 : existingConfig.threadId, agent, copilotkit, resolvedAgentId]);
1092
+ const interrupt = useLangGraphInterruptRender(agent);
1093
+ const reset = () => {
1094
+ agent == null ? void 0 : agent.setMessages([]);
1095
+ agent == null ? void 0 : agent.setState(null);
1096
+ };
1097
+ const deleteMessage = (0, import_react12.useCallback)(
1098
+ (messageId) => {
1099
+ var _a2;
1100
+ const filteredMessages = ((_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []).filter(
1101
+ (message) => message.id !== messageId
1411
1102
  );
1412
- setSuggestionsIfNotAborted(uniqueSuggestions);
1413
- } else if (hasErrors) {
1414
- const errorMessage = lastError ? lastError.message : "Failed to generate suggestions due to API errors";
1415
- throw new Error(errorMessage);
1416
- }
1417
- } catch (error) {
1418
- throw error;
1419
- }
1420
- });
1421
-
1422
- // src/components/copilot-provider/copilotkit.tsx
1423
- var import_jsx_runtime4 = require("react/jsx-runtime");
1424
- var defaultCopilotContextCategories = ["global"];
1425
-
1426
- // src/hooks/use-copilot-chat_internal.ts
1427
- var import_runtime_client_gql7 = require("@copilotkit/runtime-client-gql");
1428
-
1429
- // src/hooks/use-langgraph-interrupt-render.ts
1430
- var import_react8 = __toESM(require("react"));
1431
- var InterruptRenderer = ({ event, result, render, resolve }) => {
1432
- return render({ event, result, resolve });
1433
- };
1434
- function useLangGraphInterruptRender() {
1435
- const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession, threadId } = useCopilotContext();
1436
- const responseRef = import_react8.default.useRef();
1437
- const resolveInterrupt = (0, import_react8.useCallback)(
1438
- (response) => {
1439
- responseRef.current = response;
1440
- setTimeout(() => {
1441
- setLangGraphInterruptAction(threadId, { event: { response } });
1442
- }, 0);
1103
+ agent == null ? void 0 : agent.setMessages(filteredMessages);
1443
1104
  },
1444
- [setLangGraphInterruptAction, threadId]
1105
+ [agent == null ? void 0 : agent.setMessages, agent == null ? void 0 : agent.messages]
1445
1106
  );
1446
- if (!langGraphInterruptAction || !langGraphInterruptAction.event || !langGraphInterruptAction.render)
1447
- return null;
1448
- const { render, handler, event, enabled } = langGraphInterruptAction;
1449
- const conditionsMet = !agentSession || !enabled ? true : enabled({ eventValue: event.value, agentMetadata: agentSession });
1450
- if (!conditionsMet) {
1451
- return null;
1452
- }
1453
- let result = null;
1454
- if (handler) {
1455
- result = handler({
1456
- event,
1457
- resolve: resolveInterrupt
1458
- });
1459
- }
1460
- return import_react8.default.createElement(InterruptRenderer, {
1461
- event,
1462
- result,
1463
- render,
1464
- resolve: resolveInterrupt
1465
- });
1466
- }
1467
-
1468
- // src/hooks/use-copilot-chat_internal.ts
1469
- var globalSuggestionPromise = null;
1470
- function useCopilotChat(options = {}) {
1471
- var _a;
1472
- const makeSystemMessage2 = (_a = options.makeSystemMessage) != null ? _a : defaultSystemMessage;
1473
- const {
1474
- getContextString,
1475
- getFunctionCallHandler,
1476
- copilotApiConfig,
1477
- isLoading,
1478
- setIsLoading,
1479
- chatInstructions,
1480
- actions,
1481
- coagentStatesRef,
1482
- setCoagentStatesWithRef,
1483
- coAgentStateRenders,
1484
- agentSession,
1485
- setAgentSession,
1486
- forwardedParameters,
1487
- agentLock,
1488
- threadId,
1489
- setThreadId,
1490
- runId,
1491
- setRunId,
1492
- chatAbortControllerRef,
1493
- extensions,
1494
- setExtensions,
1495
- langGraphInterruptAction,
1496
- setLangGraphInterruptAction,
1497
- chatSuggestionConfiguration,
1498
- runtimeClient
1499
- } = useCopilotContext();
1500
- const { messages, setMessages, suggestions, setSuggestions } = useCopilotMessagesContext();
1501
- const [mcpServers, setLocalMcpServers] = (0, import_react9.useState)([]);
1502
- const suggestionsAbortControllerRef = (0, import_react9.useRef)(null);
1503
- const isLoadingSuggestionsRef = (0, import_react9.useRef)(false);
1504
- const abortSuggestions = (0, import_react9.useCallback)(
1505
- (clear = true) => {
1506
- var _a2;
1507
- (_a2 = suggestionsAbortControllerRef.current) == null ? void 0 : _a2.abort("suggestions aborted by user");
1508
- suggestionsAbortControllerRef.current = null;
1509
- if (clear) {
1510
- setSuggestions([]);
1511
- }
1107
+ const latestDelete = useUpdatedRef(deleteMessage);
1108
+ const latestDeleteFunc = (0, import_react12.useCallback)(
1109
+ (messageId) => {
1110
+ return latestDelete.current(messageId);
1512
1111
  },
1513
- [setSuggestions]
1112
+ [latestDelete]
1514
1113
  );
1515
- const stableContext = (0, import_react9.useMemo)(() => {
1516
- return {
1517
- actions,
1518
- copilotApiConfig,
1519
- chatSuggestionConfiguration,
1520
- messages,
1521
- setMessages,
1522
- getContextString,
1523
- runtimeClient
1524
- };
1525
- }, [
1526
- JSON.stringify(Object.keys(actions)),
1527
- copilotApiConfig.chatApiEndpoint,
1528
- messages.length,
1529
- Object.keys(chatSuggestionConfiguration).length
1530
- ]);
1531
- const generateSuggestionsFunc = (0, import_react9.useCallback)(() => __async(this, null, function* () {
1532
- if (globalSuggestionPromise) {
1533
- return globalSuggestionPromise;
1534
- }
1535
- globalSuggestionPromise = (() => __async(this, null, function* () {
1536
- try {
1537
- abortSuggestions();
1538
- isLoadingSuggestionsRef.current = true;
1539
- suggestionsAbortControllerRef.current = new AbortController();
1540
- setSuggestions([]);
1541
- yield reloadSuggestions(
1542
- stableContext,
1543
- chatSuggestionConfiguration,
1544
- setSuggestions,
1545
- suggestionsAbortControllerRef
1546
- );
1547
- } catch (error) {
1548
- throw error;
1549
- } finally {
1550
- isLoadingSuggestionsRef.current = false;
1551
- globalSuggestionPromise = null;
1114
+ const currentSuggestions = (0, import_react13.useSuggestions)({ agentId: resolvedAgentId });
1115
+ const reload = useAsyncCallback(
1116
+ (reloadMessageId) => __async(this, null, function* () {
1117
+ var _a2;
1118
+ const messages = (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : [];
1119
+ const isLoading = false;
1120
+ if (isLoading || messages.length === 0) {
1121
+ return;
1552
1122
  }
1553
- }))();
1554
- return globalSuggestionPromise;
1555
- }), [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);
1556
- const resetSuggestions = (0, import_react9.useCallback)(() => {
1557
- setSuggestions([]);
1558
- }, [setSuggestions]);
1559
- (0, import_react9.useEffect)(() => {
1560
- if (mcpServers.length > 0) {
1561
- const serversCopy = [...mcpServers];
1562
- copilotApiConfig.mcpServers = serversCopy;
1563
- if (!copilotApiConfig.properties) {
1564
- copilotApiConfig.properties = {};
1123
+ const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
1124
+ if (reloadMessageIndex === -1) {
1125
+ console.warn(`Message with id ${reloadMessageId} not found`);
1126
+ return;
1565
1127
  }
1566
- copilotApiConfig.properties.mcpServers = serversCopy;
1567
- }
1568
- }, [mcpServers, copilotApiConfig]);
1569
- const setMcpServers = (0, import_react9.useCallback)((servers) => {
1570
- setLocalMcpServers(servers);
1571
- }, []);
1572
- const onCoAgentStateRender = useAsyncCallback(
1573
- (args) => __async(this, null, function* () {
1574
- var _a2;
1575
- const { name, nodeName, state } = args;
1576
- let action = Object.values(coAgentStateRenders).find(
1577
- (action2) => action2.name === name && action2.nodeName === nodeName
1578
- );
1579
- if (!action) {
1580
- action = Object.values(coAgentStateRenders).find(
1581
- (action2) => action2.name === name && !action2.nodeName
1582
- );
1128
+ const reloadMessageRole = messages[reloadMessageIndex].role;
1129
+ if (reloadMessageRole !== "assistant") {
1130
+ console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
1131
+ return;
1132
+ }
1133
+ let historyCutoff = [messages[0]];
1134
+ if (messages.length > 2 && reloadMessageIndex !== 0) {
1135
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find((msg) => msg.role === "user");
1136
+ if (!lastUserMessageBeforeRegenerate) {
1137
+ historyCutoff = [messages[0]];
1138
+ } else {
1139
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1140
+ (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1141
+ );
1142
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1143
+ }
1144
+ } else if (messages.length > 2 && reloadMessageIndex === 0) {
1145
+ historyCutoff = [messages[0], messages[1]];
1583
1146
  }
1584
- if (action) {
1585
- yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
1147
+ agent == null ? void 0 : agent.setMessages(historyCutoff);
1148
+ if (agent) {
1149
+ copilotkit.runAgent({ agent });
1586
1150
  }
1151
+ return;
1587
1152
  }),
1588
- [coAgentStateRenders]
1153
+ [agent == null ? void 0 : agent.setMessages, copilotkit == null ? void 0 : copilotkit.runAgent]
1589
1154
  );
1590
- const makeSystemMessageCallback = (0, import_react9.useCallback)(() => {
1591
- const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
1592
- const contextString = getContextString([], defaultCopilotContextCategories);
1593
- return new import_runtime_client_gql7.TextMessage({
1594
- content: systemMessageMaker(contextString, chatInstructions),
1595
- role: import_runtime_client_gql7.Role.System
1596
- });
1597
- }, [getContextString, makeSystemMessage2, chatInstructions]);
1598
- const deleteMessage = (0, import_react9.useCallback)(
1599
- (messageId) => {
1600
- setMessages((prev) => prev.filter((message) => message.id !== messageId));
1601
- },
1602
- [setMessages]
1155
+ const latestSendMessageFunc = useAsyncCallback(
1156
+ (message, options) => __async(this, null, function* () {
1157
+ var _a2;
1158
+ if (!agent)
1159
+ return;
1160
+ const followUp = (_a2 = options == null ? void 0 : options.followUp) != null ? _a2 : true;
1161
+ if (options == null ? void 0 : options.clearSuggestions) {
1162
+ copilotkit.clearSuggestions(resolvedAgentId);
1163
+ }
1164
+ agent == null ? void 0 : agent.addMessage(message);
1165
+ if (followUp) {
1166
+ try {
1167
+ yield copilotkit.runAgent({ agent });
1168
+ } catch (error) {
1169
+ console.error("CopilotChat: runAgent failed", error);
1170
+ }
1171
+ }
1172
+ }),
1173
+ [agent, copilotkit, resolvedAgentId]
1603
1174
  );
1604
- const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
1605
- actions: Object.values(actions),
1606
- copilotConfig: copilotApiConfig,
1607
- initialMessages: (0, import_runtime_client_gql7.aguiToGQL)(options.initialMessages || []),
1608
- onFunctionCall: getFunctionCallHandler(),
1609
- onCoAgentStateRender,
1610
- messages,
1611
- setMessages,
1612
- makeSystemMessageCallback,
1613
- isLoading,
1614
- setIsLoading,
1615
- coagentStatesRef,
1616
- setCoagentStatesWithRef,
1617
- agentSession,
1618
- setAgentSession,
1619
- forwardedParameters,
1620
- threadId,
1621
- setThreadId,
1622
- runId,
1623
- setRunId,
1624
- chatAbortControllerRef,
1625
- agentLock,
1626
- extensions,
1627
- setExtensions,
1628
- langGraphInterruptAction,
1629
- setLangGraphInterruptAction,
1630
- disableSystemMessage: options.disableSystemMessage
1631
- }));
1632
- const latestAppend = useUpdatedRef(append);
1633
1175
  const latestAppendFunc = useAsyncCallback(
1634
- (message, options2) => __async(this, null, function* () {
1635
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
1636
- return yield latestAppend.current(message, options2);
1176
+ (message, options) => __async(this, null, function* () {
1177
+ return latestSendMessageFunc((0, import_runtime_client_gql2.gqlToAGUI)([message])[0], options);
1637
1178
  }),
1638
- [latestAppend]
1179
+ [latestSendMessageFunc]
1639
1180
  );
1640
- const latestSendMessageFunc = useAsyncCallback(
1641
- (message, options2) => __async(this, null, function* () {
1642
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
1643
- return yield latestAppend.current((0, import_runtime_client_gql7.aguiToGQL)([message])[0], options2);
1644
- }),
1645
- [latestAppend]
1181
+ const latestSetMessages = useUpdatedRef(agent == null ? void 0 : agent.setMessages);
1182
+ const latestSetMessagesFunc = (0, import_react12.useCallback)(
1183
+ (messages) => {
1184
+ var _a2, _b2;
1185
+ if (messages.every((message) => message instanceof import_runtime_client_gql2.Message)) {
1186
+ return (_a2 = latestSetMessages.current) == null ? void 0 : _a2.call(latestSetMessages, (0, import_runtime_client_gql2.gqlToAGUI)(messages));
1187
+ }
1188
+ return (_b2 = latestSetMessages.current) == null ? void 0 : _b2.call(latestSetMessages, messages);
1189
+ },
1190
+ [latestSetMessages, agent]
1646
1191
  );
1647
1192
  const latestReload = useUpdatedRef(reload);
1648
1193
  const latestReloadFunc = useAsyncCallback(
@@ -1651,61 +1196,81 @@ function useCopilotChat(options = {}) {
1651
1196
  }),
1652
1197
  [latestReload]
1653
1198
  );
1654
- const latestStop = useUpdatedRef(stop);
1655
- const latestStopFunc = (0, import_react9.useCallback)(() => {
1656
- return latestStop.current();
1199
+ const latestStop = useUpdatedRef(agent == null ? void 0 : agent.abortRun);
1200
+ const latestStopFunc = (0, import_react12.useCallback)(() => {
1201
+ var _a2;
1202
+ return (_a2 = latestStop.current) == null ? void 0 : _a2.call(latestStop);
1657
1203
  }, [latestStop]);
1658
- const latestDelete = useUpdatedRef(deleteMessage);
1659
- const latestDeleteFunc = (0, import_react9.useCallback)(
1660
- (messageId) => {
1661
- return latestDelete.current(messageId);
1662
- },
1663
- [latestDelete]
1664
- );
1665
- const latestSetMessages = useUpdatedRef(setMessages);
1666
- const latestSetMessagesFunc = (0, import_react9.useCallback)(
1667
- (messages2) => {
1668
- if (messages2.every((message) => message instanceof import_runtime_client_gql7.Message)) {
1669
- return latestSetMessages.current(messages2);
1204
+ const latestReset = useUpdatedRef(reset);
1205
+ const latestResetFunc = (0, import_react12.useCallback)(() => {
1206
+ return latestReset.current();
1207
+ }, [latestReset]);
1208
+ const lazyToolRendered = useLazyToolRenderer();
1209
+ const renderCustomMessage = (0, import_react13.useRenderCustomMessages)();
1210
+ const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
1211
+ copilotkit,
1212
+ agent,
1213
+ agentId: resolvedAgentId,
1214
+ threadId: (_c = existingConfig == null ? void 0 : existingConfig.threadId) != null ? _c : threadId
1215
+ });
1216
+ const allMessages = (_d = agent == null ? void 0 : agent.messages) != null ? _d : [];
1217
+ const resolvedMessages = (0, import_react12.useMemo)(() => {
1218
+ let processedMessages = allMessages.map((message) => {
1219
+ if (message.role !== "assistant") {
1220
+ return message;
1670
1221
  }
1671
- return latestSetMessages.current((0, import_runtime_client_gql7.aguiToGQL)(messages2));
1672
- },
1673
- [latestSetMessages]
1674
- );
1675
- const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
1676
- const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
1677
- return yield latestRunChatCompletion.current();
1678
- }), [latestRunChatCompletion]);
1679
- const reset = (0, import_react9.useCallback)(() => {
1680
- latestStopFunc();
1681
- setMessages([]);
1682
- setRunId(null);
1683
- setCoagentStatesWithRef({});
1684
- let initialAgentSession = null;
1685
- if (agentLock) {
1686
- initialAgentSession = {
1687
- agentName: agentLock
1222
+ const lazyRendered = lazyToolRendered(message, allMessages);
1223
+ if (lazyRendered) {
1224
+ const renderedGenUi = lazyRendered();
1225
+ if (renderedGenUi) {
1226
+ return __spreadProps(__spreadValues({}, message), { generativeUI: () => renderedGenUi });
1227
+ }
1228
+ }
1229
+ const bridgeRenderer = legacyCustomMessageRenderer || renderCustomMessage ? () => {
1230
+ const customRender = renderCustomMessage == null ? void 0 : renderCustomMessage({
1231
+ message,
1232
+ position: "before"
1233
+ });
1234
+ if (customRender) {
1235
+ return customRender;
1236
+ }
1237
+ return legacyCustomMessageRenderer == null ? void 0 : legacyCustomMessageRenderer({ message, position: "before" });
1238
+ } : null;
1239
+ if (bridgeRenderer) {
1240
+ return __spreadProps(__spreadValues({}, message), { generativeUI: bridgeRenderer });
1241
+ }
1242
+ return message;
1243
+ });
1244
+ const hasAssistantMessages = processedMessages.some((msg) => msg.role === "assistant");
1245
+ if (legacyCustomMessageRenderer && !hasAssistantMessages) {
1246
+ const placeholderId = `coagent-state-render-${resolvedAgentId}`;
1247
+ const placeholderMessage = {
1248
+ id: placeholderId,
1249
+ role: "assistant",
1250
+ content: "",
1251
+ name: "coagent-state-render"
1688
1252
  };
1253
+ processedMessages = [
1254
+ ...processedMessages,
1255
+ __spreadProps(__spreadValues({}, placeholderMessage), {
1256
+ generativeUI: () => legacyCustomMessageRenderer({
1257
+ message: placeholderMessage,
1258
+ position: "before"
1259
+ })
1260
+ })
1261
+ ];
1689
1262
  }
1690
- setAgentSession(initialAgentSession);
1691
- resetSuggestions();
1263
+ return processedMessages;
1692
1264
  }, [
1693
- latestStopFunc,
1694
- setMessages,
1695
- setThreadId,
1696
- setCoagentStatesWithRef,
1697
- setAgentSession,
1698
- agentLock,
1699
- resetSuggestions
1265
+ agent == null ? void 0 : agent.messages,
1266
+ lazyToolRendered,
1267
+ allMessages,
1268
+ renderCustomMessage,
1269
+ legacyCustomMessageRenderer,
1270
+ resolvedAgentId
1700
1271
  ]);
1701
- const latestReset = useUpdatedRef(reset);
1702
- const latestResetFunc = (0, import_react9.useCallback)(() => {
1703
- return latestReset.current();
1704
- }, [latestReset]);
1705
- const interrupt = useLangGraphInterruptRender();
1706
1272
  return {
1707
- visibleMessages: messages,
1708
- messages: (0, import_runtime_client_gql7.gqlToAGUI)(messages, actions, coAgentStateRenders),
1273
+ messages: resolvedMessages,
1709
1274
  sendMessage: latestSendMessageFunc,
1710
1275
  appendMessage: latestAppendFunc,
1711
1276
  setMessages: latestSetMessagesFunc,
@@ -1713,25 +1278,63 @@ function useCopilotChat(options = {}) {
1713
1278
  stopGeneration: latestStopFunc,
1714
1279
  reset: latestResetFunc,
1715
1280
  deleteMessage: latestDeleteFunc,
1716
- runChatCompletion: latestRunChatCompletionFunc,
1717
- isLoading,
1718
- mcpServers,
1719
- setMcpServers,
1720
- suggestions,
1721
- setSuggestions,
1722
- generateSuggestions: generateSuggestionsFunc,
1723
- resetSuggestions,
1724
- isLoadingSuggestions: isLoadingSuggestionsRef.current,
1725
- interrupt
1281
+ isAvailable: !agentAvailable,
1282
+ isLoading: Boolean(agent == null ? void 0 : agent.isRunning),
1283
+ // mcpServers,
1284
+ // setMcpServers,
1285
+ suggestions: currentSuggestions.suggestions,
1286
+ setSuggestions: (suggestions2) => copilotkit.addSuggestionsConfig({ suggestions: suggestions2 }),
1287
+ generateSuggestions: () => __async(this, null, function* () {
1288
+ return copilotkit.reloadSuggestions(resolvedAgentId);
1289
+ }),
1290
+ resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),
1291
+ isLoadingSuggestions: currentSuggestions.isLoading,
1292
+ interrupt,
1293
+ agent,
1294
+ threadId
1726
1295
  };
1727
1296
  }
1728
1297
  function useUpdatedRef(value) {
1729
- const ref = (0, import_react9.useRef)(value);
1730
- (0, import_react9.useEffect)(() => {
1298
+ const ref = (0, import_react12.useRef)(value);
1299
+ (0, import_react12.useEffect)(() => {
1731
1300
  ref.current = value;
1732
1301
  }, [value]);
1733
1302
  return ref;
1734
1303
  }
1304
+ function useLegacyCoagentRenderer({
1305
+ copilotkit,
1306
+ agent,
1307
+ agentId,
1308
+ threadId
1309
+ }) {
1310
+ return (0, import_react12.useMemo)(() => {
1311
+ if (!copilotkit || !agent) {
1312
+ return null;
1313
+ }
1314
+ return ({ message, position }) => {
1315
+ var _a;
1316
+ const effectiveThreadId = (_a = threadId != null ? threadId : agent.threadId) != null ? _a : "default";
1317
+ const existingRunId = copilotkit.getRunIdForMessage(
1318
+ agentId,
1319
+ effectiveThreadId,
1320
+ message.id
1321
+ );
1322
+ const runId = existingRunId || `pending:${message.id}`;
1323
+ const messageIndex = Math.max(agent.messages.findIndex((msg) => msg.id === message.id), 0);
1324
+ const bridgeProps = {
1325
+ message,
1326
+ position,
1327
+ runId,
1328
+ messageIndex,
1329
+ messageIndexInRun: 0,
1330
+ numberOfMessagesInRun: 1,
1331
+ agentId,
1332
+ stateSnapshot: message.state
1333
+ };
1334
+ return (0, import_react12.createElement)(CoAgentStateRenderBridge, bridgeProps);
1335
+ };
1336
+ }, [agent, agentId, copilotkit, threadId]);
1337
+ }
1735
1338
  function defaultSystemMessage(contextString, additionalInstructions) {
1736
1339
  return `
1737
1340
  Please act as an efficient, competent, conscientious, and industrious professional assistant.
@@ -1761,6 +1364,6 @@ ${additionalInstructions}` : "");
1761
1364
  // Annotate the CommonJS export names for ESM import in node:
1762
1365
  0 && (module.exports = {
1763
1366
  defaultSystemMessage,
1764
- useCopilotChat
1367
+ useCopilotChatInternal
1765
1368
  });
1766
1369
  //# sourceMappingURL=use-copilot-chat_internal.js.map