@copilotkit/react-core 1.10.6 → 1.50.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (333) hide show
  1. package/dist/chunk-24SCZAB4.mjs +143 -0
  2. package/dist/chunk-24SCZAB4.mjs.map +1 -0
  3. package/dist/chunk-36KQV2NA.mjs +1 -0
  4. package/dist/{chunk-U7QULEVO.mjs → chunk-3GURHDG7.mjs} +3 -3
  5. package/dist/{chunk-4BHIQMN6.mjs → chunk-3R423LZT.mjs} +6 -5
  6. package/dist/{chunk-4BHIQMN6.mjs.map → chunk-3R423LZT.mjs.map} +1 -1
  7. package/dist/chunk-5X5DJRQQ.mjs +71 -0
  8. package/dist/chunk-5X5DJRQQ.mjs.map +1 -0
  9. package/dist/{chunk-N4WEHORG.mjs → chunk-6PUNP7CD.mjs} +4 -4
  10. package/dist/chunk-6PUNP7CD.mjs.map +1 -0
  11. package/dist/chunk-7BYHZLPL.mjs +32 -0
  12. package/dist/chunk-7BYHZLPL.mjs.map +1 -0
  13. package/dist/chunk-7DTB7S5V.mjs +83 -0
  14. package/dist/chunk-7DTB7S5V.mjs.map +1 -0
  15. package/dist/chunk-A6NKSGH3.mjs +1 -0
  16. package/dist/{chunk-GT5WI3AF.mjs → chunk-BR5YEYZJ.mjs} +7 -9
  17. package/dist/chunk-BR5YEYZJ.mjs.map +1 -0
  18. package/dist/chunk-CB7CRBDG.mjs +48 -0
  19. package/dist/chunk-CB7CRBDG.mjs.map +1 -0
  20. package/dist/chunk-CYDWEPFL.mjs +1 -0
  21. package/dist/{chunk-BBUQMG45.mjs → chunk-D3QSYDJR.mjs} +3 -3
  22. package/dist/{chunk-BBUQMG45.mjs.map → chunk-D3QSYDJR.mjs.map} +1 -1
  23. package/dist/chunk-DCHSCK62.mjs +549 -0
  24. package/dist/chunk-DCHSCK62.mjs.map +1 -0
  25. package/dist/{chunk-ZLQVRPDS.mjs → chunk-DMLQZG75.mjs} +1 -1
  26. package/dist/chunk-DMLQZG75.mjs.map +1 -0
  27. package/dist/chunk-F555TVE4.mjs +33 -0
  28. package/dist/chunk-F555TVE4.mjs.map +1 -0
  29. package/dist/{chunk-C6IANC2R.mjs → chunk-FBD24VEH.mjs} +7 -43
  30. package/dist/chunk-FBD24VEH.mjs.map +1 -0
  31. package/dist/chunk-FD6FGKYY.mjs +1 -0
  32. package/dist/chunk-FDOMAPJY.mjs +59 -0
  33. package/dist/chunk-FDOMAPJY.mjs.map +1 -0
  34. package/dist/{chunk-X7MJWPI7.mjs → chunk-GMI4KO4X.mjs} +8 -6
  35. package/dist/{chunk-X7MJWPI7.mjs.map → chunk-GMI4KO4X.mjs.map} +1 -1
  36. package/dist/chunk-IUSKVYUI.mjs +13 -0
  37. package/dist/chunk-IUSKVYUI.mjs.map +1 -0
  38. package/dist/chunk-JD7BAH7U.mjs +1 -0
  39. package/dist/{chunk-N5HOP3PG.mjs → chunk-JRT5BJF3.mjs} +2 -2
  40. package/dist/{chunk-N4VN2B5S.mjs → chunk-LHERIF3L.mjs} +2 -2
  41. package/dist/{chunk-DXEQPN43.mjs → chunk-LHKZJ2ND.mjs} +3 -3
  42. package/dist/chunk-NB2FKV2V.mjs +1 -0
  43. package/dist/chunk-NBK4KBLX.mjs +54 -0
  44. package/dist/chunk-NBK4KBLX.mjs.map +1 -0
  45. package/dist/chunk-NG26QEGF.mjs +46 -0
  46. package/dist/chunk-NG26QEGF.mjs.map +1 -0
  47. package/dist/chunk-NROJOTQP.mjs +163 -0
  48. package/dist/chunk-NROJOTQP.mjs.map +1 -0
  49. package/dist/{chunk-MGWRDFBE.mjs → chunk-OVYFRPSN.mjs} +2 -2
  50. package/dist/{chunk-MQYWH4E6.mjs → chunk-QU6NONOD.mjs} +2 -2
  51. package/dist/chunk-R4MR43UQ.mjs +101 -0
  52. package/dist/chunk-R4MR43UQ.mjs.map +1 -0
  53. package/dist/chunk-SPCZTZCY.mjs +1 -0
  54. package/dist/chunk-SPCZTZCY.mjs.map +1 -0
  55. package/dist/chunk-TXI72QHK.mjs +80 -0
  56. package/dist/chunk-TXI72QHK.mjs.map +1 -0
  57. package/dist/chunk-UJBV5GAG.mjs +767 -0
  58. package/dist/chunk-UJBV5GAG.mjs.map +1 -0
  59. package/dist/{chunk-OKCYPO4I.mjs → chunk-WMJVBMUX.mjs} +3 -3
  60. package/dist/{chunk-EUX2P2E7.mjs → chunk-WVLHXIFP.mjs} +11 -9
  61. package/dist/chunk-WVLHXIFP.mjs.map +1 -0
  62. package/dist/{chunk-5FHSUKQL.mjs → chunk-YYN33GSG.mjs} +5 -2
  63. package/dist/chunk-YYN33GSG.mjs.map +1 -0
  64. package/dist/chunk-ZVF5Q6IH.mjs +29 -0
  65. package/dist/chunk-ZVF5Q6IH.mjs.map +1 -0
  66. package/dist/components/CopilotListeners.d.ts +3 -0
  67. package/dist/components/CopilotListeners.js +234 -0
  68. package/dist/components/CopilotListeners.js.map +1 -0
  69. package/dist/components/CopilotListeners.mjs +14 -0
  70. package/dist/components/CopilotListeners.mjs.map +1 -0
  71. package/dist/components/copilot-provider/copilot-messages.js +14 -48
  72. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  73. package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
  74. package/dist/components/copilot-provider/copilotkit-props.d.ts +9 -2
  75. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  76. package/dist/components/copilot-provider/copilotkit.d.ts +2 -1
  77. package/dist/components/copilot-provider/copilotkit.js +528 -370
  78. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  79. package/dist/components/copilot-provider/copilotkit.mjs +17 -12
  80. package/dist/components/copilot-provider/index.d.ts +2 -1
  81. package/dist/components/copilot-provider/index.js +528 -370
  82. package/dist/components/copilot-provider/index.js.map +1 -1
  83. package/dist/components/copilot-provider/index.mjs +18 -12
  84. package/dist/components/dev-console/console-trigger.js +10 -8
  85. package/dist/components/dev-console/console-trigger.js.map +1 -1
  86. package/dist/components/dev-console/console-trigger.mjs +4 -4
  87. package/dist/components/dev-console/developer-console-modal.js +10 -8
  88. package/dist/components/dev-console/developer-console-modal.js.map +1 -1
  89. package/dist/components/dev-console/developer-console-modal.mjs +3 -3
  90. package/dist/components/error-boundary/error-boundary.d.ts +7 -7
  91. package/dist/components/error-boundary/error-boundary.js +3 -3
  92. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  93. package/dist/components/error-boundary/error-boundary.mjs +2 -2
  94. package/dist/components/error-boundary/error-utils.d.ts +1 -1
  95. package/dist/components/error-boundary/error-utils.js +3 -3
  96. package/dist/components/error-boundary/error-utils.js.map +1 -1
  97. package/dist/components/error-boundary/error-utils.mjs +1 -1
  98. package/dist/components/index.d.ts +2 -1
  99. package/dist/components/index.js +528 -370
  100. package/dist/components/index.js.map +1 -1
  101. package/dist/components/index.mjs +19 -12
  102. package/dist/components/toast/exclamation-mark-icon.d.ts +2 -2
  103. package/dist/components/toast/toast-provider.d.ts +3 -3
  104. package/dist/components/usage-banner.d.ts +2 -2
  105. package/dist/context/coagent-state-renders-context.d.ts +24 -0
  106. package/dist/context/coagent-state-renders-context.js +91 -0
  107. package/dist/context/coagent-state-renders-context.js.map +1 -0
  108. package/dist/context/coagent-state-renders-context.mjs +12 -0
  109. package/dist/context/coagent-state-renders-context.mjs.map +1 -0
  110. package/dist/context/copilot-context.d.ts +1 -1
  111. package/dist/context/copilot-context.js +10 -8
  112. package/dist/context/copilot-context.js.map +1 -1
  113. package/dist/context/copilot-context.mjs +1 -1
  114. package/dist/context/copilot-messages-context.d.ts +18 -11
  115. package/dist/context/copilot-messages-context.js.map +1 -1
  116. package/dist/context/copilot-messages-context.mjs +1 -1
  117. package/dist/context/index.d.ts +6 -2
  118. package/dist/context/index.js +110 -10
  119. package/dist/context/index.js.map +1 -1
  120. package/dist/context/index.mjs +20 -4
  121. package/dist/context/threads-context.d.ts +16 -0
  122. package/dist/context/threads-context.js +59 -0
  123. package/dist/context/threads-context.js.map +1 -0
  124. package/dist/context/threads-context.mjs +12 -0
  125. package/dist/context/threads-context.mjs.map +1 -0
  126. package/dist/{copilot-context-cf9de848.d.ts → copilot-context-1cd70a3f.d.ts} +36 -32
  127. package/dist/hooks/index.d.ts +9 -6
  128. package/dist/hooks/index.js +1445 -1839
  129. package/dist/hooks/index.js.map +1 -1
  130. package/dist/hooks/index.mjs +47 -56
  131. package/dist/hooks/use-coagent-state-render-bridge.d.ts +100 -0
  132. package/dist/hooks/use-coagent-state-render-bridge.js +211 -0
  133. package/dist/hooks/use-coagent-state-render-bridge.js.map +1 -0
  134. package/dist/hooks/use-coagent-state-render-bridge.mjs +15 -0
  135. package/dist/hooks/use-coagent-state-render-bridge.mjs.map +1 -0
  136. package/dist/hooks/use-coagent-state-render.js +31 -20
  137. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  138. package/dist/hooks/use-coagent-state-render.mjs +3 -2
  139. package/dist/hooks/use-coagent.d.ts +2 -14
  140. package/dist/hooks/use-coagent.js +109 -1906
  141. package/dist/hooks/use-coagent.js.map +1 -1
  142. package/dist/hooks/use-coagent.mjs +1 -30
  143. package/dist/hooks/use-configure-chat-suggestions.d.ts +36 -0
  144. package/dist/hooks/use-configure-chat-suggestions.js +210 -0
  145. package/dist/hooks/use-configure-chat-suggestions.js.map +1 -0
  146. package/dist/hooks/use-configure-chat-suggestions.mjs +13 -0
  147. package/dist/hooks/use-configure-chat-suggestions.mjs.map +1 -0
  148. package/dist/hooks/use-copilot-action.d.ts +8 -45
  149. package/dist/hooks/use-copilot-action.js +207 -349
  150. package/dist/hooks/use-copilot-action.js.map +1 -1
  151. package/dist/hooks/use-copilot-action.mjs +4 -5
  152. package/dist/hooks/use-copilot-additional-instructions.js +10 -8
  153. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  154. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  155. package/dist/hooks/use-copilot-authenticated-action.js +224 -248
  156. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  157. package/dist/hooks/use-copilot-authenticated-action.mjs +6 -6
  158. package/dist/hooks/use-copilot-chat-headless_c.d.ts +2 -10
  159. package/dist/hooks/use-copilot-chat-headless_c.js +973 -1369
  160. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  161. package/dist/hooks/use-copilot-chat-headless_c.mjs +12 -22
  162. package/dist/hooks/use-copilot-chat.d.ts +2 -10
  163. package/dist/hooks/use-copilot-chat.js +967 -1388
  164. package/dist/hooks/use-copilot-chat.js.map +1 -1
  165. package/dist/hooks/use-copilot-chat.mjs +12 -22
  166. package/dist/hooks/use-copilot-chat_internal.d.ts +38 -14
  167. package/dist/hooks/use-copilot-chat_internal.js +965 -1362
  168. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  169. package/dist/hooks/use-copilot-chat_internal.mjs +13 -23
  170. package/dist/hooks/use-copilot-readable.d.ts +1 -1
  171. package/dist/hooks/use-copilot-readable.js +6 -157
  172. package/dist/hooks/use-copilot-readable.js.map +1 -1
  173. package/dist/hooks/use-copilot-readable.mjs +1 -2
  174. package/dist/hooks/use-default-tool.js +204 -349
  175. package/dist/hooks/use-default-tool.js.map +1 -1
  176. package/dist/hooks/use-default-tool.mjs +5 -6
  177. package/dist/hooks/use-flat-category-store.js +4 -1
  178. package/dist/hooks/use-flat-category-store.js.map +1 -1
  179. package/dist/hooks/use-flat-category-store.mjs +1 -1
  180. package/dist/hooks/use-frontend-tool.d.ts +3 -3
  181. package/dist/hooks/use-frontend-tool.js +30 -370
  182. package/dist/hooks/use-frontend-tool.js.map +1 -1
  183. package/dist/hooks/use-frontend-tool.mjs +1 -6
  184. package/dist/hooks/use-human-in-the-loop.d.ts +4 -3
  185. package/dist/hooks/use-human-in-the-loop.js +61 -393
  186. package/dist/hooks/use-human-in-the-loop.js.map +1 -1
  187. package/dist/hooks/use-human-in-the-loop.mjs +1 -6
  188. package/dist/hooks/use-langgraph-interrupt-render.d.ts +3 -2
  189. package/dist/hooks/use-langgraph-interrupt-render.js +92 -36
  190. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  191. package/dist/hooks/use-langgraph-interrupt-render.mjs +6 -4
  192. package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
  193. package/dist/hooks/use-langgraph-interrupt.js +24 -1642
  194. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  195. package/dist/hooks/use-langgraph-interrupt.mjs +2 -23
  196. package/dist/hooks/use-lazy-tool-renderer.d.ts +6 -0
  197. package/dist/hooks/use-lazy-tool-renderer.js +53 -0
  198. package/dist/hooks/use-lazy-tool-renderer.js.map +1 -0
  199. package/dist/hooks/use-lazy-tool-renderer.mjs +8 -0
  200. package/dist/hooks/use-lazy-tool-renderer.mjs.map +1 -0
  201. package/dist/hooks/use-make-copilot-document-readable.js +11 -9
  202. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  203. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  204. package/dist/hooks/use-render-tool-call.d.ts +7 -6
  205. package/dist/hooks/use-render-tool-call.js +36 -386
  206. package/dist/hooks/use-render-tool-call.js.map +1 -1
  207. package/dist/hooks/use-render-tool-call.mjs +1 -6
  208. package/dist/index.d.ts +11 -6
  209. package/dist/index.js +1841 -2056
  210. package/dist/index.js.map +1 -1
  211. package/dist/index.mjs +82 -63
  212. package/dist/lib/copilot-task.d.ts +1 -1
  213. package/dist/lib/copilot-task.js +1 -0
  214. package/dist/lib/copilot-task.js.map +1 -1
  215. package/dist/lib/copilot-task.mjs +20 -13
  216. package/dist/lib/index.d.ts +1 -1
  217. package/dist/lib/index.js +1 -0
  218. package/dist/lib/index.js.map +1 -1
  219. package/dist/lib/index.mjs +20 -13
  220. package/dist/setupTests.d.ts +2 -2
  221. package/dist/types/frontend-action.d.ts +5 -5
  222. package/dist/types/index.d.ts +4 -0
  223. package/dist/types/index.js.map +1 -1
  224. package/dist/types/index.mjs +2 -1
  225. package/dist/types/interrupt-action.d.ts +1 -1
  226. package/dist/types/interrupt-action.js.map +1 -1
  227. package/dist/types/interrupt-action.mjs +1 -0
  228. package/dist/utils/index.d.ts +0 -12
  229. package/dist/utils/index.js +6 -325
  230. package/dist/utils/index.js.map +1 -1
  231. package/dist/utils/index.mjs +3 -23
  232. package/dist/utils/utils.js.map +1 -1
  233. package/dist/v2/index.d.ts +2 -0
  234. package/dist/v2/index.js +27 -0
  235. package/dist/v2/index.js.map +1 -0
  236. package/dist/v2/index.mjs +4 -0
  237. package/dist/v2/index.mjs.map +1 -0
  238. package/package.json +34 -23
  239. package/src/components/CopilotListeners.tsx +82 -0
  240. package/src/components/copilot-provider/copilot-messages.tsx +46 -47
  241. package/src/components/copilot-provider/copilotkit-props.tsx +8 -1
  242. package/src/components/copilot-provider/copilotkit.tsx +177 -144
  243. package/src/components/error-boundary/error-utils.tsx +3 -3
  244. package/src/context/coagent-state-renders-context.tsx +76 -0
  245. package/src/context/copilot-context.tsx +21 -21
  246. package/src/context/copilot-messages-context.tsx +3 -3
  247. package/src/context/index.ts +8 -0
  248. package/src/context/threads-context.tsx +41 -0
  249. package/src/hooks/index.ts +7 -3
  250. package/src/hooks/use-coagent-state-render-bridge.tsx +293 -0
  251. package/src/hooks/use-coagent-state-render.ts +4 -7
  252. package/src/hooks/use-coagent.ts +129 -249
  253. package/src/hooks/use-configure-chat-suggestions.tsx +85 -0
  254. package/src/hooks/use-copilot-action.ts +88 -199
  255. package/src/hooks/use-copilot-chat-headless_c.ts +2 -1
  256. package/src/hooks/use-copilot-chat.ts +4 -1
  257. package/src/hooks/use-copilot-chat_internal.ts +349 -258
  258. package/src/hooks/use-copilot-readable.ts +6 -26
  259. package/src/hooks/use-flat-category-store.ts +4 -3
  260. package/src/hooks/use-frontend-tool.ts +67 -8
  261. package/src/hooks/use-human-in-the-loop.ts +111 -13
  262. package/src/hooks/use-langgraph-interrupt-render.ts +90 -40
  263. package/src/hooks/use-langgraph-interrupt.ts +18 -47
  264. package/src/hooks/use-lazy-tool-renderer.tsx +30 -0
  265. package/src/hooks/use-make-copilot-document-readable.ts +1 -1
  266. package/src/hooks/use-render-tool-call.ts +73 -13
  267. package/src/types/index.ts +1 -0
  268. package/src/types/interrupt-action.ts +8 -4
  269. package/src/utils/index.ts +0 -3
  270. package/src/utils/utils.ts +7 -0
  271. package/src/v2/index.ts +2 -0
  272. package/src/v2/styles.css +1 -0
  273. package/tsup.config.ts +1 -1
  274. package/dist/chunk-5FHSUKQL.mjs.map +0 -1
  275. package/dist/chunk-6GPVUMBU.mjs +0 -13
  276. package/dist/chunk-6GPVUMBU.mjs.map +0 -1
  277. package/dist/chunk-AKR2SSUJ.mjs +0 -22
  278. package/dist/chunk-AKR2SSUJ.mjs.map +0 -1
  279. package/dist/chunk-C6IANC2R.mjs.map +0 -1
  280. package/dist/chunk-CI4KD357.mjs +0 -804
  281. package/dist/chunk-CI4KD357.mjs.map +0 -1
  282. package/dist/chunk-DZTU6PGS.mjs +0 -1
  283. package/dist/chunk-EUX2P2E7.mjs.map +0 -1
  284. package/dist/chunk-EVVO67QO.mjs +0 -25
  285. package/dist/chunk-EVVO67QO.mjs.map +0 -1
  286. package/dist/chunk-GT5WI3AF.mjs.map +0 -1
  287. package/dist/chunk-HDOG2RTM.mjs +0 -37
  288. package/dist/chunk-HDOG2RTM.mjs.map +0 -1
  289. package/dist/chunk-N4WEHORG.mjs.map +0 -1
  290. package/dist/chunk-OT5NHMEC.mjs +0 -723
  291. package/dist/chunk-OT5NHMEC.mjs.map +0 -1
  292. package/dist/chunk-QHCLJODF.mjs +0 -332
  293. package/dist/chunk-QHCLJODF.mjs.map +0 -1
  294. package/dist/chunk-QV5SBF2S.mjs +0 -239
  295. package/dist/chunk-QV5SBF2S.mjs.map +0 -1
  296. package/dist/chunk-T3376SZS.mjs +0 -142
  297. package/dist/chunk-T3376SZS.mjs.map +0 -1
  298. package/dist/chunk-U3DQY67T.mjs +0 -71
  299. package/dist/chunk-U3DQY67T.mjs.map +0 -1
  300. package/dist/chunk-YPBKY4KY.mjs +0 -1
  301. package/dist/chunk-YPSGKPDA.mjs +0 -1
  302. package/dist/chunk-ZLQVRPDS.mjs.map +0 -1
  303. package/dist/chunk-ZVOLWJCY.mjs +0 -47
  304. package/dist/chunk-ZVOLWJCY.mjs.map +0 -1
  305. package/dist/hooks/use-chat.d.ts +0 -145
  306. package/dist/hooks/use-chat.js +0 -1129
  307. package/dist/hooks/use-chat.js.map +0 -1
  308. package/dist/hooks/use-chat.mjs +0 -14
  309. package/dist/index-1f5b66ac.d.ts +0 -36
  310. package/dist/utils/extract.d.ts +0 -43
  311. package/dist/utils/extract.js +0 -208
  312. package/dist/utils/extract.js.map +0 -1
  313. package/dist/utils/extract.mjs +0 -25
  314. package/dist/utils/suggestions.d.ts +0 -11
  315. package/dist/utils/suggestions.js +0 -343
  316. package/dist/utils/suggestions.js.map +0 -1
  317. package/dist/utils/suggestions.mjs +0 -25
  318. package/src/hooks/use-chat.ts +0 -1142
  319. package/src/utils/extract.ts +0 -215
  320. package/src/utils/suggestions.ts +0 -208
  321. /package/dist/{chunk-DZTU6PGS.mjs.map → chunk-36KQV2NA.mjs.map} +0 -0
  322. /package/dist/{chunk-U7QULEVO.mjs.map → chunk-3GURHDG7.mjs.map} +0 -0
  323. /package/dist/{chunk-YPBKY4KY.mjs.map → chunk-A6NKSGH3.mjs.map} +0 -0
  324. /package/dist/{chunk-YPSGKPDA.mjs.map → chunk-CYDWEPFL.mjs.map} +0 -0
  325. /package/dist/{hooks/use-chat.mjs.map → chunk-FD6FGKYY.mjs.map} +0 -0
  326. /package/dist/{utils/extract.mjs.map → chunk-JD7BAH7U.mjs.map} +0 -0
  327. /package/dist/{chunk-N5HOP3PG.mjs.map → chunk-JRT5BJF3.mjs.map} +0 -0
  328. /package/dist/{chunk-N4VN2B5S.mjs.map → chunk-LHERIF3L.mjs.map} +0 -0
  329. /package/dist/{chunk-DXEQPN43.mjs.map → chunk-LHKZJ2ND.mjs.map} +0 -0
  330. /package/dist/{utils/suggestions.mjs.map → chunk-NB2FKV2V.mjs.map} +0 -0
  331. /package/dist/{chunk-MGWRDFBE.mjs.map → chunk-OVYFRPSN.mjs.map} +0 -0
  332. /package/dist/{chunk-MQYWH4E6.mjs.map → chunk-QU6NONOD.mjs.map} +0 -0
  333. /package/dist/{chunk-OKCYPO4I.mjs.map → chunk-WMJVBMUX.mjs.map} +0 -0
@@ -1,12 +1,8 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
- var __defProps = Object.defineProperties;
5
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
8
5
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
- var __getProtoOf = Object.getPrototypeOf;
10
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
11
7
  var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
@@ -21,19 +17,6 @@ var __spreadValues = (a, b) => {
21
17
  }
22
18
  return a;
23
19
  };
24
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
- var __objRest = (source, exclude) => {
26
- var target = {};
27
- for (var prop in source)
28
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
- target[prop] = source[prop];
30
- if (source != null && __getOwnPropSymbols)
31
- for (var prop of __getOwnPropSymbols(source)) {
32
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
- target[prop] = source[prop];
34
- }
35
- return target;
36
- };
37
20
  var __export = (target, all) => {
38
21
  for (var name in all)
39
22
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -46,14 +29,6 @@ var __copyProps = (to, from, except, desc) => {
46
29
  }
47
30
  return to;
48
31
  };
49
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
- // If the importer is in node compatibility mode or this is not an ESM
51
- // file that has been converted to a CommonJS file using a Babel-
52
- // compatible transform (i.e. "__esModule" has not been set), then set
53
- // "default" to the CommonJS "module.exports" for node compatibility.
54
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
- mod
56
- ));
57
32
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
33
  var __async = (__this, __arguments, generator) => {
59
34
  return new Promise((resolve, reject) => {
@@ -79,1915 +54,143 @@ var __async = (__this, __arguments, generator) => {
79
54
  // src/hooks/use-coagent.ts
80
55
  var use_coagent_exports = {};
81
56
  __export(use_coagent_exports, {
82
- runAgent: () => runAgent,
83
- startAgent: () => startAgent,
84
- stopAgent: () => stopAgent,
85
57
  useCoAgent: () => useCoAgent
86
58
  });
87
59
  module.exports = __toCommonJS(use_coagent_exports);
88
- var import_react11 = require("react");
89
-
90
- // src/context/copilot-context.tsx
91
- var import_react = __toESM(require("react"));
92
- var emptyCopilotContext = {
93
- actions: {},
94
- setAction: () => {
95
- },
96
- removeAction: () => {
97
- },
98
- coAgentStateRenders: {},
99
- setCoAgentStateRender: () => {
100
- },
101
- removeCoAgentStateRender: () => {
102
- },
103
- chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },
104
- getContextString: (documents, categories) => returnAndThrowInDebug(""),
105
- addContext: () => "",
106
- removeContext: () => {
107
- },
108
- getAllContext: () => [],
109
- getFunctionCallHandler: () => returnAndThrowInDebug(() => __async(void 0, null, function* () {
110
- })),
111
- isLoading: false,
112
- setIsLoading: () => returnAndThrowInDebug(false),
113
- chatInstructions: "",
114
- setChatInstructions: () => returnAndThrowInDebug(""),
115
- additionalInstructions: [],
116
- setAdditionalInstructions: () => returnAndThrowInDebug([]),
117
- getDocumentsContext: (categories) => returnAndThrowInDebug([]),
118
- addDocumentContext: () => returnAndThrowInDebug(""),
119
- removeDocumentContext: () => {
120
- },
121
- runtimeClient: {},
122
- copilotApiConfig: new class {
123
- get chatApiEndpoint() {
124
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
125
- }
126
- get headers() {
127
- return {};
128
- }
129
- get body() {
130
- return {};
131
- }
132
- }(),
133
- chatSuggestionConfiguration: {},
134
- addChatSuggestionConfiguration: () => {
135
- },
136
- removeChatSuggestionConfiguration: () => {
137
- },
138
- showDevConsole: false,
139
- coagentStates: {},
140
- setCoagentStates: () => {
141
- },
142
- coagentStatesRef: { current: {} },
143
- setCoagentStatesWithRef: () => {
144
- },
145
- agentSession: null,
146
- setAgentSession: () => {
147
- },
148
- forwardedParameters: {},
149
- agentLock: null,
150
- threadId: "",
151
- setThreadId: () => {
152
- },
153
- runId: null,
154
- setRunId: () => {
155
- },
156
- chatAbortControllerRef: { current: null },
157
- availableAgents: [],
158
- extensions: {},
159
- setExtensions: () => {
160
- },
161
- langGraphInterruptAction: null,
162
- setLangGraphInterruptAction: () => {
163
- },
164
- removeLangGraphInterruptAction: () => {
165
- },
166
- onError: () => {
167
- },
168
- bannerError: null,
169
- setBannerError: () => {
170
- },
171
- internalErrorHandlers: {},
172
- setInternalErrorHandler: () => {
173
- },
174
- removeInternalErrorHandler: () => {
175
- }
176
- };
177
- var CopilotContext = import_react.default.createContext(emptyCopilotContext);
178
- function useCopilotContext() {
179
- const context = import_react.default.useContext(CopilotContext);
180
- if (context === emptyCopilotContext) {
181
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
182
- }
183
- return context;
184
- }
185
- function returnAndThrowInDebug(_value) {
186
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
187
- }
188
-
189
- // src/context/copilot-messages-context.tsx
190
- var import_react2 = __toESM(require("react"));
191
- var emptyCopilotContext2 = {
192
- messages: [],
193
- setMessages: () => [],
194
- // suggestions state
195
- suggestions: [],
196
- setSuggestions: () => []
197
- };
198
- var CopilotMessagesContext = import_react2.default.createContext(emptyCopilotContext2);
199
- function useCopilotMessagesContext() {
200
- const context = import_react2.default.useContext(CopilotMessagesContext);
201
- if (context === emptyCopilotContext2) {
202
- throw new Error(
203
- "A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`"
204
- );
205
- }
206
- return context;
207
- }
208
-
209
- // src/hooks/use-copilot-chat_internal.ts
210
- var import_react10 = require("react");
211
-
212
- // src/hooks/use-chat.ts
213
- var import_react6 = require("react");
214
- var import_react_dom = require("react-dom");
215
- var import_shared4 = require("@copilotkit/shared");
216
- var import_runtime_client_gql3 = require("@copilotkit/runtime-client-gql");
217
-
218
- // src/types/frontend-action.ts
219
- var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
220
- var import_shared = require("@copilotkit/shared");
221
- function processActionsForRuntimeRequest(actions) {
222
- const filteredActions = actions.filter(
223
- (action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
224
- ).map((action) => {
225
- let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
226
- if (action.disabled) {
227
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
228
- } else if (action.available === "disabled") {
229
- available = import_runtime_client_gql.ActionInputAvailability.Disabled;
230
- } else if (action.available === "remote") {
231
- available = import_runtime_client_gql.ActionInputAvailability.Remote;
232
- }
233
- return {
234
- name: action.name,
235
- description: action.description || "",
236
- jsonSchema: JSON.stringify((0, import_shared.actionParametersToJsonSchema)(action.parameters || [])),
237
- available
238
- };
239
- });
240
- return filteredActions;
241
- }
242
-
243
- // src/hooks/use-copilot-runtime-client.ts
244
- var import_runtime_client_gql2 = require("@copilotkit/runtime-client-gql");
245
-
246
- // src/components/toast/toast-provider.tsx
247
- var import_react3 = require("react");
248
- var import_shared2 = require("@copilotkit/shared");
249
- var import_jsx_runtime = require("react/jsx-runtime");
250
- var ToastContext = (0, import_react3.createContext)(void 0);
251
- function useToast() {
252
- const context = (0, import_react3.useContext)(ToastContext);
253
- if (!context) {
254
- throw new Error("useToast must be used within a ToastProvider");
255
- }
256
- return context;
257
- }
258
-
259
- // src/hooks/use-copilot-runtime-client.ts
260
- var import_react4 = require("react");
261
- var import_shared3 = require("@copilotkit/shared");
262
- var useCopilotRuntimeClient = (options) => {
263
- const { setBannerError } = useToast();
264
- const _a = options, { showDevConsole, onError } = _a, runtimeOptions = __objRest(_a, ["showDevConsole", "onError"]);
265
- const lastStructuredErrorRef = (0, import_react4.useRef)(null);
266
- const traceUIError = (error, originalError) => __async(void 0, null, function* () {
267
- try {
268
- const errorEvent = {
269
- type: "error",
270
- timestamp: Date.now(),
271
- context: {
272
- source: "ui",
273
- request: {
274
- operation: "runtimeClient",
275
- url: runtimeOptions.url,
276
- startTime: Date.now()
277
- },
278
- technical: {
279
- environment: "browser",
280
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
281
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
282
- }
283
- },
284
- error
285
- };
286
- yield onError(errorEvent);
287
- } catch (error2) {
288
- console.error("Error in onError handler:", error2);
289
- }
290
- });
291
- const runtimeClient = (0, import_react4.useMemo)(() => {
292
- return new import_runtime_client_gql2.CopilotRuntimeClient(__spreadProps(__spreadValues({}, runtimeOptions), {
293
- handleGQLErrors: (error) => {
294
- var _a2;
295
- if ((_a2 = error.graphQLErrors) == null ? void 0 : _a2.length) {
296
- const graphQLErrors = error.graphQLErrors;
297
- const routeError = (gqlError) => {
298
- const extensions = gqlError.extensions;
299
- const visibility = extensions == null ? void 0 : extensions.visibility;
300
- if (visibility === import_shared3.ErrorVisibility.SILENT) {
301
- console.error("CopilotKit Silent Error:", gqlError.message);
302
- return;
303
- }
304
- const now = Date.now();
305
- const errorMessage = gqlError.message;
306
- if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) {
307
- return;
308
- }
309
- lastStructuredErrorRef.current = { message: errorMessage, timestamp: now };
310
- const ckError = createStructuredError(gqlError);
311
- if (ckError) {
312
- setBannerError(ckError);
313
- traceUIError(ckError, gqlError);
314
- } else {
315
- const fallbackError = new import_shared3.CopilotKitError({
316
- message: gqlError.message,
317
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
318
- });
319
- setBannerError(fallbackError);
320
- traceUIError(fallbackError, gqlError);
321
- }
322
- };
323
- graphQLErrors.forEach(routeError);
324
- } else {
325
- const fallbackError = new import_shared3.CopilotKitError({
326
- message: (error == null ? void 0 : error.message) || String(error),
327
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
328
- });
329
- setBannerError(fallbackError);
330
- traceUIError(fallbackError, error);
331
- }
332
- },
333
- handleGQLWarning: (message) => {
334
- console.warn(message);
335
- const warningError = new import_shared3.CopilotKitError({
336
- message,
337
- code: import_shared3.CopilotKitErrorCode.UNKNOWN
338
- });
339
- setBannerError(warningError);
60
+ var import_react = require("react");
61
+ var import_react2 = require("@copilotkitnext/react");
62
+ function useCoAgent(options) {
63
+ const { agent } = (0, import_react2.useAgent)({ agentId: options.name });
64
+ const nodeNameRef = (0, import_react.useRef)("start");
65
+ const handleStateUpdate = (0, import_react.useCallback)(
66
+ (newState) => {
67
+ if (!agent)
68
+ return;
69
+ if (typeof newState === "function") {
70
+ const updater = newState;
71
+ agent.setState(updater(agent.state));
72
+ } else {
73
+ agent.setState(__spreadValues(__spreadValues({}, agent.state), newState));
340
74
  }
341
- }));
342
- }, [runtimeOptions, setBannerError, onError]);
343
- return runtimeClient;
344
- };
345
- function createStructuredError(gqlError) {
346
- var _a, _b, _c;
347
- const extensions = gqlError.extensions;
348
- const originalError = extensions == null ? void 0 : extensions.originalError;
349
- const message = (originalError == null ? void 0 : originalError.message) || gqlError.message;
350
- const code = extensions == null ? void 0 : extensions.code;
351
- if (code) {
352
- return new import_shared3.CopilotKitError({ message, code });
353
- }
354
- if ((_a = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _a.includes("CopilotApiDiscoveryError")) {
355
- return new import_shared3.CopilotKitApiDiscoveryError({ message });
356
- }
357
- if ((_b = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _b.includes("CopilotKitRemoteEndpointDiscoveryError")) {
358
- return new import_shared3.CopilotKitRemoteEndpointDiscoveryError({ message });
359
- }
360
- if ((_c = originalError == null ? void 0 : originalError.stack) == null ? void 0 : _c.includes("CopilotKitAgentDiscoveryError")) {
361
- return new import_shared3.CopilotKitAgentDiscoveryError({
362
- agentName: "",
363
- availableAgents: []
364
- });
365
- }
366
- return null;
367
- }
368
-
369
- // src/components/error-boundary/error-utils.tsx
370
- var import_react5 = require("react");
371
-
372
- // src/components/toast/exclamation-mark-icon.tsx
373
- var import_jsx_runtime2 = require("react/jsx-runtime");
374
- var ExclamationMarkIcon = ({
375
- className,
376
- style
377
- }) => /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
378
- "svg",
379
- {
380
- xmlns: "http://www.w3.org/2000/svg",
381
- width: "24",
382
- height: "24",
383
- viewBox: "0 0 24 24",
384
- fill: "none",
385
- stroke: "currentColor",
386
- strokeWidth: "2",
387
- strokeLinecap: "round",
388
- strokeLinejoin: "round",
389
- className: `lucide lucide-circle-alert ${className ? className : ""}`,
390
- style,
391
- children: [
392
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("circle", { cx: "12", cy: "12", r: "10" }),
393
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
394
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
395
- ]
396
- }
397
- );
398
-
399
- // src/components/error-boundary/error-utils.tsx
400
- var import_react_markdown = __toESM(require("react-markdown"));
401
- var import_jsx_runtime3 = require("react/jsx-runtime");
402
- function ErrorToast({ errors }) {
403
- const errorsToRender = errors.map((error, idx) => {
404
- var _a, _b, _c;
405
- const originalError = "extensions" in error ? (_a = error.extensions) == null ? void 0 : _a.originalError : {};
406
- const message = (_b = originalError == null ? void 0 : originalError.message) != null ? _b : error.message;
407
- const code = "extensions" in error ? (_c = error.extensions) == null ? void 0 : _c.code : null;
408
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
409
- "div",
410
- {
411
- style: {
412
- marginTop: idx === 0 ? 0 : 10,
413
- marginBottom: 14
414
- },
415
- children: [
416
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
417
- code && /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
418
- "div",
419
- {
420
- style: {
421
- fontWeight: "600",
422
- marginBottom: 4
423
- },
424
- children: [
425
- "Copilot Runtime Error:",
426
- " ",
427
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: { fontFamily: "monospace", fontWeight: "normal" }, children: code })
428
- ]
429
- }
430
- ),
431
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react_markdown.default, { children: message })
432
- ]
433
- },
434
- idx
435
- );
436
- });
437
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
438
- "div",
439
- {
440
- style: {
441
- fontSize: "13px",
442
- maxWidth: "600px"
443
- },
444
- children: [
445
- errorsToRender,
446
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("div", { style: { fontSize: "11px", opacity: 0.75 }, children: "NOTE: This error only displays during local development." })
447
- ]
448
- }
449
- );
450
- }
451
- function useErrorToast() {
452
- const { addToast } = useToast();
453
- return (0, import_react5.useCallback)(
454
- (error) => {
455
- const errorId = error.map((err) => {
456
- var _a, _b;
457
- const message = "extensions" in err ? ((_b = (_a = err.extensions) == null ? void 0 : _a.originalError) == null ? void 0 : _b.message) || err.message : err.message;
458
- const stack = err.stack || "";
459
- return btoa(message + stack).slice(0, 32);
460
- }).join("|");
461
- addToast({
462
- type: "error",
463
- id: errorId,
464
- // Toast libraries typically dedupe by id
465
- message: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ErrorToast, { errors: error })
466
- });
467
75
  },
468
- [addToast]
76
+ [agent == null ? void 0 : agent.state, agent == null ? void 0 : agent.setState]
469
77
  );
470
- }
471
- function useAsyncCallback(callback, deps) {
472
- const addErrorToast = useErrorToast();
473
- return (0, import_react5.useCallback)((...args) => __async(this, null, function* () {
474
- try {
475
- return yield callback(...args);
476
- } catch (error) {
477
- console.error("Error in async callback:", error);
478
- addErrorToast([error]);
479
- throw error;
78
+ const externalStateStr = (0, import_react.useMemo)(
79
+ () => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
80
+ [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]
81
+ );
82
+ (0, import_react.useEffect)(() => {
83
+ if ((agent == null ? void 0 : agent.state) && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) {
84
+ handleStateUpdate(options.state);
480
85
  }
481
- }), deps);
482
- }
483
-
484
- // src/hooks/use-chat.ts
485
- function useChat(options) {
486
- const {
487
- messages,
488
- setMessages,
489
- makeSystemMessageCallback,
490
- copilotConfig,
491
- setIsLoading,
492
- initialMessages,
493
- isLoading,
494
- actions,
495
- onFunctionCall,
496
- onCoAgentStateRender,
497
- setCoagentStatesWithRef,
498
- coagentStatesRef,
499
- agentSession,
500
- setAgentSession,
501
- threadId,
502
- setThreadId,
503
- runId,
504
- setRunId,
505
- chatAbortControllerRef,
506
- agentLock,
507
- extensions,
508
- setExtensions,
509
- langGraphInterruptAction,
510
- setLangGraphInterruptAction,
511
- disableSystemMessage = false
512
- } = options;
513
- const runChatCompletionRef = (0, import_react6.useRef)();
514
- const addErrorToast = useErrorToast();
515
- const { setBannerError } = useToast();
516
- const { onError, showDevConsole, getAllContext } = useCopilotContext();
517
- const copilotReadableContext = getAllContext();
518
- const context = (0, import_react6.useMemo)(
519
- () => copilotReadableContext.map((contextItem) => {
520
- const [description, ...valueParts] = contextItem.value.split(":");
521
- return {
522
- description: description.trim(),
523
- value: valueParts.join(":").trim()
524
- };
525
- }),
526
- [copilotReadableContext]
86
+ }, [agent, externalStateStr, handleStateUpdate]);
87
+ const hasStateValues = (0, import_react.useCallback)((value) => {
88
+ return Boolean(value && Object.keys(value).length);
89
+ }, []);
90
+ const initialStateRef = (0, import_react.useRef)(
91
+ isExternalStateManagement(options) ? options.state : "initialState" in options ? options.initialState : void 0
527
92
  );
528
- const traceUIError = (error, originalError) => __async(this, null, function* () {
529
- try {
530
- const traceEvent = {
531
- type: "error",
532
- timestamp: Date.now(),
533
- context: {
534
- source: "ui",
535
- request: {
536
- operation: "useChatCompletion",
537
- url: copilotConfig.chatApiEndpoint,
538
- startTime: Date.now()
539
- },
540
- technical: {
541
- environment: "browser",
542
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
543
- stackTrace: originalError instanceof Error ? originalError.stack : void 0
544
- }
545
- },
546
- error
547
- };
548
- yield onError(traceEvent);
549
- } catch (traceError) {
550
- console.error("Error in use-chat onError handler:", traceError);
93
+ (0, import_react.useEffect)(() => {
94
+ if (isExternalStateManagement(options)) {
95
+ initialStateRef.current = options.state;
96
+ } else if ("initialState" in options) {
97
+ initialStateRef.current = options.initialState;
551
98
  }
552
- });
553
- const agentSessionRef = (0, import_react6.useRef)(agentSession);
554
- agentSessionRef.current = agentSession;
555
- const runIdRef = (0, import_react6.useRef)(runId);
556
- runIdRef.current = runId;
557
- const extensionsRef = (0, import_react6.useRef)(extensions);
558
- extensionsRef.current = extensions;
559
- const publicApiKey = copilotConfig.publicApiKey;
560
- const headers = __spreadValues(__spreadValues({}, copilotConfig.headers || {}), publicApiKey ? { [import_shared4.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey } : {});
561
- const runtimeClient = useCopilotRuntimeClient({
562
- url: copilotConfig.chatApiEndpoint,
563
- publicApiKey: copilotConfig.publicApiKey,
564
- headers,
565
- credentials: copilotConfig.credentials,
566
- showDevConsole,
567
- onError
568
- });
569
- const pendingAppendsRef = (0, import_react6.useRef)([]);
570
- const runChatCompletion = useAsyncCallback(
571
- (previousMessages) => __async(this, null, function* () {
572
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
573
- setIsLoading(true);
574
- const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
575
- 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) {
576
- addErrorToast([
577
- new Error(
578
- "A message was sent while interrupt is active. This will cause failure on the agent side"
579
- )
580
- ]);
581
- }
582
- let newMessages = [
583
- new import_runtime_client_gql3.TextMessage({
584
- content: "",
585
- role: import_runtime_client_gql3.Role.Assistant
586
- })
587
- ];
588
- chatAbortControllerRef.current = new AbortController();
589
- setMessages([...previousMessages, ...newMessages]);
590
- const messagesWithContext = disableSystemMessage ? [...initialMessages || [], ...previousMessages] : [makeSystemMessageCallback(), ...initialMessages || [], ...previousMessages];
591
- const finalProperties = __spreadValues({}, copilotConfig.properties || {});
592
- let mcpServersToUse = null;
593
- if (copilotConfig.mcpServers && Array.isArray(copilotConfig.mcpServers) && copilotConfig.mcpServers.length > 0) {
594
- mcpServersToUse = copilotConfig.mcpServers;
595
- } else if (((_a = copilotConfig.properties) == null ? void 0 : _a.mcpServers) && Array.isArray(copilotConfig.properties.mcpServers) && copilotConfig.properties.mcpServers.length > 0) {
596
- mcpServersToUse = copilotConfig.properties.mcpServers;
597
- }
598
- if (mcpServersToUse) {
599
- finalProperties.mcpServers = mcpServersToUse;
600
- copilotConfig.mcpServers = mcpServersToUse;
601
- }
602
- const isAgentRun = agentSessionRef.current !== null;
603
- const stream = runtimeClient.asStream(
604
- runtimeClient.generateCopilotResponse({
605
- data: __spreadProps(__spreadValues(__spreadProps(__spreadValues({
606
- frontend: {
607
- actions: processActionsForRuntimeRequest(actions),
608
- url: window.location.href
609
- },
610
- threadId,
611
- runId: runIdRef.current,
612
- extensions: extensionsRef.current,
613
- metaEvents: composeAndFlushMetaEventsInput([langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event]),
614
- messages: (0, import_runtime_client_gql3.convertMessagesToGqlInput)((0, import_runtime_client_gql3.filterAgentStateMessages)(messagesWithContext))
615
- }, copilotConfig.cloud ? {
616
- cloud: __spreadValues({}, ((_d = (_c = (_b = copilotConfig.cloud.guardrails) == null ? void 0 : _b.input) == null ? void 0 : _c.restrictToTopic) == null ? void 0 : _d.enabled) ? {
617
- guardrails: {
618
- inputValidationRules: {
619
- allowList: copilotConfig.cloud.guardrails.input.restrictToTopic.validTopics,
620
- denyList: copilotConfig.cloud.guardrails.input.restrictToTopic.invalidTopics
621
- }
622
- }
623
- } : {})
624
- } : {}), {
625
- metadata: {
626
- requestType: import_runtime_client_gql3.CopilotRequestType.Chat
627
- }
628
- }), agentSessionRef.current ? {
629
- agentSession: agentSessionRef.current
630
- } : {}), {
631
- agentStates: Object.values(coagentStatesRef.current).map((state) => {
632
- const stateObject = {
633
- agentName: state.name,
634
- state: JSON.stringify(state.state)
635
- };
636
- if (state.config !== void 0) {
637
- stateObject.config = JSON.stringify(state.config);
638
- }
639
- return stateObject;
640
- }),
641
- forwardedParameters: options.forwardedParameters || {},
642
- context
643
- }),
644
- properties: finalProperties,
645
- signal: (_e = chatAbortControllerRef.current) == null ? void 0 : _e.signal
646
- })
647
- );
648
- const guardrailsEnabled = ((_h = (_g = (_f = copilotConfig.cloud) == null ? void 0 : _f.guardrails) == null ? void 0 : _g.input) == null ? void 0 : _h.restrictToTopic.enabled) || false;
649
- const reader = stream.getReader();
650
- let executedCoAgentStateRenders = [];
651
- let followUp = void 0;
652
- let messages2 = [];
653
- let syncedMessages = [];
654
- let interruptMessages = [];
655
- try {
656
- while (true) {
657
- let done, value;
658
- try {
659
- const readResult = yield reader.read();
660
- done = readResult.done;
661
- value = readResult.value;
662
- } catch (readError) {
663
- break;
664
- }
665
- if (done) {
666
- if (chatAbortControllerRef.current.signal.aborted) {
667
- return [];
668
- }
669
- break;
670
- }
671
- if (!(value == null ? void 0 : value.generateCopilotResponse)) {
672
- continue;
673
- }
674
- runIdRef.current = value.generateCopilotResponse.runId || null;
675
- extensionsRef.current = import_runtime_client_gql3.CopilotRuntimeClient.removeGraphQLTypename(
676
- value.generateCopilotResponse.extensions || {}
677
- );
678
- setRunId(runIdRef.current);
679
- setExtensions(extensionsRef.current);
680
- let rawMessagesResponse = value.generateCopilotResponse.messages;
681
- const metaEvents = (_j = (_i = value.generateCopilotResponse) == null ? void 0 : _i.metaEvents) != null ? _j : [];
682
- (metaEvents != null ? metaEvents : []).forEach((ev) => {
683
- if (ev.name === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent) {
684
- let eventValue = (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev).value;
685
- eventValue = (0, import_shared4.parseJson)(eventValue, eventValue);
686
- setLangGraphInterruptAction(threadId, {
687
- event: __spreadProps(__spreadValues({}, (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev)), {
688
- value: eventValue
689
- })
690
- });
691
- }
692
- if (ev.name === import_runtime_client_gql3.MetaEventName.CopilotKitLangGraphInterruptEvent) {
693
- const data = ev.data;
694
- rawMessagesResponse = [...rawMessagesResponse, ...data.messages];
695
- interruptMessages = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
696
- // @ts-ignore
697
- (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(data.messages)
698
- );
699
- }
700
- });
701
- messages2 = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
702
- (0, import_runtime_client_gql3.filterAdjacentAgentStateMessages)(rawMessagesResponse)
703
- );
704
- newMessages = [];
705
- if (((_k = value.generateCopilotResponse.status) == null ? void 0 : _k.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "GUARDRAILS_VALIDATION_FAILED") {
706
- const guardrailsReason = ((_l = value.generateCopilotResponse.status.details) == null ? void 0 : _l.guardrailsReason) || "";
707
- newMessages = [
708
- new import_runtime_client_gql3.TextMessage({
709
- role: import_runtime_client_gql3.MessageRole.Assistant,
710
- content: guardrailsReason
711
- })
712
- ];
713
- const guardrailsError = new import_shared4.CopilotKitError({
714
- message: `Guardrails validation failed: ${guardrailsReason}`,
715
- code: import_shared4.CopilotKitErrorCode.MISUSE
716
- });
717
- yield traceUIError(guardrailsError, {
718
- statusReason: value.generateCopilotResponse.status.reason,
719
- statusDetails: value.generateCopilotResponse.status.details
720
- });
721
- setMessages([...previousMessages, ...newMessages]);
722
- break;
723
- }
724
- if (((_m = value.generateCopilotResponse.status) == null ? void 0 : _m.__typename) === "FailedResponseStatus" && value.generateCopilotResponse.status.reason === "UNKNOWN_ERROR") {
725
- const errorMessage = ((_n = value.generateCopilotResponse.status.details) == null ? void 0 : _n.description) || "An unknown error occurred";
726
- const statusDetails = value.generateCopilotResponse.status.details;
727
- const originalError = (statusDetails == null ? void 0 : statusDetails.originalError) || (statusDetails == null ? void 0 : statusDetails.error);
728
- const originalCode = (originalError == null ? void 0 : originalError.code) || ((_o = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _o.code);
729
- const originalSeverity = (originalError == null ? void 0 : originalError.severity) || ((_p = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _p.severity);
730
- const originalVisibility = (originalError == null ? void 0 : originalError.visibility) || ((_q = originalError == null ? void 0 : originalError.extensions) == null ? void 0 : _q.visibility);
731
- let errorCode = import_shared4.CopilotKitErrorCode.NETWORK_ERROR;
732
- if (originalCode && Object.values(import_shared4.CopilotKitErrorCode).includes(originalCode)) {
733
- errorCode = originalCode;
734
- }
735
- const structuredError = new import_shared4.CopilotKitError({
736
- message: errorMessage,
737
- code: errorCode,
738
- severity: originalSeverity,
739
- visibility: originalVisibility
740
- });
741
- setBannerError(structuredError);
742
- yield traceUIError(structuredError, {
743
- statusReason: value.generateCopilotResponse.status.reason,
744
- statusDetails: value.generateCopilotResponse.status.details,
745
- originalErrorCode: originalCode,
746
- preservedStructure: !!originalCode
747
- });
748
- setIsLoading(false);
749
- throw new Error(structuredError.message);
750
- } else if (messages2.length > 0) {
751
- newMessages = [...messages2];
752
- for (const message of messages2) {
753
- if (message.isAgentStateMessage() && !message.active && !executedCoAgentStateRenders.includes(message.id) && onCoAgentStateRender) {
754
- if (guardrailsEnabled && value.generateCopilotResponse.status === void 0) {
755
- break;
756
- }
757
- yield onCoAgentStateRender({
758
- name: message.agentName,
759
- nodeName: message.nodeName,
760
- state: message.state
761
- });
762
- executedCoAgentStateRenders.push(message.id);
763
- }
764
- }
765
- const lastAgentStateMessage = [...messages2].reverse().find((message) => message.isAgentStateMessage());
766
- if (lastAgentStateMessage) {
767
- if (lastAgentStateMessage.state.messages && lastAgentStateMessage.state.messages.length > 0) {
768
- syncedMessages = (0, import_runtime_client_gql3.loadMessagesFromJsonRepresentation)(
769
- lastAgentStateMessage.state.messages
770
- );
771
- }
772
- setCoagentStatesWithRef((prevAgentStates) => {
773
- var _a2;
774
- return __spreadProps(__spreadValues({}, prevAgentStates), {
775
- [lastAgentStateMessage.agentName]: {
776
- name: lastAgentStateMessage.agentName,
777
- state: lastAgentStateMessage.state,
778
- running: lastAgentStateMessage.running,
779
- active: lastAgentStateMessage.active,
780
- threadId: lastAgentStateMessage.threadId,
781
- nodeName: lastAgentStateMessage.nodeName,
782
- runId: lastAgentStateMessage.runId,
783
- // Preserve existing config from previous state
784
- config: (_a2 = prevAgentStates[lastAgentStateMessage.agentName]) == null ? void 0 : _a2.config
785
- }
786
- });
787
- });
788
- if (lastAgentStateMessage.running) {
789
- setAgentSession({
790
- threadId: lastAgentStateMessage.threadId,
791
- agentName: lastAgentStateMessage.agentName,
792
- nodeName: lastAgentStateMessage.nodeName
793
- });
794
- } else {
795
- if (agentLock) {
796
- setAgentSession({
797
- threadId: (0, import_shared4.randomId)(),
798
- agentName: agentLock,
799
- nodeName: void 0
800
- });
801
- } else {
802
- setAgentSession(null);
803
- }
804
- }
805
- }
806
- }
807
- if (newMessages.length > 0) {
808
- setMessages([...previousMessages, ...newMessages]);
809
- }
99
+ }, [
100
+ isExternalStateManagement(options) ? JSON.stringify(options.state) : "initialState" in options ? JSON.stringify(options.initialState) : void 0
101
+ ]);
102
+ (0, import_react.useEffect)(() => {
103
+ if (!agent)
104
+ return;
105
+ const subscriber = {
106
+ onStateChanged: (args) => {
107
+ if (isExternalStateManagement(options)) {
108
+ options.setState(args.state);
810
109
  }
811
- let finalMessages = constructFinalMessages(
812
- [...syncedMessages, ...interruptMessages],
813
- previousMessages,
814
- newMessages
815
- );
816
- let didExecuteAction = false;
817
- const executeActionFromMessage = (currentAction, actionMessage) => __async(this, null, function* () {
818
- var _a2;
819
- const isInterruptAction = interruptMessages.find((m) => m.id === actionMessage.id);
820
- followUp = (_a2 = currentAction == null ? void 0 : currentAction.followUp) != null ? _a2 : !isInterruptAction;
821
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
822
- currentAction._setActivatingMessageId(actionMessage.id);
823
- }
824
- const resultMessage = yield executeAction({
825
- onFunctionCall,
826
- message: actionMessage,
827
- chatAbortControllerRef,
828
- onError: (error) => {
829
- addErrorToast([error]);
830
- console.error(`Failed to execute action ${actionMessage.name}: ${error}`);
831
- },
832
- setMessages,
833
- getFinalMessages: () => finalMessages,
834
- isRenderAndWait: (currentAction == null ? void 0 : currentAction._isRenderAndWait) || false
835
- });
836
- didExecuteAction = true;
837
- const messageIndex = finalMessages.findIndex((msg) => msg.id === actionMessage.id);
838
- finalMessages.splice(messageIndex + 1, 0, resultMessage);
839
- if (currentAction == null ? void 0 : currentAction._isRenderAndWait) {
840
- const messagesForImmediateUpdate = [...finalMessages];
841
- (0, import_react_dom.flushSync)(() => {
842
- setMessages(messagesForImmediateUpdate);
843
- });
844
- }
845
- if (currentAction == null ? void 0 : currentAction._setActivatingMessageId) {
846
- currentAction._setActivatingMessageId(null);
847
- }
848
- return resultMessage;
849
- });
850
- if (onFunctionCall) {
851
- const lastMessages = [];
852
- for (let i = finalMessages.length - 1; i >= 0; i--) {
853
- const message = finalMessages[i];
854
- if ((message.isActionExecutionMessage() || message.isResultMessage()) && message.status.code !== import_runtime_client_gql3.MessageStatusCode.Pending) {
855
- lastMessages.unshift(message);
856
- } else if (!message.isAgentStateMessage()) {
857
- break;
858
- }
859
- }
860
- for (const message of lastMessages) {
861
- setMessages(finalMessages);
862
- const action = actions.find(
863
- (action2) => action2.name === message.name
864
- );
865
- if (action && action.available === "frontend") {
866
- continue;
867
- }
868
- const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
869
- if (action && message.isActionExecutionMessage()) {
870
- const isRenderAndWaitAction = (action == null ? void 0 : action._isRenderAndWait) || false;
871
- const alreadyProcessed = isRenderAndWaitAction && finalMessages.some(
872
- (fm) => fm.isResultMessage() && fm.actionExecutionId === message.id
873
- );
874
- if (alreadyProcessed) {
875
- } else {
876
- const resultMessage = yield executeActionFromMessage(
877
- action,
878
- message
879
- );
880
- const pairedFeAction = getPairedFeAction(actions, resultMessage);
881
- if (pairedFeAction) {
882
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
883
- name: pairedFeAction.name,
884
- arguments: (0, import_shared4.parseJson)(resultMessage.result, resultMessage.result),
885
- status: message.status,
886
- createdAt: message.createdAt,
887
- parentMessageId: message.parentMessageId
888
- });
889
- yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
890
- }
891
- }
892
- } else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
893
- const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
894
- name: currentResultMessagePairedFeAction.name,
895
- arguments: (0, import_shared4.parseJson)(message.result, message.result),
896
- status: message.status,
897
- createdAt: message.createdAt
898
- });
899
- finalMessages.push(newExecutionMessage);
900
- yield executeActionFromMessage(
901
- currentResultMessagePairedFeAction,
902
- newExecutionMessage
903
- );
904
- }
905
- }
906
- setMessages(finalMessages);
110
+ },
111
+ onRunInitialized: (args) => {
112
+ const runHasState = hasStateValues(args.state);
113
+ if (runHasState) {
114
+ handleStateUpdate(args.state);
115
+ return;
907
116
  }
908
- if (followUp !== false && (didExecuteAction || // the last message is a server side result
909
- !isAgentRun && finalMessages.length && finalMessages[finalMessages.length - 1].isResultMessage()) && // the user did not stop generation
910
- !((_r = chatAbortControllerRef.current) == null ? void 0 : _r.signal.aborted)) {
911
- yield new Promise((resolve) => setTimeout(resolve, 10));
912
- return yield runChatCompletionRef.current(finalMessages);
913
- } else if ((_s = chatAbortControllerRef.current) == null ? void 0 : _s.signal.aborted) {
914
- const repairedMessages = finalMessages.filter((message, actionExecutionIndex) => {
915
- if (message.isActionExecutionMessage()) {
916
- return finalMessages.find(
917
- (msg, resultIndex) => msg.isResultMessage() && msg.actionExecutionId === message.id && resultIndex === actionExecutionIndex + 1
918
- );
919
- }
920
- return true;
921
- });
922
- const repairedMessageIds = repairedMessages.map((message) => message.id);
923
- setMessages(repairedMessages);
924
- if ((_t = agentSessionRef.current) == null ? void 0 : _t.nodeName) {
925
- setAgentSession({
926
- threadId: agentSessionRef.current.threadId,
927
- agentName: agentSessionRef.current.agentName,
928
- nodeName: "__end__"
929
- });
930
- }
931
- return newMessages.filter((message) => repairedMessageIds.includes(message.id));
932
- } else {
933
- return newMessages.slice();
117
+ if (hasStateValues(agent.state)) {
118
+ return;
934
119
  }
935
- } finally {
936
- setIsLoading(false);
937
- }
938
- }),
939
- [
940
- messages,
941
- setMessages,
942
- makeSystemMessageCallback,
943
- copilotConfig,
944
- setIsLoading,
945
- initialMessages,
946
- isLoading,
947
- actions,
948
- onFunctionCall,
949
- onCoAgentStateRender,
950
- setCoagentStatesWithRef,
951
- coagentStatesRef,
952
- agentSession,
953
- setAgentSession,
954
- disableSystemMessage,
955
- context
956
- ]
957
- );
958
- runChatCompletionRef.current = runChatCompletion;
959
- const runChatCompletionAndHandleFunctionCall = useAsyncCallback(
960
- (messages2) => __async(this, null, function* () {
961
- yield runChatCompletionRef.current(messages2);
962
- }),
963
- [messages]
964
- );
965
- (0, import_react6.useEffect)(() => {
966
- if (!isLoading && pendingAppendsRef.current.length > 0) {
967
- const pending = pendingAppendsRef.current.splice(0);
968
- const followUp = pending.some((p) => p.followUp);
969
- const newMessages = [...messages, ...pending.map((p) => p.message)];
970
- setMessages(newMessages);
971
- if (followUp) {
972
- runChatCompletionAndHandleFunctionCall(newMessages);
973
- }
974
- }
975
- }, [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]);
976
- const composeAndFlushMetaEventsInput = (0, import_react6.useCallback)(
977
- (metaEvents) => {
978
- return metaEvents.reduce((acc, event) => {
979
- if (!event)
980
- return acc;
981
- switch (event.name) {
982
- case import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent:
983
- if (event.response) {
984
- setLangGraphInterruptAction(threadId, null);
985
- const value = event.value;
986
- return [
987
- ...acc,
988
- {
989
- name: event.name,
990
- value: typeof value === "string" ? value : JSON.stringify(value),
991
- response: typeof event.response === "string" ? event.response : JSON.stringify(event.response)
992
- }
993
- ];
994
- }
995
- return acc;
996
- default:
997
- return acc;
998
- }
999
- }, []);
1000
- },
1001
- [setLangGraphInterruptAction]
1002
- );
1003
- const append = useAsyncCallback(
1004
- (message, options2) => __async(this, null, function* () {
1005
- var _a;
1006
- const followUp = (_a = options2 == null ? void 0 : options2.followUp) != null ? _a : true;
1007
- if (isLoading) {
1008
- pendingAppendsRef.current.push({ message, followUp });
1009
- return;
1010
- }
1011
- const newMessages = [...messages, message];
1012
- setMessages(newMessages);
1013
- if (followUp) {
1014
- return runChatCompletionAndHandleFunctionCall(newMessages);
1015
- }
1016
- }),
1017
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1018
- );
1019
- const reload = useAsyncCallback(
1020
- (reloadMessageId) => __async(this, null, function* () {
1021
- if (isLoading || messages.length === 0) {
1022
- return;
1023
- }
1024
- const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
1025
- if (reloadMessageIndex === -1) {
1026
- console.warn(`Message with id ${reloadMessageId} not found`);
1027
- return;
1028
- }
1029
- const reloadMessageRole = messages[reloadMessageIndex].role;
1030
- if (reloadMessageRole !== import_runtime_client_gql3.MessageRole.Assistant) {
1031
- console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
1032
- return;
1033
- }
1034
- let historyCutoff = [messages[0]];
1035
- if (messages.length > 2 && reloadMessageIndex !== 0) {
1036
- const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find(
1037
- (msg) => (
1038
- // @ts-expect-error -- message has role
1039
- msg.role === import_runtime_client_gql3.MessageRole.User
1040
- )
1041
- );
1042
- const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(
1043
- (msg) => msg.id === lastUserMessageBeforeRegenerate.id
1044
- );
1045
- historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
1046
- } else if (messages.length > 2 && reloadMessageIndex === 0) {
1047
- historyCutoff = [messages[0], messages[1]];
1048
- }
1049
- setMessages(historyCutoff);
1050
- return runChatCompletionAndHandleFunctionCall(historyCutoff);
1051
- }),
1052
- [isLoading, messages, setMessages, runChatCompletionAndHandleFunctionCall]
1053
- );
1054
- const stop = () => {
1055
- var _a;
1056
- (_a = chatAbortControllerRef.current) == null ? void 0 : _a.abort("Stop was called");
1057
- };
1058
- return {
1059
- append,
1060
- reload,
1061
- stop,
1062
- runChatCompletion: () => runChatCompletionRef.current(messages)
1063
- };
1064
- }
1065
- function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
1066
- const finalMessages = syncedMessages.length > 0 ? [...syncedMessages] : [...previousMessages, ...newMessages];
1067
- if (syncedMessages.length > 0) {
1068
- const messagesWithAgentState = [...previousMessages, ...newMessages];
1069
- let previousMessageId = void 0;
1070
- for (const message of messagesWithAgentState) {
1071
- if (message.isAgentStateMessage()) {
1072
- const index = finalMessages.findIndex((msg) => msg.id === previousMessageId);
1073
- if (index !== -1) {
1074
- finalMessages.splice(index + 1, 0, message);
120
+ if (initialStateRef.current !== void 0) {
121
+ handleStateUpdate(initialStateRef.current);
1075
122
  }
1076
- }
1077
- previousMessageId = message.id;
1078
- }
1079
- }
1080
- return finalMessages;
1081
- }
1082
- function executeAction(_0) {
1083
- return __async(this, arguments, function* ({
1084
- onFunctionCall,
1085
- message,
1086
- chatAbortControllerRef,
1087
- onError,
1088
- setMessages,
1089
- getFinalMessages,
1090
- isRenderAndWait
1091
- }) {
1092
- let result;
1093
- let error = null;
1094
- const currentMessagesForHandler = getFinalMessages();
1095
- const handlerReturnedPromise = onFunctionCall({
1096
- messages: currentMessagesForHandler,
1097
- name: message.name,
1098
- args: message.arguments
1099
- });
1100
- if (isRenderAndWait) {
1101
- const currentMessagesForRender = getFinalMessages();
1102
- (0, import_react_dom.flushSync)(() => {
1103
- setMessages([...currentMessagesForRender]);
1104
- });
1105
- }
1106
- try {
1107
- result = yield Promise.race([
1108
- handlerReturnedPromise,
1109
- // Await the promise returned by the handler
1110
- new Promise(
1111
- (resolve) => {
1112
- var _a;
1113
- return (_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.addEventListener(
1114
- "abort",
1115
- () => resolve("Operation was aborted by the user")
1116
- );
1117
- }
1118
- ),
1119
- // if the user stopped generation, we also abort consecutive actions
1120
- new Promise((resolve) => {
1121
- var _a;
1122
- if ((_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.aborted) {
1123
- resolve("Operation was aborted by the user");
1124
- }
1125
- })
1126
- ]);
1127
- } catch (e) {
1128
- onError(e);
1129
- }
1130
- return new import_runtime_client_gql3.ResultMessage({
1131
- id: "result-" + message.id,
1132
- result: import_runtime_client_gql3.ResultMessage.encodeResult(
1133
- error ? {
1134
- content: result,
1135
- error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
1136
- } : result
1137
- ),
1138
- actionExecutionId: message.id,
1139
- actionName: message.name
1140
- });
1141
- });
1142
- }
1143
- function getPairedFeAction(actions, message) {
1144
- let actionName = null;
1145
- if (message.isActionExecutionMessage()) {
1146
- actionName = message.name;
1147
- } else if (message.isResultMessage()) {
1148
- actionName = message.actionName;
1149
- }
1150
- return actions.find(
1151
- (action) => action.name === actionName && action.available === "frontend" || action.pairedAction === actionName
1152
- );
1153
- }
1154
-
1155
- // src/components/copilot-provider/copilotkit.tsx
1156
- var import_react8 = require("react");
1157
- var import_react_dom2 = require("react-dom");
1158
- var import_shared8 = require("@copilotkit/shared");
1159
-
1160
- // src/components/copilot-provider/copilot-messages.tsx
1161
- var import_react7 = require("react");
1162
- var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
1163
- var import_shared5 = require("@copilotkit/shared");
1164
- var import_jsx_runtime4 = require("react/jsx-runtime");
1165
- var MessagesTapContext = (0, import_react7.createContext)(null);
1166
- function useMessagesTap() {
1167
- const tap = (0, import_react7.useContext)(MessagesTapContext);
1168
- if (!tap)
1169
- throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");
1170
- return tap;
1171
- }
1172
-
1173
- // src/utils/extract.ts
1174
- var import_shared6 = require("@copilotkit/shared");
1175
- var import_runtime_client_gql5 = require("@copilotkit/runtime-client-gql");
1176
- var import_runtime_client_gql6 = require("@copilotkit/runtime-client-gql");
1177
- function extract(_0) {
1178
- return __async(this, arguments, function* ({
1179
- context,
1180
- instructions,
1181
- parameters,
1182
- include,
1183
- data,
1184
- abortSignal,
1185
- stream,
1186
- requestType = import_runtime_client_gql5.CopilotRequestType.Task,
1187
- forwardedParameters
1188
- }) {
1189
- var _a, _b;
1190
- const { messages } = context;
1191
- const action = {
1192
- name: "extract",
1193
- description: instructions,
1194
- parameters,
1195
- handler: (args) => {
123
+ },
124
+ onStepStartedEvent: ({ event }) => {
125
+ nodeNameRef.current = event.stepName;
126
+ },
127
+ onRunStartedEvent: () => {
128
+ nodeNameRef.current = "start";
129
+ },
130
+ onRunFinishedEvent: () => {
131
+ nodeNameRef.current = "end";
1196
132
  }
1197
133
  };
1198
- const includeReadable = (_a = include == null ? void 0 : include.readable) != null ? _a : false;
1199
- const includeMessages = (_b = include == null ? void 0 : include.messages) != null ? _b : false;
1200
- let contextString = "";
1201
- if (data) {
1202
- contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
1203
- }
1204
- if (includeReadable) {
1205
- contextString += context.getContextString([], defaultCopilotContextCategories);
1206
- }
1207
- const systemMessage = new import_runtime_client_gql5.TextMessage({
1208
- content: makeSystemMessage(contextString, instructions),
1209
- role: import_runtime_client_gql5.Role.System
1210
- });
1211
- const instructionsMessage = new import_runtime_client_gql5.TextMessage({
1212
- content: makeInstructionsMessage(instructions),
1213
- role: import_runtime_client_gql5.Role.User
1214
- });
1215
- const response = context.runtimeClient.asStream(
1216
- context.runtimeClient.generateCopilotResponse({
1217
- data: {
1218
- frontend: {
1219
- actions: [
1220
- {
1221
- name: action.name,
1222
- description: action.description || "",
1223
- jsonSchema: JSON.stringify((0, import_shared6.actionParametersToJsonSchema)(action.parameters || []))
1224
- }
1225
- ],
1226
- url: window.location.href
1227
- },
1228
- messages: (0, import_runtime_client_gql6.convertMessagesToGqlInput)(
1229
- includeMessages ? [systemMessage, instructionsMessage, ...(0, import_runtime_client_gql6.filterAgentStateMessages)(messages)] : [systemMessage, instructionsMessage]
1230
- ),
1231
- metadata: {
1232
- requestType
1233
- },
1234
- forwardedParameters: __spreadProps(__spreadValues({}, forwardedParameters != null ? forwardedParameters : {}), {
1235
- toolChoice: "function",
1236
- toolChoiceFunctionName: action.name
1237
- })
1238
- },
1239
- properties: context.copilotApiConfig.properties,
1240
- signal: abortSignal
1241
- })
1242
- );
1243
- const reader = response.getReader();
1244
- let isInitial = true;
1245
- let actionExecutionMessage = void 0;
1246
- while (true) {
1247
- const { done, value } = yield reader.read();
1248
- if (done) {
1249
- break;
1250
- }
1251
- if (abortSignal == null ? void 0 : abortSignal.aborted) {
1252
- throw new Error("Aborted");
1253
- }
1254
- actionExecutionMessage = (0, import_runtime_client_gql5.convertGqlOutputToMessages)(
1255
- value.generateCopilotResponse.messages
1256
- ).find((msg) => msg.isActionExecutionMessage());
1257
- if (!actionExecutionMessage) {
1258
- continue;
1259
- }
1260
- stream == null ? void 0 : stream({
1261
- status: isInitial ? "initial" : "inProgress",
1262
- args: actionExecutionMessage.arguments
1263
- });
1264
- isInitial = false;
1265
- }
1266
- if (!actionExecutionMessage) {
1267
- throw new Error("extract() failed: No function call occurred");
1268
- }
1269
- stream == null ? void 0 : stream({
1270
- status: "complete",
1271
- args: actionExecutionMessage.arguments
1272
- });
1273
- return actionExecutionMessage.arguments;
1274
- });
1275
- }
1276
- function makeInstructionsMessage(instructions) {
1277
- return `
1278
- The user has given you the following task to complete:
1279
-
1280
- \`\`\`
1281
- ${instructions}
1282
- \`\`\`
1283
-
1284
- Any additional messages provided are for providing context only and should not be used to ask questions or engage in conversation.
1285
- `;
1286
- }
1287
- function makeSystemMessage(contextString, instructions) {
1288
- return `
1289
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1290
-
1291
- 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.
1292
- Always be polite and respectful, and prefer brevity over verbosity.
1293
-
1294
- The user has provided you with the following context:
1295
- \`\`\`
1296
- ${contextString}
1297
- \`\`\`
1298
-
1299
- They have also provided you with a function called extract you MUST call to initiate actions on their behalf.
1300
-
1301
- Please assist them as best you can.
1302
-
1303
- This is not a conversation, so please do not ask questions. Just call the function without saying anything else.
1304
- `;
1305
- }
1306
-
1307
- // src/utils/suggestions.ts
1308
- var import_shared7 = require("@copilotkit/shared");
1309
- var import_runtime_client_gql7 = require("@copilotkit/runtime-client-gql");
1310
- var reloadSuggestions = (context, chatSuggestionConfiguration, setCurrentSuggestions, abortControllerRef) => __async(void 0, null, function* () {
1311
- const abortController = abortControllerRef.current;
1312
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1313
- return;
1314
- }
1315
- const setSuggestionsIfNotAborted = (suggestions) => {
1316
- if (!(abortController == null ? void 0 : abortController.signal.aborted) && abortControllerRef.current === abortController) {
1317
- setCurrentSuggestions(suggestions);
1318
- }
1319
- };
1320
- try {
1321
- const tools = JSON.stringify(
1322
- Object.values(context.actions).map((action) => ({
1323
- name: action.name,
1324
- description: action.description,
1325
- jsonSchema: JSON.stringify((0, import_shared7.actionParametersToJsonSchema)(action.parameters))
1326
- }))
1327
- );
1328
- const allSuggestions = [];
1329
- let hasSuccessfulSuggestions = false;
1330
- let hasErrors = false;
1331
- let lastError = null;
1332
- const enabledConfigs = Object.values(chatSuggestionConfiguration).filter(
1333
- (config) => config.instructions && config.instructions.trim().length > 0
1334
- );
1335
- if (enabledConfigs.length === 0) {
1336
- return;
1337
- }
1338
- setSuggestionsIfNotAborted([]);
1339
- for (const config of enabledConfigs) {
1340
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1341
- setSuggestionsIfNotAborted([]);
1342
- return;
1343
- }
1344
- try {
1345
- const result = yield extract({
1346
- context,
1347
- instructions: "Suggest what the user could say next. Provide clear, highly relevant suggestions. Do not literally suggest function calls. ",
1348
- data: `${config.instructions}
1349
-
1350
- Available tools: ${tools}
1351
-
1352
- `,
1353
- requestType: import_runtime_client_gql7.CopilotRequestType.Task,
1354
- parameters: [
1355
- {
1356
- name: "suggestions",
1357
- type: "object[]",
1358
- attributes: [
1359
- {
1360
- name: "title",
1361
- description: "The title of the suggestion. This is shown as a button and should be short.",
1362
- type: "string"
1363
- },
1364
- {
1365
- name: "message",
1366
- 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.",
1367
- type: "string"
1368
- }
1369
- ]
1370
- }
1371
- ],
1372
- include: {
1373
- messages: true,
1374
- readable: true
1375
- },
1376
- abortSignal: abortController == null ? void 0 : abortController.signal,
1377
- stream: ({ status, args }) => {
1378
- if (abortController == null ? void 0 : abortController.signal.aborted) {
1379
- return;
1380
- }
1381
- const suggestions = args.suggestions || [];
1382
- const newSuggestions = [];
1383
- for (let i = 0; i < suggestions.length; i++) {
1384
- if (config.maxSuggestions !== void 0 && i >= config.maxSuggestions) {
1385
- break;
1386
- }
1387
- const suggestion = suggestions[i];
1388
- if (!suggestion || typeof suggestion !== "object") {
1389
- continue;
1390
- }
1391
- const { title, message } = suggestion;
1392
- const hasValidTitle = title && typeof title === "string" && title.trim().length > 0;
1393
- const hasValidMessage = message && typeof message === "string" && message.trim().length > 0;
1394
- if (!hasValidTitle) {
1395
- continue;
1396
- }
1397
- const partial = i === suggestions.length - 1 && status !== "complete";
1398
- newSuggestions.push({
1399
- title: title.trim(),
1400
- message: hasValidMessage ? message.trim() : "",
1401
- // Use title as fallback
1402
- partial,
1403
- className: config.className
1404
- });
1405
- }
1406
- setSuggestionsIfNotAborted([...allSuggestions, ...newSuggestions]);
1407
- }
1408
- });
1409
- if ((result == null ? void 0 : result.suggestions) && Array.isArray(result.suggestions)) {
1410
- const validSuggestions = result.suggestions.filter(
1411
- (suggestion) => suggestion && typeof suggestion.title === "string" && suggestion.title.trim().length > 0
1412
- ).map((suggestion) => ({
1413
- title: suggestion.title.trim(),
1414
- message: suggestion.message && typeof suggestion.message === "string" && suggestion.message.trim() ? suggestion.message.trim() : suggestion.title.trim()
1415
- }));
1416
- if (validSuggestions.length > 0) {
1417
- allSuggestions.push(...validSuggestions);
1418
- hasSuccessfulSuggestions = true;
1419
- }
1420
- }
1421
- } catch (error) {
1422
- hasErrors = true;
1423
- lastError = error instanceof Error ? error : new Error(String(error));
1424
- }
1425
- }
1426
- if (hasSuccessfulSuggestions && allSuggestions.length > 0) {
1427
- const uniqueSuggestions = allSuggestions.filter(
1428
- (suggestion, index, self) => index === self.findIndex((s) => s.message === suggestion.message)
1429
- );
1430
- setSuggestionsIfNotAborted(uniqueSuggestions);
1431
- } else if (hasErrors) {
1432
- const errorMessage = lastError ? lastError.message : "Failed to generate suggestions due to API errors";
1433
- throw new Error(errorMessage);
1434
- }
1435
- } catch (error) {
1436
- throw error;
1437
- }
1438
- });
1439
-
1440
- // src/components/copilot-provider/copilotkit.tsx
1441
- var import_jsx_runtime5 = require("react/jsx-runtime");
1442
- var defaultCopilotContextCategories = ["global"];
1443
-
1444
- // src/hooks/use-copilot-chat_internal.ts
1445
- var import_runtime_client_gql8 = require("@copilotkit/runtime-client-gql");
1446
-
1447
- // src/hooks/use-langgraph-interrupt-render.ts
1448
- var import_react9 = __toESM(require("react"));
1449
- var InterruptRenderer = ({ event, result, render, resolve }) => {
1450
- return render({ event, result, resolve });
1451
- };
1452
- function useLangGraphInterruptRender() {
1453
- const { langGraphInterruptAction, setLangGraphInterruptAction, agentSession, threadId } = useCopilotContext();
1454
- const responseRef = import_react9.default.useRef();
1455
- const resolveInterrupt = (0, import_react9.useCallback)(
1456
- (response) => {
1457
- responseRef.current = response;
1458
- setTimeout(() => {
1459
- setLangGraphInterruptAction(threadId, { event: { response } });
1460
- }, 0);
1461
- },
1462
- [setLangGraphInterruptAction, threadId]
1463
- );
1464
- if (!langGraphInterruptAction || !langGraphInterruptAction.event || !langGraphInterruptAction.render)
1465
- return null;
1466
- const { render, handler, event, enabled } = langGraphInterruptAction;
1467
- const conditionsMet = !agentSession || !enabled ? true : enabled({ eventValue: event.value, agentMetadata: agentSession });
1468
- if (!conditionsMet) {
1469
- return null;
1470
- }
1471
- let result = null;
1472
- if (handler) {
1473
- result = handler({
1474
- event,
1475
- resolve: resolveInterrupt
1476
- });
1477
- }
1478
- return import_react9.default.createElement(InterruptRenderer, {
1479
- event,
1480
- result,
1481
- render,
1482
- resolve: resolveInterrupt
1483
- });
1484
- }
1485
-
1486
- // src/hooks/use-copilot-chat_internal.ts
1487
- var globalSuggestionPromise = null;
1488
- function useCopilotChat(options = {}) {
1489
- var _a;
1490
- const makeSystemMessage2 = (_a = options.makeSystemMessage) != null ? _a : defaultSystemMessage;
1491
- const {
1492
- getContextString,
1493
- getFunctionCallHandler,
1494
- copilotApiConfig,
1495
- isLoading,
1496
- setIsLoading,
1497
- chatInstructions,
1498
- actions,
1499
- coagentStatesRef,
1500
- setCoagentStatesWithRef,
1501
- coAgentStateRenders,
1502
- agentSession,
1503
- setAgentSession,
1504
- forwardedParameters,
1505
- agentLock,
1506
- threadId,
1507
- setThreadId,
1508
- runId,
1509
- setRunId,
1510
- chatAbortControllerRef,
1511
- extensions,
1512
- setExtensions,
1513
- langGraphInterruptAction,
1514
- setLangGraphInterruptAction,
1515
- chatSuggestionConfiguration,
1516
- runtimeClient
1517
- } = useCopilotContext();
1518
- const { messages, setMessages, suggestions, setSuggestions } = useCopilotMessagesContext();
1519
- const [mcpServers, setLocalMcpServers] = (0, import_react10.useState)([]);
1520
- const suggestionsAbortControllerRef = (0, import_react10.useRef)(null);
1521
- const isLoadingSuggestionsRef = (0, import_react10.useRef)(false);
1522
- const abortSuggestions = (0, import_react10.useCallback)(
1523
- (clear = true) => {
1524
- var _a2;
1525
- (_a2 = suggestionsAbortControllerRef.current) == null ? void 0 : _a2.abort("suggestions aborted by user");
1526
- suggestionsAbortControllerRef.current = null;
1527
- if (clear) {
1528
- setSuggestions([]);
1529
- }
1530
- },
1531
- [setSuggestions]
1532
- );
1533
- const stableContext = (0, import_react10.useMemo)(() => {
1534
- return {
1535
- actions,
1536
- copilotApiConfig,
1537
- chatSuggestionConfiguration,
1538
- messages,
1539
- setMessages,
1540
- getContextString,
1541
- runtimeClient
134
+ const subscription = agent.subscribe(subscriber);
135
+ return () => {
136
+ subscription.unsubscribe();
1542
137
  };
1543
- }, [
1544
- JSON.stringify(Object.keys(actions)),
1545
- copilotApiConfig.chatApiEndpoint,
1546
- messages.length,
1547
- Object.keys(chatSuggestionConfiguration).length
1548
- ]);
1549
- const generateSuggestionsFunc = (0, import_react10.useCallback)(() => __async(this, null, function* () {
1550
- if (globalSuggestionPromise) {
1551
- return globalSuggestionPromise;
1552
- }
1553
- globalSuggestionPromise = (() => __async(this, null, function* () {
1554
- try {
1555
- abortSuggestions();
1556
- isLoadingSuggestionsRef.current = true;
1557
- suggestionsAbortControllerRef.current = new AbortController();
1558
- setSuggestions([]);
1559
- yield reloadSuggestions(
1560
- stableContext,
1561
- chatSuggestionConfiguration,
1562
- setSuggestions,
1563
- suggestionsAbortControllerRef
1564
- );
1565
- } catch (error) {
1566
- throw error;
1567
- } finally {
1568
- isLoadingSuggestionsRef.current = false;
1569
- globalSuggestionPromise = null;
1570
- }
1571
- }))();
1572
- return globalSuggestionPromise;
1573
- }), [stableContext, chatSuggestionConfiguration, setSuggestions, abortSuggestions]);
1574
- const resetSuggestions = (0, import_react10.useCallback)(() => {
1575
- setSuggestions([]);
1576
- }, [setSuggestions]);
1577
- (0, import_react10.useEffect)(() => {
1578
- if (mcpServers.length > 0) {
1579
- const serversCopy = [...mcpServers];
1580
- copilotApiConfig.mcpServers = serversCopy;
1581
- if (!copilotApiConfig.properties) {
1582
- copilotApiConfig.properties = {};
1583
- }
1584
- copilotApiConfig.properties.mcpServers = serversCopy;
1585
- }
1586
- }, [mcpServers, copilotApiConfig]);
1587
- const setMcpServers = (0, import_react10.useCallback)((servers) => {
1588
- setLocalMcpServers(servers);
1589
- }, []);
1590
- const onCoAgentStateRender = useAsyncCallback(
1591
- (args) => __async(this, null, function* () {
1592
- var _a2;
1593
- const { name, nodeName, state } = args;
1594
- let action = Object.values(coAgentStateRenders).find(
1595
- (action2) => action2.name === name && action2.nodeName === nodeName
1596
- );
1597
- if (!action) {
1598
- action = Object.values(coAgentStateRenders).find(
1599
- (action2) => action2.name === name && !action2.nodeName
1600
- );
1601
- }
1602
- if (action) {
1603
- yield (_a2 = action.handler) == null ? void 0 : _a2.call(action, { state, nodeName });
1604
- }
1605
- }),
1606
- [coAgentStateRenders]
1607
- );
1608
- const makeSystemMessageCallback = (0, import_react10.useCallback)(() => {
1609
- const systemMessageMaker = makeSystemMessage2 || defaultSystemMessage;
1610
- const contextString = getContextString([], defaultCopilotContextCategories);
1611
- return new import_runtime_client_gql8.TextMessage({
1612
- content: systemMessageMaker(contextString, chatInstructions),
1613
- role: import_runtime_client_gql8.Role.System
1614
- });
1615
- }, [getContextString, makeSystemMessage2, chatInstructions]);
1616
- const deleteMessage = (0, import_react10.useCallback)(
1617
- (messageId) => {
1618
- setMessages((prev) => prev.filter((message) => message.id !== messageId));
1619
- },
1620
- [setMessages]
1621
- );
1622
- const { append, reload, stop, runChatCompletion } = useChat(__spreadProps(__spreadValues({}, options), {
1623
- actions: Object.values(actions),
1624
- copilotConfig: copilotApiConfig,
1625
- initialMessages: (0, import_runtime_client_gql8.aguiToGQL)(options.initialMessages || []),
1626
- onFunctionCall: getFunctionCallHandler(),
1627
- onCoAgentStateRender,
1628
- messages,
1629
- setMessages,
1630
- makeSystemMessageCallback,
1631
- isLoading,
1632
- setIsLoading,
1633
- coagentStatesRef,
1634
- setCoagentStatesWithRef,
1635
- agentSession,
1636
- setAgentSession,
1637
- forwardedParameters,
1638
- threadId,
1639
- setThreadId,
1640
- runId,
1641
- setRunId,
1642
- chatAbortControllerRef,
1643
- agentLock,
1644
- extensions,
1645
- setExtensions,
1646
- langGraphInterruptAction,
1647
- setLangGraphInterruptAction,
1648
- disableSystemMessage: options.disableSystemMessage
1649
- }));
1650
- const latestAppend = useUpdatedRef(append);
1651
- const latestAppendFunc = useAsyncCallback(
1652
- (message, options2) => __async(this, null, function* () {
1653
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
1654
- return yield latestAppend.current(message, options2);
1655
- }),
1656
- [latestAppend]
1657
- );
1658
- const latestSendMessageFunc = useAsyncCallback(
1659
- (message, options2) => __async(this, null, function* () {
1660
- abortSuggestions(options2 == null ? void 0 : options2.clearSuggestions);
1661
- return yield latestAppend.current((0, import_runtime_client_gql8.aguiToGQL)([message])[0], options2);
1662
- }),
1663
- [latestAppend]
1664
- );
1665
- const latestReload = useUpdatedRef(reload);
1666
- const latestReloadFunc = useAsyncCallback(
1667
- (messageId) => __async(this, null, function* () {
1668
- return yield latestReload.current(messageId);
1669
- }),
1670
- [latestReload]
1671
- );
1672
- const latestStop = useUpdatedRef(stop);
1673
- const latestStopFunc = (0, import_react10.useCallback)(() => {
1674
- return latestStop.current();
1675
- }, [latestStop]);
1676
- const latestDelete = useUpdatedRef(deleteMessage);
1677
- const latestDeleteFunc = (0, import_react10.useCallback)(
1678
- (messageId) => {
1679
- return latestDelete.current(messageId);
1680
- },
1681
- [latestDelete]
1682
- );
1683
- const latestSetMessages = useUpdatedRef(setMessages);
1684
- const latestSetMessagesFunc = (0, import_react10.useCallback)(
1685
- (messages2) => {
1686
- if (messages2.every((message) => message instanceof import_runtime_client_gql8.Message)) {
1687
- return latestSetMessages.current(messages2);
1688
- }
1689
- return latestSetMessages.current((0, import_runtime_client_gql8.aguiToGQL)(messages2));
1690
- },
1691
- [latestSetMessages]
1692
- );
1693
- const latestRunChatCompletion = useUpdatedRef(runChatCompletion);
1694
- const latestRunChatCompletionFunc = useAsyncCallback(() => __async(this, null, function* () {
1695
- return yield latestRunChatCompletion.current();
1696
- }), [latestRunChatCompletion]);
1697
- const reset = (0, import_react10.useCallback)(() => {
1698
- latestStopFunc();
1699
- setMessages([]);
1700
- setRunId(null);
1701
- setCoagentStatesWithRef({});
1702
- let initialAgentSession = null;
1703
- if (agentLock) {
1704
- initialAgentSession = {
1705
- agentName: agentLock
138
+ }, [agent, handleStateUpdate, hasStateValues]);
139
+ return (0, import_react.useMemo)(() => {
140
+ var _a, _b, _c;
141
+ if (!agent) {
142
+ const noop = () => {
1706
143
  };
1707
- }
1708
- setAgentSession(initialAgentSession);
1709
- resetSuggestions();
1710
- }, [
1711
- latestStopFunc,
1712
- setMessages,
1713
- setThreadId,
1714
- setCoagentStatesWithRef,
1715
- setAgentSession,
1716
- agentLock,
1717
- resetSuggestions
1718
- ]);
1719
- const latestReset = useUpdatedRef(reset);
1720
- const latestResetFunc = (0, import_react10.useCallback)(() => {
1721
- return latestReset.current();
1722
- }, [latestReset]);
1723
- const interrupt = useLangGraphInterruptRender();
1724
- return {
1725
- visibleMessages: messages,
1726
- messages: (0, import_runtime_client_gql8.gqlToAGUI)(messages, actions, coAgentStateRenders),
1727
- sendMessage: latestSendMessageFunc,
1728
- appendMessage: latestAppendFunc,
1729
- setMessages: latestSetMessagesFunc,
1730
- reloadMessages: latestReloadFunc,
1731
- stopGeneration: latestStopFunc,
1732
- reset: latestResetFunc,
1733
- deleteMessage: latestDeleteFunc,
1734
- runChatCompletion: latestRunChatCompletionFunc,
1735
- isLoading,
1736
- mcpServers,
1737
- setMcpServers,
1738
- suggestions,
1739
- setSuggestions,
1740
- generateSuggestions: generateSuggestionsFunc,
1741
- resetSuggestions,
1742
- isLoadingSuggestions: isLoadingSuggestionsRef.current,
1743
- interrupt
1744
- };
1745
- }
1746
- function useUpdatedRef(value) {
1747
- const ref = (0, import_react10.useRef)(value);
1748
- (0, import_react10.useEffect)(() => {
1749
- ref.current = value;
1750
- }, [value]);
1751
- return ref;
1752
- }
1753
- function defaultSystemMessage(contextString, additionalInstructions) {
1754
- return `
1755
- Please act as an efficient, competent, conscientious, and industrious professional assistant.
1756
-
1757
- 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.
1758
- Always be polite and respectful, and prefer brevity over verbosity.
1759
-
1760
- The user has provided you with the following context:
1761
- \`\`\`
1762
- ${contextString}
1763
- \`\`\`
1764
-
1765
- 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.
1766
-
1767
- Please assist them as best you can.
1768
-
1769
- 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.
1770
-
1771
- If you would like to call a function, call it without saying anything else.
1772
- In case of a function error:
1773
- - If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.
1774
- - If the error's source is unclear or seems unrelated to your input, do not attempt further retries.
1775
- ` + (additionalInstructions ? `
1776
-
1777
- ${additionalInstructions}` : "");
1778
- }
1779
-
1780
- // src/hooks/use-coagent.ts
1781
- var import_shared9 = require("@copilotkit/shared");
1782
- function useCoAgent(options) {
1783
- const context = useCopilotContext();
1784
- const { availableAgents, onError } = context;
1785
- const { setBannerError } = useToast();
1786
- const lastLoadedThreadId = (0, import_react11.useRef)();
1787
- const lastLoadedState = (0, import_react11.useRef)();
1788
- const { name } = options;
1789
- (0, import_react11.useEffect)(() => {
1790
- if ((availableAgents == null ? void 0 : availableAgents.length) && !availableAgents.some((a) => a.name === name)) {
1791
- const message = `(useCoAgent): Agent "${name}" not found. Make sure the agent exists and is properly configured.`;
1792
- console.warn(message);
1793
- const agentError = new import_shared9.CopilotKitAgentDiscoveryError({
1794
- agentName: name,
1795
- availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id }))
1796
- });
1797
- setBannerError(agentError);
1798
- }
1799
- }, [availableAgents]);
1800
- const { getMessagesFromTap } = useMessagesTap();
1801
- const { coagentStates, coagentStatesRef, setCoagentStatesWithRef, threadId, copilotApiConfig } = context;
1802
- const { sendMessage, runChatCompletion } = useCopilotChat();
1803
- const headers = __spreadValues({}, copilotApiConfig.headers || {});
1804
- const runtimeClient = useCopilotRuntimeClient({
1805
- url: copilotApiConfig.chatApiEndpoint,
1806
- publicApiKey: copilotApiConfig.publicApiKey,
1807
- headers,
1808
- credentials: copilotApiConfig.credentials,
1809
- showDevConsole: context.showDevConsole,
1810
- onError
1811
- });
1812
- const setState = (0, import_react11.useCallback)(
1813
- (newState) => {
1814
- let coagentState = getCoagentState({ coagentStates, name, options });
1815
- const updatedState = typeof newState === "function" ? newState(coagentState.state) : newState;
1816
- setCoagentStatesWithRef(__spreadProps(__spreadValues({}, coagentStatesRef.current), {
1817
- [name]: __spreadProps(__spreadValues({}, coagentState), {
1818
- state: updatedState
1819
- })
1820
- }));
1821
- },
1822
- [coagentStates, name]
1823
- );
1824
- (0, import_react11.useEffect)(() => {
1825
- const fetchAgentState = () => __async(this, null, function* () {
1826
- var _a, _b, _c, _d;
1827
- if (!threadId || threadId === lastLoadedThreadId.current)
1828
- return;
1829
- const result = yield runtimeClient.loadAgentState({
1830
- threadId,
1831
- agentName: name
144
+ const noopAsync = () => __async(this, null, function* () {
1832
145
  });
1833
- if (result.error) {
1834
- return;
1835
- }
1836
- const newState = (_b = (_a = result.data) == null ? void 0 : _a.loadAgentState) == null ? void 0 : _b.state;
1837
- if (newState === lastLoadedState.current)
1838
- return;
1839
- if (((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) && newState && newState != "{}") {
1840
- lastLoadedState.current = newState;
1841
- lastLoadedThreadId.current = threadId;
1842
- const fetchedState = (0, import_shared9.parseJson)(newState, {});
1843
- isExternalStateManagement(options) ? options.setState(fetchedState) : setState(fetchedState);
1844
- }
1845
- });
1846
- void fetchAgentState();
1847
- }, [threadId]);
1848
- (0, import_react11.useEffect)(() => {
1849
- if (isExternalStateManagement(options)) {
1850
- setState(options.state);
1851
- } else if (coagentStates[name] === void 0) {
1852
- setState(options.initialState === void 0 ? {} : options.initialState);
1853
- }
1854
- }, [
1855
- isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
1856
- // reset initialstate on reset
1857
- coagentStates[name] === void 0
1858
- ]);
1859
- (0, import_react11.useEffect)(() => {
1860
- const newConfig = options.config ? options.config : options.configurable ? { configurable: options.configurable } : void 0;
1861
- if (newConfig === void 0)
1862
- return;
1863
- setCoagentStatesWithRef((prev) => {
1864
- var _a;
1865
- const existing = (_a = prev[name]) != null ? _a : {
1866
- name,
1867
- state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
1868
- config: {},
1869
- running: false,
1870
- active: false,
146
+ const initialState = (
147
+ // prefer externally provided state if available
148
+ (_b = (_a = "state" in options && options.state) != null ? _a : (
149
+ // then initialState if provided
150
+ "initialState" in options && options.initialState
151
+ )) != null ? _b : {}
152
+ );
153
+ return {
154
+ name: options.name,
155
+ nodeName: nodeNameRef.current,
1871
156
  threadId: void 0,
1872
- nodeName: void 0,
1873
- runId: void 0
157
+ running: false,
158
+ state: initialState,
159
+ setState: noop,
160
+ start: noop,
161
+ stop: noop,
162
+ run: noopAsync
1874
163
  };
1875
- if (JSON.stringify(existing.config) === JSON.stringify(newConfig)) {
1876
- return prev;
1877
- }
1878
- return __spreadProps(__spreadValues({}, prev), {
1879
- [name]: __spreadProps(__spreadValues({}, existing), {
1880
- config: newConfig
1881
- })
1882
- });
1883
- });
1884
- }, [JSON.stringify(options.config), JSON.stringify(options.configurable)]);
1885
- const runAgentCallback = useAsyncCallback(
1886
- (hint) => __async(this, null, function* () {
1887
- yield runAgent(name, context, getMessagesFromTap(), sendMessage, runChatCompletion, hint);
1888
- }),
1889
- [name, context, sendMessage, runChatCompletion]
1890
- );
1891
- return (0, import_react11.useMemo)(() => {
1892
- const coagentState = getCoagentState({ coagentStates, name, options });
164
+ }
1893
165
  return {
1894
- name,
1895
- nodeName: coagentState.nodeName,
1896
- threadId: coagentState.threadId,
1897
- running: coagentState.running,
1898
- state: coagentState.state,
1899
- setState: isExternalStateManagement(options) ? options.setState : setState,
1900
- start: () => startAgent(name, context),
1901
- stop: () => stopAgent(name, context),
1902
- run: runAgentCallback
166
+ name: (_c = agent == null ? void 0 : agent.agentId) != null ? _c : options.name,
167
+ nodeName: nodeNameRef.current,
168
+ threadId: agent.threadId,
169
+ running: agent.isRunning,
170
+ state: agent.state,
171
+ setState: handleStateUpdate,
172
+ // TODO: start and run both have same thing. need to figure out
173
+ start: agent.runAgent,
174
+ stop: agent.abortRun,
175
+ run: agent.runAgent
1903
176
  };
1904
- }, [name, coagentStates, options, setState, runAgentCallback]);
1905
- }
1906
- function startAgent(name, context) {
1907
- const { setAgentSession } = context;
1908
- setAgentSession({
1909
- agentName: name
1910
- });
1911
- }
1912
- function stopAgent(name, context) {
1913
- const { agentSession, setAgentSession } = context;
1914
- if (agentSession && agentSession.agentName === name) {
1915
- setAgentSession(null);
1916
- context.setCoagentStates((prevAgentStates) => {
1917
- return __spreadProps(__spreadValues({}, prevAgentStates), {
1918
- [name]: __spreadProps(__spreadValues({}, prevAgentStates[name]), {
1919
- running: false,
1920
- active: false,
1921
- threadId: void 0,
1922
- nodeName: void 0,
1923
- runId: void 0
1924
- })
1925
- });
1926
- });
1927
- } else {
1928
- console.warn(`No agent session found for ${name}`);
1929
- }
1930
- }
1931
- function runAgent(name, context, messages, sendMessage, runChatCompletion, hint) {
1932
- return __async(this, null, function* () {
1933
- var _a, _b;
1934
- const { agentSession, setAgentSession } = context;
1935
- if (!agentSession || agentSession.agentName !== name) {
1936
- setAgentSession({
1937
- agentName: name
1938
- });
1939
- }
1940
- let previousState = null;
1941
- for (let i = messages.length - 1; i >= 0; i--) {
1942
- const message = messages[i];
1943
- if (message.isAgentStateMessage() && message.agentName === name) {
1944
- previousState = message.state;
1945
- }
1946
- }
1947
- let state = ((_b = (_a = context.coagentStatesRef.current) == null ? void 0 : _a[name]) == null ? void 0 : _b.state) || {};
1948
- if (hint) {
1949
- const hintMessage = hint({ previousState, currentState: state });
1950
- if (hintMessage) {
1951
- yield sendMessage(hintMessage);
1952
- } else {
1953
- yield runChatCompletion();
1954
- }
1955
- } else {
1956
- yield runChatCompletion();
1957
- }
1958
- });
177
+ }, [
178
+ agent == null ? void 0 : agent.state,
179
+ agent == null ? void 0 : agent.runAgent,
180
+ agent == null ? void 0 : agent.abortRun,
181
+ agent == null ? void 0 : agent.runAgent,
182
+ agent == null ? void 0 : agent.threadId,
183
+ agent == null ? void 0 : agent.isRunning,
184
+ agent == null ? void 0 : agent.agentId,
185
+ handleStateUpdate,
186
+ options.name
187
+ ]);
1959
188
  }
1960
189
  var isExternalStateManagement = (options) => {
1961
190
  return "state" in options && "setState" in options;
1962
191
  };
1963
- var isInternalStateManagementWithInitial = (options) => {
1964
- return "initialState" in options;
1965
- };
1966
- var getCoagentState = ({
1967
- coagentStates,
1968
- name,
1969
- options
1970
- }) => {
1971
- if (coagentStates[name]) {
1972
- return coagentStates[name];
1973
- } else {
1974
- return {
1975
- name,
1976
- state: isInternalStateManagementWithInitial(options) ? options.initialState : {},
1977
- config: options.config ? options.config : options.configurable ? { configurable: options.configurable } : {},
1978
- running: false,
1979
- active: false,
1980
- threadId: void 0,
1981
- nodeName: void 0,
1982
- runId: void 0
1983
- };
1984
- }
1985
- };
1986
192
  // Annotate the CommonJS export names for ESM import in node:
1987
193
  0 && (module.exports = {
1988
- runAgent,
1989
- startAgent,
1990
- stopAgent,
1991
194
  useCoAgent
1992
195
  });
1993
196
  //# sourceMappingURL=use-coagent.js.map