@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
package/dist/index.js CHANGED
@@ -81,26 +81,27 @@ var __async = (__this, __arguments, generator) => {
81
81
  // src/index.tsx
82
82
  var src_exports = {};
83
83
  __export(src_exports, {
84
+ CoAgentStateRendersContext: () => CoAgentStateRendersContext,
85
+ CoAgentStateRendersProvider: () => CoAgentStateRendersProvider,
84
86
  CopilotContext: () => CopilotContext,
85
87
  CopilotKit: () => CopilotKit,
86
88
  CopilotMessagesContext: () => CopilotMessagesContext,
87
89
  CopilotTask: () => CopilotTask,
88
90
  SUGGESTION_RETRY_CONFIG: () => SUGGESTION_RETRY_CONFIG,
91
+ ThreadsContext: () => ThreadsContext,
92
+ ThreadsProvider: () => ThreadsProvider,
89
93
  defaultCopilotContextCategories: () => defaultCopilotContextCategories,
90
- extract: () => extract,
91
- reloadSuggestions: () => reloadSuggestions,
92
- runAgent: () => runAgent,
93
94
  shouldShowDevConsole: () => shouldShowDevConsole,
94
- startAgent: () => startAgent,
95
- stopAgent: () => stopAgent,
96
95
  useCoAgent: () => useCoAgent,
97
96
  useCoAgentStateRender: () => useCoAgentStateRender,
97
+ useCoAgentStateRenders: () => useCoAgentStateRenders,
98
+ useConfigureChatSuggestions: () => useConfigureChatSuggestions,
98
99
  useCopilotAction: () => useCopilotAction,
99
100
  useCopilotAdditionalInstructions: () => useCopilotAdditionalInstructions,
100
101
  useCopilotAuthenticatedAction_c: () => useCopilotAuthenticatedAction_c,
101
- useCopilotChat: () => useCopilotChat2,
102
+ useCopilotChat: () => useCopilotChat,
102
103
  useCopilotChatHeadless_c: () => useCopilotChatHeadless_c,
103
- useCopilotChatInternal: () => useCopilotChat,
104
+ useCopilotChatInternal: () => useCopilotChatInternal,
104
105
  useCopilotContext: () => useCopilotContext,
105
106
  useCopilotMessagesContext: () => useCopilotMessagesContext,
106
107
  useCopilotReadable: () => useCopilotReadable,
@@ -110,13 +111,16 @@ __export(src_exports, {
110
111
  useHumanInTheLoop: () => useHumanInTheLoop,
111
112
  useLangGraphInterrupt: () => useLangGraphInterrupt,
112
113
  useLangGraphInterruptRender: () => useLangGraphInterruptRender,
114
+ useLazyToolRenderer: () => useLazyToolRenderer,
113
115
  useMakeCopilotDocumentReadable: () => useMakeCopilotDocumentReadable,
114
- useRenderToolCall: () => useRenderToolCall
116
+ useRenderToolCall: () => useRenderToolCall2,
117
+ useThreads: () => useThreads
115
118
  });
116
119
  module.exports = __toCommonJS(src_exports);
117
120
 
118
121
  // src/components/copilot-provider/copilotkit.tsx
119
- var import_react12 = require("react");
122
+ var import_react17 = require("react");
123
+ var import_react18 = require("@copilotkitnext/react");
120
124
 
121
125
  // src/context/copilot-context.tsx
122
126
  var import_react = __toESM(require("react"));
@@ -126,10 +130,8 @@ var emptyCopilotContext = {
126
130
  },
127
131
  removeAction: () => {
128
132
  },
129
- coAgentStateRenders: {},
130
- setCoAgentStateRender: () => {
131
- },
132
- removeCoAgentStateRender: () => {
133
+ setRegisteredActions: () => "",
134
+ removeRegisteredAction: () => {
133
135
  },
134
136
  chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
135
137
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
@@ -149,7 +151,6 @@ var emptyCopilotContext = {
149
151
  addDocumentContext: () => returnAndThrowInDebug(""),
150
152
  removeDocumentContext: () => {
151
153
  },
152
- runtimeClient: {},
153
154
  copilotApiConfig: new class {
154
155
  get chatApiEndpoint() {
155
156
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
@@ -189,10 +190,15 @@ var emptyCopilotContext = {
189
190
  extensions: {},
190
191
  setExtensions: () => {
191
192
  },
192
- langGraphInterruptAction: null,
193
- setLangGraphInterruptAction: () => {
193
+ interruptActions: {},
194
+ setInterruptAction: () => {
195
+ },
196
+ removeInterruptAction: () => {
194
197
  },
195
- removeLangGraphInterruptAction: () => {
198
+ interruptEventQueue: {},
199
+ addInterruptEvent: () => {
200
+ },
201
+ removeInterruptEvent: () => {
196
202
  },
197
203
  onError: () => {
198
204
  },
@@ -353,13 +359,16 @@ function setsHaveIntersection(setA, setB) {
353
359
 
354
360
  // src/components/copilot-provider/copilotkit.tsx
355
361
  var import_react_dom = require("react-dom");
356
- var import_shared12 = require("@copilotkit/shared");
362
+ var import_shared13 = require("@copilotkit/shared");
357
363
 
358
364
  // src/hooks/use-flat-category-store.ts
359
365
  var import_react3 = require("react");
360
366
  var import_shared2 = require("@copilotkit/shared");
361
367
  var useFlatCategoryStore = () => {
362
- const [elements, dispatch] = (0, import_react3.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
368
+ const [elements, dispatch] = (0, import_react3.useReducer)(
369
+ flatCategoryStoreReducer,
370
+ /* @__PURE__ */ new Map()
371
+ );
363
372
  const addElement = (0, import_react3.useCallback)((value, categories) => {
364
373
  const newId = (0, import_shared2.randomId)();
365
374
  dispatch({
@@ -444,9 +453,6 @@ function useCopilotMessagesContext() {
444
453
  return context;
445
454
  }
446
455
 
447
- // src/components/copilot-provider/copilot-messages.tsx
448
- var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
449
-
450
456
  // src/components/toast/toast-provider.tsx
451
457
  var import_react5 = require("react");
452
458
  var import_shared3 = require("@copilotkit/shared");
@@ -782,11 +788,11 @@ function MessagesTapProvider({ children }) {
782
788
  }
783
789
  function CopilotMessages({ children }) {
784
790
  const [messages, setMessages] = (0, import_react6.useState)([]);
785
- const lastLoadedThreadId = (0, import_react6.useRef)();
786
- const lastLoadedAgentName = (0, import_react6.useRef)();
787
- const lastLoadedMessages = (0, import_react6.useRef)();
791
+ const lastLoadedThreadId = (0, import_react6.useRef)(void 0);
792
+ const lastLoadedAgentName = (0, import_react6.useRef)(void 0);
793
+ const lastLoadedMessages = (0, import_react6.useRef)(void 0);
788
794
  const { updateTapMessages } = useMessagesTap();
789
- const { threadId, agentSession, runtimeClient, showDevConsole, onError, copilotApiConfig } = useCopilotContext();
795
+ const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } = useCopilotContext();
790
796
  const { setBannerError } = useToast();
791
797
  const traceUIError = (0, import_react6.useCallback)(
792
798
  (error, originalError) => __async(this, null, function* () {
@@ -889,39 +895,6 @@ function CopilotMessages({ children }) {
889
895
  },
890
896
  [setBannerError, showDevConsole, traceUIError]
891
897
  );
892
- (0, import_react6.useEffect)(() => {
893
- if (!threadId || threadId === lastLoadedThreadId.current)
894
- return;
895
- if (threadId === lastLoadedThreadId.current && (agentSession == null ? void 0 : agentSession.agentName) === lastLoadedAgentName.current) {
896
- return;
897
- }
898
- const fetchMessages = () => __async(this, null, function* () {
899
- var _a, _b, _c;
900
- if (!(agentSession == null ? void 0 : agentSession.agentName))
901
- return;
902
- const result = yield runtimeClient.loadAgentState({
903
- threadId,
904
- agentName: agentSession == null ? void 0 : agentSession.agentName
905
- });
906
- if (result.error) {
907
- lastLoadedThreadId.current = threadId;
908
- lastLoadedAgentName.current = agentSession == null ? void 0 : agentSession.agentName;
909
- handleGraphQLErrors(result.error);
910
- return;
911
- }
912
- const newMessages = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.messages;
913
- if (newMessages === lastLoadedMessages.current)
914
- return;
915
- if ((_c = result.data) == null ? void 0 : _c.loadAgentState) {
916
- lastLoadedMessages.current = newMessages;
917
- lastLoadedThreadId.current = threadId;
918
- lastLoadedAgentName.current = agentSession == null ? void 0 : agentSession.agentName;
919
- const messages2 = (0, import_runtime_client_gql.loadMessagesFromJsonRepresentation)(JSON.parse(newMessages || "[]"));
920
- setMessages(messages2);
921
- }
922
- });
923
- void fetchMessages();
924
- }, [threadId, agentSession == null ? void 0 : agentSession.agentName]);
925
898
  (0, import_react6.useEffect)(() => {
926
899
  updateTapMessages(messages);
927
900
  }, [messages, updateTapMessages]);
@@ -1142,384 +1115,6 @@ var getErrorActions = (error) => {
1142
1115
  }
1143
1116
  };
1144
1117
 
1145
- // src/hooks/use-copilot-runtime-client.ts
1146
- var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
1147
- var import_react7 = require("react");
1148
- var import_shared6 = require("@copilotkit/shared");
1149
- var useCopilotRuntimeClient = (options) => {
1150
- const { setBannerError } = useToast();
1151
- const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
1152
- const lastStructuredErrorRef = (0, import_react7.useRef)(null);
1153
- const traceUIError = (error, originalError) => __async(void 0, null, function* () {
1154
- try {
1155
- const errorEvent = {
1156
- type: "error",
1157
- timestamp: Date.now(),
1158
- context: {
1159
- source: "ui",
1160
- request: {
1161
- operation: "runtimeClient",
1162
- url: runtimeOptions.url,
1163
- startTime: Date.now()
1164
- },
1165
- technical: {
1166
- environment: "browser",
1167
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
1168
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
1169
- }
1170
- },
1171
- error
1172
- };
1173
- yield onError(errorEvent);
1174
- } catch (error2) {
1175
- console.error("Error in onError handler:", error2);
1176
- }
1177
- });
1178
- const runtimeClient = (0, import_react7.useMemo)(() => {
1179
- return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
1180
- handleGQLErrors: (error) => {
1181
- var _a2;
1182
- if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
1183
- const graphQLErrors = error.graphQLErrors;
1184
- const routeError = (gqlError) => {
1185
- const extensions = gqlError.extensions;
1186
- const visibility = extensions == null ? void 0 : extensions.visibility;
1187
- if (visibility === import_shared6.ErrorVisibility.SILENT) {
1188
- console.error("CopilotKit Silent Error:", gqlError.message);
1189
- return;
1190
- }
1191
- const now = Date.now();
1192
- const errorMessage = gqlError.message;
1193
- if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
1194
- return;
1195
- }
1196
- lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
1197
- const ckError = createStructuredError(gqlError);
1198
- if (ckError) {
1199
- setBannerError(ckError);
1200
- traceUIError(ckError, gqlError);
1201
- } else {
1202
- const fallbackError = new import_shared6.CopilotKitError({
1203
- message: gqlError.message,
1204
- code: import_shared6.CopilotKitErrorCode.UNKNOWN
1205
- });
1206
- setBannerError(fallbackError);
1207
- traceUIError(fallbackError, gqlError);
1208
- }
1209
- };
1210
- graphQLErrors.forEach(routeError);
1211
- } else {
1212
- const fallbackError = new import_shared6.CopilotKitError({
1213
- message: (error == null ? void 0 : error.message) || String(error),
1214
- code: import_shared6.CopilotKitErrorCode.UNKNOWN
1215
- });
1216
- setBannerError(fallbackError);
1217
- traceUIError(fallbackError, error);
1218
- }
1219
- },
1220
- handleGQLWarning: (message) => {
1221
- console.warn(message);
1222
- const warningError = new import_shared6.CopilotKitError({
1223
- message,
1224
- code: import_shared6.CopilotKitErrorCode.UNKNOWN
1225
- });
1226
- setBannerError(warningError);
1227
- }
1228
- }));
1229
- }, [runtimeOptions, setBannerError, onError]);
1230
- return runtimeClient;
1231
- };
1232
- function createStructuredError(gqlError) {
1233
- var _a, _b, _c;
1234
- const extensions = gqlError.extensions;
1235
- const originalError = extensions == null ? void 0 : extensions.originalError;
1236
- const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
1237
- const code = extensions == null ? void 0 : extensions.code;
1238
- if (code) {
1239
- return new import_shared6.CopilotKitError({ message, code });
1240
- }
1241
- if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
1242
- return new import_shared6.CopilotKitApiDiscoveryError({ message });
1243
- }
1244
- if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
1245
- return new import_shared6.CopilotKitRemoteEndpointDiscoveryError({ message });
1246
- }
1247
- if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
1248
- return new import_shared6.CopilotKitAgentDiscoveryError({
1249
- agentName: "",
1250
- availableAgents: []
1251
- });
1252
- }
1253
- return null;
1254
- }
1255
-
1256
- // src/utils/extract.ts
1257
- var import_shared7 = require("@copilotkit/shared");
1258
- var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
1259
- var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
1260
- function extract(_0) {
1261
- return __async(this, arguments, function* ({
1262
- context,
1263
- instructions,
1264
- parameters,
1265
- include,
1266
- data,
1267
- abortSignal,
1268
- stream,
1269
- requestType = import_runtime_client_gql3.CopilotRequestType.Task,
1270
- forwardedParameters
1271
- }) {
1272
- var _a, _b;
1273
- const { messages } = context;
1274
- const action = {
1275
- name: "extract",
1276
- description: instructions,
1277
- parameters,
1278
- handler: (args) => {
1279
- }
1280
- };
1281
- const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
1282
- const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
1283
- let contextString = "";
1284
- if (data) {
1285
- contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
1286
- }
1287
- if (includeReadable) {
1288
- contextString += context.getContextString([], defaultCopilotContextCategories);
1289
- }
1290
- const systemMessage = new import_runtime_client_gql3.TextMessage({
1291
- content: makeSystemMessage(contextString, instructions),
1292
- role: import_runtime_client_gql3.Role.System
1293
- });
1294
- const instructionsMessage = new import_runtime_client_gql3.TextMessage({
1295
- content: makeInstructionsMessage(instructions),
1296
- role: import_runtime_client_gql3.Role.User
1297
- });
1298
- const response = context.runtimeClient.asStream(
1299
- context.runtimeClient.generateCopilotResponse({
1300
- data: {
1301
- frontend: {
1302
- actions: [
1303
- {
1304
- name: action.name,
1305
- description: action.description || "",
1306
- jsonSchema: JSON.stringify((0, import_shared7.actionParametersToJsonSchema)(action.parameters || []))
1307
- }
1308
- ],
1309
- url: window.location.href
1310
- },
1311
- messages: (0, import_runtime_client_gql4.convertMessagesToGqlInput)(
1312
- includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql4.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
1313
- ),
1314
- metadata: {
1315
- requestType
1316
- },
1317
- forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
1318
- toolChoice: "function",
1319
- toolChoiceFunctionName: action.name
1320
- })
1321
- },
1322
- properties: context.copilotApiConfig.properties,
1323
- signal: abortSignal
1324
- })
1325
- );
1326
- const reader = response.getReader();
1327
- let isInitial = true;
1328
- let actionExecutionMessage = void 0;
1329
- while (true) {
1330
- const { done, value } = yield reader.read();
1331
- if (done) {
1332
- break;
1333
- }
1334
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
1335
- throw new Error("Aborted");
1336
- }
1337
- actionExecutionMessage = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
1338
- value.generateCopilotResponse.messages
1339
- ).find((msg) => msg.isActionExecutionMessage());
1340
- if (!actionExecutionMessage) {
1341
- continue;
1342
- }
1343
- stream == null ? void 0 : stream({
1344
- status: isInitial ? "initial" : "inProgress",
1345
- args: actionExecutionMessage.arguments
1346
- });
1347
- isInitial = false;
1348
- }
1349
- if (!actionExecutionMessage) {
1350
- throw new Error("extract() failed: No function call occurred");
1351
- }
1352
- stream == null ? void 0 : stream({
1353
- status: "complete",
1354
- args: actionExecutionMessage.arguments
1355
- });
1356
- return actionExecutionMessage.arguments;
1357
- });
1358
- }
1359
- function makeInstructionsMessage(instructions) {
1360
- return `
1361
- The user has given you the following task to complete:
1362
-
1363
- \`\`\`
1364
- ${instructions}
1365
- \`\`\`
1366
-
1367
- Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
1368
- `;
1369
- }
1370
- function makeSystemMessage(contextString, instructions) {
1371
- return `
1372
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1373
-
1374
- 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.
1375
- Always be polite and respectful, and prefer brevity over verbosity.
1376
-
1377
- The user has provided you with the following context:
1378
- \`\`\`
1379
- ${contextString}
1380
- \`\`\`
1381
-
1382
- They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
1383
-
1384
- Please assist them as best you can.
1385
-
1386
- This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
1387
- `;
1388
- }
1389
-
1390
- // src/utils/suggestions.ts
1391
- var import_shared8 = require("@copilotkit/shared");
1392
- var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
1393
- var reloadSuggestions = (context, chatSuggestionConfiguration, setCurrentSuggestions, abortControllerRef) => __async(void 0, null, function* () {
1394
- const abortController = abortControllerRef.current;
1395
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1396
- return;
1397
- }
1398
- const setSuggestionsIfNotAborted = (suggestions) => {
1399
- if (!(abortController == null ? void 0 : abortController.signal.aborted) && abortControllerRef.current === abortController) {
1400
- setCurrentSuggestions(suggestions);
1401
- }
1402
- };
1403
- try {
1404
- const tools = JSON.stringify(
1405
- Object.values(context.actions).map((action) => ({
1406
- name: action.name,
1407
- description: action.description,
1408
- jsonSchema: JSON.stringify((0, import_shared8.actionParametersToJsonSchema)(action.parameters))
1409
- }))
1410
- );
1411
- const allSuggestions = [];
1412
- let hasSuccessfulSuggestions = false;
1413
- let hasErrors = false;
1414
- let lastError = null;
1415
- const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(
1416
- (config) => config.instructions && config.instructions.trim().length > 0
1417
- );
1418
- if (enabledConfigs.length === 0) {
1419
- return;
1420
- }
1421
- setSuggestionsIfNotAborted([]);
1422
- for (const config of enabledConfigs) {
1423
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1424
- setSuggestionsIfNotAborted([]);
1425
- return;
1426
- }
1427
- try {
1428
- const result = yield extract({
1429
- context,
1430
- instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. ",
1431
- data: `${config.instructions}
1432
-
1433
- Available tools: ${tools}
1434
-
1435
- `,
1436
- requestType: import_runtime_client_gql5.CopilotRequestType.Task,
1437
- parameters: [
1438
- {
1439
- name: "suggestions",
1440
- type: "object[]",
1441
- attributes: [
1442
- {
1443
- name: "title",
1444
- description: "The title of the suggestion. This is shown as a button and should be short.",
1445
- type: "string"
1446
- },
1447
- {
1448
- name: "message",
1449
- 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.",
1450
- type: "string"
1451
- }
1452
- ]
1453
- }
1454
- ],
1455
- include: {
1456
- messages: true,
1457
- readable: true
1458
- },
1459
- abortSignal: abortController == null ? void 0 : abortController.signal,
1460
- stream: ({ status, args }) => {
1461
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1462
- return;
1463
- }
1464
- const suggestions = args.suggestions || [];
1465
- const newSuggestions = [];
1466
- for (let i = 0; i < suggestions.length; i++) {
1467
- if (config.maxSuggestions !== void 0 && i >= config.maxSuggestions) {
1468
- break;
1469
- }
1470
- const suggestion = suggestions[i];
1471
- if (!suggestion || typeof suggestion !== "object") {
1472
- continue;
1473
- }
1474
- const { title, message } = suggestion;
1475
- const hasValidTitle = title && typeof title === "string" && title.trim().length > 0;
1476
- const hasValidMessage = message && typeof message === "string" && message.trim().length > 0;
1477
- if (!hasValidTitle) {
1478
- continue;
1479
- }
1480
- const partial = i === suggestions.length - 1 && status !== "complete";
1481
- newSuggestions.push({
1482
- title: title.trim(),
1483
- message: hasValidMessage ? message.trim() : "",
1484
- // Use title as fallback
1485
- partial,
1486
- className: config.className
1487
- });
1488
- }
1489
- setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);
1490
- }
1491
- });
1492
- if ((result == null ? void 0 : result.suggestions) && Array.isArray(result.suggestions)) {
1493
- const validSuggestions = result.suggestions.filter(
1494
- (suggestion) => suggestion && typeof suggestion.title === "string" && suggestion.title.trim().length > 0
1495
- ).map((suggestion) => ({
1496
- title: suggestion.title.trim(),
1497
- message: suggestion.message && typeof suggestion.message === "string" && suggestion.message.trim() ? suggestion.message.trim() : suggestion.title.trim()
1498
- }));
1499
- if (validSuggestions.length > 0) {
1500
- allSuggestions.push(...validSuggestions);
1501
- hasSuccessfulSuggestions = true;
1502
- }
1503
- }
1504
- } catch (error) {
1505
- hasErrors = true;
1506
- lastError = error instanceof Error ? error : new Error(String(error));
1507
- }
1508
- }
1509
- if (hasSuccessfulSuggestions && allSuggestions.length > 0) {
1510
- const uniqueSuggestions = allSuggestions.filter(
1511
- (suggestion, index, self) => index === self.findIndex((s) => s.message === suggestion.message)
1512
- );
1513
- setSuggestionsIfNotAborted(uniqueSuggestions);
1514
- } else if (hasErrors) {
1515
- const errorMessage = lastError ? lastError.message : "Failed to generate suggestions due to API errors";
1516
- throw new Error(errorMessage);
1517
- }
1518
- } catch (error) {
1519
- throw error;
1520
- }
1521
- });
1522
-
1523
1118
  // src/utils/suggestions-constants.ts
1524
1119
  var SUGGESTION_RETRY_CONFIG = {
1525
1120
  MAX_RETRIES: 3,
@@ -1528,11 +1123,11 @@ var SUGGESTION_RETRY_CONFIG = {
1528
1123
  };
1529
1124
 
1530
1125
  // src/components/error-boundary/error-boundary.tsx
1531
- var import_react9 = __toESM(require("react"));
1532
- var import_shared10 = require("@copilotkit/shared");
1126
+ var import_react8 = __toESM(require("react"));
1127
+ var import_shared7 = require("@copilotkit/shared");
1533
1128
 
1534
1129
  // src/lib/status-checker.ts
1535
- var import_shared9 = require("@copilotkit/shared");
1130
+ var import_shared6 = require("@copilotkit/shared");
1536
1131
  var STATUS_CHECK_INTERVAL = 1e3 * 60 * 5;
1537
1132
  var StatusChecker = class {
1538
1133
  constructor() {
@@ -1550,10 +1145,10 @@ var StatusChecker = class {
1550
1145
  clearInterval(this.intervalId);
1551
1146
  const checkStatus = () => __async(this, null, function* () {
1552
1147
  try {
1553
- const response = yield fetch(`${import_shared9.COPILOT_CLOUD_API_URL}/ciu`, {
1148
+ const response = yield fetch(`${import_shared6.COPILOT_CLOUD_API_URL}/ciu`, {
1554
1149
  method: "GET",
1555
1150
  headers: {
1556
- [import_shared9.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey
1151
+ [import_shared6.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey
1557
1152
  }
1558
1153
  }).then((response2) => response2.json());
1559
1154
  this.lastResponse = response;
@@ -1586,7 +1181,7 @@ var StatusChecker = class {
1586
1181
  };
1587
1182
 
1588
1183
  // src/components/error-boundary/error-utils.tsx
1589
- var import_react8 = require("react");
1184
+ var import_react7 = require("react");
1590
1185
 
1591
1186
  // src/components/toast/exclamation-mark-icon.tsx
1592
1187
  var import_jsx_runtime4 = require("react/jsx-runtime");
@@ -1669,9 +1264,9 @@ function ErrorToast({ errors }) {
1669
1264
  }
1670
1265
  function useErrorToast() {
1671
1266
  const { addToast } = useToast();
1672
- return (0, import_react8.useCallback)(
1673
- (error) => {
1674
- const errorId = error.map((err) => {
1267
+ return (0, import_react7.useCallback)(
1268
+ (errors) => {
1269
+ const errorId = errors.map((err) => {
1675
1270
  var _a, _b;
1676
1271
  const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
1677
1272
  const stack = err.stack || "";
@@ -1681,7 +1276,7 @@ function useErrorToast() {
1681
1276
  type: "error",
1682
1277
  id: errorId,
1683
1278
  // Toast libraries typically dedupe by id
1684
- message: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ErrorToast, { errors: error })
1279
+ message: /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(ErrorToast, { errors })
1685
1280
  });
1686
1281
  },
1687
1282
  [addToast]
@@ -1689,7 +1284,7 @@ function useErrorToast() {
1689
1284
  }
1690
1285
  function useAsyncCallback(callback, deps) {
1691
1286
  const addErrorToast = useErrorToast();
1692
- return (0, import_react8.useCallback)((...args) => __async(this, null, function* () {
1287
+ return (0, import_react7.useCallback)((...args) => __async(this, null, function* () {
1693
1288
  try {
1694
1289
  return yield callback(...args);
1695
1290
  } catch (error) {
@@ -1703,7 +1298,7 @@ function useAsyncCallback(callback, deps) {
1703
1298
  // src/components/error-boundary/error-boundary.tsx
1704
1299
  var import_jsx_runtime6 = require("react/jsx-runtime");
1705
1300
  var statusChecker = new StatusChecker();
1706
- var CopilotErrorBoundary = class extends import_react9.default.Component {
1301
+ var CopilotErrorBoundary = class extends import_react8.default.Component {
1707
1302
  constructor(props) {
1708
1303
  super(props);
1709
1304
  this.state = {
@@ -1735,7 +1330,7 @@ var CopilotErrorBoundary = class extends import_react9.default.Component {
1735
1330
  render() {
1736
1331
  var _a, _b, _c, _d;
1737
1332
  if (this.state.hasError) {
1738
- if (this.state.error instanceof import_shared10.CopilotKitError) {
1333
+ if (this.state.error instanceof import_shared7.CopilotKitError) {
1739
1334
  return /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_jsx_runtime6.Fragment, { children: [
1740
1335
  this.props.children,
1741
1336
  this.props.showUsageBanner && /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(
@@ -1755,7 +1350,7 @@ var CopilotErrorBoundary = class extends import_react9.default.Component {
1755
1350
  };
1756
1351
 
1757
1352
  // src/components/dev-console/console-trigger.tsx
1758
- var import_react11 = require("react");
1353
+ var import_react10 = require("react");
1759
1354
 
1760
1355
  // src/components/dev-console/icons.tsx
1761
1356
  var import_jsx_runtime7 = require("react/jsx-runtime");
@@ -1818,14 +1413,14 @@ var CopilotKitIcon = () => /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(
1818
1413
  );
1819
1414
 
1820
1415
  // src/components/dev-console/developer-console-modal.tsx
1821
- var import_shared11 = require("@copilotkit/shared");
1822
- var import_react10 = require("react");
1416
+ var import_shared8 = require("@copilotkit/shared");
1417
+ var import_react9 = require("react");
1823
1418
  var import_jsx_runtime8 = require("react/jsx-runtime");
1824
1419
  function DeveloperConsoleModal({ isOpen, onClose, hasApiKey }) {
1825
1420
  const context = useCopilotContext();
1826
1421
  const messagesContext = useCopilotMessagesContext();
1827
- const [activeTab, setActiveTab] = (0, import_react10.useState)("actions");
1828
- (0, import_react10.useEffect)(() => {
1422
+ const [activeTab, setActiveTab] = (0, import_react9.useState)("actions");
1423
+ (0, import_react9.useEffect)(() => {
1829
1424
  const handleEscape = (e) => {
1830
1425
  if (e.key === "Escape") {
1831
1426
  onClose();
@@ -1990,7 +1585,7 @@ function DeveloperConsoleModal({ isOpen, onClose, hasApiKey }) {
1990
1585
  },
1991
1586
  children: [
1992
1587
  "v",
1993
- import_shared11.COPILOTKIT_VERSION
1588
+ import_shared8.COPILOTKIT_VERSION
1994
1589
  ]
1995
1590
  }
1996
1591
  )
@@ -2566,15 +2161,15 @@ var INSPECTOR_HIDE_KEY = "cpk:inspector:hidden";
2566
2161
  function ConsoleTrigger({ position = "bottom-right" }) {
2567
2162
  const context = useCopilotContext();
2568
2163
  const hasApiKey = Boolean(context.copilotApiConfig.publicApiKey);
2569
- const [isModalOpen, setIsModalOpen] = (0, import_react11.useState)(false);
2570
- const [isHovered, setIsHovered] = (0, import_react11.useState)(false);
2571
- const [isDragging, setIsDragging] = (0, import_react11.useState)(false);
2572
- const [buttonPosition, setButtonPosition] = (0, import_react11.useState)(null);
2573
- const [mounted, setMounted] = (0, import_react11.useState)(false);
2574
- const [isHidden, setIsHidden] = (0, import_react11.useState)(false);
2575
- const dragRef = (0, import_react11.useRef)(null);
2576
- const buttonRef = (0, import_react11.useRef)(null);
2577
- (0, import_react11.useEffect)(() => {
2164
+ const [isModalOpen, setIsModalOpen] = (0, import_react10.useState)(false);
2165
+ const [isHovered, setIsHovered] = (0, import_react10.useState)(false);
2166
+ const [isDragging, setIsDragging] = (0, import_react10.useState)(false);
2167
+ const [buttonPosition, setButtonPosition] = (0, import_react10.useState)(null);
2168
+ const [mounted, setMounted] = (0, import_react10.useState)(false);
2169
+ const [isHidden, setIsHidden] = (0, import_react10.useState)(false);
2170
+ const dragRef = (0, import_react10.useRef)(null);
2171
+ const buttonRef = (0, import_react10.useRef)(null);
2172
+ (0, import_react10.useEffect)(() => {
2578
2173
  setMounted(true);
2579
2174
  try {
2580
2175
  const hidden = typeof window !== "undefined" ? localStorage.getItem(INSPECTOR_HIDE_KEY) : null;
@@ -2605,7 +2200,7 @@ function ConsoleTrigger({ position = "bottom-right" }) {
2605
2200
  };
2606
2201
  setIsDragging(true);
2607
2202
  };
2608
- (0, import_react11.useEffect)(() => {
2203
+ (0, import_react10.useEffect)(() => {
2609
2204
  if (!isDragging)
2610
2205
  return;
2611
2206
  const handleMouseMove = (e) => {
@@ -2776,66 +2371,343 @@ function ConsoleTrigger({ position = "bottom-right" }) {
2776
2371
  ] });
2777
2372
  }
2778
2373
 
2779
- // src/components/copilot-provider/copilotkit.tsx
2374
+ // src/context/coagent-state-renders-context.tsx
2375
+ var import_react11 = require("react");
2780
2376
  var import_jsx_runtime10 = require("react/jsx-runtime");
2781
- function CopilotKit(_a) {
2782
- var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
2783
- const enabled = shouldShowDevConsole(props.showDevConsole);
2784
- const publicApiKey = props.publicApiKey || props.publicLicenseKey;
2785
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(ToastProvider, { enabled, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(CopilotErrorBoundary, { publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children })) }) });
2377
+ var CoAgentStateRendersContext = (0, import_react11.createContext)(
2378
+ void 0
2379
+ );
2380
+ function CoAgentStateRendersProvider({ children }) {
2381
+ const [coAgentStateRenders, setCoAgentStateRenders] = (0, import_react11.useState)({});
2382
+ const setCoAgentStateRender = (0, import_react11.useCallback)((id, stateRender) => {
2383
+ setCoAgentStateRenders((prevPoints) => __spreadProps(__spreadValues({}, prevPoints), {
2384
+ [id]: stateRender
2385
+ }));
2386
+ }, []);
2387
+ const removeCoAgentStateRender = (0, import_react11.useCallback)((id) => {
2388
+ setCoAgentStateRenders((prevPoints) => {
2389
+ const newPoints = __spreadValues({}, prevPoints);
2390
+ delete newPoints[id];
2391
+ return newPoints;
2392
+ });
2393
+ }, []);
2394
+ const claimsRef = (0, import_react11.useRef)({});
2395
+ return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
2396
+ CoAgentStateRendersContext.Provider,
2397
+ {
2398
+ value: {
2399
+ coAgentStateRenders,
2400
+ setCoAgentStateRender,
2401
+ removeCoAgentStateRender,
2402
+ claimsRef
2403
+ },
2404
+ children
2405
+ }
2406
+ );
2786
2407
  }
2787
- function CopilotKitInternal(cpkProps) {
2408
+ function useCoAgentStateRenders() {
2409
+ const context = (0, import_react11.useContext)(CoAgentStateRendersContext);
2410
+ if (!context) {
2411
+ throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
2412
+ }
2413
+ return context;
2414
+ }
2415
+
2416
+ // src/hooks/use-coagent-state-render-bridge.tsx
2417
+ var import_react13 = require("@copilotkitnext/react");
2418
+ var import_react14 = require("react");
2419
+
2420
+ // src/context/threads-context.tsx
2421
+ var import_react12 = require("react");
2422
+ var import_shared9 = require("@copilotkit/shared");
2423
+ var import_jsx_runtime11 = require("react/jsx-runtime");
2424
+ var ThreadsContext = (0, import_react12.createContext)(void 0);
2425
+ function ThreadsProvider({ children, threadId: explicitThreadId }) {
2426
+ const [internalThreadId, setThreadId] = (0, import_react12.useState)(explicitThreadId != null ? explicitThreadId : (0, import_shared9.randomUUID)());
2427
+ const threadId = internalThreadId;
2428
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
2429
+ ThreadsContext.Provider,
2430
+ {
2431
+ value: {
2432
+ threadId,
2433
+ setThreadId
2434
+ },
2435
+ children
2436
+ }
2437
+ );
2438
+ }
2439
+ function useThreads() {
2440
+ const context = (0, import_react12.useContext)(ThreadsContext);
2441
+ if (!context) {
2442
+ throw new Error("useThreads must be used within ThreadsProvider");
2443
+ }
2444
+ return context;
2445
+ }
2446
+
2447
+ // src/hooks/use-coagent-state-render-bridge.tsx
2448
+ var import_shared10 = require("@copilotkit/shared");
2449
+ function getStateWithoutConstantKeys(state) {
2450
+ const _a = state, { messages, tools, copilotkit } = _a, stateWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]);
2451
+ return stateWithoutConstantKeys;
2452
+ }
2453
+ function areStatesEquals(a, b) {
2454
+ if (a && !b || !a && b)
2455
+ return false;
2456
+ const _a = a, { messages, tools, copilotkit } = _a, aWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]);
2457
+ const _b = b, {
2458
+ messages: bMessages,
2459
+ tools: bTools,
2460
+ copilotkit: bCopilotkit
2461
+ } = _b, bWithoutConstantKeys = __objRest(_b, [
2462
+ "messages",
2463
+ "tools",
2464
+ "copilotkit"
2465
+ ]);
2466
+ return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
2467
+ }
2468
+ function useCoagentStateRenderBridge(agentId, props) {
2469
+ var _a;
2470
+ const { stateSnapshot, messageIndexInRun, message } = props;
2471
+ const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
2472
+ const { agent } = (0, import_react13.useAgent)({ agentId });
2473
+ const [nodeName, setNodeName] = (0, import_react14.useState)(void 0);
2474
+ const runId = (_a = props.runId) != null ? _a : message.runId;
2475
+ const effectiveRunId = runId || "pending";
2476
+ (0, import_react14.useEffect)(() => {
2477
+ if (!agent)
2478
+ return;
2479
+ const subscriber = {
2480
+ onStepStartedEvent: ({ event }) => {
2481
+ if (event.stepName !== nodeName) {
2482
+ setNodeName(event.stepName);
2483
+ }
2484
+ },
2485
+ onStepFinishedEvent: ({ event }) => {
2486
+ if (event.stepName === nodeName) {
2487
+ setNodeName(void 0);
2488
+ }
2489
+ }
2490
+ };
2491
+ const { unsubscribe } = agent.subscribe(subscriber);
2492
+ return () => {
2493
+ unsubscribe();
2494
+ };
2495
+ }, [agentId, nodeName]);
2496
+ if (messageIndexInRun !== 0) {
2497
+ return null;
2498
+ }
2499
+ const getStateRender = (0, import_react14.useCallback)(
2500
+ (messageId) => {
2501
+ return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
2502
+ if (claimsRef.current[messageId]) {
2503
+ return stateRenderId === claimsRef.current[messageId].stateRenderId;
2504
+ }
2505
+ const matchingAgentName = stateRender.name === agentId;
2506
+ const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
2507
+ return matchingAgentName && matchesNodeContext;
2508
+ });
2509
+ },
2510
+ [coAgentStateRenders, nodeName, agentId]
2511
+ );
2512
+ const handleRenderRequest = ({
2513
+ stateRenderId,
2514
+ messageId,
2515
+ runId: runId2,
2516
+ stateSnapshot: renderSnapshot
2517
+ }) => {
2518
+ if (claimsRef.current[messageId]) {
2519
+ const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;
2520
+ if (canRender && runId2 && (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === "pending")) {
2521
+ claimsRef.current[messageId].runId = runId2;
2522
+ }
2523
+ return canRender;
2524
+ }
2525
+ const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(
2526
+ (c) => c.stateRenderId === stateRenderId && (0, import_shared10.dataToUUID)(JSON.stringify(getStateWithoutConstantKeys(c.stateSnapshot))) === (0, import_shared10.dataToUUID)(JSON.stringify(getStateWithoutConstantKeys(renderSnapshot)))
2527
+ );
2528
+ if (renderClaimedByOtherMessage) {
2529
+ if (renderSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)) {
2530
+ claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
2531
+ return true;
2532
+ }
2533
+ return false;
2534
+ }
2535
+ if (!runId2) {
2536
+ return false;
2537
+ }
2538
+ claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
2539
+ return true;
2540
+ };
2541
+ return (0, import_react14.useMemo)(() => {
2542
+ var _a2, _b, _c;
2543
+ const [stateRenderId, stateRender] = (_a2 = getStateRender(message.id)) != null ? _a2 : [];
2544
+ if (!stateRender || !stateRenderId) {
2545
+ return null;
2546
+ }
2547
+ const snapshot = stateSnapshot ? (0, import_shared10.parseJson)(stateSnapshot, stateSnapshot) : agent == null ? void 0 : agent.state;
2548
+ const canRender = handleRenderRequest({
2549
+ stateRenderId,
2550
+ messageId: message.id,
2551
+ runId: effectiveRunId,
2552
+ stateSnapshot: snapshot
2553
+ });
2554
+ if (!canRender) {
2555
+ return null;
2556
+ }
2557
+ if (snapshot && !claimsRef.current[message.id].locked) {
2558
+ if (stateSnapshot) {
2559
+ claimsRef.current[message.id].stateSnapshot = snapshot;
2560
+ claimsRef.current[message.id].locked = true;
2561
+ } else {
2562
+ claimsRef.current[message.id].stateSnapshot = snapshot;
2563
+ }
2564
+ }
2565
+ if (stateRender.handler) {
2566
+ stateRender.handler({
2567
+ state: stateSnapshot ? (0, import_shared10.parseJson)(stateSnapshot, stateSnapshot) : (_b = agent == null ? void 0 : agent.state) != null ? _b : {},
2568
+ nodeName: nodeName != null ? nodeName : ""
2569
+ });
2570
+ }
2571
+ if (stateRender.render) {
2572
+ const status = (agent == null ? void 0 : agent.isRunning) ? "inProgress" : "complete";
2573
+ if (typeof stateRender.render === "string")
2574
+ return stateRender.render;
2575
+ return stateRender.render({
2576
+ status,
2577
+ // Always use state from claim, to make sure the state does not seem "wiped" for a fraction of a second
2578
+ state: (_c = claimsRef.current[message.id].stateSnapshot) != null ? _c : {},
2579
+ nodeName: nodeName != null ? nodeName : ""
2580
+ });
2581
+ }
2582
+ }, [
2583
+ getStateRender,
2584
+ stateSnapshot,
2585
+ agent == null ? void 0 : agent.state,
2586
+ agent == null ? void 0 : agent.isRunning,
2587
+ nodeName,
2588
+ effectiveRunId,
2589
+ message.id
2590
+ ]);
2591
+ }
2592
+ function CoAgentStateRenderBridge(props) {
2593
+ return useCoagentStateRenderBridge(props.agentId, props);
2594
+ }
2595
+
2596
+ // src/components/CopilotListeners.tsx
2597
+ var import_react15 = require("react");
2598
+ var import_react16 = require("@copilotkitnext/react");
2599
+ var import_shared11 = require("@copilotkit/shared");
2600
+ var import_shared12 = require("@copilotkit/shared");
2601
+ var usePredictStateSubscription = (agent) => {
2602
+ const predictStateToolsRef = (0, import_react15.useRef)([]);
2603
+ const getSubscriber = (0, import_react15.useCallback)(
2604
+ (agent2) => ({
2605
+ onCustomEvent: ({ event }) => {
2606
+ if (event.name === "PredictState") {
2607
+ predictStateToolsRef.current = event.value;
2608
+ }
2609
+ },
2610
+ onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {
2611
+ predictStateToolsRef.current.forEach((t) => {
2612
+ if ((t == null ? void 0 : t.tool) !== toolCallName)
2613
+ return;
2614
+ const emittedState = typeof partialToolCallArgs === "string" ? (0, import_shared11.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
2615
+ agent2.setState({
2616
+ [t.state_key]: emittedState[t.state_key]
2617
+ });
2618
+ });
2619
+ }
2620
+ }),
2621
+ []
2622
+ );
2623
+ (0, import_react15.useEffect)(() => {
2624
+ if (!agent)
2625
+ return;
2626
+ const subscriber = getSubscriber(agent);
2627
+ const { unsubscribe } = agent.subscribe(subscriber);
2628
+ return () => {
2629
+ unsubscribe();
2630
+ };
2631
+ }, [agent, getSubscriber]);
2632
+ };
2633
+ function CopilotListeners() {
2634
+ var _a, _b;
2635
+ const { copilotkit } = (0, import_react16.useCopilotKit)();
2636
+ const { agentSession } = useCopilotContext();
2637
+ const existingConfig = (0, import_react16.useCopilotChatConfiguration)();
2638
+ const resolvedAgentId = (_b = (_a = agentSession == null ? void 0 : agentSession.agentName) != null ? _a : existingConfig == null ? void 0 : existingConfig.agentId) != null ? _b : "default";
2639
+ const { setBannerError } = useToast();
2640
+ const { agent } = (0, import_react16.useAgent)({ agentId: resolvedAgentId });
2641
+ usePredictStateSubscription(agent);
2642
+ (0, import_react15.useEffect)(() => {
2643
+ const subscriber = {
2644
+ onError: ({ error }) => {
2645
+ setBannerError(new import_shared12.CopilotKitLowLevelError({ error, message: error.message }));
2646
+ }
2647
+ };
2648
+ const subscription = copilotkit.subscribe(subscriber);
2649
+ return () => {
2650
+ subscription.unsubscribe();
2651
+ };
2652
+ }, [copilotkit == null ? void 0 : copilotkit.subscribe]);
2653
+ return null;
2654
+ }
2655
+
2656
+ // src/components/copilot-provider/copilotkit.tsx
2657
+ var import_jsx_runtime12 = require("react/jsx-runtime");
2658
+ function CopilotKit(_a) {
2659
+ var _b = _a, { children } = _b, props = __objRest(_b, ["children"]);
2660
+ const enabled = shouldShowDevConsole(props.showDevConsole);
2661
+ const publicApiKey = props.publicApiKey || props.publicLicenseKey;
2662
+ const renderArr = (0, import_react17.useMemo)(() => [{ render: CoAgentStateRenderBridge }], []);
2663
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(ToastProvider, { enabled, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(CopilotErrorBoundary, { publicApiKey, showUsageBanner: enabled, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(ThreadsProvider, { threadId: props.threadId, children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
2664
+ import_react18.CopilotKitProvider,
2665
+ {
2666
+ runtimeUrl: props.runtimeUrl,
2667
+ renderCustomMessages: renderArr,
2668
+ useSingleEndpoint: true,
2669
+ children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(CopilotKitInternal, __spreadProps(__spreadValues({}, props), { children }))
2670
+ }
2671
+ ) }) }) });
2672
+ }
2673
+ function CopilotKitInternal(cpkProps) {
2788
2674
  var _b;
2789
2675
  const _a = cpkProps, { children } = _a, props = __objRest(_a, ["children"]);
2790
2676
  validateProps(cpkProps);
2791
2677
  const publicApiKey = props.publicLicenseKey || props.publicApiKey;
2792
- const chatApiEndpoint = props.runtimeUrl || import_shared12.COPILOT_CLOUD_CHAT_URL;
2793
- const [actions, setActions] = (0, import_react12.useState)({});
2794
- const [coAgentStateRenders, setCoAgentStateRenders] = (0, import_react12.useState)({});
2795
- const chatComponentsCache = (0, import_react12.useRef)({
2678
+ const chatApiEndpoint = props.runtimeUrl || import_shared13.COPILOT_CLOUD_CHAT_URL;
2679
+ const [actions, setActions] = (0, import_react17.useState)({});
2680
+ const [registeredActionConfigs, setRegisteredActionConfigs] = (0, import_react17.useState)(/* @__PURE__ */ new Map());
2681
+ const chatComponentsCache = (0, import_react17.useRef)({
2796
2682
  actions: {},
2797
2683
  coAgentStateRenders: {}
2798
2684
  });
2799
2685
  const { addElement, removeElement, printTree, getAllElements } = use_tree_default();
2800
- const [isLoading, setIsLoading] = (0, import_react12.useState)(false);
2801
- const [chatInstructions, setChatInstructions] = (0, import_react12.useState)("");
2802
- const [authStates, setAuthStates] = (0, import_react12.useState)({});
2803
- const [extensions, setExtensions] = (0, import_react12.useState)({});
2804
- const [additionalInstructions, setAdditionalInstructions] = (0, import_react12.useState)([]);
2686
+ const [isLoading, setIsLoading] = (0, import_react17.useState)(false);
2687
+ const [chatInstructions, setChatInstructions] = (0, import_react17.useState)("");
2688
+ const [authStates, setAuthStates] = (0, import_react17.useState)({});
2689
+ const [extensions, setExtensions] = (0, import_react17.useState)({});
2690
+ const [additionalInstructions, setAdditionalInstructions] = (0, import_react17.useState)([]);
2805
2691
  const {
2806
2692
  addElement: addDocument,
2807
2693
  removeElement: removeDocument,
2808
2694
  allElements: allDocuments
2809
2695
  } = use_flat_category_store_default();
2810
- const setAction = (0, import_react12.useCallback)((id, action) => {
2696
+ const setAction = (0, import_react17.useCallback)((id, action) => {
2811
2697
  setActions((prevPoints) => {
2812
2698
  return __spreadProps(__spreadValues({}, prevPoints), {
2813
2699
  [id]: action
2814
2700
  });
2815
2701
  });
2816
2702
  }, []);
2817
- const removeAction = (0, import_react12.useCallback)((id) => {
2703
+ const removeAction = (0, import_react17.useCallback)((id) => {
2818
2704
  setActions((prevPoints) => {
2819
2705
  const newPoints = __spreadValues({}, prevPoints);
2820
2706
  delete newPoints[id];
2821
2707
  return newPoints;
2822
2708
  });
2823
2709
  }, []);
2824
- const setCoAgentStateRender = (0, import_react12.useCallback)((id, stateRender) => {
2825
- setCoAgentStateRenders((prevPoints) => {
2826
- return __spreadProps(__spreadValues({}, prevPoints), {
2827
- [id]: stateRender
2828
- });
2829
- });
2830
- }, []);
2831
- const removeCoAgentStateRender = (0, import_react12.useCallback)((id) => {
2832
- setCoAgentStateRenders((prevPoints) => {
2833
- const newPoints = __spreadValues({}, prevPoints);
2834
- delete newPoints[id];
2835
- return newPoints;
2836
- });
2837
- }, []);
2838
- const getContextString = (0, import_react12.useCallback)(
2710
+ const getContextString = (0, import_react17.useCallback)(
2839
2711
  (documents, categories) => {
2840
2712
  const documentsString = documents.map((document2) => {
2841
2713
  return `${document2.name} (${document2.sourceApplication}):
@@ -2848,46 +2720,46 @@ ${nonDocumentStrings}`;
2848
2720
  },
2849
2721
  [printTree]
2850
2722
  );
2851
- const addContext = (0, import_react12.useCallback)(
2723
+ const addContext = (0, import_react17.useCallback)(
2852
2724
  (context, parentId, categories = defaultCopilotContextCategories) => {
2853
2725
  return addElement(context, categories, parentId);
2854
2726
  },
2855
2727
  [addElement]
2856
2728
  );
2857
- const removeContext = (0, import_react12.useCallback)(
2729
+ const removeContext = (0, import_react17.useCallback)(
2858
2730
  (id) => {
2859
2731
  removeElement(id);
2860
2732
  },
2861
2733
  [removeElement]
2862
2734
  );
2863
- const getAllContext = (0, import_react12.useCallback)(() => {
2735
+ const getAllContext = (0, import_react17.useCallback)(() => {
2864
2736
  return getAllElements();
2865
2737
  }, [getAllElements]);
2866
- const getFunctionCallHandler = (0, import_react12.useCallback)(
2738
+ const getFunctionCallHandler = (0, import_react17.useCallback)(
2867
2739
  (customEntryPoints) => {
2868
2740
  return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
2869
2741
  },
2870
2742
  [actions]
2871
2743
  );
2872
- const getDocumentsContext = (0, import_react12.useCallback)(
2744
+ const getDocumentsContext = (0, import_react17.useCallback)(
2873
2745
  (categories) => {
2874
2746
  return allDocuments(categories);
2875
2747
  },
2876
2748
  [allDocuments]
2877
2749
  );
2878
- const addDocumentContext = (0, import_react12.useCallback)(
2750
+ const addDocumentContext = (0, import_react17.useCallback)(
2879
2751
  (documentPointer, categories = defaultCopilotContextCategories) => {
2880
2752
  return addDocument(documentPointer, categories);
2881
2753
  },
2882
2754
  [addDocument]
2883
2755
  );
2884
- const removeDocumentContext = (0, import_react12.useCallback)(
2756
+ const removeDocumentContext = (0, import_react17.useCallback)(
2885
2757
  (documentId) => {
2886
2758
  removeDocument(documentId);
2887
2759
  },
2888
2760
  [removeDocument]
2889
2761
  );
2890
- const copilotApiConfig = (0, import_react12.useMemo)(() => {
2762
+ const copilotApiConfig = (0, import_react17.useMemo)(() => {
2891
2763
  var _a2, _b2;
2892
2764
  let cloud = void 0;
2893
2765
  if (publicApiKey) {
@@ -2923,7 +2795,7 @@ ${nonDocumentStrings}`;
2923
2795
  props.cloudRestrictToTopic,
2924
2796
  props.guardrails_c
2925
2797
  ]);
2926
- const headers = (0, import_react12.useMemo)(() => {
2798
+ const headers = (0, import_react17.useMemo)(() => {
2927
2799
  const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
2928
2800
  if (state.status === "authenticated" && state.authHeaders) {
2929
2801
  return __spreadValues(__spreadValues({}, acc), Object.entries(state.authHeaders).reduce(
@@ -2935,27 +2807,27 @@ ${nonDocumentStrings}`;
2935
2807
  }
2936
2808
  return acc;
2937
2809
  }, {});
2938
- return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared12.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
2810
+ return __spreadValues(__spreadValues(__spreadValues({}, copilotApiConfig.headers || {}), copilotApiConfig.publicApiKey ? { [import_shared13.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {}), authHeaders);
2939
2811
  }, [copilotApiConfig.headers, copilotApiConfig.publicApiKey, authStates]);
2940
- const [internalErrorHandlers, _setInternalErrorHandler] = (0, import_react12.useState)({});
2941
- const setInternalErrorHandler = (0, import_react12.useCallback)((handler) => {
2812
+ const [internalErrorHandlers, _setInternalErrorHandler] = (0, import_react17.useState)({});
2813
+ const setInternalErrorHandler = (0, import_react17.useCallback)((handler) => {
2942
2814
  _setInternalErrorHandler((prev) => __spreadValues(__spreadValues({}, prev), handler));
2943
2815
  }, []);
2944
- const removeInternalErrorHandler = (0, import_react12.useCallback)((key) => {
2816
+ const removeInternalErrorHandler = (0, import_react17.useCallback)((key) => {
2945
2817
  _setInternalErrorHandler((prev) => {
2946
2818
  const _a2 = prev, { [key]: _removed } = _a2, rest = __objRest(_a2, [__restKey(key)]);
2947
2819
  return rest;
2948
2820
  });
2949
2821
  }, []);
2950
- const onErrorRef = (0, import_react12.useRef)(props.onError);
2951
- (0, import_react12.useEffect)(() => {
2822
+ const onErrorRef = (0, import_react17.useRef)(props.onError);
2823
+ (0, import_react17.useEffect)(() => {
2952
2824
  onErrorRef.current = props.onError;
2953
2825
  }, [props.onError]);
2954
- const internalHandlersRef = (0, import_react12.useRef)({});
2955
- (0, import_react12.useEffect)(() => {
2826
+ const internalHandlersRef = (0, import_react17.useRef)({});
2827
+ (0, import_react17.useEffect)(() => {
2956
2828
  internalHandlersRef.current = internalErrorHandlers;
2957
2829
  }, [internalErrorHandlers]);
2958
- const handleErrors = (0, import_react12.useCallback)(
2830
+ const handleErrors = (0, import_react17.useCallback)(
2959
2831
  (error) => __async(this, null, function* () {
2960
2832
  if (copilotApiConfig.publicApiKey && onErrorRef.current) {
2961
2833
  try {
@@ -2975,22 +2847,14 @@ ${nonDocumentStrings}`;
2975
2847
  }),
2976
2848
  [copilotApiConfig.publicApiKey]
2977
2849
  );
2978
- const runtimeClient = useCopilotRuntimeClient({
2979
- url: copilotApiConfig.chatApiEndpoint,
2980
- publicApiKey,
2981
- headers,
2982
- credentials: copilotApiConfig.credentials,
2983
- showDevConsole: shouldShowDevConsole(props.showDevConsole),
2984
- onError: handleErrors
2985
- });
2986
- const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react12.useState)({});
2987
- const addChatSuggestionConfiguration = (0, import_react12.useCallback)(
2850
+ const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, import_react17.useState)({});
2851
+ const addChatSuggestionConfiguration = (0, import_react17.useCallback)(
2988
2852
  (id, suggestion) => {
2989
2853
  setChatSuggestionConfiguration((prev) => __spreadProps(__spreadValues({}, prev), { [id]: suggestion }));
2990
2854
  },
2991
2855
  [setChatSuggestionConfiguration]
2992
2856
  );
2993
- const removeChatSuggestionConfiguration = (0, import_react12.useCallback)(
2857
+ const removeChatSuggestionConfiguration = (0, import_react17.useCallback)(
2994
2858
  (id) => {
2995
2859
  setChatSuggestionConfiguration((prev) => {
2996
2860
  const _a2 = prev, { [id]: _ } = _a2, rest = __objRest(_a2, [__restKey(id)]);
@@ -2999,10 +2863,10 @@ ${nonDocumentStrings}`;
2999
2863
  },
3000
2864
  [setChatSuggestionConfiguration]
3001
2865
  );
3002
- const [availableAgents, setAvailableAgents] = (0, import_react12.useState)([]);
3003
- const [coagentStates, setCoagentStates] = (0, import_react12.useState)({});
3004
- const coagentStatesRef = (0, import_react12.useRef)({});
3005
- const setCoagentStatesWithRef = (0, import_react12.useCallback)(
2866
+ const [availableAgents, setAvailableAgents] = (0, import_react17.useState)([]);
2867
+ const [coagentStates, setCoagentStates] = (0, import_react17.useState)({});
2868
+ const coagentStatesRef = (0, import_react17.useRef)({});
2869
+ const setCoagentStatesWithRef = (0, import_react17.useCallback)(
3006
2870
  (value) => {
3007
2871
  const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
3008
2872
  coagentStatesRef.current = newValue;
@@ -3012,28 +2876,14 @@ ${nonDocumentStrings}`;
3012
2876
  },
3013
2877
  []
3014
2878
  );
3015
- const hasLoadedAgents = (0, import_react12.useRef)(false);
3016
- (0, import_react12.useEffect)(() => {
3017
- if (hasLoadedAgents.current)
3018
- return;
3019
- const fetchData = () => __async(this, null, function* () {
3020
- var _a2;
3021
- const result = yield runtimeClient.availableAgents();
3022
- if ((_a2 = result.data) == null ? void 0 : _a2.availableAgents) {
3023
- setAvailableAgents(result.data.availableAgents.agents);
3024
- }
3025
- hasLoadedAgents.current = true;
3026
- });
3027
- void fetchData();
3028
- }, []);
3029
2879
  let initialAgentSession = null;
3030
2880
  if (props.agent) {
3031
2881
  initialAgentSession = {
3032
2882
  agentName: props.agent
3033
2883
  };
3034
2884
  }
3035
- const [agentSession, setAgentSession] = (0, import_react12.useState)(initialAgentSession);
3036
- (0, import_react12.useEffect)(() => {
2885
+ const [agentSession, setAgentSession] = (0, import_react17.useState)(initialAgentSession);
2886
+ (0, import_react17.useEffect)(() => {
3037
2887
  if (props.agent) {
3038
2888
  setAgentSession({
3039
2889
  agentName: props.agent
@@ -3042,8 +2892,8 @@ ${nonDocumentStrings}`;
3042
2892
  setAgentSession(null);
3043
2893
  }
3044
2894
  }, [props.agent]);
3045
- const [internalThreadId, setInternalThreadId] = (0, import_react12.useState)(props.threadId || (0, import_shared12.randomUUID)());
3046
- const setThreadId = (0, import_react12.useCallback)(
2895
+ const { threadId, setThreadId: setInternalThreadId } = useThreads();
2896
+ const setThreadId = (0, import_react17.useCallback)(
3047
2897
  (value) => {
3048
2898
  if (props.threadId) {
3049
2899
  throw new Error("Cannot call setThreadId() when threadId is provided via props.");
@@ -3052,51 +2902,61 @@ ${nonDocumentStrings}`;
3052
2902
  },
3053
2903
  [props.threadId]
3054
2904
  );
3055
- (0, import_react12.useEffect)(() => {
3056
- if (props.threadId !== void 0) {
3057
- setInternalThreadId(props.threadId);
3058
- }
3059
- }, [props.threadId]);
3060
- const [runId, setRunId] = (0, import_react12.useState)(null);
3061
- const chatAbortControllerRef = (0, import_react12.useRef)(null);
2905
+ const [runId, setRunId] = (0, import_react17.useState)(null);
2906
+ const chatAbortControllerRef = (0, import_react17.useRef)(null);
3062
2907
  const showDevConsole = shouldShowDevConsole(props.showDevConsole);
3063
- const [langGraphInterruptActions, _setLangGraphInterruptAction] = (0, import_react12.useState)({});
3064
- const setLangGraphInterruptAction = (0, import_react12.useCallback)(
3065
- (threadId, action) => {
3066
- _setLangGraphInterruptAction((prev) => {
3067
- var _a2, _b2, _c;
3068
- if (action == null)
3069
- return __spreadProps(__spreadValues({}, prev), {
3070
- [threadId]: null
3071
- });
3072
- let event = (_a2 = prev[threadId]) == null ? void 0 : _a2.event;
3073
- if (action.event) {
3074
- event = __spreadValues(__spreadValues({}, ((_b2 = prev[threadId]) == null ? void 0 : _b2.event) || {}), action.event);
2908
+ const [interruptActions, _setInterruptActions] = (0, import_react17.useState)({});
2909
+ const setInterruptAction = (0, import_react17.useCallback)(
2910
+ (threadId2, action) => {
2911
+ _setInterruptActions((prev) => {
2912
+ var _a2;
2913
+ if (action == null || !action.id) {
2914
+ return prev;
3075
2915
  }
3076
2916
  return __spreadProps(__spreadValues({}, prev), {
3077
- [threadId]: __spreadProps(__spreadValues(__spreadValues({}, (_c = prev[threadId]) != null ? _c : {}), action), { event })
2917
+ [action.id]: __spreadValues(__spreadValues({}, (_a2 = prev[action.id]) != null ? _a2 : {}), action)
3078
2918
  });
3079
2919
  });
3080
2920
  },
3081
2921
  []
3082
2922
  );
3083
- const removeLangGraphInterruptAction = (0, import_react12.useCallback)((threadId) => {
3084
- setLangGraphInterruptAction(threadId, null);
2923
+ const removeInterruptAction = (0, import_react17.useCallback)((actionId) => {
2924
+ _setInterruptActions((prev) => {
2925
+ const _a2 = prev, { [actionId]: _ } = _a2, rest = __objRest(_a2, [__restKey(actionId)]);
2926
+ return rest;
2927
+ });
2928
+ }, []);
2929
+ const [interruptEventQueue, setInterruptEventQueue] = (0, import_react17.useState)({});
2930
+ const addInterruptEvent = (0, import_react17.useCallback)((queuedEvent) => {
2931
+ setInterruptEventQueue((prev) => {
2932
+ const threadQueue = prev[queuedEvent.threadId] || [];
2933
+ return __spreadProps(__spreadValues({}, prev), {
2934
+ [queuedEvent.threadId]: [...threadQueue, queuedEvent]
2935
+ });
2936
+ });
2937
+ }, []);
2938
+ const removeInterruptEvent = (0, import_react17.useCallback)((threadId2, eventId) => {
2939
+ setInterruptEventQueue((prev) => {
2940
+ const threadQueue = prev[threadId2] || [];
2941
+ return __spreadProps(__spreadValues({}, prev), {
2942
+ [threadId2]: threadQueue.filter((event) => event.eventId !== eventId)
2943
+ });
2944
+ });
3085
2945
  }, []);
3086
- const memoizedChildren = (0, import_react12.useMemo)(() => children, [children]);
3087
- const [bannerError, setBannerError] = (0, import_react12.useState)(null);
3088
- const agentLock = (0, import_react12.useMemo)(() => {
2946
+ const memoizedChildren = (0, import_react17.useMemo)(() => children, [children]);
2947
+ const [bannerError, setBannerError] = (0, import_react17.useState)(null);
2948
+ const agentLock = (0, import_react17.useMemo)(() => {
3089
2949
  var _a2;
3090
2950
  return (_a2 = props.agent) != null ? _a2 : null;
3091
2951
  }, [props.agent]);
3092
- const forwardedParameters = (0, import_react12.useMemo)(
2952
+ const forwardedParameters = (0, import_react17.useMemo)(
3093
2953
  () => {
3094
2954
  var _a2;
3095
2955
  return (_a2 = props.forwardedParameters) != null ? _a2 : {};
3096
2956
  },
3097
2957
  [props.forwardedParameters]
3098
2958
  );
3099
- const updateExtensions = (0, import_react12.useCallback)(
2959
+ const updateExtensions = (0, import_react17.useCallback)(
3100
2960
  (newExtensions) => {
3101
2961
  setExtensions((prev) => {
3102
2962
  const resolved = typeof newExtensions === "function" ? newExtensions(prev) : newExtensions;
@@ -3108,7 +2968,7 @@ ${nonDocumentStrings}`;
3108
2968
  },
3109
2969
  [setExtensions]
3110
2970
  );
3111
- const updateAuthStates = (0, import_react12.useCallback)(
2971
+ const updateAuthStates = (0, import_react17.useCallback)(
3112
2972
  (newAuthStates) => {
3113
2973
  setAuthStates((prev) => {
3114
2974
  const resolved = typeof newAuthStates === "function" ? newAuthStates(prev) : newAuthStates;
@@ -3120,81 +2980,115 @@ ${nonDocumentStrings}`;
3120
2980
  },
3121
2981
  [setAuthStates]
3122
2982
  );
3123
- return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
3124
- CopilotContext.Provider,
2983
+ const handleSetRegisteredActions = (0, import_react17.useCallback)((actionConfig) => {
2984
+ const key = actionConfig.action.name || (0, import_shared13.randomUUID)();
2985
+ setRegisteredActionConfigs((prev) => {
2986
+ const newMap = new Map(prev);
2987
+ newMap.set(key, actionConfig);
2988
+ return newMap;
2989
+ });
2990
+ return key;
2991
+ }, []);
2992
+ const handleRemoveRegisteredAction = (0, import_react17.useCallback)((actionKey) => {
2993
+ setRegisteredActionConfigs((prev) => {
2994
+ const newMap = new Map(prev);
2995
+ newMap.delete(actionKey);
2996
+ return newMap;
2997
+ });
2998
+ }, []);
2999
+ const RegisteredActionsRenderer = (0, import_react17.useMemo)(() => {
3000
+ return () => /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_jsx_runtime12.Fragment, { children: Array.from(registeredActionConfigs.entries()).map(([key, config]) => {
3001
+ const Component = config.component;
3002
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(Component, { action: config.action }, key);
3003
+ }) });
3004
+ }, [registeredActionConfigs]);
3005
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
3006
+ import_react18.CopilotChatConfigurationProvider,
3125
3007
  {
3126
- value: {
3127
- actions,
3128
- chatComponentsCache,
3129
- getFunctionCallHandler,
3130
- setAction,
3131
- removeAction,
3132
- coAgentStateRenders,
3133
- setCoAgentStateRender,
3134
- removeCoAgentStateRender,
3135
- getContextString,
3136
- addContext,
3137
- removeContext,
3138
- getAllContext,
3139
- getDocumentsContext,
3140
- addDocumentContext,
3141
- removeDocumentContext,
3142
- copilotApiConfig,
3143
- isLoading,
3144
- setIsLoading,
3145
- chatSuggestionConfiguration,
3146
- addChatSuggestionConfiguration,
3147
- removeChatSuggestionConfiguration,
3148
- chatInstructions,
3149
- setChatInstructions,
3150
- additionalInstructions,
3151
- setAdditionalInstructions,
3152
- showDevConsole,
3153
- coagentStates,
3154
- setCoagentStates,
3155
- coagentStatesRef,
3156
- setCoagentStatesWithRef,
3157
- agentSession,
3158
- setAgentSession,
3159
- runtimeClient,
3160
- forwardedParameters,
3161
- agentLock,
3162
- threadId: internalThreadId,
3163
- setThreadId,
3164
- runId,
3165
- setRunId,
3166
- chatAbortControllerRef,
3167
- availableAgents,
3168
- authConfig_c: props.authConfig_c,
3169
- authStates_c: authStates,
3170
- setAuthStates_c: updateAuthStates,
3171
- extensions,
3172
- setExtensions: updateExtensions,
3173
- langGraphInterruptAction: (_b = langGraphInterruptActions[internalThreadId]) != null ? _b : null,
3174
- setLangGraphInterruptAction,
3175
- removeLangGraphInterruptAction,
3176
- bannerError,
3177
- setBannerError,
3178
- onError: handleErrors,
3179
- internalErrorHandlers,
3180
- setInternalErrorHandler,
3181
- removeInternalErrorHandler
3182
- },
3183
- children: [
3184
- /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(MessagesTapProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(CopilotMessages, { children: [
3185
- memoizedChildren,
3186
- showDevConsole && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(ConsoleTrigger, {})
3187
- ] }) }),
3188
- bannerError && showDevConsole && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
3189
- UsageBanner,
3190
- {
3191
- severity: bannerError.severity,
3192
- message: bannerError.message,
3193
- onClose: () => setBannerError(null),
3194
- actions: getErrorActions(bannerError)
3195
- }
3196
- )
3197
- ]
3008
+ agentId: (_b = agentSession == null ? void 0 : agentSession.agentName) != null ? _b : "default",
3009
+ threadId,
3010
+ children: /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(
3011
+ CopilotContext.Provider,
3012
+ {
3013
+ value: {
3014
+ actions,
3015
+ chatComponentsCache,
3016
+ getFunctionCallHandler,
3017
+ setAction,
3018
+ removeAction,
3019
+ setRegisteredActions: handleSetRegisteredActions,
3020
+ removeRegisteredAction: handleRemoveRegisteredAction,
3021
+ getContextString,
3022
+ addContext,
3023
+ removeContext,
3024
+ getAllContext,
3025
+ getDocumentsContext,
3026
+ addDocumentContext,
3027
+ removeDocumentContext,
3028
+ copilotApiConfig,
3029
+ isLoading,
3030
+ setIsLoading,
3031
+ chatSuggestionConfiguration,
3032
+ addChatSuggestionConfiguration,
3033
+ removeChatSuggestionConfiguration,
3034
+ chatInstructions,
3035
+ setChatInstructions,
3036
+ additionalInstructions,
3037
+ setAdditionalInstructions,
3038
+ showDevConsole,
3039
+ coagentStates,
3040
+ setCoagentStates,
3041
+ coagentStatesRef,
3042
+ setCoagentStatesWithRef,
3043
+ agentSession,
3044
+ setAgentSession,
3045
+ forwardedParameters,
3046
+ agentLock,
3047
+ threadId,
3048
+ setThreadId,
3049
+ runId,
3050
+ setRunId,
3051
+ chatAbortControllerRef,
3052
+ availableAgents,
3053
+ authConfig_c: props.authConfig_c,
3054
+ authStates_c: authStates,
3055
+ setAuthStates_c: updateAuthStates,
3056
+ extensions,
3057
+ setExtensions: updateExtensions,
3058
+ interruptActions,
3059
+ setInterruptAction,
3060
+ removeInterruptAction,
3061
+ interruptEventQueue,
3062
+ addInterruptEvent,
3063
+ removeInterruptEvent,
3064
+ bannerError,
3065
+ setBannerError,
3066
+ onError: handleErrors,
3067
+ internalErrorHandlers,
3068
+ setInternalErrorHandler,
3069
+ removeInternalErrorHandler
3070
+ },
3071
+ children: [
3072
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(CopilotListeners, {}),
3073
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(CoAgentStateRendersProvider, { children: [
3074
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(MessagesTapProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime12.jsxs)(CopilotMessages, { children: [
3075
+ memoizedChildren,
3076
+ showDevConsole && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(ConsoleTrigger, {}),
3077
+ /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(RegisteredActionsRenderer, {})
3078
+ ] }) }),
3079
+ bannerError && showDevConsole && /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
3080
+ UsageBanner,
3081
+ {
3082
+ severity: bannerError.severity,
3083
+ message: bannerError.message,
3084
+ onClose: () => setBannerError(null),
3085
+ actions: getErrorActions(bannerError)
3086
+ }
3087
+ )
3088
+ ] })
3089
+ ]
3090
+ }
3091
+ )
3198
3092
  }
3199
3093
  );
3200
3094
  }
@@ -3231,588 +3125,656 @@ function validateProps(props) {
3231
3125
  const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c"));
3232
3126
  const hasApiKey = props.publicApiKey || props.publicLicenseKey;
3233
3127
  if (!props.runtimeUrl && !hasApiKey) {
3234
- throw new import_shared12.ConfigurationError(
3128
+ throw new import_shared13.ConfigurationError(
3235
3129
  "Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'"
3236
3130
  );
3237
3131
  }
3238
3132
  if (cloudFeatures.length > 0 && !hasApiKey) {
3239
- throw new import_shared12.MissingPublicApiKeyError(
3133
+ throw new import_shared13.MissingPublicApiKeyError(
3240
3134
  `Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}`
3241
3135
  );
3242
3136
  }
3243
3137
  }
3244
3138
 
3245
3139
  // src/hooks/use-copilot-chat_internal.ts
3246
- var import_react15 = require("react");
3140
+ var import_react24 = require("react");
3141
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
3247
3142
 
3248
- // src/hooks/use-chat.ts
3249
- var import_react13 = require("react");
3250
- var import_react_dom2 = require("react-dom");
3143
+ // src/hooks/use-langgraph-interrupt-render.ts
3144
+ var import_react19 = __toESM(require("react"));
3145
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
3251
3146
  var import_shared14 = require("@copilotkit/shared");
3252
- var import_runtime_client_gql7 = require("@copilotkit/runtime-client-gql");
3253
-
3254
- // src/types/frontend-action.ts
3255
- var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
3256
- var import_shared13 = require("@copilotkit/shared");
3257
- function processActionsForRuntimeRequest(actions) {
3258
- const filteredActions = actions.filter(
3259
- (action) => action.available !== import_runtime_client_gql6.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
3260
- ).map((action) => {
3261
- let available = import_runtime_client_gql6.ActionInputAvailability.Enabled;
3262
- if (action.disabled) {
3263
- available = import_runtime_client_gql6.ActionInputAvailability.Disabled;
3264
- } else if (action.available === "disabled") {
3265
- available = import_runtime_client_gql6.ActionInputAvailability.Disabled;
3266
- } else if (action.available === "remote") {
3267
- available = import_runtime_client_gql6.ActionInputAvailability.Remote;
3268
- }
3269
- return {
3270
- name: action.name,
3271
- description: action.description || "",
3272
- jsonSchema: JSON.stringify((0, import_shared13.actionParametersToJsonSchema)(action.parameters || [])),
3273
- available
3274
- };
3275
- });
3276
- return filteredActions;
3277
- }
3278
-
3279
- // src/hooks/use-chat.ts
3280
- function useChat(options) {
3147
+ var InterruptRenderer = ({ event, result, render, resolve }) => {
3148
+ return render({ event, result, resolve });
3149
+ };
3150
+ function useLangGraphInterruptRender(agent) {
3281
3151
  const {
3282
- messages,
3283
- setMessages,
3284
- makeSystemMessageCallback,
3285
- copilotConfig,
3286
- setIsLoading,
3287
- initialMessages,
3288
- isLoading,
3289
- actions,
3290
- onFunctionCall,
3291
- onCoAgentStateRender,
3292
- setCoagentStatesWithRef,
3293
- coagentStatesRef,
3152
+ interruptActions,
3294
3153
  agentSession,
3295
- setAgentSession,
3296
3154
  threadId,
3297
- setThreadId,
3298
- runId,
3299
- setRunId,
3300
- chatAbortControllerRef,
3301
- agentLock,
3302
- extensions,
3303
- setExtensions,
3304
- langGraphInterruptAction,
3305
- setLangGraphInterruptAction,
3306
- disableSystemMessage = false
3307
- } = options;
3308
- const runChatCompletionRef = (0, import_react13.useRef)();
3309
- const addErrorToast = useErrorToast();
3310
- const { setBannerError } = useToast();
3311
- const { onError, showDevConsole, getAllContext } = useCopilotContext();
3312
- const copilotReadableContext = getAllContext();
3313
- const context = (0, import_react13.useMemo)(
3314
- () => copilotReadableContext.map((contextItem) => {
3315
- const [description, ...valueParts] = contextItem.value.split(":");
3316
- return {
3317
- description: description.trim(),
3318
- value: valueParts.join(":").trim()
3319
- };
3320
- }),
3321
- [copilotReadableContext]
3322
- );
3323
- const traceUIError = (error, originalError) => __async(this, null, function* () {
3324
- try {
3325
- const traceEvent = {
3326
- type: "error",
3327
- timestamp: Date.now(),
3328
- context: {
3329
- source: "ui",
3330
- request: {
3331
- operation: "useChatCompletion",
3332
- url: copilotConfig.chatApiEndpoint,
3333
- startTime: Date.now()
3334
- },
3335
- technical: {
3336
- environment: "browser",
3337
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
3338
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
3155
+ interruptEventQueue,
3156
+ addInterruptEvent,
3157
+ removeInterruptEvent
3158
+ } = useCopilotContext();
3159
+ (0, import_react19.useEffect)(() => {
3160
+ if (!agent)
3161
+ return;
3162
+ const subscriber = {
3163
+ onCustomEvent: ({ event }) => {
3164
+ if (event.name === "on_interrupt") {
3165
+ const eventData = {
3166
+ name: import_runtime_client_gql.MetaEventName.LangGraphInterruptEvent,
3167
+ type: event.type,
3168
+ value: (0, import_shared14.parseJson)(event.value, event.value)
3169
+ };
3170
+ const eventId = (0, import_shared14.dataToUUID)(JSON.stringify(eventData), "interruptEvents");
3171
+ addInterruptEvent({
3172
+ eventId,
3173
+ threadId,
3174
+ event: eventData
3175
+ });
3176
+ }
3177
+ }
3178
+ };
3179
+ const { unsubscribe } = agent.subscribe(subscriber);
3180
+ return () => {
3181
+ unsubscribe();
3182
+ };
3183
+ }, [agent, threadId]);
3184
+ const handleResolve = (0, import_react19.useCallback)(
3185
+ (eventId, response) => {
3186
+ agent == null ? void 0 : agent.runAgent({
3187
+ forwardedProps: {
3188
+ command: {
3189
+ resume: response
3339
3190
  }
3340
- },
3341
- error
3342
- };
3343
- yield onError(traceEvent);
3344
- } catch (traceError) {
3345
- console.error("Error in use-chat onError handler:", traceError);
3191
+ }
3192
+ });
3193
+ removeInterruptEvent(threadId, eventId);
3194
+ },
3195
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3196
+ [agent, threadId]
3197
+ );
3198
+ return (0, import_react19.useMemo)(() => {
3199
+ const eventQueue = interruptEventQueue[threadId] || [];
3200
+ const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);
3201
+ if (!currentQueuedEvent)
3202
+ return null;
3203
+ const allActions = Object.values(interruptActions);
3204
+ const matchingAction = allActions.find((action) => {
3205
+ if (!action.enabled)
3206
+ return true;
3207
+ return action.enabled({
3208
+ eventValue: currentQueuedEvent.event.value,
3209
+ agentMetadata: agentSession
3210
+ });
3211
+ });
3212
+ if (!matchingAction)
3213
+ return null;
3214
+ const { render, handler } = matchingAction;
3215
+ const resolveInterrupt = (response) => {
3216
+ handleResolve(currentQueuedEvent.eventId, response);
3217
+ };
3218
+ let result = null;
3219
+ if (handler) {
3220
+ result = handler({
3221
+ event: currentQueuedEvent.event,
3222
+ resolve: resolveInterrupt
3223
+ });
3346
3224
  }
3225
+ if (!render)
3226
+ return null;
3227
+ return import_react19.default.createElement(InterruptRenderer, {
3228
+ event: currentQueuedEvent.event,
3229
+ result,
3230
+ render,
3231
+ resolve: resolveInterrupt
3232
+ });
3233
+ }, [interruptActions, interruptEventQueue, threadId, agentSession, handleResolve]);
3234
+ }
3235
+
3236
+ // src/hooks/use-copilot-chat_internal.ts
3237
+ var import_react25 = require("@copilotkitnext/react");
3238
+
3239
+ // src/hooks/use-lazy-tool-renderer.tsx
3240
+ var import_react20 = require("@copilotkitnext/react");
3241
+ var import_react21 = require("react");
3242
+ function useLazyToolRenderer() {
3243
+ const renderToolCall = (0, import_react20.useRenderToolCall)();
3244
+ return (0, import_react21.useCallback)(
3245
+ (message, messages) => {
3246
+ var _a;
3247
+ if (!((_a = message == null ? void 0 : message.toolCalls) == null ? void 0 : _a.length))
3248
+ return null;
3249
+ const toolCall = message.toolCalls[0];
3250
+ if (!toolCall)
3251
+ return null;
3252
+ const toolMessage = messages == null ? void 0 : messages.find(
3253
+ (m) => m.role === "tool" && m.toolCallId === toolCall.id
3254
+ );
3255
+ return () => renderToolCall({
3256
+ toolCall,
3257
+ toolMessage
3258
+ });
3259
+ },
3260
+ [renderToolCall]
3261
+ );
3262
+ }
3263
+
3264
+ // src/hooks/use-configure-chat-suggestions.tsx
3265
+ var import_react22 = require("@copilotkitnext/react");
3266
+ var import_react23 = require("react");
3267
+ function useConfigureChatSuggestions(config, dependencies = []) {
3268
+ const { agentSession } = useCopilotContext();
3269
+ const { copilotkit } = (0, import_react22.useCopilotKit)();
3270
+ const available = config.available === "enabled" ? "always" : config.available;
3271
+ const finalSuggestionConfig = __spreadProps(__spreadValues({}, config), {
3272
+ available,
3273
+ consumerAgentId: agentSession == null ? void 0 : agentSession.agentName
3274
+ // Use chatConfig.agentId here
3347
3275
  });
3348
- const agentSessionRef = (0, import_react13.useRef)(agentSession);
3349
- agentSessionRef.current = agentSession;
3350
- const runIdRef = (0, import_react13.useRef)(runId);
3351
- runIdRef.current = runId;
3352
- const extensionsRef = (0, import_react13.useRef)(extensions);
3353
- extensionsRef.current = extensions;
3354
- const publicApiKey = copilotConfig.publicApiKey;
3355
- const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared14.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
3356
- const runtimeClient = useCopilotRuntimeClient({
3357
- url: copilotConfig.chatApiEndpoint,
3358
- publicApiKey: copilotConfig.publicApiKey,
3359
- headers,
3360
- credentials: copilotConfig.credentials,
3361
- showDevConsole,
3362
- onError
3363
- });
3364
- const pendingAppendsRef = (0, import_react13.useRef)([]);
3365
- const runChatCompletion = useAsyncCallback(
3366
- (previousMessages) => __async(this, null, function* () {
3367
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
3368
- setIsLoading(true);
3369
- const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
3370
- if ((interruptEvent == null ? void 0 : interruptEvent.name) === import_runtime_client_gql7.MetaEventName.LangGraphInterruptEvent && (interruptEvent == null ? void 0 : interruptEvent.value) && !(interruptEvent == null ? void 0 : interruptEvent.response) && agentSessionRef.current) {
3371
- addErrorToast([
3372
- new Error(
3373
- "A message was sent while interrupt is active. This will cause failure on the agent side"
3374
- )
3375
- ]);
3376
- }
3377
- let newMessages = [
3378
- new import_runtime_client_gql7.TextMessage({
3379
- content: "",
3380
- role: import_runtime_client_gql7.Role.Assistant
3381
- })
3382
- ];
3383
- chatAbortControllerRef.current = new AbortController();
3384
- setMessages([...previousMessages, ...newMessages]);
3385
- const messagesWithContext = disableSystemMessage ? [...initialMessages || [], ...previousMessages] : [makeSystemMessageCallback(), ...initialMessages || [], ...previousMessages];
3386
- const finalProperties = __spreadValues({}, copilotConfig.properties || {});
3387
- let mcpServersToUse = null;
3388
- if (copilotConfig.mcpServers && Array.isArray(copilotConfig.mcpServers) && copilotConfig.mcpServers.length > 0) {
3389
- mcpServersToUse = copilotConfig.mcpServers;
3390
- } else if (((_a = copilotConfig.properties) == null ? void 0 : _a.mcpServers) && Array.isArray(copilotConfig.properties.mcpServers) && copilotConfig.properties.mcpServers.length > 0) {
3391
- mcpServersToUse = copilotConfig.properties.mcpServers;
3392
- }
3393
- if (mcpServersToUse) {
3394
- finalProperties.mcpServers = mcpServersToUse;
3395
- copilotConfig.mcpServers = mcpServersToUse;
3276
+ (0, import_react22.useConfigureSuggestions)(finalSuggestionConfig, { deps: dependencies });
3277
+ const result = (0, import_react22.useSuggestions)({ agentId: agentSession == null ? void 0 : agentSession.agentName });
3278
+ (0, import_react23.useEffect)(() => {
3279
+ if (finalSuggestionConfig.available === "disabled")
3280
+ return;
3281
+ const subscription = copilotkit.subscribe({
3282
+ onAgentsChanged: () => {
3283
+ const agent = copilotkit.getAgent(agentSession == null ? void 0 : agentSession.agentName);
3284
+ if (agent && !agent.isRunning && !result.suggestions.length) {
3285
+ copilotkit.reloadSuggestions(agentSession == null ? void 0 : agentSession.agentName);
3286
+ }
3396
3287
  }
3397
- const isAgentRun = agentSessionRef.current !== null;
3398
- const stream = runtimeClient.asStream(
3399
- runtimeClient.generateCopilotResponse({
3400
- data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
3401
- frontend: {
3402
- actions: processActionsForRuntimeRequest(actions),
3403
- url: window.location.href
3404
- },
3405
- threadId,
3406
- runId: runIdRef.current,
3407
- extensions: extensionsRef.current,
3408
- metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event]),
3409
- messages: (0, import_runtime_client_gql7.convertMessagesToGqlInput)((0, import_runtime_client_gql7.filterAgentStateMessages)(messagesWithContext))
3410
- }, copilotConfig.cloud ? {
3411
- cloud: __spreadValues({}, ((_d = (_c = (_b = copilotConfig.cloud.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic) == null ? void 0 : _d.enabled) ? {
3412
- guardrails: {
3413
- inputValidationRules: {
3414
- allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
3415
- denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
3416
- }
3417
- }
3418
- } : {})
3419
- } : {}), {
3420
- metadata: {
3421
- requestType: import_runtime_client_gql7.CopilotRequestType.Chat
3422
- }
3423
- }), agentSessionRef.current ? {
3424
- agentSession: agentSessionRef.current
3425
- } : {}), {
3426
- agentStates: Object.values(coagentStatesRef.current).map((state) => {
3427
- const stateObject = {
3428
- agentName: state.name,
3429
- state: JSON.stringify(state.state)
3430
- };
3431
- if (state.config !== void 0) {
3432
- stateObject.config = JSON.stringify(state.config);
3433
- }
3434
- return stateObject;
3435
- }),
3436
- forwardedParameters: options.forwardedParameters || {},
3437
- context
3438
- }),
3439
- properties: finalProperties,
3440
- signal: (_e = chatAbortControllerRef.current) == null ? void 0 : _e.signal
3441
- })
3442
- );
3443
- const guardrailsEnabled = ((_h = (_g = (_f = copilotConfig.cloud) == null ? void 0 : _f.guardrails) == null ? void 0 : _g.input) == null ? void 0 : _h.restrictToTopic.enabled) || false;
3444
- const reader = stream.getReader();
3445
- let executedCoAgentStateRenders = [];
3446
- let followUp = void 0;
3447
- let messages2 = [];
3448
- let syncedMessages = [];
3449
- let interruptMessages = [];
3288
+ });
3289
+ return () => {
3290
+ subscription.unsubscribe();
3291
+ };
3292
+ }, []);
3293
+ return result;
3294
+ }
3295
+
3296
+ // ../../node_modules/.pnpm/@ag-ui+core@0.0.42-alpha.1/node_modules/@ag-ui/core/dist/index.mjs
3297
+ var import_zod = require("zod");
3298
+ var import_zod2 = require("zod");
3299
+ var FunctionCallSchema = import_zod.z.object({
3300
+ name: import_zod.z.string(),
3301
+ arguments: import_zod.z.string()
3302
+ });
3303
+ var ToolCallSchema = import_zod.z.object({
3304
+ id: import_zod.z.string(),
3305
+ type: import_zod.z.literal("function"),
3306
+ function: FunctionCallSchema
3307
+ });
3308
+ var BaseMessageSchema = import_zod.z.object({
3309
+ id: import_zod.z.string(),
3310
+ role: import_zod.z.string(),
3311
+ content: import_zod.z.string().optional(),
3312
+ name: import_zod.z.string().optional()
3313
+ });
3314
+ var TextInputContentSchema = import_zod.z.object({
3315
+ type: import_zod.z.literal("text"),
3316
+ text: import_zod.z.string()
3317
+ });
3318
+ var BinaryInputContentObjectSchema = import_zod.z.object({
3319
+ type: import_zod.z.literal("binary"),
3320
+ mimeType: import_zod.z.string(),
3321
+ id: import_zod.z.string().optional(),
3322
+ url: import_zod.z.string().optional(),
3323
+ data: import_zod.z.string().optional(),
3324
+ filename: import_zod.z.string().optional()
3325
+ });
3326
+ var ensureBinaryPayload = (value, ctx) => {
3327
+ if (!value.id && !value.url && !value.data) {
3328
+ ctx.addIssue({
3329
+ code: import_zod.z.ZodIssueCode.custom,
3330
+ message: "BinaryInputContent requires at least one of id, url, or data.",
3331
+ path: ["id"]
3332
+ });
3333
+ }
3334
+ };
3335
+ var BinaryInputContentSchema = BinaryInputContentObjectSchema.superRefine((value, ctx) => {
3336
+ ensureBinaryPayload(value, ctx);
3337
+ });
3338
+ var InputContentBaseSchema = import_zod.z.discriminatedUnion("type", [
3339
+ TextInputContentSchema,
3340
+ BinaryInputContentObjectSchema
3341
+ ]);
3342
+ var InputContentSchema = InputContentBaseSchema.superRefine((value, ctx) => {
3343
+ if (value.type === "binary") {
3344
+ ensureBinaryPayload(value, ctx);
3345
+ }
3346
+ });
3347
+ var DeveloperMessageSchema = BaseMessageSchema.extend({
3348
+ role: import_zod.z.literal("developer"),
3349
+ content: import_zod.z.string()
3350
+ });
3351
+ var SystemMessageSchema = BaseMessageSchema.extend({
3352
+ role: import_zod.z.literal("system"),
3353
+ content: import_zod.z.string()
3354
+ });
3355
+ var AssistantMessageSchema = BaseMessageSchema.extend({
3356
+ role: import_zod.z.literal("assistant"),
3357
+ content: import_zod.z.string().optional(),
3358
+ toolCalls: import_zod.z.array(ToolCallSchema).optional()
3359
+ });
3360
+ var UserMessageSchema = BaseMessageSchema.extend({
3361
+ role: import_zod.z.literal("user"),
3362
+ content: import_zod.z.union([import_zod.z.string(), import_zod.z.array(InputContentSchema)])
3363
+ });
3364
+ var ToolMessageSchema = import_zod.z.object({
3365
+ id: import_zod.z.string(),
3366
+ content: import_zod.z.string(),
3367
+ role: import_zod.z.literal("tool"),
3368
+ toolCallId: import_zod.z.string(),
3369
+ error: import_zod.z.string().optional()
3370
+ });
3371
+ var ActivityMessageSchema = import_zod.z.object({
3372
+ id: import_zod.z.string(),
3373
+ role: import_zod.z.literal("activity"),
3374
+ activityType: import_zod.z.string(),
3375
+ content: import_zod.z.record(import_zod.z.any())
3376
+ });
3377
+ var MessageSchema = import_zod.z.discriminatedUnion("role", [
3378
+ DeveloperMessageSchema,
3379
+ SystemMessageSchema,
3380
+ AssistantMessageSchema,
3381
+ UserMessageSchema,
3382
+ ToolMessageSchema,
3383
+ ActivityMessageSchema
3384
+ ]);
3385
+ var RoleSchema = import_zod.z.union([
3386
+ import_zod.z.literal("developer"),
3387
+ import_zod.z.literal("system"),
3388
+ import_zod.z.literal("assistant"),
3389
+ import_zod.z.literal("user"),
3390
+ import_zod.z.literal("tool"),
3391
+ import_zod.z.literal("activity")
3392
+ ]);
3393
+ var ContextSchema = import_zod.z.object({
3394
+ description: import_zod.z.string(),
3395
+ value: import_zod.z.string()
3396
+ });
3397
+ var ToolSchema = import_zod.z.object({
3398
+ name: import_zod.z.string(),
3399
+ description: import_zod.z.string(),
3400
+ parameters: import_zod.z.any()
3401
+ // JSON Schema for the tool parameters
3402
+ });
3403
+ var RunAgentInputSchema = import_zod.z.object({
3404
+ threadId: import_zod.z.string(),
3405
+ runId: import_zod.z.string(),
3406
+ parentRunId: import_zod.z.string().optional(),
3407
+ state: import_zod.z.any(),
3408
+ messages: import_zod.z.array(MessageSchema),
3409
+ tools: import_zod.z.array(ToolSchema),
3410
+ context: import_zod.z.array(ContextSchema),
3411
+ forwardedProps: import_zod.z.any()
3412
+ });
3413
+ var StateSchema = import_zod.z.any();
3414
+ var AGUIError = class extends Error {
3415
+ constructor(message) {
3416
+ super(message);
3417
+ }
3418
+ };
3419
+ var AGUIConnectNotImplementedError = class extends AGUIError {
3420
+ constructor() {
3421
+ super("Connect not implemented. This method is not supported by the current agent.");
3422
+ }
3423
+ };
3424
+ var TextMessageRoleSchema = import_zod2.z.union([
3425
+ import_zod2.z.literal("developer"),
3426
+ import_zod2.z.literal("system"),
3427
+ import_zod2.z.literal("assistant"),
3428
+ import_zod2.z.literal("user")
3429
+ ]);
3430
+ var EventType = /* @__PURE__ */ ((EventType2) => {
3431
+ EventType2["TEXT_MESSAGE_START"] = "TEXT_MESSAGE_START";
3432
+ EventType2["TEXT_MESSAGE_CONTENT"] = "TEXT_MESSAGE_CONTENT";
3433
+ EventType2["TEXT_MESSAGE_END"] = "TEXT_MESSAGE_END";
3434
+ EventType2["TEXT_MESSAGE_CHUNK"] = "TEXT_MESSAGE_CHUNK";
3435
+ EventType2["THINKING_TEXT_MESSAGE_START"] = "THINKING_TEXT_MESSAGE_START";
3436
+ EventType2["THINKING_TEXT_MESSAGE_CONTENT"] = "THINKING_TEXT_MESSAGE_CONTENT";
3437
+ EventType2["THINKING_TEXT_MESSAGE_END"] = "THINKING_TEXT_MESSAGE_END";
3438
+ EventType2["TOOL_CALL_START"] = "TOOL_CALL_START";
3439
+ EventType2["TOOL_CALL_ARGS"] = "TOOL_CALL_ARGS";
3440
+ EventType2["TOOL_CALL_END"] = "TOOL_CALL_END";
3441
+ EventType2["TOOL_CALL_CHUNK"] = "TOOL_CALL_CHUNK";
3442
+ EventType2["TOOL_CALL_RESULT"] = "TOOL_CALL_RESULT";
3443
+ EventType2["THINKING_START"] = "THINKING_START";
3444
+ EventType2["THINKING_END"] = "THINKING_END";
3445
+ EventType2["STATE_SNAPSHOT"] = "STATE_SNAPSHOT";
3446
+ EventType2["STATE_DELTA"] = "STATE_DELTA";
3447
+ EventType2["MESSAGES_SNAPSHOT"] = "MESSAGES_SNAPSHOT";
3448
+ EventType2["ACTIVITY_SNAPSHOT"] = "ACTIVITY_SNAPSHOT";
3449
+ EventType2["ACTIVITY_DELTA"] = "ACTIVITY_DELTA";
3450
+ EventType2["RAW"] = "RAW";
3451
+ EventType2["CUSTOM"] = "CUSTOM";
3452
+ EventType2["RUN_STARTED"] = "RUN_STARTED";
3453
+ EventType2["RUN_FINISHED"] = "RUN_FINISHED";
3454
+ EventType2["RUN_ERROR"] = "RUN_ERROR";
3455
+ EventType2["STEP_STARTED"] = "STEP_STARTED";
3456
+ EventType2["STEP_FINISHED"] = "STEP_FINISHED";
3457
+ return EventType2;
3458
+ })(EventType || {});
3459
+ var BaseEventSchema = import_zod2.z.object({
3460
+ type: import_zod2.z.nativeEnum(EventType),
3461
+ timestamp: import_zod2.z.number().optional(),
3462
+ rawEvent: import_zod2.z.any().optional()
3463
+ });
3464
+ var TextMessageStartEventSchema = BaseEventSchema.extend({
3465
+ type: import_zod2.z.literal(
3466
+ "TEXT_MESSAGE_START"
3467
+ /* TEXT_MESSAGE_START */
3468
+ ),
3469
+ messageId: import_zod2.z.string(),
3470
+ role: TextMessageRoleSchema.default("assistant")
3471
+ });
3472
+ var TextMessageContentEventSchema = BaseEventSchema.extend({
3473
+ type: import_zod2.z.literal(
3474
+ "TEXT_MESSAGE_CONTENT"
3475
+ /* TEXT_MESSAGE_CONTENT */
3476
+ ),
3477
+ messageId: import_zod2.z.string(),
3478
+ delta: import_zod2.z.string().refine((s) => s.length > 0, "Delta must not be an empty string")
3479
+ });
3480
+ var TextMessageEndEventSchema = BaseEventSchema.extend({
3481
+ type: import_zod2.z.literal(
3482
+ "TEXT_MESSAGE_END"
3483
+ /* TEXT_MESSAGE_END */
3484
+ ),
3485
+ messageId: import_zod2.z.string()
3486
+ });
3487
+ var TextMessageChunkEventSchema = BaseEventSchema.extend({
3488
+ type: import_zod2.z.literal(
3489
+ "TEXT_MESSAGE_CHUNK"
3490
+ /* TEXT_MESSAGE_CHUNK */
3491
+ ),
3492
+ messageId: import_zod2.z.string().optional(),
3493
+ role: TextMessageRoleSchema.optional(),
3494
+ delta: import_zod2.z.string().optional()
3495
+ });
3496
+ var ThinkingTextMessageStartEventSchema = BaseEventSchema.extend({
3497
+ type: import_zod2.z.literal(
3498
+ "THINKING_TEXT_MESSAGE_START"
3499
+ /* THINKING_TEXT_MESSAGE_START */
3500
+ )
3501
+ });
3502
+ var ThinkingTextMessageContentEventSchema = TextMessageContentEventSchema.omit({
3503
+ messageId: true,
3504
+ type: true
3505
+ }).extend({
3506
+ type: import_zod2.z.literal(
3507
+ "THINKING_TEXT_MESSAGE_CONTENT"
3508
+ /* THINKING_TEXT_MESSAGE_CONTENT */
3509
+ )
3510
+ });
3511
+ var ThinkingTextMessageEndEventSchema = BaseEventSchema.extend({
3512
+ type: import_zod2.z.literal(
3513
+ "THINKING_TEXT_MESSAGE_END"
3514
+ /* THINKING_TEXT_MESSAGE_END */
3515
+ )
3516
+ });
3517
+ var ToolCallStartEventSchema = BaseEventSchema.extend({
3518
+ type: import_zod2.z.literal(
3519
+ "TOOL_CALL_START"
3520
+ /* TOOL_CALL_START */
3521
+ ),
3522
+ toolCallId: import_zod2.z.string(),
3523
+ toolCallName: import_zod2.z.string(),
3524
+ parentMessageId: import_zod2.z.string().optional()
3525
+ });
3526
+ var ToolCallArgsEventSchema = BaseEventSchema.extend({
3527
+ type: import_zod2.z.literal(
3528
+ "TOOL_CALL_ARGS"
3529
+ /* TOOL_CALL_ARGS */
3530
+ ),
3531
+ toolCallId: import_zod2.z.string(),
3532
+ delta: import_zod2.z.string()
3533
+ });
3534
+ var ToolCallEndEventSchema = BaseEventSchema.extend({
3535
+ type: import_zod2.z.literal(
3536
+ "TOOL_CALL_END"
3537
+ /* TOOL_CALL_END */
3538
+ ),
3539
+ toolCallId: import_zod2.z.string()
3540
+ });
3541
+ var ToolCallResultEventSchema = BaseEventSchema.extend({
3542
+ messageId: import_zod2.z.string(),
3543
+ type: import_zod2.z.literal(
3544
+ "TOOL_CALL_RESULT"
3545
+ /* TOOL_CALL_RESULT */
3546
+ ),
3547
+ toolCallId: import_zod2.z.string(),
3548
+ content: import_zod2.z.string(),
3549
+ role: import_zod2.z.literal("tool").optional()
3550
+ });
3551
+ var ToolCallChunkEventSchema = BaseEventSchema.extend({
3552
+ type: import_zod2.z.literal(
3553
+ "TOOL_CALL_CHUNK"
3554
+ /* TOOL_CALL_CHUNK */
3555
+ ),
3556
+ toolCallId: import_zod2.z.string().optional(),
3557
+ toolCallName: import_zod2.z.string().optional(),
3558
+ parentMessageId: import_zod2.z.string().optional(),
3559
+ delta: import_zod2.z.string().optional()
3560
+ });
3561
+ var ThinkingStartEventSchema = BaseEventSchema.extend({
3562
+ type: import_zod2.z.literal(
3563
+ "THINKING_START"
3564
+ /* THINKING_START */
3565
+ ),
3566
+ title: import_zod2.z.string().optional()
3567
+ });
3568
+ var ThinkingEndEventSchema = BaseEventSchema.extend({
3569
+ type: import_zod2.z.literal(
3570
+ "THINKING_END"
3571
+ /* THINKING_END */
3572
+ )
3573
+ });
3574
+ var StateSnapshotEventSchema = BaseEventSchema.extend({
3575
+ type: import_zod2.z.literal(
3576
+ "STATE_SNAPSHOT"
3577
+ /* STATE_SNAPSHOT */
3578
+ ),
3579
+ snapshot: StateSchema
3580
+ });
3581
+ var StateDeltaEventSchema = BaseEventSchema.extend({
3582
+ type: import_zod2.z.literal(
3583
+ "STATE_DELTA"
3584
+ /* STATE_DELTA */
3585
+ ),
3586
+ delta: import_zod2.z.array(import_zod2.z.any())
3587
+ // JSON Patch (RFC 6902)
3588
+ });
3589
+ var MessagesSnapshotEventSchema = BaseEventSchema.extend({
3590
+ type: import_zod2.z.literal(
3591
+ "MESSAGES_SNAPSHOT"
3592
+ /* MESSAGES_SNAPSHOT */
3593
+ ),
3594
+ messages: import_zod2.z.array(MessageSchema)
3595
+ });
3596
+ var ActivitySnapshotEventSchema = BaseEventSchema.extend({
3597
+ type: import_zod2.z.literal(
3598
+ "ACTIVITY_SNAPSHOT"
3599
+ /* ACTIVITY_SNAPSHOT */
3600
+ ),
3601
+ messageId: import_zod2.z.string(),
3602
+ activityType: import_zod2.z.string(),
3603
+ content: import_zod2.z.record(import_zod2.z.any()),
3604
+ replace: import_zod2.z.boolean().optional().default(true)
3605
+ });
3606
+ var ActivityDeltaEventSchema = BaseEventSchema.extend({
3607
+ type: import_zod2.z.literal(
3608
+ "ACTIVITY_DELTA"
3609
+ /* ACTIVITY_DELTA */
3610
+ ),
3611
+ messageId: import_zod2.z.string(),
3612
+ activityType: import_zod2.z.string(),
3613
+ patch: import_zod2.z.array(import_zod2.z.any())
3614
+ });
3615
+ var RawEventSchema = BaseEventSchema.extend({
3616
+ type: import_zod2.z.literal(
3617
+ "RAW"
3618
+ /* RAW */
3619
+ ),
3620
+ event: import_zod2.z.any(),
3621
+ source: import_zod2.z.string().optional()
3622
+ });
3623
+ var CustomEventSchema = BaseEventSchema.extend({
3624
+ type: import_zod2.z.literal(
3625
+ "CUSTOM"
3626
+ /* CUSTOM */
3627
+ ),
3628
+ name: import_zod2.z.string(),
3629
+ value: import_zod2.z.any()
3630
+ });
3631
+ var RunStartedEventSchema = BaseEventSchema.extend({
3632
+ type: import_zod2.z.literal(
3633
+ "RUN_STARTED"
3634
+ /* RUN_STARTED */
3635
+ ),
3636
+ threadId: import_zod2.z.string(),
3637
+ runId: import_zod2.z.string(),
3638
+ parentRunId: import_zod2.z.string().optional(),
3639
+ input: RunAgentInputSchema.optional()
3640
+ });
3641
+ var RunFinishedEventSchema = BaseEventSchema.extend({
3642
+ type: import_zod2.z.literal(
3643
+ "RUN_FINISHED"
3644
+ /* RUN_FINISHED */
3645
+ ),
3646
+ threadId: import_zod2.z.string(),
3647
+ runId: import_zod2.z.string(),
3648
+ result: import_zod2.z.any().optional()
3649
+ });
3650
+ var RunErrorEventSchema = BaseEventSchema.extend({
3651
+ type: import_zod2.z.literal(
3652
+ "RUN_ERROR"
3653
+ /* RUN_ERROR */
3654
+ ),
3655
+ message: import_zod2.z.string(),
3656
+ code: import_zod2.z.string().optional()
3657
+ });
3658
+ var StepStartedEventSchema = BaseEventSchema.extend({
3659
+ type: import_zod2.z.literal(
3660
+ "STEP_STARTED"
3661
+ /* STEP_STARTED */
3662
+ ),
3663
+ stepName: import_zod2.z.string()
3664
+ });
3665
+ var StepFinishedEventSchema = BaseEventSchema.extend({
3666
+ type: import_zod2.z.literal(
3667
+ "STEP_FINISHED"
3668
+ /* STEP_FINISHED */
3669
+ ),
3670
+ stepName: import_zod2.z.string()
3671
+ });
3672
+ var EventSchemas = import_zod2.z.discriminatedUnion("type", [
3673
+ TextMessageStartEventSchema,
3674
+ TextMessageContentEventSchema,
3675
+ TextMessageEndEventSchema,
3676
+ TextMessageChunkEventSchema,
3677
+ ThinkingStartEventSchema,
3678
+ ThinkingEndEventSchema,
3679
+ ThinkingTextMessageStartEventSchema,
3680
+ ThinkingTextMessageContentEventSchema,
3681
+ ThinkingTextMessageEndEventSchema,
3682
+ ToolCallStartEventSchema,
3683
+ ToolCallArgsEventSchema,
3684
+ ToolCallEndEventSchema,
3685
+ ToolCallChunkEventSchema,
3686
+ ToolCallResultEventSchema,
3687
+ StateSnapshotEventSchema,
3688
+ StateDeltaEventSchema,
3689
+ MessagesSnapshotEventSchema,
3690
+ ActivitySnapshotEventSchema,
3691
+ ActivityDeltaEventSchema,
3692
+ RawEventSchema,
3693
+ CustomEventSchema,
3694
+ RunStartedEventSchema,
3695
+ RunFinishedEventSchema,
3696
+ RunErrorEventSchema,
3697
+ StepStartedEventSchema,
3698
+ StepFinishedEventSchema
3699
+ ]);
3700
+
3701
+ // src/hooks/use-copilot-chat_internal.ts
3702
+ function useConfigureSuggestions2(suggestions) {
3703
+ let suggestionsConfig;
3704
+ if (Array.isArray(suggestions)) {
3705
+ suggestionsConfig = {
3706
+ suggestions,
3707
+ available: "always"
3708
+ };
3709
+ } else if (suggestions === "auto") {
3710
+ suggestionsConfig = {
3711
+ available: suggestions === "auto" ? "always" : "disabled",
3712
+ instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls."
3713
+ };
3714
+ } else {
3715
+ suggestionsConfig = { available: "disabled" };
3716
+ }
3717
+ useConfigureChatSuggestions(suggestionsConfig);
3718
+ }
3719
+ function useCopilotChatInternal({
3720
+ suggestions
3721
+ } = {}) {
3722
+ var _a, _b, _c, _d;
3723
+ const { copilotkit } = (0, import_react25.useCopilotKit)();
3724
+ const { threadId, agentSession } = useCopilotContext();
3725
+ const existingConfig = (0, import_react25.useCopilotChatConfiguration)();
3726
+ const [agentAvailable, setAgentAvailable] = (0, import_react24.useState)(false);
3727
+ useConfigureSuggestions2(suggestions);
3728
+ const resolvedAgentId = (_b = (_a = agentSession == null ? void 0 : agentSession.agentName) != null ? _a : existingConfig == null ? void 0 : existingConfig.agentId) != null ? _b : "default";
3729
+ const { agent } = (0, import_react25.useAgent)({ agentId: resolvedAgentId });
3730
+ (0, import_react24.useEffect)(() => {
3731
+ const connect = (agent2) => __async(this, null, function* () {
3732
+ setAgentAvailable(false);
3450
3733
  try {
3451
- while (true) {
3452
- let done, value;
3453
- try {
3454
- const readResult = yield reader.read();
3455
- done = readResult.done;
3456
- value = readResult.value;
3457
- } catch (readError) {
3458
- break;
3459
- }
3460
- if (done) {
3461
- if (chatAbortControllerRef.current.signal.aborted) {
3462
- return [];
3463
- }
3464
- break;
3465
- }
3466
- if (!(value == null ? void 0 : value.generateCopilotResponse)) {
3467
- continue;
3468
- }
3469
- runIdRef.current = value.generateCopilotResponse.runId || null;
3470
- extensionsRef.current = import_runtime_client_gql7.CopilotRuntimeClient.removeGraphQLTypename(
3471
- value.generateCopilotResponse.extensions || {}
3472
- );
3473
- setRunId(runIdRef.current);
3474
- setExtensions(extensionsRef.current);
3475
- let rawMessagesResponse = value.generateCopilotResponse.messages;
3476
- const metaEvents = (_j = (_i = value.generateCopilotResponse) == null ? void 0 : _i.metaEvents) != null ? _j : [];
3477
- (metaEvents != null ? metaEvents : []).forEach((ev) => {
3478
- if (ev.name === import_runtime_client_gql7.MetaEventName.LangGraphInterruptEvent) {
3479
- let eventValue = (0, import_runtime_client_gql7.langGraphInterruptEvent)(ev).value;
3480
- eventValue = (0, import_shared14.parseJson)(eventValue, eventValue);
3481
- setLangGraphInterruptAction(threadId, {
3482
- event: __spreadProps(__spreadValues({}, (0, import_runtime_client_gql7.langGraphInterruptEvent)(ev)), {
3483
- value: eventValue
3484
- })
3485
- });
3486
- }
3487
- if (ev.name === import_runtime_client_gql7.MetaEventName.CopilotKitLangGraphInterruptEvent) {
3488
- const data = ev.data;
3489
- rawMessagesResponse = [...rawMessagesResponse, ...data.messages];
3490
- interruptMessages = (0, import_runtime_client_gql7.convertGqlOutputToMessages)(
3491
- // @ts-ignore
3492
- (0, import_runtime_client_gql7.filterAdjacentAgentStateMessages)(data.messages)
3493
- );
3494
- }
3495
- });
3496
- messages2 = (0, import_runtime_client_gql7.convertGqlOutputToMessages)(
3497
- (0, import_runtime_client_gql7.filterAdjacentAgentStateMessages)(rawMessagesResponse)
3498
- );
3499
- newMessages = [];
3500
- if (((_k = value.generateCopilotResponse.status) == null ? void 0 : _k.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
3501
- const guardrailsReason = ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || "";
3502
- newMessages = [
3503
- new import_runtime_client_gql7.TextMessage({
3504
- role: import_runtime_client_gql7.MessageRole.Assistant,
3505
- content: guardrailsReason
3506
- })
3507
- ];
3508
- const guardrailsError = new import_shared14.CopilotKitError({
3509
- message: `Guardrails validation failed: ${guardrailsReason}`,
3510
- code: import_shared14.CopilotKitErrorCode.MISUSE
3511
- });
3512
- yield traceUIError(guardrailsError, {
3513
- statusReason: value.generateCopilotResponse.status.reason,
3514
- statusDetails: value.generateCopilotResponse.status.details
3515
- });
3516
- setMessages([...previousMessages, ...newMessages]);
3517
- break;
3518
- }
3519
- if (((_m = value.generateCopilotResponse.status) == null ? void 0 : _m.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "UNKNOWN_ERROR") {
3520
- const errorMessage = ((_n = value.generateCopilotResponse.status.details) == null ? void 0 : _n.description) || "An unknown error occurred";
3521
- const statusDetails = value.generateCopilotResponse.status.details;
3522
- const originalError = (statusDetails == null ? void 0 : statusDetails.originalError) || (statusDetails == null ? void 0 : statusDetails.error);
3523
- const originalCode = (originalError == null ? void 0 : originalError.code) || ((_o = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _o.code);
3524
- const originalSeverity = (originalError == null ? void 0 : originalError.severity) || ((_p = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _p.severity);
3525
- const originalVisibility = (originalError == null ? void 0 : originalError.visibility) || ((_q = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _q.visibility);
3526
- let errorCode = import_shared14.CopilotKitErrorCode.NETWORK_ERROR;
3527
- if (originalCode && Object.values(import_shared14.CopilotKitErrorCode).includes(originalCode)) {
3528
- errorCode = originalCode;
3529
- }
3530
- const structuredError = new import_shared14.CopilotKitError({
3531
- message: errorMessage,
3532
- code: errorCode,
3533
- severity: originalSeverity,
3534
- visibility: originalVisibility
3535
- });
3536
- setBannerError(structuredError);
3537
- yield traceUIError(structuredError, {
3538
- statusReason: value.generateCopilotResponse.status.reason,
3539
- statusDetails: value.generateCopilotResponse.status.details,
3540
- originalErrorCode: originalCode,
3541
- preservedStructure: !!originalCode
3542
- });
3543
- setIsLoading(false);
3544
- throw new Error(structuredError.message);
3545
- } else if (messages2.length > 0) {
3546
- newMessages = [...messages2];
3547
- for (const message of messages2) {
3548
- if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
3549
- if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
3550
- break;
3551
- }
3552
- yield onCoAgentStateRender({
3553
- name: message.agentName,
3554
- nodeName: message.nodeName,
3555
- state: message.state
3556
- });
3557
- executedCoAgentStateRenders.push(message.id);
3558
- }
3559
- }
3560
- const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
3561
- if (lastAgentStateMessage) {
3562
- if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
3563
- syncedMessages = (0, import_runtime_client_gql7.loadMessagesFromJsonRepresentation)(
3564
- lastAgentStateMessage.state.messages
3565
- );
3566
- }
3567
- setCoagentStatesWithRef((prevAgentStates) => {
3568
- var _a2;
3569
- return __spreadProps(__spreadValues({}, prevAgentStates), {
3570
- [lastAgentStateMessage.agentName]: {
3571
- name: lastAgentStateMessage.agentName,
3572
- state: lastAgentStateMessage.state,
3573
- running: lastAgentStateMessage.running,
3574
- active: lastAgentStateMessage.active,
3575
- threadId: lastAgentStateMessage.threadId,
3576
- nodeName: lastAgentStateMessage.nodeName,
3577
- runId: lastAgentStateMessage.runId,
3578
- // Preserve existing config from previous state
3579
- config: (_a2 = prevAgentStates[lastAgentStateMessage.agentName]) == null ? void 0 : _a2.config
3580
- }
3581
- });
3582
- });
3583
- if (lastAgentStateMessage.running) {
3584
- setAgentSession({
3585
- threadId: lastAgentStateMessage.threadId,
3586
- agentName: lastAgentStateMessage.agentName,
3587
- nodeName: lastAgentStateMessage.nodeName
3588
- });
3589
- } else {
3590
- if (agentLock) {
3591
- setAgentSession({
3592
- threadId: (0, import_shared14.randomId)(),
3593
- agentName: agentLock,
3594
- nodeName: void 0
3595
- });
3596
- } else {
3597
- setAgentSession(null);
3598
- }
3599
- }
3600
- }
3601
- }
3602
- if (newMessages.length > 0) {
3603
- setMessages([...previousMessages, ...newMessages]);
3604
- }
3605
- }
3606
- let finalMessages = constructFinalMessages(
3607
- [...syncedMessages, ...interruptMessages],
3608
- previousMessages,
3609
- newMessages
3610
- );
3611
- let didExecuteAction = false;
3612
- const executeActionFromMessage = (currentAction, actionMessage) => __async(this, null, function* () {
3613
- var _a2;
3614
- const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);
3615
- followUp = (_a2 = currentAction == null ? void 0 : currentAction.followUp) != null ? _a2 : !isInterruptAction;
3616
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
3617
- currentAction._setActivatingMessageId(actionMessage.id);
3618
- }
3619
- const resultMessage = yield executeAction({
3620
- onFunctionCall,
3621
- message: actionMessage,
3622
- chatAbortControllerRef,
3623
- onError: (error) => {
3624
- addErrorToast([error]);
3625
- console.error(`Failed to execute action ${actionMessage.name}: ${error}`);
3626
- },
3627
- setMessages,
3628
- getFinalMessages: () => finalMessages,
3629
- isRenderAndWait: (currentAction == null ? void 0 : currentAction._isRenderAndWait) || false
3630
- });
3631
- didExecuteAction = true;
3632
- const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);
3633
- finalMessages.splice(messageIndex + 1, 0, resultMessage);
3634
- if (currentAction == null ? void 0 : currentAction._isRenderAndWait) {
3635
- const messagesForImmediateUpdate = [...finalMessages];
3636
- (0, import_react_dom2.flushSync)(() => {
3637
- setMessages(messagesForImmediateUpdate);
3638
- });
3639
- }
3640
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
3641
- currentAction._setActivatingMessageId(null);
3642
- }
3643
- return resultMessage;
3644
- });
3645
- if (onFunctionCall) {
3646
- const lastMessages = [];
3647
- for (let i = finalMessages.length - 1; i >= 0; i--) {
3648
- const message = finalMessages[i];
3649
- if ((message.isActionExecutionMessage() || message.isResultMessage()) && message.status.code !== import_runtime_client_gql7.MessageStatusCode.Pending) {
3650
- lastMessages.unshift(message);
3651
- } else if (!message.isAgentStateMessage()) {
3652
- break;
3653
- }
3654
- }
3655
- for (const message of lastMessages) {
3656
- setMessages(finalMessages);
3657
- const action = actions.find(
3658
- (action2) => action2.name === message.name
3659
- );
3660
- if (action && action.available === "frontend") {
3661
- continue;
3662
- }
3663
- const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
3664
- if (action && message.isActionExecutionMessage()) {
3665
- const isRenderAndWaitAction = (action == null ? void 0 : action._isRenderAndWait) || false;
3666
- const alreadyProcessed = isRenderAndWaitAction && finalMessages.some(
3667
- (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
3668
- );
3669
- if (alreadyProcessed) {
3670
- } else {
3671
- const resultMessage = yield executeActionFromMessage(
3672
- action,
3673
- message
3674
- );
3675
- const pairedFeAction = getPairedFeAction(actions, resultMessage);
3676
- if (pairedFeAction) {
3677
- const newExecutionMessage = new import_runtime_client_gql7.ActionExecutionMessage({
3678
- name: pairedFeAction.name,
3679
- arguments: (0, import_shared14.parseJson)(resultMessage.result, resultMessage.result),
3680
- status: message.status,
3681
- createdAt: message.createdAt,
3682
- parentMessageId: message.parentMessageId
3683
- });
3684
- yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
3685
- }
3686
- }
3687
- } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
3688
- const newExecutionMessage = new import_runtime_client_gql7.ActionExecutionMessage({
3689
- name: currentResultMessagePairedFeAction.name,
3690
- arguments: (0, import_shared14.parseJson)(message.result, message.result),
3691
- status: message.status,
3692
- createdAt: message.createdAt
3693
- });
3694
- finalMessages.push(newExecutionMessage);
3695
- yield executeActionFromMessage(
3696
- currentResultMessagePairedFeAction,
3697
- newExecutionMessage
3698
- );
3699
- }
3700
- }
3701
- setMessages(finalMessages);
3702
- }
3703
- if (followUp !== false && (didExecuteAction || // the last message is a server side result
3704
- !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
3705
- !((_r = chatAbortControllerRef.current) == null ? void 0 : _r.signal.aborted)) {
3706
- yield new Promise((resolve) => setTimeout(resolve, 10));
3707
- return yield runChatCompletionRef.current(finalMessages);
3708
- } else if ((_s = chatAbortControllerRef.current) == null ? void 0 : _s.signal.aborted) {
3709
- const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
3710
- if (message.isActionExecutionMessage()) {
3711
- return finalMessages.find(
3712
- (msg, resultIndex) => msg.isResultMessage() && msg.actionExecutionId === message.id && resultIndex === actionExecutionIndex + 1
3713
- );
3714
- }
3715
- return true;
3716
- });
3717
- const repairedMessageIds = repairedMessages.map((message) => message.id);
3718
- setMessages(repairedMessages);
3719
- if ((_t = agentSessionRef.current) == null ? void 0 : _t.nodeName) {
3720
- setAgentSession({
3721
- threadId: agentSessionRef.current.threadId,
3722
- agentName: agentSessionRef.current.agentName,
3723
- nodeName: "__end__"
3724
- });
3725
- }
3726
- return newMessages.filter((message) => repairedMessageIds.includes(message.id));
3734
+ yield copilotkit.connectAgent({ agent: agent2 });
3735
+ setAgentAvailable(true);
3736
+ } catch (error) {
3737
+ if (error instanceof AGUIConnectNotImplementedError) {
3727
3738
  } else {
3728
- return newMessages.slice();
3739
+ throw error;
3729
3740
  }
3730
- } finally {
3731
- setIsLoading(false);
3732
- }
3733
- }),
3734
- [
3735
- messages,
3736
- setMessages,
3737
- makeSystemMessageCallback,
3738
- copilotConfig,
3739
- setIsLoading,
3740
- initialMessages,
3741
- isLoading,
3742
- actions,
3743
- onFunctionCall,
3744
- onCoAgentStateRender,
3745
- setCoagentStatesWithRef,
3746
- coagentStatesRef,
3747
- agentSession,
3748
- setAgentSession,
3749
- disableSystemMessage,
3750
- context
3751
- ]
3752
- );
3753
- runChatCompletionRef.current = runChatCompletion;
3754
- const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
3755
- (messages2) => __async(this, null, function* () {
3756
- yield runChatCompletionRef.current(messages2);
3757
- }),
3758
- [messages]
3759
- );
3760
- (0, import_react13.useEffect)(() => {
3761
- if (!isLoading && pendingAppendsRef.current.length > 0) {
3762
- const pending = pendingAppendsRef.current.splice(0);
3763
- const followUp = pending.some((p) => p.followUp);
3764
- const newMessages = [...messages, ...pending.map((p) => p.message)];
3765
- setMessages(newMessages);
3766
- if (followUp) {
3767
- runChatCompletionAndHandleFunctionCall(newMessages);
3768
3741
  }
3742
+ });
3743
+ if (agent && (existingConfig == null ? void 0 : existingConfig.threadId) && agent.threadId !== existingConfig.threadId) {
3744
+ agent.threadId = existingConfig.threadId;
3745
+ connect(agent);
3769
3746
  }
3770
- }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
3771
- const composeAndFlushMetaEventsInput = (0, import_react13.useCallback)(
3772
- (metaEvents) => {
3773
- return metaEvents.reduce((acc, event) => {
3774
- if (!event)
3775
- return acc;
3776
- switch (event.name) {
3777
- case import_runtime_client_gql7.MetaEventName.LangGraphInterruptEvent:
3778
- if (event.response) {
3779
- setLangGraphInterruptAction(threadId, null);
3780
- const value = event.value;
3781
- return [
3782
- ...acc,
3783
- {
3784
- name: event.name,
3785
- value: typeof value === "string" ? value : JSON.stringify(value),
3786
- response: typeof event.response === "string" ? event.response : JSON.stringify(event.response)
3787
- }
3788
- ];
3789
- }
3790
- return acc;
3791
- default:
3792
- return acc;
3793
- }
3794
- }, []);
3747
+ return () => {
3748
+ };
3749
+ }, [existingConfig == null ? void 0 : existingConfig.threadId, agent, copilotkit, resolvedAgentId]);
3750
+ const interrupt = useLangGraphInterruptRender(agent);
3751
+ const reset = () => {
3752
+ agent == null ? void 0 : agent.setMessages([]);
3753
+ agent == null ? void 0 : agent.setState(null);
3754
+ };
3755
+ const deleteMessage = (0, import_react24.useCallback)(
3756
+ (messageId) => {
3757
+ var _a2;
3758
+ const filteredMessages = ((_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []).filter(
3759
+ (message) => message.id !== messageId
3760
+ );
3761
+ agent == null ? void 0 : agent.setMessages(filteredMessages);
3795
3762
  },
3796
- [setLangGraphInterruptAction]
3763
+ [agent == null ? void 0 : agent.setMessages, agent == null ? void 0 : agent.messages]
3797
3764
  );
3798
- const append = useAsyncCallback(
3799
- (message, options2) => __async(this, null, function* () {
3800
- var _a;
3801
- const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
3802
- if (isLoading) {
3803
- pendingAppendsRef.current.push({ message, followUp });
3804
- return;
3805
- }
3806
- const newMessages = [...messages, message];
3807
- setMessages(newMessages);
3808
- if (followUp) {
3809
- return runChatCompletionAndHandleFunctionCall(newMessages);
3810
- }
3811
- }),
3812
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
3765
+ const latestDelete = useUpdatedRef(deleteMessage);
3766
+ const latestDeleteFunc = (0, import_react24.useCallback)(
3767
+ (messageId) => {
3768
+ return latestDelete.current(messageId);
3769
+ },
3770
+ [latestDelete]
3813
3771
  );
3772
+ const currentSuggestions = (0, import_react25.useSuggestions)({ agentId: resolvedAgentId });
3814
3773
  const reload = useAsyncCallback(
3815
3774
  (reloadMessageId) => __async(this, null, function* () {
3775
+ var _a2;
3776
+ const messages = (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : [];
3777
+ const isLoading = false;
3816
3778
  if (isLoading || messages.length === 0) {
3817
3779
  return;
3818
3780
  }
@@ -3822,351 +3784,68 @@ function useChat(options) {
3822
3784
  return;
3823
3785
  }
3824
3786
  const reloadMessageRole = messages[reloadMessageIndex].role;
3825
- if (reloadMessageRole !== import_runtime_client_gql7.MessageRole.Assistant) {
3787
+ if (reloadMessageRole !== "assistant") {
3826
3788
  console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
3827
3789
  return;
3828
3790
  }
3829
3791
  let historyCutoff = [messages[0]];
3830
3792
  if (messages.length > 2 && reloadMessageIndex !== 0) {
3831
- const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
3832
- (msg) => (
3833
- // @ts-expect-error -- message has role
3834
- msg.role === import_runtime_client_gql7.MessageRole.User
3835
- )
3836
- );
3837
- const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
3838
- (msg) => msg.id === lastUserMessageBeforeRegenerate.id
3839
- );
3840
- historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
3793
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find((msg) => msg.role === "user");
3794
+ if (!lastUserMessageBeforeRegenerate) {
3795
+ historyCutoff = [messages[0]];
3796
+ } else {
3797
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
3798
+ (msg) => msg.id === lastUserMessageBeforeRegenerate.id
3799
+ );
3800
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
3801
+ }
3841
3802
  } else if (messages.length > 2 && reloadMessageIndex === 0) {
3842
3803
  historyCutoff = [messages[0], messages[1]];
3843
3804
  }
3844
- setMessages(historyCutoff);
3845
- return runChatCompletionAndHandleFunctionCall(historyCutoff);
3846
- }),
3847
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
3848
- );
3849
- const stop = () => {
3850
- var _a;
3851
- (_a = chatAbortControllerRef.current) == null ? void 0 : _a.abort("Stop was called");
3852
- };
3853
- return {
3854
- append,
3855
- reload,
3856
- stop,
3857
- runChatCompletion: () => runChatCompletionRef.current(messages)
3858
- };
3859
- }
3860
- function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
3861
- const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
3862
- if (syncedMessages.length > 0) {
3863
- const messagesWithAgentState = [...previousMessages, ...newMessages];
3864
- let previousMessageId = void 0;
3865
- for (const message of messagesWithAgentState) {
3866
- if (message.isAgentStateMessage()) {
3867
- const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
3868
- if (index !== -1) {
3869
- finalMessages.splice(index + 1, 0, message);
3870
- }
3871
- }
3872
- previousMessageId = message.id;
3873
- }
3874
- }
3875
- return finalMessages;
3876
- }
3877
- function executeAction(_0) {
3878
- return __async(this, arguments, function* ({
3879
- onFunctionCall,
3880
- message,
3881
- chatAbortControllerRef,
3882
- onError,
3883
- setMessages,
3884
- getFinalMessages,
3885
- isRenderAndWait
3886
- }) {
3887
- let result;
3888
- let error = null;
3889
- const currentMessagesForHandler = getFinalMessages();
3890
- const handlerReturnedPromise = onFunctionCall({
3891
- messages: currentMessagesForHandler,
3892
- name: message.name,
3893
- args: message.arguments
3894
- });
3895
- if (isRenderAndWait) {
3896
- const currentMessagesForRender = getFinalMessages();
3897
- (0, import_react_dom2.flushSync)(() => {
3898
- setMessages([...currentMessagesForRender]);
3899
- });
3900
- }
3901
- try {
3902
- result = yield Promise.race([
3903
- handlerReturnedPromise,
3904
- // Await the promise returned by the handler
3905
- new Promise(
3906
- (resolve) => {
3907
- var _a;
3908
- return (_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.addEventListener(
3909
- "abort",
3910
- () => resolve("Operation was aborted by the user")
3911
- );
3912
- }
3913
- ),
3914
- // if the user stopped generation, we also abort consecutive actions
3915
- new Promise((resolve) => {
3916
- var _a;
3917
- if ((_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.aborted) {
3918
- resolve("Operation was aborted by the user");
3919
- }
3920
- })
3921
- ]);
3922
- } catch (e) {
3923
- onError(e);
3924
- }
3925
- return new import_runtime_client_gql7.ResultMessage({
3926
- id: "result-" + message.id,
3927
- result: import_runtime_client_gql7.ResultMessage.encodeResult(
3928
- error ? {
3929
- content: result,
3930
- error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
3931
- } : result
3932
- ),
3933
- actionExecutionId: message.id,
3934
- actionName: message.name
3935
- });
3936
- });
3937
- }
3938
- function getPairedFeAction(actions, message) {
3939
- let actionName = null;
3940
- if (message.isActionExecutionMessage()) {
3941
- actionName = message.name;
3942
- } else if (message.isResultMessage()) {
3943
- actionName = message.actionName;
3944
- }
3945
- return actions.find(
3946
- (action) => action.name === actionName && action.available === "frontend" || action.pairedAction === actionName
3947
- );
3948
- }
3949
-
3950
- // src/hooks/use-copilot-chat_internal.ts
3951
- var import_runtime_client_gql8 = require("@copilotkit/runtime-client-gql");
3952
-
3953
- // src/hooks/use-langgraph-interrupt-render.ts
3954
- var import_react14 = __toESM(require("react"));
3955
- var InterruptRenderer = ({ event, result, render, resolve }) => {
3956
- return render({ event, result, resolve });
3957
- };
3958
- function useLangGraphInterruptRender() {
3959
- const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession, threadId } = useCopilotContext();
3960
- const responseRef = import_react14.default.useRef();
3961
- const resolveInterrupt = (0, import_react14.useCallback)(
3962
- (response) => {
3963
- responseRef.current = response;
3964
- setTimeout(() => {
3965
- setLangGraphInterruptAction(threadId, { event: { response } });
3966
- }, 0);
3967
- },
3968
- [setLangGraphInterruptAction, threadId]
3969
- );
3970
- if (!langGraphInterruptAction || !langGraphInterruptAction.event || !langGraphInterruptAction.render)
3971
- return null;
3972
- const { render, handler, event, enabled } = langGraphInterruptAction;
3973
- const conditionsMet = !agentSession || !enabled ? true : enabled({ eventValue: event.value, agentMetadata: agentSession });
3974
- if (!conditionsMet) {
3975
- return null;
3976
- }
3977
- let result = null;
3978
- if (handler) {
3979
- result = handler({
3980
- event,
3981
- resolve: resolveInterrupt
3982
- });
3983
- }
3984
- return import_react14.default.createElement(InterruptRenderer, {
3985
- event,
3986
- result,
3987
- render,
3988
- resolve: resolveInterrupt
3989
- });
3990
- }
3991
-
3992
- // src/hooks/use-copilot-chat_internal.ts
3993
- var globalSuggestionPromise = null;
3994
- function useCopilotChat(options = {}) {
3995
- var _a;
3996
- const makeSystemMessage2 = (_a = options.makeSystemMessage) != null ? _a : defaultSystemMessage;
3997
- const {
3998
- getContextString,
3999
- getFunctionCallHandler,
4000
- copilotApiConfig,
4001
- isLoading,
4002
- setIsLoading,
4003
- chatInstructions,
4004
- actions,
4005
- coagentStatesRef,
4006
- setCoagentStatesWithRef,
4007
- coAgentStateRenders,
4008
- agentSession,
4009
- setAgentSession,
4010
- forwardedParameters,
4011
- agentLock,
4012
- threadId,
4013
- setThreadId,
4014
- runId,
4015
- setRunId,
4016
- chatAbortControllerRef,
4017
- extensions,
4018
- setExtensions,
4019
- langGraphInterruptAction,
4020
- setLangGraphInterruptAction,
4021
- chatSuggestionConfiguration,
4022
- runtimeClient
4023
- } = useCopilotContext();
4024
- const { messages, setMessages, suggestions, setSuggestions } = useCopilotMessagesContext();
4025
- const [mcpServers, setLocalMcpServers] = (0, import_react15.useState)([]);
4026
- const suggestionsAbortControllerRef = (0, import_react15.useRef)(null);
4027
- const isLoadingSuggestionsRef = (0, import_react15.useRef)(false);
4028
- const abortSuggestions = (0, import_react15.useCallback)(
4029
- (clear = true) => {
4030
- var _a2;
4031
- (_a2 = suggestionsAbortControllerRef.current) == null ? void 0 : _a2.abort("suggestions aborted by user");
4032
- suggestionsAbortControllerRef.current = null;
4033
- if (clear) {
4034
- setSuggestions([]);
3805
+ agent == null ? void 0 : agent.setMessages(historyCutoff);
3806
+ if (agent) {
3807
+ copilotkit.runAgent({ agent });
4035
3808
  }
4036
- },
4037
- [setSuggestions]
3809
+ return;
3810
+ }),
3811
+ [agent == null ? void 0 : agent.setMessages, copilotkit == null ? void 0 : copilotkit.runAgent]
4038
3812
  );
4039
- const stableContext = (0, import_react15.useMemo)(() => {
4040
- return {
4041
- actions,
4042
- copilotApiConfig,
4043
- chatSuggestionConfiguration,
4044
- messages,
4045
- setMessages,
4046
- getContextString,
4047
- runtimeClient
4048
- };
4049
- }, [
4050
- JSON.stringify(Object.keys(actions)),
4051
- copilotApiConfig.chatApiEndpoint,
4052
- messages.length,
4053
- Object.keys(chatSuggestionConfiguration).length
4054
- ]);
4055
- const generateSuggestionsFunc = (0, import_react15.useCallback)(() => __async(this, null, function* () {
4056
- if (globalSuggestionPromise) {
4057
- return globalSuggestionPromise;
4058
- }
4059
- globalSuggestionPromise = (() => __async(this, null, function* () {
4060
- try {
4061
- abortSuggestions();
4062
- isLoadingSuggestionsRef.current = true;
4063
- suggestionsAbortControllerRef.current = new AbortController();
4064
- setSuggestions([]);
4065
- yield reloadSuggestions(
4066
- stableContext,
4067
- chatSuggestionConfiguration,
4068
- setSuggestions,
4069
- suggestionsAbortControllerRef
4070
- );
4071
- } catch (error) {
4072
- throw error;
4073
- } finally {
4074
- isLoadingSuggestionsRef.current = false;
4075
- globalSuggestionPromise = null;
4076
- }
4077
- }))();
4078
- return globalSuggestionPromise;
4079
- }), [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);
4080
- const resetSuggestions = (0, import_react15.useCallback)(() => {
4081
- setSuggestions([]);
4082
- }, [setSuggestions]);
4083
- (0, import_react15.useEffect)(() => {
4084
- if (mcpServers.length > 0) {
4085
- const serversCopy = [...mcpServers];
4086
- copilotApiConfig.mcpServers = serversCopy;
4087
- if (!copilotApiConfig.properties) {
4088
- copilotApiConfig.properties = {};
4089
- }
4090
- copilotApiConfig.properties.mcpServers = serversCopy;
4091
- }
4092
- }, [mcpServers, copilotApiConfig]);
4093
- const setMcpServers = (0, import_react15.useCallback)((servers) => {
4094
- setLocalMcpServers(servers);
4095
- }, []);
4096
- const onCoAgentStateRender = useAsyncCallback(
4097
- (args) => __async(this, null, function* () {
3813
+ const latestSendMessageFunc = useAsyncCallback(
3814
+ (message, options) => __async(this, null, function* () {
4098
3815
  var _a2;
4099
- const { name, nodeName, state } = args;
4100
- let action = Object.values(coAgentStateRenders).find(
4101
- (action2) => action2.name === name && action2.nodeName === nodeName
4102
- );
4103
- if (!action) {
4104
- action = Object.values(coAgentStateRenders).find(
4105
- (action2) => action2.name === name && !action2.nodeName
4106
- );
3816
+ if (!agent)
3817
+ return;
3818
+ const followUp = (_a2 = options == null ? void 0 : options.followUp) != null ? _a2 : true;
3819
+ if (options == null ? void 0 : options.clearSuggestions) {
3820
+ copilotkit.clearSuggestions(resolvedAgentId);
4107
3821
  }
4108
- if (action) {
4109
- yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
3822
+ agent == null ? void 0 : agent.addMessage(message);
3823
+ if (followUp) {
3824
+ try {
3825
+ yield copilotkit.runAgent({ agent });
3826
+ } catch (error) {
3827
+ console.error("CopilotChat: runAgent failed", error);
3828
+ }
4110
3829
  }
4111
3830
  }),
4112
- [coAgentStateRenders]
4113
- );
4114
- const makeSystemMessageCallback = (0, import_react15.useCallback)(() => {
4115
- const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
4116
- const contextString = getContextString([], defaultCopilotContextCategories);
4117
- return new import_runtime_client_gql8.TextMessage({
4118
- content: systemMessageMaker(contextString, chatInstructions),
4119
- role: import_runtime_client_gql8.Role.System
4120
- });
4121
- }, [getContextString, makeSystemMessage2, chatInstructions]);
4122
- const deleteMessage = (0, import_react15.useCallback)(
4123
- (messageId) => {
4124
- setMessages((prev) => prev.filter((message) => message.id !== messageId));
4125
- },
4126
- [setMessages]
3831
+ [agent, copilotkit, resolvedAgentId]
4127
3832
  );
4128
- const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
4129
- actions: Object.values(actions),
4130
- copilotConfig: copilotApiConfig,
4131
- initialMessages: (0, import_runtime_client_gql8.aguiToGQL)(options.initialMessages || []),
4132
- onFunctionCall: getFunctionCallHandler(),
4133
- onCoAgentStateRender,
4134
- messages,
4135
- setMessages,
4136
- makeSystemMessageCallback,
4137
- isLoading,
4138
- setIsLoading,
4139
- coagentStatesRef,
4140
- setCoagentStatesWithRef,
4141
- agentSession,
4142
- setAgentSession,
4143
- forwardedParameters,
4144
- threadId,
4145
- setThreadId,
4146
- runId,
4147
- setRunId,
4148
- chatAbortControllerRef,
4149
- agentLock,
4150
- extensions,
4151
- setExtensions,
4152
- langGraphInterruptAction,
4153
- setLangGraphInterruptAction,
4154
- disableSystemMessage: options.disableSystemMessage
4155
- }));
4156
- const latestAppend = useUpdatedRef(append);
4157
3833
  const latestAppendFunc = useAsyncCallback(
4158
- (message, options2) => __async(this, null, function* () {
4159
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
4160
- return yield latestAppend.current(message, options2);
3834
+ (message, options) => __async(this, null, function* () {
3835
+ return latestSendMessageFunc((0, import_runtime_client_gql2.gqlToAGUI)([message])[0], options);
4161
3836
  }),
4162
- [latestAppend]
3837
+ [latestSendMessageFunc]
4163
3838
  );
4164
- const latestSendMessageFunc = useAsyncCallback(
4165
- (message, options2) => __async(this, null, function* () {
4166
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
4167
- return yield latestAppend.current((0, import_runtime_client_gql8.aguiToGQL)([message])[0], options2);
4168
- }),
4169
- [latestAppend]
3839
+ const latestSetMessages = useUpdatedRef(agent == null ? void 0 : agent.setMessages);
3840
+ const latestSetMessagesFunc = (0, import_react24.useCallback)(
3841
+ (messages) => {
3842
+ var _a2, _b2;
3843
+ if (messages.every((message) => message instanceof import_runtime_client_gql2.Message)) {
3844
+ return (_a2 = latestSetMessages.current) == null ? void 0 : _a2.call(latestSetMessages, (0, import_runtime_client_gql2.gqlToAGUI)(messages));
3845
+ }
3846
+ return (_b2 = latestSetMessages.current) == null ? void 0 : _b2.call(latestSetMessages, messages);
3847
+ },
3848
+ [latestSetMessages, agent]
4170
3849
  );
4171
3850
  const latestReload = useUpdatedRef(reload);
4172
3851
  const latestReloadFunc = useAsyncCallback(
@@ -4175,61 +3854,81 @@ function useCopilotChat(options = {}) {
4175
3854
  }),
4176
3855
  [latestReload]
4177
3856
  );
4178
- const latestStop = useUpdatedRef(stop);
4179
- const latestStopFunc = (0, import_react15.useCallback)(() => {
4180
- return latestStop.current();
3857
+ const latestStop = useUpdatedRef(agent == null ? void 0 : agent.abortRun);
3858
+ const latestStopFunc = (0, import_react24.useCallback)(() => {
3859
+ var _a2;
3860
+ return (_a2 = latestStop.current) == null ? void 0 : _a2.call(latestStop);
4181
3861
  }, [latestStop]);
4182
- const latestDelete = useUpdatedRef(deleteMessage);
4183
- const latestDeleteFunc = (0, import_react15.useCallback)(
4184
- (messageId) => {
4185
- return latestDelete.current(messageId);
4186
- },
4187
- [latestDelete]
4188
- );
4189
- const latestSetMessages = useUpdatedRef(setMessages);
4190
- const latestSetMessagesFunc = (0, import_react15.useCallback)(
4191
- (messages2) => {
4192
- if (messages2.every((message) => message instanceof import_runtime_client_gql8.Message)) {
4193
- return latestSetMessages.current(messages2);
3862
+ const latestReset = useUpdatedRef(reset);
3863
+ const latestResetFunc = (0, import_react24.useCallback)(() => {
3864
+ return latestReset.current();
3865
+ }, [latestReset]);
3866
+ const lazyToolRendered = useLazyToolRenderer();
3867
+ const renderCustomMessage = (0, import_react25.useRenderCustomMessages)();
3868
+ const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
3869
+ copilotkit,
3870
+ agent,
3871
+ agentId: resolvedAgentId,
3872
+ threadId: (_c = existingConfig == null ? void 0 : existingConfig.threadId) != null ? _c : threadId
3873
+ });
3874
+ const allMessages = (_d = agent == null ? void 0 : agent.messages) != null ? _d : [];
3875
+ const resolvedMessages = (0, import_react24.useMemo)(() => {
3876
+ let processedMessages = allMessages.map((message) => {
3877
+ if (message.role !== "assistant") {
3878
+ return message;
4194
3879
  }
4195
- return latestSetMessages.current((0, import_runtime_client_gql8.aguiToGQL)(messages2));
4196
- },
4197
- [latestSetMessages]
4198
- );
4199
- const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
4200
- const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
4201
- return yield latestRunChatCompletion.current();
4202
- }), [latestRunChatCompletion]);
4203
- const reset = (0, import_react15.useCallback)(() => {
4204
- latestStopFunc();
4205
- setMessages([]);
4206
- setRunId(null);
4207
- setCoagentStatesWithRef({});
4208
- let initialAgentSession = null;
4209
- if (agentLock) {
4210
- initialAgentSession = {
4211
- agentName: agentLock
3880
+ const lazyRendered = lazyToolRendered(message, allMessages);
3881
+ if (lazyRendered) {
3882
+ const renderedGenUi = lazyRendered();
3883
+ if (renderedGenUi) {
3884
+ return __spreadProps(__spreadValues({}, message), { generativeUI: () => renderedGenUi });
3885
+ }
3886
+ }
3887
+ const bridgeRenderer = legacyCustomMessageRenderer || renderCustomMessage ? () => {
3888
+ const customRender = renderCustomMessage == null ? void 0 : renderCustomMessage({
3889
+ message,
3890
+ position: "before"
3891
+ });
3892
+ if (customRender) {
3893
+ return customRender;
3894
+ }
3895
+ return legacyCustomMessageRenderer == null ? void 0 : legacyCustomMessageRenderer({ message, position: "before" });
3896
+ } : null;
3897
+ if (bridgeRenderer) {
3898
+ return __spreadProps(__spreadValues({}, message), { generativeUI: bridgeRenderer });
3899
+ }
3900
+ return message;
3901
+ });
3902
+ const hasAssistantMessages = processedMessages.some((msg) => msg.role === "assistant");
3903
+ if (legacyCustomMessageRenderer && !hasAssistantMessages) {
3904
+ const placeholderId = `coagent-state-render-${resolvedAgentId}`;
3905
+ const placeholderMessage = {
3906
+ id: placeholderId,
3907
+ role: "assistant",
3908
+ content: "",
3909
+ name: "coagent-state-render"
4212
3910
  };
3911
+ processedMessages = [
3912
+ ...processedMessages,
3913
+ __spreadProps(__spreadValues({}, placeholderMessage), {
3914
+ generativeUI: () => legacyCustomMessageRenderer({
3915
+ message: placeholderMessage,
3916
+ position: "before"
3917
+ })
3918
+ })
3919
+ ];
4213
3920
  }
4214
- setAgentSession(initialAgentSession);
4215
- resetSuggestions();
3921
+ return processedMessages;
4216
3922
  }, [
4217
- latestStopFunc,
4218
- setMessages,
4219
- setThreadId,
4220
- setCoagentStatesWithRef,
4221
- setAgentSession,
4222
- agentLock,
4223
- resetSuggestions
3923
+ agent == null ? void 0 : agent.messages,
3924
+ lazyToolRendered,
3925
+ allMessages,
3926
+ renderCustomMessage,
3927
+ legacyCustomMessageRenderer,
3928
+ resolvedAgentId
4224
3929
  ]);
4225
- const latestReset = useUpdatedRef(reset);
4226
- const latestResetFunc = (0, import_react15.useCallback)(() => {
4227
- return latestReset.current();
4228
- }, [latestReset]);
4229
- const interrupt = useLangGraphInterruptRender();
4230
3930
  return {
4231
- visibleMessages: messages,
4232
- messages: (0, import_runtime_client_gql8.gqlToAGUI)(messages, actions, coAgentStateRenders),
3931
+ messages: resolvedMessages,
4233
3932
  sendMessage: latestSendMessageFunc,
4234
3933
  appendMessage: latestAppendFunc,
4235
3934
  setMessages: latestSetMessagesFunc,
@@ -4237,54 +3936,66 @@ function useCopilotChat(options = {}) {
4237
3936
  stopGeneration: latestStopFunc,
4238
3937
  reset: latestResetFunc,
4239
3938
  deleteMessage: latestDeleteFunc,
4240
- runChatCompletion: latestRunChatCompletionFunc,
4241
- isLoading,
4242
- mcpServers,
4243
- setMcpServers,
4244
- suggestions,
4245
- setSuggestions,
4246
- generateSuggestions: generateSuggestionsFunc,
4247
- resetSuggestions,
4248
- isLoadingSuggestions: isLoadingSuggestionsRef.current,
4249
- interrupt
3939
+ isAvailable: !agentAvailable,
3940
+ isLoading: Boolean(agent == null ? void 0 : agent.isRunning),
3941
+ // mcpServers,
3942
+ // setMcpServers,
3943
+ suggestions: currentSuggestions.suggestions,
3944
+ setSuggestions: (suggestions2) => copilotkit.addSuggestionsConfig({ suggestions: suggestions2 }),
3945
+ generateSuggestions: () => __async(this, null, function* () {
3946
+ return copilotkit.reloadSuggestions(resolvedAgentId);
3947
+ }),
3948
+ resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),
3949
+ isLoadingSuggestions: currentSuggestions.isLoading,
3950
+ interrupt,
3951
+ agent,
3952
+ threadId
4250
3953
  };
4251
3954
  }
4252
3955
  function useUpdatedRef(value) {
4253
- const ref = (0, import_react15.useRef)(value);
4254
- (0, import_react15.useEffect)(() => {
3956
+ const ref = (0, import_react24.useRef)(value);
3957
+ (0, import_react24.useEffect)(() => {
4255
3958
  ref.current = value;
4256
3959
  }, [value]);
4257
3960
  return ref;
4258
3961
  }
4259
- function defaultSystemMessage(contextString, additionalInstructions) {
4260
- return `
4261
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
4262
-
4263
- 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.
4264
- Always be polite and respectful, and prefer brevity over verbosity.
4265
-
4266
- The user has provided you with the following context:
4267
- \`\`\`
4268
- ${contextString}
4269
- \`\`\`
4270
-
4271
- They have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.
4272
-
4273
- Please assist them as best you can.
4274
-
4275
- You can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.
4276
-
4277
- If you would like to call a function, call it without saying anything else.
4278
- In case of a function error:
4279
- - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
4280
- - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
4281
- ` + (additionalInstructions ? `
4282
-
4283
- ${additionalInstructions}` : "");
3962
+ function useLegacyCoagentRenderer({
3963
+ copilotkit,
3964
+ agent,
3965
+ agentId,
3966
+ threadId
3967
+ }) {
3968
+ return (0, import_react24.useMemo)(() => {
3969
+ if (!copilotkit || !agent) {
3970
+ return null;
3971
+ }
3972
+ return ({ message, position }) => {
3973
+ var _a;
3974
+ const effectiveThreadId = (_a = threadId != null ? threadId : agent.threadId) != null ? _a : "default";
3975
+ const existingRunId = copilotkit.getRunIdForMessage(
3976
+ agentId,
3977
+ effectiveThreadId,
3978
+ message.id
3979
+ );
3980
+ const runId = existingRunId || `pending:${message.id}`;
3981
+ const messageIndex = Math.max(agent.messages.findIndex((msg) => msg.id === message.id), 0);
3982
+ const bridgeProps = {
3983
+ message,
3984
+ position,
3985
+ runId,
3986
+ messageIndex,
3987
+ messageIndexInRun: 0,
3988
+ numberOfMessagesInRun: 1,
3989
+ agentId,
3990
+ stateSnapshot: message.state
3991
+ };
3992
+ return (0, import_react24.createElement)(CoAgentStateRenderBridge, bridgeProps);
3993
+ };
3994
+ }, [agent, agentId, copilotkit, threadId]);
4284
3995
  }
4285
3996
 
4286
3997
  // src/hooks/use-copilot-chat.ts
4287
- function useCopilotChat2(options = {}) {
3998
+ function useCopilotChat(options = {}) {
4288
3999
  const {
4289
4000
  visibleMessages,
4290
4001
  appendMessage,
@@ -4292,10 +4003,11 @@ function useCopilotChat2(options = {}) {
4292
4003
  stopGeneration,
4293
4004
  reset,
4294
4005
  isLoading,
4006
+ isAvailable,
4295
4007
  runChatCompletion,
4296
4008
  mcpServers,
4297
4009
  setMcpServers
4298
- } = useCopilotChat(options);
4010
+ } = useCopilotChatInternal(options);
4299
4011
  return {
4300
4012
  visibleMessages,
4301
4013
  appendMessage,
@@ -4303,6 +4015,7 @@ function useCopilotChat2(options = {}) {
4303
4015
  stopGeneration,
4304
4016
  reset,
4305
4017
  isLoading,
4018
+ isAvailable,
4306
4019
  runChatCompletion,
4307
4020
  mcpServers,
4308
4021
  setMcpServers
@@ -4310,7 +4023,7 @@ function useCopilotChat2(options = {}) {
4310
4023
  }
4311
4024
 
4312
4025
  // src/hooks/use-copilot-chat-headless_c.ts
4313
- var import_react16 = require("react");
4026
+ var import_react26 = require("react");
4314
4027
  var import_shared15 = require("@copilotkit/shared");
4315
4028
  var createNonFunctionalReturn = () => ({
4316
4029
  visibleMessages: [],
@@ -4330,6 +4043,7 @@ var createNonFunctionalReturn = () => ({
4330
4043
  reset: () => {
4331
4044
  },
4332
4045
  isLoading: false,
4046
+ isAvailable: false,
4333
4047
  runChatCompletion: () => __async(void 0, null, function* () {
4334
4048
  return [];
4335
4049
  }),
@@ -4349,8 +4063,8 @@ var createNonFunctionalReturn = () => ({
4349
4063
  function useCopilotChatHeadless_c(options = {}) {
4350
4064
  const { copilotApiConfig, setBannerError } = useCopilotContext();
4351
4065
  const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);
4352
- const internalResult = useCopilotChat(options);
4353
- (0, import_react16.useEffect)(() => {
4066
+ const internalResult = useCopilotChatInternal(options);
4067
+ (0, import_react26.useEffect)(() => {
4354
4068
  if (!hasPublicApiKey) {
4355
4069
  setBannerError(
4356
4070
  new import_shared15.CopilotKitError({
@@ -4375,146 +4089,233 @@ function useCopilotChatHeadless_c(options = {}) {
4375
4089
  }
4376
4090
 
4377
4091
  // src/hooks/use-copilot-action.ts
4092
+ var import_react33 = require("react");
4093
+
4094
+ // src/hooks/use-frontend-tool.ts
4095
+ var import_react27 = __toESM(require("react"));
4378
4096
  var import_shared16 = require("@copilotkit/shared");
4379
- var import_react17 = require("react");
4380
- function useCopilotAction(action, dependencies) {
4381
- const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
4382
- const idRef = (0, import_react17.useRef)((0, import_shared16.randomId)());
4383
- const renderAndWaitRef = (0, import_react17.useRef)(null);
4384
- const activatingMessageIdRef = (0, import_react17.useRef)(null);
4385
- const { addToast } = useToast();
4386
- action = __spreadValues({}, action);
4387
- if (
4388
- // renderAndWaitForResponse is not available for catch all actions
4389
- isFrontendAction(action) && // check if renderAndWaitForResponse is set
4390
- (action.renderAndWait || action.renderAndWaitForResponse)
4391
- ) {
4392
- action._isRenderAndWait = true;
4393
- const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;
4394
- action.renderAndWait = void 0;
4395
- action.renderAndWaitForResponse = void 0;
4396
- action._setActivatingMessageId = (id) => {
4397
- activatingMessageIdRef.current = id;
4398
- };
4399
- action.handler = useAsyncCallback(() => __async(this, null, function* () {
4400
- const currentActivatingId = activatingMessageIdRef.current;
4401
- let resolve;
4402
- let reject;
4403
- const promise = new Promise((resolvePromise, rejectPromise) => {
4404
- resolve = resolvePromise;
4405
- reject = rejectPromise;
4097
+ var import_shared17 = require("@copilotkit/shared");
4098
+ var import_react28 = require("@copilotkitnext/react");
4099
+ function useFrontendTool(tool, dependencies) {
4100
+ const { name, description, parameters, render, followUp } = tool;
4101
+ const zodParameters = (0, import_shared16.getZodParameters)(parameters);
4102
+ const normalizedRender = (() => {
4103
+ if (typeof render === "undefined") {
4104
+ return void 0;
4105
+ }
4106
+ if (typeof render === "string") {
4107
+ const staticRender = render;
4108
+ return () => import_react27.default.createElement(import_react27.default.Fragment, null, staticRender);
4109
+ }
4110
+ return (args) => {
4111
+ const renderArgs = __spreadProps(__spreadValues({}, args), {
4112
+ result: typeof args.result === "string" ? (0, import_shared17.parseJson)(args.result, args.result) : args.result
4406
4113
  });
4407
- renderAndWaitRef.current = {
4408
- promise,
4409
- resolve,
4410
- reject,
4411
- messageId: currentActivatingId
4412
- };
4413
- const result = yield promise;
4414
- return result;
4415
- }), []);
4416
- action.render = (props) => {
4417
- const currentRenderMessageId = props.messageId;
4418
- let status = props.status;
4419
- if (props.status === "executing") {
4420
- if (!renderAndWaitRef.current || !renderAndWaitRef.current.promise) {
4421
- status = "inProgress";
4422
- } else if (renderAndWaitRef.current.messageId !== currentRenderMessageId && activatingMessageIdRef.current !== currentRenderMessageId) {
4423
- status = "inProgress";
4424
- }
4114
+ const rendered = render(renderArgs);
4115
+ if (typeof rendered === "string") {
4116
+ return import_react27.default.createElement(import_react27.default.Fragment, null, rendered);
4425
4117
  }
4426
- const waitProps = {
4427
- status,
4428
- args: props.args,
4429
- result: props.result,
4430
- // handler and respond should only be provided if this is the truly active instance
4431
- // and its promise infrastructure is ready.
4432
- handler: status === "executing" && renderAndWaitRef.current && renderAndWaitRef.current.messageId === currentRenderMessageId ? renderAndWaitRef.current.resolve : void 0,
4433
- respond: status === "executing" && renderAndWaitRef.current && renderAndWaitRef.current.messageId === currentRenderMessageId ? renderAndWaitRef.current.resolve : void 0
4434
- };
4435
- const isNoArgsRenderWait = (_fn) => {
4436
- var _a;
4437
- return ((_a = action.parameters) == null ? void 0 : _a.length) === 0;
4438
- };
4439
- if (renderAndWait) {
4440
- if (isNoArgsRenderWait(renderAndWait)) {
4441
- return renderAndWait(waitProps);
4442
- } else {
4443
- return renderAndWait(waitProps);
4118
+ return rendered != null ? rendered : null;
4119
+ };
4120
+ })();
4121
+ (0, import_react28.useFrontendTool)({
4122
+ name,
4123
+ description,
4124
+ parameters: zodParameters,
4125
+ handler: tool.handler,
4126
+ followUp,
4127
+ render: normalizedRender
4128
+ });
4129
+ }
4130
+
4131
+ // src/hooks/use-render-tool-call.ts
4132
+ var import_shared18 = require("@copilotkit/shared");
4133
+ var import_react29 = require("react");
4134
+ var import_react30 = require("@copilotkitnext/react");
4135
+ var import_shared19 = require("@copilotkit/shared");
4136
+ function useRenderToolCall2(tool, dependencies) {
4137
+ const { copilotkit } = (0, import_react30.useCopilotKit)();
4138
+ const hasAddedRef = (0, import_react29.useRef)(false);
4139
+ (0, import_react29.useEffect)(() => {
4140
+ const { name, parameters, render } = tool;
4141
+ const zodParameters = (0, import_shared18.getZodParameters)(parameters);
4142
+ const renderToolCall = name === "*" ? (0, import_react30.defineToolCallRenderer)({
4143
+ name: "*",
4144
+ render: (args) => {
4145
+ return render(__spreadProps(__spreadValues({}, args), {
4146
+ result: args.result ? (0, import_shared19.parseJson)(args.result, args.result) : args.result
4147
+ }));
4148
+ }
4149
+ }) : (0, import_react30.defineToolCallRenderer)({
4150
+ name,
4151
+ args: zodParameters,
4152
+ render: (args) => {
4153
+ return render(__spreadProps(__spreadValues({}, args), {
4154
+ result: args.result ? (0, import_shared19.parseJson)(args.result, args.result) : args.result
4155
+ }));
4156
+ }
4157
+ });
4158
+ const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
4159
+ if (existingIndex !== -1) {
4160
+ copilotkit.renderToolCalls.splice(existingIndex, 1);
4161
+ }
4162
+ copilotkit.renderToolCalls.push(renderToolCall);
4163
+ hasAddedRef.current = true;
4164
+ return () => {
4165
+ if (hasAddedRef.current) {
4166
+ const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
4167
+ if (index !== -1) {
4168
+ copilotkit.renderToolCalls.splice(index, 1);
4444
4169
  }
4170
+ hasAddedRef.current = false;
4445
4171
  }
4446
- return (0, import_react17.createElement)(import_react17.Fragment);
4447
4172
  };
4448
- }
4449
- if (dependencies === void 0) {
4450
- if (actions[idRef.current]) {
4451
- if (isFrontendAction(action)) {
4452
- actions[idRef.current].handler = action.handler;
4173
+ }, [tool, ...dependencies != null ? dependencies : []]);
4174
+ }
4175
+
4176
+ // src/hooks/use-human-in-the-loop.ts
4177
+ var import_shared20 = require("@copilotkit/shared");
4178
+ var import_react31 = require("@copilotkitnext/react");
4179
+ var import_core = require("@copilotkitnext/core");
4180
+ var import_react32 = __toESM(require("react"));
4181
+ function useHumanInTheLoop(tool, dependencies) {
4182
+ const _a = tool, { render } = _a, toolRest = __objRest(_a, ["render"]);
4183
+ const { name, description, parameters, followUp } = toolRest;
4184
+ const zodParameters = (0, import_shared20.getZodParameters)(parameters);
4185
+ const renderRef = (0, import_react32.useRef)(null);
4186
+ (0, import_react32.useEffect)(() => {
4187
+ renderRef.current = (args) => {
4188
+ if (typeof render === "string") {
4189
+ return import_react32.default.createElement(import_react32.default.Fragment, null, render);
4453
4190
  }
4454
- if (typeof action.render === "function") {
4455
- if (chatComponentsCache.current !== null) {
4456
- chatComponentsCache.current.actions[action.name] = action.render;
4191
+ if (!render) {
4192
+ return null;
4193
+ }
4194
+ const renderProps = (() => {
4195
+ const mappedArgs = args.args;
4196
+ switch (args.status) {
4197
+ case import_core.ToolCallStatus.InProgress:
4198
+ return {
4199
+ args: mappedArgs,
4200
+ respond: args.respond,
4201
+ status: args.status,
4202
+ handler: void 0
4203
+ };
4204
+ case import_core.ToolCallStatus.Executing:
4205
+ return {
4206
+ args: mappedArgs,
4207
+ respond: args.respond,
4208
+ status: args.status,
4209
+ handler: () => {
4210
+ }
4211
+ };
4212
+ case import_core.ToolCallStatus.Complete:
4213
+ return {
4214
+ args: mappedArgs,
4215
+ respond: args.respond,
4216
+ status: args.status,
4217
+ result: args.result ? (0, import_shared20.parseJson)(args.result, args.result) : args.result,
4218
+ handler: void 0
4219
+ };
4220
+ default:
4221
+ throw new import_shared20.CopilotKitError({
4222
+ code: import_shared20.CopilotKitErrorCode.UNKNOWN,
4223
+ message: `Invalid tool call status: ${args.status}`
4224
+ });
4457
4225
  }
4226
+ })();
4227
+ const rendered = render(renderProps);
4228
+ if (typeof rendered === "string") {
4229
+ return import_react32.default.createElement(import_react32.default.Fragment, null, rendered);
4458
4230
  }
4231
+ return rendered != null ? rendered : null;
4232
+ };
4233
+ }, [render, ...dependencies != null ? dependencies : []]);
4234
+ (0, import_react31.useHumanInTheLoop)({
4235
+ name,
4236
+ description,
4237
+ followUp,
4238
+ parameters: zodParameters,
4239
+ render: (args) => {
4240
+ var _a2, _b;
4241
+ return (_b = (_a2 = renderRef.current) == null ? void 0 : _a2.call(renderRef, args)) != null ? _b : null;
4459
4242
  }
4243
+ });
4244
+ }
4245
+
4246
+ // src/hooks/use-copilot-action.ts
4247
+ function getActionConfig(action) {
4248
+ if (action.name === "*") {
4249
+ return {
4250
+ type: "render",
4251
+ action
4252
+ };
4460
4253
  }
4461
- (0, import_react17.useEffect)(() => {
4462
- const hasDuplicate = Object.values(actions).some(
4463
- (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current]
4464
- );
4465
- if (hasDuplicate) {
4466
- addToast({
4467
- type: "warning",
4468
- message: `Found an already registered action with name ${action.name}.`,
4469
- id: `dup-action-${action.name}`
4470
- });
4254
+ if ("renderAndWaitForResponse" in action || "renderAndWait" in action) {
4255
+ let render = action.render;
4256
+ if (!render && "renderAndWaitForResponse" in action) {
4257
+ render = action.renderAndWaitForResponse;
4471
4258
  }
4472
- }, [actions]);
4473
- (0, import_react17.useEffect)(() => {
4474
- setAction(idRef.current, action);
4475
- if (chatComponentsCache.current !== null && action.render !== void 0) {
4476
- chatComponentsCache.current.actions[action.name] = action.render;
4259
+ if (!render && "renderAndWait" in action) {
4260
+ render = action.renderAndWait;
4477
4261
  }
4478
- return () => {
4479
- removeAction(idRef.current);
4262
+ return {
4263
+ type: "hitl",
4264
+ action: __spreadProps(__spreadValues({}, action), { render })
4480
4265
  };
4481
- }, [
4482
- setAction,
4483
- removeAction,
4484
- isFrontendAction(action) ? action.description : void 0,
4485
- action.name,
4486
- isFrontendAction(action) ? action.disabled : void 0,
4487
- isFrontendAction(action) ? action.available : void 0,
4488
- // This should be faster than deep equality checking
4489
- // In addition, all major JS engines guarantee the order of object keys
4490
- JSON.stringify(isFrontendAction(action) ? action.parameters : []),
4491
- // include render only if it's a string
4492
- typeof action.render === "string" ? action.render : void 0,
4493
- // dependencies set by the developer
4494
- ...dependencies || []
4495
- ]);
4266
+ }
4267
+ if ("available" in action) {
4268
+ if (action.available === "enabled" || action.available === "remote") {
4269
+ return {
4270
+ type: "frontend",
4271
+ action
4272
+ };
4273
+ }
4274
+ if (action.available === "frontend" || action.available === "disabled") {
4275
+ return {
4276
+ type: "render",
4277
+ action
4278
+ };
4279
+ }
4280
+ }
4281
+ if ("handler" in action) {
4282
+ return {
4283
+ type: "frontend",
4284
+ action
4285
+ };
4286
+ }
4287
+ throw new Error("Invalid action configuration");
4496
4288
  }
4497
- function isFrontendAction(action) {
4498
- return action.name !== "*";
4289
+ function useCopilotAction(action, dependencies) {
4290
+ const [initialActionConfig] = (0, import_react33.useState)(getActionConfig(action));
4291
+ const currentActionConfig = getActionConfig(action);
4292
+ if (initialActionConfig.type !== currentActionConfig.type) {
4293
+ throw new Error("Action configuration changed between renders");
4294
+ }
4295
+ switch (currentActionConfig.type) {
4296
+ case "render":
4297
+ return useRenderToolCall2(currentActionConfig.action, dependencies);
4298
+ case "hitl":
4299
+ return useHumanInTheLoop(currentActionConfig.action, dependencies);
4300
+ case "frontend":
4301
+ return useFrontendTool(currentActionConfig.action, dependencies);
4302
+ default:
4303
+ throw new Error("Invalid action configuration");
4304
+ }
4499
4305
  }
4500
4306
 
4501
4307
  // src/hooks/use-coagent-state-render.ts
4502
- var import_react18 = require("react");
4503
- var import_shared17 = require("@copilotkit/shared");
4308
+ var import_react34 = require("react");
4309
+ var import_shared21 = require("@copilotkit/shared");
4504
4310
  function useCoAgentStateRender(action, dependencies) {
4505
- const {
4506
- setCoAgentStateRender,
4507
- removeCoAgentStateRender,
4508
- coAgentStateRenders,
4509
- chatComponentsCache,
4510
- availableAgents
4511
- } = (0, import_react18.useContext)(CopilotContext);
4512
- const idRef = (0, import_react18.useRef)((0, import_shared17.randomId)());
4311
+ const { chatComponentsCache, availableAgents } = (0, import_react34.useContext)(CopilotContext);
4312
+ const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } = useCoAgentStateRenders();
4313
+ const idRef = (0, import_react34.useRef)((0, import_shared21.randomId)());
4513
4314
  const { setBannerError, addToast } = useToast();
4514
- (0, import_react18.useEffect)(() => {
4315
+ (0, import_react34.useEffect)(() => {
4515
4316
  if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === action.name)) {
4516
4317
  const message = `(useCoAgentStateRender): Agent "${action.name}" not found. Make sure the agent exists and is properly configured.`;
4517
- const agentError = new import_shared17.CopilotKitAgentDiscoveryError({
4318
+ const agentError = new import_shared21.CopilotKitAgentDiscoveryError({
4518
4319
  agentName: action.name,
4519
4320
  availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id }))
4520
4321
  });
@@ -4532,7 +4333,7 @@ function useCoAgentStateRender(action, dependencies) {
4532
4333
  }
4533
4334
  }
4534
4335
  }
4535
- (0, import_react18.useEffect)(() => {
4336
+ (0, import_react34.useEffect)(() => {
4536
4337
  const currentId = idRef.current;
4537
4338
  const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
4538
4339
  if (id === currentId)
@@ -4556,7 +4357,7 @@ function useCoAgentStateRender(action, dependencies) {
4556
4357
  });
4557
4358
  }
4558
4359
  }, [coAgentStateRenders]);
4559
- (0, import_react18.useEffect)(() => {
4360
+ (0, import_react34.useEffect)(() => {
4560
4361
  setCoAgentStateRender(idRef.current, action);
4561
4362
  if (chatComponentsCache.current !== null && action.render !== void 0) {
4562
4363
  chatComponentsCache.current.coAgentStateRenders[key] = action.render;
@@ -4576,11 +4377,11 @@ function useCoAgentStateRender(action, dependencies) {
4576
4377
  }
4577
4378
 
4578
4379
  // src/hooks/use-make-copilot-document-readable.ts
4579
- var import_react19 = require("react");
4380
+ var import_react35 = require("react");
4580
4381
  function useMakeCopilotDocumentReadable(document2, categories, dependencies = []) {
4581
4382
  const { addDocumentContext, removeDocumentContext } = useCopilotContext();
4582
- const idRef = (0, import_react19.useRef)();
4583
- (0, import_react19.useEffect)(() => {
4383
+ const idRef = (0, import_react35.useRef)(void 0);
4384
+ (0, import_react35.useEffect)(() => {
4584
4385
  const id = addDocumentContext(document2, categories);
4585
4386
  idRef.current = id;
4586
4387
  return () => {
@@ -4591,275 +4392,292 @@ function useMakeCopilotDocumentReadable(document2, categories, dependencies = []
4591
4392
  }
4592
4393
 
4593
4394
  // src/hooks/use-copilot-readable.ts
4594
- var import_react20 = require("react");
4595
- function convertToJSON(description, value) {
4596
- return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
4597
- }
4598
- function useCopilotReadable({
4599
- description,
4600
- value,
4601
- parentId,
4602
- categories,
4603
- convert,
4604
- available = "enabled"
4605
- }, dependencies) {
4606
- const { addContext, removeContext } = useCopilotContext();
4607
- const idRef = (0, import_react20.useRef)();
4608
- convert = convert || convertToJSON;
4609
- const information = convert(description, value);
4610
- (0, import_react20.useEffect)(() => {
4611
- if (available === "disabled")
4612
- return;
4613
- const id = addContext(information, parentId, categories);
4614
- idRef.current = id;
4615
- return () => {
4616
- removeContext(id);
4617
- };
4618
- }, [available, information, parentId, addContext, removeContext, ...dependencies || []]);
4619
- return idRef.current;
4395
+ var import_react36 = require("@copilotkitnext/react");
4396
+ function useCopilotReadable({ description, value }, dependencies) {
4397
+ (0, import_react36.useAgentContext)({
4398
+ description,
4399
+ value
4400
+ });
4620
4401
  }
4621
4402
 
4622
4403
  // src/hooks/use-coagent.ts
4623
- var import_react21 = require("react");
4624
- var import_shared18 = require("@copilotkit/shared");
4404
+ var import_react37 = require("react");
4405
+ var import_react38 = require("@copilotkitnext/react");
4625
4406
  function useCoAgent(options) {
4626
- const context = useCopilotContext();
4627
- const { availableAgents, onError } = context;
4628
- const { setBannerError } = useToast();
4629
- const lastLoadedThreadId = (0, import_react21.useRef)();
4630
- const lastLoadedState = (0, import_react21.useRef)();
4631
- const { name } = options;
4632
- (0, import_react21.useEffect)(() => {
4633
- if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === name)) {
4634
- const message = `(useCoAgent): Agent "${name}" not found. Make sure the agent exists and is properly configured.`;
4635
- console.warn(message);
4636
- const agentError = new import_shared18.CopilotKitAgentDiscoveryError({
4637
- agentName: name,
4638
- availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id }))
4639
- });
4640
- setBannerError(agentError);
4641
- }
4642
- }, [availableAgents]);
4643
- const { getMessagesFromTap } = useMessagesTap();
4644
- const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context;
4645
- const { sendMessage, runChatCompletion } = useCopilotChat();
4646
- const headers = __spreadValues({}, copilotApiConfig.headers || {});
4647
- const runtimeClient = useCopilotRuntimeClient({
4648
- url: copilotApiConfig.chatApiEndpoint,
4649
- publicApiKey: copilotApiConfig.publicApiKey,
4650
- headers,
4651
- credentials: copilotApiConfig.credentials,
4652
- showDevConsole: context.showDevConsole,
4653
- onError
4654
- });
4655
- const setState = (0, import_react21.useCallback)(
4407
+ const { agent } = (0, import_react38.useAgent)({ agentId: options.name });
4408
+ const nodeNameRef = (0, import_react37.useRef)("start");
4409
+ const handleStateUpdate = (0, import_react37.useCallback)(
4656
4410
  (newState) => {
4657
- let coagentState = getCoagentState({ coagentStates, name, options });
4658
- const updatedState = typeof newState === "function" ? newState(coagentState.state) : newState;
4659
- setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), {
4660
- [name]: __spreadProps(__spreadValues({}, coagentState), {
4661
- state: updatedState
4662
- })
4663
- }));
4664
- },
4665
- [coagentStates, name]
4666
- );
4667
- (0, import_react21.useEffect)(() => {
4668
- const fetchAgentState = () => __async(this, null, function* () {
4669
- var _a, _b, _c, _d;
4670
- if (!threadId || threadId === lastLoadedThreadId.current)
4671
- return;
4672
- const result = yield runtimeClient.loadAgentState({
4673
- threadId,
4674
- agentName: name
4675
- });
4676
- if (result.error) {
4677
- return;
4678
- }
4679
- const newState = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.state;
4680
- if (newState === lastLoadedState.current)
4411
+ if (!agent)
4681
4412
  return;
4682
- if (((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) && newState && newState != "{}") {
4683
- lastLoadedState.current = newState;
4684
- lastLoadedThreadId.current = threadId;
4685
- const fetchedState = (0, import_shared18.parseJson)(newState, {});
4686
- isExternalStateManagement(options) ? options.setState(fetchedState) : setState(fetchedState);
4413
+ if (typeof newState === "function") {
4414
+ const updater = newState;
4415
+ agent.setState(updater(agent.state));
4416
+ } else {
4417
+ agent.setState(__spreadValues(__spreadValues({}, agent.state), newState));
4687
4418
  }
4688
- });
4689
- void fetchAgentState();
4690
- }, [threadId]);
4691
- (0, import_react21.useEffect)(() => {
4419
+ },
4420
+ [agent == null ? void 0 : agent.state, agent == null ? void 0 : agent.setState]
4421
+ );
4422
+ const externalStateStr = (0, import_react37.useMemo)(
4423
+ () => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
4424
+ [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]
4425
+ );
4426
+ (0, import_react37.useEffect)(() => {
4427
+ if ((agent == null ? void 0 : agent.state) && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) {
4428
+ handleStateUpdate(options.state);
4429
+ }
4430
+ }, [agent, externalStateStr, handleStateUpdate]);
4431
+ const hasStateValues = (0, import_react37.useCallback)((value) => {
4432
+ return Boolean(value && Object.keys(value).length);
4433
+ }, []);
4434
+ const initialStateRef = (0, import_react37.useRef)(
4435
+ isExternalStateManagement(options) ? options.state : "initialState" in options ? options.initialState : void 0
4436
+ );
4437
+ (0, import_react37.useEffect)(() => {
4692
4438
  if (isExternalStateManagement(options)) {
4693
- setState(options.state);
4694
- } else if (coagentStates[name] === void 0) {
4695
- setState(options.initialState === void 0 ? {} : options.initialState);
4439
+ initialStateRef.current = options.state;
4440
+ } else if ("initialState" in options) {
4441
+ initialStateRef.current = options.initialState;
4696
4442
  }
4697
4443
  }, [
4698
- isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
4699
- // reset initialstate on reset
4700
- coagentStates[name] === void 0
4444
+ isExternalStateManagement(options) ? JSON.stringify(options.state) : "initialState" in options ? JSON.stringify(options.initialState) : void 0
4701
4445
  ]);
4702
- (0, import_react21.useEffect)(() => {
4703
- const newConfig = options.config ? options.config : options.configurable ? { configurable: options.configurable } : void 0;
4704
- if (newConfig === void 0)
4446
+ (0, import_react37.useEffect)(() => {
4447
+ if (!agent)
4705
4448
  return;
4706
- setCoagentStatesWithRef((prev) => {
4707
- var _a;
4708
- const existing = (_a = prev[name]) != null ? _a : {
4709
- name,
4710
- state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
4711
- config: {},
4712
- running: false,
4713
- active: false,
4714
- threadId: void 0,
4715
- nodeName: void 0,
4716
- runId: void 0
4717
- };
4718
- if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {
4719
- return prev;
4449
+ const subscriber = {
4450
+ onStateChanged: (args) => {
4451
+ if (isExternalStateManagement(options)) {
4452
+ options.setState(args.state);
4453
+ }
4454
+ },
4455
+ onRunInitialized: (args) => {
4456
+ const runHasState = hasStateValues(args.state);
4457
+ if (runHasState) {
4458
+ handleStateUpdate(args.state);
4459
+ return;
4460
+ }
4461
+ if (hasStateValues(agent.state)) {
4462
+ return;
4463
+ }
4464
+ if (initialStateRef.current !== void 0) {
4465
+ handleStateUpdate(initialStateRef.current);
4466
+ }
4467
+ },
4468
+ onStepStartedEvent: ({ event }) => {
4469
+ nodeNameRef.current = event.stepName;
4470
+ },
4471
+ onRunStartedEvent: () => {
4472
+ nodeNameRef.current = "start";
4473
+ },
4474
+ onRunFinishedEvent: () => {
4475
+ nodeNameRef.current = "end";
4720
4476
  }
4721
- return __spreadProps(__spreadValues({}, prev), {
4722
- [name]: __spreadProps(__spreadValues({}, existing), {
4723
- config: newConfig
4724
- })
4725
- });
4726
- });
4727
- }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);
4728
- const runAgentCallback = useAsyncCallback(
4729
- (hint) => __async(this, null, function* () {
4730
- yield runAgent(name, context, getMessagesFromTap(), sendMessage, runChatCompletion, hint);
4731
- }),
4732
- [name, context, sendMessage, runChatCompletion]
4733
- );
4734
- return (0, import_react21.useMemo)(() => {
4735
- const coagentState = getCoagentState({ coagentStates, name, options });
4736
- return {
4737
- name,
4738
- nodeName: coagentState.nodeName,
4739
- threadId: coagentState.threadId,
4740
- running: coagentState.running,
4741
- state: coagentState.state,
4742
- setState: isExternalStateManagement(options) ? options.setState : setState,
4743
- start: () => startAgent(name, context),
4744
- stop: () => stopAgent(name, context),
4745
- run: runAgentCallback
4746
4477
  };
4747
- }, [name, coagentStates, options, setState, runAgentCallback]);
4748
- }
4749
- function startAgent(name, context) {
4750
- const { setAgentSession } = context;
4751
- setAgentSession({
4752
- agentName: name
4753
- });
4754
- }
4755
- function stopAgent(name, context) {
4756
- const { agentSession, setAgentSession } = context;
4757
- if (agentSession && agentSession.agentName === name) {
4758
- setAgentSession(null);
4759
- context.setCoagentStates((prevAgentStates) => {
4760
- return __spreadProps(__spreadValues({}, prevAgentStates), {
4761
- [name]: __spreadProps(__spreadValues({}, prevAgentStates[name]), {
4762
- running: false,
4763
- active: false,
4764
- threadId: void 0,
4765
- nodeName: void 0,
4766
- runId: void 0
4767
- })
4768
- });
4769
- });
4770
- } else {
4771
- console.warn(`No agent session found for ${name}`);
4772
- }
4773
- }
4774
- function runAgent(name, context, messages, sendMessage, runChatCompletion, hint) {
4775
- return __async(this, null, function* () {
4776
- var _a, _b;
4777
- const { agentSession, setAgentSession } = context;
4778
- if (!agentSession || agentSession.agentName !== name) {
4779
- setAgentSession({
4780
- agentName: name
4478
+ const subscription = agent.subscribe(subscriber);
4479
+ return () => {
4480
+ subscription.unsubscribe();
4481
+ };
4482
+ }, [agent, handleStateUpdate, hasStateValues]);
4483
+ return (0, import_react37.useMemo)(() => {
4484
+ var _a, _b, _c;
4485
+ if (!agent) {
4486
+ const noop = () => {
4487
+ };
4488
+ const noopAsync = () => __async(this, null, function* () {
4781
4489
  });
4490
+ const initialState = (
4491
+ // prefer externally provided state if available
4492
+ (_b = (_a = "state" in options && options.state) != null ? _a : (
4493
+ // then initialState if provided
4494
+ "initialState" in options && options.initialState
4495
+ )) != null ? _b : {}
4496
+ );
4497
+ return {
4498
+ name: options.name,
4499
+ nodeName: nodeNameRef.current,
4500
+ threadId: void 0,
4501
+ running: false,
4502
+ state: initialState,
4503
+ setState: noop,
4504
+ start: noop,
4505
+ stop: noop,
4506
+ run: noopAsync
4507
+ };
4782
4508
  }
4783
- let previousState = null;
4784
- for (let i = messages.length - 1; i >= 0; i--) {
4785
- const message = messages[i];
4786
- if (message.isAgentStateMessage() && message.agentName === name) {
4787
- previousState = message.state;
4788
- }
4789
- }
4790
- let state = ((_b = (_a = context.coagentStatesRef.current) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {};
4791
- if (hint) {
4792
- const hintMessage = hint({ previousState, currentState: state });
4793
- if (hintMessage) {
4794
- yield sendMessage(hintMessage);
4795
- } else {
4796
- yield runChatCompletion();
4797
- }
4798
- } else {
4799
- yield runChatCompletion();
4800
- }
4801
- });
4509
+ return {
4510
+ name: (_c = agent == null ? void 0 : agent.agentId) != null ? _c : options.name,
4511
+ nodeName: nodeNameRef.current,
4512
+ threadId: agent.threadId,
4513
+ running: agent.isRunning,
4514
+ state: agent.state,
4515
+ setState: handleStateUpdate,
4516
+ // TODO: start and run both have same thing. need to figure out
4517
+ start: agent.runAgent,
4518
+ stop: agent.abortRun,
4519
+ run: agent.runAgent
4520
+ };
4521
+ }, [
4522
+ agent == null ? void 0 : agent.state,
4523
+ agent == null ? void 0 : agent.runAgent,
4524
+ agent == null ? void 0 : agent.abortRun,
4525
+ agent == null ? void 0 : agent.runAgent,
4526
+ agent == null ? void 0 : agent.threadId,
4527
+ agent == null ? void 0 : agent.isRunning,
4528
+ agent == null ? void 0 : agent.agentId,
4529
+ handleStateUpdate,
4530
+ options.name
4531
+ ]);
4802
4532
  }
4803
4533
  var isExternalStateManagement = (options) => {
4804
4534
  return "state" in options && "setState" in options;
4805
4535
  };
4806
- var isInternalStateManagementWithInitial = (options) => {
4807
- return "initialState" in options;
4536
+
4537
+ // src/hooks/use-copilot-runtime-client.ts
4538
+ var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
4539
+ var import_react39 = require("react");
4540
+ var import_shared22 = require("@copilotkit/shared");
4541
+ var useCopilotRuntimeClient = (options) => {
4542
+ const { setBannerError } = useToast();
4543
+ const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
4544
+ const lastStructuredErrorRef = (0, import_react39.useRef)(null);
4545
+ const traceUIError = (error, originalError) => __async(void 0, null, function* () {
4546
+ try {
4547
+ const errorEvent = {
4548
+ type: "error",
4549
+ timestamp: Date.now(),
4550
+ context: {
4551
+ source: "ui",
4552
+ request: {
4553
+ operation: "runtimeClient",
4554
+ url: runtimeOptions.url,
4555
+ startTime: Date.now()
4556
+ },
4557
+ technical: {
4558
+ environment: "browser",
4559
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
4560
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
4561
+ }
4562
+ },
4563
+ error
4564
+ };
4565
+ yield onError(errorEvent);
4566
+ } catch (error2) {
4567
+ console.error("Error in onError handler:", error2);
4568
+ }
4569
+ });
4570
+ const runtimeClient = (0, import_react39.useMemo)(() => {
4571
+ return new import_runtime_client_gql3.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
4572
+ handleGQLErrors: (error) => {
4573
+ var _a2;
4574
+ if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
4575
+ const graphQLErrors = error.graphQLErrors;
4576
+ const routeError = (gqlError) => {
4577
+ const extensions = gqlError.extensions;
4578
+ const visibility = extensions == null ? void 0 : extensions.visibility;
4579
+ if (visibility === import_shared22.ErrorVisibility.SILENT) {
4580
+ console.error("CopilotKit Silent Error:", gqlError.message);
4581
+ return;
4582
+ }
4583
+ const now = Date.now();
4584
+ const errorMessage = gqlError.message;
4585
+ if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
4586
+ return;
4587
+ }
4588
+ lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
4589
+ const ckError = createStructuredError(gqlError);
4590
+ if (ckError) {
4591
+ setBannerError(ckError);
4592
+ traceUIError(ckError, gqlError);
4593
+ } else {
4594
+ const fallbackError = new import_shared22.CopilotKitError({
4595
+ message: gqlError.message,
4596
+ code: import_shared22.CopilotKitErrorCode.UNKNOWN
4597
+ });
4598
+ setBannerError(fallbackError);
4599
+ traceUIError(fallbackError, gqlError);
4600
+ }
4601
+ };
4602
+ graphQLErrors.forEach(routeError);
4603
+ } else {
4604
+ const fallbackError = new import_shared22.CopilotKitError({
4605
+ message: (error == null ? void 0 : error.message) || String(error),
4606
+ code: import_shared22.CopilotKitErrorCode.UNKNOWN
4607
+ });
4608
+ setBannerError(fallbackError);
4609
+ traceUIError(fallbackError, error);
4610
+ }
4611
+ },
4612
+ handleGQLWarning: (message) => {
4613
+ console.warn(message);
4614
+ const warningError = new import_shared22.CopilotKitError({
4615
+ message,
4616
+ code: import_shared22.CopilotKitErrorCode.UNKNOWN
4617
+ });
4618
+ setBannerError(warningError);
4619
+ }
4620
+ }));
4621
+ }, [runtimeOptions, setBannerError, onError]);
4622
+ return runtimeClient;
4808
4623
  };
4809
- var getCoagentState = ({
4810
- coagentStates,
4811
- name,
4812
- options
4813
- }) => {
4814
- if (coagentStates[name]) {
4815
- return coagentStates[name];
4816
- } else {
4817
- return {
4818
- name,
4819
- state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
4820
- config: options.config ? options.config : options.configurable ? { configurable: options.configurable } : {},
4821
- running: false,
4822
- active: false,
4823
- threadId: void 0,
4824
- nodeName: void 0,
4825
- runId: void 0
4826
- };
4624
+ function createStructuredError(gqlError) {
4625
+ var _a, _b, _c;
4626
+ const extensions = gqlError.extensions;
4627
+ const originalError = extensions == null ? void 0 : extensions.originalError;
4628
+ const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
4629
+ const code = extensions == null ? void 0 : extensions.code;
4630
+ if (code) {
4631
+ return new import_shared22.CopilotKitError({ message, code });
4827
4632
  }
4828
- };
4633
+ if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
4634
+ return new import_shared22.CopilotKitApiDiscoveryError({ message });
4635
+ }
4636
+ if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
4637
+ return new import_shared22.CopilotKitRemoteEndpointDiscoveryError({ message });
4638
+ }
4639
+ if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
4640
+ return new import_shared22.CopilotKitAgentDiscoveryError({
4641
+ agentName: "",
4642
+ availableAgents: []
4643
+ });
4644
+ }
4645
+ return null;
4646
+ }
4829
4647
 
4830
4648
  // src/hooks/use-copilot-authenticated-action.ts
4831
- var import_react22 = require("react");
4832
- var import_react23 = __toESM(require("react"));
4649
+ var import_react40 = require("react");
4650
+ var import_react41 = __toESM(require("react"));
4833
4651
  function useCopilotAuthenticatedAction_c(action, dependencies) {
4834
4652
  const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
4835
- const pendingActionRef = (0, import_react22.useRef)(null);
4836
- const executeAction2 = (0, import_react22.useCallback)(
4653
+ const pendingActionRef = (0, import_react40.useRef)(null);
4654
+ const executeAction = (0, import_react40.useCallback)(
4837
4655
  (props) => {
4838
4656
  if (typeof action.render === "function") {
4839
4657
  return action.render(props);
4840
4658
  }
4841
- return action.render || import_react23.default.createElement(import_react22.Fragment);
4659
+ return action.render || import_react41.default.createElement(import_react40.Fragment);
4842
4660
  },
4843
4661
  [action]
4844
4662
  );
4845
- const wrappedRender = (0, import_react22.useCallback)(
4663
+ const wrappedRender = (0, import_react40.useCallback)(
4846
4664
  (props) => {
4847
4665
  const isAuthenticated = Object.values(authStates_c || {}).some(
4848
4666
  (state) => state.status === "authenticated"
4849
4667
  );
4850
4668
  if (!isAuthenticated) {
4851
4669
  pendingActionRef.current = props;
4852
- return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? import_react23.default.createElement(authConfig_c.SignInComponent, {
4670
+ return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? import_react41.default.createElement(authConfig_c.SignInComponent, {
4853
4671
  onSignInComplete: (authState) => {
4854
4672
  setAuthStates_c == null ? void 0 : setAuthStates_c((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
4855
4673
  if (pendingActionRef.current) {
4856
- executeAction2(pendingActionRef.current);
4674
+ executeAction(pendingActionRef.current);
4857
4675
  pendingActionRef.current = null;
4858
4676
  }
4859
4677
  }
4860
- }) : import_react23.default.createElement(import_react22.Fragment);
4678
+ }) : import_react41.default.createElement(import_react40.Fragment);
4861
4679
  }
4862
- return executeAction2(props);
4680
+ return executeAction(props);
4863
4681
  },
4864
4682
  [action, authStates_c, setAuthStates_c]
4865
4683
  );
@@ -4872,63 +4690,27 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
4872
4690
  }
4873
4691
 
4874
4692
  // src/hooks/use-langgraph-interrupt.ts
4875
- var import_react24 = require("react");
4876
- var import_shared19 = require("@copilotkit/shared");
4693
+ var import_react42 = require("react");
4694
+ var import_shared23 = require("@copilotkit/shared");
4877
4695
  function useLangGraphInterrupt(action, dependencies) {
4878
- var _a;
4879
- const {
4880
- setLangGraphInterruptAction,
4881
- removeLangGraphInterruptAction,
4882
- langGraphInterruptAction,
4883
- threadId
4884
- } = (0, import_react24.useContext)(CopilotContext);
4885
- const { runChatCompletion } = useCopilotChat();
4696
+ const { setInterruptAction, removeInterruptAction, interruptActions, threadId } = (0, import_react42.useContext)(CopilotContext);
4886
4697
  const { addToast } = useToast();
4887
- const actionId = (0, import_shared19.dataToUUID)(JSON.stringify(action), "lgAction");
4888
- const hasAction = (0, import_react24.useMemo)(
4889
- () => Boolean(langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id),
4890
- [langGraphInterruptAction]
4891
- );
4892
- const isCurrentAction = (0, import_react24.useMemo)(
4893
- () => (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) && (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) === actionId,
4894
- [langGraphInterruptAction]
4895
- );
4896
- (0, import_react24.useEffect)(() => {
4897
- var _a2;
4898
- if (hasAction && isCurrentAction && ((_a2 = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a2.response)) {
4899
- runChatCompletion();
4900
- }
4901
- }, [(_a = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a.response, runChatCompletion, hasAction, isCurrentAction]);
4902
- (0, import_react24.useEffect)(() => {
4698
+ const actionId = (0, import_shared23.dataToUUID)(JSON.stringify(action), "lgAction");
4699
+ (0, import_react42.useEffect)(() => {
4903
4700
  if (!action)
4904
4701
  return;
4905
- if (hasAction && !isCurrentAction && !action.enabled) {
4906
- addToast({
4907
- type: "warning",
4908
- message: "An action is already registered for the interrupt event"
4909
- });
4910
- return;
4911
- }
4912
- if (hasAction && isCurrentAction) {
4913
- return;
4914
- }
4915
- setLangGraphInterruptAction(threadId, __spreadProps(__spreadValues({}, action), { id: actionId }));
4916
- }, [
4917
- action,
4918
- hasAction,
4919
- isCurrentAction,
4920
- setLangGraphInterruptAction,
4921
- removeLangGraphInterruptAction,
4922
- threadId,
4923
- ...dependencies || []
4924
- ]);
4702
+ setInterruptAction(threadId, __spreadProps(__spreadValues({}, action), { id: actionId }));
4703
+ return () => {
4704
+ removeInterruptAction(actionId);
4705
+ };
4706
+ }, [setInterruptAction, removeInterruptAction, threadId, actionId, ...dependencies || []]);
4925
4707
  }
4926
4708
 
4927
4709
  // src/hooks/use-copilot-additional-instructions.ts
4928
- var import_react25 = require("react");
4710
+ var import_react43 = require("react");
4929
4711
  function useCopilotAdditionalInstructions({ instructions, available = "enabled" }, dependencies) {
4930
4712
  const { setAdditionalInstructions } = useCopilotContext();
4931
- (0, import_react25.useEffect)(() => {
4713
+ (0, import_react43.useEffect)(() => {
4932
4714
  if (available === "disabled")
4933
4715
  return;
4934
4716
  setAdditionalInstructions((prevInstructions) => [...prevInstructions || [], instructions]);
@@ -4940,40 +4722,40 @@ function useCopilotAdditionalInstructions({ instructions, available = "enabled"
4940
4722
  }, [available, instructions, setAdditionalInstructions, ...dependencies || []]);
4941
4723
  }
4942
4724
 
4943
- // src/hooks/use-frontend-tool.ts
4944
- function useFrontendTool(tool, dependencies) {
4945
- useCopilotAction(tool, dependencies);
4946
- }
4947
-
4948
- // src/hooks/use-human-in-the-loop.ts
4949
- function useHumanInTheLoop(tool, dependencies) {
4950
- const _a = tool, { render } = _a, toolRest = __objRest(_a, ["render"]);
4951
- useCopilotAction(
4952
- __spreadProps(__spreadValues({}, toolRest), {
4953
- available: tool.available === "disabled" ? tool.available : "remote",
4954
- renderAndWaitForResponse: render
4955
- }),
4956
- dependencies
4957
- );
4958
- }
4959
-
4960
- // src/hooks/use-render-tool-call.ts
4961
- function useRenderToolCall(tool, dependencies) {
4962
- useCopilotAction(
4963
- __spreadProps(__spreadValues({}, tool), {
4964
- available: tool.available === "disabled" ? tool.available : "frontend"
4965
- }),
4966
- dependencies
4967
- );
4968
- }
4969
-
4970
4725
  // src/hooks/use-default-tool.ts
4971
4726
  function useDefaultTool(tool, dependencies) {
4972
4727
  useCopilotAction(__spreadProps(__spreadValues({}, tool), { name: "*" }), dependencies);
4973
4728
  }
4974
4729
 
4975
4730
  // src/lib/copilot-task.ts
4976
- var import_runtime_client_gql9 = require("@copilotkit/runtime-client-gql");
4731
+ var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
4732
+
4733
+ // src/types/frontend-action.ts
4734
+ var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
4735
+ var import_shared24 = require("@copilotkit/shared");
4736
+ function processActionsForRuntimeRequest(actions) {
4737
+ const filteredActions = actions.filter(
4738
+ (action) => action.available !== import_runtime_client_gql4.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
4739
+ ).map((action) => {
4740
+ let available = import_runtime_client_gql4.ActionInputAvailability.Enabled;
4741
+ if (action.disabled) {
4742
+ available = import_runtime_client_gql4.ActionInputAvailability.Disabled;
4743
+ } else if (action.available === "disabled") {
4744
+ available = import_runtime_client_gql4.ActionInputAvailability.Disabled;
4745
+ } else if (action.available === "remote") {
4746
+ available = import_runtime_client_gql4.ActionInputAvailability.Remote;
4747
+ }
4748
+ return {
4749
+ name: action.name,
4750
+ description: action.description || "",
4751
+ jsonSchema: JSON.stringify((0, import_shared24.actionParametersToJsonSchema)(action.parameters || [])),
4752
+ available
4753
+ };
4754
+ });
4755
+ return filteredActions;
4756
+ }
4757
+
4758
+ // src/lib/copilot-task.ts
4977
4759
  var CopilotTask = class {
4978
4760
  constructor(config) {
4979
4761
  this.instructions = config.instructions;
@@ -5001,12 +4783,12 @@ var CopilotTask = class {
5001
4783
  if (this.includeCopilotReadable) {
5002
4784
  contextString += context.getContextString([], defaultCopilotContextCategories);
5003
4785
  }
5004
- const systemMessage = new import_runtime_client_gql9.TextMessage({
4786
+ const systemMessage = new import_runtime_client_gql5.TextMessage({
5005
4787
  content: taskSystemMessage(contextString, this.instructions),
5006
- role: import_runtime_client_gql9.Role.System
4788
+ role: import_runtime_client_gql5.Role.System
5007
4789
  });
5008
4790
  const messages = [systemMessage];
5009
- const runtimeClient = new import_runtime_client_gql9.CopilotRuntimeClient({
4791
+ const runtimeClient = new import_runtime_client_gql5.CopilotRuntimeClient({
5010
4792
  url: context.copilotApiConfig.chatApiEndpoint,
5011
4793
  publicApiKey: context.copilotApiConfig.publicApiKey,
5012
4794
  headers: context.copilotApiConfig.headers,
@@ -5018,9 +4800,9 @@ var CopilotTask = class {
5018
4800
  actions: processActionsForRuntimeRequest(Object.values(actions)),
5019
4801
  url: window.location.href
5020
4802
  },
5021
- messages: (0, import_runtime_client_gql9.convertMessagesToGqlInput)((0, import_runtime_client_gql9.filterAgentStateMessages)(messages)),
4803
+ messages: (0, import_runtime_client_gql5.convertMessagesToGqlInput)((0, import_runtime_client_gql5.filterAgentStateMessages)(messages)),
5022
4804
  metadata: {
5023
- requestType: import_runtime_client_gql9.CopilotRequestType.Task
4805
+ requestType: import_runtime_client_gql5.CopilotRequestType.Task
5024
4806
  },
5025
4807
  forwardedParameters: __spreadValues({
5026
4808
  // if forwardedParameters is provided, use it
@@ -5030,7 +4812,7 @@ var CopilotTask = class {
5030
4812
  properties: context.copilotApiConfig.properties
5031
4813
  }).toPromise();
5032
4814
  const functionCallHandler = context.getFunctionCallHandler(actions);
5033
- const functionCalls = (0, import_runtime_client_gql9.convertGqlOutputToMessages)(
4815
+ const functionCalls = (0, import_runtime_client_gql5.convertGqlOutputToMessages)(
5034
4816
  ((_c = (_b = response.data) == null ? void 0 : _b.generateCopilotResponse) == null ? void 0 : _c.messages) || []
5035
4817
  ).filter((m) => m.isActionExecutionMessage());
5036
4818
  for (const functionCall of functionCalls) {
@@ -5070,20 +4852,21 @@ ${instructions}
5070
4852
  }
5071
4853
  // Annotate the CommonJS export names for ESM import in node:
5072
4854
  0 && (module.exports = {
4855
+ CoAgentStateRendersContext,
4856
+ CoAgentStateRendersProvider,
5073
4857
  CopilotContext,
5074
4858
  CopilotKit,
5075
4859
  CopilotMessagesContext,
5076
4860
  CopilotTask,
5077
4861
  SUGGESTION_RETRY_CONFIG,
4862
+ ThreadsContext,
4863
+ ThreadsProvider,
5078
4864
  defaultCopilotContextCategories,
5079
- extract,
5080
- reloadSuggestions,
5081
- runAgent,
5082
4865
  shouldShowDevConsole,
5083
- startAgent,
5084
- stopAgent,
5085
4866
  useCoAgent,
5086
4867
  useCoAgentStateRender,
4868
+ useCoAgentStateRenders,
4869
+ useConfigureChatSuggestions,
5087
4870
  useCopilotAction,
5088
4871
  useCopilotAdditionalInstructions,
5089
4872
  useCopilotAuthenticatedAction_c,
@@ -5099,7 +4882,9 @@ ${instructions}
5099
4882
  useHumanInTheLoop,
5100
4883
  useLangGraphInterrupt,
5101
4884
  useLangGraphInterruptRender,
4885
+ useLazyToolRenderer,
5102
4886
  useMakeCopilotDocumentReadable,
5103
- useRenderToolCall
4887
+ useRenderToolCall,
4888
+ useThreads
5104
4889
  });
5105
4890
  //# sourceMappingURL=index.js.map