@copilotkit/react-core 0.0.0-fix-debug-infosys-20251107162427 → 0.0.0-fix-restore-handle-method-node-http-20260105204107

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