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