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

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