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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (334) hide show
  1. package/CHANGELOG.md +0 -7
  2. package/dist/chunk-24SCZAB4.mjs +143 -0
  3. package/dist/chunk-24SCZAB4.mjs.map +1 -0
  4. package/dist/chunk-36KQV2NA.mjs +1 -0
  5. package/dist/{chunk-U7QULEVO.mjs → chunk-3GURHDG7.mjs} +3 -3
  6. package/dist/{chunk-OAGAFMUM.mjs → chunk-3R423LZT.mjs} +6 -5
  7. package/dist/{chunk-OAGAFMUM.mjs.map → chunk-3R423LZT.mjs.map} +1 -1
  8. package/dist/chunk-5X5DJRQQ.mjs +71 -0
  9. package/dist/chunk-5X5DJRQQ.mjs.map +1 -0
  10. package/dist/{chunk-N4WEHORG.mjs → chunk-6PUNP7CD.mjs} +4 -4
  11. package/dist/chunk-6PUNP7CD.mjs.map +1 -0
  12. package/dist/chunk-7BYHZLPL.mjs +32 -0
  13. package/dist/chunk-7BYHZLPL.mjs.map +1 -0
  14. package/dist/chunk-7DTB7S5V.mjs +83 -0
  15. package/dist/chunk-7DTB7S5V.mjs.map +1 -0
  16. package/dist/chunk-A6NKSGH3.mjs +1 -0
  17. package/dist/{chunk-GT5WI3AF.mjs → chunk-BR5YEYZJ.mjs} +7 -9
  18. package/dist/chunk-BR5YEYZJ.mjs.map +1 -0
  19. package/dist/chunk-CB7CRBDG.mjs +48 -0
  20. package/dist/chunk-CB7CRBDG.mjs.map +1 -0
  21. package/dist/chunk-CYDWEPFL.mjs +1 -0
  22. package/dist/{chunk-BBUQMG45.mjs → chunk-D3QSYDJR.mjs} +3 -3
  23. package/dist/{chunk-BBUQMG45.mjs.map → chunk-D3QSYDJR.mjs.map} +1 -1
  24. package/dist/chunk-DCHSCK62.mjs +549 -0
  25. package/dist/chunk-DCHSCK62.mjs.map +1 -0
  26. package/dist/{chunk-ZLQVRPDS.mjs → chunk-DMLQZG75.mjs} +1 -1
  27. package/dist/chunk-DMLQZG75.mjs.map +1 -0
  28. package/dist/chunk-F555TVE4.mjs +33 -0
  29. package/dist/chunk-F555TVE4.mjs.map +1 -0
  30. package/dist/{chunk-C6IANC2R.mjs → chunk-FBD24VEH.mjs} +7 -43
  31. package/dist/chunk-FBD24VEH.mjs.map +1 -0
  32. package/dist/chunk-FD6FGKYY.mjs +1 -0
  33. package/dist/chunk-FDOMAPJY.mjs +59 -0
  34. package/dist/chunk-FDOMAPJY.mjs.map +1 -0
  35. package/dist/{chunk-E3624YDU.mjs → chunk-GMI4KO4X.mjs} +8 -6
  36. package/dist/{chunk-E3624YDU.mjs.map → chunk-GMI4KO4X.mjs.map} +1 -1
  37. package/dist/chunk-IUSKVYUI.mjs +13 -0
  38. package/dist/chunk-IUSKVYUI.mjs.map +1 -0
  39. package/dist/chunk-JD7BAH7U.mjs +1 -0
  40. package/dist/{chunk-EDBI5PCJ.mjs → chunk-JRT5BJF3.mjs} +2 -2
  41. package/dist/{chunk-N4VN2B5S.mjs → chunk-LHERIF3L.mjs} +2 -2
  42. package/dist/{chunk-DXEQPN43.mjs → chunk-LHKZJ2ND.mjs} +3 -3
  43. package/dist/chunk-NB2FKV2V.mjs +1 -0
  44. package/dist/chunk-NBK4KBLX.mjs +54 -0
  45. package/dist/chunk-NBK4KBLX.mjs.map +1 -0
  46. package/dist/chunk-NG26QEGF.mjs +46 -0
  47. package/dist/chunk-NG26QEGF.mjs.map +1 -0
  48. package/dist/chunk-NROJOTQP.mjs +163 -0
  49. package/dist/chunk-NROJOTQP.mjs.map +1 -0
  50. package/dist/{chunk-MGWRDFBE.mjs → chunk-OVYFRPSN.mjs} +2 -2
  51. package/dist/{chunk-MQYWH4E6.mjs → chunk-QU6NONOD.mjs} +2 -2
  52. package/dist/chunk-R4MR43UQ.mjs +101 -0
  53. package/dist/chunk-R4MR43UQ.mjs.map +1 -0
  54. package/dist/chunk-SPCZTZCY.mjs +1 -0
  55. package/dist/chunk-SPCZTZCY.mjs.map +1 -0
  56. package/dist/chunk-TXI72QHK.mjs +80 -0
  57. package/dist/chunk-TXI72QHK.mjs.map +1 -0
  58. package/dist/chunk-UJBV5GAG.mjs +767 -0
  59. package/dist/chunk-UJBV5GAG.mjs.map +1 -0
  60. package/dist/{chunk-OKCYPO4I.mjs → chunk-WMJVBMUX.mjs} +3 -3
  61. package/dist/{chunk-EUX2P2E7.mjs → chunk-WVLHXIFP.mjs} +11 -9
  62. package/dist/chunk-WVLHXIFP.mjs.map +1 -0
  63. package/dist/{chunk-5FHSUKQL.mjs → chunk-YYN33GSG.mjs} +5 -2
  64. package/dist/chunk-YYN33GSG.mjs.map +1 -0
  65. package/dist/chunk-ZVF5Q6IH.mjs +29 -0
  66. package/dist/chunk-ZVF5Q6IH.mjs.map +1 -0
  67. package/dist/components/CopilotListeners.d.ts +3 -0
  68. package/dist/components/CopilotListeners.js +234 -0
  69. package/dist/components/CopilotListeners.js.map +1 -0
  70. package/dist/components/CopilotListeners.mjs +14 -0
  71. package/dist/components/CopilotListeners.mjs.map +1 -0
  72. package/dist/components/copilot-provider/copilot-messages.js +14 -48
  73. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  74. package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
  75. package/dist/components/copilot-provider/copilotkit-props.d.ts +9 -2
  76. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  77. package/dist/components/copilot-provider/copilotkit.d.ts +2 -1
  78. package/dist/components/copilot-provider/copilotkit.js +528 -370
  79. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  80. package/dist/components/copilot-provider/copilotkit.mjs +15 -10
  81. package/dist/components/copilot-provider/index.d.ts +2 -1
  82. package/dist/components/copilot-provider/index.js +528 -370
  83. package/dist/components/copilot-provider/index.js.map +1 -1
  84. package/dist/components/copilot-provider/index.mjs +16 -10
  85. package/dist/components/dev-console/console-trigger.js +10 -8
  86. package/dist/components/dev-console/console-trigger.js.map +1 -1
  87. package/dist/components/dev-console/console-trigger.mjs +4 -4
  88. package/dist/components/dev-console/developer-console-modal.js +10 -8
  89. package/dist/components/dev-console/developer-console-modal.js.map +1 -1
  90. package/dist/components/dev-console/developer-console-modal.mjs +3 -3
  91. package/dist/components/error-boundary/error-boundary.d.ts +7 -7
  92. package/dist/components/error-boundary/error-boundary.js +3 -3
  93. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  94. package/dist/components/error-boundary/error-boundary.mjs +2 -2
  95. package/dist/components/error-boundary/error-utils.d.ts +1 -1
  96. package/dist/components/error-boundary/error-utils.js +3 -3
  97. package/dist/components/error-boundary/error-utils.js.map +1 -1
  98. package/dist/components/error-boundary/error-utils.mjs +1 -1
  99. package/dist/components/index.d.ts +2 -1
  100. package/dist/components/index.js +528 -370
  101. package/dist/components/index.js.map +1 -1
  102. package/dist/components/index.mjs +17 -10
  103. package/dist/components/toast/exclamation-mark-icon.d.ts +2 -2
  104. package/dist/components/toast/toast-provider.d.ts +3 -3
  105. package/dist/components/usage-banner.d.ts +2 -2
  106. package/dist/context/coagent-state-renders-context.d.ts +24 -0
  107. package/dist/context/coagent-state-renders-context.js +91 -0
  108. package/dist/context/coagent-state-renders-context.js.map +1 -0
  109. package/dist/context/coagent-state-renders-context.mjs +12 -0
  110. package/dist/context/coagent-state-renders-context.mjs.map +1 -0
  111. package/dist/context/copilot-context.d.ts +1 -1
  112. package/dist/context/copilot-context.js +10 -8
  113. package/dist/context/copilot-context.js.map +1 -1
  114. package/dist/context/copilot-context.mjs +1 -1
  115. package/dist/context/copilot-messages-context.d.ts +18 -11
  116. package/dist/context/copilot-messages-context.js.map +1 -1
  117. package/dist/context/copilot-messages-context.mjs +1 -1
  118. package/dist/context/index.d.ts +6 -2
  119. package/dist/context/index.js +110 -10
  120. package/dist/context/index.js.map +1 -1
  121. package/dist/context/index.mjs +20 -4
  122. package/dist/context/threads-context.d.ts +16 -0
  123. package/dist/context/threads-context.js +59 -0
  124. package/dist/context/threads-context.js.map +1 -0
  125. package/dist/context/threads-context.mjs +12 -0
  126. package/dist/context/threads-context.mjs.map +1 -0
  127. package/dist/{copilot-context-cf9de848.d.ts → copilot-context-1cd70a3f.d.ts} +36 -32
  128. package/dist/hooks/index.d.ts +9 -6
  129. package/dist/hooks/index.js +1445 -1839
  130. package/dist/hooks/index.js.map +1 -1
  131. package/dist/hooks/index.mjs +47 -56
  132. package/dist/hooks/use-coagent-state-render-bridge.d.ts +100 -0
  133. package/dist/hooks/use-coagent-state-render-bridge.js +211 -0
  134. package/dist/hooks/use-coagent-state-render-bridge.js.map +1 -0
  135. package/dist/hooks/use-coagent-state-render-bridge.mjs +15 -0
  136. package/dist/hooks/use-coagent-state-render-bridge.mjs.map +1 -0
  137. package/dist/hooks/use-coagent-state-render.js +31 -20
  138. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  139. package/dist/hooks/use-coagent-state-render.mjs +3 -2
  140. package/dist/hooks/use-coagent.d.ts +2 -14
  141. package/dist/hooks/use-coagent.js +109 -1906
  142. package/dist/hooks/use-coagent.js.map +1 -1
  143. package/dist/hooks/use-coagent.mjs +1 -30
  144. package/dist/hooks/use-configure-chat-suggestions.d.ts +36 -0
  145. package/dist/hooks/use-configure-chat-suggestions.js +210 -0
  146. package/dist/hooks/use-configure-chat-suggestions.js.map +1 -0
  147. package/dist/hooks/use-configure-chat-suggestions.mjs +13 -0
  148. package/dist/hooks/use-configure-chat-suggestions.mjs.map +1 -0
  149. package/dist/hooks/use-copilot-action.d.ts +8 -45
  150. package/dist/hooks/use-copilot-action.js +207 -349
  151. package/dist/hooks/use-copilot-action.js.map +1 -1
  152. package/dist/hooks/use-copilot-action.mjs +4 -5
  153. package/dist/hooks/use-copilot-additional-instructions.js +10 -8
  154. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  155. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  156. package/dist/hooks/use-copilot-authenticated-action.js +224 -248
  157. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  158. package/dist/hooks/use-copilot-authenticated-action.mjs +6 -6
  159. package/dist/hooks/use-copilot-chat-headless_c.d.ts +2 -10
  160. package/dist/hooks/use-copilot-chat-headless_c.js +973 -1369
  161. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  162. package/dist/hooks/use-copilot-chat-headless_c.mjs +12 -22
  163. package/dist/hooks/use-copilot-chat.d.ts +2 -10
  164. package/dist/hooks/use-copilot-chat.js +967 -1388
  165. package/dist/hooks/use-copilot-chat.js.map +1 -1
  166. package/dist/hooks/use-copilot-chat.mjs +12 -22
  167. package/dist/hooks/use-copilot-chat_internal.d.ts +38 -14
  168. package/dist/hooks/use-copilot-chat_internal.js +965 -1362
  169. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  170. package/dist/hooks/use-copilot-chat_internal.mjs +13 -23
  171. package/dist/hooks/use-copilot-readable.d.ts +1 -1
  172. package/dist/hooks/use-copilot-readable.js +6 -157
  173. package/dist/hooks/use-copilot-readable.js.map +1 -1
  174. package/dist/hooks/use-copilot-readable.mjs +1 -2
  175. package/dist/hooks/use-default-tool.js +204 -349
  176. package/dist/hooks/use-default-tool.js.map +1 -1
  177. package/dist/hooks/use-default-tool.mjs +5 -6
  178. package/dist/hooks/use-flat-category-store.js +4 -1
  179. package/dist/hooks/use-flat-category-store.js.map +1 -1
  180. package/dist/hooks/use-flat-category-store.mjs +1 -1
  181. package/dist/hooks/use-frontend-tool.d.ts +3 -3
  182. package/dist/hooks/use-frontend-tool.js +30 -370
  183. package/dist/hooks/use-frontend-tool.js.map +1 -1
  184. package/dist/hooks/use-frontend-tool.mjs +1 -6
  185. package/dist/hooks/use-human-in-the-loop.d.ts +4 -3
  186. package/dist/hooks/use-human-in-the-loop.js +61 -393
  187. package/dist/hooks/use-human-in-the-loop.js.map +1 -1
  188. package/dist/hooks/use-human-in-the-loop.mjs +1 -6
  189. package/dist/hooks/use-langgraph-interrupt-render.d.ts +3 -2
  190. package/dist/hooks/use-langgraph-interrupt-render.js +92 -36
  191. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  192. package/dist/hooks/use-langgraph-interrupt-render.mjs +6 -4
  193. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  194. package/dist/hooks/use-langgraph-interrupt.js +24 -1642
  195. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  196. package/dist/hooks/use-langgraph-interrupt.mjs +2 -23
  197. package/dist/hooks/use-lazy-tool-renderer.d.ts +6 -0
  198. package/dist/hooks/use-lazy-tool-renderer.js +53 -0
  199. package/dist/hooks/use-lazy-tool-renderer.js.map +1 -0
  200. package/dist/hooks/use-lazy-tool-renderer.mjs +8 -0
  201. package/dist/hooks/use-lazy-tool-renderer.mjs.map +1 -0
  202. package/dist/hooks/use-make-copilot-document-readable.js +11 -9
  203. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  204. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  205. package/dist/hooks/use-render-tool-call.d.ts +7 -6
  206. package/dist/hooks/use-render-tool-call.js +36 -386
  207. package/dist/hooks/use-render-tool-call.js.map +1 -1
  208. package/dist/hooks/use-render-tool-call.mjs +1 -6
  209. package/dist/index.d.ts +11 -6
  210. package/dist/index.js +1841 -2056
  211. package/dist/index.js.map +1 -1
  212. package/dist/index.mjs +78 -59
  213. package/dist/lib/copilot-task.d.ts +1 -1
  214. package/dist/lib/copilot-task.js +1 -0
  215. package/dist/lib/copilot-task.js.map +1 -1
  216. package/dist/lib/copilot-task.mjs +18 -11
  217. package/dist/lib/index.d.ts +1 -1
  218. package/dist/lib/index.js +1 -0
  219. package/dist/lib/index.js.map +1 -1
  220. package/dist/lib/index.mjs +18 -11
  221. package/dist/setupTests.d.ts +2 -2
  222. package/dist/types/frontend-action.d.ts +5 -5
  223. package/dist/types/index.d.ts +4 -0
  224. package/dist/types/index.js.map +1 -1
  225. package/dist/types/index.mjs +2 -1
  226. package/dist/types/interrupt-action.d.ts +1 -1
  227. package/dist/types/interrupt-action.js.map +1 -1
  228. package/dist/types/interrupt-action.mjs +1 -0
  229. package/dist/utils/index.d.ts +0 -12
  230. package/dist/utils/index.js +6 -325
  231. package/dist/utils/index.js.map +1 -1
  232. package/dist/utils/index.mjs +1 -21
  233. package/dist/utils/utils.js.map +1 -1
  234. package/dist/v2/index.d.ts +2 -0
  235. package/dist/v2/index.js +27 -0
  236. package/dist/v2/index.js.map +1 -0
  237. package/dist/v2/index.mjs +4 -0
  238. package/dist/v2/index.mjs.map +1 -0
  239. package/package.json +20 -9
  240. package/src/components/CopilotListeners.tsx +82 -0
  241. package/src/components/copilot-provider/copilot-messages.tsx +46 -47
  242. package/src/components/copilot-provider/copilotkit-props.tsx +8 -1
  243. package/src/components/copilot-provider/copilotkit.tsx +177 -144
  244. package/src/components/error-boundary/error-utils.tsx +3 -3
  245. package/src/context/coagent-state-renders-context.tsx +76 -0
  246. package/src/context/copilot-context.tsx +21 -21
  247. package/src/context/copilot-messages-context.tsx +3 -3
  248. package/src/context/index.ts +8 -0
  249. package/src/context/threads-context.tsx +41 -0
  250. package/src/hooks/index.ts +7 -3
  251. package/src/hooks/use-coagent-state-render-bridge.tsx +293 -0
  252. package/src/hooks/use-coagent-state-render.ts +4 -7
  253. package/src/hooks/use-coagent.ts +129 -249
  254. package/src/hooks/use-configure-chat-suggestions.tsx +85 -0
  255. package/src/hooks/use-copilot-action.ts +88 -199
  256. package/src/hooks/use-copilot-chat-headless_c.ts +2 -1
  257. package/src/hooks/use-copilot-chat.ts +4 -1
  258. package/src/hooks/use-copilot-chat_internal.ts +349 -258
  259. package/src/hooks/use-copilot-readable.ts +6 -26
  260. package/src/hooks/use-flat-category-store.ts +4 -3
  261. package/src/hooks/use-frontend-tool.ts +67 -8
  262. package/src/hooks/use-human-in-the-loop.ts +111 -13
  263. package/src/hooks/use-langgraph-interrupt-render.ts +90 -40
  264. package/src/hooks/use-langgraph-interrupt.ts +18 -47
  265. package/src/hooks/use-lazy-tool-renderer.tsx +30 -0
  266. package/src/hooks/use-make-copilot-document-readable.ts +1 -1
  267. package/src/hooks/use-render-tool-call.ts +73 -13
  268. package/src/types/index.ts +1 -0
  269. package/src/types/interrupt-action.ts +8 -4
  270. package/src/utils/index.ts +0 -3
  271. package/src/utils/utils.ts +7 -0
  272. package/src/v2/index.ts +2 -0
  273. package/src/v2/styles.css +1 -0
  274. package/tsup.config.ts +1 -1
  275. package/dist/chunk-5FHSUKQL.mjs.map +0 -1
  276. package/dist/chunk-6GPVUMBU.mjs +0 -13
  277. package/dist/chunk-6GPVUMBU.mjs.map +0 -1
  278. package/dist/chunk-AKR2SSUJ.mjs +0 -22
  279. package/dist/chunk-AKR2SSUJ.mjs.map +0 -1
  280. package/dist/chunk-BXXJQ2BL.mjs +0 -239
  281. package/dist/chunk-BXXJQ2BL.mjs.map +0 -1
  282. package/dist/chunk-C6IANC2R.mjs.map +0 -1
  283. package/dist/chunk-DZTU6PGS.mjs +0 -1
  284. package/dist/chunk-EUX2P2E7.mjs.map +0 -1
  285. package/dist/chunk-EVVO67QO.mjs +0 -25
  286. package/dist/chunk-EVVO67QO.mjs.map +0 -1
  287. package/dist/chunk-GGLAHG3I.mjs +0 -804
  288. package/dist/chunk-GGLAHG3I.mjs.map +0 -1
  289. package/dist/chunk-GT5WI3AF.mjs.map +0 -1
  290. package/dist/chunk-HDOG2RTM.mjs +0 -37
  291. package/dist/chunk-HDOG2RTM.mjs.map +0 -1
  292. package/dist/chunk-MIXSWZSB.mjs +0 -71
  293. package/dist/chunk-MIXSWZSB.mjs.map +0 -1
  294. package/dist/chunk-N4WEHORG.mjs.map +0 -1
  295. package/dist/chunk-NSBAWITG.mjs +0 -332
  296. package/dist/chunk-NSBAWITG.mjs.map +0 -1
  297. package/dist/chunk-OT5NHMEC.mjs +0 -723
  298. package/dist/chunk-OT5NHMEC.mjs.map +0 -1
  299. package/dist/chunk-T3376SZS.mjs +0 -142
  300. package/dist/chunk-T3376SZS.mjs.map +0 -1
  301. package/dist/chunk-YPBKY4KY.mjs +0 -1
  302. package/dist/chunk-YPSGKPDA.mjs +0 -1
  303. package/dist/chunk-ZLQVRPDS.mjs.map +0 -1
  304. package/dist/chunk-ZVOLWJCY.mjs +0 -47
  305. package/dist/chunk-ZVOLWJCY.mjs.map +0 -1
  306. package/dist/hooks/use-chat.d.ts +0 -145
  307. package/dist/hooks/use-chat.js +0 -1129
  308. package/dist/hooks/use-chat.js.map +0 -1
  309. package/dist/hooks/use-chat.mjs +0 -14
  310. package/dist/index-1f5b66ac.d.ts +0 -36
  311. package/dist/utils/extract.d.ts +0 -43
  312. package/dist/utils/extract.js +0 -208
  313. package/dist/utils/extract.js.map +0 -1
  314. package/dist/utils/extract.mjs +0 -25
  315. package/dist/utils/suggestions.d.ts +0 -11
  316. package/dist/utils/suggestions.js +0 -343
  317. package/dist/utils/suggestions.js.map +0 -1
  318. package/dist/utils/suggestions.mjs +0 -25
  319. package/src/hooks/use-chat.ts +0 -1142
  320. package/src/utils/extract.ts +0 -215
  321. package/src/utils/suggestions.ts +0 -208
  322. /package/dist/{chunk-DZTU6PGS.mjs.map → chunk-36KQV2NA.mjs.map} +0 -0
  323. /package/dist/{chunk-U7QULEVO.mjs.map → chunk-3GURHDG7.mjs.map} +0 -0
  324. /package/dist/{chunk-YPBKY4KY.mjs.map → chunk-A6NKSGH3.mjs.map} +0 -0
  325. /package/dist/{chunk-YPSGKPDA.mjs.map → chunk-CYDWEPFL.mjs.map} +0 -0
  326. /package/dist/{hooks/use-chat.mjs.map → chunk-FD6FGKYY.mjs.map} +0 -0
  327. /package/dist/{utils/extract.mjs.map → chunk-JD7BAH7U.mjs.map} +0 -0
  328. /package/dist/{chunk-EDBI5PCJ.mjs.map → chunk-JRT5BJF3.mjs.map} +0 -0
  329. /package/dist/{chunk-N4VN2B5S.mjs.map → chunk-LHERIF3L.mjs.map} +0 -0
  330. /package/dist/{chunk-DXEQPN43.mjs.map → chunk-LHKZJ2ND.mjs.map} +0 -0
  331. /package/dist/{utils/suggestions.mjs.map → chunk-NB2FKV2V.mjs.map} +0 -0
  332. /package/dist/{chunk-MGWRDFBE.mjs.map → chunk-OVYFRPSN.mjs.map} +0 -0
  333. /package/dist/{chunk-MQYWH4E6.mjs.map → chunk-QU6NONOD.mjs.map} +0 -0
  334. /package/dist/{chunk-OKCYPO4I.mjs.map → chunk-WMJVBMUX.mjs.map} +0 -0
@@ -79,17 +79,15 @@ var __async = (__this, __arguments, generator) => {
79
79
  // src/hooks/index.ts
80
80
  var hooks_exports = {};
81
81
  __export(hooks_exports, {
82
- runAgent: () => runAgent,
83
- startAgent: () => startAgent,
84
- stopAgent: () => stopAgent,
85
82
  useCoAgent: () => useCoAgent,
86
83
  useCoAgentStateRender: () => useCoAgentStateRender,
84
+ useConfigureChatSuggestions: () => useConfigureChatSuggestions,
87
85
  useCopilotAction: () => useCopilotAction,
88
86
  useCopilotAdditionalInstructions: () => useCopilotAdditionalInstructions,
89
87
  useCopilotAuthenticatedAction_c: () => useCopilotAuthenticatedAction_c,
90
- useCopilotChat: () => useCopilotChat2,
88
+ useCopilotChat: () => useCopilotChat,
91
89
  useCopilotChatHeadless_c: () => useCopilotChatHeadless_c,
92
- useCopilotChatInternal: () => useCopilotChat,
90
+ useCopilotChatInternal: () => useCopilotChatInternal,
93
91
  useCopilotReadable: () => useCopilotReadable,
94
92
  useCopilotRuntimeClient: () => useCopilotRuntimeClient,
95
93
  useDefaultTool: () => useDefaultTool,
@@ -97,13 +95,14 @@ __export(hooks_exports, {
97
95
  useHumanInTheLoop: () => useHumanInTheLoop,
98
96
  useLangGraphInterrupt: () => useLangGraphInterrupt,
99
97
  useLangGraphInterruptRender: () => useLangGraphInterruptRender,
98
+ useLazyToolRenderer: () => useLazyToolRenderer,
100
99
  useMakeCopilotDocumentReadable: () => useMakeCopilotDocumentReadable,
101
- useRenderToolCall: () => useRenderToolCall
100
+ useRenderToolCall: () => useRenderToolCall2
102
101
  });
103
102
  module.exports = __toCommonJS(hooks_exports);
104
103
 
105
104
  // src/hooks/use-copilot-chat_internal.ts
106
- var import_react10 = require("react");
105
+ var import_react12 = require("react");
107
106
 
108
107
  // src/context/copilot-context.tsx
109
108
  var import_react = __toESM(require("react"));
@@ -113,10 +112,8 @@ var emptyCopilotContext = {
113
112
  },
114
113
  removeAction: () => {
115
114
  },
116
- coAgentStateRenders: {},
117
- setCoAgentStateRender: () => {
118
- },
119
- removeCoAgentStateRender: () => {
115
+ setRegisteredActions: () => "",
116
+ removeRegisteredAction: () => {
120
117
  },
121
118
  chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
122
119
  getContextString: (documents, categories) => returnAndThrowInDebug(""),
@@ -136,7 +133,6 @@ var emptyCopilotContext = {
136
133
  addDocumentContext: () => returnAndThrowInDebug(""),
137
134
  removeDocumentContext: () => {
138
135
  },
139
- runtimeClient: {},
140
136
  copilotApiConfig: new class {
141
137
  get chatApiEndpoint() {
142
138
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
@@ -176,10 +172,15 @@ var emptyCopilotContext = {
176
172
  extensions: {},
177
173
  setExtensions: () => {
178
174
  },
179
- langGraphInterruptAction: null,
180
- setLangGraphInterruptAction: () => {
175
+ interruptActions: {},
176
+ setInterruptAction: () => {
177
+ },
178
+ removeInterruptAction: () => {
179
+ },
180
+ interruptEventQueue: {},
181
+ addInterruptEvent: () => {
181
182
  },
182
- removeLangGraphInterruptAction: () => {
183
+ removeInterruptEvent: () => {
183
184
  },
184
185
  onError: () => {
185
186
  },
@@ -204,186 +205,22 @@ function returnAndThrowInDebug(_value) {
204
205
  throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
205
206
  }
206
207
 
207
- // src/context/copilot-messages-context.tsx
208
- var import_react2 = __toESM(require("react"));
209
- var emptyCopilotContext2 = {
210
- messages: [],
211
- setMessages: () => [],
212
- // suggestions state
213
- suggestions: [],
214
- setSuggestions: () => []
215
- };
216
- var CopilotMessagesContext = import_react2.default.createContext(emptyCopilotContext2);
217
- function useCopilotMessagesContext() {
218
- const context = import_react2.default.useContext(CopilotMessagesContext);
219
- if (context === emptyCopilotContext2) {
220
- throw new Error(
221
- "A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`"
222
- );
223
- }
224
- return context;
225
- }
226
-
227
- // src/hooks/use-chat.ts
228
- var import_react6 = require("react");
229
- var import_react_dom = require("react-dom");
230
- var import_shared4 = require("@copilotkit/shared");
231
- var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
232
-
233
- // src/types/frontend-action.ts
234
- var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
235
- var import_shared = require("@copilotkit/shared");
236
- function processActionsForRuntimeRequest(actions) {
237
- const filteredActions = actions.filter(
238
- (action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
239
- ).map((action) => {
240
- let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
241
- if (action.disabled) {
242
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
243
- } else if (action.available === "disabled") {
244
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
245
- } else if (action.available === "remote") {
246
- available = import_runtime_client_gql.ActionInputAvailability.Remote;
247
- }
248
- return {
249
- name: action.name,
250
- description: action.description || "",
251
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
252
- available
253
- };
254
- });
255
- return filteredActions;
256
- }
257
-
258
- // src/hooks/use-copilot-runtime-client.ts
259
- var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
208
+ // src/components/error-boundary/error-utils.tsx
209
+ var import_react3 = require("react");
260
210
 
261
211
  // src/components/toast/toast-provider.tsx
262
- var import_react3 = require("react");
263
- var import_shared2 = require("@copilotkit/shared");
212
+ var import_react2 = require("react");
213
+ var import_shared = require("@copilotkit/shared");
264
214
  var import_jsx_runtime = require("react/jsx-runtime");
265
- var ToastContext = (0, import_react3.createContext)(void 0);
215
+ var ToastContext = (0, import_react2.createContext)(void 0);
266
216
  function useToast() {
267
- const context = (0, import_react3.useContext)(ToastContext);
217
+ const context = (0, import_react2.useContext)(ToastContext);
268
218
  if (!context) {
269
219
  throw new Error("useToast must be used within a ToastProvider");
270
220
  }
271
221
  return context;
272
222
  }
273
223
 
274
- // src/hooks/use-copilot-runtime-client.ts
275
- var import_react4 = require("react");
276
- var import_shared3 = require("@copilotkit/shared");
277
- var useCopilotRuntimeClient = (options) => {
278
- const { setBannerError } = useToast();
279
- const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
280
- const lastStructuredErrorRef = (0, import_react4.useRef)(null);
281
- const traceUIError = (error, originalError) => __async(void 0, null, function* () {
282
- try {
283
- const errorEvent = {
284
- type: "error",
285
- timestamp: Date.now(),
286
- context: {
287
- source: "ui",
288
- request: {
289
- operation: "runtimeClient",
290
- url: runtimeOptions.url,
291
- startTime: Date.now()
292
- },
293
- technical: {
294
- environment: "browser",
295
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
296
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
297
- }
298
- },
299
- error
300
- };
301
- yield onError(errorEvent);
302
- } catch (error2) {
303
- console.error("Error in onError handler:", error2);
304
- }
305
- });
306
- const runtimeClient = (0, import_react4.useMemo)(() => {
307
- return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
308
- handleGQLErrors: (error) => {
309
- var _a2;
310
- if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
311
- const graphQLErrors = error.graphQLErrors;
312
- const routeError = (gqlError) => {
313
- const extensions = gqlError.extensions;
314
- const visibility = extensions == null ? void 0 : extensions.visibility;
315
- if (visibility === import_shared3.ErrorVisibility.SILENT) {
316
- console.error("CopilotKit Silent Error:", gqlError.message);
317
- return;
318
- }
319
- const now = Date.now();
320
- const errorMessage = gqlError.message;
321
- if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
322
- return;
323
- }
324
- lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
325
- const ckError = createStructuredError(gqlError);
326
- if (ckError) {
327
- setBannerError(ckError);
328
- traceUIError(ckError, gqlError);
329
- } else {
330
- const fallbackError = new import_shared3.CopilotKitError({
331
- message: gqlError.message,
332
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
333
- });
334
- setBannerError(fallbackError);
335
- traceUIError(fallbackError, gqlError);
336
- }
337
- };
338
- graphQLErrors.forEach(routeError);
339
- } else {
340
- const fallbackError = new import_shared3.CopilotKitError({
341
- message: (error == null ? void 0 : error.message) || String(error),
342
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
343
- });
344
- setBannerError(fallbackError);
345
- traceUIError(fallbackError, error);
346
- }
347
- },
348
- handleGQLWarning: (message) => {
349
- console.warn(message);
350
- const warningError = new import_shared3.CopilotKitError({
351
- message,
352
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
353
- });
354
- setBannerError(warningError);
355
- }
356
- }));
357
- }, [runtimeOptions, setBannerError, onError]);
358
- return runtimeClient;
359
- };
360
- function createStructuredError(gqlError) {
361
- var _a, _b, _c;
362
- const extensions = gqlError.extensions;
363
- const originalError = extensions == null ? void 0 : extensions.originalError;
364
- const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
365
- const code = extensions == null ? void 0 : extensions.code;
366
- if (code) {
367
- return new import_shared3.CopilotKitError({ message, code });
368
- }
369
- if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
370
- return new import_shared3.CopilotKitApiDiscoveryError({ message });
371
- }
372
- if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
373
- return new import_shared3.CopilotKitRemoteEndpointDiscoveryError({ message });
374
- }
375
- if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
376
- return new import_shared3.CopilotKitAgentDiscoveryError({
377
- agentName: "",
378
- availableAgents: []
379
- });
380
- }
381
- return null;
382
- }
383
-
384
- // src/components/error-boundary/error-utils.tsx
385
- var import_react5 = require("react");
386
-
387
224
  // src/components/toast/exclamation-mark-icon.tsx
388
225
  var import_jsx_runtime2 = require("react/jsx-runtime");
389
226
  var ExclamationMarkIcon = ({
@@ -465,9 +302,9 @@ function ErrorToast({ errors }) {
465
302
  }
466
303
  function useErrorToast() {
467
304
  const { addToast } = useToast();
468
- return (0, import_react5.useCallback)(
469
- (error) => {
470
- const errorId = error.map((err) => {
305
+ return (0, import_react3.useCallback)(
306
+ (errors) => {
307
+ const errorId = errors.map((err) => {
471
308
  var _a, _b;
472
309
  const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
473
310
  const stack = err.stack || "";
@@ -477,7 +314,7 @@ function useErrorToast() {
477
314
  type: "error",
478
315
  id: errorId,
479
316
  // Toast libraries typically dedupe by id
480
- message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
317
+ message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors })
481
318
  });
482
319
  },
483
320
  [addToast]
@@ -485,7 +322,7 @@ function useErrorToast() {
485
322
  }
486
323
  function useAsyncCallback(callback, deps) {
487
324
  const addErrorToast = useErrorToast();
488
- return (0, import_react5.useCallback)((...args) => __async(this, null, function* () {
325
+ return (0, import_react3.useCallback)((...args) => __async(this, null, function* () {
489
326
  try {
490
327
  return yield callback(...args);
491
328
  } catch (error) {
@@ -496,1186 +333,880 @@ function useAsyncCallback(callback, deps) {
496
333
  }), deps);
497
334
  }
498
335
 
499
- // src/hooks/use-chat.ts
500
- function useChat(options) {
336
+ // src/hooks/use-copilot-chat_internal.ts
337
+ var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
338
+
339
+ // src/context/coagent-state-renders-context.tsx
340
+ var import_react4 = require("react");
341
+ var import_jsx_runtime4 = require("react/jsx-runtime");
342
+ var CoAgentStateRendersContext = (0, import_react4.createContext)(
343
+ void 0
344
+ );
345
+ function useCoAgentStateRenders() {
346
+ const context = (0, import_react4.useContext)(CoAgentStateRendersContext);
347
+ if (!context) {
348
+ throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
349
+ }
350
+ return context;
351
+ }
352
+
353
+ // src/hooks/use-langgraph-interrupt-render.ts
354
+ var import_react5 = __toESM(require("react"));
355
+ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
356
+ var import_shared2 = require("@copilotkit/shared");
357
+ var InterruptRenderer = ({ event, result, render, resolve }) => {
358
+ return render({ event, result, resolve });
359
+ };
360
+ function useLangGraphInterruptRender(agent) {
501
361
  const {
502
- messages,
503
- setMessages,
504
- makeSystemMessageCallback,
505
- copilotConfig,
506
- setIsLoading,
507
- initialMessages,
508
- isLoading,
509
- actions,
510
- onFunctionCall,
511
- onCoAgentStateRender,
512
- setCoagentStatesWithRef,
513
- coagentStatesRef,
362
+ interruptActions,
514
363
  agentSession,
515
- setAgentSession,
516
364
  threadId,
517
- setThreadId,
518
- runId,
519
- setRunId,
520
- chatAbortControllerRef,
521
- agentLock,
522
- extensions,
523
- setExtensions,
524
- langGraphInterruptAction,
525
- setLangGraphInterruptAction,
526
- disableSystemMessage = false
527
- } = options;
528
- const runChatCompletionRef = (0, import_react6.useRef)();
529
- const addErrorToast = useErrorToast();
530
- const { setBannerError } = useToast();
531
- const { onError, showDevConsole, getAllContext } = useCopilotContext();
532
- const copilotReadableContext = getAllContext();
533
- const context = (0, import_react6.useMemo)(
534
- () => copilotReadableContext.map((contextItem) => {
535
- const [description, ...valueParts] = contextItem.value.split(":");
536
- return {
537
- description: description.trim(),
538
- value: valueParts.join(":").trim()
539
- };
540
- }),
541
- [copilotReadableContext]
542
- );
543
- const traceUIError = (error, originalError) => __async(this, null, function* () {
544
- try {
545
- const traceEvent = {
546
- type: "error",
547
- timestamp: Date.now(),
548
- context: {
549
- source: "ui",
550
- request: {
551
- operation: "useChatCompletion",
552
- url: copilotConfig.chatApiEndpoint,
553
- startTime: Date.now()
554
- },
555
- technical: {
556
- environment: "browser",
557
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
558
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
559
- }
560
- },
561
- error
562
- };
563
- yield onError(traceEvent);
564
- } catch (traceError) {
565
- console.error("Error in use-chat onError handler:", traceError);
566
- }
567
- });
568
- const agentSessionRef = (0, import_react6.useRef)(agentSession);
569
- agentSessionRef.current = agentSession;
570
- const runIdRef = (0, import_react6.useRef)(runId);
571
- runIdRef.current = runId;
572
- const extensionsRef = (0, import_react6.useRef)(extensions);
573
- extensionsRef.current = extensions;
574
- const publicApiKey = copilotConfig.publicApiKey;
575
- const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared4.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
576
- const runtimeClient = useCopilotRuntimeClient({
577
- url: copilotConfig.chatApiEndpoint,
578
- publicApiKey: copilotConfig.publicApiKey,
579
- headers,
580
- credentials: copilotConfig.credentials,
581
- showDevConsole,
582
- onError
583
- });
584
- const pendingAppendsRef = (0, import_react6.useRef)([]);
585
- const runChatCompletion = useAsyncCallback(
586
- (previousMessages) => __async(this, null, function* () {
587
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
588
- setIsLoading(true);
589
- const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
590
- if ((interruptEvent == null ? void 0 : interruptEvent.name) === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent && (interruptEvent == null ? void 0 : interruptEvent.value) && !(interruptEvent == null ? void 0 : interruptEvent.response) && agentSessionRef.current) {
591
- addErrorToast([
592
- new Error(
593
- "A message was sent while interrupt is active. This will cause failure on the agent side"
594
- )
595
- ]);
596
- }
597
- let newMessages = [
598
- new import_runtime_client_gql3.TextMessage({
599
- content: "",
600
- role: import_runtime_client_gql3.Role.Assistant
601
- })
602
- ];
603
- chatAbortControllerRef.current = new AbortController();
604
- setMessages([...previousMessages, ...newMessages]);
605
- const messagesWithContext = disableSystemMessage ? [...initialMessages || [], ...previousMessages] : [makeSystemMessageCallback(), ...initialMessages || [], ...previousMessages];
606
- const finalProperties = __spreadValues({}, copilotConfig.properties || {});
607
- let mcpServersToUse = null;
608
- if (copilotConfig.mcpServers && Array.isArray(copilotConfig.mcpServers) && copilotConfig.mcpServers.length > 0) {
609
- mcpServersToUse = copilotConfig.mcpServers;
610
- } else if (((_a = copilotConfig.properties) == null ? void 0 : _a.mcpServers) && Array.isArray(copilotConfig.properties.mcpServers) && copilotConfig.properties.mcpServers.length > 0) {
611
- mcpServersToUse = copilotConfig.properties.mcpServers;
612
- }
613
- if (mcpServersToUse) {
614
- finalProperties.mcpServers = mcpServersToUse;
615
- copilotConfig.mcpServers = mcpServersToUse;
616
- }
617
- const isAgentRun = agentSessionRef.current !== null;
618
- const stream = runtimeClient.asStream(
619
- runtimeClient.generateCopilotResponse({
620
- data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
621
- frontend: {
622
- actions: processActionsForRuntimeRequest(actions),
623
- url: window.location.href
624
- },
365
+ interruptEventQueue,
366
+ addInterruptEvent,
367
+ removeInterruptEvent
368
+ } = useCopilotContext();
369
+ (0, import_react5.useEffect)(() => {
370
+ if (!agent)
371
+ return;
372
+ const subscriber = {
373
+ onCustomEvent: ({ event }) => {
374
+ if (event.name === "on_interrupt") {
375
+ const eventData = {
376
+ name: import_runtime_client_gql.MetaEventName.LangGraphInterruptEvent,
377
+ type: event.type,
378
+ value: (0, import_shared2.parseJson)(event.value, event.value)
379
+ };
380
+ const eventId = (0, import_shared2.dataToUUID)(JSON.stringify(eventData), "interruptEvents");
381
+ addInterruptEvent({
382
+ eventId,
625
383
  threadId,
626
- runId: runIdRef.current,
627
- extensions: extensionsRef.current,
628
- metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event]),
629
- messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)((0, import_runtime_client_gql3.filterAgentStateMessages)(messagesWithContext))
630
- }, copilotConfig.cloud ? {
631
- cloud: __spreadValues({}, ((_d = (_c = (_b = copilotConfig.cloud.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic) == null ? void 0 : _d.enabled) ? {
632
- guardrails: {
633
- inputValidationRules: {
634
- allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
635
- denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
636
- }
637
- }
638
- } : {})
639
- } : {}), {
640
- metadata: {
641
- requestType: import_runtime_client_gql3.CopilotRequestType.Chat
642
- }
643
- }), agentSessionRef.current ? {
644
- agentSession: agentSessionRef.current
645
- } : {}), {
646
- agentStates: Object.values(coagentStatesRef.current).map((state) => {
647
- const stateObject = {
648
- agentName: state.name,
649
- state: JSON.stringify(state.state)
650
- };
651
- if (state.config !== void 0) {
652
- stateObject.config = JSON.stringify(state.config);
653
- }
654
- return stateObject;
655
- }),
656
- forwardedParameters: options.forwardedParameters || {},
657
- context
658
- }),
659
- properties: finalProperties,
660
- signal: (_e = chatAbortControllerRef.current) == null ? void 0 : _e.signal
661
- })
662
- );
663
- const guardrailsEnabled = ((_h = (_g = (_f = copilotConfig.cloud) == null ? void 0 : _f.guardrails) == null ? void 0 : _g.input) == null ? void 0 : _h.restrictToTopic.enabled) || false;
664
- const reader = stream.getReader();
665
- let executedCoAgentStateRenders = [];
666
- let followUp = void 0;
667
- let messages2 = [];
668
- let syncedMessages = [];
669
- let interruptMessages = [];
670
- try {
671
- while (true) {
672
- let done, value;
673
- try {
674
- const readResult = yield reader.read();
675
- done = readResult.done;
676
- value = readResult.value;
677
- } catch (readError) {
678
- break;
679
- }
680
- if (done) {
681
- if (chatAbortControllerRef.current.signal.aborted) {
682
- return [];
683
- }
684
- break;
685
- }
686
- if (!(value == null ? void 0 : value.generateCopilotResponse)) {
687
- continue;
688
- }
689
- runIdRef.current = value.generateCopilotResponse.runId || null;
690
- extensionsRef.current = import_runtime_client_gql3.CopilotRuntimeClient.removeGraphQLTypename(
691
- value.generateCopilotResponse.extensions || {}
692
- );
693
- setRunId(runIdRef.current);
694
- setExtensions(extensionsRef.current);
695
- let rawMessagesResponse = value.generateCopilotResponse.messages;
696
- const metaEvents = (_j = (_i = value.generateCopilotResponse) == null ? void 0 : _i.metaEvents) != null ? _j : [];
697
- (metaEvents != null ? metaEvents : []).forEach((ev) => {
698
- if (ev.name === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent) {
699
- let eventValue = (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev).value;
700
- eventValue = (0, import_shared4.parseJson)(eventValue, eventValue);
701
- setLangGraphInterruptAction(threadId, {
702
- event: __spreadProps(__spreadValues({}, (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev)), {
703
- value: eventValue
704
- })
705
- });
706
- }
707
- if (ev.name === import_runtime_client_gql3.MetaEventName.CopilotKitLangGraphInterruptEvent) {
708
- const data = ev.data;
709
- rawMessagesResponse = [...rawMessagesResponse, ...data.messages];
710
- interruptMessages = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
711
- // @ts-ignore
712
- (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(data.messages)
713
- );
714
- }
715
- });
716
- messages2 = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
717
- (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(rawMessagesResponse)
718
- );
719
- newMessages = [];
720
- if (((_k = value.generateCopilotResponse.status) == null ? void 0 : _k.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
721
- const guardrailsReason = ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || "";
722
- newMessages = [
723
- new import_runtime_client_gql3.TextMessage({
724
- role: import_runtime_client_gql3.MessageRole.Assistant,
725
- content: guardrailsReason
726
- })
727
- ];
728
- const guardrailsError = new import_shared4.CopilotKitError({
729
- message: `Guardrails validation failed: ${guardrailsReason}`,
730
- code: import_shared4.CopilotKitErrorCode.MISUSE
731
- });
732
- yield traceUIError(guardrailsError, {
733
- statusReason: value.generateCopilotResponse.status.reason,
734
- statusDetails: value.generateCopilotResponse.status.details
735
- });
736
- setMessages([...previousMessages, ...newMessages]);
737
- break;
738
- }
739
- if (((_m = value.generateCopilotResponse.status) == null ? void 0 : _m.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "UNKNOWN_ERROR") {
740
- const errorMessage = ((_n = value.generateCopilotResponse.status.details) == null ? void 0 : _n.description) || "An unknown error occurred";
741
- const statusDetails = value.generateCopilotResponse.status.details;
742
- const originalError = (statusDetails == null ? void 0 : statusDetails.originalError) || (statusDetails == null ? void 0 : statusDetails.error);
743
- const originalCode = (originalError == null ? void 0 : originalError.code) || ((_o = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _o.code);
744
- const originalSeverity = (originalError == null ? void 0 : originalError.severity) || ((_p = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _p.severity);
745
- const originalVisibility = (originalError == null ? void 0 : originalError.visibility) || ((_q = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _q.visibility);
746
- let errorCode = import_shared4.CopilotKitErrorCode.NETWORK_ERROR;
747
- if (originalCode && Object.values(import_shared4.CopilotKitErrorCode).includes(originalCode)) {
748
- errorCode = originalCode;
749
- }
750
- const structuredError = new import_shared4.CopilotKitError({
751
- message: errorMessage,
752
- code: errorCode,
753
- severity: originalSeverity,
754
- visibility: originalVisibility
755
- });
756
- setBannerError(structuredError);
757
- yield traceUIError(structuredError, {
758
- statusReason: value.generateCopilotResponse.status.reason,
759
- statusDetails: value.generateCopilotResponse.status.details,
760
- originalErrorCode: originalCode,
761
- preservedStructure: !!originalCode
762
- });
763
- setIsLoading(false);
764
- throw new Error(structuredError.message);
765
- } else if (messages2.length > 0) {
766
- newMessages = [...messages2];
767
- for (const message of messages2) {
768
- if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
769
- if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
770
- break;
771
- }
772
- yield onCoAgentStateRender({
773
- name: message.agentName,
774
- nodeName: message.nodeName,
775
- state: message.state
776
- });
777
- executedCoAgentStateRenders.push(message.id);
778
- }
779
- }
780
- const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
781
- if (lastAgentStateMessage) {
782
- if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
783
- syncedMessages = (0, import_runtime_client_gql3.loadMessagesFromJsonRepresentation)(
784
- lastAgentStateMessage.state.messages
785
- );
786
- }
787
- setCoagentStatesWithRef((prevAgentStates) => {
788
- var _a2;
789
- return __spreadProps(__spreadValues({}, prevAgentStates), {
790
- [lastAgentStateMessage.agentName]: {
791
- name: lastAgentStateMessage.agentName,
792
- state: lastAgentStateMessage.state,
793
- running: lastAgentStateMessage.running,
794
- active: lastAgentStateMessage.active,
795
- threadId: lastAgentStateMessage.threadId,
796
- nodeName: lastAgentStateMessage.nodeName,
797
- runId: lastAgentStateMessage.runId,
798
- // Preserve existing config from previous state
799
- config: (_a2 = prevAgentStates[lastAgentStateMessage.agentName]) == null ? void 0 : _a2.config
800
- }
801
- });
802
- });
803
- if (lastAgentStateMessage.running) {
804
- setAgentSession({
805
- threadId: lastAgentStateMessage.threadId,
806
- agentName: lastAgentStateMessage.agentName,
807
- nodeName: lastAgentStateMessage.nodeName
808
- });
809
- } else {
810
- if (agentLock) {
811
- setAgentSession({
812
- threadId: (0, import_shared4.randomId)(),
813
- agentName: agentLock,
814
- nodeName: void 0
815
- });
816
- } else {
817
- setAgentSession(null);
818
- }
819
- }
820
- }
821
- }
822
- if (newMessages.length > 0) {
823
- setMessages([...previousMessages, ...newMessages]);
824
- }
825
- }
826
- let finalMessages = constructFinalMessages(
827
- [...syncedMessages, ...interruptMessages],
828
- previousMessages,
829
- newMessages
830
- );
831
- let didExecuteAction = false;
832
- const executeActionFromMessage = (currentAction, actionMessage) => __async(this, null, function* () {
833
- var _a2;
834
- const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);
835
- followUp = (_a2 = currentAction == null ? void 0 : currentAction.followUp) != null ? _a2 : !isInterruptAction;
836
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
837
- currentAction._setActivatingMessageId(actionMessage.id);
838
- }
839
- const resultMessage = yield executeAction({
840
- onFunctionCall,
841
- message: actionMessage,
842
- chatAbortControllerRef,
843
- onError: (error) => {
844
- addErrorToast([error]);
845
- console.error(`Failed to execute action ${actionMessage.name}: ${error}`);
846
- },
847
- setMessages,
848
- getFinalMessages: () => finalMessages,
849
- isRenderAndWait: (currentAction == null ? void 0 : currentAction._isRenderAndWait) || false
850
- });
851
- didExecuteAction = true;
852
- const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);
853
- finalMessages.splice(messageIndex + 1, 0, resultMessage);
854
- if (currentAction == null ? void 0 : currentAction._isRenderAndWait) {
855
- const messagesForImmediateUpdate = [...finalMessages];
856
- (0, import_react_dom.flushSync)(() => {
857
- setMessages(messagesForImmediateUpdate);
858
- });
859
- }
860
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
861
- currentAction._setActivatingMessageId(null);
862
- }
863
- return resultMessage;
864
- });
865
- if (onFunctionCall) {
866
- const lastMessages = [];
867
- for (let i = finalMessages.length - 1; i >= 0; i--) {
868
- const message = finalMessages[i];
869
- if ((message.isActionExecutionMessage() || message.isResultMessage()) && message.status.code !== import_runtime_client_gql3.MessageStatusCode.Pending) {
870
- lastMessages.unshift(message);
871
- } else if (!message.isAgentStateMessage()) {
872
- break;
873
- }
874
- }
875
- for (const message of lastMessages) {
876
- setMessages(finalMessages);
877
- const action = actions.find(
878
- (action2) => action2.name === message.name
879
- );
880
- if (action && action.available === "frontend") {
881
- continue;
882
- }
883
- const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
884
- if (action && message.isActionExecutionMessage()) {
885
- const isRenderAndWaitAction = (action == null ? void 0 : action._isRenderAndWait) || false;
886
- const alreadyProcessed = isRenderAndWaitAction && finalMessages.some(
887
- (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
888
- );
889
- if (alreadyProcessed) {
890
- } else {
891
- const resultMessage = yield executeActionFromMessage(
892
- action,
893
- message
894
- );
895
- const pairedFeAction = getPairedFeAction(actions, resultMessage);
896
- if (pairedFeAction) {
897
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
898
- name: pairedFeAction.name,
899
- arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
900
- status: message.status,
901
- createdAt: message.createdAt,
902
- parentMessageId: message.parentMessageId
903
- });
904
- yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
905
- }
906
- }
907
- } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
908
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
909
- name: currentResultMessagePairedFeAction.name,
910
- arguments: (0, import_shared4.parseJson)(message.result, message.result),
911
- status: message.status,
912
- createdAt: message.createdAt
913
- });
914
- finalMessages.push(newExecutionMessage);
915
- yield executeActionFromMessage(
916
- currentResultMessagePairedFeAction,
917
- newExecutionMessage
918
- );
919
- }
920
- }
921
- setMessages(finalMessages);
922
- }
923
- if (followUp !== false && (didExecuteAction || // the last message is a server side result
924
- !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
925
- !((_r = chatAbortControllerRef.current) == null ? void 0 : _r.signal.aborted)) {
926
- yield new Promise((resolve) => setTimeout(resolve, 10));
927
- return yield runChatCompletionRef.current(finalMessages);
928
- } else if ((_s = chatAbortControllerRef.current) == null ? void 0 : _s.signal.aborted) {
929
- const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
930
- if (message.isActionExecutionMessage()) {
931
- return finalMessages.find(
932
- (msg, resultIndex) => msg.isResultMessage() && msg.actionExecutionId === message.id && resultIndex === actionExecutionIndex + 1
933
- );
934
- }
935
- return true;
384
+ event: eventData
936
385
  });
937
- const repairedMessageIds = repairedMessages.map((message) => message.id);
938
- setMessages(repairedMessages);
939
- if ((_t = agentSessionRef.current) == null ? void 0 : _t.nodeName) {
940
- setAgentSession({
941
- threadId: agentSessionRef.current.threadId,
942
- agentName: agentSessionRef.current.agentName,
943
- nodeName: "__end__"
944
- });
945
- }
946
- return newMessages.filter((message) => repairedMessageIds.includes(message.id));
947
- } else {
948
- return newMessages.slice();
949
386
  }
950
- } finally {
951
- setIsLoading(false);
952
- }
953
- }),
954
- [
955
- messages,
956
- setMessages,
957
- makeSystemMessageCallback,
958
- copilotConfig,
959
- setIsLoading,
960
- initialMessages,
961
- isLoading,
962
- actions,
963
- onFunctionCall,
964
- onCoAgentStateRender,
965
- setCoagentStatesWithRef,
966
- coagentStatesRef,
967
- agentSession,
968
- setAgentSession,
969
- disableSystemMessage,
970
- context
971
- ]
972
- );
973
- runChatCompletionRef.current = runChatCompletion;
974
- const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
975
- (messages2) => __async(this, null, function* () {
976
- yield runChatCompletionRef.current(messages2);
977
- }),
978
- [messages]
979
- );
980
- (0, import_react6.useEffect)(() => {
981
- if (!isLoading && pendingAppendsRef.current.length > 0) {
982
- const pending = pendingAppendsRef.current.splice(0);
983
- const followUp = pending.some((p) => p.followUp);
984
- const newMessages = [...messages, ...pending.map((p) => p.message)];
985
- setMessages(newMessages);
986
- if (followUp) {
987
- runChatCompletionAndHandleFunctionCall(newMessages);
988
387
  }
989
- }
990
- }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
991
- const composeAndFlushMetaEventsInput = (0, import_react6.useCallback)(
992
- (metaEvents) => {
993
- return metaEvents.reduce((acc, event) => {
994
- if (!event)
995
- return acc;
996
- switch (event.name) {
997
- case import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent:
998
- if (event.response) {
999
- setLangGraphInterruptAction(threadId, null);
1000
- const value = event.value;
1001
- return [
1002
- ...acc,
1003
- {
1004
- name: event.name,
1005
- value: typeof value === "string" ? value : JSON.stringify(value),
1006
- response: typeof event.response === "string" ? event.response : JSON.stringify(event.response)
1007
- }
1008
- ];
1009
- }
1010
- return acc;
1011
- default:
1012
- return acc;
388
+ };
389
+ const { unsubscribe } = agent.subscribe(subscriber);
390
+ return () => {
391
+ unsubscribe();
392
+ };
393
+ }, [agent, threadId]);
394
+ const handleResolve = (0, import_react5.useCallback)(
395
+ (eventId, response) => {
396
+ agent == null ? void 0 : agent.runAgent({
397
+ forwardedProps: {
398
+ command: {
399
+ resume: response
400
+ }
1013
401
  }
1014
- }, []);
402
+ });
403
+ removeInterruptEvent(threadId, eventId);
1015
404
  },
1016
- [setLangGraphInterruptAction]
405
+ // eslint-disable-next-line react-hooks/exhaustive-deps
406
+ [agent, threadId]
1017
407
  );
1018
- const append = useAsyncCallback(
1019
- (message, options2) => __async(this, null, function* () {
408
+ return (0, import_react5.useMemo)(() => {
409
+ const eventQueue = interruptEventQueue[threadId] || [];
410
+ const currentQueuedEvent = eventQueue.find((qe) => !qe.event.response);
411
+ if (!currentQueuedEvent)
412
+ return null;
413
+ const allActions = Object.values(interruptActions);
414
+ const matchingAction = allActions.find((action) => {
415
+ if (!action.enabled)
416
+ return true;
417
+ return action.enabled({
418
+ eventValue: currentQueuedEvent.event.value,
419
+ agentMetadata: agentSession
420
+ });
421
+ });
422
+ if (!matchingAction)
423
+ return null;
424
+ const { render, handler } = matchingAction;
425
+ const resolveInterrupt = (response) => {
426
+ handleResolve(currentQueuedEvent.eventId, response);
427
+ };
428
+ let result = null;
429
+ if (handler) {
430
+ result = handler({
431
+ event: currentQueuedEvent.event,
432
+ resolve: resolveInterrupt
433
+ });
434
+ }
435
+ if (!render)
436
+ return null;
437
+ return import_react5.default.createElement(InterruptRenderer, {
438
+ event: currentQueuedEvent.event,
439
+ result,
440
+ render,
441
+ resolve: resolveInterrupt
442
+ });
443
+ }, [interruptActions, interruptEventQueue, threadId, agentSession, handleResolve]);
444
+ }
445
+
446
+ // src/hooks/use-copilot-chat_internal.ts
447
+ var import_react13 = require("@copilotkitnext/react");
448
+
449
+ // src/hooks/use-lazy-tool-renderer.tsx
450
+ var import_react6 = require("@copilotkitnext/react");
451
+ var import_react7 = require("react");
452
+ function useLazyToolRenderer() {
453
+ const renderToolCall = (0, import_react6.useRenderToolCall)();
454
+ return (0, import_react7.useCallback)(
455
+ (message, messages) => {
1020
456
  var _a;
1021
- const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
1022
- if (isLoading) {
1023
- pendingAppendsRef.current.push({ message, followUp });
1024
- return;
1025
- }
1026
- const newMessages = [...messages, message];
1027
- setMessages(newMessages);
1028
- if (followUp) {
1029
- return runChatCompletionAndHandleFunctionCall(newMessages);
1030
- }
1031
- }),
1032
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1033
- );
1034
- const reload = useAsyncCallback(
1035
- (reloadMessageId) => __async(this, null, function* () {
1036
- if (isLoading || messages.length === 0) {
1037
- return;
1038
- }
1039
- const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
1040
- if (reloadMessageIndex === -1) {
1041
- console.warn(`Message with id ${reloadMessageId} not found`);
1042
- return;
1043
- }
1044
- const reloadMessageRole = messages[reloadMessageIndex].role;
1045
- if (reloadMessageRole !== import_runtime_client_gql3.MessageRole.Assistant) {
1046
- console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
1047
- return;
1048
- }
1049
- let historyCutoff = [messages[0]];
1050
- if (messages.length > 2 && reloadMessageIndex !== 0) {
1051
- const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
1052
- (msg) => (
1053
- // @ts-expect-error -- message has role
1054
- msg.role === import_runtime_client_gql3.MessageRole.User
1055
- )
1056
- );
1057
- const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1058
- (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1059
- );
1060
- historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1061
- } else if (messages.length > 2 && reloadMessageIndex === 0) {
1062
- historyCutoff = [messages[0], messages[1]];
1063
- }
1064
- setMessages(historyCutoff);
1065
- return runChatCompletionAndHandleFunctionCall(historyCutoff);
1066
- }),
1067
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
457
+ if (!((_a = message == null ? void 0 : message.toolCalls) == null ? void 0 : _a.length))
458
+ return null;
459
+ const toolCall = message.toolCalls[0];
460
+ if (!toolCall)
461
+ return null;
462
+ const toolMessage = messages == null ? void 0 : messages.find(
463
+ (m) => m.role === "tool" && m.toolCallId === toolCall.id
464
+ );
465
+ return () => renderToolCall({
466
+ toolCall,
467
+ toolMessage
468
+ });
469
+ },
470
+ [renderToolCall]
1068
471
  );
1069
- const stop = () => {
1070
- var _a;
1071
- (_a = chatAbortControllerRef.current) == null ? void 0 : _a.abort("Stop was called");
1072
- };
1073
- return {
1074
- append,
1075
- reload,
1076
- stop,
1077
- runChatCompletion: () => runChatCompletionRef.current(messages)
1078
- };
1079
472
  }
1080
- function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
1081
- const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
1082
- if (syncedMessages.length > 0) {
1083
- const messagesWithAgentState = [...previousMessages, ...newMessages];
1084
- let previousMessageId = void 0;
1085
- for (const message of messagesWithAgentState) {
1086
- if (message.isAgentStateMessage()) {
1087
- const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
1088
- if (index !== -1) {
1089
- finalMessages.splice(index + 1, 0, message);
473
+
474
+ // src/hooks/use-configure-chat-suggestions.tsx
475
+ var import_react8 = require("@copilotkitnext/react");
476
+ var import_react9 = require("react");
477
+ function useConfigureChatSuggestions(config, dependencies = []) {
478
+ const { agentSession } = useCopilotContext();
479
+ const { copilotkit } = (0, import_react8.useCopilotKit)();
480
+ const available = config.available === "enabled" ? "always" : config.available;
481
+ const finalSuggestionConfig = __spreadProps(__spreadValues({}, config), {
482
+ available,
483
+ consumerAgentId: agentSession == null ? void 0 : agentSession.agentName
484
+ // Use chatConfig.agentId here
485
+ });
486
+ (0, import_react8.useConfigureSuggestions)(finalSuggestionConfig, { deps: dependencies });
487
+ const result = (0, import_react8.useSuggestions)({ agentId: agentSession == null ? void 0 : agentSession.agentName });
488
+ (0, import_react9.useEffect)(() => {
489
+ if (finalSuggestionConfig.available === "disabled")
490
+ return;
491
+ const subscription = copilotkit.subscribe({
492
+ onAgentsChanged: () => {
493
+ const agent = copilotkit.getAgent(agentSession == null ? void 0 : agentSession.agentName);
494
+ if (agent && !agent.isRunning && !result.suggestions.length) {
495
+ copilotkit.reloadSuggestions(agentSession == null ? void 0 : agentSession.agentName);
1090
496
  }
1091
497
  }
1092
- previousMessageId = message.id;
1093
- }
1094
- }
1095
- return finalMessages;
1096
- }
1097
- function executeAction(_0) {
1098
- return __async(this, arguments, function* ({
1099
- onFunctionCall,
1100
- message,
1101
- chatAbortControllerRef,
1102
- onError,
1103
- setMessages,
1104
- getFinalMessages,
1105
- isRenderAndWait
1106
- }) {
1107
- let result;
1108
- let error = null;
1109
- const currentMessagesForHandler = getFinalMessages();
1110
- const handlerReturnedPromise = onFunctionCall({
1111
- messages: currentMessagesForHandler,
1112
- name: message.name,
1113
- args: message.arguments
1114
- });
1115
- if (isRenderAndWait) {
1116
- const currentMessagesForRender = getFinalMessages();
1117
- (0, import_react_dom.flushSync)(() => {
1118
- setMessages([...currentMessagesForRender]);
1119
- });
1120
- }
1121
- try {
1122
- result = yield Promise.race([
1123
- handlerReturnedPromise,
1124
- // Await the promise returned by the handler
1125
- new Promise(
1126
- (resolve) => {
1127
- var _a;
1128
- return (_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.addEventListener(
1129
- "abort",
1130
- () => resolve("Operation was aborted by the user")
1131
- );
1132
- }
1133
- ),
1134
- // if the user stopped generation, we also abort consecutive actions
1135
- new Promise((resolve) => {
1136
- var _a;
1137
- if ((_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.aborted) {
1138
- resolve("Operation was aborted by the user");
1139
- }
1140
- })
1141
- ]);
1142
- } catch (e) {
1143
- onError(e);
1144
- }
1145
- return new import_runtime_client_gql3.ResultMessage({
1146
- id: "result-" + message.id,
1147
- result: import_runtime_client_gql3.ResultMessage.encodeResult(
1148
- error ? {
1149
- content: result,
1150
- error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
1151
- } : result
1152
- ),
1153
- actionExecutionId: message.id,
1154
- actionName: message.name
1155
498
  });
1156
- });
1157
- }
1158
- function getPairedFeAction(actions, message) {
1159
- let actionName = null;
1160
- if (message.isActionExecutionMessage()) {
1161
- actionName = message.name;
1162
- } else if (message.isResultMessage()) {
1163
- actionName = message.actionName;
1164
- }
1165
- return actions.find(
1166
- (action) => action.name === actionName && action.available === "frontend" || action.pairedAction === actionName
1167
- );
499
+ return () => {
500
+ subscription.unsubscribe();
501
+ };
502
+ }, []);
503
+ return result;
1168
504
  }
1169
505
 
1170
- // src/components/copilot-provider/copilotkit.tsx
1171
- var import_react8 = require("react");
1172
- var import_react_dom2 = require("react-dom");
1173
- var import_shared8 = require("@copilotkit/shared");
506
+ // ../../node_modules/.pnpm/@ag-ui+core@0.0.42-alpha.1/node_modules/@ag-ui/core/dist/index.mjs
507
+ var import_zod = require("zod");
508
+ var import_zod2 = require("zod");
509
+ var FunctionCallSchema = import_zod.z.object({
510
+ name: import_zod.z.string(),
511
+ arguments: import_zod.z.string()
512
+ });
513
+ var ToolCallSchema = import_zod.z.object({
514
+ id: import_zod.z.string(),
515
+ type: import_zod.z.literal("function"),
516
+ function: FunctionCallSchema
517
+ });
518
+ var BaseMessageSchema = import_zod.z.object({
519
+ id: import_zod.z.string(),
520
+ role: import_zod.z.string(),
521
+ content: import_zod.z.string().optional(),
522
+ name: import_zod.z.string().optional()
523
+ });
524
+ var TextInputContentSchema = import_zod.z.object({
525
+ type: import_zod.z.literal("text"),
526
+ text: import_zod.z.string()
527
+ });
528
+ var BinaryInputContentObjectSchema = import_zod.z.object({
529
+ type: import_zod.z.literal("binary"),
530
+ mimeType: import_zod.z.string(),
531
+ id: import_zod.z.string().optional(),
532
+ url: import_zod.z.string().optional(),
533
+ data: import_zod.z.string().optional(),
534
+ filename: import_zod.z.string().optional()
535
+ });
536
+ var ensureBinaryPayload = (value, ctx) => {
537
+ if (!value.id && !value.url && !value.data) {
538
+ ctx.addIssue({
539
+ code: import_zod.z.ZodIssueCode.custom,
540
+ message: "BinaryInputContent requires at least one of id, url, or data.",
541
+ path: ["id"]
542
+ });
543
+ }
544
+ };
545
+ var BinaryInputContentSchema = BinaryInputContentObjectSchema.superRefine((value, ctx) => {
546
+ ensureBinaryPayload(value, ctx);
547
+ });
548
+ var InputContentBaseSchema = import_zod.z.discriminatedUnion("type", [
549
+ TextInputContentSchema,
550
+ BinaryInputContentObjectSchema
551
+ ]);
552
+ var InputContentSchema = InputContentBaseSchema.superRefine((value, ctx) => {
553
+ if (value.type === "binary") {
554
+ ensureBinaryPayload(value, ctx);
555
+ }
556
+ });
557
+ var DeveloperMessageSchema = BaseMessageSchema.extend({
558
+ role: import_zod.z.literal("developer"),
559
+ content: import_zod.z.string()
560
+ });
561
+ var SystemMessageSchema = BaseMessageSchema.extend({
562
+ role: import_zod.z.literal("system"),
563
+ content: import_zod.z.string()
564
+ });
565
+ var AssistantMessageSchema = BaseMessageSchema.extend({
566
+ role: import_zod.z.literal("assistant"),
567
+ content: import_zod.z.string().optional(),
568
+ toolCalls: import_zod.z.array(ToolCallSchema).optional()
569
+ });
570
+ var UserMessageSchema = BaseMessageSchema.extend({
571
+ role: import_zod.z.literal("user"),
572
+ content: import_zod.z.union([import_zod.z.string(), import_zod.z.array(InputContentSchema)])
573
+ });
574
+ var ToolMessageSchema = import_zod.z.object({
575
+ id: import_zod.z.string(),
576
+ content: import_zod.z.string(),
577
+ role: import_zod.z.literal("tool"),
578
+ toolCallId: import_zod.z.string(),
579
+ error: import_zod.z.string().optional()
580
+ });
581
+ var ActivityMessageSchema = import_zod.z.object({
582
+ id: import_zod.z.string(),
583
+ role: import_zod.z.literal("activity"),
584
+ activityType: import_zod.z.string(),
585
+ content: import_zod.z.record(import_zod.z.any())
586
+ });
587
+ var MessageSchema = import_zod.z.discriminatedUnion("role", [
588
+ DeveloperMessageSchema,
589
+ SystemMessageSchema,
590
+ AssistantMessageSchema,
591
+ UserMessageSchema,
592
+ ToolMessageSchema,
593
+ ActivityMessageSchema
594
+ ]);
595
+ var RoleSchema = import_zod.z.union([
596
+ import_zod.z.literal("developer"),
597
+ import_zod.z.literal("system"),
598
+ import_zod.z.literal("assistant"),
599
+ import_zod.z.literal("user"),
600
+ import_zod.z.literal("tool"),
601
+ import_zod.z.literal("activity")
602
+ ]);
603
+ var ContextSchema = import_zod.z.object({
604
+ description: import_zod.z.string(),
605
+ value: import_zod.z.string()
606
+ });
607
+ var ToolSchema = import_zod.z.object({
608
+ name: import_zod.z.string(),
609
+ description: import_zod.z.string(),
610
+ parameters: import_zod.z.any()
611
+ // JSON Schema for the tool parameters
612
+ });
613
+ var RunAgentInputSchema = import_zod.z.object({
614
+ threadId: import_zod.z.string(),
615
+ runId: import_zod.z.string(),
616
+ parentRunId: import_zod.z.string().optional(),
617
+ state: import_zod.z.any(),
618
+ messages: import_zod.z.array(MessageSchema),
619
+ tools: import_zod.z.array(ToolSchema),
620
+ context: import_zod.z.array(ContextSchema),
621
+ forwardedProps: import_zod.z.any()
622
+ });
623
+ var StateSchema = import_zod.z.any();
624
+ var AGUIError = class extends Error {
625
+ constructor(message) {
626
+ super(message);
627
+ }
628
+ };
629
+ var AGUIConnectNotImplementedError = class extends AGUIError {
630
+ constructor() {
631
+ super("Connect not implemented. This method is not supported by the current agent.");
632
+ }
633
+ };
634
+ var TextMessageRoleSchema = import_zod2.z.union([
635
+ import_zod2.z.literal("developer"),
636
+ import_zod2.z.literal("system"),
637
+ import_zod2.z.literal("assistant"),
638
+ import_zod2.z.literal("user")
639
+ ]);
640
+ var EventType = /* @__PURE__ */ ((EventType2) => {
641
+ EventType2["TEXT_MESSAGE_START"] = "TEXT_MESSAGE_START";
642
+ EventType2["TEXT_MESSAGE_CONTENT"] = "TEXT_MESSAGE_CONTENT";
643
+ EventType2["TEXT_MESSAGE_END"] = "TEXT_MESSAGE_END";
644
+ EventType2["TEXT_MESSAGE_CHUNK"] = "TEXT_MESSAGE_CHUNK";
645
+ EventType2["THINKING_TEXT_MESSAGE_START"] = "THINKING_TEXT_MESSAGE_START";
646
+ EventType2["THINKING_TEXT_MESSAGE_CONTENT"] = "THINKING_TEXT_MESSAGE_CONTENT";
647
+ EventType2["THINKING_TEXT_MESSAGE_END"] = "THINKING_TEXT_MESSAGE_END";
648
+ EventType2["TOOL_CALL_START"] = "TOOL_CALL_START";
649
+ EventType2["TOOL_CALL_ARGS"] = "TOOL_CALL_ARGS";
650
+ EventType2["TOOL_CALL_END"] = "TOOL_CALL_END";
651
+ EventType2["TOOL_CALL_CHUNK"] = "TOOL_CALL_CHUNK";
652
+ EventType2["TOOL_CALL_RESULT"] = "TOOL_CALL_RESULT";
653
+ EventType2["THINKING_START"] = "THINKING_START";
654
+ EventType2["THINKING_END"] = "THINKING_END";
655
+ EventType2["STATE_SNAPSHOT"] = "STATE_SNAPSHOT";
656
+ EventType2["STATE_DELTA"] = "STATE_DELTA";
657
+ EventType2["MESSAGES_SNAPSHOT"] = "MESSAGES_SNAPSHOT";
658
+ EventType2["ACTIVITY_SNAPSHOT"] = "ACTIVITY_SNAPSHOT";
659
+ EventType2["ACTIVITY_DELTA"] = "ACTIVITY_DELTA";
660
+ EventType2["RAW"] = "RAW";
661
+ EventType2["CUSTOM"] = "CUSTOM";
662
+ EventType2["RUN_STARTED"] = "RUN_STARTED";
663
+ EventType2["RUN_FINISHED"] = "RUN_FINISHED";
664
+ EventType2["RUN_ERROR"] = "RUN_ERROR";
665
+ EventType2["STEP_STARTED"] = "STEP_STARTED";
666
+ EventType2["STEP_FINISHED"] = "STEP_FINISHED";
667
+ return EventType2;
668
+ })(EventType || {});
669
+ var BaseEventSchema = import_zod2.z.object({
670
+ type: import_zod2.z.nativeEnum(EventType),
671
+ timestamp: import_zod2.z.number().optional(),
672
+ rawEvent: import_zod2.z.any().optional()
673
+ });
674
+ var TextMessageStartEventSchema = BaseEventSchema.extend({
675
+ type: import_zod2.z.literal(
676
+ "TEXT_MESSAGE_START"
677
+ /* TEXT_MESSAGE_START */
678
+ ),
679
+ messageId: import_zod2.z.string(),
680
+ role: TextMessageRoleSchema.default("assistant")
681
+ });
682
+ var TextMessageContentEventSchema = BaseEventSchema.extend({
683
+ type: import_zod2.z.literal(
684
+ "TEXT_MESSAGE_CONTENT"
685
+ /* TEXT_MESSAGE_CONTENT */
686
+ ),
687
+ messageId: import_zod2.z.string(),
688
+ delta: import_zod2.z.string().refine((s) => s.length > 0, "Delta must not be an empty string")
689
+ });
690
+ var TextMessageEndEventSchema = BaseEventSchema.extend({
691
+ type: import_zod2.z.literal(
692
+ "TEXT_MESSAGE_END"
693
+ /* TEXT_MESSAGE_END */
694
+ ),
695
+ messageId: import_zod2.z.string()
696
+ });
697
+ var TextMessageChunkEventSchema = BaseEventSchema.extend({
698
+ type: import_zod2.z.literal(
699
+ "TEXT_MESSAGE_CHUNK"
700
+ /* TEXT_MESSAGE_CHUNK */
701
+ ),
702
+ messageId: import_zod2.z.string().optional(),
703
+ role: TextMessageRoleSchema.optional(),
704
+ delta: import_zod2.z.string().optional()
705
+ });
706
+ var ThinkingTextMessageStartEventSchema = BaseEventSchema.extend({
707
+ type: import_zod2.z.literal(
708
+ "THINKING_TEXT_MESSAGE_START"
709
+ /* THINKING_TEXT_MESSAGE_START */
710
+ )
711
+ });
712
+ var ThinkingTextMessageContentEventSchema = TextMessageContentEventSchema.omit({
713
+ messageId: true,
714
+ type: true
715
+ }).extend({
716
+ type: import_zod2.z.literal(
717
+ "THINKING_TEXT_MESSAGE_CONTENT"
718
+ /* THINKING_TEXT_MESSAGE_CONTENT */
719
+ )
720
+ });
721
+ var ThinkingTextMessageEndEventSchema = BaseEventSchema.extend({
722
+ type: import_zod2.z.literal(
723
+ "THINKING_TEXT_MESSAGE_END"
724
+ /* THINKING_TEXT_MESSAGE_END */
725
+ )
726
+ });
727
+ var ToolCallStartEventSchema = BaseEventSchema.extend({
728
+ type: import_zod2.z.literal(
729
+ "TOOL_CALL_START"
730
+ /* TOOL_CALL_START */
731
+ ),
732
+ toolCallId: import_zod2.z.string(),
733
+ toolCallName: import_zod2.z.string(),
734
+ parentMessageId: import_zod2.z.string().optional()
735
+ });
736
+ var ToolCallArgsEventSchema = BaseEventSchema.extend({
737
+ type: import_zod2.z.literal(
738
+ "TOOL_CALL_ARGS"
739
+ /* TOOL_CALL_ARGS */
740
+ ),
741
+ toolCallId: import_zod2.z.string(),
742
+ delta: import_zod2.z.string()
743
+ });
744
+ var ToolCallEndEventSchema = BaseEventSchema.extend({
745
+ type: import_zod2.z.literal(
746
+ "TOOL_CALL_END"
747
+ /* TOOL_CALL_END */
748
+ ),
749
+ toolCallId: import_zod2.z.string()
750
+ });
751
+ var ToolCallResultEventSchema = BaseEventSchema.extend({
752
+ messageId: import_zod2.z.string(),
753
+ type: import_zod2.z.literal(
754
+ "TOOL_CALL_RESULT"
755
+ /* TOOL_CALL_RESULT */
756
+ ),
757
+ toolCallId: import_zod2.z.string(),
758
+ content: import_zod2.z.string(),
759
+ role: import_zod2.z.literal("tool").optional()
760
+ });
761
+ var ToolCallChunkEventSchema = BaseEventSchema.extend({
762
+ type: import_zod2.z.literal(
763
+ "TOOL_CALL_CHUNK"
764
+ /* TOOL_CALL_CHUNK */
765
+ ),
766
+ toolCallId: import_zod2.z.string().optional(),
767
+ toolCallName: import_zod2.z.string().optional(),
768
+ parentMessageId: import_zod2.z.string().optional(),
769
+ delta: import_zod2.z.string().optional()
770
+ });
771
+ var ThinkingStartEventSchema = BaseEventSchema.extend({
772
+ type: import_zod2.z.literal(
773
+ "THINKING_START"
774
+ /* THINKING_START */
775
+ ),
776
+ title: import_zod2.z.string().optional()
777
+ });
778
+ var ThinkingEndEventSchema = BaseEventSchema.extend({
779
+ type: import_zod2.z.literal(
780
+ "THINKING_END"
781
+ /* THINKING_END */
782
+ )
783
+ });
784
+ var StateSnapshotEventSchema = BaseEventSchema.extend({
785
+ type: import_zod2.z.literal(
786
+ "STATE_SNAPSHOT"
787
+ /* STATE_SNAPSHOT */
788
+ ),
789
+ snapshot: StateSchema
790
+ });
791
+ var StateDeltaEventSchema = BaseEventSchema.extend({
792
+ type: import_zod2.z.literal(
793
+ "STATE_DELTA"
794
+ /* STATE_DELTA */
795
+ ),
796
+ delta: import_zod2.z.array(import_zod2.z.any())
797
+ // JSON Patch (RFC 6902)
798
+ });
799
+ var MessagesSnapshotEventSchema = BaseEventSchema.extend({
800
+ type: import_zod2.z.literal(
801
+ "MESSAGES_SNAPSHOT"
802
+ /* MESSAGES_SNAPSHOT */
803
+ ),
804
+ messages: import_zod2.z.array(MessageSchema)
805
+ });
806
+ var ActivitySnapshotEventSchema = BaseEventSchema.extend({
807
+ type: import_zod2.z.literal(
808
+ "ACTIVITY_SNAPSHOT"
809
+ /* ACTIVITY_SNAPSHOT */
810
+ ),
811
+ messageId: import_zod2.z.string(),
812
+ activityType: import_zod2.z.string(),
813
+ content: import_zod2.z.record(import_zod2.z.any()),
814
+ replace: import_zod2.z.boolean().optional().default(true)
815
+ });
816
+ var ActivityDeltaEventSchema = BaseEventSchema.extend({
817
+ type: import_zod2.z.literal(
818
+ "ACTIVITY_DELTA"
819
+ /* ACTIVITY_DELTA */
820
+ ),
821
+ messageId: import_zod2.z.string(),
822
+ activityType: import_zod2.z.string(),
823
+ patch: import_zod2.z.array(import_zod2.z.any())
824
+ });
825
+ var RawEventSchema = BaseEventSchema.extend({
826
+ type: import_zod2.z.literal(
827
+ "RAW"
828
+ /* RAW */
829
+ ),
830
+ event: import_zod2.z.any(),
831
+ source: import_zod2.z.string().optional()
832
+ });
833
+ var CustomEventSchema = BaseEventSchema.extend({
834
+ type: import_zod2.z.literal(
835
+ "CUSTOM"
836
+ /* CUSTOM */
837
+ ),
838
+ name: import_zod2.z.string(),
839
+ value: import_zod2.z.any()
840
+ });
841
+ var RunStartedEventSchema = BaseEventSchema.extend({
842
+ type: import_zod2.z.literal(
843
+ "RUN_STARTED"
844
+ /* RUN_STARTED */
845
+ ),
846
+ threadId: import_zod2.z.string(),
847
+ runId: import_zod2.z.string(),
848
+ parentRunId: import_zod2.z.string().optional(),
849
+ input: RunAgentInputSchema.optional()
850
+ });
851
+ var RunFinishedEventSchema = BaseEventSchema.extend({
852
+ type: import_zod2.z.literal(
853
+ "RUN_FINISHED"
854
+ /* RUN_FINISHED */
855
+ ),
856
+ threadId: import_zod2.z.string(),
857
+ runId: import_zod2.z.string(),
858
+ result: import_zod2.z.any().optional()
859
+ });
860
+ var RunErrorEventSchema = BaseEventSchema.extend({
861
+ type: import_zod2.z.literal(
862
+ "RUN_ERROR"
863
+ /* RUN_ERROR */
864
+ ),
865
+ message: import_zod2.z.string(),
866
+ code: import_zod2.z.string().optional()
867
+ });
868
+ var StepStartedEventSchema = BaseEventSchema.extend({
869
+ type: import_zod2.z.literal(
870
+ "STEP_STARTED"
871
+ /* STEP_STARTED */
872
+ ),
873
+ stepName: import_zod2.z.string()
874
+ });
875
+ var StepFinishedEventSchema = BaseEventSchema.extend({
876
+ type: import_zod2.z.literal(
877
+ "STEP_FINISHED"
878
+ /* STEP_FINISHED */
879
+ ),
880
+ stepName: import_zod2.z.string()
881
+ });
882
+ var EventSchemas = import_zod2.z.discriminatedUnion("type", [
883
+ TextMessageStartEventSchema,
884
+ TextMessageContentEventSchema,
885
+ TextMessageEndEventSchema,
886
+ TextMessageChunkEventSchema,
887
+ ThinkingStartEventSchema,
888
+ ThinkingEndEventSchema,
889
+ ThinkingTextMessageStartEventSchema,
890
+ ThinkingTextMessageContentEventSchema,
891
+ ThinkingTextMessageEndEventSchema,
892
+ ToolCallStartEventSchema,
893
+ ToolCallArgsEventSchema,
894
+ ToolCallEndEventSchema,
895
+ ToolCallChunkEventSchema,
896
+ ToolCallResultEventSchema,
897
+ StateSnapshotEventSchema,
898
+ StateDeltaEventSchema,
899
+ MessagesSnapshotEventSchema,
900
+ ActivitySnapshotEventSchema,
901
+ ActivityDeltaEventSchema,
902
+ RawEventSchema,
903
+ CustomEventSchema,
904
+ RunStartedEventSchema,
905
+ RunFinishedEventSchema,
906
+ RunErrorEventSchema,
907
+ StepStartedEventSchema,
908
+ StepFinishedEventSchema
909
+ ]);
1174
910
 
1175
- // src/components/copilot-provider/copilot-messages.tsx
1176
- var import_react7 = require("react");
1177
- var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
1178
- var import_shared5 = require("@copilotkit/shared");
1179
- var import_jsx_runtime4 = require("react/jsx-runtime");
1180
- var MessagesTapContext = (0, import_react7.createContext)(null);
1181
- function useMessagesTap() {
1182
- const tap = (0, import_react7.useContext)(MessagesTapContext);
1183
- if (!tap)
1184
- throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");
1185
- return tap;
911
+ // src/hooks/use-coagent-state-render-bridge.tsx
912
+ var import_react10 = require("@copilotkitnext/react");
913
+ var import_react11 = require("react");
914
+ var import_shared3 = require("@copilotkit/shared");
915
+ function getStateWithoutConstantKeys(state) {
916
+ const _a = state, { messages, tools, copilotkit } = _a, stateWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]);
917
+ return stateWithoutConstantKeys;
1186
918
  }
1187
-
1188
- // src/utils/extract.ts
1189
- var import_shared6 = require("@copilotkit/shared");
1190
- var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
1191
- var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
1192
- function extract(_0) {
1193
- return __async(this, arguments, function* ({
1194
- context,
1195
- instructions,
1196
- parameters,
1197
- include,
1198
- data,
1199
- abortSignal,
1200
- stream,
1201
- requestType = import_runtime_client_gql5.CopilotRequestType.Task,
1202
- forwardedParameters
1203
- }) {
1204
- var _a, _b;
1205
- const { messages } = context;
1206
- const action = {
1207
- name: "extract",
1208
- description: instructions,
1209
- parameters,
1210
- handler: (args) => {
919
+ function areStatesEquals(a, b) {
920
+ if (a && !b || !a && b)
921
+ return false;
922
+ const _a = a, { messages, tools, copilotkit } = _a, aWithoutConstantKeys = __objRest(_a, ["messages", "tools", "copilotkit"]);
923
+ const _b = b, {
924
+ messages: bMessages,
925
+ tools: bTools,
926
+ copilotkit: bCopilotkit
927
+ } = _b, bWithoutConstantKeys = __objRest(_b, [
928
+ "messages",
929
+ "tools",
930
+ "copilotkit"
931
+ ]);
932
+ return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
933
+ }
934
+ function useCoagentStateRenderBridge(agentId, props) {
935
+ var _a;
936
+ const { stateSnapshot, messageIndexInRun, message } = props;
937
+ const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
938
+ const { agent } = (0, import_react10.useAgent)({ agentId });
939
+ const [nodeName, setNodeName] = (0, import_react11.useState)(void 0);
940
+ const runId = (_a = props.runId) != null ? _a : message.runId;
941
+ const effectiveRunId = runId || "pending";
942
+ (0, import_react11.useEffect)(() => {
943
+ if (!agent)
944
+ return;
945
+ const subscriber = {
946
+ onStepStartedEvent: ({ event }) => {
947
+ if (event.stepName !== nodeName) {
948
+ setNodeName(event.stepName);
949
+ }
950
+ },
951
+ onStepFinishedEvent: ({ event }) => {
952
+ if (event.stepName === nodeName) {
953
+ setNodeName(void 0);
954
+ }
1211
955
  }
1212
956
  };
1213
- const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
1214
- const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
1215
- let contextString = "";
1216
- if (data) {
1217
- contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
1218
- }
1219
- if (includeReadable) {
1220
- contextString += context.getContextString([], defaultCopilotContextCategories);
957
+ const { unsubscribe } = agent.subscribe(subscriber);
958
+ return () => {
959
+ unsubscribe();
960
+ };
961
+ }, [agentId, nodeName]);
962
+ if (messageIndexInRun !== 0) {
963
+ return null;
964
+ }
965
+ const getStateRender = (0, import_react11.useCallback)(
966
+ (messageId) => {
967
+ return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
968
+ if (claimsRef.current[messageId]) {
969
+ return stateRenderId === claimsRef.current[messageId].stateRenderId;
970
+ }
971
+ const matchingAgentName = stateRender.name === agentId;
972
+ const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
973
+ return matchingAgentName && matchesNodeContext;
974
+ });
975
+ },
976
+ [coAgentStateRenders, nodeName, agentId]
977
+ );
978
+ const handleRenderRequest = ({
979
+ stateRenderId,
980
+ messageId,
981
+ runId: runId2,
982
+ stateSnapshot: renderSnapshot
983
+ }) => {
984
+ if (claimsRef.current[messageId]) {
985
+ const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;
986
+ if (canRender && runId2 && (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === "pending")) {
987
+ claimsRef.current[messageId].runId = runId2;
988
+ }
989
+ return canRender;
1221
990
  }
1222
- const systemMessage = new import_runtime_client_gql5.TextMessage({
1223
- content: makeSystemMessage(contextString, instructions),
1224
- role: import_runtime_client_gql5.Role.System
1225
- });
1226
- const instructionsMessage = new import_runtime_client_gql5.TextMessage({
1227
- content: makeInstructionsMessage(instructions),
1228
- role: import_runtime_client_gql5.Role.User
1229
- });
1230
- const response = context.runtimeClient.asStream(
1231
- context.runtimeClient.generateCopilotResponse({
1232
- data: {
1233
- frontend: {
1234
- actions: [
1235
- {
1236
- name: action.name,
1237
- description: action.description || "",
1238
- jsonSchema: JSON.stringify((0, import_shared6.actionParametersToJsonSchema)(action.parameters || []))
1239
- }
1240
- ],
1241
- url: window.location.href
1242
- },
1243
- messages: (0, import_runtime_client_gql6.convertMessagesToGqlInput)(
1244
- includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql6.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
1245
- ),
1246
- metadata: {
1247
- requestType
1248
- },
1249
- forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
1250
- toolChoice: "function",
1251
- toolChoiceFunctionName: action.name
1252
- })
1253
- },
1254
- properties: context.copilotApiConfig.properties,
1255
- signal: abortSignal
1256
- })
991
+ const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(
992
+ (c) => c.stateRenderId === stateRenderId && (0, import_shared3.dataToUUID)(JSON.stringify(getStateWithoutConstantKeys(c.stateSnapshot))) === (0, import_shared3.dataToUUID)(JSON.stringify(getStateWithoutConstantKeys(renderSnapshot)))
1257
993
  );
1258
- const reader = response.getReader();
1259
- let isInitial = true;
1260
- let actionExecutionMessage = void 0;
1261
- while (true) {
1262
- const { done, value } = yield reader.read();
1263
- if (done) {
1264
- break;
1265
- }
1266
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
1267
- throw new Error("Aborted");
994
+ if (renderClaimedByOtherMessage) {
995
+ if (renderSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)) {
996
+ claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
997
+ return true;
1268
998
  }
1269
- actionExecutionMessage = (0, import_runtime_client_gql5.convertGqlOutputToMessages)(
1270
- value.generateCopilotResponse.messages
1271
- ).find((msg) => msg.isActionExecutionMessage());
1272
- if (!actionExecutionMessage) {
1273
- continue;
999
+ return false;
1000
+ }
1001
+ if (!runId2) {
1002
+ return false;
1003
+ }
1004
+ claimsRef.current[messageId] = { stateRenderId, runId: runId2 };
1005
+ return true;
1006
+ };
1007
+ return (0, import_react11.useMemo)(() => {
1008
+ var _a2, _b, _c;
1009
+ const [stateRenderId, stateRender] = (_a2 = getStateRender(message.id)) != null ? _a2 : [];
1010
+ if (!stateRender || !stateRenderId) {
1011
+ return null;
1012
+ }
1013
+ const snapshot = stateSnapshot ? (0, import_shared3.parseJson)(stateSnapshot, stateSnapshot) : agent == null ? void 0 : agent.state;
1014
+ const canRender = handleRenderRequest({
1015
+ stateRenderId,
1016
+ messageId: message.id,
1017
+ runId: effectiveRunId,
1018
+ stateSnapshot: snapshot
1019
+ });
1020
+ if (!canRender) {
1021
+ return null;
1022
+ }
1023
+ if (snapshot && !claimsRef.current[message.id].locked) {
1024
+ if (stateSnapshot) {
1025
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1026
+ claimsRef.current[message.id].locked = true;
1027
+ } else {
1028
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1274
1029
  }
1275
- stream == null ? void 0 : stream({
1276
- status: isInitial ? "initial" : "inProgress",
1277
- args: actionExecutionMessage.arguments
1030
+ }
1031
+ if (stateRender.handler) {
1032
+ stateRender.handler({
1033
+ state: stateSnapshot ? (0, import_shared3.parseJson)(stateSnapshot, stateSnapshot) : (_b = agent == null ? void 0 : agent.state) != null ? _b : {},
1034
+ nodeName: nodeName != null ? nodeName : ""
1278
1035
  });
1279
- isInitial = false;
1280
1036
  }
1281
- if (!actionExecutionMessage) {
1282
- throw new Error("extract() failed: No function call occurred");
1037
+ if (stateRender.render) {
1038
+ const status = (agent == null ? void 0 : agent.isRunning) ? "inProgress" : "complete";
1039
+ if (typeof stateRender.render === "string")
1040
+ return stateRender.render;
1041
+ return stateRender.render({
1042
+ status,
1043
+ // Always use state from claim, to make sure the state does not seem "wiped" for a fraction of a second
1044
+ state: (_c = claimsRef.current[message.id].stateSnapshot) != null ? _c : {},
1045
+ nodeName: nodeName != null ? nodeName : ""
1046
+ });
1283
1047
  }
1284
- stream == null ? void 0 : stream({
1285
- status: "complete",
1286
- args: actionExecutionMessage.arguments
1287
- });
1288
- return actionExecutionMessage.arguments;
1289
- });
1048
+ }, [
1049
+ getStateRender,
1050
+ stateSnapshot,
1051
+ agent == null ? void 0 : agent.state,
1052
+ agent == null ? void 0 : agent.isRunning,
1053
+ nodeName,
1054
+ effectiveRunId,
1055
+ message.id
1056
+ ]);
1290
1057
  }
1291
- function makeInstructionsMessage(instructions) {
1292
- return `
1293
- The user has given you the following task to complete:
1294
-
1295
- \`\`\`
1296
- ${instructions}
1297
- \`\`\`
1298
-
1299
- Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
1300
- `;
1058
+ function CoAgentStateRenderBridge(props) {
1059
+ return useCoagentStateRenderBridge(props.agentId, props);
1301
1060
  }
1302
- function makeSystemMessage(contextString, instructions) {
1303
- return `
1304
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1305
-
1306
- 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.
1307
- Always be polite and respectful, and prefer brevity over verbosity.
1308
-
1309
- The user has provided you with the following context:
1310
- \`\`\`
1311
- ${contextString}
1312
- \`\`\`
1313
1061
 
1314
- They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
1315
-
1316
- Please assist them as best you can.
1317
-
1318
- This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
1319
- `;
1320
- }
1321
-
1322
- // src/utils/suggestions.ts
1323
- var import_shared7 = require("@copilotkit/shared");
1324
- var import_runtime_client_gql7 = require("@copilotkit/runtime-client-gql");
1325
- var reloadSuggestions = (context, chatSuggestionConfiguration, setCurrentSuggestions, abortControllerRef) => __async(void 0, null, function* () {
1326
- const abortController = abortControllerRef.current;
1327
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1328
- return;
1062
+ // src/hooks/use-copilot-chat_internal.ts
1063
+ function useConfigureSuggestions2(suggestions) {
1064
+ let suggestionsConfig;
1065
+ if (Array.isArray(suggestions)) {
1066
+ suggestionsConfig = {
1067
+ suggestions,
1068
+ available: "always"
1069
+ };
1070
+ } else if (suggestions === "auto") {
1071
+ suggestionsConfig = {
1072
+ available: suggestions === "auto" ? "always" : "disabled",
1073
+ instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls."
1074
+ };
1075
+ } else {
1076
+ suggestionsConfig = { available: "disabled" };
1329
1077
  }
1330
- const setSuggestionsIfNotAborted = (suggestions) => {
1331
- if (!(abortController == null ? void 0 : abortController.signal.aborted) && abortControllerRef.current === abortController) {
1332
- setCurrentSuggestions(suggestions);
1333
- }
1334
- };
1335
- try {
1336
- const tools = JSON.stringify(
1337
- Object.values(context.actions).map((action) => ({
1338
- name: action.name,
1339
- description: action.description,
1340
- jsonSchema: JSON.stringify((0, import_shared7.actionParametersToJsonSchema)(action.parameters))
1341
- }))
1342
- );
1343
- const allSuggestions = [];
1344
- let hasSuccessfulSuggestions = false;
1345
- let hasErrors = false;
1346
- let lastError = null;
1347
- const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(
1348
- (config) => config.instructions && config.instructions.trim().length > 0
1349
- );
1350
- if (enabledConfigs.length === 0) {
1351
- return;
1352
- }
1353
- setSuggestionsIfNotAborted([]);
1354
- for (const config of enabledConfigs) {
1355
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1356
- setSuggestionsIfNotAborted([]);
1357
- return;
1358
- }
1078
+ useConfigureChatSuggestions(suggestionsConfig);
1079
+ }
1080
+ function useCopilotChatInternal({
1081
+ suggestions
1082
+ } = {}) {
1083
+ var _a, _b, _c, _d;
1084
+ const { copilotkit } = (0, import_react13.useCopilotKit)();
1085
+ const { threadId, agentSession } = useCopilotContext();
1086
+ const existingConfig = (0, import_react13.useCopilotChatConfiguration)();
1087
+ const [agentAvailable, setAgentAvailable] = (0, import_react12.useState)(false);
1088
+ useConfigureSuggestions2(suggestions);
1089
+ const resolvedAgentId = (_b = (_a = agentSession == null ? void 0 : agentSession.agentName) != null ? _a : existingConfig == null ? void 0 : existingConfig.agentId) != null ? _b : "default";
1090
+ const { agent } = (0, import_react13.useAgent)({ agentId: resolvedAgentId });
1091
+ (0, import_react12.useEffect)(() => {
1092
+ const connect = (agent2) => __async(this, null, function* () {
1093
+ setAgentAvailable(false);
1359
1094
  try {
1360
- const result = yield extract({
1361
- context,
1362
- instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. ",
1363
- data: `${config.instructions}
1364
-
1365
- Available tools: ${tools}
1366
-
1367
- `,
1368
- requestType: import_runtime_client_gql7.CopilotRequestType.Task,
1369
- parameters: [
1370
- {
1371
- name: "suggestions",
1372
- type: "object[]",
1373
- attributes: [
1374
- {
1375
- name: "title",
1376
- description: "The title of the suggestion. This is shown as a button and should be short.",
1377
- type: "string"
1378
- },
1379
- {
1380
- name: "message",
1381
- 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.",
1382
- type: "string"
1383
- }
1384
- ]
1385
- }
1386
- ],
1387
- include: {
1388
- messages: true,
1389
- readable: true
1390
- },
1391
- abortSignal: abortController == null ? void 0 : abortController.signal,
1392
- stream: ({ status, args }) => {
1393
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1394
- return;
1395
- }
1396
- const suggestions = args.suggestions || [];
1397
- const newSuggestions = [];
1398
- for (let i = 0; i < suggestions.length; i++) {
1399
- if (config.maxSuggestions !== void 0 && i >= config.maxSuggestions) {
1400
- break;
1401
- }
1402
- const suggestion = suggestions[i];
1403
- if (!suggestion || typeof suggestion !== "object") {
1404
- continue;
1405
- }
1406
- const { title, message } = suggestion;
1407
- const hasValidTitle = title && typeof title === "string" && title.trim().length > 0;
1408
- const hasValidMessage = message && typeof message === "string" && message.trim().length > 0;
1409
- if (!hasValidTitle) {
1410
- continue;
1411
- }
1412
- const partial = i === suggestions.length - 1 && status !== "complete";
1413
- newSuggestions.push({
1414
- title: title.trim(),
1415
- message: hasValidMessage ? message.trim() : "",
1416
- // Use title as fallback
1417
- partial,
1418
- className: config.className
1419
- });
1420
- }
1421
- setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);
1422
- }
1423
- });
1424
- if ((result == null ? void 0 : result.suggestions) && Array.isArray(result.suggestions)) {
1425
- const validSuggestions = result.suggestions.filter(
1426
- (suggestion) => suggestion && typeof suggestion.title === "string" && suggestion.title.trim().length > 0
1427
- ).map((suggestion) => ({
1428
- title: suggestion.title.trim(),
1429
- message: suggestion.message && typeof suggestion.message === "string" && suggestion.message.trim() ? suggestion.message.trim() : suggestion.title.trim()
1430
- }));
1431
- if (validSuggestions.length > 0) {
1432
- allSuggestions.push(...validSuggestions);
1433
- hasSuccessfulSuggestions = true;
1434
- }
1435
- }
1095
+ yield copilotkit.connectAgent({ agent: agent2 });
1096
+ setAgentAvailable(true);
1436
1097
  } catch (error) {
1437
- hasErrors = true;
1438
- lastError = error instanceof Error ? error : new Error(String(error));
1098
+ if (error instanceof AGUIConnectNotImplementedError) {
1099
+ } else {
1100
+ throw error;
1101
+ }
1439
1102
  }
1103
+ });
1104
+ if (agent && (existingConfig == null ? void 0 : existingConfig.threadId) && agent.threadId !== existingConfig.threadId) {
1105
+ agent.threadId = existingConfig.threadId;
1106
+ connect(agent);
1440
1107
  }
1441
- if (hasSuccessfulSuggestions && allSuggestions.length > 0) {
1442
- const uniqueSuggestions = allSuggestions.filter(
1443
- (suggestion, index, self) => index === self.findIndex((s) => s.message === suggestion.message)
1108
+ return () => {
1109
+ };
1110
+ }, [existingConfig == null ? void 0 : existingConfig.threadId, agent, copilotkit, resolvedAgentId]);
1111
+ const interrupt = useLangGraphInterruptRender(agent);
1112
+ const reset = () => {
1113
+ agent == null ? void 0 : agent.setMessages([]);
1114
+ agent == null ? void 0 : agent.setState(null);
1115
+ };
1116
+ const deleteMessage = (0, import_react12.useCallback)(
1117
+ (messageId) => {
1118
+ var _a2;
1119
+ const filteredMessages = ((_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : []).filter(
1120
+ (message) => message.id !== messageId
1444
1121
  );
1445
- setSuggestionsIfNotAborted(uniqueSuggestions);
1446
- } else if (hasErrors) {
1447
- const errorMessage = lastError ? lastError.message : "Failed to generate suggestions due to API errors";
1448
- throw new Error(errorMessage);
1449
- }
1450
- } catch (error) {
1451
- throw error;
1452
- }
1453
- });
1454
-
1455
- // src/components/copilot-provider/copilotkit.tsx
1456
- var import_jsx_runtime5 = require("react/jsx-runtime");
1457
- var defaultCopilotContextCategories = ["global"];
1458
-
1459
- // src/hooks/use-copilot-chat_internal.ts
1460
- var import_runtime_client_gql8 = require("@copilotkit/runtime-client-gql");
1461
-
1462
- // src/hooks/use-langgraph-interrupt-render.ts
1463
- var import_react9 = __toESM(require("react"));
1464
- var InterruptRenderer = ({ event, result, render, resolve }) => {
1465
- return render({ event, result, resolve });
1466
- };
1467
- function useLangGraphInterruptRender() {
1468
- const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession, threadId } = useCopilotContext();
1469
- const responseRef = import_react9.default.useRef();
1470
- const resolveInterrupt = (0, import_react9.useCallback)(
1471
- (response) => {
1472
- responseRef.current = response;
1473
- setTimeout(() => {
1474
- setLangGraphInterruptAction(threadId, { event: { response } });
1475
- }, 0);
1122
+ agent == null ? void 0 : agent.setMessages(filteredMessages);
1476
1123
  },
1477
- [setLangGraphInterruptAction, threadId]
1124
+ [agent == null ? void 0 : agent.setMessages, agent == null ? void 0 : agent.messages]
1478
1125
  );
1479
- if (!langGraphInterruptAction || !langGraphInterruptAction.event || !langGraphInterruptAction.render)
1480
- return null;
1481
- const { render, handler, event, enabled } = langGraphInterruptAction;
1482
- const conditionsMet = !agentSession || !enabled ? true : enabled({ eventValue: event.value, agentMetadata: agentSession });
1483
- if (!conditionsMet) {
1484
- return null;
1485
- }
1486
- let result = null;
1487
- if (handler) {
1488
- result = handler({
1489
- event,
1490
- resolve: resolveInterrupt
1491
- });
1492
- }
1493
- return import_react9.default.createElement(InterruptRenderer, {
1494
- event,
1495
- result,
1496
- render,
1497
- resolve: resolveInterrupt
1498
- });
1499
- }
1500
-
1501
- // src/hooks/use-copilot-chat_internal.ts
1502
- var globalSuggestionPromise = null;
1503
- function useCopilotChat(options = {}) {
1504
- var _a;
1505
- const makeSystemMessage2 = (_a = options.makeSystemMessage) != null ? _a : defaultSystemMessage;
1506
- const {
1507
- getContextString,
1508
- getFunctionCallHandler,
1509
- copilotApiConfig,
1510
- isLoading,
1511
- setIsLoading,
1512
- chatInstructions,
1513
- actions,
1514
- coagentStatesRef,
1515
- setCoagentStatesWithRef,
1516
- coAgentStateRenders,
1517
- agentSession,
1518
- setAgentSession,
1519
- forwardedParameters,
1520
- agentLock,
1521
- threadId,
1522
- setThreadId,
1523
- runId,
1524
- setRunId,
1525
- chatAbortControllerRef,
1526
- extensions,
1527
- setExtensions,
1528
- langGraphInterruptAction,
1529
- setLangGraphInterruptAction,
1530
- chatSuggestionConfiguration,
1531
- runtimeClient
1532
- } = useCopilotContext();
1533
- const { messages, setMessages, suggestions, setSuggestions } = useCopilotMessagesContext();
1534
- const [mcpServers, setLocalMcpServers] = (0, import_react10.useState)([]);
1535
- const suggestionsAbortControllerRef = (0, import_react10.useRef)(null);
1536
- const isLoadingSuggestionsRef = (0, import_react10.useRef)(false);
1537
- const abortSuggestions = (0, import_react10.useCallback)(
1538
- (clear = true) => {
1539
- var _a2;
1540
- (_a2 = suggestionsAbortControllerRef.current) == null ? void 0 : _a2.abort("suggestions aborted by user");
1541
- suggestionsAbortControllerRef.current = null;
1542
- if (clear) {
1543
- setSuggestions([]);
1544
- }
1126
+ const latestDelete = useUpdatedRef(deleteMessage);
1127
+ const latestDeleteFunc = (0, import_react12.useCallback)(
1128
+ (messageId) => {
1129
+ return latestDelete.current(messageId);
1545
1130
  },
1546
- [setSuggestions]
1131
+ [latestDelete]
1547
1132
  );
1548
- const stableContext = (0, import_react10.useMemo)(() => {
1549
- return {
1550
- actions,
1551
- copilotApiConfig,
1552
- chatSuggestionConfiguration,
1553
- messages,
1554
- setMessages,
1555
- getContextString,
1556
- runtimeClient
1557
- };
1558
- }, [
1559
- JSON.stringify(Object.keys(actions)),
1560
- copilotApiConfig.chatApiEndpoint,
1561
- messages.length,
1562
- Object.keys(chatSuggestionConfiguration).length
1563
- ]);
1564
- const generateSuggestionsFunc = (0, import_react10.useCallback)(() => __async(this, null, function* () {
1565
- if (globalSuggestionPromise) {
1566
- return globalSuggestionPromise;
1567
- }
1568
- globalSuggestionPromise = (() => __async(this, null, function* () {
1569
- try {
1570
- abortSuggestions();
1571
- isLoadingSuggestionsRef.current = true;
1572
- suggestionsAbortControllerRef.current = new AbortController();
1573
- setSuggestions([]);
1574
- yield reloadSuggestions(
1575
- stableContext,
1576
- chatSuggestionConfiguration,
1577
- setSuggestions,
1578
- suggestionsAbortControllerRef
1579
- );
1580
- } catch (error) {
1581
- throw error;
1582
- } finally {
1583
- isLoadingSuggestionsRef.current = false;
1584
- globalSuggestionPromise = null;
1133
+ const currentSuggestions = (0, import_react13.useSuggestions)({ agentId: resolvedAgentId });
1134
+ const reload = useAsyncCallback(
1135
+ (reloadMessageId) => __async(this, null, function* () {
1136
+ var _a2;
1137
+ const messages = (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : [];
1138
+ const isLoading = false;
1139
+ if (isLoading || messages.length === 0) {
1140
+ return;
1585
1141
  }
1586
- }))();
1587
- return globalSuggestionPromise;
1588
- }), [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);
1589
- const resetSuggestions = (0, import_react10.useCallback)(() => {
1590
- setSuggestions([]);
1591
- }, [setSuggestions]);
1592
- (0, import_react10.useEffect)(() => {
1593
- if (mcpServers.length > 0) {
1594
- const serversCopy = [...mcpServers];
1595
- copilotApiConfig.mcpServers = serversCopy;
1596
- if (!copilotApiConfig.properties) {
1597
- copilotApiConfig.properties = {};
1142
+ const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
1143
+ if (reloadMessageIndex === -1) {
1144
+ console.warn(`Message with id ${reloadMessageId} not found`);
1145
+ return;
1598
1146
  }
1599
- copilotApiConfig.properties.mcpServers = serversCopy;
1600
- }
1601
- }, [mcpServers, copilotApiConfig]);
1602
- const setMcpServers = (0, import_react10.useCallback)((servers) => {
1603
- setLocalMcpServers(servers);
1604
- }, []);
1605
- const onCoAgentStateRender = useAsyncCallback(
1606
- (args) => __async(this, null, function* () {
1607
- var _a2;
1608
- const { name, nodeName, state } = args;
1609
- let action = Object.values(coAgentStateRenders).find(
1610
- (action2) => action2.name === name && action2.nodeName === nodeName
1611
- );
1612
- if (!action) {
1613
- action = Object.values(coAgentStateRenders).find(
1614
- (action2) => action2.name === name && !action2.nodeName
1615
- );
1147
+ const reloadMessageRole = messages[reloadMessageIndex].role;
1148
+ if (reloadMessageRole !== "assistant") {
1149
+ console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
1150
+ return;
1616
1151
  }
1617
- if (action) {
1618
- yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
1152
+ let historyCutoff = [messages[0]];
1153
+ if (messages.length > 2 && reloadMessageIndex !== 0) {
1154
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find((msg) => msg.role === "user");
1155
+ if (!lastUserMessageBeforeRegenerate) {
1156
+ historyCutoff = [messages[0]];
1157
+ } else {
1158
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1159
+ (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1160
+ );
1161
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1162
+ }
1163
+ } else if (messages.length > 2 && reloadMessageIndex === 0) {
1164
+ historyCutoff = [messages[0], messages[1]];
1619
1165
  }
1166
+ agent == null ? void 0 : agent.setMessages(historyCutoff);
1167
+ if (agent) {
1168
+ copilotkit.runAgent({ agent });
1169
+ }
1170
+ return;
1620
1171
  }),
1621
- [coAgentStateRenders]
1172
+ [agent == null ? void 0 : agent.setMessages, copilotkit == null ? void 0 : copilotkit.runAgent]
1622
1173
  );
1623
- const makeSystemMessageCallback = (0, import_react10.useCallback)(() => {
1624
- const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
1625
- const contextString = getContextString([], defaultCopilotContextCategories);
1626
- return new import_runtime_client_gql8.TextMessage({
1627
- content: systemMessageMaker(contextString, chatInstructions),
1628
- role: import_runtime_client_gql8.Role.System
1629
- });
1630
- }, [getContextString, makeSystemMessage2, chatInstructions]);
1631
- const deleteMessage = (0, import_react10.useCallback)(
1632
- (messageId) => {
1633
- setMessages((prev) => prev.filter((message) => message.id !== messageId));
1634
- },
1635
- [setMessages]
1174
+ const latestSendMessageFunc = useAsyncCallback(
1175
+ (message, options) => __async(this, null, function* () {
1176
+ var _a2;
1177
+ if (!agent)
1178
+ return;
1179
+ const followUp = (_a2 = options == null ? void 0 : options.followUp) != null ? _a2 : true;
1180
+ if (options == null ? void 0 : options.clearSuggestions) {
1181
+ copilotkit.clearSuggestions(resolvedAgentId);
1182
+ }
1183
+ agent == null ? void 0 : agent.addMessage(message);
1184
+ if (followUp) {
1185
+ try {
1186
+ yield copilotkit.runAgent({ agent });
1187
+ } catch (error) {
1188
+ console.error("CopilotChat: runAgent failed", error);
1189
+ }
1190
+ }
1191
+ }),
1192
+ [agent, copilotkit, resolvedAgentId]
1636
1193
  );
1637
- const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
1638
- actions: Object.values(actions),
1639
- copilotConfig: copilotApiConfig,
1640
- initialMessages: (0, import_runtime_client_gql8.aguiToGQL)(options.initialMessages || []),
1641
- onFunctionCall: getFunctionCallHandler(),
1642
- onCoAgentStateRender,
1643
- messages,
1644
- setMessages,
1645
- makeSystemMessageCallback,
1646
- isLoading,
1647
- setIsLoading,
1648
- coagentStatesRef,
1649
- setCoagentStatesWithRef,
1650
- agentSession,
1651
- setAgentSession,
1652
- forwardedParameters,
1653
- threadId,
1654
- setThreadId,
1655
- runId,
1656
- setRunId,
1657
- chatAbortControllerRef,
1658
- agentLock,
1659
- extensions,
1660
- setExtensions,
1661
- langGraphInterruptAction,
1662
- setLangGraphInterruptAction,
1663
- disableSystemMessage: options.disableSystemMessage
1664
- }));
1665
- const latestAppend = useUpdatedRef(append);
1666
1194
  const latestAppendFunc = useAsyncCallback(
1667
- (message, options2) => __async(this, null, function* () {
1668
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
1669
- return yield latestAppend.current(message, options2);
1195
+ (message, options) => __async(this, null, function* () {
1196
+ return latestSendMessageFunc((0, import_runtime_client_gql2.gqlToAGUI)([message])[0], options);
1670
1197
  }),
1671
- [latestAppend]
1198
+ [latestSendMessageFunc]
1672
1199
  );
1673
- const latestSendMessageFunc = useAsyncCallback(
1674
- (message, options2) => __async(this, null, function* () {
1675
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
1676
- return yield latestAppend.current((0, import_runtime_client_gql8.aguiToGQL)([message])[0], options2);
1677
- }),
1678
- [latestAppend]
1200
+ const latestSetMessages = useUpdatedRef(agent == null ? void 0 : agent.setMessages);
1201
+ const latestSetMessagesFunc = (0, import_react12.useCallback)(
1202
+ (messages) => {
1203
+ var _a2, _b2;
1204
+ if (messages.every((message) => message instanceof import_runtime_client_gql2.Message)) {
1205
+ return (_a2 = latestSetMessages.current) == null ? void 0 : _a2.call(latestSetMessages, (0, import_runtime_client_gql2.gqlToAGUI)(messages));
1206
+ }
1207
+ return (_b2 = latestSetMessages.current) == null ? void 0 : _b2.call(latestSetMessages, messages);
1208
+ },
1209
+ [latestSetMessages, agent]
1679
1210
  );
1680
1211
  const latestReload = useUpdatedRef(reload);
1681
1212
  const latestReloadFunc = useAsyncCallback(
@@ -1684,61 +1215,81 @@ function useCopilotChat(options = {}) {
1684
1215
  }),
1685
1216
  [latestReload]
1686
1217
  );
1687
- const latestStop = useUpdatedRef(stop);
1688
- const latestStopFunc = (0, import_react10.useCallback)(() => {
1689
- return latestStop.current();
1218
+ const latestStop = useUpdatedRef(agent == null ? void 0 : agent.abortRun);
1219
+ const latestStopFunc = (0, import_react12.useCallback)(() => {
1220
+ var _a2;
1221
+ return (_a2 = latestStop.current) == null ? void 0 : _a2.call(latestStop);
1690
1222
  }, [latestStop]);
1691
- const latestDelete = useUpdatedRef(deleteMessage);
1692
- const latestDeleteFunc = (0, import_react10.useCallback)(
1693
- (messageId) => {
1694
- return latestDelete.current(messageId);
1695
- },
1696
- [latestDelete]
1697
- );
1698
- const latestSetMessages = useUpdatedRef(setMessages);
1699
- const latestSetMessagesFunc = (0, import_react10.useCallback)(
1700
- (messages2) => {
1701
- if (messages2.every((message) => message instanceof import_runtime_client_gql8.Message)) {
1702
- return latestSetMessages.current(messages2);
1223
+ const latestReset = useUpdatedRef(reset);
1224
+ const latestResetFunc = (0, import_react12.useCallback)(() => {
1225
+ return latestReset.current();
1226
+ }, [latestReset]);
1227
+ const lazyToolRendered = useLazyToolRenderer();
1228
+ const renderCustomMessage = (0, import_react13.useRenderCustomMessages)();
1229
+ const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
1230
+ copilotkit,
1231
+ agent,
1232
+ agentId: resolvedAgentId,
1233
+ threadId: (_c = existingConfig == null ? void 0 : existingConfig.threadId) != null ? _c : threadId
1234
+ });
1235
+ const allMessages = (_d = agent == null ? void 0 : agent.messages) != null ? _d : [];
1236
+ const resolvedMessages = (0, import_react12.useMemo)(() => {
1237
+ let processedMessages = allMessages.map((message) => {
1238
+ if (message.role !== "assistant") {
1239
+ return message;
1703
1240
  }
1704
- return latestSetMessages.current((0, import_runtime_client_gql8.aguiToGQL)(messages2));
1705
- },
1706
- [latestSetMessages]
1707
- );
1708
- const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
1709
- const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
1710
- return yield latestRunChatCompletion.current();
1711
- }), [latestRunChatCompletion]);
1712
- const reset = (0, import_react10.useCallback)(() => {
1713
- latestStopFunc();
1714
- setMessages([]);
1715
- setRunId(null);
1716
- setCoagentStatesWithRef({});
1717
- let initialAgentSession = null;
1718
- if (agentLock) {
1719
- initialAgentSession = {
1720
- agentName: agentLock
1241
+ const lazyRendered = lazyToolRendered(message, allMessages);
1242
+ if (lazyRendered) {
1243
+ const renderedGenUi = lazyRendered();
1244
+ if (renderedGenUi) {
1245
+ return __spreadProps(__spreadValues({}, message), { generativeUI: () => renderedGenUi });
1246
+ }
1247
+ }
1248
+ const bridgeRenderer = legacyCustomMessageRenderer || renderCustomMessage ? () => {
1249
+ const customRender = renderCustomMessage == null ? void 0 : renderCustomMessage({
1250
+ message,
1251
+ position: "before"
1252
+ });
1253
+ if (customRender) {
1254
+ return customRender;
1255
+ }
1256
+ return legacyCustomMessageRenderer == null ? void 0 : legacyCustomMessageRenderer({ message, position: "before" });
1257
+ } : null;
1258
+ if (bridgeRenderer) {
1259
+ return __spreadProps(__spreadValues({}, message), { generativeUI: bridgeRenderer });
1260
+ }
1261
+ return message;
1262
+ });
1263
+ const hasAssistantMessages = processedMessages.some((msg) => msg.role === "assistant");
1264
+ if (legacyCustomMessageRenderer && !hasAssistantMessages) {
1265
+ const placeholderId = `coagent-state-render-${resolvedAgentId}`;
1266
+ const placeholderMessage = {
1267
+ id: placeholderId,
1268
+ role: "assistant",
1269
+ content: "",
1270
+ name: "coagent-state-render"
1721
1271
  };
1272
+ processedMessages = [
1273
+ ...processedMessages,
1274
+ __spreadProps(__spreadValues({}, placeholderMessage), {
1275
+ generativeUI: () => legacyCustomMessageRenderer({
1276
+ message: placeholderMessage,
1277
+ position: "before"
1278
+ })
1279
+ })
1280
+ ];
1722
1281
  }
1723
- setAgentSession(initialAgentSession);
1724
- resetSuggestions();
1282
+ return processedMessages;
1725
1283
  }, [
1726
- latestStopFunc,
1727
- setMessages,
1728
- setThreadId,
1729
- setCoagentStatesWithRef,
1730
- setAgentSession,
1731
- agentLock,
1732
- resetSuggestions
1284
+ agent == null ? void 0 : agent.messages,
1285
+ lazyToolRendered,
1286
+ allMessages,
1287
+ renderCustomMessage,
1288
+ legacyCustomMessageRenderer,
1289
+ resolvedAgentId
1733
1290
  ]);
1734
- const latestReset = useUpdatedRef(reset);
1735
- const latestResetFunc = (0, import_react10.useCallback)(() => {
1736
- return latestReset.current();
1737
- }, [latestReset]);
1738
- const interrupt = useLangGraphInterruptRender();
1739
1291
  return {
1740
- visibleMessages: messages,
1741
- messages: (0, import_runtime_client_gql8.gqlToAGUI)(messages, actions, coAgentStateRenders),
1292
+ messages: resolvedMessages,
1742
1293
  sendMessage: latestSendMessageFunc,
1743
1294
  appendMessage: latestAppendFunc,
1744
1295
  setMessages: latestSetMessagesFunc,
@@ -1746,54 +1297,66 @@ function useCopilotChat(options = {}) {
1746
1297
  stopGeneration: latestStopFunc,
1747
1298
  reset: latestResetFunc,
1748
1299
  deleteMessage: latestDeleteFunc,
1749
- runChatCompletion: latestRunChatCompletionFunc,
1750
- isLoading,
1751
- mcpServers,
1752
- setMcpServers,
1753
- suggestions,
1754
- setSuggestions,
1755
- generateSuggestions: generateSuggestionsFunc,
1756
- resetSuggestions,
1757
- isLoadingSuggestions: isLoadingSuggestionsRef.current,
1758
- interrupt
1300
+ isAvailable: !agentAvailable,
1301
+ isLoading: Boolean(agent == null ? void 0 : agent.isRunning),
1302
+ // mcpServers,
1303
+ // setMcpServers,
1304
+ suggestions: currentSuggestions.suggestions,
1305
+ setSuggestions: (suggestions2) => copilotkit.addSuggestionsConfig({ suggestions: suggestions2 }),
1306
+ generateSuggestions: () => __async(this, null, function* () {
1307
+ return copilotkit.reloadSuggestions(resolvedAgentId);
1308
+ }),
1309
+ resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),
1310
+ isLoadingSuggestions: currentSuggestions.isLoading,
1311
+ interrupt,
1312
+ agent,
1313
+ threadId
1759
1314
  };
1760
1315
  }
1761
1316
  function useUpdatedRef(value) {
1762
- const ref = (0, import_react10.useRef)(value);
1763
- (0, import_react10.useEffect)(() => {
1317
+ const ref = (0, import_react12.useRef)(value);
1318
+ (0, import_react12.useEffect)(() => {
1764
1319
  ref.current = value;
1765
1320
  }, [value]);
1766
1321
  return ref;
1767
1322
  }
1768
- function defaultSystemMessage(contextString, additionalInstructions) {
1769
- return `
1770
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1771
-
1772
- 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.
1773
- Always be polite and respectful, and prefer brevity over verbosity.
1774
-
1775
- The user has provided you with the following context:
1776
- \`\`\`
1777
- ${contextString}
1778
- \`\`\`
1779
-
1780
- 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.
1781
-
1782
- Please assist them as best you can.
1783
-
1784
- 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.
1785
-
1786
- If you would like to call a function, call it without saying anything else.
1787
- In case of a function error:
1788
- - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
1789
- - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
1790
- ` + (additionalInstructions ? `
1791
-
1792
- ${additionalInstructions}` : "");
1323
+ function useLegacyCoagentRenderer({
1324
+ copilotkit,
1325
+ agent,
1326
+ agentId,
1327
+ threadId
1328
+ }) {
1329
+ return (0, import_react12.useMemo)(() => {
1330
+ if (!copilotkit || !agent) {
1331
+ return null;
1332
+ }
1333
+ return ({ message, position }) => {
1334
+ var _a;
1335
+ const effectiveThreadId = (_a = threadId != null ? threadId : agent.threadId) != null ? _a : "default";
1336
+ const existingRunId = copilotkit.getRunIdForMessage(
1337
+ agentId,
1338
+ effectiveThreadId,
1339
+ message.id
1340
+ );
1341
+ const runId = existingRunId || `pending:${message.id}`;
1342
+ const messageIndex = Math.max(agent.messages.findIndex((msg) => msg.id === message.id), 0);
1343
+ const bridgeProps = {
1344
+ message,
1345
+ position,
1346
+ runId,
1347
+ messageIndex,
1348
+ messageIndexInRun: 0,
1349
+ numberOfMessagesInRun: 1,
1350
+ agentId,
1351
+ stateSnapshot: message.state
1352
+ };
1353
+ return (0, import_react12.createElement)(CoAgentStateRenderBridge, bridgeProps);
1354
+ };
1355
+ }, [agent, agentId, copilotkit, threadId]);
1793
1356
  }
1794
1357
 
1795
1358
  // src/hooks/use-copilot-chat.ts
1796
- function useCopilotChat2(options = {}) {
1359
+ function useCopilotChat(options = {}) {
1797
1360
  const {
1798
1361
  visibleMessages,
1799
1362
  appendMessage,
@@ -1801,10 +1364,11 @@ function useCopilotChat2(options = {}) {
1801
1364
  stopGeneration,
1802
1365
  reset,
1803
1366
  isLoading,
1367
+ isAvailable,
1804
1368
  runChatCompletion,
1805
1369
  mcpServers,
1806
1370
  setMcpServers
1807
- } = useCopilotChat(options);
1371
+ } = useCopilotChatInternal(options);
1808
1372
  return {
1809
1373
  visibleMessages,
1810
1374
  appendMessage,
@@ -1812,6 +1376,7 @@ function useCopilotChat2(options = {}) {
1812
1376
  stopGeneration,
1813
1377
  reset,
1814
1378
  isLoading,
1379
+ isAvailable,
1815
1380
  runChatCompletion,
1816
1381
  mcpServers,
1817
1382
  setMcpServers
@@ -1819,8 +1384,8 @@ function useCopilotChat2(options = {}) {
1819
1384
  }
1820
1385
 
1821
1386
  // src/hooks/use-copilot-chat-headless_c.ts
1822
- var import_react11 = require("react");
1823
- var import_shared9 = require("@copilotkit/shared");
1387
+ var import_react14 = require("react");
1388
+ var import_shared4 = require("@copilotkit/shared");
1824
1389
  var createNonFunctionalReturn = () => ({
1825
1390
  visibleMessages: [],
1826
1391
  messages: [],
@@ -1839,6 +1404,7 @@ var createNonFunctionalReturn = () => ({
1839
1404
  reset: () => {
1840
1405
  },
1841
1406
  isLoading: false,
1407
+ isAvailable: false,
1842
1408
  runChatCompletion: () => __async(void 0, null, function* () {
1843
1409
  return [];
1844
1410
  }),
@@ -1858,21 +1424,21 @@ var createNonFunctionalReturn = () => ({
1858
1424
  function useCopilotChatHeadless_c(options = {}) {
1859
1425
  const { copilotApiConfig, setBannerError } = useCopilotContext();
1860
1426
  const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);
1861
- const internalResult = useCopilotChat(options);
1862
- (0, import_react11.useEffect)(() => {
1427
+ const internalResult = useCopilotChatInternal(options);
1428
+ (0, import_react14.useEffect)(() => {
1863
1429
  if (!hasPublicApiKey) {
1864
1430
  setBannerError(
1865
- new import_shared9.CopilotKitError({
1431
+ new import_shared4.CopilotKitError({
1866
1432
  message: (
1867
1433
  // add link to documentation here
1868
1434
  "You're using useCopilotChatHeadless_c, a premium-only feature, which offers extensive headless chat capabilities. To continue, you'll need to provide a free public license key."
1869
1435
  ),
1870
- code: import_shared9.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
1871
- severity: import_shared9.Severity.WARNING,
1872
- visibility: import_shared9.ErrorVisibility.BANNER
1436
+ code: import_shared4.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
1437
+ severity: import_shared4.Severity.WARNING,
1438
+ visibility: import_shared4.ErrorVisibility.BANNER
1873
1439
  })
1874
1440
  );
1875
- import_shared9.styledConsole.logCopilotKitPlatformMessage();
1441
+ import_shared4.styledConsole.logCopilotKitPlatformMessage();
1876
1442
  } else {
1877
1443
  setBannerError(null);
1878
1444
  }
@@ -1884,146 +1450,233 @@ function useCopilotChatHeadless_c(options = {}) {
1884
1450
  }
1885
1451
 
1886
1452
  // src/hooks/use-copilot-action.ts
1887
- var import_shared10 = require("@copilotkit/shared");
1888
- var import_react12 = require("react");
1889
- function useCopilotAction(action, dependencies) {
1890
- const { setAction, removeAction, actions, chatComponentsCache } = useCopilotContext();
1891
- const idRef = (0, import_react12.useRef)((0, import_shared10.randomId)());
1892
- const renderAndWaitRef = (0, import_react12.useRef)(null);
1893
- const activatingMessageIdRef = (0, import_react12.useRef)(null);
1894
- const { addToast } = useToast();
1895
- action = __spreadValues({}, action);
1896
- if (
1897
- // renderAndWaitForResponse is not available for catch all actions
1898
- isFrontendAction(action) && // check if renderAndWaitForResponse is set
1899
- (action.renderAndWait || action.renderAndWaitForResponse)
1900
- ) {
1901
- action._isRenderAndWait = true;
1902
- const renderAndWait = action.renderAndWait || action.renderAndWaitForResponse;
1903
- action.renderAndWait = void 0;
1904
- action.renderAndWaitForResponse = void 0;
1905
- action._setActivatingMessageId = (id) => {
1906
- activatingMessageIdRef.current = id;
1907
- };
1908
- action.handler = useAsyncCallback(() => __async(this, null, function* () {
1909
- const currentActivatingId = activatingMessageIdRef.current;
1910
- let resolve;
1911
- let reject;
1912
- const promise = new Promise((resolvePromise, rejectPromise) => {
1913
- resolve = resolvePromise;
1914
- reject = rejectPromise;
1453
+ var import_react21 = require("react");
1454
+
1455
+ // src/hooks/use-frontend-tool.ts
1456
+ var import_react15 = __toESM(require("react"));
1457
+ var import_shared5 = require("@copilotkit/shared");
1458
+ var import_shared6 = require("@copilotkit/shared");
1459
+ var import_react16 = require("@copilotkitnext/react");
1460
+ function useFrontendTool(tool, dependencies) {
1461
+ const { name, description, parameters, render, followUp } = tool;
1462
+ const zodParameters = (0, import_shared5.getZodParameters)(parameters);
1463
+ const normalizedRender = (() => {
1464
+ if (typeof render === "undefined") {
1465
+ return void 0;
1466
+ }
1467
+ if (typeof render === "string") {
1468
+ const staticRender = render;
1469
+ return () => import_react15.default.createElement(import_react15.default.Fragment, null, staticRender);
1470
+ }
1471
+ return (args) => {
1472
+ const renderArgs = __spreadProps(__spreadValues({}, args), {
1473
+ result: typeof args.result === "string" ? (0, import_shared6.parseJson)(args.result, args.result) : args.result
1915
1474
  });
1916
- renderAndWaitRef.current = {
1917
- promise,
1918
- resolve,
1919
- reject,
1920
- messageId: currentActivatingId
1921
- };
1922
- const result = yield promise;
1923
- return result;
1924
- }), []);
1925
- action.render = (props) => {
1926
- const currentRenderMessageId = props.messageId;
1927
- let status = props.status;
1928
- if (props.status === "executing") {
1929
- if (!renderAndWaitRef.current || !renderAndWaitRef.current.promise) {
1930
- status = "inProgress";
1931
- } else if (renderAndWaitRef.current.messageId !== currentRenderMessageId && activatingMessageIdRef.current !== currentRenderMessageId) {
1932
- status = "inProgress";
1933
- }
1475
+ const rendered = render(renderArgs);
1476
+ if (typeof rendered === "string") {
1477
+ return import_react15.default.createElement(import_react15.default.Fragment, null, rendered);
1934
1478
  }
1935
- const waitProps = {
1936
- status,
1937
- args: props.args,
1938
- result: props.result,
1939
- // handler and respond should only be provided if this is the truly active instance
1940
- // and its promise infrastructure is ready.
1941
- handler: status === "executing" && renderAndWaitRef.current && renderAndWaitRef.current.messageId === currentRenderMessageId ? renderAndWaitRef.current.resolve : void 0,
1942
- respond: status === "executing" && renderAndWaitRef.current && renderAndWaitRef.current.messageId === currentRenderMessageId ? renderAndWaitRef.current.resolve : void 0
1943
- };
1944
- const isNoArgsRenderWait = (_fn) => {
1945
- var _a;
1946
- return ((_a = action.parameters) == null ? void 0 : _a.length) === 0;
1947
- };
1948
- if (renderAndWait) {
1949
- if (isNoArgsRenderWait(renderAndWait)) {
1950
- return renderAndWait(waitProps);
1951
- } else {
1952
- return renderAndWait(waitProps);
1479
+ return rendered != null ? rendered : null;
1480
+ };
1481
+ })();
1482
+ (0, import_react16.useFrontendTool)({
1483
+ name,
1484
+ description,
1485
+ parameters: zodParameters,
1486
+ handler: tool.handler,
1487
+ followUp,
1488
+ render: normalizedRender
1489
+ });
1490
+ }
1491
+
1492
+ // src/hooks/use-render-tool-call.ts
1493
+ var import_shared7 = require("@copilotkit/shared");
1494
+ var import_react17 = require("react");
1495
+ var import_react18 = require("@copilotkitnext/react");
1496
+ var import_shared8 = require("@copilotkit/shared");
1497
+ function useRenderToolCall2(tool, dependencies) {
1498
+ const { copilotkit } = (0, import_react18.useCopilotKit)();
1499
+ const hasAddedRef = (0, import_react17.useRef)(false);
1500
+ (0, import_react17.useEffect)(() => {
1501
+ const { name, parameters, render } = tool;
1502
+ const zodParameters = (0, import_shared7.getZodParameters)(parameters);
1503
+ const renderToolCall = name === "*" ? (0, import_react18.defineToolCallRenderer)({
1504
+ name: "*",
1505
+ render: (args) => {
1506
+ return render(__spreadProps(__spreadValues({}, args), {
1507
+ result: args.result ? (0, import_shared8.parseJson)(args.result, args.result) : args.result
1508
+ }));
1509
+ }
1510
+ }) : (0, import_react18.defineToolCallRenderer)({
1511
+ name,
1512
+ args: zodParameters,
1513
+ render: (args) => {
1514
+ return render(__spreadProps(__spreadValues({}, args), {
1515
+ result: args.result ? (0, import_shared8.parseJson)(args.result, args.result) : args.result
1516
+ }));
1517
+ }
1518
+ });
1519
+ const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
1520
+ if (existingIndex !== -1) {
1521
+ copilotkit.renderToolCalls.splice(existingIndex, 1);
1522
+ }
1523
+ copilotkit.renderToolCalls.push(renderToolCall);
1524
+ hasAddedRef.current = true;
1525
+ return () => {
1526
+ if (hasAddedRef.current) {
1527
+ const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
1528
+ if (index !== -1) {
1529
+ copilotkit.renderToolCalls.splice(index, 1);
1953
1530
  }
1531
+ hasAddedRef.current = false;
1954
1532
  }
1955
- return (0, import_react12.createElement)(import_react12.Fragment);
1956
1533
  };
1957
- }
1958
- if (dependencies === void 0) {
1959
- if (actions[idRef.current]) {
1960
- if (isFrontendAction(action)) {
1961
- actions[idRef.current].handler = action.handler;
1534
+ }, [tool, ...dependencies != null ? dependencies : []]);
1535
+ }
1536
+
1537
+ // src/hooks/use-human-in-the-loop.ts
1538
+ var import_shared9 = require("@copilotkit/shared");
1539
+ var import_react19 = require("@copilotkitnext/react");
1540
+ var import_core = require("@copilotkitnext/core");
1541
+ var import_react20 = __toESM(require("react"));
1542
+ function useHumanInTheLoop(tool, dependencies) {
1543
+ const _a = tool, { render } = _a, toolRest = __objRest(_a, ["render"]);
1544
+ const { name, description, parameters, followUp } = toolRest;
1545
+ const zodParameters = (0, import_shared9.getZodParameters)(parameters);
1546
+ const renderRef = (0, import_react20.useRef)(null);
1547
+ (0, import_react20.useEffect)(() => {
1548
+ renderRef.current = (args) => {
1549
+ if (typeof render === "string") {
1550
+ return import_react20.default.createElement(import_react20.default.Fragment, null, render);
1962
1551
  }
1963
- if (typeof action.render === "function") {
1964
- if (chatComponentsCache.current !== null) {
1965
- chatComponentsCache.current.actions[action.name] = action.render;
1552
+ if (!render) {
1553
+ return null;
1554
+ }
1555
+ const renderProps = (() => {
1556
+ const mappedArgs = args.args;
1557
+ switch (args.status) {
1558
+ case import_core.ToolCallStatus.InProgress:
1559
+ return {
1560
+ args: mappedArgs,
1561
+ respond: args.respond,
1562
+ status: args.status,
1563
+ handler: void 0
1564
+ };
1565
+ case import_core.ToolCallStatus.Executing:
1566
+ return {
1567
+ args: mappedArgs,
1568
+ respond: args.respond,
1569
+ status: args.status,
1570
+ handler: () => {
1571
+ }
1572
+ };
1573
+ case import_core.ToolCallStatus.Complete:
1574
+ return {
1575
+ args: mappedArgs,
1576
+ respond: args.respond,
1577
+ status: args.status,
1578
+ result: args.result ? (0, import_shared9.parseJson)(args.result, args.result) : args.result,
1579
+ handler: void 0
1580
+ };
1581
+ default:
1582
+ throw new import_shared9.CopilotKitError({
1583
+ code: import_shared9.CopilotKitErrorCode.UNKNOWN,
1584
+ message: `Invalid tool call status: ${args.status}`
1585
+ });
1966
1586
  }
1587
+ })();
1588
+ const rendered = render(renderProps);
1589
+ if (typeof rendered === "string") {
1590
+ return import_react20.default.createElement(import_react20.default.Fragment, null, rendered);
1967
1591
  }
1592
+ return rendered != null ? rendered : null;
1593
+ };
1594
+ }, [render, ...dependencies != null ? dependencies : []]);
1595
+ (0, import_react19.useHumanInTheLoop)({
1596
+ name,
1597
+ description,
1598
+ followUp,
1599
+ parameters: zodParameters,
1600
+ render: (args) => {
1601
+ var _a2, _b;
1602
+ return (_b = (_a2 = renderRef.current) == null ? void 0 : _a2.call(renderRef, args)) != null ? _b : null;
1603
+ }
1604
+ });
1605
+ }
1606
+
1607
+ // src/hooks/use-copilot-action.ts
1608
+ function getActionConfig(action) {
1609
+ if (action.name === "*") {
1610
+ return {
1611
+ type: "render",
1612
+ action
1613
+ };
1614
+ }
1615
+ if ("renderAndWaitForResponse" in action || "renderAndWait" in action) {
1616
+ let render = action.render;
1617
+ if (!render && "renderAndWaitForResponse" in action) {
1618
+ render = action.renderAndWaitForResponse;
1619
+ }
1620
+ if (!render && "renderAndWait" in action) {
1621
+ render = action.renderAndWait;
1968
1622
  }
1623
+ return {
1624
+ type: "hitl",
1625
+ action: __spreadProps(__spreadValues({}, action), { render })
1626
+ };
1969
1627
  }
1970
- (0, import_react12.useEffect)(() => {
1971
- const hasDuplicate = Object.values(actions).some(
1972
- (otherAction) => otherAction.name === action.name && otherAction !== actions[idRef.current]
1973
- );
1974
- if (hasDuplicate) {
1975
- addToast({
1976
- type: "warning",
1977
- message: `Found an already registered action with name ${action.name}.`,
1978
- id: `dup-action-${action.name}`
1979
- });
1628
+ if ("available" in action) {
1629
+ if (action.available === "enabled" || action.available === "remote") {
1630
+ return {
1631
+ type: "frontend",
1632
+ action
1633
+ };
1980
1634
  }
1981
- }, [actions]);
1982
- (0, import_react12.useEffect)(() => {
1983
- setAction(idRef.current, action);
1984
- if (chatComponentsCache.current !== null && action.render !== void 0) {
1985
- chatComponentsCache.current.actions[action.name] = action.render;
1635
+ if (action.available === "frontend" || action.available === "disabled") {
1636
+ return {
1637
+ type: "render",
1638
+ action
1639
+ };
1986
1640
  }
1987
- return () => {
1988
- removeAction(idRef.current);
1641
+ }
1642
+ if ("handler" in action) {
1643
+ return {
1644
+ type: "frontend",
1645
+ action
1989
1646
  };
1990
- }, [
1991
- setAction,
1992
- removeAction,
1993
- isFrontendAction(action) ? action.description : void 0,
1994
- action.name,
1995
- isFrontendAction(action) ? action.disabled : void 0,
1996
- isFrontendAction(action) ? action.available : void 0,
1997
- // This should be faster than deep equality checking
1998
- // In addition, all major JS engines guarantee the order of object keys
1999
- JSON.stringify(isFrontendAction(action) ? action.parameters : []),
2000
- // include render only if it's a string
2001
- typeof action.render === "string" ? action.render : void 0,
2002
- // dependencies set by the developer
2003
- ...dependencies || []
2004
- ]);
1647
+ }
1648
+ throw new Error("Invalid action configuration");
2005
1649
  }
2006
- function isFrontendAction(action) {
2007
- return action.name !== "*";
1650
+ function useCopilotAction(action, dependencies) {
1651
+ const [initialActionConfig] = (0, import_react21.useState)(getActionConfig(action));
1652
+ const currentActionConfig = getActionConfig(action);
1653
+ if (initialActionConfig.type !== currentActionConfig.type) {
1654
+ throw new Error("Action configuration changed between renders");
1655
+ }
1656
+ switch (currentActionConfig.type) {
1657
+ case "render":
1658
+ return useRenderToolCall2(currentActionConfig.action, dependencies);
1659
+ case "hitl":
1660
+ return useHumanInTheLoop(currentActionConfig.action, dependencies);
1661
+ case "frontend":
1662
+ return useFrontendTool(currentActionConfig.action, dependencies);
1663
+ default:
1664
+ throw new Error("Invalid action configuration");
1665
+ }
2008
1666
  }
2009
1667
 
2010
1668
  // src/hooks/use-coagent-state-render.ts
2011
- var import_react13 = require("react");
2012
- var import_shared11 = require("@copilotkit/shared");
1669
+ var import_react22 = require("react");
1670
+ var import_shared10 = require("@copilotkit/shared");
2013
1671
  function useCoAgentStateRender(action, dependencies) {
2014
- const {
2015
- setCoAgentStateRender,
2016
- removeCoAgentStateRender,
2017
- coAgentStateRenders,
2018
- chatComponentsCache,
2019
- availableAgents
2020
- } = (0, import_react13.useContext)(CopilotContext);
2021
- const idRef = (0, import_react13.useRef)((0, import_shared11.randomId)());
1672
+ const { chatComponentsCache, availableAgents } = (0, import_react22.useContext)(CopilotContext);
1673
+ const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } = useCoAgentStateRenders();
1674
+ const idRef = (0, import_react22.useRef)((0, import_shared10.randomId)());
2022
1675
  const { setBannerError, addToast } = useToast();
2023
- (0, import_react13.useEffect)(() => {
1676
+ (0, import_react22.useEffect)(() => {
2024
1677
  if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === action.name)) {
2025
1678
  const message = `(useCoAgentStateRender): Agent "${action.name}" not found. Make sure the agent exists and is properly configured.`;
2026
- const agentError = new import_shared11.CopilotKitAgentDiscoveryError({
1679
+ const agentError = new import_shared10.CopilotKitAgentDiscoveryError({
2027
1680
  agentName: action.name,
2028
1681
  availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id }))
2029
1682
  });
@@ -2041,7 +1694,7 @@ function useCoAgentStateRender(action, dependencies) {
2041
1694
  }
2042
1695
  }
2043
1696
  }
2044
- (0, import_react13.useEffect)(() => {
1697
+ (0, import_react22.useEffect)(() => {
2045
1698
  const currentId = idRef.current;
2046
1699
  const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
2047
1700
  if (id === currentId)
@@ -2065,7 +1718,7 @@ function useCoAgentStateRender(action, dependencies) {
2065
1718
  });
2066
1719
  }
2067
1720
  }, [coAgentStateRenders]);
2068
- (0, import_react13.useEffect)(() => {
1721
+ (0, import_react22.useEffect)(() => {
2069
1722
  setCoAgentStateRender(idRef.current, action);
2070
1723
  if (chatComponentsCache.current !== null && action.render !== void 0) {
2071
1724
  chatComponentsCache.current.coAgentStateRenders[key] = action.render;
@@ -2085,11 +1738,11 @@ function useCoAgentStateRender(action, dependencies) {
2085
1738
  }
2086
1739
 
2087
1740
  // src/hooks/use-make-copilot-document-readable.ts
2088
- var import_react14 = require("react");
1741
+ var import_react23 = require("react");
2089
1742
  function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
2090
1743
  const { addDocumentContext, removeDocumentContext } = useCopilotContext();
2091
- const idRef = (0, import_react14.useRef)();
2092
- (0, import_react14.useEffect)(() => {
1744
+ const idRef = (0, import_react23.useRef)(void 0);
1745
+ (0, import_react23.useEffect)(() => {
2093
1746
  const id = addDocumentContext(document, categories);
2094
1747
  idRef.current = id;
2095
1748
  return () => {
@@ -2100,275 +1753,292 @@ function useMakeCopilotDocumentReadable(document, categories, dependencies = [])
2100
1753
  }
2101
1754
 
2102
1755
  // src/hooks/use-copilot-readable.ts
2103
- var import_react15 = require("react");
2104
- function convertToJSON(description, value) {
2105
- return `${description}: ${typeof value === "string" ? value : JSON.stringify(value)}`;
2106
- }
2107
- function useCopilotReadable({
2108
- description,
2109
- value,
2110
- parentId,
2111
- categories,
2112
- convert,
2113
- available = "enabled"
2114
- }, dependencies) {
2115
- const { addContext, removeContext } = useCopilotContext();
2116
- const idRef = (0, import_react15.useRef)();
2117
- convert = convert || convertToJSON;
2118
- const information = convert(description, value);
2119
- (0, import_react15.useEffect)(() => {
2120
- if (available === "disabled")
2121
- return;
2122
- const id = addContext(information, parentId, categories);
2123
- idRef.current = id;
2124
- return () => {
2125
- removeContext(id);
2126
- };
2127
- }, [available, information, parentId, addContext, removeContext, ...dependencies || []]);
2128
- return idRef.current;
1756
+ var import_react24 = require("@copilotkitnext/react");
1757
+ function useCopilotReadable({ description, value }, dependencies) {
1758
+ (0, import_react24.useAgentContext)({
1759
+ description,
1760
+ value
1761
+ });
2129
1762
  }
2130
1763
 
2131
1764
  // src/hooks/use-coagent.ts
2132
- var import_react16 = require("react");
2133
- var import_shared12 = require("@copilotkit/shared");
1765
+ var import_react25 = require("react");
1766
+ var import_react26 = require("@copilotkitnext/react");
2134
1767
  function useCoAgent(options) {
2135
- const context = useCopilotContext();
2136
- const { availableAgents, onError } = context;
2137
- const { setBannerError } = useToast();
2138
- const lastLoadedThreadId = (0, import_react16.useRef)();
2139
- const lastLoadedState = (0, import_react16.useRef)();
2140
- const { name } = options;
2141
- (0, import_react16.useEffect)(() => {
2142
- if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === name)) {
2143
- const message = `(useCoAgent): Agent "${name}" not found. Make sure the agent exists and is properly configured.`;
2144
- console.warn(message);
2145
- const agentError = new import_shared12.CopilotKitAgentDiscoveryError({
2146
- agentName: name,
2147
- availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id }))
2148
- });
2149
- setBannerError(agentError);
2150
- }
2151
- }, [availableAgents]);
2152
- const { getMessagesFromTap } = useMessagesTap();
2153
- const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context;
2154
- const { sendMessage, runChatCompletion } = useCopilotChat();
2155
- const headers = __spreadValues({}, copilotApiConfig.headers || {});
2156
- const runtimeClient = useCopilotRuntimeClient({
2157
- url: copilotApiConfig.chatApiEndpoint,
2158
- publicApiKey: copilotApiConfig.publicApiKey,
2159
- headers,
2160
- credentials: copilotApiConfig.credentials,
2161
- showDevConsole: context.showDevConsole,
2162
- onError
2163
- });
2164
- const setState = (0, import_react16.useCallback)(
1768
+ const { agent } = (0, import_react26.useAgent)({ agentId: options.name });
1769
+ const nodeNameRef = (0, import_react25.useRef)("start");
1770
+ const handleStateUpdate = (0, import_react25.useCallback)(
2165
1771
  (newState) => {
2166
- let coagentState = getCoagentState({ coagentStates, name, options });
2167
- const updatedState = typeof newState === "function" ? newState(coagentState.state) : newState;
2168
- setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), {
2169
- [name]: __spreadProps(__spreadValues({}, coagentState), {
2170
- state: updatedState
2171
- })
2172
- }));
2173
- },
2174
- [coagentStates, name]
2175
- );
2176
- (0, import_react16.useEffect)(() => {
2177
- const fetchAgentState = () => __async(this, null, function* () {
2178
- var _a, _b, _c, _d;
2179
- if (!threadId || threadId === lastLoadedThreadId.current)
2180
- return;
2181
- const result = yield runtimeClient.loadAgentState({
2182
- threadId,
2183
- agentName: name
2184
- });
2185
- if (result.error) {
1772
+ if (!agent)
2186
1773
  return;
1774
+ if (typeof newState === "function") {
1775
+ const updater = newState;
1776
+ agent.setState(updater(agent.state));
1777
+ } else {
1778
+ agent.setState(__spreadValues(__spreadValues({}, agent.state), newState));
2187
1779
  }
2188
- const newState = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.state;
2189
- if (newState === lastLoadedState.current)
2190
- return;
2191
- if (((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) && newState && newState != "{}") {
2192
- lastLoadedState.current = newState;
2193
- lastLoadedThreadId.current = threadId;
2194
- const fetchedState = (0, import_shared12.parseJson)(newState, {});
2195
- isExternalStateManagement(options) ? options.setState(fetchedState) : setState(fetchedState);
2196
- }
2197
- });
2198
- void fetchAgentState();
2199
- }, [threadId]);
2200
- (0, import_react16.useEffect)(() => {
1780
+ },
1781
+ [agent == null ? void 0 : agent.state, agent == null ? void 0 : agent.setState]
1782
+ );
1783
+ const externalStateStr = (0, import_react25.useMemo)(
1784
+ () => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
1785
+ [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]
1786
+ );
1787
+ (0, import_react25.useEffect)(() => {
1788
+ if ((agent == null ? void 0 : agent.state) && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) {
1789
+ handleStateUpdate(options.state);
1790
+ }
1791
+ }, [agent, externalStateStr, handleStateUpdate]);
1792
+ const hasStateValues = (0, import_react25.useCallback)((value) => {
1793
+ return Boolean(value && Object.keys(value).length);
1794
+ }, []);
1795
+ const initialStateRef = (0, import_react25.useRef)(
1796
+ isExternalStateManagement(options) ? options.state : "initialState" in options ? options.initialState : void 0
1797
+ );
1798
+ (0, import_react25.useEffect)(() => {
2201
1799
  if (isExternalStateManagement(options)) {
2202
- setState(options.state);
2203
- } else if (coagentStates[name] === void 0) {
2204
- setState(options.initialState === void 0 ? {} : options.initialState);
1800
+ initialStateRef.current = options.state;
1801
+ } else if ("initialState" in options) {
1802
+ initialStateRef.current = options.initialState;
2205
1803
  }
2206
1804
  }, [
2207
- isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
2208
- // reset initialstate on reset
2209
- coagentStates[name] === void 0
1805
+ isExternalStateManagement(options) ? JSON.stringify(options.state) : "initialState" in options ? JSON.stringify(options.initialState) : void 0
2210
1806
  ]);
2211
- (0, import_react16.useEffect)(() => {
2212
- const newConfig = options.config ? options.config : options.configurable ? { configurable: options.configurable } : void 0;
2213
- if (newConfig === void 0)
1807
+ (0, import_react25.useEffect)(() => {
1808
+ if (!agent)
2214
1809
  return;
2215
- setCoagentStatesWithRef((prev) => {
2216
- var _a;
2217
- const existing = (_a = prev[name]) != null ? _a : {
2218
- name,
2219
- state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
2220
- config: {},
2221
- running: false,
2222
- active: false,
2223
- threadId: void 0,
2224
- nodeName: void 0,
2225
- runId: void 0
2226
- };
2227
- if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {
2228
- return prev;
1810
+ const subscriber = {
1811
+ onStateChanged: (args) => {
1812
+ if (isExternalStateManagement(options)) {
1813
+ options.setState(args.state);
1814
+ }
1815
+ },
1816
+ onRunInitialized: (args) => {
1817
+ const runHasState = hasStateValues(args.state);
1818
+ if (runHasState) {
1819
+ handleStateUpdate(args.state);
1820
+ return;
1821
+ }
1822
+ if (hasStateValues(agent.state)) {
1823
+ return;
1824
+ }
1825
+ if (initialStateRef.current !== void 0) {
1826
+ handleStateUpdate(initialStateRef.current);
1827
+ }
1828
+ },
1829
+ onStepStartedEvent: ({ event }) => {
1830
+ nodeNameRef.current = event.stepName;
1831
+ },
1832
+ onRunStartedEvent: () => {
1833
+ nodeNameRef.current = "start";
1834
+ },
1835
+ onRunFinishedEvent: () => {
1836
+ nodeNameRef.current = "end";
2229
1837
  }
2230
- return __spreadProps(__spreadValues({}, prev), {
2231
- [name]: __spreadProps(__spreadValues({}, existing), {
2232
- config: newConfig
2233
- })
2234
- });
2235
- });
2236
- }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);
2237
- const runAgentCallback = useAsyncCallback(
2238
- (hint) => __async(this, null, function* () {
2239
- yield runAgent(name, context, getMessagesFromTap(), sendMessage, runChatCompletion, hint);
2240
- }),
2241
- [name, context, sendMessage, runChatCompletion]
2242
- );
2243
- return (0, import_react16.useMemo)(() => {
2244
- const coagentState = getCoagentState({ coagentStates, name, options });
2245
- return {
2246
- name,
2247
- nodeName: coagentState.nodeName,
2248
- threadId: coagentState.threadId,
2249
- running: coagentState.running,
2250
- state: coagentState.state,
2251
- setState: isExternalStateManagement(options) ? options.setState : setState,
2252
- start: () => startAgent(name, context),
2253
- stop: () => stopAgent(name, context),
2254
- run: runAgentCallback
2255
1838
  };
2256
- }, [name, coagentStates, options, setState, runAgentCallback]);
2257
- }
2258
- function startAgent(name, context) {
2259
- const { setAgentSession } = context;
2260
- setAgentSession({
2261
- agentName: name
2262
- });
2263
- }
2264
- function stopAgent(name, context) {
2265
- const { agentSession, setAgentSession } = context;
2266
- if (agentSession && agentSession.agentName === name) {
2267
- setAgentSession(null);
2268
- context.setCoagentStates((prevAgentStates) => {
2269
- return __spreadProps(__spreadValues({}, prevAgentStates), {
2270
- [name]: __spreadProps(__spreadValues({}, prevAgentStates[name]), {
2271
- running: false,
2272
- active: false,
2273
- threadId: void 0,
2274
- nodeName: void 0,
2275
- runId: void 0
2276
- })
2277
- });
2278
- });
2279
- } else {
2280
- console.warn(`No agent session found for ${name}`);
2281
- }
2282
- }
2283
- function runAgent(name, context, messages, sendMessage, runChatCompletion, hint) {
2284
- return __async(this, null, function* () {
2285
- var _a, _b;
2286
- const { agentSession, setAgentSession } = context;
2287
- if (!agentSession || agentSession.agentName !== name) {
2288
- setAgentSession({
2289
- agentName: name
1839
+ const subscription = agent.subscribe(subscriber);
1840
+ return () => {
1841
+ subscription.unsubscribe();
1842
+ };
1843
+ }, [agent, handleStateUpdate, hasStateValues]);
1844
+ return (0, import_react25.useMemo)(() => {
1845
+ var _a, _b, _c;
1846
+ if (!agent) {
1847
+ const noop = () => {
1848
+ };
1849
+ const noopAsync = () => __async(this, null, function* () {
2290
1850
  });
1851
+ const initialState = (
1852
+ // prefer externally provided state if available
1853
+ (_b = (_a = "state" in options && options.state) != null ? _a : (
1854
+ // then initialState if provided
1855
+ "initialState" in options && options.initialState
1856
+ )) != null ? _b : {}
1857
+ );
1858
+ return {
1859
+ name: options.name,
1860
+ nodeName: nodeNameRef.current,
1861
+ threadId: void 0,
1862
+ running: false,
1863
+ state: initialState,
1864
+ setState: noop,
1865
+ start: noop,
1866
+ stop: noop,
1867
+ run: noopAsync
1868
+ };
2291
1869
  }
2292
- let previousState = null;
2293
- for (let i = messages.length - 1; i >= 0; i--) {
2294
- const message = messages[i];
2295
- if (message.isAgentStateMessage() && message.agentName === name) {
2296
- previousState = message.state;
2297
- }
2298
- }
2299
- let state = ((_b = (_a = context.coagentStatesRef.current) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {};
2300
- if (hint) {
2301
- const hintMessage = hint({ previousState, currentState: state });
2302
- if (hintMessage) {
2303
- yield sendMessage(hintMessage);
2304
- } else {
2305
- yield runChatCompletion();
2306
- }
2307
- } else {
2308
- yield runChatCompletion();
2309
- }
2310
- });
1870
+ return {
1871
+ name: (_c = agent == null ? void 0 : agent.agentId) != null ? _c : options.name,
1872
+ nodeName: nodeNameRef.current,
1873
+ threadId: agent.threadId,
1874
+ running: agent.isRunning,
1875
+ state: agent.state,
1876
+ setState: handleStateUpdate,
1877
+ // TODO: start and run both have same thing. need to figure out
1878
+ start: agent.runAgent,
1879
+ stop: agent.abortRun,
1880
+ run: agent.runAgent
1881
+ };
1882
+ }, [
1883
+ agent == null ? void 0 : agent.state,
1884
+ agent == null ? void 0 : agent.runAgent,
1885
+ agent == null ? void 0 : agent.abortRun,
1886
+ agent == null ? void 0 : agent.runAgent,
1887
+ agent == null ? void 0 : agent.threadId,
1888
+ agent == null ? void 0 : agent.isRunning,
1889
+ agent == null ? void 0 : agent.agentId,
1890
+ handleStateUpdate,
1891
+ options.name
1892
+ ]);
2311
1893
  }
2312
1894
  var isExternalStateManagement = (options) => {
2313
1895
  return "state" in options && "setState" in options;
2314
1896
  };
2315
- var isInternalStateManagementWithInitial = (options) => {
2316
- return "initialState" in options;
1897
+
1898
+ // src/hooks/use-copilot-runtime-client.ts
1899
+ var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
1900
+ var import_react27 = require("react");
1901
+ var import_shared11 = require("@copilotkit/shared");
1902
+ var useCopilotRuntimeClient = (options) => {
1903
+ const { setBannerError } = useToast();
1904
+ const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
1905
+ const lastStructuredErrorRef = (0, import_react27.useRef)(null);
1906
+ const traceUIError = (error, originalError) => __async(void 0, null, function* () {
1907
+ try {
1908
+ const errorEvent = {
1909
+ type: "error",
1910
+ timestamp: Date.now(),
1911
+ context: {
1912
+ source: "ui",
1913
+ request: {
1914
+ operation: "runtimeClient",
1915
+ url: runtimeOptions.url,
1916
+ startTime: Date.now()
1917
+ },
1918
+ technical: {
1919
+ environment: "browser",
1920
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
1921
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
1922
+ }
1923
+ },
1924
+ error
1925
+ };
1926
+ yield onError(errorEvent);
1927
+ } catch (error2) {
1928
+ console.error("Error in onError handler:", error2);
1929
+ }
1930
+ });
1931
+ const runtimeClient = (0, import_react27.useMemo)(() => {
1932
+ return new import_runtime_client_gql3.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
1933
+ handleGQLErrors: (error) => {
1934
+ var _a2;
1935
+ if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
1936
+ const graphQLErrors = error.graphQLErrors;
1937
+ const routeError = (gqlError) => {
1938
+ const extensions = gqlError.extensions;
1939
+ const visibility = extensions == null ? void 0 : extensions.visibility;
1940
+ if (visibility === import_shared11.ErrorVisibility.SILENT) {
1941
+ console.error("CopilotKit Silent Error:", gqlError.message);
1942
+ return;
1943
+ }
1944
+ const now = Date.now();
1945
+ const errorMessage = gqlError.message;
1946
+ if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
1947
+ return;
1948
+ }
1949
+ lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
1950
+ const ckError = createStructuredError(gqlError);
1951
+ if (ckError) {
1952
+ setBannerError(ckError);
1953
+ traceUIError(ckError, gqlError);
1954
+ } else {
1955
+ const fallbackError = new import_shared11.CopilotKitError({
1956
+ message: gqlError.message,
1957
+ code: import_shared11.CopilotKitErrorCode.UNKNOWN
1958
+ });
1959
+ setBannerError(fallbackError);
1960
+ traceUIError(fallbackError, gqlError);
1961
+ }
1962
+ };
1963
+ graphQLErrors.forEach(routeError);
1964
+ } else {
1965
+ const fallbackError = new import_shared11.CopilotKitError({
1966
+ message: (error == null ? void 0 : error.message) || String(error),
1967
+ code: import_shared11.CopilotKitErrorCode.UNKNOWN
1968
+ });
1969
+ setBannerError(fallbackError);
1970
+ traceUIError(fallbackError, error);
1971
+ }
1972
+ },
1973
+ handleGQLWarning: (message) => {
1974
+ console.warn(message);
1975
+ const warningError = new import_shared11.CopilotKitError({
1976
+ message,
1977
+ code: import_shared11.CopilotKitErrorCode.UNKNOWN
1978
+ });
1979
+ setBannerError(warningError);
1980
+ }
1981
+ }));
1982
+ }, [runtimeOptions, setBannerError, onError]);
1983
+ return runtimeClient;
2317
1984
  };
2318
- var getCoagentState = ({
2319
- coagentStates,
2320
- name,
2321
- options
2322
- }) => {
2323
- if (coagentStates[name]) {
2324
- return coagentStates[name];
2325
- } else {
2326
- return {
2327
- name,
2328
- state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
2329
- config: options.config ? options.config : options.configurable ? { configurable: options.configurable } : {},
2330
- running: false,
2331
- active: false,
2332
- threadId: void 0,
2333
- nodeName: void 0,
2334
- runId: void 0
2335
- };
1985
+ function createStructuredError(gqlError) {
1986
+ var _a, _b, _c;
1987
+ const extensions = gqlError.extensions;
1988
+ const originalError = extensions == null ? void 0 : extensions.originalError;
1989
+ const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
1990
+ const code = extensions == null ? void 0 : extensions.code;
1991
+ if (code) {
1992
+ return new import_shared11.CopilotKitError({ message, code });
2336
1993
  }
2337
- };
1994
+ if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
1995
+ return new import_shared11.CopilotKitApiDiscoveryError({ message });
1996
+ }
1997
+ if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
1998
+ return new import_shared11.CopilotKitRemoteEndpointDiscoveryError({ message });
1999
+ }
2000
+ if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
2001
+ return new import_shared11.CopilotKitAgentDiscoveryError({
2002
+ agentName: "",
2003
+ availableAgents: []
2004
+ });
2005
+ }
2006
+ return null;
2007
+ }
2338
2008
 
2339
2009
  // src/hooks/use-copilot-authenticated-action.ts
2340
- var import_react17 = require("react");
2341
- var import_react18 = __toESM(require("react"));
2010
+ var import_react28 = require("react");
2011
+ var import_react29 = __toESM(require("react"));
2342
2012
  function useCopilotAuthenticatedAction_c(action, dependencies) {
2343
2013
  const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
2344
- const pendingActionRef = (0, import_react17.useRef)(null);
2345
- const executeAction2 = (0, import_react17.useCallback)(
2014
+ const pendingActionRef = (0, import_react28.useRef)(null);
2015
+ const executeAction = (0, import_react28.useCallback)(
2346
2016
  (props) => {
2347
2017
  if (typeof action.render === "function") {
2348
2018
  return action.render(props);
2349
2019
  }
2350
- return action.render || import_react18.default.createElement(import_react17.Fragment);
2020
+ return action.render || import_react29.default.createElement(import_react28.Fragment);
2351
2021
  },
2352
2022
  [action]
2353
2023
  );
2354
- const wrappedRender = (0, import_react17.useCallback)(
2024
+ const wrappedRender = (0, import_react28.useCallback)(
2355
2025
  (props) => {
2356
2026
  const isAuthenticated = Object.values(authStates_c || {}).some(
2357
2027
  (state) => state.status === "authenticated"
2358
2028
  );
2359
2029
  if (!isAuthenticated) {
2360
2030
  pendingActionRef.current = props;
2361
- return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? import_react18.default.createElement(authConfig_c.SignInComponent, {
2031
+ return (authConfig_c == null ? void 0 : authConfig_c.SignInComponent) ? import_react29.default.createElement(authConfig_c.SignInComponent, {
2362
2032
  onSignInComplete: (authState) => {
2363
2033
  setAuthStates_c == null ? void 0 : setAuthStates_c((prev) => __spreadProps(__spreadValues({}, prev), { [action.name]: authState }));
2364
2034
  if (pendingActionRef.current) {
2365
- executeAction2(pendingActionRef.current);
2035
+ executeAction(pendingActionRef.current);
2366
2036
  pendingActionRef.current = null;
2367
2037
  }
2368
2038
  }
2369
- }) : import_react18.default.createElement(import_react17.Fragment);
2039
+ }) : import_react29.default.createElement(import_react28.Fragment);
2370
2040
  }
2371
- return executeAction2(props);
2041
+ return executeAction(props);
2372
2042
  },
2373
2043
  [action, authStates_c, setAuthStates_c]
2374
2044
  );
@@ -2381,63 +2051,27 @@ function useCopilotAuthenticatedAction_c(action, dependencies) {
2381
2051
  }
2382
2052
 
2383
2053
  // src/hooks/use-langgraph-interrupt.ts
2384
- var import_react19 = require("react");
2385
- var import_shared13 = require("@copilotkit/shared");
2054
+ var import_react30 = require("react");
2055
+ var import_shared12 = require("@copilotkit/shared");
2386
2056
  function useLangGraphInterrupt(action, dependencies) {
2387
- var _a;
2388
- const {
2389
- setLangGraphInterruptAction,
2390
- removeLangGraphInterruptAction,
2391
- langGraphInterruptAction,
2392
- threadId
2393
- } = (0, import_react19.useContext)(CopilotContext);
2394
- const { runChatCompletion } = useCopilotChat();
2057
+ const { setInterruptAction, removeInterruptAction, interruptActions, threadId } = (0, import_react30.useContext)(CopilotContext);
2395
2058
  const { addToast } = useToast();
2396
- const actionId = (0, import_shared13.dataToUUID)(JSON.stringify(action), "lgAction");
2397
- const hasAction = (0, import_react19.useMemo)(
2398
- () => Boolean(langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id),
2399
- [langGraphInterruptAction]
2400
- );
2401
- const isCurrentAction = (0, import_react19.useMemo)(
2402
- () => (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) && (langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.id) === actionId,
2403
- [langGraphInterruptAction]
2404
- );
2405
- (0, import_react19.useEffect)(() => {
2406
- var _a2;
2407
- if (hasAction && isCurrentAction && ((_a2 = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a2.response)) {
2408
- runChatCompletion();
2409
- }
2410
- }, [(_a = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event) == null ? void 0 : _a.response, runChatCompletion, hasAction, isCurrentAction]);
2411
- (0, import_react19.useEffect)(() => {
2059
+ const actionId = (0, import_shared12.dataToUUID)(JSON.stringify(action), "lgAction");
2060
+ (0, import_react30.useEffect)(() => {
2412
2061
  if (!action)
2413
2062
  return;
2414
- if (hasAction && !isCurrentAction && !action.enabled) {
2415
- addToast({
2416
- type: "warning",
2417
- message: "An action is already registered for the interrupt event"
2418
- });
2419
- return;
2420
- }
2421
- if (hasAction && isCurrentAction) {
2422
- return;
2423
- }
2424
- setLangGraphInterruptAction(threadId, __spreadProps(__spreadValues({}, action), { id: actionId }));
2425
- }, [
2426
- action,
2427
- hasAction,
2428
- isCurrentAction,
2429
- setLangGraphInterruptAction,
2430
- removeLangGraphInterruptAction,
2431
- threadId,
2432
- ...dependencies || []
2433
- ]);
2063
+ setInterruptAction(threadId, __spreadProps(__spreadValues({}, action), { id: actionId }));
2064
+ return () => {
2065
+ removeInterruptAction(actionId);
2066
+ };
2067
+ }, [setInterruptAction, removeInterruptAction, threadId, actionId, ...dependencies || []]);
2434
2068
  }
2435
2069
 
2436
2070
  // src/hooks/use-copilot-additional-instructions.ts
2437
- var import_react20 = require("react");
2071
+ var import_react31 = require("react");
2438
2072
  function useCopilotAdditionalInstructions({ instructions, available = "enabled" }, dependencies) {
2439
2073
  const { setAdditionalInstructions } = useCopilotContext();
2440
- (0, import_react20.useEffect)(() => {
2074
+ (0, import_react31.useEffect)(() => {
2441
2075
  if (available === "disabled")
2442
2076
  return;
2443
2077
  setAdditionalInstructions((prevInstructions) => [...prevInstructions || [], instructions]);
@@ -2449,44 +2083,15 @@ function useCopilotAdditionalInstructions({ instructions, available = "enabled"
2449
2083
  }, [available, instructions, setAdditionalInstructions, ...dependencies || []]);
2450
2084
  }
2451
2085
 
2452
- // src/hooks/use-frontend-tool.ts
2453
- function useFrontendTool(tool, dependencies) {
2454
- useCopilotAction(tool, dependencies);
2455
- }
2456
-
2457
- // src/hooks/use-human-in-the-loop.ts
2458
- function useHumanInTheLoop(tool, dependencies) {
2459
- const _a = tool, { render } = _a, toolRest = __objRest(_a, ["render"]);
2460
- useCopilotAction(
2461
- __spreadProps(__spreadValues({}, toolRest), {
2462
- available: tool.available === "disabled" ? tool.available : "remote",
2463
- renderAndWaitForResponse: render
2464
- }),
2465
- dependencies
2466
- );
2467
- }
2468
-
2469
- // src/hooks/use-render-tool-call.ts
2470
- function useRenderToolCall(tool, dependencies) {
2471
- useCopilotAction(
2472
- __spreadProps(__spreadValues({}, tool), {
2473
- available: tool.available === "disabled" ? tool.available : "frontend"
2474
- }),
2475
- dependencies
2476
- );
2477
- }
2478
-
2479
2086
  // src/hooks/use-default-tool.ts
2480
2087
  function useDefaultTool(tool, dependencies) {
2481
2088
  useCopilotAction(__spreadProps(__spreadValues({}, tool), { name: "*" }), dependencies);
2482
2089
  }
2483
2090
  // Annotate the CommonJS export names for ESM import in node:
2484
2091
  0 && (module.exports = {
2485
- runAgent,
2486
- startAgent,
2487
- stopAgent,
2488
2092
  useCoAgent,
2489
2093
  useCoAgentStateRender,
2094
+ useConfigureChatSuggestions,
2490
2095
  useCopilotAction,
2491
2096
  useCopilotAdditionalInstructions,
2492
2097
  useCopilotAuthenticatedAction_c,
@@ -2500,6 +2105,7 @@ function useDefaultTool(tool, dependencies) {
2500
2105
  useHumanInTheLoop,
2501
2106
  useLangGraphInterrupt,
2502
2107
  useLangGraphInterruptRender,
2108
+ useLazyToolRenderer,
2503
2109
  useMakeCopilotDocumentReadable,
2504
2110
  useRenderToolCall
2505
2111
  });