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