@copilotkit/react-core 1.51.4 → 1.51.5-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (474) hide show
  1. package/.attw.json +3 -0
  2. package/CHANGELOG.md +21 -0
  3. package/dist/index.cjs +4010 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +1327 -0
  6. package/dist/index.d.cts.map +1 -0
  7. package/dist/index.d.mts +1327 -0
  8. package/dist/index.d.mts.map +1 -0
  9. package/dist/index.mjs +3944 -148
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/index.umd.js +4075 -39
  12. package/dist/index.umd.js.map +1 -1
  13. package/dist/v2/index.cjs +17 -0
  14. package/dist/v2/index.css +2 -3
  15. package/dist/v2/index.css.map +1 -1
  16. package/dist/v2/index.d.cts +2 -0
  17. package/dist/v2/index.d.mts +2 -0
  18. package/dist/v2/index.mjs +4 -5
  19. package/dist/v2/index.umd.js +24 -2
  20. package/package.json +22 -22
  21. package/src/components/copilot-provider/__tests__/copilotkit-error.test.tsx +3 -3
  22. package/src/hooks/__tests__/use-coagent-config.test.ts +23 -22
  23. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +33 -35
  24. package/src/hooks/__tests__/use-coagent-state-render.test.tsx +19 -18
  25. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +72 -0
  26. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +9 -7
  27. package/src/hooks/use-copilot-chat.ts +1 -1
  28. package/src/hooks/use-frontend-tool.ts +2 -1
  29. package/src/lib/copilot-task.ts +1 -1
  30. package/src/setupTests.ts +17 -16
  31. package/tsconfig.json +1 -1
  32. package/tsdown.config.ts +94 -0
  33. package/vitest.config.mjs +30 -0
  34. package/dist/chunk-2IDV5OHF.mjs +0 -11
  35. package/dist/chunk-2IDV5OHF.mjs.map +0 -1
  36. package/dist/chunk-2RSAYTXH.mjs +0 -137
  37. package/dist/chunk-2RSAYTXH.mjs.map +0 -1
  38. package/dist/chunk-36KQV2NA.mjs +0 -1
  39. package/dist/chunk-36KQV2NA.mjs.map +0 -1
  40. package/dist/chunk-3LZZ4RVM.mjs +0 -37
  41. package/dist/chunk-3LZZ4RVM.mjs.map +0 -1
  42. package/dist/chunk-4ZQYMC5F.mjs +0 -36
  43. package/dist/chunk-4ZQYMC5F.mjs.map +0 -1
  44. package/dist/chunk-6ABVYB2U.mjs +0 -95
  45. package/dist/chunk-6ABVYB2U.mjs.map +0 -1
  46. package/dist/chunk-6AWG5FWL.mjs +0 -102
  47. package/dist/chunk-6AWG5FWL.mjs.map +0 -1
  48. package/dist/chunk-6YOKPWQ7.mjs +0 -1
  49. package/dist/chunk-6YOKPWQ7.mjs.map +0 -1
  50. package/dist/chunk-7GIBHX6X.mjs +0 -195
  51. package/dist/chunk-7GIBHX6X.mjs.map +0 -1
  52. package/dist/chunk-7PJKPWMD.mjs +0 -112
  53. package/dist/chunk-7PJKPWMD.mjs.map +0 -1
  54. package/dist/chunk-7U3DNFBF.mjs +0 -20
  55. package/dist/chunk-7U3DNFBF.mjs.map +0 -1
  56. package/dist/chunk-A6NKSGH3.mjs +0 -1
  57. package/dist/chunk-A6NKSGH3.mjs.map +0 -1
  58. package/dist/chunk-AAGMWZCN.mjs +0 -439
  59. package/dist/chunk-AAGMWZCN.mjs.map +0 -1
  60. package/dist/chunk-C7HSVDHD.mjs +0 -116
  61. package/dist/chunk-C7HSVDHD.mjs.map +0 -1
  62. package/dist/chunk-CYDWEPFL.mjs +0 -1
  63. package/dist/chunk-CYDWEPFL.mjs.map +0 -1
  64. package/dist/chunk-CZT7JUIM.mjs +0 -153
  65. package/dist/chunk-CZT7JUIM.mjs.map +0 -1
  66. package/dist/chunk-DMLQZG75.mjs +0 -25
  67. package/dist/chunk-DMLQZG75.mjs.map +0 -1
  68. package/dist/chunk-FD6FGKYY.mjs +0 -1
  69. package/dist/chunk-FD6FGKYY.mjs.map +0 -1
  70. package/dist/chunk-G7SUZGGB.mjs +0 -126
  71. package/dist/chunk-G7SUZGGB.mjs.map +0 -1
  72. package/dist/chunk-GY3FQICF.mjs +0 -23
  73. package/dist/chunk-GY3FQICF.mjs.map +0 -1
  74. package/dist/chunk-I76HKHPJ.mjs +0 -32
  75. package/dist/chunk-I76HKHPJ.mjs.map +0 -1
  76. package/dist/chunk-ICIK2BSB.mjs +0 -17
  77. package/dist/chunk-ICIK2BSB.mjs.map +0 -1
  78. package/dist/chunk-IHMMKEFG.mjs +0 -64
  79. package/dist/chunk-IHMMKEFG.mjs.map +0 -1
  80. package/dist/chunk-JD7BAH7U.mjs +0 -1
  81. package/dist/chunk-JD7BAH7U.mjs.map +0 -1
  82. package/dist/chunk-K5OXUXCG.mjs +0 -76
  83. package/dist/chunk-K5OXUXCG.mjs.map +0 -1
  84. package/dist/chunk-L7GPCF2V.mjs +0 -229
  85. package/dist/chunk-L7GPCF2V.mjs.map +0 -1
  86. package/dist/chunk-LD34IXVT.mjs +0 -86
  87. package/dist/chunk-LD34IXVT.mjs.map +0 -1
  88. package/dist/chunk-LNGBARXE.mjs +0 -86
  89. package/dist/chunk-LNGBARXE.mjs.map +0 -1
  90. package/dist/chunk-LRPWSPXG.mjs +0 -628
  91. package/dist/chunk-LRPWSPXG.mjs.map +0 -1
  92. package/dist/chunk-LUGEI4YQ.mjs +0 -1
  93. package/dist/chunk-LUGEI4YQ.mjs.map +0 -1
  94. package/dist/chunk-MBJ7OLYI.mjs +0 -58
  95. package/dist/chunk-MBJ7OLYI.mjs.map +0 -1
  96. package/dist/chunk-NB2FKV2V.mjs +0 -1
  97. package/dist/chunk-NB2FKV2V.mjs.map +0 -1
  98. package/dist/chunk-O7ARI5CV.mjs +0 -31
  99. package/dist/chunk-O7ARI5CV.mjs.map +0 -1
  100. package/dist/chunk-P6ZPE4XJ.mjs +0 -86
  101. package/dist/chunk-P6ZPE4XJ.mjs.map +0 -1
  102. package/dist/chunk-QXZTCGF4.mjs +0 -163
  103. package/dist/chunk-QXZTCGF4.mjs.map +0 -1
  104. package/dist/chunk-R2DP4APC.mjs +0 -125
  105. package/dist/chunk-R2DP4APC.mjs.map +0 -1
  106. package/dist/chunk-R7BV32X4.mjs +0 -146
  107. package/dist/chunk-R7BV32X4.mjs.map +0 -1
  108. package/dist/chunk-SBRCWA4S.mjs +0 -913
  109. package/dist/chunk-SBRCWA4S.mjs.map +0 -1
  110. package/dist/chunk-SK2XMJUD.mjs +0 -42
  111. package/dist/chunk-SK2XMJUD.mjs.map +0 -1
  112. package/dist/chunk-SKC7AJIV.mjs +0 -61
  113. package/dist/chunk-SKC7AJIV.mjs.map +0 -1
  114. package/dist/chunk-SLM6CLAH.mjs +0 -195
  115. package/dist/chunk-SLM6CLAH.mjs.map +0 -1
  116. package/dist/chunk-SPCZTZCY.mjs +0 -1
  117. package/dist/chunk-SPCZTZCY.mjs.map +0 -1
  118. package/dist/chunk-SYGQHN3H.mjs +0 -27
  119. package/dist/chunk-SYGQHN3H.mjs.map +0 -1
  120. package/dist/chunk-SYMT73HM.mjs +0 -43
  121. package/dist/chunk-SYMT73HM.mjs.map +0 -1
  122. package/dist/chunk-TFZXOEY4.mjs +0 -61
  123. package/dist/chunk-TFZXOEY4.mjs.map +0 -1
  124. package/dist/chunk-TPN7WC53.mjs +0 -33
  125. package/dist/chunk-TPN7WC53.mjs.map +0 -1
  126. package/dist/chunk-UA23VX5J.mjs +0 -65
  127. package/dist/chunk-UA23VX5J.mjs.map +0 -1
  128. package/dist/chunk-V42VL2JR.mjs +0 -136
  129. package/dist/chunk-V42VL2JR.mjs.map +0 -1
  130. package/dist/chunk-VZ4NSOFQ.mjs +0 -80
  131. package/dist/chunk-VZ4NSOFQ.mjs.map +0 -1
  132. package/dist/chunk-WRALJIW5.mjs +0 -79
  133. package/dist/chunk-WRALJIW5.mjs.map +0 -1
  134. package/dist/chunk-WV2EA7SX.mjs +0 -65
  135. package/dist/chunk-WV2EA7SX.mjs.map +0 -1
  136. package/dist/chunk-Z6JV2LRY.mjs +0 -37
  137. package/dist/chunk-Z6JV2LRY.mjs.map +0 -1
  138. package/dist/chunk-ZP2IMXFY.mjs +0 -316
  139. package/dist/chunk-ZP2IMXFY.mjs.map +0 -1
  140. package/dist/chunk-ZVF5Q6IH.mjs +0 -29
  141. package/dist/chunk-ZVF5Q6IH.mjs.map +0 -1
  142. package/dist/components/CopilotListeners.d.ts +0 -3
  143. package/dist/components/CopilotListeners.js +0 -110
  144. package/dist/components/CopilotListeners.js.map +0 -1
  145. package/dist/components/CopilotListeners.mjs +0 -9
  146. package/dist/components/CopilotListeners.mjs.map +0 -1
  147. package/dist/components/copilot-provider/copilot-messages.d.ts +0 -24
  148. package/dist/components/copilot-provider/copilot-messages.js +0 -366
  149. package/dist/components/copilot-provider/copilot-messages.js.map +0 -1
  150. package/dist/components/copilot-provider/copilot-messages.mjs +0 -16
  151. package/dist/components/copilot-provider/copilot-messages.mjs.map +0 -1
  152. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -180
  153. package/dist/components/copilot-provider/copilotkit-props.js +0 -19
  154. package/dist/components/copilot-provider/copilotkit-props.js.map +0 -1
  155. package/dist/components/copilot-provider/copilotkit-props.mjs +0 -1
  156. package/dist/components/copilot-provider/copilotkit-props.mjs.map +0 -1
  157. package/dist/components/copilot-provider/copilotkit.d.ts +0 -19
  158. package/dist/components/copilot-provider/copilotkit.js +0 -2348
  159. package/dist/components/copilot-provider/copilotkit.js.map +0 -1
  160. package/dist/components/copilot-provider/copilotkit.mjs +0 -33
  161. package/dist/components/copilot-provider/copilotkit.mjs.map +0 -1
  162. package/dist/components/copilot-provider/index.d.ts +0 -14
  163. package/dist/components/copilot-provider/index.js +0 -2348
  164. package/dist/components/copilot-provider/index.js.map +0 -1
  165. package/dist/components/copilot-provider/index.mjs +0 -32
  166. package/dist/components/copilot-provider/index.mjs.map +0 -1
  167. package/dist/components/dev-console/console-trigger.d.ts +0 -8
  168. package/dist/components/dev-console/console-trigger.js +0 -1387
  169. package/dist/components/dev-console/console-trigger.js.map +0 -1
  170. package/dist/components/dev-console/console-trigger.mjs +0 -249
  171. package/dist/components/dev-console/console-trigger.mjs.map +0 -1
  172. package/dist/components/dev-console/developer-console-modal.d.ts +0 -10
  173. package/dist/components/dev-console/developer-console-modal.js +0 -1156
  174. package/dist/components/dev-console/developer-console-modal.js.map +0 -1
  175. package/dist/components/dev-console/developer-console-modal.mjs +0 -12
  176. package/dist/components/dev-console/developer-console-modal.mjs.map +0 -1
  177. package/dist/components/dev-console/icons.d.ts +0 -9
  178. package/dist/components/dev-console/icons.js +0 -140
  179. package/dist/components/dev-console/icons.js.map +0 -1
  180. package/dist/components/dev-console/icons.mjs +0 -16
  181. package/dist/components/dev-console/icons.mjs.map +0 -1
  182. package/dist/components/error-boundary/error-boundary.d.ts +0 -31
  183. package/dist/components/error-boundary/error-boundary.js +0 -507
  184. package/dist/components/error-boundary/error-boundary.js.map +0 -1
  185. package/dist/components/error-boundary/error-boundary.mjs +0 -15
  186. package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
  187. package/dist/components/error-boundary/error-utils.d.ts +0 -11
  188. package/dist/components/error-boundary/error-utils.js +0 -190
  189. package/dist/components/error-boundary/error-utils.js.map +0 -1
  190. package/dist/components/error-boundary/error-utils.mjs +0 -14
  191. package/dist/components/error-boundary/error-utils.mjs.map +0 -1
  192. package/dist/components/index.d.ts +0 -14
  193. package/dist/components/index.js +0 -2348
  194. package/dist/components/index.js.map +0 -1
  195. package/dist/components/index.mjs +0 -33
  196. package/dist/components/index.mjs.map +0 -1
  197. package/dist/components/toast/exclamation-mark-icon.d.ts +0 -9
  198. package/dist/components/toast/exclamation-mark-icon.js +0 -55
  199. package/dist/components/toast/exclamation-mark-icon.js.map +0 -1
  200. package/dist/components/toast/exclamation-mark-icon.mjs +0 -8
  201. package/dist/components/toast/exclamation-mark-icon.mjs.map +0 -1
  202. package/dist/components/toast/toast-provider.d.ts +0 -27
  203. package/dist/components/toast/toast-provider.js +0 -353
  204. package/dist/components/toast/toast-provider.js.map +0 -1
  205. package/dist/components/toast/toast-provider.mjs +0 -10
  206. package/dist/components/toast/toast-provider.mjs.map +0 -1
  207. package/dist/components/usage-banner.d.ts +0 -29
  208. package/dist/components/usage-banner.js +0 -251
  209. package/dist/components/usage-banner.js.map +0 -1
  210. package/dist/components/usage-banner.mjs +0 -12
  211. package/dist/components/usage-banner.mjs.map +0 -1
  212. package/dist/context/coagent-state-renders-context.d.ts +0 -25
  213. package/dist/context/coagent-state-renders-context.js +0 -96
  214. package/dist/context/coagent-state-renders-context.js.map +0 -1
  215. package/dist/context/coagent-state-renders-context.mjs +0 -12
  216. package/dist/context/coagent-state-renders-context.mjs.map +0 -1
  217. package/dist/context/copilot-context.d.ts +0 -10
  218. package/dist/context/copilot-context.js +0 -167
  219. package/dist/context/copilot-context.js.map +0 -1
  220. package/dist/context/copilot-context.mjs +0 -10
  221. package/dist/context/copilot-context.mjs.map +0 -1
  222. package/dist/context/copilot-messages-context.d.ts +0 -18
  223. package/dist/context/copilot-messages-context.js +0 -60
  224. package/dist/context/copilot-messages-context.js.map +0 -1
  225. package/dist/context/copilot-messages-context.mjs +0 -10
  226. package/dist/context/copilot-messages-context.mjs.map +0 -1
  227. package/dist/context/index.d.ts +0 -15
  228. package/dist/context/index.js +0 -301
  229. package/dist/context/index.js.map +0 -1
  230. package/dist/context/index.mjs +0 -33
  231. package/dist/context/index.mjs.map +0 -1
  232. package/dist/context/threads-context.d.ts +0 -16
  233. package/dist/context/threads-context.js +0 -64
  234. package/dist/context/threads-context.js.map +0 -1
  235. package/dist/context/threads-context.mjs +0 -12
  236. package/dist/context/threads-context.mjs.map +0 -1
  237. package/dist/copilot-context-ec77e921.d.ts +0 -209
  238. package/dist/hooks/index.d.ts +0 -33
  239. package/dist/hooks/index.js +0 -2190
  240. package/dist/hooks/index.js.map +0 -1
  241. package/dist/hooks/index.mjs +0 -93
  242. package/dist/hooks/index.mjs.map +0 -1
  243. package/dist/hooks/use-agent-nodename.d.ts +0 -3
  244. package/dist/hooks/use-agent-nodename.js +0 -56
  245. package/dist/hooks/use-agent-nodename.js.map +0 -1
  246. package/dist/hooks/use-agent-nodename.mjs +0 -8
  247. package/dist/hooks/use-agent-nodename.mjs.map +0 -1
  248. package/dist/hooks/use-coagent-state-render-bridge.d.ts +0 -100
  249. package/dist/hooks/use-coagent-state-render-bridge.helpers.d.ts +0 -92
  250. package/dist/hooks/use-coagent-state-render-bridge.helpers.js +0 -237
  251. package/dist/hooks/use-coagent-state-render-bridge.helpers.js.map +0 -1
  252. package/dist/hooks/use-coagent-state-render-bridge.helpers.mjs +0 -24
  253. package/dist/hooks/use-coagent-state-render-bridge.helpers.mjs.map +0 -1
  254. package/dist/hooks/use-coagent-state-render-bridge.js +0 -498
  255. package/dist/hooks/use-coagent-state-render-bridge.js.map +0 -1
  256. package/dist/hooks/use-coagent-state-render-bridge.mjs +0 -17
  257. package/dist/hooks/use-coagent-state-render-bridge.mjs.map +0 -1
  258. package/dist/hooks/use-coagent-state-render-registry.d.ts +0 -25
  259. package/dist/hooks/use-coagent-state-render-registry.js +0 -369
  260. package/dist/hooks/use-coagent-state-render-registry.js.map +0 -1
  261. package/dist/hooks/use-coagent-state-render-registry.mjs +0 -9
  262. package/dist/hooks/use-coagent-state-render-registry.mjs.map +0 -1
  263. package/dist/hooks/use-coagent-state-render.d.ts +0 -55
  264. package/dist/hooks/use-coagent-state-render.js +0 -268
  265. package/dist/hooks/use-coagent-state-render.js.map +0 -1
  266. package/dist/hooks/use-coagent-state-render.mjs +0 -11
  267. package/dist/hooks/use-coagent-state-render.mjs.map +0 -1
  268. package/dist/hooks/use-coagent.d.ts +0 -192
  269. package/dist/hooks/use-coagent.js +0 -235
  270. package/dist/hooks/use-coagent.js.map +0 -1
  271. package/dist/hooks/use-coagent.mjs +0 -9
  272. package/dist/hooks/use-coagent.mjs.map +0 -1
  273. package/dist/hooks/use-configure-chat-suggestions.d.ts +0 -36
  274. package/dist/hooks/use-configure-chat-suggestions.js +0 -79
  275. package/dist/hooks/use-configure-chat-suggestions.js.map +0 -1
  276. package/dist/hooks/use-configure-chat-suggestions.mjs +0 -47
  277. package/dist/hooks/use-configure-chat-suggestions.mjs.map +0 -1
  278. package/dist/hooks/use-copilot-action.d.ts +0 -103
  279. package/dist/hooks/use-copilot-action.js +0 -302
  280. package/dist/hooks/use-copilot-action.js.map +0 -1
  281. package/dist/hooks/use-copilot-action.mjs +0 -11
  282. package/dist/hooks/use-copilot-action.mjs.map +0 -1
  283. package/dist/hooks/use-copilot-additional-instructions.d.ts +0 -26
  284. package/dist/hooks/use-copilot-additional-instructions.js +0 -196
  285. package/dist/hooks/use-copilot-additional-instructions.js.map +0 -1
  286. package/dist/hooks/use-copilot-additional-instructions.mjs +0 -9
  287. package/dist/hooks/use-copilot-additional-instructions.mjs.map +0 -1
  288. package/dist/hooks/use-copilot-authenticated-action.d.ts +0 -18
  289. package/dist/hooks/use-copilot-authenticated-action.js +0 -477
  290. package/dist/hooks/use-copilot-authenticated-action.js.map +0 -1
  291. package/dist/hooks/use-copilot-authenticated-action.mjs +0 -13
  292. package/dist/hooks/use-copilot-authenticated-action.mjs.map +0 -1
  293. package/dist/hooks/use-copilot-chat-headless_c.d.ts +0 -25
  294. package/dist/hooks/use-copilot-chat-headless_c.js +0 -1410
  295. package/dist/hooks/use-copilot-chat-headless_c.js.map +0 -1
  296. package/dist/hooks/use-copilot-chat-headless_c.mjs +0 -26
  297. package/dist/hooks/use-copilot-chat-headless_c.mjs.map +0 -1
  298. package/dist/hooks/use-copilot-chat-suggestions.d.ts +0 -35
  299. package/dist/hooks/use-copilot-chat-suggestions.js +0 -60
  300. package/dist/hooks/use-copilot-chat-suggestions.js.map +0 -1
  301. package/dist/hooks/use-copilot-chat-suggestions.mjs +0 -8
  302. package/dist/hooks/use-copilot-chat-suggestions.mjs.map +0 -1
  303. package/dist/hooks/use-copilot-chat.d.ts +0 -92
  304. package/dist/hooks/use-copilot-chat.js +0 -1344
  305. package/dist/hooks/use-copilot-chat.js.map +0 -1
  306. package/dist/hooks/use-copilot-chat.mjs +0 -23
  307. package/dist/hooks/use-copilot-chat.mjs.map +0 -1
  308. package/dist/hooks/use-copilot-chat_internal.d.ts +0 -244
  309. package/dist/hooks/use-copilot-chat_internal.js +0 -1342
  310. package/dist/hooks/use-copilot-chat_internal.js.map +0 -1
  311. package/dist/hooks/use-copilot-chat_internal.mjs +0 -24
  312. package/dist/hooks/use-copilot-chat_internal.mjs.map +0 -1
  313. package/dist/hooks/use-copilot-readable.d.ts +0 -37
  314. package/dist/hooks/use-copilot-readable.js +0 -61
  315. package/dist/hooks/use-copilot-readable.js.map +0 -1
  316. package/dist/hooks/use-copilot-readable.mjs +0 -8
  317. package/dist/hooks/use-copilot-readable.mjs.map +0 -1
  318. package/dist/hooks/use-copilot-runtime-client.d.ts +0 -10
  319. package/dist/hooks/use-copilot-runtime-client.js +0 -206
  320. package/dist/hooks/use-copilot-runtime-client.js.map +0 -1
  321. package/dist/hooks/use-copilot-runtime-client.mjs +0 -9
  322. package/dist/hooks/use-copilot-runtime-client.mjs.map +0 -1
  323. package/dist/hooks/use-default-tool.d.ts +0 -8
  324. package/dist/hooks/use-default-tool.js +0 -312
  325. package/dist/hooks/use-default-tool.js.map +0 -1
  326. package/dist/hooks/use-default-tool.mjs +0 -12
  327. package/dist/hooks/use-default-tool.mjs.map +0 -1
  328. package/dist/hooks/use-flat-category-store.d.ts +0 -9
  329. package/dist/hooks/use-flat-category-store.js +0 -96
  330. package/dist/hooks/use-flat-category-store.js.map +0 -1
  331. package/dist/hooks/use-flat-category-store.mjs +0 -8
  332. package/dist/hooks/use-flat-category-store.mjs.map +0 -1
  333. package/dist/hooks/use-frontend-tool.d.ts +0 -11
  334. package/dist/hooks/use-frontend-tool.js +0 -107
  335. package/dist/hooks/use-frontend-tool.js.map +0 -1
  336. package/dist/hooks/use-frontend-tool.mjs +0 -8
  337. package/dist/hooks/use-frontend-tool.mjs.map +0 -1
  338. package/dist/hooks/use-human-in-the-loop.d.ts +0 -13
  339. package/dist/hooks/use-human-in-the-loop.js +0 -122
  340. package/dist/hooks/use-human-in-the-loop.js.map +0 -1
  341. package/dist/hooks/use-human-in-the-loop.mjs +0 -8
  342. package/dist/hooks/use-human-in-the-loop.mjs.map +0 -1
  343. package/dist/hooks/use-langgraph-interrupt-render.d.ts +0 -6
  344. package/dist/hooks/use-langgraph-interrupt-render.js +0 -335
  345. package/dist/hooks/use-langgraph-interrupt-render.js.map +0 -1
  346. package/dist/hooks/use-langgraph-interrupt-render.mjs +0 -14
  347. package/dist/hooks/use-langgraph-interrupt-render.mjs.map +0 -1
  348. package/dist/hooks/use-langgraph-interrupt.d.ts +0 -14
  349. package/dist/hooks/use-langgraph-interrupt.js +0 -216
  350. package/dist/hooks/use-langgraph-interrupt.js.map +0 -1
  351. package/dist/hooks/use-langgraph-interrupt.mjs +0 -10
  352. package/dist/hooks/use-langgraph-interrupt.mjs.map +0 -1
  353. package/dist/hooks/use-lazy-tool-renderer.d.ts +0 -6
  354. package/dist/hooks/use-lazy-tool-renderer.js +0 -53
  355. package/dist/hooks/use-lazy-tool-renderer.js.map +0 -1
  356. package/dist/hooks/use-lazy-tool-renderer.mjs +0 -8
  357. package/dist/hooks/use-lazy-tool-renderer.mjs.map +0 -1
  358. package/dist/hooks/use-make-copilot-document-readable.d.ts +0 -12
  359. package/dist/hooks/use-make-copilot-document-readable.js +0 -182
  360. package/dist/hooks/use-make-copilot-document-readable.js.map +0 -1
  361. package/dist/hooks/use-make-copilot-document-readable.mjs +0 -9
  362. package/dist/hooks/use-make-copilot-document-readable.mjs.map +0 -1
  363. package/dist/hooks/use-render-tool-call.d.ts +0 -12
  364. package/dist/hooks/use-render-tool-call.js +0 -94
  365. package/dist/hooks/use-render-tool-call.js.map +0 -1
  366. package/dist/hooks/use-render-tool-call.mjs +0 -8
  367. package/dist/hooks/use-render-tool-call.mjs.map +0 -1
  368. package/dist/hooks/use-tree.d.ts +0 -19
  369. package/dist/hooks/use-tree.js +0 -178
  370. package/dist/hooks/use-tree.js.map +0 -1
  371. package/dist/hooks/use-tree.mjs +0 -8
  372. package/dist/hooks/use-tree.mjs.map +0 -1
  373. package/dist/index.d.ts +0 -43
  374. package/dist/index.js +0 -4064
  375. package/dist/index.js.map +0 -1
  376. package/dist/lib/copilot-task.d.ts +0 -97
  377. package/dist/lib/copilot-task.js +0 -201
  378. package/dist/lib/copilot-task.js.map +0 -1
  379. package/dist/lib/copilot-task.mjs +0 -33
  380. package/dist/lib/copilot-task.mjs.map +0 -1
  381. package/dist/lib/index.d.ts +0 -11
  382. package/dist/lib/index.js +0 -203
  383. package/dist/lib/index.js.map +0 -1
  384. package/dist/lib/index.mjs +0 -34
  385. package/dist/lib/index.mjs.map +0 -1
  386. package/dist/lib/status-checker.d.ts +0 -17
  387. package/dist/lib/status-checker.js +0 -102
  388. package/dist/lib/status-checker.js.map +0 -1
  389. package/dist/lib/status-checker.mjs +0 -8
  390. package/dist/lib/status-checker.mjs.map +0 -1
  391. package/dist/setupTests.d.ts +0 -2
  392. package/dist/setupTests.js +0 -31
  393. package/dist/setupTests.js.map +0 -1
  394. package/dist/setupTests.mjs +0 -29
  395. package/dist/setupTests.mjs.map +0 -1
  396. package/dist/test-helpers/copilot-context.d.ts +0 -14
  397. package/dist/test-helpers/copilot-context.js +0 -128
  398. package/dist/test-helpers/copilot-context.js.map +0 -1
  399. package/dist/test-helpers/copilot-context.mjs +0 -74
  400. package/dist/test-helpers/copilot-context.mjs.map +0 -1
  401. package/dist/types/chat-suggestion-configuration.d.ts +0 -22
  402. package/dist/types/chat-suggestion-configuration.js +0 -19
  403. package/dist/types/chat-suggestion-configuration.js.map +0 -1
  404. package/dist/types/chat-suggestion-configuration.mjs +0 -1
  405. package/dist/types/chat-suggestion-configuration.mjs.map +0 -1
  406. package/dist/types/coagent-action.d.ts +0 -29
  407. package/dist/types/coagent-action.js +0 -19
  408. package/dist/types/coagent-action.js.map +0 -1
  409. package/dist/types/coagent-action.mjs +0 -1
  410. package/dist/types/coagent-action.mjs.map +0 -1
  411. package/dist/types/coagent-state.d.ts +0 -15
  412. package/dist/types/coagent-state.js +0 -19
  413. package/dist/types/coagent-state.js.map +0 -1
  414. package/dist/types/coagent-state.mjs +0 -1
  415. package/dist/types/coagent-state.mjs.map +0 -1
  416. package/dist/types/crew.d.ts +0 -79
  417. package/dist/types/crew.js +0 -19
  418. package/dist/types/crew.js.map +0 -1
  419. package/dist/types/crew.mjs +0 -2
  420. package/dist/types/crew.mjs.map +0 -1
  421. package/dist/types/document-pointer.d.ts +0 -9
  422. package/dist/types/document-pointer.js +0 -19
  423. package/dist/types/document-pointer.js.map +0 -1
  424. package/dist/types/document-pointer.mjs +0 -1
  425. package/dist/types/document-pointer.mjs.map +0 -1
  426. package/dist/types/frontend-action.d.ts +0 -127
  427. package/dist/types/frontend-action.js +0 -55
  428. package/dist/types/frontend-action.js.map +0 -1
  429. package/dist/types/frontend-action.mjs +0 -8
  430. package/dist/types/frontend-action.mjs.map +0 -1
  431. package/dist/types/index.d.ts +0 -12
  432. package/dist/types/index.js +0 -19
  433. package/dist/types/index.js.map +0 -1
  434. package/dist/types/index.mjs +0 -4
  435. package/dist/types/index.mjs.map +0 -1
  436. package/dist/types/interrupt-action.d.ts +0 -10
  437. package/dist/types/interrupt-action.js +0 -19
  438. package/dist/types/interrupt-action.js.map +0 -1
  439. package/dist/types/interrupt-action.mjs +0 -2
  440. package/dist/types/interrupt-action.mjs.map +0 -1
  441. package/dist/types/system-message.d.ts +0 -3
  442. package/dist/types/system-message.js +0 -19
  443. package/dist/types/system-message.js.map +0 -1
  444. package/dist/types/system-message.mjs +0 -1
  445. package/dist/types/system-message.mjs.map +0 -1
  446. package/dist/utils/dev-console.d.ts +0 -3
  447. package/dist/utils/dev-console.js +0 -41
  448. package/dist/utils/dev-console.js.map +0 -1
  449. package/dist/utils/dev-console.mjs +0 -8
  450. package/dist/utils/dev-console.mjs.map +0 -1
  451. package/dist/utils/index.d.ts +0 -2
  452. package/dist/utils/index.js +0 -52
  453. package/dist/utils/index.js.map +0 -1
  454. package/dist/utils/index.mjs +0 -13
  455. package/dist/utils/index.mjs.map +0 -1
  456. package/dist/utils/suggestions-constants.d.ts +0 -9
  457. package/dist/utils/suggestions-constants.js +0 -35
  458. package/dist/utils/suggestions-constants.js.map +0 -1
  459. package/dist/utils/suggestions-constants.mjs +0 -8
  460. package/dist/utils/suggestions-constants.mjs.map +0 -1
  461. package/dist/utils/utils.d.ts +0 -2
  462. package/dist/utils/utils.js +0 -19
  463. package/dist/utils/utils.js.map +0 -1
  464. package/dist/utils/utils.mjs +0 -1
  465. package/dist/utils/utils.mjs.map +0 -1
  466. package/dist/v2/index.d.ts +0 -2
  467. package/dist/v2/index.js +0 -27
  468. package/dist/v2/index.js.map +0 -1
  469. package/dist/v2/index.mjs.map +0 -1
  470. package/dist/v2/index.umd.js.map +0 -1
  471. package/jest.config.js +0 -26
  472. package/rollup.config.mjs +0 -92
  473. package/src/__mocks__/analytics-node.js +0 -9
  474. package/tsup.config.ts +0 -16
package/dist/index.cjs ADDED
@@ -0,0 +1,4010 @@
1
+ "use client";
2
+
3
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
4
+ //#region \0rolldown/runtime.js
5
+ var __create = Object.create;
6
+ var __defProp = Object.defineProperty;
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __getOwnPropNames = Object.getOwnPropertyNames;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) {
16
+ __defProp(to, key, {
17
+ get: ((k) => from[k]).bind(null, key),
18
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
19
+ });
20
+ }
21
+ }
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
26
+ value: mod,
27
+ enumerable: true
28
+ }) : target, mod));
29
+
30
+ //#endregion
31
+ let react = require("react");
32
+ react = __toESM(react);
33
+ let _copilotkitnext_react = require("@copilotkitnext/react");
34
+ let _copilotkit_shared = require("@copilotkit/shared");
35
+ let react_dom = require("react-dom");
36
+ let react_jsx_runtime = require("react/jsx-runtime");
37
+ let react_markdown = require("react-markdown");
38
+ react_markdown = __toESM(react_markdown);
39
+ let _copilotkit_runtime_client_gql = require("@copilotkit/runtime-client-gql");
40
+ let _ag_ui_client = require("@ag-ui/client");
41
+ let _copilotkitnext_core = require("@copilotkitnext/core");
42
+
43
+ //#region src/context/copilot-context.tsx
44
+ const emptyCopilotContext$1 = {
45
+ actions: {},
46
+ setAction: () => {},
47
+ removeAction: () => {},
48
+ setRegisteredActions: () => "",
49
+ removeRegisteredAction: () => {},
50
+ chatComponentsCache: { current: {
51
+ actions: {},
52
+ coAgentStateRenders: {}
53
+ } },
54
+ getContextString: (documents, categories) => returnAndThrowInDebug(""),
55
+ addContext: () => "",
56
+ removeContext: () => {},
57
+ getAllContext: () => [],
58
+ getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),
59
+ isLoading: false,
60
+ setIsLoading: () => returnAndThrowInDebug(false),
61
+ chatInstructions: "",
62
+ setChatInstructions: () => returnAndThrowInDebug(""),
63
+ additionalInstructions: [],
64
+ setAdditionalInstructions: () => returnAndThrowInDebug([]),
65
+ getDocumentsContext: (categories) => returnAndThrowInDebug([]),
66
+ addDocumentContext: () => returnAndThrowInDebug(""),
67
+ removeDocumentContext: () => {},
68
+ copilotApiConfig: new class {
69
+ get chatApiEndpoint() {
70
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
71
+ }
72
+ get headers() {
73
+ return {};
74
+ }
75
+ get body() {
76
+ return {};
77
+ }
78
+ }(),
79
+ chatSuggestionConfiguration: {},
80
+ addChatSuggestionConfiguration: () => {},
81
+ removeChatSuggestionConfiguration: () => {},
82
+ showDevConsole: false,
83
+ coagentStates: {},
84
+ setCoagentStates: () => {},
85
+ coagentStatesRef: { current: {} },
86
+ setCoagentStatesWithRef: () => {},
87
+ agentSession: null,
88
+ setAgentSession: () => {},
89
+ forwardedParameters: {},
90
+ agentLock: null,
91
+ threadId: "",
92
+ setThreadId: () => {},
93
+ runId: null,
94
+ setRunId: () => {},
95
+ chatAbortControllerRef: { current: null },
96
+ availableAgents: [],
97
+ extensions: {},
98
+ setExtensions: () => {},
99
+ interruptActions: {},
100
+ setInterruptAction: () => {},
101
+ removeInterruptAction: () => {},
102
+ interruptEventQueue: {},
103
+ addInterruptEvent: () => {},
104
+ resolveInterruptEvent: () => {},
105
+ onError: () => {},
106
+ bannerError: null,
107
+ setBannerError: () => {},
108
+ internalErrorHandlers: {},
109
+ setInternalErrorHandler: () => {},
110
+ removeInternalErrorHandler: () => {}
111
+ };
112
+ const CopilotContext = react.default.createContext(emptyCopilotContext$1);
113
+ function useCopilotContext() {
114
+ const context = react.default.useContext(CopilotContext);
115
+ if (context === emptyCopilotContext$1) throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
116
+ return context;
117
+ }
118
+ function returnAndThrowInDebug(_value) {
119
+ throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
120
+ }
121
+
122
+ //#endregion
123
+ //#region src/hooks/use-tree.ts
124
+ const removeNode = (nodes, id) => {
125
+ return nodes.reduce((result, node) => {
126
+ if (node.id !== id) {
127
+ const newNode = {
128
+ ...node,
129
+ children: removeNode(node.children, id)
130
+ };
131
+ result.push(newNode);
132
+ }
133
+ return result;
134
+ }, []);
135
+ };
136
+ const addNode = (nodes, newNode, parentId) => {
137
+ if (!parentId) return [...nodes, newNode];
138
+ return nodes.map((node) => {
139
+ if (node.id === parentId) return {
140
+ ...node,
141
+ children: [...node.children, newNode]
142
+ };
143
+ else if (node.children.length) return {
144
+ ...node,
145
+ children: addNode(node.children, newNode, parentId)
146
+ };
147
+ return node;
148
+ });
149
+ };
150
+ const treeIndentationRepresentation = (index, indentLevel) => {
151
+ if (indentLevel === 0) return (index + 1).toString();
152
+ else if (indentLevel === 1) return String.fromCharCode(65 + index);
153
+ else if (indentLevel === 2) return String.fromCharCode(97 + index);
154
+ else return "-";
155
+ };
156
+ const printNode = (node, prefix = "", indentLevel = 0) => {
157
+ const indent = " ".repeat(3).repeat(indentLevel);
158
+ const prefixPlusIndentLength = prefix.length + indent.length;
159
+ const subsequentLinesPrefix = " ".repeat(prefixPlusIndentLength);
160
+ const valueLines = node.value.split("\n");
161
+ const outputFirstLine = `${indent}${prefix}${valueLines[0]}`;
162
+ const outputSubsequentLines = valueLines.slice(1).map((line) => `${subsequentLinesPrefix}${line}`).join("\n");
163
+ let output = `${outputFirstLine}\n`;
164
+ if (outputSubsequentLines) output += `${outputSubsequentLines}\n`;
165
+ const childPrePrefix = " ".repeat(prefix.length);
166
+ node.children.forEach((child, index) => output += printNode(child, `${childPrePrefix}${treeIndentationRepresentation(index, indentLevel + 1)}. `, indentLevel + 1));
167
+ return output;
168
+ };
169
+ function treeReducer(state, action) {
170
+ switch (action.type) {
171
+ case "ADD_NODE": {
172
+ const { value, parentId, id: newNodeId } = action;
173
+ const newNode = {
174
+ id: newNodeId,
175
+ value,
176
+ children: [],
177
+ categories: new Set(action.categories)
178
+ };
179
+ try {
180
+ return addNode(state, newNode, parentId);
181
+ } catch (error) {
182
+ console.error(`Error while adding node with id ${newNodeId}: ${error}`);
183
+ return state;
184
+ }
185
+ }
186
+ case "REMOVE_NODE": return removeNode(state, action.id);
187
+ default: return state;
188
+ }
189
+ }
190
+ const useTree = () => {
191
+ const [tree, dispatch] = (0, react.useReducer)(treeReducer, []);
192
+ const addElement = (0, react.useCallback)((value, categories, parentId) => {
193
+ const newNodeId = (0, _copilotkit_shared.randomId)();
194
+ dispatch({
195
+ type: "ADD_NODE",
196
+ value,
197
+ parentId,
198
+ id: newNodeId,
199
+ categories
200
+ });
201
+ return newNodeId;
202
+ }, []);
203
+ const removeElement = (0, react.useCallback)((id) => {
204
+ dispatch({
205
+ type: "REMOVE_NODE",
206
+ id
207
+ });
208
+ }, []);
209
+ const getAllElements = (0, react.useCallback)(() => {
210
+ return tree;
211
+ }, [tree]);
212
+ return {
213
+ tree,
214
+ addElement,
215
+ printTree: (0, react.useCallback)((categories) => {
216
+ const categoriesSet = new Set(categories);
217
+ let output = "";
218
+ tree.forEach((node, index) => {
219
+ if (!setsHaveIntersection$1(categoriesSet, node.categories)) return;
220
+ if (index !== 0) output += "\n";
221
+ output += printNode(node, `${treeIndentationRepresentation(index, 0)}. `);
222
+ });
223
+ return output;
224
+ }, [tree]),
225
+ removeElement,
226
+ getAllElements
227
+ };
228
+ };
229
+ function setsHaveIntersection$1(setA, setB) {
230
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
231
+ for (let item of smallerSet) if (largerSet.has(item)) return true;
232
+ return false;
233
+ }
234
+
235
+ //#endregion
236
+ //#region src/hooks/use-flat-category-store.ts
237
+ const useFlatCategoryStore = () => {
238
+ const [elements, dispatch] = (0, react.useReducer)(flatCategoryStoreReducer, /* @__PURE__ */ new Map());
239
+ return {
240
+ addElement: (0, react.useCallback)((value, categories) => {
241
+ const newId = (0, _copilotkit_shared.randomId)();
242
+ dispatch({
243
+ type: "ADD_ELEMENT",
244
+ value,
245
+ id: newId,
246
+ categories
247
+ });
248
+ return newId;
249
+ }, []),
250
+ removeElement: (0, react.useCallback)((id) => {
251
+ dispatch({
252
+ type: "REMOVE_ELEMENT",
253
+ id
254
+ });
255
+ }, []),
256
+ allElements: (0, react.useCallback)((categories) => {
257
+ const categoriesSet = new Set(categories);
258
+ const result = [];
259
+ elements.forEach((element) => {
260
+ if (setsHaveIntersection(categoriesSet, element.categories)) result.push(element.value);
261
+ });
262
+ return result;
263
+ }, [elements])
264
+ };
265
+ };
266
+ function flatCategoryStoreReducer(state, action) {
267
+ switch (action.type) {
268
+ case "ADD_ELEMENT": {
269
+ const { value, id, categories } = action;
270
+ const newElement = {
271
+ id,
272
+ value,
273
+ categories: new Set(categories)
274
+ };
275
+ const newState = new Map(state);
276
+ newState.set(id, newElement);
277
+ return newState;
278
+ }
279
+ case "REMOVE_ELEMENT": {
280
+ const newState = new Map(state);
281
+ newState.delete(action.id);
282
+ return newState;
283
+ }
284
+ default: return state;
285
+ }
286
+ }
287
+ function setsHaveIntersection(setA, setB) {
288
+ const [smallerSet, largerSet] = setA.size <= setB.size ? [setA, setB] : [setB, setA];
289
+ for (let item of smallerSet) if (largerSet.has(item)) return true;
290
+ return false;
291
+ }
292
+
293
+ //#endregion
294
+ //#region src/context/copilot-messages-context.tsx
295
+ const emptyCopilotContext = {
296
+ messages: [],
297
+ setMessages: () => [],
298
+ suggestions: [],
299
+ setSuggestions: () => []
300
+ };
301
+ const CopilotMessagesContext = react.default.createContext(emptyCopilotContext);
302
+ function useCopilotMessagesContext() {
303
+ const context = react.default.useContext(CopilotMessagesContext);
304
+ if (context === emptyCopilotContext) throw new Error("A messages consuming component was not wrapped with `<CopilotMessages> {...} </CopilotMessages>`");
305
+ return context;
306
+ }
307
+
308
+ //#endregion
309
+ //#region src/components/toast/toast-provider.tsx
310
+ const ToastContext = (0, react.createContext)(void 0);
311
+ function getErrorSeverity(error) {
312
+ if (error.severity) switch (error.severity) {
313
+ case _copilotkit_shared.Severity.CRITICAL: return "critical";
314
+ case _copilotkit_shared.Severity.WARNING: return "warning";
315
+ case _copilotkit_shared.Severity.INFO: return "info";
316
+ default: return "info";
317
+ }
318
+ const message = error.message.toLowerCase();
319
+ if (message.includes("api key") || message.includes("401") || message.includes("unauthorized") || message.includes("authentication") || message.includes("incorrect api key")) return "critical";
320
+ return "info";
321
+ }
322
+ function getErrorColors(severity) {
323
+ switch (severity) {
324
+ case "critical": return {
325
+ background: "#fee2e2",
326
+ border: "#dc2626",
327
+ text: "#7f1d1d",
328
+ icon: "#dc2626"
329
+ };
330
+ case "warning": return {
331
+ background: "#fef3c7",
332
+ border: "#d97706",
333
+ text: "#78350f",
334
+ icon: "#d97706"
335
+ };
336
+ case "info": return {
337
+ background: "#dbeafe",
338
+ border: "#2563eb",
339
+ text: "#1e3a8a",
340
+ icon: "#2563eb"
341
+ };
342
+ }
343
+ }
344
+ function useToast() {
345
+ const context = (0, react.useContext)(ToastContext);
346
+ if (!context) throw new Error("useToast must be used within a ToastProvider");
347
+ return context;
348
+ }
349
+ function ToastProvider({ enabled, children }) {
350
+ const [toasts, setToasts] = (0, react.useState)([]);
351
+ const [bannerError, setBannerErrorState] = (0, react.useState)(null);
352
+ const removeToast = (0, react.useCallback)((id) => {
353
+ setToasts((prev) => prev.filter((toast) => toast.id !== id));
354
+ }, []);
355
+ const addToast = (0, react.useCallback)((toast) => {
356
+ if (!enabled) return;
357
+ const id = toast.id ?? Math.random().toString(36).substring(2, 9);
358
+ setToasts((currentToasts) => {
359
+ if (currentToasts.find((toast) => toast.id === id)) return currentToasts;
360
+ return [...currentToasts, {
361
+ ...toast,
362
+ id
363
+ }];
364
+ });
365
+ if (toast.duration) setTimeout(() => {
366
+ removeToast(id);
367
+ }, toast.duration);
368
+ }, [enabled, removeToast]);
369
+ const setBannerError = (0, react.useCallback)((error) => {
370
+ if (!enabled && error !== null) return;
371
+ setBannerErrorState(error);
372
+ }, [enabled]);
373
+ const value = {
374
+ toasts,
375
+ addToast,
376
+ addGraphQLErrorsToast: (0, react.useCallback)((errors) => {
377
+ console.warn("addGraphQLErrorsToast is deprecated. All errors now show as banners.");
378
+ }, []),
379
+ removeToast,
380
+ enabled,
381
+ bannerError,
382
+ setBannerError
383
+ };
384
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(ToastContext.Provider, {
385
+ value,
386
+ children: [bannerError && (() => {
387
+ const colors = getErrorColors(getErrorSeverity(bannerError));
388
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
389
+ style: {
390
+ position: "fixed",
391
+ bottom: "20px",
392
+ left: "50%",
393
+ transform: "translateX(-50%)",
394
+ zIndex: 9999,
395
+ backgroundColor: colors.background,
396
+ border: `1px solid ${colors.border}`,
397
+ borderLeft: `4px solid ${colors.border}`,
398
+ borderRadius: "8px",
399
+ padding: "12px 16px",
400
+ fontSize: "13px",
401
+ boxShadow: "0 4px 12px rgba(0, 0, 0, 0.15)",
402
+ backdropFilter: "blur(8px)",
403
+ maxWidth: "min(90vw, 700px)",
404
+ width: "100%",
405
+ boxSizing: "border-box",
406
+ overflow: "hidden"
407
+ },
408
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
409
+ style: {
410
+ display: "flex",
411
+ justifyContent: "space-between",
412
+ alignItems: "center",
413
+ gap: "10px"
414
+ },
415
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
416
+ style: {
417
+ display: "flex",
418
+ alignItems: "center",
419
+ gap: "8px",
420
+ flex: 1,
421
+ minWidth: 0
422
+ },
423
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { style: {
424
+ width: "12px",
425
+ height: "12px",
426
+ borderRadius: "50%",
427
+ backgroundColor: colors.border,
428
+ flexShrink: 0
429
+ } }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
430
+ style: {
431
+ display: "flex",
432
+ alignItems: "center",
433
+ gap: "10px",
434
+ flex: 1,
435
+ minWidth: 0
436
+ },
437
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
438
+ style: {
439
+ color: colors.text,
440
+ lineHeight: "1.4",
441
+ fontWeight: "400",
442
+ fontSize: "13px",
443
+ flex: 1,
444
+ wordBreak: "break-all",
445
+ overflowWrap: "break-word",
446
+ maxWidth: "550px",
447
+ overflow: "hidden",
448
+ display: "-webkit-box",
449
+ WebkitLineClamp: 10,
450
+ WebkitBoxOrient: "vertical"
451
+ },
452
+ children: (() => {
453
+ let message = bannerError.message;
454
+ const jsonMatch = message.match(/'message':\s*'([^']+)'/);
455
+ if (jsonMatch) return jsonMatch[1];
456
+ message = message.split(" - ")[0];
457
+ message = message.split(": Error code")[0];
458
+ message = message.replace(/:\s*\d{3}$/, "");
459
+ message = message.replace(/See more:.*$/g, "");
460
+ message = message.trim();
461
+ return message || "Configuration error occurred.";
462
+ })()
463
+ }), (() => {
464
+ const message = bannerError.message;
465
+ const markdownLinkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;
466
+ const plainUrlRegex = /(https?:\/\/[^\s)]+)/g;
467
+ let url = null;
468
+ let buttonText = "See More";
469
+ const markdownMatch = markdownLinkRegex.exec(message);
470
+ if (markdownMatch) {
471
+ url = markdownMatch[2];
472
+ buttonText = "See More";
473
+ } else {
474
+ const urlMatch = plainUrlRegex.exec(message);
475
+ if (urlMatch) {
476
+ url = urlMatch[0].replace(/[.,;:'"]*$/, "");
477
+ buttonText = "See More";
478
+ }
479
+ }
480
+ if (!url) return null;
481
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
482
+ onClick: () => window.open(url, "_blank", "noopener,noreferrer"),
483
+ style: {
484
+ background: colors.border,
485
+ color: "white",
486
+ border: "none",
487
+ borderRadius: "5px",
488
+ padding: "4px 10px",
489
+ fontSize: "11px",
490
+ fontWeight: "500",
491
+ cursor: "pointer",
492
+ transition: "all 0.2s ease",
493
+ flexShrink: 0
494
+ },
495
+ onMouseEnter: (e) => {
496
+ e.currentTarget.style.opacity = "0.9";
497
+ e.currentTarget.style.transform = "translateY(-1px)";
498
+ },
499
+ onMouseLeave: (e) => {
500
+ e.currentTarget.style.opacity = "1";
501
+ e.currentTarget.style.transform = "translateY(0)";
502
+ },
503
+ children: buttonText
504
+ });
505
+ })()]
506
+ })]
507
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
508
+ onClick: () => setBannerError(null),
509
+ style: {
510
+ background: "transparent",
511
+ border: "none",
512
+ color: colors.text,
513
+ cursor: "pointer",
514
+ padding: "2px",
515
+ borderRadius: "3px",
516
+ fontSize: "14px",
517
+ lineHeight: "1",
518
+ opacity: .6,
519
+ transition: "all 0.2s ease",
520
+ flexShrink: 0
521
+ },
522
+ title: "Dismiss",
523
+ onMouseEnter: (e) => {
524
+ e.currentTarget.style.opacity = "1";
525
+ e.currentTarget.style.background = "rgba(0, 0, 0, 0.05)";
526
+ },
527
+ onMouseLeave: (e) => {
528
+ e.currentTarget.style.opacity = "0.6";
529
+ e.currentTarget.style.background = "transparent";
530
+ },
531
+ children: "×"
532
+ })]
533
+ })
534
+ });
535
+ })(), children]
536
+ });
537
+ }
538
+
539
+ //#endregion
540
+ //#region src/utils/dev-console.ts
541
+ function isLocalhost() {
542
+ if (typeof window === "undefined") return false;
543
+ return window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1" || window.location.hostname === "0.0.0.0";
544
+ }
545
+ function shouldShowDevConsole(showDevConsole) {
546
+ if (showDevConsole !== void 0) return showDevConsole;
547
+ return isLocalhost();
548
+ }
549
+
550
+ //#endregion
551
+ //#region src/components/copilot-provider/copilot-messages.tsx
552
+ /**
553
+ * An internal context to separate the messages state (which is constantly changing) from the rest of CopilotKit context
554
+ */
555
+ const MessagesTapContext = (0, react.createContext)(null);
556
+ function useMessagesTap() {
557
+ const tap = (0, react.useContext)(MessagesTapContext);
558
+ if (!tap) throw new Error("useMessagesTap must be used inside <MessagesTapProvider>");
559
+ return tap;
560
+ }
561
+ function MessagesTapProvider({ children }) {
562
+ const messagesRef = (0, react.useRef)([]);
563
+ const tapRef = (0, react.useRef)({
564
+ getMessagesFromTap: () => messagesRef.current,
565
+ updateTapMessages: (messages) => {
566
+ messagesRef.current = messages;
567
+ }
568
+ });
569
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapContext.Provider, {
570
+ value: tapRef.current,
571
+ children
572
+ });
573
+ }
574
+ /**
575
+ * CopilotKit messages context.
576
+ */
577
+ function CopilotMessages({ children }) {
578
+ const [messages, setMessages] = (0, react.useState)([]);
579
+ (0, react.useRef)(void 0);
580
+ (0, react.useRef)(void 0);
581
+ (0, react.useRef)(void 0);
582
+ const { updateTapMessages } = useMessagesTap();
583
+ const { threadId, agentSession, showDevConsole, onError, copilotApiConfig } = useCopilotContext();
584
+ const { setBannerError } = useToast();
585
+ const traceUIError = (0, react.useCallback)(async (error, originalError) => {
586
+ if (!onError || !copilotApiConfig.publicApiKey) return;
587
+ try {
588
+ await onError({
589
+ type: "error",
590
+ timestamp: Date.now(),
591
+ context: {
592
+ source: "ui",
593
+ request: {
594
+ operation: "loadAgentState",
595
+ url: copilotApiConfig.chatApiEndpoint,
596
+ startTime: Date.now()
597
+ },
598
+ technical: {
599
+ environment: "browser",
600
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
601
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
602
+ }
603
+ },
604
+ error
605
+ });
606
+ } catch (traceError) {
607
+ console.error("Error in CopilotMessages onError handler:", traceError);
608
+ }
609
+ }, [
610
+ onError,
611
+ copilotApiConfig.publicApiKey,
612
+ copilotApiConfig.chatApiEndpoint
613
+ ]);
614
+ const createStructuredError = (gqlError) => {
615
+ const extensions = gqlError.extensions;
616
+ const originalError = extensions?.originalError;
617
+ if (originalError?.stack) {
618
+ if (originalError.stack.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message: originalError.message });
619
+ if (originalError.stack.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message: originalError.message });
620
+ if (originalError.stack.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
621
+ agentName: "",
622
+ availableAgents: []
623
+ });
624
+ }
625
+ const message = originalError?.message || gqlError.message;
626
+ const code = extensions?.code;
627
+ if (code) return new _copilotkit_shared.CopilotKitError({
628
+ message,
629
+ code
630
+ });
631
+ return null;
632
+ };
633
+ (0, react.useCallback)((error) => {
634
+ if (error.graphQLErrors?.length) {
635
+ const graphQLErrors = error.graphQLErrors;
636
+ const routeError = (gqlError) => {
637
+ const visibility = gqlError.extensions?.visibility;
638
+ if (!shouldShowDevConsole(showDevConsole)) {
639
+ console.error("CopilotKit Error (hidden in production):", gqlError.message);
640
+ return;
641
+ }
642
+ if (visibility === _copilotkit_shared.ErrorVisibility.SILENT) {
643
+ console.error("CopilotKit Silent Error:", gqlError.message);
644
+ return;
645
+ }
646
+ const ckError = createStructuredError(gqlError);
647
+ if (ckError) {
648
+ setBannerError(ckError);
649
+ traceUIError(ckError, gqlError);
650
+ } else {
651
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
652
+ message: gqlError.message,
653
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
654
+ });
655
+ setBannerError(fallbackError);
656
+ traceUIError(fallbackError, gqlError);
657
+ }
658
+ };
659
+ graphQLErrors.forEach(routeError);
660
+ } else if (!shouldShowDevConsole(showDevConsole)) console.error("CopilotKit Error (hidden in production):", error);
661
+ else {
662
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
663
+ message: error?.message || String(error),
664
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
665
+ });
666
+ setBannerError(fallbackError);
667
+ traceUIError(fallbackError, error);
668
+ }
669
+ }, [
670
+ setBannerError,
671
+ showDevConsole,
672
+ traceUIError
673
+ ]);
674
+ (0, react.useEffect)(() => {
675
+ updateTapMessages(messages);
676
+ }, [messages, updateTapMessages]);
677
+ const memoizedChildren = (0, react.useMemo)(() => children, [children]);
678
+ const [suggestions, setSuggestions] = (0, react.useState)([]);
679
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotMessagesContext.Provider, {
680
+ value: {
681
+ messages,
682
+ setMessages,
683
+ suggestions,
684
+ setSuggestions
685
+ },
686
+ children: memoizedChildren
687
+ });
688
+ }
689
+
690
+ //#endregion
691
+ //#region src/components/usage-banner.tsx
692
+ function UsageBanner({ severity = _copilotkit_shared.Severity.CRITICAL, message = "", onClose, actions }) {
693
+ if (!message || !severity) return null;
694
+ const theme = {
695
+ [_copilotkit_shared.Severity.INFO]: {
696
+ bg: "#f8fafc",
697
+ border: "#e2e8f0",
698
+ text: "#475569",
699
+ accent: "#3b82f6"
700
+ },
701
+ [_copilotkit_shared.Severity.WARNING]: {
702
+ bg: "#fffbeb",
703
+ border: "#fbbf24",
704
+ text: "#92400e",
705
+ accent: "#f59e0b"
706
+ },
707
+ [_copilotkit_shared.Severity.CRITICAL]: {
708
+ bg: "#fef2f2",
709
+ border: "#fecaca",
710
+ text: "#dc2626",
711
+ accent: "#ef4444"
712
+ }
713
+ }[severity];
714
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { children: `
715
+ @keyframes slideUp {
716
+ from { opacity: 0; transform: translateX(-50%) translateY(8px); }
717
+ to { opacity: 1; transform: translateX(-50%) translateY(0); }
718
+ }
719
+
720
+ .usage-banner {
721
+ position: fixed;
722
+ bottom: 24px;
723
+ left: 50%;
724
+ transform: translateX(-50%);
725
+ width: min(600px, calc(100vw - 32px));
726
+ z-index: 10000;
727
+ animation: slideUp 0.2s cubic-bezier(0.16, 1, 0.3, 1);
728
+ }
729
+
730
+ .banner-content {
731
+ background: linear-gradient(135deg, ${theme.bg} 0%, ${theme.bg}f5 100%);
732
+ border: 1px solid ${theme.border};
733
+ border-radius: 12px;
734
+ padding: 18px 20px;
735
+ box-shadow:
736
+ 0 4px 24px rgba(0, 0, 0, 0.08),
737
+ 0 2px 8px rgba(0, 0, 0, 0.04),
738
+ inset 0 1px 0 rgba(255, 255, 255, 0.7);
739
+ display: flex;
740
+ align-items: center;
741
+ gap: 16px;
742
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
743
+ backdrop-filter: blur(12px);
744
+ position: relative;
745
+ overflow: hidden;
746
+ }
747
+
748
+ .banner-content::before {
749
+ content: '';
750
+ position: absolute;
751
+ top: 0;
752
+ left: 0;
753
+ right: 0;
754
+ height: 1px;
755
+ background: linear-gradient(90deg, transparent, ${theme.accent}40, transparent);
756
+ }
757
+
758
+ .banner-message {
759
+ color: ${theme.text};
760
+ font-size: 14px;
761
+ line-height: 1.5;
762
+ font-weight: 500;
763
+ flex: 1;
764
+ letter-spacing: -0.01em;
765
+ }
766
+
767
+ .close-btn {
768
+ background: rgba(0, 0, 0, 0.05);
769
+ border: none;
770
+ color: ${theme.text};
771
+ cursor: pointer;
772
+ padding: 0;
773
+ border-radius: 6px;
774
+ opacity: 0.6;
775
+ transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
776
+ font-size: 14px;
777
+ line-height: 1;
778
+ flex-shrink: 0;
779
+ width: 24px;
780
+ height: 24px;
781
+ display: flex;
782
+ align-items: center;
783
+ justify-content: center;
784
+ }
785
+
786
+ .close-btn:hover {
787
+ opacity: 1;
788
+ background: rgba(0, 0, 0, 0.08);
789
+ transform: scale(1.05);
790
+ }
791
+
792
+ .btn-primary {
793
+ background: linear-gradient(135deg, ${theme.accent} 0%, ${theme.accent}e6 100%);
794
+ color: white;
795
+ border: none;
796
+ border-radius: 8px;
797
+ padding: 10px 18px;
798
+ font-size: 13px;
799
+ font-weight: 600;
800
+ cursor: pointer;
801
+ transition: all 0.15s cubic-bezier(0.16, 1, 0.3, 1);
802
+ font-family: inherit;
803
+ flex-shrink: 0;
804
+ box-shadow:
805
+ 0 2px 8px ${theme.accent}30,
806
+ inset 0 1px 0 rgba(255, 255, 255, 0.2);
807
+ letter-spacing: -0.01em;
808
+ }
809
+
810
+ .btn-primary:hover {
811
+ transform: translateY(-1px) scale(1.02);
812
+ box-shadow:
813
+ 0 4px 12px ${theme.accent}40,
814
+ inset 0 1px 0 rgba(255, 255, 255, 0.25);
815
+ }
816
+
817
+ .btn-primary:active {
818
+ transform: translateY(0) scale(0.98);
819
+ transition: all 0.08s cubic-bezier(0.16, 1, 0.3, 1);
820
+ }
821
+
822
+ @media (max-width: 640px) {
823
+ .usage-banner {
824
+ width: calc(100vw - 24px);
825
+ }
826
+
827
+ .banner-content {
828
+ padding: 16px;
829
+ gap: 12px;
830
+ }
831
+
832
+ .banner-message {
833
+ font-size: 13px;
834
+ line-height: 1.45;
835
+ }
836
+
837
+ .btn-primary {
838
+ padding: 8px 14px;
839
+ font-size: 12px;
840
+ }
841
+
842
+ .close-btn {
843
+ width: 22px;
844
+ height: 22px;
845
+ font-size: 12px;
846
+ }
847
+ }
848
+ ` }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
849
+ className: "usage-banner",
850
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
851
+ className: "banner-content",
852
+ children: [
853
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
854
+ className: "banner-message",
855
+ children: message
856
+ }),
857
+ actions?.primary && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
858
+ className: "btn-primary",
859
+ onClick: actions.primary.onClick,
860
+ children: actions.primary.label
861
+ }),
862
+ onClose && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
863
+ className: "close-btn",
864
+ onClick: onClose,
865
+ title: "Close",
866
+ children: "×"
867
+ })
868
+ ]
869
+ })
870
+ })] });
871
+ }
872
+ const getErrorActions = (error) => {
873
+ switch (error.code) {
874
+ case _copilotkit_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR: return { primary: {
875
+ label: "Show me how",
876
+ onClick: () => window.open("https://docs.copilotkit.ai/premium#how-do-i-get-access-to-premium-features", "_blank", "noopener,noreferrer")
877
+ } };
878
+ case _copilotkit_shared.CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR: return { primary: {
879
+ label: "Upgrade",
880
+ onClick: () => window.open("https://cloud.copilotkit.ai", "_blank", "noopener,noreferrer")
881
+ } };
882
+ default: return;
883
+ }
884
+ };
885
+
886
+ //#endregion
887
+ //#region src/utils/suggestions-constants.ts
888
+ /**
889
+ * Constants for suggestions retry logic
890
+ */
891
+ const SUGGESTION_RETRY_CONFIG = {
892
+ MAX_RETRIES: 3,
893
+ COOLDOWN_MS: 5e3
894
+ };
895
+
896
+ //#endregion
897
+ //#region src/lib/status-checker.ts
898
+ const STATUS_CHECK_INTERVAL = 1e3 * 60 * 5;
899
+ var StatusChecker = class {
900
+ constructor() {
901
+ this.activeKey = null;
902
+ this.intervalId = null;
903
+ this.instanceCount = 0;
904
+ this.lastResponse = null;
905
+ }
906
+ async start(publicApiKey, onUpdate) {
907
+ this.instanceCount++;
908
+ if (this.activeKey === publicApiKey) return;
909
+ if (this.intervalId) clearInterval(this.intervalId);
910
+ const checkStatus = async () => {
911
+ try {
912
+ const response = await fetch(`${_copilotkit_shared.COPILOT_CLOUD_API_URL}/ciu`, {
913
+ method: "GET",
914
+ headers: { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: publicApiKey }
915
+ }).then((response) => response.json());
916
+ this.lastResponse = response;
917
+ onUpdate?.(response);
918
+ return response;
919
+ } catch (error) {
920
+ return null;
921
+ }
922
+ };
923
+ const initialResponse = await checkStatus();
924
+ this.intervalId = setInterval(checkStatus, STATUS_CHECK_INTERVAL);
925
+ this.activeKey = publicApiKey;
926
+ return initialResponse;
927
+ }
928
+ getLastResponse() {
929
+ return this.lastResponse;
930
+ }
931
+ stop() {
932
+ this.instanceCount--;
933
+ if (this.instanceCount === 0) {
934
+ if (this.intervalId) {
935
+ clearInterval(this.intervalId);
936
+ this.intervalId = null;
937
+ this.activeKey = null;
938
+ this.lastResponse = null;
939
+ }
940
+ }
941
+ }
942
+ };
943
+
944
+ //#endregion
945
+ //#region src/components/toast/exclamation-mark-icon.tsx
946
+ const ExclamationMarkIcon = ({ className, style }) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("svg", {
947
+ xmlns: "http://www.w3.org/2000/svg",
948
+ width: "24",
949
+ height: "24",
950
+ viewBox: "0 0 24 24",
951
+ fill: "none",
952
+ stroke: "currentColor",
953
+ strokeWidth: "2",
954
+ strokeLinecap: "round",
955
+ strokeLinejoin: "round",
956
+ className: `lucide lucide-circle-alert ${className ? className : ""}`,
957
+ style,
958
+ children: [
959
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("circle", {
960
+ cx: "12",
961
+ cy: "12",
962
+ r: "10"
963
+ }),
964
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
965
+ x1: "12",
966
+ x2: "12",
967
+ y1: "8",
968
+ y2: "12"
969
+ }),
970
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("line", {
971
+ x1: "12",
972
+ x2: "12.01",
973
+ y1: "16",
974
+ y2: "16"
975
+ })
976
+ ]
977
+ });
978
+
979
+ //#endregion
980
+ //#region src/components/error-boundary/error-utils.tsx
981
+ function ErrorToast({ errors }) {
982
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
983
+ style: {
984
+ fontSize: "13px",
985
+ maxWidth: "600px"
986
+ },
987
+ children: [errors.map((error, idx) => {
988
+ const message = ("extensions" in error ? error.extensions?.originalError : {})?.message ?? error.message;
989
+ const code = "extensions" in error ? error.extensions?.code : null;
990
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
991
+ style: {
992
+ marginTop: idx === 0 ? 0 : 10,
993
+ marginBottom: 14
994
+ },
995
+ children: [
996
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ExclamationMarkIcon, { style: { marginBottom: 4 } }),
997
+ code && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
998
+ style: {
999
+ fontWeight: "600",
1000
+ marginBottom: 4
1001
+ },
1002
+ children: [
1003
+ "Copilot Runtime Error:",
1004
+ " ",
1005
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1006
+ style: {
1007
+ fontFamily: "monospace",
1008
+ fontWeight: "normal"
1009
+ },
1010
+ children: code
1011
+ })
1012
+ ]
1013
+ }),
1014
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_markdown.default, { children: message })
1015
+ ]
1016
+ }, idx);
1017
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1018
+ style: {
1019
+ fontSize: "11px",
1020
+ opacity: .75
1021
+ },
1022
+ children: "NOTE: This error only displays during local development."
1023
+ })]
1024
+ });
1025
+ }
1026
+ function useErrorToast() {
1027
+ const { addToast } = useToast();
1028
+ return (0, react.useCallback)((errors) => {
1029
+ addToast({
1030
+ type: "error",
1031
+ id: errors.map((err) => {
1032
+ const message = "extensions" in err ? (err.extensions?.originalError)?.message || err.message : err.message;
1033
+ const stack = err.stack || "";
1034
+ return btoa(message + stack).slice(0, 32);
1035
+ }).join("|"),
1036
+ message: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorToast, { errors })
1037
+ });
1038
+ }, [addToast]);
1039
+ }
1040
+ function useAsyncCallback(callback, deps) {
1041
+ const addErrorToast = useErrorToast();
1042
+ return (0, react.useCallback)(async (...args) => {
1043
+ try {
1044
+ return await callback(...args);
1045
+ } catch (error) {
1046
+ console.error("Error in async callback:", error);
1047
+ addErrorToast([error]);
1048
+ throw error;
1049
+ }
1050
+ }, deps);
1051
+ }
1052
+
1053
+ //#endregion
1054
+ //#region src/components/error-boundary/error-boundary.tsx
1055
+ const statusChecker = new StatusChecker();
1056
+ var CopilotErrorBoundary = class extends react.default.Component {
1057
+ constructor(props) {
1058
+ super(props);
1059
+ this.state = { hasError: false };
1060
+ }
1061
+ static getDerivedStateFromError(error) {
1062
+ return {
1063
+ hasError: true,
1064
+ error
1065
+ };
1066
+ }
1067
+ componentDidMount() {
1068
+ if (this.props.publicApiKey) statusChecker.start(this.props.publicApiKey, (newStatus) => {
1069
+ this.setState((prevState) => {
1070
+ if (newStatus?.severity !== prevState.status?.severity) return { status: newStatus ?? void 0 };
1071
+ return null;
1072
+ });
1073
+ });
1074
+ }
1075
+ componentWillUnmount() {
1076
+ statusChecker.stop();
1077
+ }
1078
+ componentDidCatch(error, errorInfo) {
1079
+ console.error("CopilotKit Error:", error, errorInfo);
1080
+ }
1081
+ render() {
1082
+ if (this.state.hasError) {
1083
+ if (this.state.error instanceof _copilotkit_shared.CopilotKitError) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [this.props.children, this.props.showUsageBanner && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
1084
+ severity: this.state.status?.severity ?? this.state.error.severity,
1085
+ message: this.state.status?.message ?? this.state.error.message,
1086
+ actions: getErrorActions(this.state.error)
1087
+ })] });
1088
+ throw this.state.error;
1089
+ }
1090
+ return this.props.children;
1091
+ }
1092
+ };
1093
+
1094
+ //#endregion
1095
+ //#region src/context/coagent-state-renders-context.tsx
1096
+ const CoAgentStateRendersContext = (0, react.createContext)(void 0);
1097
+ function CoAgentStateRendersProvider({ children }) {
1098
+ const [coAgentStateRenders, setCoAgentStateRenders] = (0, react.useState)({});
1099
+ const setCoAgentStateRender = (0, react.useCallback)((id, stateRender) => {
1100
+ setCoAgentStateRenders((prevPoints) => ({
1101
+ ...prevPoints,
1102
+ [id]: stateRender
1103
+ }));
1104
+ }, []);
1105
+ const removeCoAgentStateRender = (0, react.useCallback)((id) => {
1106
+ setCoAgentStateRenders((prevPoints) => {
1107
+ const newPoints = { ...prevPoints };
1108
+ delete newPoints[id];
1109
+ return newPoints;
1110
+ });
1111
+ }, []);
1112
+ const claimsRef = (0, react.useRef)({});
1113
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CoAgentStateRendersContext.Provider, {
1114
+ value: {
1115
+ coAgentStateRenders,
1116
+ setCoAgentStateRender,
1117
+ removeCoAgentStateRender,
1118
+ claimsRef
1119
+ },
1120
+ children
1121
+ });
1122
+ }
1123
+ function useCoAgentStateRenders() {
1124
+ const context = (0, react.useContext)(CoAgentStateRendersContext);
1125
+ if (!context) throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
1126
+ return context;
1127
+ }
1128
+
1129
+ //#endregion
1130
+ //#region src/context/threads-context.tsx
1131
+ const ThreadsContext = (0, react.createContext)(void 0);
1132
+ function ThreadsProvider({ children, threadId: explicitThreadId }) {
1133
+ const [internalThreadId, setThreadId] = (0, react.useState)(() => (0, _copilotkit_shared.randomUUID)());
1134
+ const threadId = explicitThreadId ?? internalThreadId;
1135
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsContext.Provider, {
1136
+ value: {
1137
+ threadId,
1138
+ setThreadId
1139
+ },
1140
+ children
1141
+ });
1142
+ }
1143
+ function useThreads() {
1144
+ const context = (0, react.useContext)(ThreadsContext);
1145
+ if (!context) throw new Error("useThreads must be used within ThreadsProvider");
1146
+ return context;
1147
+ }
1148
+
1149
+ //#endregion
1150
+ //#region src/hooks/use-coagent-state-render-bridge.helpers.ts
1151
+ let RenderStatus = /* @__PURE__ */ function(RenderStatus) {
1152
+ RenderStatus["InProgress"] = "inProgress";
1153
+ RenderStatus["Complete"] = "complete";
1154
+ return RenderStatus;
1155
+ }({});
1156
+ let ClaimAction = /* @__PURE__ */ function(ClaimAction) {
1157
+ ClaimAction["Create"] = "create";
1158
+ ClaimAction["Override"] = "override";
1159
+ ClaimAction["Existing"] = "existing";
1160
+ ClaimAction["Block"] = "block";
1161
+ return ClaimAction;
1162
+ }({});
1163
+ function getStateWithoutConstantKeys(state) {
1164
+ if (!state) return {};
1165
+ const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;
1166
+ return stateWithoutConstantKeys;
1167
+ }
1168
+ function areStatesEquals(a, b) {
1169
+ if (a && !b || !a && b) return false;
1170
+ const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;
1171
+ const { messages: bMessages, tools: bTools, copilotkit: bCopilotkit, ...bWithoutConstantKeys } = b;
1172
+ return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);
1173
+ }
1174
+ function isPlaceholderMessageId(messageId) {
1175
+ return !!messageId && messageId.startsWith("coagent-state-render-");
1176
+ }
1177
+ function isPlaceholderMessageName(messageName) {
1178
+ return messageName === "coagent-state-render";
1179
+ }
1180
+ function readCachedMessageEntry(entry) {
1181
+ if (!entry || typeof entry !== "object") return {
1182
+ snapshot: entry,
1183
+ runId: void 0
1184
+ };
1185
+ return {
1186
+ snapshot: "snapshot" in entry ? entry.snapshot : entry,
1187
+ runId: "runId" in entry ? entry.runId : void 0
1188
+ };
1189
+ }
1190
+ function getEffectiveRunId({ existingClaimRunId, cachedMessageRunId, runId }) {
1191
+ return existingClaimRunId || cachedMessageRunId || runId || "pending";
1192
+ }
1193
+ /**
1194
+ * Resolve whether a message can claim a render slot.
1195
+ * This is a pure decision function; the caller applies claim mutations.
1196
+ */
1197
+ function resolveClaim({ claims, context, stateSnapshot }) {
1198
+ const { messageId, stateRenderId, runId, messageIndex } = context;
1199
+ const existing = claims[messageId];
1200
+ if (existing) {
1201
+ const canRender = existing.stateRenderId === stateRenderId;
1202
+ const shouldUpdateRunId = canRender && runId && (!existing.runId || existing.runId === "pending");
1203
+ return {
1204
+ canRender,
1205
+ action: canRender ? ClaimAction.Existing : ClaimAction.Block,
1206
+ updateRunId: shouldUpdateRunId ? runId : void 0
1207
+ };
1208
+ }
1209
+ const normalizedRunId = runId ?? "pending";
1210
+ const renderClaimedByOtherMessageEntry = Object.entries(claims).find(([, claim]) => claim.stateRenderId === stateRenderId && (claim.runId ?? "pending") === normalizedRunId && (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(claim.stateSnapshot)) === (0, _copilotkit_shared.dataToUUID)(getStateWithoutConstantKeys(stateSnapshot)));
1211
+ const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];
1212
+ const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];
1213
+ if (renderClaimedByOtherMessage) {
1214
+ if (messageIndex !== void 0 && renderClaimedByOtherMessage.messageIndex !== void 0 && messageIndex > renderClaimedByOtherMessage.messageIndex) return {
1215
+ canRender: true,
1216
+ action: ClaimAction.Override,
1217
+ nextClaim: {
1218
+ stateRenderId,
1219
+ runId,
1220
+ messageIndex
1221
+ },
1222
+ lockOthers: runId === renderClaimedByOtherMessage.runId || isPlaceholderMessageId(claimedMessageId)
1223
+ };
1224
+ if (runId && renderClaimedByOtherMessage.runId && runId !== renderClaimedByOtherMessage.runId) return {
1225
+ canRender: true,
1226
+ action: ClaimAction.Override,
1227
+ nextClaim: {
1228
+ stateRenderId,
1229
+ runId,
1230
+ messageIndex
1231
+ },
1232
+ lockOthers: isPlaceholderMessageId(claimedMessageId)
1233
+ };
1234
+ if (isPlaceholderMessageId(claimedMessageId)) return {
1235
+ canRender: true,
1236
+ action: ClaimAction.Override,
1237
+ nextClaim: {
1238
+ stateRenderId,
1239
+ runId,
1240
+ messageIndex
1241
+ },
1242
+ lockOthers: true
1243
+ };
1244
+ if (stateSnapshot && renderClaimedByOtherMessage.stateSnapshot && !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)) return {
1245
+ canRender: true,
1246
+ action: ClaimAction.Override,
1247
+ nextClaim: {
1248
+ stateRenderId,
1249
+ runId
1250
+ }
1251
+ };
1252
+ return {
1253
+ canRender: false,
1254
+ action: ClaimAction.Block
1255
+ };
1256
+ }
1257
+ if (!runId) return {
1258
+ canRender: false,
1259
+ action: ClaimAction.Block
1260
+ };
1261
+ return {
1262
+ canRender: true,
1263
+ action: ClaimAction.Create,
1264
+ nextClaim: {
1265
+ stateRenderId,
1266
+ runId,
1267
+ messageIndex
1268
+ }
1269
+ };
1270
+ }
1271
+ /**
1272
+ * Select the best snapshot to render for this message.
1273
+ * Priority order is:
1274
+ * 1) explicit message snapshot
1275
+ * 2) live agent state (latest assistant only)
1276
+ * 3) cached snapshot for message
1277
+ * 4) cached snapshot for stateRenderId+runId
1278
+ * 5) last cached snapshot for stateRenderId
1279
+ */
1280
+ function selectSnapshot({ messageId, messageName, allowLiveState, skipLatestCache, stateRenderId, effectiveRunId, stateSnapshotProp, agentState, agentMessages, existingClaim, caches }) {
1281
+ const lastAssistantId = agentMessages ? [...agentMessages].reverse().find((msg) => msg.role === "assistant")?.id : void 0;
1282
+ const latestSnapshot = stateRenderId !== void 0 ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : void 0;
1283
+ const messageIndex = agentMessages ? agentMessages.findIndex((msg) => msg.id === messageId) : -1;
1284
+ const messageRole = messageIndex >= 0 && agentMessages ? agentMessages[messageIndex]?.role : void 0;
1285
+ let previousUserMessageId;
1286
+ if (messageIndex > 0 && agentMessages) {
1287
+ for (let i = messageIndex - 1; i >= 0; i -= 1) if (agentMessages[i]?.role === "user") {
1288
+ previousUserMessageId = agentMessages[i]?.id;
1289
+ break;
1290
+ }
1291
+ }
1292
+ const liveStateIsStale = stateSnapshotProp === void 0 && latestSnapshot !== void 0 && agentState !== void 0 && areStatesEquals(latestSnapshot, agentState);
1293
+ const shouldUseLiveState = (Boolean(allowLiveState) || !lastAssistantId || messageId === lastAssistantId) && !liveStateIsStale;
1294
+ const snapshot = stateSnapshotProp ? (0, _copilotkit_shared.parseJson)(stateSnapshotProp, stateSnapshotProp) : shouldUseLiveState ? agentState : void 0;
1295
+ const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);
1296
+ const allowEmptySnapshot = snapshot !== void 0 && !hasSnapshotKeys && (stateSnapshotProp !== void 0 || shouldUseLiveState);
1297
+ const messageCacheEntry = caches.byMessageId[messageId];
1298
+ const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot;
1299
+ const cacheKey = stateRenderId !== void 0 ? `${stateRenderId}::${effectiveRunId}` : void 0;
1300
+ let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];
1301
+ if (cachedSnapshot === void 0 && cacheKey && caches.byStateRenderAndRun[cacheKey] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[cacheKey];
1302
+ if (cachedSnapshot === void 0 && stateRenderId && previousUserMessageId && caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !== void 0) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`];
1303
+ if (cachedSnapshot === void 0 && !skipLatestCache && stateRenderId && messageRole !== "assistant" && (stateSnapshotProp !== void 0 || agentState && Object.keys(agentState).length > 0)) cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];
1304
+ const snapshotForClaim = existingClaim?.locked ? existingClaim.stateSnapshot ?? cachedSnapshot : hasSnapshotKeys ? snapshot : existingClaim?.stateSnapshot ?? cachedSnapshot;
1305
+ return {
1306
+ snapshot,
1307
+ hasSnapshotKeys,
1308
+ cachedSnapshot,
1309
+ allowEmptySnapshot,
1310
+ snapshotForClaim
1311
+ };
1312
+ }
1313
+
1314
+ //#endregion
1315
+ //#region src/hooks/use-coagent-state-render-registry.ts
1316
+ const LAST_SNAPSHOTS_BY_RENDER_AND_RUN = "__lastSnapshotsByStateRenderIdAndRun";
1317
+ const LAST_SNAPSHOTS_BY_MESSAGE = "__lastSnapshotsByMessageId";
1318
+ function getClaimsStore(claimsRef) {
1319
+ return claimsRef.current;
1320
+ }
1321
+ function getSnapshotCaches(claimsRef) {
1322
+ const store = getClaimsStore(claimsRef);
1323
+ return {
1324
+ byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},
1325
+ byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}
1326
+ };
1327
+ }
1328
+ function useStateRenderRegistry({ agentId, stateRenderId, message, messageIndex, stateSnapshot, agentState, agentMessages, claimsRef }) {
1329
+ const store = getClaimsStore(claimsRef);
1330
+ const runId = message.runId;
1331
+ const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];
1332
+ const { runId: cachedMessageRunId } = readCachedMessageEntry(cachedMessageEntry);
1333
+ const existingClaimRunId = claimsRef.current[message.id]?.runId;
1334
+ const effectiveRunId = getEffectiveRunId({
1335
+ existingClaimRunId,
1336
+ cachedMessageRunId,
1337
+ runId
1338
+ });
1339
+ (0, react.useEffect)(() => {
1340
+ return () => {
1341
+ const existingClaim = claimsRef.current[message.id];
1342
+ if (existingClaim?.stateSnapshot && Object.keys(existingClaim.stateSnapshot).length > 0) {
1343
+ const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {} };
1344
+ const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? "pending"}`;
1345
+ snapshotCache[cacheKey] = existingClaim.stateSnapshot;
1346
+ snapshotCache[`${existingClaim.stateRenderId}::latest`] = existingClaim.stateSnapshot;
1347
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1348
+ const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {} };
1349
+ messageCache[message.id] = {
1350
+ snapshot: existingClaim.stateSnapshot,
1351
+ runId: existingClaim.runId ?? effectiveRunId
1352
+ };
1353
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1354
+ }
1355
+ delete claimsRef.current[message.id];
1356
+ };
1357
+ }, [
1358
+ claimsRef,
1359
+ effectiveRunId,
1360
+ message.id
1361
+ ]);
1362
+ if (!stateRenderId) return { canRender: false };
1363
+ const caches = getSnapshotCaches(claimsRef);
1364
+ const existingClaim = claimsRef.current[message.id];
1365
+ const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } = selectSnapshot({
1366
+ messageId: message.id,
1367
+ messageName: message.name,
1368
+ allowLiveState: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1369
+ skipLatestCache: isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),
1370
+ stateRenderId,
1371
+ effectiveRunId,
1372
+ stateSnapshotProp: stateSnapshot,
1373
+ agentState,
1374
+ agentMessages,
1375
+ existingClaim,
1376
+ caches
1377
+ });
1378
+ const resolution = resolveClaim({
1379
+ claims: claimsRef.current,
1380
+ context: {
1381
+ agentId,
1382
+ messageId: message.id,
1383
+ stateRenderId,
1384
+ runId: effectiveRunId,
1385
+ messageIndex
1386
+ },
1387
+ stateSnapshot: snapshotForClaim
1388
+ });
1389
+ if (resolution.action === ClaimAction.Block) return { canRender: false };
1390
+ if (resolution.updateRunId && claimsRef.current[message.id]) claimsRef.current[message.id].runId = resolution.updateRunId;
1391
+ if (resolution.nextClaim) claimsRef.current[message.id] = resolution.nextClaim;
1392
+ if (resolution.lockOthers) Object.entries(claimsRef.current).forEach(([id, claim]) => {
1393
+ if (id !== message.id && claim.stateRenderId === stateRenderId) claim.locked = true;
1394
+ });
1395
+ if (existingClaim && !existingClaim.locked && agentMessages?.length) {
1396
+ const indexInAgentMessages = agentMessages.findIndex((msg) => msg.id === message.id);
1397
+ if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) existingClaim.locked = true;
1398
+ }
1399
+ const existingSnapshot = claimsRef.current[message.id].stateSnapshot;
1400
+ const snapshotChanged = stateSnapshot && existingSnapshot !== void 0 && !areStatesEquals(existingSnapshot, snapshot);
1401
+ if (snapshot && (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) && (!claimsRef.current[message.id].locked || snapshotChanged)) {
1402
+ if (!claimsRef.current[message.id].locked || snapshotChanged) {
1403
+ claimsRef.current[message.id].stateSnapshot = snapshot;
1404
+ const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {} };
1405
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1406
+ snapshotCache[cacheKey] = snapshot;
1407
+ snapshotCache[`${stateRenderId}::latest`] = snapshot;
1408
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1409
+ const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {} };
1410
+ messageCache[message.id] = {
1411
+ snapshot,
1412
+ runId: effectiveRunId
1413
+ };
1414
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1415
+ if (stateSnapshot) claimsRef.current[message.id].locked = true;
1416
+ }
1417
+ } else if (snapshotForClaim) {
1418
+ if (!claimsRef.current[message.id].stateSnapshot) {
1419
+ claimsRef.current[message.id].stateSnapshot = snapshotForClaim;
1420
+ const snapshotCache = { ...store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {} };
1421
+ const cacheKey = `${stateRenderId}::${effectiveRunId}`;
1422
+ snapshotCache[cacheKey] = snapshotForClaim;
1423
+ snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;
1424
+ store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;
1425
+ const messageCache = { ...store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {} };
1426
+ messageCache[message.id] = {
1427
+ snapshot: snapshotForClaim,
1428
+ runId: effectiveRunId
1429
+ };
1430
+ store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;
1431
+ }
1432
+ }
1433
+ return { canRender: true };
1434
+ }
1435
+
1436
+ //#endregion
1437
+ //#region src/hooks/use-coagent-state-render-bridge.tsx
1438
+ function useCoagentStateRenderBridge(agentId, props) {
1439
+ const { stateSnapshot, message } = props;
1440
+ const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();
1441
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId });
1442
+ const [nodeName, setNodeName] = (0, react.useState)(void 0);
1443
+ const [, forceUpdate] = (0, react.useState)(0);
1444
+ (0, react.useEffect)(() => {
1445
+ if (!agent) return;
1446
+ const { unsubscribe } = agent.subscribe({
1447
+ onStateChanged: () => {
1448
+ forceUpdate((value) => value + 1);
1449
+ },
1450
+ onStepStartedEvent: ({ event }) => {
1451
+ if (event.stepName !== nodeName) setNodeName(event.stepName);
1452
+ },
1453
+ onStepFinishedEvent: ({ event }) => {
1454
+ if (event.stepName === nodeName) setNodeName(void 0);
1455
+ }
1456
+ });
1457
+ return () => {
1458
+ unsubscribe();
1459
+ };
1460
+ }, [agentId, nodeName]);
1461
+ const getStateRender = (0, react.useCallback)((messageId) => {
1462
+ return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {
1463
+ if (claimsRef.current[messageId]) return stateRenderId === claimsRef.current[messageId].stateRenderId;
1464
+ const matchingAgentName = stateRender.name === agentId;
1465
+ const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;
1466
+ return matchingAgentName && matchesNodeContext;
1467
+ });
1468
+ }, [
1469
+ coAgentStateRenders,
1470
+ nodeName,
1471
+ agentId
1472
+ ]);
1473
+ const stateRenderEntry = (0, react.useMemo)(() => getStateRender(message.id), [getStateRender, message.id]);
1474
+ const stateRenderId = stateRenderEntry?.[0];
1475
+ const stateRender = stateRenderEntry?.[1];
1476
+ const { canRender } = useStateRenderRegistry({
1477
+ agentId,
1478
+ stateRenderId,
1479
+ message: {
1480
+ ...message,
1481
+ runId: props.runId ?? message.runId
1482
+ },
1483
+ messageIndex: props.messageIndex,
1484
+ stateSnapshot,
1485
+ agentState: agent?.state,
1486
+ agentMessages: agent?.messages,
1487
+ claimsRef
1488
+ });
1489
+ return (0, react.useMemo)(() => {
1490
+ if (!stateRender || !stateRenderId) return null;
1491
+ if (!canRender) return null;
1492
+ if (stateRender.handler) stateRender.handler({
1493
+ state: stateSnapshot ? (0, _copilotkit_shared.parseJson)(stateSnapshot, stateSnapshot) : agent?.state ?? {},
1494
+ nodeName: nodeName ?? ""
1495
+ });
1496
+ if (stateRender.render) {
1497
+ const status = agent?.isRunning ? RenderStatus.InProgress : RenderStatus.Complete;
1498
+ if (typeof stateRender.render === "string") return stateRender.render;
1499
+ return stateRender.render({
1500
+ status,
1501
+ state: claimsRef.current[message.id].stateSnapshot ?? {},
1502
+ nodeName: nodeName ?? ""
1503
+ });
1504
+ }
1505
+ }, [
1506
+ stateRender,
1507
+ stateRenderId,
1508
+ agent?.state,
1509
+ agent?.isRunning,
1510
+ nodeName,
1511
+ message.id,
1512
+ stateSnapshot,
1513
+ canRender
1514
+ ]);
1515
+ }
1516
+ function CoAgentStateRenderBridge(props) {
1517
+ return useCoagentStateRenderBridge(props.agentId, props);
1518
+ }
1519
+
1520
+ //#endregion
1521
+ //#region src/components/CopilotListeners.tsx
1522
+ const usePredictStateSubscription = (agent) => {
1523
+ const predictStateToolsRef = (0, react.useRef)([]);
1524
+ const getSubscriber = (0, react.useCallback)((agent) => ({
1525
+ onCustomEvent: ({ event }) => {
1526
+ if (event.name === "PredictState") predictStateToolsRef.current = event.value;
1527
+ },
1528
+ onToolCallArgsEvent: ({ partialToolCallArgs, toolCallName }) => {
1529
+ predictStateToolsRef.current.forEach((t) => {
1530
+ if (t?.tool !== toolCallName) return;
1531
+ const emittedState = typeof partialToolCallArgs === "string" ? (0, _copilotkit_shared.parseJson)(partialToolCallArgs, partialToolCallArgs) : partialToolCallArgs;
1532
+ agent.setState({ [t.state_key]: emittedState[t.state_key] });
1533
+ });
1534
+ }
1535
+ }), []);
1536
+ (0, react.useEffect)(() => {
1537
+ if (!agent) return;
1538
+ const subscriber = getSubscriber(agent);
1539
+ const { unsubscribe } = agent.subscribe(subscriber);
1540
+ return () => {
1541
+ unsubscribe();
1542
+ };
1543
+ }, [agent, getSubscriber]);
1544
+ };
1545
+ function CopilotListeners() {
1546
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
1547
+ const resolvedAgentId = (0, _copilotkitnext_react.useCopilotChatConfiguration)()?.agentId;
1548
+ const { setBannerError } = useToast();
1549
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: resolvedAgentId });
1550
+ usePredictStateSubscription(agent);
1551
+ (0, react.useEffect)(() => {
1552
+ const subscription = copilotkit.subscribe({ onError: ({ error }) => {
1553
+ setBannerError(new _copilotkit_shared.CopilotKitLowLevelError({
1554
+ error,
1555
+ message: error.message,
1556
+ url: typeof window !== "undefined" ? window.location.href : ""
1557
+ }));
1558
+ } });
1559
+ return () => {
1560
+ subscription.unsubscribe();
1561
+ };
1562
+ }, [copilotkit?.subscribe]);
1563
+ return null;
1564
+ }
1565
+
1566
+ //#endregion
1567
+ //#region src/components/copilot-provider/copilotkit.tsx
1568
+ /**
1569
+ * This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks.
1570
+ *
1571
+ * ## Example
1572
+ *
1573
+ * You can find more information about self-hosting CopilotKit [here](/guides/self-hosting).
1574
+ *
1575
+ * ```tsx
1576
+ * import { CopilotKit } from "@copilotkit/react-core";
1577
+ *
1578
+ * <CopilotKit runtimeUrl="<your-runtime-url>">
1579
+ * // ... your app ...
1580
+ * </CopilotKit>
1581
+ * ```
1582
+ */
1583
+ function CopilotKit({ children, ...props }) {
1584
+ const enabled = shouldShowDevConsole(props.showDevConsole);
1585
+ const showInspector = shouldShowDevConsole(props.enableInspector);
1586
+ const publicApiKey = props.publicApiKey || props.publicLicenseKey;
1587
+ const renderArr = (0, react.useMemo)(() => [{ render: CoAgentStateRenderBridge }], []);
1588
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ToastProvider, {
1589
+ enabled,
1590
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotErrorBoundary, {
1591
+ publicApiKey,
1592
+ showUsageBanner: enabled,
1593
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ThreadsProvider, {
1594
+ threadId: props.threadId,
1595
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkitnext_react.CopilotKitProvider, {
1596
+ ...props,
1597
+ showDevConsole: showInspector,
1598
+ renderCustomMessages: renderArr,
1599
+ useSingleEndpoint: true,
1600
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitInternal, {
1601
+ ...props,
1602
+ children
1603
+ })
1604
+ })
1605
+ })
1606
+ })
1607
+ });
1608
+ }
1609
+ /**
1610
+ * Bridge component that subscribes to v2.x copilotkit core error events
1611
+ * and forwards them to v1.x error handling system.
1612
+ * This ensures only ONE subscription exists regardless of how many times
1613
+ * Chat components are rendered.
1614
+ */
1615
+ function CopilotKitErrorBridge() {
1616
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
1617
+ const { onError, copilotApiConfig } = useCopilotContext();
1618
+ (0, react.useEffect)(() => {
1619
+ if (!copilotkit) return;
1620
+ const subscription = copilotkit.subscribe({ onError: async (event) => {
1621
+ const errorEvent = {
1622
+ type: "error",
1623
+ timestamp: Date.now(),
1624
+ context: {
1625
+ source: "agent",
1626
+ request: {
1627
+ operation: event.code || "unknown",
1628
+ url: copilotApiConfig?.chatApiEndpoint,
1629
+ startTime: Date.now()
1630
+ },
1631
+ technical: {
1632
+ environment: "browser",
1633
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
1634
+ stackTrace: event.error.stack
1635
+ },
1636
+ ...event.context
1637
+ },
1638
+ error: event.error
1639
+ };
1640
+ try {
1641
+ await onError(errorEvent);
1642
+ } catch (handlerError) {
1643
+ console.error("Error in onError handler:", handlerError);
1644
+ }
1645
+ } });
1646
+ return () => {
1647
+ subscription.unsubscribe();
1648
+ };
1649
+ }, [
1650
+ copilotkit,
1651
+ onError,
1652
+ copilotApiConfig
1653
+ ]);
1654
+ return null;
1655
+ }
1656
+ function CopilotKitInternal(cpkProps) {
1657
+ const { children, ...props } = cpkProps;
1658
+ /**
1659
+ * This will throw an error if the props are invalid.
1660
+ */
1661
+ validateProps(cpkProps);
1662
+ const publicApiKey = props.publicLicenseKey || props.publicApiKey;
1663
+ const chatApiEndpoint = props.runtimeUrl || _copilotkit_shared.COPILOT_CLOUD_CHAT_URL;
1664
+ const [actions, setActions] = (0, react.useState)({});
1665
+ const [registeredActionConfigs, setRegisteredActionConfigs] = (0, react.useState)(/* @__PURE__ */ new Map());
1666
+ const chatComponentsCache = (0, react.useRef)({
1667
+ actions: {},
1668
+ coAgentStateRenders: {}
1669
+ });
1670
+ const { addElement, removeElement, printTree, getAllElements } = useTree();
1671
+ const [isLoading, setIsLoading] = (0, react.useState)(false);
1672
+ const [chatInstructions, setChatInstructions] = (0, react.useState)("");
1673
+ const [authStates, setAuthStates] = (0, react.useState)({});
1674
+ const [extensions, setExtensions] = (0, react.useState)({});
1675
+ const [additionalInstructions, setAdditionalInstructions] = (0, react.useState)([]);
1676
+ const { addElement: addDocument, removeElement: removeDocument, allElements: allDocuments } = useFlatCategoryStore();
1677
+ const setAction = (0, react.useCallback)((id, action) => {
1678
+ setActions((prevPoints) => {
1679
+ return {
1680
+ ...prevPoints,
1681
+ [id]: action
1682
+ };
1683
+ });
1684
+ }, []);
1685
+ const removeAction = (0, react.useCallback)((id) => {
1686
+ setActions((prevPoints) => {
1687
+ const newPoints = { ...prevPoints };
1688
+ delete newPoints[id];
1689
+ return newPoints;
1690
+ });
1691
+ }, []);
1692
+ const getContextString = (0, react.useCallback)((documents, categories) => {
1693
+ return `${documents.map((document) => {
1694
+ return `${document.name} (${document.sourceApplication}):\n${document.getContents()}`;
1695
+ }).join("\n\n")}\n\n${printTree(categories)}`;
1696
+ }, [printTree]);
1697
+ const addContext = (0, react.useCallback)((context, parentId, categories = defaultCopilotContextCategories) => {
1698
+ return addElement(context, categories, parentId);
1699
+ }, [addElement]);
1700
+ const removeContext = (0, react.useCallback)((id) => {
1701
+ removeElement(id);
1702
+ }, [removeElement]);
1703
+ const getAllContext = (0, react.useCallback)(() => {
1704
+ return getAllElements();
1705
+ }, [getAllElements]);
1706
+ const getFunctionCallHandler = (0, react.useCallback)((customEntryPoints) => {
1707
+ return entryPointsToFunctionCallHandler(Object.values(customEntryPoints || actions));
1708
+ }, [actions]);
1709
+ const getDocumentsContext = (0, react.useCallback)((categories) => {
1710
+ return allDocuments(categories);
1711
+ }, [allDocuments]);
1712
+ const addDocumentContext = (0, react.useCallback)((documentPointer, categories = defaultCopilotContextCategories) => {
1713
+ return addDocument(documentPointer, categories);
1714
+ }, [addDocument]);
1715
+ const removeDocumentContext = (0, react.useCallback)((documentId) => {
1716
+ removeDocument(documentId);
1717
+ }, [removeDocument]);
1718
+ const copilotApiConfig = (0, react.useMemo)(() => {
1719
+ let cloud = void 0;
1720
+ if (publicApiKey) cloud = { guardrails: { input: { restrictToTopic: {
1721
+ enabled: Boolean(props.guardrails_c),
1722
+ validTopics: props.guardrails_c?.validTopics || [],
1723
+ invalidTopics: props.guardrails_c?.invalidTopics || []
1724
+ } } } };
1725
+ return {
1726
+ publicApiKey,
1727
+ ...cloud ? { cloud } : {},
1728
+ chatApiEndpoint,
1729
+ headers: props.headers || {},
1730
+ properties: props.properties || {},
1731
+ transcribeAudioUrl: props.transcribeAudioUrl,
1732
+ textToSpeechUrl: props.textToSpeechUrl,
1733
+ credentials: props.credentials
1734
+ };
1735
+ }, [
1736
+ publicApiKey,
1737
+ props.headers,
1738
+ props.properties,
1739
+ props.transcribeAudioUrl,
1740
+ props.textToSpeechUrl,
1741
+ props.credentials,
1742
+ props.cloudRestrictToTopic,
1743
+ props.guardrails_c
1744
+ ]);
1745
+ (0, react.useMemo)(() => {
1746
+ const authHeaders = Object.values(authStates || {}).reduce((acc, state) => {
1747
+ if (state.status === "authenticated" && state.authHeaders) return {
1748
+ ...acc,
1749
+ ...Object.entries(state.authHeaders).reduce((headers, [key, value]) => ({
1750
+ ...headers,
1751
+ [key.startsWith("X-Custom-") ? key : `X-Custom-${key}`]: value
1752
+ }), {})
1753
+ };
1754
+ return acc;
1755
+ }, {});
1756
+ return {
1757
+ ...copilotApiConfig.headers || {},
1758
+ ...copilotApiConfig.publicApiKey ? { [_copilotkit_shared.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: copilotApiConfig.publicApiKey } : {},
1759
+ ...authHeaders
1760
+ };
1761
+ }, [
1762
+ copilotApiConfig.headers,
1763
+ copilotApiConfig.publicApiKey,
1764
+ authStates
1765
+ ]);
1766
+ const [internalErrorHandlers, _setInternalErrorHandler] = (0, react.useState)({});
1767
+ const setInternalErrorHandler = (0, react.useCallback)((handler) => {
1768
+ _setInternalErrorHandler((prev) => ({
1769
+ ...prev,
1770
+ ...handler
1771
+ }));
1772
+ }, []);
1773
+ const removeInternalErrorHandler = (0, react.useCallback)((key) => {
1774
+ _setInternalErrorHandler((prev) => {
1775
+ const { [key]: _removed, ...rest } = prev;
1776
+ return rest;
1777
+ });
1778
+ }, []);
1779
+ const onErrorRef = (0, react.useRef)(props.onError);
1780
+ (0, react.useEffect)(() => {
1781
+ onErrorRef.current = props.onError;
1782
+ }, [props.onError]);
1783
+ const internalHandlersRef = (0, react.useRef)({});
1784
+ (0, react.useEffect)(() => {
1785
+ internalHandlersRef.current = internalErrorHandlers;
1786
+ }, [internalErrorHandlers]);
1787
+ const handleErrors = (0, react.useCallback)(async (error) => {
1788
+ if (copilotApiConfig.publicApiKey && onErrorRef.current) try {
1789
+ await onErrorRef.current(error);
1790
+ } catch (e) {
1791
+ console.error("Error in public onError handler:", e);
1792
+ }
1793
+ const handlers = Object.values(internalHandlersRef.current);
1794
+ await Promise.all(handlers.map((h) => Promise.resolve(h(error)).catch((e) => console.error("Error in internal error handler:", e))));
1795
+ }, [copilotApiConfig.publicApiKey]);
1796
+ const [chatSuggestionConfiguration, setChatSuggestionConfiguration] = (0, react.useState)({});
1797
+ const addChatSuggestionConfiguration = (0, react.useCallback)((id, suggestion) => {
1798
+ setChatSuggestionConfiguration((prev) => ({
1799
+ ...prev,
1800
+ [id]: suggestion
1801
+ }));
1802
+ }, [setChatSuggestionConfiguration]);
1803
+ const removeChatSuggestionConfiguration = (0, react.useCallback)((id) => {
1804
+ setChatSuggestionConfiguration((prev) => {
1805
+ const { [id]: _, ...rest } = prev;
1806
+ return rest;
1807
+ });
1808
+ }, [setChatSuggestionConfiguration]);
1809
+ const [availableAgents, setAvailableAgents] = (0, react.useState)([]);
1810
+ const [coagentStates, setCoagentStates] = (0, react.useState)({});
1811
+ const coagentStatesRef = (0, react.useRef)({});
1812
+ const setCoagentStatesWithRef = (0, react.useCallback)((value) => {
1813
+ const newValue = typeof value === "function" ? value(coagentStatesRef.current) : value;
1814
+ coagentStatesRef.current = newValue;
1815
+ setCoagentStates((prev) => {
1816
+ return newValue;
1817
+ });
1818
+ }, []);
1819
+ let initialAgentSession = null;
1820
+ if (props.agent) initialAgentSession = { agentName: props.agent };
1821
+ const [agentSession, setAgentSession] = (0, react.useState)(initialAgentSession);
1822
+ (0, react.useEffect)(() => {
1823
+ if (props.agent) setAgentSession({ agentName: props.agent });
1824
+ else setAgentSession(null);
1825
+ }, [props.agent]);
1826
+ const { threadId, setThreadId: setInternalThreadId } = useThreads();
1827
+ const setThreadId = (0, react.useCallback)((value) => {
1828
+ if (props.threadId) throw new Error("Cannot call setThreadId() when threadId is provided via props.");
1829
+ setInternalThreadId(value);
1830
+ }, [props.threadId]);
1831
+ const [runId, setRunId] = (0, react.useState)(null);
1832
+ const chatAbortControllerRef = (0, react.useRef)(null);
1833
+ const showDevConsole = shouldShowDevConsole(props.showDevConsole);
1834
+ const [interruptActions, _setInterruptActions] = (0, react.useState)({});
1835
+ const setInterruptAction = (0, react.useCallback)((action) => {
1836
+ _setInterruptActions((prev) => {
1837
+ if (action == null || !action.id) return prev;
1838
+ return {
1839
+ ...prev,
1840
+ [action.id]: {
1841
+ ...prev[action.id] ?? {},
1842
+ ...action
1843
+ }
1844
+ };
1845
+ });
1846
+ }, []);
1847
+ const removeInterruptAction = (0, react.useCallback)((actionId) => {
1848
+ _setInterruptActions((prev) => {
1849
+ const { [actionId]: _, ...rest } = prev;
1850
+ return rest;
1851
+ });
1852
+ }, []);
1853
+ const [interruptEventQueue, setInterruptEventQueue] = (0, react.useState)({});
1854
+ const addInterruptEvent = (0, react.useCallback)((queuedEvent) => {
1855
+ setInterruptEventQueue((prev) => {
1856
+ const threadQueue = prev[queuedEvent.threadId] || [];
1857
+ return {
1858
+ ...prev,
1859
+ [queuedEvent.threadId]: [...threadQueue, queuedEvent]
1860
+ };
1861
+ });
1862
+ }, []);
1863
+ const resolveInterruptEvent = (0, react.useCallback)((threadId, eventId, response) => {
1864
+ setInterruptEventQueue((prev) => {
1865
+ const threadQueue = prev[threadId] || [];
1866
+ return {
1867
+ ...prev,
1868
+ [threadId]: threadQueue.map((queuedEvent) => queuedEvent.eventId === eventId ? {
1869
+ ...queuedEvent,
1870
+ event: {
1871
+ ...queuedEvent.event,
1872
+ response
1873
+ }
1874
+ } : queuedEvent)
1875
+ };
1876
+ });
1877
+ }, []);
1878
+ const memoizedChildren = (0, react.useMemo)(() => children, [children]);
1879
+ const [bannerError, setBannerError] = (0, react.useState)(null);
1880
+ const agentLock = (0, react.useMemo)(() => props.agent ?? null, [props.agent]);
1881
+ const forwardedParameters = (0, react.useMemo)(() => props.forwardedParameters ?? {}, [props.forwardedParameters]);
1882
+ const updateExtensions = (0, react.useCallback)((newExtensions) => {
1883
+ setExtensions((prev) => {
1884
+ const resolved = typeof newExtensions === "function" ? newExtensions(prev) : newExtensions;
1885
+ return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
1886
+ });
1887
+ }, [setExtensions]);
1888
+ const updateAuthStates = (0, react.useCallback)((newAuthStates) => {
1889
+ setAuthStates((prev) => {
1890
+ const resolved = typeof newAuthStates === "function" ? newAuthStates(prev) : newAuthStates;
1891
+ return Object.keys(resolved).length === Object.keys(prev).length && Object.entries(resolved).every(([key, value]) => prev[key] === value) ? prev : resolved;
1892
+ });
1893
+ }, [setAuthStates]);
1894
+ const handleSetRegisteredActions = (0, react.useCallback)((actionConfig) => {
1895
+ const key = actionConfig.action.name || (0, _copilotkit_shared.randomUUID)();
1896
+ setRegisteredActionConfigs((prev) => {
1897
+ const newMap = new Map(prev);
1898
+ newMap.set(key, actionConfig);
1899
+ return newMap;
1900
+ });
1901
+ return key;
1902
+ }, []);
1903
+ const handleRemoveRegisteredAction = (0, react.useCallback)((actionKey) => {
1904
+ setRegisteredActionConfigs((prev) => {
1905
+ const newMap = new Map(prev);
1906
+ newMap.delete(actionKey);
1907
+ return newMap;
1908
+ });
1909
+ }, []);
1910
+ const RegisteredActionsRenderer = (0, react.useMemo)(() => {
1911
+ return () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: Array.from(registeredActionConfigs.entries()).map(([key, config]) => {
1912
+ const Component = config.component;
1913
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, { action: config.action }, key);
1914
+ }) });
1915
+ }, [registeredActionConfigs]);
1916
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkitnext_react.CopilotChatConfigurationProvider, {
1917
+ agentId: props.agent ?? "default",
1918
+ threadId,
1919
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotContext.Provider, {
1920
+ value: {
1921
+ actions,
1922
+ chatComponentsCache,
1923
+ getFunctionCallHandler,
1924
+ setAction,
1925
+ removeAction,
1926
+ setRegisteredActions: handleSetRegisteredActions,
1927
+ removeRegisteredAction: handleRemoveRegisteredAction,
1928
+ getContextString,
1929
+ addContext,
1930
+ removeContext,
1931
+ getAllContext,
1932
+ getDocumentsContext,
1933
+ addDocumentContext,
1934
+ removeDocumentContext,
1935
+ copilotApiConfig,
1936
+ isLoading,
1937
+ setIsLoading,
1938
+ chatSuggestionConfiguration,
1939
+ addChatSuggestionConfiguration,
1940
+ removeChatSuggestionConfiguration,
1941
+ chatInstructions,
1942
+ setChatInstructions,
1943
+ additionalInstructions,
1944
+ setAdditionalInstructions,
1945
+ showDevConsole,
1946
+ coagentStates,
1947
+ setCoagentStates,
1948
+ coagentStatesRef,
1949
+ setCoagentStatesWithRef,
1950
+ agentSession,
1951
+ setAgentSession,
1952
+ forwardedParameters,
1953
+ agentLock,
1954
+ threadId,
1955
+ setThreadId,
1956
+ runId,
1957
+ setRunId,
1958
+ chatAbortControllerRef,
1959
+ availableAgents,
1960
+ authConfig_c: props.authConfig_c,
1961
+ authStates_c: authStates,
1962
+ setAuthStates_c: updateAuthStates,
1963
+ extensions,
1964
+ setExtensions: updateExtensions,
1965
+ interruptActions,
1966
+ setInterruptAction,
1967
+ removeInterruptAction,
1968
+ interruptEventQueue,
1969
+ addInterruptEvent,
1970
+ resolveInterruptEvent,
1971
+ bannerError,
1972
+ setBannerError,
1973
+ onError: handleErrors,
1974
+ internalErrorHandlers,
1975
+ setInternalErrorHandler,
1976
+ removeInternalErrorHandler
1977
+ },
1978
+ children: [
1979
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotListeners, {}),
1980
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotKitErrorBridge, {}),
1981
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CoAgentStateRendersProvider, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(MessagesTapProvider, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(CopilotMessages, { children: [memoizedChildren, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RegisteredActionsRenderer, {})] }) }), bannerError && showDevConsole && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(UsageBanner, {
1982
+ severity: bannerError.severity,
1983
+ message: bannerError.message,
1984
+ onClose: () => setBannerError(null),
1985
+ actions: getErrorActions(bannerError)
1986
+ })] })
1987
+ ]
1988
+ })
1989
+ });
1990
+ }
1991
+ const defaultCopilotContextCategories = ["global"];
1992
+ function entryPointsToFunctionCallHandler(actions) {
1993
+ return async ({ name, args }) => {
1994
+ let actionsByFunctionName = {};
1995
+ for (let action of actions) actionsByFunctionName[action.name] = action;
1996
+ const action = actionsByFunctionName[name];
1997
+ let result = void 0;
1998
+ if (action) {
1999
+ await new Promise((resolve, reject) => {
2000
+ (0, react_dom.flushSync)(async () => {
2001
+ try {
2002
+ result = await action.handler?.(args);
2003
+ resolve();
2004
+ } catch (error) {
2005
+ reject(error);
2006
+ }
2007
+ });
2008
+ });
2009
+ await new Promise((resolve) => setTimeout(resolve, 20));
2010
+ }
2011
+ return result;
2012
+ };
2013
+ }
2014
+ function formatFeatureName(featureName) {
2015
+ return featureName.replace(/_c$/, "").split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
2016
+ }
2017
+ function validateProps(props) {
2018
+ const cloudFeatures = Object.keys(props).filter((key) => key.endsWith("_c"));
2019
+ const hasApiKey = props.publicApiKey || props.publicLicenseKey;
2020
+ if (!props.runtimeUrl && !hasApiKey) throw new _copilotkit_shared.ConfigurationError("Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'");
2021
+ if (cloudFeatures.length > 0 && !hasApiKey) throw new _copilotkit_shared.MissingPublicApiKeyError(`Missing required prop: 'publicApiKey' or 'publicLicenseKey' to use cloud features: ${cloudFeatures.map(formatFeatureName).join(", ")}`);
2022
+ }
2023
+
2024
+ //#endregion
2025
+ //#region src/hooks/use-agent-nodename.ts
2026
+ function useAgentNodeName(agentName) {
2027
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: agentName });
2028
+ const nodeNameRef = (0, react.useRef)("start");
2029
+ (0, react.useEffect)(() => {
2030
+ if (!agent) return;
2031
+ const subscription = agent.subscribe({
2032
+ onStepStartedEvent: ({ event }) => {
2033
+ nodeNameRef.current = event.stepName;
2034
+ },
2035
+ onRunStartedEvent: () => {
2036
+ nodeNameRef.current = "start";
2037
+ },
2038
+ onRunFinishedEvent: () => {
2039
+ nodeNameRef.current = "end";
2040
+ }
2041
+ });
2042
+ return () => {
2043
+ subscription.unsubscribe();
2044
+ };
2045
+ }, [agent]);
2046
+ return nodeNameRef.current;
2047
+ }
2048
+
2049
+ //#endregion
2050
+ //#region src/hooks/use-langgraph-interrupt-render.ts
2051
+ const InterruptRenderer = ({ event, result, render, resolve }) => {
2052
+ return render({
2053
+ event,
2054
+ result,
2055
+ resolve
2056
+ });
2057
+ };
2058
+ function useLangGraphInterruptRender(agent) {
2059
+ const { interruptActions, agentSession, threadId, interruptEventQueue, addInterruptEvent, resolveInterruptEvent } = useCopilotContext();
2060
+ const nodeName = useAgentNodeName((0, _copilotkitnext_react.useCopilotChatConfiguration)()?.agentId ?? "default");
2061
+ (0, react.useEffect)(() => {
2062
+ if (!agent) return;
2063
+ let localInterrupt = null;
2064
+ const { unsubscribe } = agent.subscribe({
2065
+ onCustomEvent: ({ event }) => {
2066
+ if (event.name === "on_interrupt") {
2067
+ const eventData = {
2068
+ name: _copilotkit_runtime_client_gql.MetaEventName.LangGraphInterruptEvent,
2069
+ type: event.type,
2070
+ value: (0, _copilotkit_shared.parseJson)(event.value, event.value)
2071
+ };
2072
+ localInterrupt = {
2073
+ eventId: (0, _copilotkit_shared.dataToUUID)(eventData, "interruptEvents"),
2074
+ threadId,
2075
+ event: eventData
2076
+ };
2077
+ }
2078
+ },
2079
+ onRunStartedEvent: () => {
2080
+ localInterrupt = null;
2081
+ },
2082
+ onRunFinalized: () => {
2083
+ if (localInterrupt) {
2084
+ addInterruptEvent(localInterrupt);
2085
+ localInterrupt = null;
2086
+ }
2087
+ }
2088
+ });
2089
+ return () => {
2090
+ unsubscribe();
2091
+ };
2092
+ }, [agent, threadId]);
2093
+ const handleResolve = (0, react.useCallback)((eventId, response) => {
2094
+ agent?.runAgent({ forwardedProps: { command: { resume: response } } });
2095
+ resolveInterruptEvent(threadId, eventId, response ?? "");
2096
+ }, [agent, threadId]);
2097
+ return (0, react.useMemo)(() => {
2098
+ const currentQueuedEvent = (interruptEventQueue[threadId] || []).find((qe) => !qe.event.response);
2099
+ if (!currentQueuedEvent || !agentSession) return null;
2100
+ const matchingAction = Object.values(interruptActions).find((action) => {
2101
+ if (!action.enabled) return true;
2102
+ return action.enabled({
2103
+ eventValue: currentQueuedEvent.event.value,
2104
+ agentMetadata: {
2105
+ ...agentSession,
2106
+ nodeName
2107
+ }
2108
+ });
2109
+ });
2110
+ if (!matchingAction) return null;
2111
+ const { render, handler } = matchingAction;
2112
+ const resolveInterrupt = (response) => {
2113
+ handleResolve(currentQueuedEvent.eventId, response);
2114
+ };
2115
+ let result = null;
2116
+ if (handler) result = handler({
2117
+ event: currentQueuedEvent.event,
2118
+ resolve: resolveInterrupt
2119
+ });
2120
+ if (!render) return null;
2121
+ return react.default.createElement(InterruptRenderer, {
2122
+ event: currentQueuedEvent.event,
2123
+ result,
2124
+ render,
2125
+ resolve: resolveInterrupt
2126
+ });
2127
+ }, [
2128
+ interruptActions,
2129
+ interruptEventQueue,
2130
+ threadId,
2131
+ agentSession,
2132
+ handleResolve
2133
+ ]);
2134
+ }
2135
+
2136
+ //#endregion
2137
+ //#region src/hooks/use-lazy-tool-renderer.tsx
2138
+ function useLazyToolRenderer() {
2139
+ const renderToolCall = (0, _copilotkitnext_react.useRenderToolCall)();
2140
+ return (0, react.useCallback)((message, messages) => {
2141
+ if (!message?.toolCalls?.length) return null;
2142
+ const toolCall = message.toolCalls[0];
2143
+ if (!toolCall) return null;
2144
+ const toolMessage = messages?.find((m) => m.role === "tool" && m.toolCallId === toolCall.id);
2145
+ return () => renderToolCall({
2146
+ toolCall,
2147
+ toolMessage
2148
+ });
2149
+ }, [renderToolCall]);
2150
+ }
2151
+
2152
+ //#endregion
2153
+ //#region src/hooks/use-copilot-chat_internal.ts
2154
+ function useCopilotChatInternal({ suggestions, onInProgress, onSubmitMessage, onStopGeneration, onReloadMessages } = {}) {
2155
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
2156
+ const { threadId, agentSession } = useCopilotContext();
2157
+ const existingConfig = (0, _copilotkitnext_react.useCopilotChatConfiguration)();
2158
+ const [agentAvailable, setAgentAvailable] = (0, react.useState)(false);
2159
+ const resolvedAgentId = existingConfig?.agentId ?? "default";
2160
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: resolvedAgentId });
2161
+ (0, react.useEffect)(() => {
2162
+ const connect = async (agent) => {
2163
+ setAgentAvailable(false);
2164
+ try {
2165
+ await copilotkit.connectAgent({ agent });
2166
+ setAgentAvailable(true);
2167
+ } catch (error) {
2168
+ if (error instanceof _ag_ui_client.AGUIConnectNotImplementedError) {} else console.error("CopilotChat: connectAgent failed", error);
2169
+ }
2170
+ };
2171
+ if (agent && existingConfig?.threadId && agent.threadId !== existingConfig.threadId) {
2172
+ agent.threadId = existingConfig.threadId;
2173
+ connect(agent);
2174
+ }
2175
+ return () => {};
2176
+ }, [
2177
+ existingConfig?.threadId,
2178
+ agent,
2179
+ copilotkit,
2180
+ resolvedAgentId
2181
+ ]);
2182
+ (0, react.useEffect)(() => {
2183
+ onInProgress?.(Boolean(agent?.isRunning));
2184
+ }, [agent?.isRunning, onInProgress]);
2185
+ const interrupt = useLangGraphInterruptRender(agent);
2186
+ const reset = () => {
2187
+ agent?.setMessages([]);
2188
+ agent?.setState(null);
2189
+ };
2190
+ const latestDelete = useUpdatedRef((0, react.useCallback)((messageId) => {
2191
+ const filteredMessages = (agent?.messages ?? []).filter((message) => message.id !== messageId);
2192
+ agent?.setMessages(filteredMessages);
2193
+ }, [agent?.setMessages, agent?.messages]));
2194
+ const latestDeleteFunc = (0, react.useCallback)((messageId) => {
2195
+ return latestDelete.current(messageId);
2196
+ }, [latestDelete]);
2197
+ const currentSuggestions = (0, _copilotkitnext_react.useSuggestions)({ agentId: resolvedAgentId });
2198
+ const reload = useAsyncCallback(async (reloadMessageId) => {
2199
+ if (!agent) return;
2200
+ const messages = agent?.messages ?? [];
2201
+ if (agent.isRunning || messages.length === 0) return;
2202
+ const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);
2203
+ if (reloadMessageIndex === -1) {
2204
+ console.warn(`Message with id ${reloadMessageId} not found`);
2205
+ return;
2206
+ }
2207
+ const reloadMessageRole = messages[reloadMessageIndex].role;
2208
+ if (reloadMessageRole !== "assistant") {
2209
+ console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);
2210
+ return;
2211
+ }
2212
+ let historyCutoff = [messages[0]];
2213
+ if (messages.length > 2 && reloadMessageIndex !== 0) {
2214
+ const lastUserMessageBeforeRegenerate = messages.slice(0, reloadMessageIndex).reverse().find((msg) => msg.role === "user");
2215
+ if (!lastUserMessageBeforeRegenerate) historyCutoff = [messages[0]];
2216
+ else {
2217
+ const indexOfLastUserMessageBeforeRegenerate = messages.findIndex((msg) => msg.id === lastUserMessageBeforeRegenerate.id);
2218
+ historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);
2219
+ }
2220
+ } else if (messages.length > 2 && reloadMessageIndex === 0) historyCutoff = [messages[0], messages[1]];
2221
+ agent?.setMessages(historyCutoff);
2222
+ if (agent) try {
2223
+ await copilotkit.runAgent({ agent });
2224
+ } catch (error) {
2225
+ console.error("CopilotChat: runAgent failed during reload", error);
2226
+ }
2227
+ }, [
2228
+ agent?.messages.length,
2229
+ agent?.isRunning,
2230
+ agent?.setMessages,
2231
+ copilotkit?.runAgent
2232
+ ]);
2233
+ const latestSendMessageFunc = useAsyncCallback(async (message, options) => {
2234
+ if (!agent) return;
2235
+ const followUp = options?.followUp ?? true;
2236
+ if (options?.clearSuggestions) copilotkit.clearSuggestions(resolvedAgentId);
2237
+ if (onSubmitMessage) {
2238
+ 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 : "";
2239
+ try {
2240
+ await onSubmitMessage(content);
2241
+ } catch (error) {
2242
+ console.error("Error in onSubmitMessage:", error);
2243
+ }
2244
+ }
2245
+ agent?.addMessage(message);
2246
+ if (followUp) try {
2247
+ await copilotkit.runAgent({ agent });
2248
+ } catch (error) {
2249
+ console.error("CopilotChat: runAgent failed", error);
2250
+ }
2251
+ }, [
2252
+ agent,
2253
+ copilotkit,
2254
+ resolvedAgentId,
2255
+ onSubmitMessage
2256
+ ]);
2257
+ const latestAppendFunc = useAsyncCallback(async (message, options) => {
2258
+ return latestSendMessageFunc((0, _copilotkit_runtime_client_gql.gqlToAGUI)([message])[0], options);
2259
+ }, [latestSendMessageFunc]);
2260
+ const latestSetMessagesFunc = (0, react.useCallback)((messages) => {
2261
+ if (messages.every((message) => message instanceof _copilotkit_runtime_client_gql.Message)) return agent?.setMessages?.((0, _copilotkit_runtime_client_gql.gqlToAGUI)(messages));
2262
+ return agent?.setMessages?.(messages);
2263
+ }, [agent?.setMessages, agent]);
2264
+ const latestReload = useUpdatedRef(reload);
2265
+ const latestReloadFunc = useAsyncCallback(async (messageId) => {
2266
+ onReloadMessages?.({
2267
+ messageId,
2268
+ currentAgentName: agent?.agentId,
2269
+ messages: agent?.messages ?? []
2270
+ });
2271
+ return await latestReload.current(messageId);
2272
+ }, [
2273
+ latestReload,
2274
+ agent,
2275
+ onReloadMessages
2276
+ ]);
2277
+ const latestStopFunc = (0, react.useCallback)(() => {
2278
+ onStopGeneration?.({
2279
+ currentAgentName: agent?.agentId,
2280
+ messages: agent?.messages ?? []
2281
+ });
2282
+ return agent?.abortRun?.();
2283
+ }, [onStopGeneration, agent]);
2284
+ const latestReset = useUpdatedRef(reset);
2285
+ const latestResetFunc = (0, react.useCallback)(() => {
2286
+ return latestReset.current();
2287
+ }, [latestReset]);
2288
+ const lazyToolRendered = useLazyToolRenderer();
2289
+ const renderCustomMessage = (0, _copilotkitnext_react.useRenderCustomMessages)();
2290
+ const legacyCustomMessageRenderer = useLegacyCoagentRenderer({
2291
+ copilotkit,
2292
+ agent,
2293
+ agentId: resolvedAgentId,
2294
+ threadId: existingConfig?.threadId ?? threadId
2295
+ });
2296
+ const allMessages = agent?.messages ?? [];
2297
+ const resolvedMessages = (0, react.useMemo)(() => {
2298
+ let processedMessages = allMessages.map((message) => {
2299
+ if (message.role !== "assistant") return message;
2300
+ const lazyRendered = lazyToolRendered(message, allMessages);
2301
+ if (lazyRendered) {
2302
+ const renderedGenUi = lazyRendered();
2303
+ if (renderedGenUi) return {
2304
+ ...message,
2305
+ generativeUI: () => renderedGenUi
2306
+ };
2307
+ }
2308
+ const bridgeRenderer = legacyCustomMessageRenderer || renderCustomMessage ? () => {
2309
+ if (legacyCustomMessageRenderer) return legacyCustomMessageRenderer({
2310
+ message,
2311
+ position: "before"
2312
+ });
2313
+ try {
2314
+ return renderCustomMessage?.({
2315
+ message,
2316
+ position: "before"
2317
+ }) ?? null;
2318
+ } catch (error) {
2319
+ console.warn("[CopilotKit] renderCustomMessages failed, falling back to legacy renderer", error);
2320
+ return null;
2321
+ }
2322
+ } : null;
2323
+ if (bridgeRenderer) return {
2324
+ ...message,
2325
+ generativeUI: bridgeRenderer,
2326
+ generativeUIPosition: "before"
2327
+ };
2328
+ return message;
2329
+ });
2330
+ const hasAssistantMessages = processedMessages.some((msg) => msg.role === "assistant");
2331
+ const canUseCustomRenderer = Boolean(renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId));
2332
+ const placeholderRenderer = legacyCustomMessageRenderer ? legacyCustomMessageRenderer : canUseCustomRenderer ? renderCustomMessage : null;
2333
+ const shouldRenderPlaceholder = Boolean(agent?.isRunning) || Boolean(agent?.state && Object.keys(agent.state).length);
2334
+ const effectiveThreadId = threadId ?? agent?.threadId ?? "default";
2335
+ let latestUserIndex = -1;
2336
+ for (let i = processedMessages.length - 1; i >= 0; i -= 1) if (processedMessages[i].role === "user") {
2337
+ latestUserIndex = i;
2338
+ break;
2339
+ }
2340
+ const latestUserMessageId = latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : void 0;
2341
+ const currentRunId = latestUserMessageId ? copilotkit.getRunIdForMessage(resolvedAgentId, effectiveThreadId, latestUserMessageId) || `pending:${latestUserMessageId}` : void 0;
2342
+ const hasAssistantForCurrentRun = latestUserIndex >= 0 ? processedMessages.slice(latestUserIndex + 1).some((msg) => msg.role === "assistant") : hasAssistantMessages;
2343
+ if (placeholderRenderer && shouldRenderPlaceholder && !hasAssistantForCurrentRun) {
2344
+ const placeholderMessage = {
2345
+ id: currentRunId ? `coagent-state-render-${resolvedAgentId}-${currentRunId}` : `coagent-state-render-${resolvedAgentId}`,
2346
+ role: "assistant",
2347
+ content: "",
2348
+ name: "coagent-state-render",
2349
+ runId: currentRunId
2350
+ };
2351
+ processedMessages = [...processedMessages, {
2352
+ ...placeholderMessage,
2353
+ generativeUIPosition: "before",
2354
+ generativeUI: () => placeholderRenderer({
2355
+ message: placeholderMessage,
2356
+ position: "before"
2357
+ })
2358
+ }];
2359
+ }
2360
+ return processedMessages;
2361
+ }, [
2362
+ agent?.messages,
2363
+ lazyToolRendered,
2364
+ allMessages,
2365
+ renderCustomMessage,
2366
+ legacyCustomMessageRenderer,
2367
+ resolvedAgentId,
2368
+ copilotkit,
2369
+ agent?.isRunning,
2370
+ agent?.state
2371
+ ]);
2372
+ const renderedSuggestions = (0, react.useMemo)(() => {
2373
+ if (Array.isArray(suggestions)) return {
2374
+ suggestions: suggestions.map((s) => ({
2375
+ ...s,
2376
+ isLoading: false
2377
+ })),
2378
+ isLoading: false
2379
+ };
2380
+ return currentSuggestions;
2381
+ }, [suggestions, currentSuggestions]);
2382
+ return {
2383
+ messages: resolvedMessages,
2384
+ sendMessage: latestSendMessageFunc,
2385
+ appendMessage: latestAppendFunc,
2386
+ setMessages: latestSetMessagesFunc,
2387
+ reloadMessages: latestReloadFunc,
2388
+ stopGeneration: latestStopFunc,
2389
+ reset: latestResetFunc,
2390
+ deleteMessage: latestDeleteFunc,
2391
+ isAvailable: agentAvailable,
2392
+ isLoading: Boolean(agent?.isRunning),
2393
+ suggestions: renderedSuggestions.suggestions,
2394
+ setSuggestions: (suggestions) => copilotkit.addSuggestionsConfig({ suggestions }),
2395
+ generateSuggestions: async () => copilotkit.reloadSuggestions(resolvedAgentId),
2396
+ resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),
2397
+ isLoadingSuggestions: renderedSuggestions.isLoading,
2398
+ interrupt,
2399
+ agent,
2400
+ threadId
2401
+ };
2402
+ }
2403
+ function useUpdatedRef(value) {
2404
+ const ref = (0, react.useRef)(value);
2405
+ (0, react.useEffect)(() => {
2406
+ ref.current = value;
2407
+ }, [value]);
2408
+ return ref;
2409
+ }
2410
+ function useLegacyCoagentRenderer({ copilotkit, agent, agentId, threadId }) {
2411
+ return (0, react.useMemo)(() => {
2412
+ if (!copilotkit || !agent) return null;
2413
+ return ({ message, position }) => {
2414
+ const effectiveThreadId = threadId ?? agent.threadId ?? "default";
2415
+ const providedRunId = message.runId;
2416
+ return (0, react.createElement)(CoAgentStateRenderBridge, {
2417
+ message,
2418
+ position,
2419
+ runId: (providedRunId ? providedRunId : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id)) || `pending:${message.id}`,
2420
+ messageIndex: Math.max(agent.messages.findIndex((msg) => msg.id === message.id), 0),
2421
+ messageIndexInRun: 0,
2422
+ numberOfMessagesInRun: 1,
2423
+ agentId,
2424
+ stateSnapshot: message.state
2425
+ });
2426
+ };
2427
+ }, [
2428
+ agent,
2429
+ agentId,
2430
+ copilotkit,
2431
+ threadId
2432
+ ]);
2433
+ }
2434
+
2435
+ //#endregion
2436
+ //#region src/hooks/use-copilot-chat.ts
2437
+ /**
2438
+ * `useCopilotChat` is a lightweight React hook for headless chat interactions.
2439
+ * Perfect for controlling the prebuilt chat components programmatically.
2440
+ *
2441
+ * **Open Source Friendly** - Works without requiring a free public license key.
2442
+ *
2443
+ * <Callout title="Looking for fully headless UI?">
2444
+ * Get started with [useCopilotChatHeadless_c](https://docs.copilotkit.ai/reference/v1/hooks/useCopilotChatHeadless_c).
2445
+ * </Callout>
2446
+ *
2447
+ * ## Use Cases
2448
+ *
2449
+ * - **Programmatic Messaging**: Send messages without displaying chat UI
2450
+ * - **Programmatic control**: Control prebuilt component programmatically
2451
+ * - **Background Operations**: Trigger AI interactions in the background
2452
+ * - **Fire-and-Forget**: Send messages without needing to read responses
2453
+ *
2454
+ * ## Usage
2455
+ *
2456
+ * ```tsx
2457
+ * import { TextMessage, MessageRole } from "@copilotkit/runtime-client-gql";
2458
+ *
2459
+ * const { appendMessage } = useCopilotChat();
2460
+ *
2461
+ * // Example usage without naming conflicts
2462
+ * const handleSendMessage = async (content: string) => {
2463
+ * await appendMessage(
2464
+ * new TextMessage({
2465
+ * role: MessageRole.User,
2466
+ * content,
2467
+ * })
2468
+ * );
2469
+ * };
2470
+ * ```
2471
+ *
2472
+ * ## Return Values
2473
+ * The following properties are returned from the hook:
2474
+ *
2475
+ * <PropertyReference name="visibleMessages" type="DeprecatedGqlMessage[]" deprecated>
2476
+ * Array of messages in old non-AG-UI format, use for compatibility only
2477
+ * </PropertyReference>
2478
+ *
2479
+ * <PropertyReference name="appendMessage" type="(message: DeprecatedGqlMessage, options?) => Promise<void>" deprecated>
2480
+ * Append message using old format, use `sendMessage` instead
2481
+ * </PropertyReference>
2482
+ *
2483
+ * <PropertyReference name="reloadMessages" type="(messageId: string) => Promise<void>">
2484
+ * Regenerate the response for a specific message by ID
2485
+ * </PropertyReference>
2486
+ *
2487
+ * <PropertyReference name="stopGeneration" type="() => void">
2488
+ * Stop the current message generation process
2489
+ * </PropertyReference>
2490
+ *
2491
+ * <PropertyReference name="reset" type="() => void">
2492
+ * Clear all messages and reset chat state completely
2493
+ * </PropertyReference>
2494
+ *
2495
+ * <PropertyReference name="isLoading" type="boolean">
2496
+ * Whether the chat is currently generating a response
2497
+ * </PropertyReference>
2498
+ *
2499
+ * <PropertyReference name="runChatCompletion" type="() => Promise<Message[]>">
2500
+ * Manually trigger chat completion for advanced usage
2501
+ * </PropertyReference>
2502
+ *
2503
+ * <PropertyReference name="mcpServers" type="MCPServerConfig[]">
2504
+ * Array of Model Context Protocol server configurations
2505
+ * </PropertyReference>
2506
+ *
2507
+ * <PropertyReference name="setMcpServers" type="(servers: MCPServerConfig[]) => void">
2508
+ * Update MCP server configurations for enhanced context
2509
+ * </PropertyReference>
2510
+ */
2511
+ /**
2512
+ * A lightweight React hook for headless chat interactions.
2513
+ * Perfect for programmatic messaging, background operations, and custom UI implementations.
2514
+ *
2515
+ * **Open Source Friendly** - Works without requiring a `publicApiKey`.
2516
+ */
2517
+ function useCopilotChat(options = {}) {
2518
+ const { visibleMessages, appendMessage, reloadMessages, stopGeneration, reset, isLoading, isAvailable, runChatCompletion, mcpServers, setMcpServers } = useCopilotChatInternal(options);
2519
+ return {
2520
+ visibleMessages,
2521
+ appendMessage,
2522
+ reloadMessages,
2523
+ stopGeneration,
2524
+ reset,
2525
+ isLoading,
2526
+ isAvailable,
2527
+ runChatCompletion,
2528
+ mcpServers,
2529
+ setMcpServers
2530
+ };
2531
+ }
2532
+
2533
+ //#endregion
2534
+ //#region src/hooks/use-copilot-chat-headless_c.ts
2535
+ /**
2536
+ * `useCopilotChatHeadless_c` is for building fully custom UI (headless UI) implementations.
2537
+ *
2538
+ * <Callout title="This is a premium-only feature">
2539
+ * Sign up for free on [Copilot Cloud](https://cloud.copilotkit.ai) to get your public license key or read more about <a href="/premium/overview">premium features</a>.
2540
+ *
2541
+ * Usage is generous, **free** to get started, and works with **either self-hosted or Copilot Cloud** environments.
2542
+ * </Callout>
2543
+ *
2544
+ * ## Key Features
2545
+ *
2546
+ * - **Fully headless**: Build your own fully custom UI's for your agentic applications.
2547
+ * - **Advanced Suggestions**: Direct access to suggestions array with full control
2548
+ * - **Interrupt Handling**: Support for advanced interrupt functionality
2549
+ * - **MCP Server Support**: Model Context Protocol server configurations
2550
+ * - **Chat Controls**: Complete set of chat management functions
2551
+ * - **Loading States**: Comprehensive loading state management
2552
+ *
2553
+ *
2554
+ * ## Usage
2555
+ *
2556
+ * ### Basic Setup
2557
+ *
2558
+ * ```tsx
2559
+ * import { CopilotKit } from "@copilotkit/react-core";
2560
+ * import { useCopilotChatHeadless_c } from "@copilotkit/react-core";
2561
+ *
2562
+ * export function App() {
2563
+ * return (
2564
+ * <CopilotKit publicApiKey="your-free-public-license-key">
2565
+ * <YourComponent />
2566
+ * </CopilotKit>
2567
+ * );
2568
+ * }
2569
+ *
2570
+ * export function YourComponent() {
2571
+ * const { messages, sendMessage, isLoading } = useCopilotChatHeadless_c();
2572
+ *
2573
+ * const handleSendMessage = async () => {
2574
+ * await sendMessage({
2575
+ * id: "123",
2576
+ * role: "user",
2577
+ * content: "Hello World",
2578
+ * });
2579
+ * };
2580
+ *
2581
+ * return (
2582
+ * <div>
2583
+ * {messages.map(msg => <div key={msg.id}>{msg.content}</div>)}
2584
+ * <button onClick={handleSendMessage} disabled={isLoading}>
2585
+ * Send Message
2586
+ * </button>
2587
+ * </div>
2588
+ * );
2589
+ * }
2590
+ * ```
2591
+ *
2592
+ * ### Working with Suggestions
2593
+ *
2594
+ * ```tsx
2595
+ * import { useCopilotChatHeadless_c, useCopilotChatSuggestions } from "@copilotkit/react-core";
2596
+ *
2597
+ * export function SuggestionExample() {
2598
+ * const {
2599
+ * suggestions,
2600
+ * setSuggestions,
2601
+ * generateSuggestions,
2602
+ * isLoadingSuggestions
2603
+ * } = useCopilotChatHeadless_c();
2604
+ *
2605
+ * // Configure AI suggestion generation
2606
+ * useCopilotChatSuggestions({
2607
+ * instructions: "Suggest helpful actions based on the current context",
2608
+ * maxSuggestions: 3
2609
+ * });
2610
+ *
2611
+ * return (
2612
+ * <div>
2613
+ * {suggestions.map(suggestion => (
2614
+ * <button key={suggestion.title}>{suggestion.title}</button>
2615
+ * ))}
2616
+ * <button onClick={generateSuggestions} disabled={isLoadingSuggestions}>
2617
+ * Generate Suggestions
2618
+ * </button>
2619
+ * </div>
2620
+ * );
2621
+ * }
2622
+ * ```
2623
+ *
2624
+ * ## Return Values
2625
+ * The following properties are returned from the hook:
2626
+ *
2627
+ * <PropertyReference name="messages" type="Message[]">
2628
+ * The messages currently in the chat in AG-UI format
2629
+ * </PropertyReference>
2630
+ *
2631
+ * <PropertyReference name="sendMessage" type="(message: Message, options?) => Promise<void>">
2632
+ * Send a new message to the chat and trigger AI response
2633
+ * </PropertyReference>
2634
+ *
2635
+ * <PropertyReference name="setMessages" type="(messages: Message[] | DeprecatedGqlMessage[]) => void">
2636
+ * Replace all messages in the chat with new array
2637
+ * </PropertyReference>
2638
+ *
2639
+ * <PropertyReference name="deleteMessage" type="(messageId: string) => void">
2640
+ * Remove a specific message by ID from the chat
2641
+ * </PropertyReference>
2642
+ *
2643
+ * <PropertyReference name="reloadMessages" type="(messageId: string) => Promise<void>">
2644
+ * Regenerate the response for a specific message by ID
2645
+ * </PropertyReference>
2646
+ *
2647
+ * <PropertyReference name="stopGeneration" type="() => void">
2648
+ * Stop the current message generation process
2649
+ * </PropertyReference>
2650
+ *
2651
+ * <PropertyReference name="reset" type="() => void">
2652
+ * Clear all messages and reset chat state completely
2653
+ * </PropertyReference>
2654
+ *
2655
+ * <PropertyReference name="isLoading" type="boolean">
2656
+ * Whether the chat is currently generating a response
2657
+ * </PropertyReference>
2658
+ *
2659
+ * <PropertyReference name="runChatCompletion" type="() => Promise<Message[]>">
2660
+ * Manually trigger chat completion for advanced usage
2661
+ * </PropertyReference>
2662
+ *
2663
+ * <PropertyReference name="mcpServers" type="MCPServerConfig[]">
2664
+ * Array of Model Context Protocol server configurations
2665
+ * </PropertyReference>
2666
+ *
2667
+ * <PropertyReference name="setMcpServers" type="(servers: MCPServerConfig[]) => void">
2668
+ * Update MCP server configurations for enhanced context
2669
+ * </PropertyReference>
2670
+ *
2671
+ * <PropertyReference name="suggestions" type="SuggestionItem[]">
2672
+ * Current suggestions array for reading or manual control
2673
+ * </PropertyReference>
2674
+ *
2675
+ * <PropertyReference name="setSuggestions" type="(suggestions: SuggestionItem[]) => void">
2676
+ * Manually set suggestions for custom workflows
2677
+ * </PropertyReference>
2678
+ *
2679
+ * <PropertyReference name="generateSuggestions" type="() => Promise<void>">
2680
+ * Trigger AI-powered suggestion generation using configured settings
2681
+ * </PropertyReference>
2682
+ *
2683
+ * <PropertyReference name="resetSuggestions" type="() => void">
2684
+ * Clear all current suggestions and reset generation state
2685
+ * </PropertyReference>
2686
+ *
2687
+ * <PropertyReference name="isLoadingSuggestions" type="boolean">
2688
+ * Whether suggestions are currently being generated
2689
+ * </PropertyReference>
2690
+ *
2691
+ * <PropertyReference name="interrupt" type="string | React.ReactElement | null">
2692
+ * Interrupt content for human-in-the-loop workflows
2693
+ * </PropertyReference>
2694
+ */
2695
+ const createNonFunctionalReturn = () => ({
2696
+ visibleMessages: [],
2697
+ messages: [],
2698
+ sendMessage: async () => {},
2699
+ appendMessage: async () => {},
2700
+ setMessages: () => {},
2701
+ deleteMessage: () => {},
2702
+ reloadMessages: async () => {},
2703
+ stopGeneration: () => {},
2704
+ reset: () => {},
2705
+ isLoading: false,
2706
+ isAvailable: false,
2707
+ runChatCompletion: async () => [],
2708
+ mcpServers: [],
2709
+ setMcpServers: () => {},
2710
+ suggestions: [],
2711
+ setSuggestions: () => {},
2712
+ generateSuggestions: async () => {},
2713
+ resetSuggestions: () => {},
2714
+ isLoadingSuggestions: false,
2715
+ interrupt: null
2716
+ });
2717
+ /**
2718
+ * Enterprise React hook that provides complete chat functionality for fully custom UI implementations.
2719
+ * Includes all advanced features like direct message access, suggestions array, interrupt handling, and MCP support.
2720
+ *
2721
+ * **Requires a publicApiKey** - Sign up for free at https://cloud.copilotkit.ai/
2722
+ *
2723
+ * @param options - Configuration options for the chat
2724
+ * @returns Complete chat interface with all enterprise features
2725
+ *
2726
+ * @example
2727
+ * ```tsx
2728
+ * const { messages, sendMessage, suggestions, interrupt } = useCopilotChatHeadless_c();
2729
+ * ```
2730
+ */
2731
+ function useCopilotChatHeadless_c(options = {}) {
2732
+ const { copilotApiConfig, setBannerError } = useCopilotContext();
2733
+ const hasPublicApiKey = Boolean(copilotApiConfig.publicApiKey);
2734
+ const internalResult = useCopilotChatInternal(options);
2735
+ (0, react.useEffect)(() => {
2736
+ if (!hasPublicApiKey) {
2737
+ setBannerError(new _copilotkit_shared.CopilotKitError({
2738
+ message: "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.",
2739
+ code: _copilotkit_shared.CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR,
2740
+ severity: _copilotkit_shared.Severity.WARNING,
2741
+ visibility: _copilotkit_shared.ErrorVisibility.BANNER
2742
+ }));
2743
+ _copilotkit_shared.styledConsole.logCopilotKitPlatformMessage();
2744
+ } else setBannerError(null);
2745
+ }, [hasPublicApiKey]);
2746
+ if (hasPublicApiKey) return internalResult;
2747
+ return createNonFunctionalReturn();
2748
+ }
2749
+
2750
+ //#endregion
2751
+ //#region src/hooks/use-frontend-tool.ts
2752
+ function useFrontendTool(tool, dependencies) {
2753
+ const { name, description, parameters, render, followUp, available } = tool;
2754
+ const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
2755
+ const renderRef = (0, react.useRef)(render);
2756
+ (0, react.useEffect)(() => {
2757
+ renderRef.current = render;
2758
+ }, [render, ...dependencies ?? []]);
2759
+ const normalizedRender = (0, react.useMemo)(() => {
2760
+ if (typeof render === "undefined") return;
2761
+ return ((args) => {
2762
+ const currentRender = renderRef.current;
2763
+ if (typeof currentRender === "undefined") return null;
2764
+ if (typeof currentRender === "string") return react.default.createElement(react.default.Fragment, null, currentRender);
2765
+ const rendered = currentRender({
2766
+ ...args,
2767
+ result: typeof args.result === "string" ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
2768
+ });
2769
+ if (typeof rendered === "string") return react.default.createElement(react.default.Fragment, null, rendered);
2770
+ return rendered ?? null;
2771
+ });
2772
+ }, []);
2773
+ const handlerRef = (0, react.useRef)(tool.handler);
2774
+ (0, react.useEffect)(() => {
2775
+ handlerRef.current = tool.handler;
2776
+ }, [tool.handler, ...dependencies ?? []]);
2777
+ (0, _copilotkitnext_react.useFrontendTool)({
2778
+ name,
2779
+ description,
2780
+ parameters: zodParameters,
2781
+ handler: tool.handler ? (args) => handlerRef.current?.(args) : void 0,
2782
+ followUp,
2783
+ render: normalizedRender,
2784
+ available: available === void 0 ? void 0 : available !== "disabled"
2785
+ });
2786
+ }
2787
+
2788
+ //#endregion
2789
+ //#region src/hooks/use-render-tool-call.ts
2790
+ function useRenderToolCall(tool, dependencies) {
2791
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
2792
+ const hasAddedRef = (0, react.useRef)(false);
2793
+ (0, react.useEffect)(() => {
2794
+ const { name, parameters, render } = tool;
2795
+ const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
2796
+ const renderToolCall = name === "*" ? (0, _copilotkitnext_react.defineToolCallRenderer)({
2797
+ name: "*",
2798
+ render: ((args) => {
2799
+ return render({
2800
+ ...args,
2801
+ result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
2802
+ });
2803
+ })
2804
+ }) : (0, _copilotkitnext_react.defineToolCallRenderer)({
2805
+ name,
2806
+ args: zodParameters,
2807
+ render: ((args) => {
2808
+ return render({
2809
+ ...args,
2810
+ result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result
2811
+ });
2812
+ })
2813
+ });
2814
+ const existingIndex = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
2815
+ if (existingIndex !== -1) copilotkit.renderToolCalls.splice(existingIndex, 1);
2816
+ copilotkit.renderToolCalls.push(renderToolCall);
2817
+ hasAddedRef.current = true;
2818
+ return () => {
2819
+ if (hasAddedRef.current) {
2820
+ const index = copilotkit.renderToolCalls.findIndex((r) => r.name === name);
2821
+ if (index !== -1) copilotkit.renderToolCalls.splice(index, 1);
2822
+ hasAddedRef.current = false;
2823
+ }
2824
+ };
2825
+ }, [tool, ...dependencies ?? []]);
2826
+ }
2827
+
2828
+ //#endregion
2829
+ //#region src/hooks/use-human-in-the-loop.ts
2830
+ function useHumanInTheLoop(tool, dependencies) {
2831
+ const { render, ...toolRest } = tool;
2832
+ const { name, description, parameters, followUp } = toolRest;
2833
+ const zodParameters = (0, _copilotkit_shared.getZodParameters)(parameters);
2834
+ const renderRef = (0, react.useRef)(null);
2835
+ (0, react.useEffect)(() => {
2836
+ renderRef.current = (args) => {
2837
+ if (typeof render === "string") return react.default.createElement(react.default.Fragment, null, render);
2838
+ if (!render) return null;
2839
+ const rendered = render((() => {
2840
+ const mappedArgs = args.args;
2841
+ switch (args.status) {
2842
+ case _copilotkitnext_core.ToolCallStatus.InProgress: return {
2843
+ args: mappedArgs,
2844
+ respond: args.respond,
2845
+ status: args.status,
2846
+ handler: void 0
2847
+ };
2848
+ case _copilotkitnext_core.ToolCallStatus.Executing: return {
2849
+ args: mappedArgs,
2850
+ respond: args.respond,
2851
+ status: args.status,
2852
+ handler: () => {}
2853
+ };
2854
+ case _copilotkitnext_core.ToolCallStatus.Complete: return {
2855
+ args: mappedArgs,
2856
+ respond: args.respond,
2857
+ status: args.status,
2858
+ result: args.result ? (0, _copilotkit_shared.parseJson)(args.result, args.result) : args.result,
2859
+ handler: void 0
2860
+ };
2861
+ default: throw new _copilotkit_shared.CopilotKitError({
2862
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN,
2863
+ message: `Invalid tool call status: ${args.status}`
2864
+ });
2865
+ }
2866
+ })());
2867
+ if (typeof rendered === "string") return react.default.createElement(react.default.Fragment, null, rendered);
2868
+ return rendered ?? null;
2869
+ };
2870
+ }, [render, ...dependencies ?? []]);
2871
+ (0, _copilotkitnext_react.useHumanInTheLoop)({
2872
+ name,
2873
+ description,
2874
+ followUp,
2875
+ parameters: zodParameters,
2876
+ render: ((args) => renderRef.current?.(args) ?? null)
2877
+ });
2878
+ }
2879
+
2880
+ //#endregion
2881
+ //#region src/hooks/use-copilot-action.ts
2882
+ /**
2883
+ * Example usage of useCopilotAction with complex parameters:
2884
+ *
2885
+ * @example
2886
+ * useCopilotAction({
2887
+ * name: "myAction",
2888
+ * parameters: [
2889
+ * { name: "arg1", type: "string", enum: ["option1", "option2", "option3"], required: false },
2890
+ * { name: "arg2", type: "number" },
2891
+ * {
2892
+ * name: "arg3",
2893
+ * type: "object",
2894
+ * attributes: [
2895
+ * { name: "nestedArg1", type: "boolean" },
2896
+ * { name: "xyz", required: false },
2897
+ * ],
2898
+ * },
2899
+ * { name: "arg4", type: "number[]" },
2900
+ * ],
2901
+ * handler: ({ arg1, arg2, arg3, arg4 }) => {
2902
+ * const x = arg3.nestedArg1;
2903
+ * const z = arg3.xyz;
2904
+ * console.log(arg1, arg2, arg3);
2905
+ * },
2906
+ * });
2907
+ *
2908
+ * @example
2909
+ * // Simple action without parameters
2910
+ * useCopilotAction({
2911
+ * name: "myAction",
2912
+ * handler: () => {
2913
+ * console.log("No parameters provided.");
2914
+ * },
2915
+ * });
2916
+ *
2917
+ * @example
2918
+ * // Interactive action with UI rendering and response handling
2919
+ * useCopilotAction({
2920
+ * name: "handleMeeting",
2921
+ * description: "Handle a meeting by booking or canceling",
2922
+ * parameters: [
2923
+ * {
2924
+ * name: "meeting",
2925
+ * type: "string",
2926
+ * description: "The meeting to handle",
2927
+ * required: true,
2928
+ * },
2929
+ * {
2930
+ * name: "date",
2931
+ * type: "string",
2932
+ * description: "The date of the meeting",
2933
+ * required: true,
2934
+ * },
2935
+ * {
2936
+ * name: "title",
2937
+ * type: "string",
2938
+ * description: "The title of the meeting",
2939
+ * required: true,
2940
+ * },
2941
+ * ],
2942
+ * renderAndWaitForResponse: ({ args, respond, status }) => {
2943
+ * const { meeting, date, title } = args;
2944
+ * return (
2945
+ * <MeetingConfirmationDialog
2946
+ * meeting={meeting}
2947
+ * date={date}
2948
+ * title={title}
2949
+ * onConfirm={() => respond('meeting confirmed')}
2950
+ * onCancel={() => respond('meeting canceled')}
2951
+ * />
2952
+ * );
2953
+ * },
2954
+ * });
2955
+ *
2956
+ * @example
2957
+ * // Catch all action allows you to render actions that are not defined in the frontend
2958
+ * useCopilotAction({
2959
+ * name: "*",
2960
+ * render: ({ name, args, status, result, handler, respond }) => {
2961
+ * return <div>Rendering action: {name}</div>;
2962
+ * },
2963
+ * });
2964
+ */
2965
+ /**
2966
+ * <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif" width="500" />
2967
+ * `useCopilotAction` is a React hook that you can use in your application to provide
2968
+ * custom actions that can be called by the AI. Essentially, it allows the Copilot to
2969
+ * execute these actions contextually during a chat, based on the user's interactions
2970
+ * and needs.
2971
+ *
2972
+ * Here's how it works:
2973
+ *
2974
+ * Use `useCopilotAction` to set up actions that the Copilot can call. To provide
2975
+ * more context to the Copilot, you can provide it with a `description` (for example to explain
2976
+ * what the action does, under which conditions it can be called, etc.).
2977
+ *
2978
+ * Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers,
2979
+ * or complex, e.g. objects or arrays.
2980
+ *
2981
+ * Finally, you provide a `handler` function that receives the parameters and returns a result.
2982
+ * CopilotKit takes care of automatically inferring the parameter types, so you get type safety
2983
+ * and autocompletion for free.
2984
+ *
2985
+ * To render a custom UI for the action, you can provide a `render()` function. This function
2986
+ * lets you render a custom component or return a string to display.
2987
+ *
2988
+ * ## Usage
2989
+ *
2990
+ * ### Simple Usage
2991
+ *
2992
+ * ```tsx
2993
+ * useCopilotAction({
2994
+ * name: "sayHello",
2995
+ * description: "Say hello to someone.",
2996
+ * parameters: [
2997
+ * {
2998
+ * name: "name",
2999
+ * type: "string",
3000
+ * description: "name of the person to say greet",
3001
+ * },
3002
+ * ],
3003
+ * handler: async ({ name }) => {
3004
+ * alert(`Hello, ${name}!`);
3005
+ * },
3006
+ * });
3007
+ * ```
3008
+ *
3009
+ * ## Generative UI
3010
+ *
3011
+ * This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](/guides/generative-ui) page.
3012
+ */
3013
+ function getActionConfig(action) {
3014
+ if (action.name === "*") return {
3015
+ type: "render",
3016
+ action
3017
+ };
3018
+ if ("renderAndWaitForResponse" in action || "renderAndWait" in action) {
3019
+ let render = action.render;
3020
+ if (!render && "renderAndWaitForResponse" in action) render = action.renderAndWaitForResponse;
3021
+ if (!render && "renderAndWait" in action) render = action.renderAndWait;
3022
+ return {
3023
+ type: "hitl",
3024
+ action: {
3025
+ ...action,
3026
+ render
3027
+ }
3028
+ };
3029
+ }
3030
+ if ("available" in action) {
3031
+ if (action.available === "enabled" || action.available === "remote") return {
3032
+ type: "frontend",
3033
+ action
3034
+ };
3035
+ if (action.available === "frontend" || action.available === "disabled") return {
3036
+ type: "render",
3037
+ action
3038
+ };
3039
+ }
3040
+ if ("handler" in action) return {
3041
+ type: "frontend",
3042
+ action
3043
+ };
3044
+ throw new Error("Invalid action configuration");
3045
+ }
3046
+ /**
3047
+ * useCopilotAction is a legacy hook maintained for backwards compatibility.
3048
+ *
3049
+ * To avoid violating React's Rules of Hooks (which prohibit conditional hook calls),
3050
+ * we use a registration pattern:
3051
+ * 1. This hook registers the action configuration with the CopilotContext
3052
+ * 2. A renderer component in CopilotKit actually renders the appropriate hook wrapper
3053
+ * 3. React properly manages hook state since components are rendered, not conditionally called
3054
+ *
3055
+ * This allows action types to change between renders without corrupting React's hook state.
3056
+ */
3057
+ function useCopilotAction(action, dependencies) {
3058
+ const [initialActionConfig] = (0, react.useState)(getActionConfig(action));
3059
+ const currentActionConfig = getActionConfig(action);
3060
+ /**
3061
+ * Calling hooks conditionally violates React's Rules of Hooks. This rule exists because
3062
+ * React maintains the call stack for hooks like useEffect or useState, and conditionally
3063
+ * calling a hook would result in inconsistent call stacks between renders.
3064
+ *
3065
+ * Unfortunately, useCopilotAction _has_ to conditionally call a hook based on the
3066
+ * supplied parameters. In order to avoid breaking React's call stack tracking, while
3067
+ * breaking the Rule of Hooks, we use a ref to store the initial action configuration
3068
+ * and throw an error if the _configuration_ changes such that we would call a different hook.
3069
+ */
3070
+ if (initialActionConfig.type !== currentActionConfig.type) throw new Error("Action configuration changed between renders");
3071
+ switch (currentActionConfig.type) {
3072
+ case "render": return useRenderToolCall(currentActionConfig.action, dependencies);
3073
+ case "hitl": return useHumanInTheLoop(currentActionConfig.action, dependencies);
3074
+ case "frontend": return useFrontendTool(currentActionConfig.action, dependencies);
3075
+ default: throw new Error("Invalid action configuration");
3076
+ }
3077
+ }
3078
+
3079
+ //#endregion
3080
+ //#region src/hooks/use-coagent-state-render.ts
3081
+ /**
3082
+ * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.
3083
+ * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.
3084
+ *
3085
+ * ## Usage
3086
+ *
3087
+ * ### Simple Usage
3088
+ *
3089
+ * ```tsx
3090
+ * import { useCoAgentStateRender } from "@copilotkit/react-core";
3091
+ *
3092
+ * type YourAgentState = {
3093
+ * agent_state_property: string;
3094
+ * }
3095
+ *
3096
+ * useCoAgentStateRender<YourAgentState>({
3097
+ * name: "basic_agent",
3098
+ * nodeName: "optionally_specify_a_specific_node",
3099
+ * render: ({ status, state, nodeName }) => {
3100
+ * return (
3101
+ * <YourComponent
3102
+ * agentStateProperty={state.agent_state_property}
3103
+ * status={status}
3104
+ * nodeName={nodeName}
3105
+ * />
3106
+ * );
3107
+ * },
3108
+ * });
3109
+ * ```
3110
+ *
3111
+ * This allows for you to render UI components or text based on what is happening within the agent.
3112
+ *
3113
+ * ### Example
3114
+ * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.
3115
+ * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).
3116
+ *
3117
+ * <Callout type="info">
3118
+ * This example is hosted on Vercel and may take a few seconds to load.
3119
+ * </Callout>
3120
+ *
3121
+ * <iframe src="https://examples-coagents-ai-researcher-ui.vercel.app/" className="w-full rounded-lg border h-[700px] my-4" />
3122
+ */
3123
+ /**
3124
+ * This hook is used to render agent state with custom UI components or text. This is particularly
3125
+ * useful for showing intermediate state or progress during Agentic Copilot operations.
3126
+ * To get started using rendering intermediate state through this hook, checkout the documentation.
3127
+ *
3128
+ * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates
3129
+ */
3130
+ function useCoAgentStateRender(action, dependencies) {
3131
+ const { chatComponentsCache, availableAgents } = (0, react.useContext)(CopilotContext);
3132
+ const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } = useCoAgentStateRenders();
3133
+ const idRef = (0, react.useRef)((0, _copilotkit_shared.randomId)());
3134
+ const { setBannerError, addToast } = useToast();
3135
+ (0, react.useEffect)(() => {
3136
+ if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {
3137
+ `${action.name}`;
3138
+ setBannerError(new _copilotkit_shared.CopilotKitAgentDiscoveryError({
3139
+ agentName: action.name,
3140
+ availableAgents: availableAgents.map((a) => ({
3141
+ name: a.name,
3142
+ id: a.id
3143
+ }))
3144
+ }));
3145
+ }
3146
+ }, [availableAgents]);
3147
+ const key = `${action.name}-${action.nodeName || "global"}`;
3148
+ if (dependencies === void 0) {
3149
+ if (coAgentStateRenders[idRef.current]) {
3150
+ coAgentStateRenders[idRef.current].handler = action.handler;
3151
+ if (typeof action.render === "function") {
3152
+ if (chatComponentsCache.current !== null) chatComponentsCache.current.coAgentStateRenders[key] = action.render;
3153
+ }
3154
+ }
3155
+ }
3156
+ (0, react.useEffect)(() => {
3157
+ const currentId = idRef.current;
3158
+ if (Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
3159
+ if (id === currentId) return false;
3160
+ if (otherAction.name !== action.name) return false;
3161
+ const hasNodeName = !!action.nodeName;
3162
+ const hasOtherNodeName = !!otherAction.nodeName;
3163
+ if (!hasNodeName && !hasOtherNodeName) return true;
3164
+ if (hasNodeName !== hasOtherNodeName) return false;
3165
+ return action.nodeName === otherAction.nodeName;
3166
+ })) addToast({
3167
+ type: "warning",
3168
+ message: action.nodeName ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden` : `Found multiple state renders for agent ${action.name}. State renders might get overridden`,
3169
+ id: `dup-action-${action.name}`
3170
+ });
3171
+ }, [coAgentStateRenders]);
3172
+ (0, react.useEffect)(() => {
3173
+ setCoAgentStateRender(idRef.current, action);
3174
+ if (chatComponentsCache.current !== null && action.render !== void 0) chatComponentsCache.current.coAgentStateRenders[key] = action.render;
3175
+ return () => {
3176
+ removeCoAgentStateRender(idRef.current);
3177
+ };
3178
+ }, [
3179
+ setCoAgentStateRender,
3180
+ removeCoAgentStateRender,
3181
+ action.name,
3182
+ typeof action.render === "string" ? action.render : void 0,
3183
+ ...dependencies || []
3184
+ ]);
3185
+ }
3186
+
3187
+ //#endregion
3188
+ //#region src/hooks/use-make-copilot-document-readable.ts
3189
+ /**
3190
+ * Makes a document readable by Copilot.
3191
+ * @param document The document to make readable.
3192
+ * @param categories The categories to associate with the document.
3193
+ * @param dependencies The dependencies to use for the effect.
3194
+ * @returns The id of the document.
3195
+ */
3196
+ function useMakeCopilotDocumentReadable(document, categories, dependencies = []) {
3197
+ const { addDocumentContext, removeDocumentContext } = useCopilotContext();
3198
+ const idRef = (0, react.useRef)(void 0);
3199
+ (0, react.useEffect)(() => {
3200
+ const id = addDocumentContext(document, categories);
3201
+ idRef.current = id;
3202
+ return () => {
3203
+ removeDocumentContext(id);
3204
+ };
3205
+ }, [
3206
+ addDocumentContext,
3207
+ removeDocumentContext,
3208
+ ...dependencies
3209
+ ]);
3210
+ return idRef.current;
3211
+ }
3212
+
3213
+ //#endregion
3214
+ //#region src/hooks/use-copilot-readable.ts
3215
+ /**
3216
+ * `useCopilotReadable` is a React hook that provides app-state and other information
3217
+ * to the Copilot. Optionally, the hook can also handle hierarchical state within your
3218
+ * application, passing these parent-child relationships to the Copilot.
3219
+ *
3220
+ * ## Usage
3221
+ *
3222
+ * ### Simple Usage
3223
+ *
3224
+ * In its most basic usage, useCopilotReadable accepts a single string argument
3225
+ * representing any piece of app state, making it available for the Copilot to use
3226
+ * as context when responding to user input.
3227
+ *
3228
+ * ```tsx
3229
+ * import { useCopilotReadable } from "@copilotkit/react-core";
3230
+ *
3231
+ * export function MyComponent() {
3232
+ * const [employees, setEmployees] = useState([]);
3233
+ *
3234
+ * useCopilotReadable({
3235
+ * description: "The list of employees",
3236
+ * value: employees,
3237
+ * });
3238
+ * }
3239
+ * ```
3240
+ *
3241
+ * ### Nested Components
3242
+ *
3243
+ * Optionally, you can maintain the hierarchical structure of information by passing
3244
+ * `parentId`. This allows you to use `useCopilotReadable` in nested components:
3245
+ *
3246
+ * ```tsx /employeeContextId/1 {17,23}
3247
+ * import { useCopilotReadable } from "@copilotkit/react-core";
3248
+ *
3249
+ * function Employee(props: EmployeeProps) {
3250
+ * const { employeeName, workProfile, metadata } = props;
3251
+ *
3252
+ * // propagate any information to copilot
3253
+ * const employeeContextId = useCopilotReadable({
3254
+ * description: "Employee name",
3255
+ * value: employeeName
3256
+ * });
3257
+ *
3258
+ * // Pass a parentID to maintain a hierarchical structure.
3259
+ * // Especially useful with child React components, list elements, etc.
3260
+ * useCopilotReadable({
3261
+ * description: "Work profile",
3262
+ * value: workProfile.description(),
3263
+ * parentId: employeeContextId
3264
+ * });
3265
+ *
3266
+ * useCopilotReadable({
3267
+ * description: "Employee metadata",
3268
+ * value: metadata.description(),
3269
+ * parentId: employeeContextId
3270
+ * });
3271
+ *
3272
+ * return (
3273
+ * // Render as usual...
3274
+ * );
3275
+ * }
3276
+ * ```
3277
+ */
3278
+ /**
3279
+ * Adds the given information to the Copilot context to make it readable by Copilot.
3280
+ */
3281
+ function useCopilotReadable({ description, value, convert, available }, dependencies) {
3282
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
3283
+ const ctxIdRef = (0, react.useRef)(void 0);
3284
+ (0, react.useEffect)(() => {
3285
+ if (!copilotkit) return;
3286
+ const found = Object.entries(copilotkit.context).find(([id, ctxItem]) => {
3287
+ return JSON.stringify({
3288
+ description,
3289
+ value
3290
+ }) == JSON.stringify(ctxItem);
3291
+ });
3292
+ if (found) {
3293
+ ctxIdRef.current = found[0];
3294
+ if (available === "disabled") copilotkit.removeContext(ctxIdRef.current);
3295
+ return;
3296
+ }
3297
+ if (!found && available === "disabled") return;
3298
+ ctxIdRef.current = copilotkit.addContext({
3299
+ description,
3300
+ value: (convert ?? JSON.stringify)(value)
3301
+ });
3302
+ return () => {
3303
+ if (!ctxIdRef.current) return;
3304
+ copilotkit.removeContext(ctxIdRef.current);
3305
+ };
3306
+ }, [
3307
+ description,
3308
+ value,
3309
+ convert
3310
+ ]);
3311
+ return ctxIdRef.current;
3312
+ }
3313
+
3314
+ //#endregion
3315
+ //#region src/hooks/use-coagent.ts
3316
+ /**
3317
+ * <Callout type="info">
3318
+ * Usage of this hook assumes some additional setup in your application, for more information
3319
+ * on that see the CoAgents <span className="text-blue-500">[getting started guide](/coagents/quickstart/langgraph)</span>.
3320
+ * </Callout>
3321
+ * <Frame className="my-12">
3322
+ * <img
3323
+ * src="https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif"
3324
+ * alt="CoAgents demonstration"
3325
+ * className="w-auto"
3326
+ * />
3327
+ * </Frame>
3328
+ *
3329
+ * This hook is used to integrate an agent into your application. With its use, you can
3330
+ * render and update the state of an agent, allowing for a dynamic and interactive experience.
3331
+ * We call these shared state experiences agentic copilots, or CoAgents for short.
3332
+ *
3333
+ * ## Usage
3334
+ *
3335
+ * ### Simple Usage
3336
+ *
3337
+ * ```tsx
3338
+ * import { useCoAgent } from "@copilotkit/react-core";
3339
+ *
3340
+ * type AgentState = {
3341
+ * count: number;
3342
+ * }
3343
+ *
3344
+ * const agent = useCoAgent<AgentState>({
3345
+ * name: "my-agent",
3346
+ * initialState: {
3347
+ * count: 0,
3348
+ * },
3349
+ * });
3350
+ *
3351
+ * ```
3352
+ *
3353
+ * `useCoAgent` returns an object with the following properties:
3354
+ *
3355
+ * ```tsx
3356
+ * const {
3357
+ * name, // The name of the agent currently being used.
3358
+ * nodeName, // The name of the current LangGraph node.
3359
+ * state, // The current state of the agent.
3360
+ * setState, // A function to update the state of the agent.
3361
+ * running, // A boolean indicating if the agent is currently running.
3362
+ * start, // A function to start the agent.
3363
+ * stop, // A function to stop the agent.
3364
+ * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.
3365
+ * } = agent;
3366
+ * ```
3367
+ *
3368
+ * Finally we can leverage these properties to create reactive experiences with the agent!
3369
+ *
3370
+ * ```tsx
3371
+ * const { state, setState } = useCoAgent<AgentState>({
3372
+ * name: "my-agent",
3373
+ * initialState: {
3374
+ * count: 0,
3375
+ * },
3376
+ * });
3377
+ *
3378
+ * return (
3379
+ * <div>
3380
+ * <p>Count: {state.count}</p>
3381
+ * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>
3382
+ * </div>
3383
+ * );
3384
+ * ```
3385
+ *
3386
+ * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.
3387
+ *
3388
+ * ## Parameters
3389
+ * <PropertyReference name="options" type="UseCoagentOptions<T>" required>
3390
+ * The options to use when creating the coagent.
3391
+ * <PropertyReference name="name" type="string" required>
3392
+ * The name of the agent to use.
3393
+ * </PropertyReference>
3394
+ * <PropertyReference name="initialState" type="T | any">
3395
+ * The initial state of the agent.
3396
+ * </PropertyReference>
3397
+ * <PropertyReference name="state" type="T | any">
3398
+ * State to manage externally if you are using this hook with external state management.
3399
+ * </PropertyReference>
3400
+ * <PropertyReference name="setState" type="(newState: T | ((prevState: T | undefined) => T)) => void">
3401
+ * A function to update the state of the agent if you are using this hook with external state management.
3402
+ * </PropertyReference>
3403
+ * </PropertyReference>
3404
+ */
3405
+ /**
3406
+ * This hook is used to integrate an agent into your application. With its use, you can
3407
+ * render and update the state of the agent, allowing for a dynamic and interactive experience.
3408
+ * We call these shared state experiences "agentic copilots". To get started using agentic copilots, which
3409
+ * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.
3410
+ */
3411
+ function useCoAgent(options) {
3412
+ const { agent } = (0, _copilotkitnext_react.useAgent)({ agentId: options.name });
3413
+ const { copilotkit } = (0, _copilotkitnext_react.useCopilotKit)();
3414
+ const nodeName = useAgentNodeName(options.name);
3415
+ const handleStateUpdate = (0, react.useCallback)((newState) => {
3416
+ if (!agent) return;
3417
+ if (typeof newState === "function") {
3418
+ const updater = newState;
3419
+ agent.setState(updater(agent.state));
3420
+ } else agent.setState({
3421
+ ...agent.state,
3422
+ ...newState
3423
+ });
3424
+ }, [agent?.state, agent?.setState]);
3425
+ (0, react.useEffect)(() => {
3426
+ if (!options.config && !options.configurable) return;
3427
+ let config = options.config ?? {};
3428
+ if (options.configurable) config = {
3429
+ ...config,
3430
+ configurable: {
3431
+ ...options.configurable,
3432
+ ...config.configurable
3433
+ }
3434
+ };
3435
+ copilotkit.setProperties(config);
3436
+ }, [options.config, options.configurable]);
3437
+ (0, react.useEffect)(() => {
3438
+ if (agent?.state && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) handleStateUpdate(options.state);
3439
+ }, [
3440
+ agent,
3441
+ (0, react.useMemo)(() => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0, [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]),
3442
+ handleStateUpdate
3443
+ ]);
3444
+ const hasStateValues = (0, react.useCallback)((value) => {
3445
+ return Boolean(value && Object.keys(value).length);
3446
+ }, []);
3447
+ const initialStateRef = (0, react.useRef)(isExternalStateManagement(options) ? options.state : "initialState" in options ? options.initialState : void 0);
3448
+ (0, react.useEffect)(() => {
3449
+ if (isExternalStateManagement(options)) initialStateRef.current = options.state;
3450
+ else if ("initialState" in options) initialStateRef.current = options.initialState;
3451
+ }, [isExternalStateManagement(options) ? JSON.stringify(options.state) : "initialState" in options ? JSON.stringify(options.initialState) : void 0]);
3452
+ (0, react.useEffect)(() => {
3453
+ if (!agent) return;
3454
+ const subscription = agent.subscribe({
3455
+ onStateChanged: (args) => {
3456
+ if (isExternalStateManagement(options)) options.setState(args.state);
3457
+ },
3458
+ onRunInitialized: (args) => {
3459
+ if (hasStateValues(args.state)) {
3460
+ handleStateUpdate(args.state);
3461
+ return;
3462
+ }
3463
+ if (hasStateValues(agent.state)) return;
3464
+ if (initialStateRef.current !== void 0) handleStateUpdate(initialStateRef.current);
3465
+ }
3466
+ });
3467
+ return () => {
3468
+ subscription.unsubscribe();
3469
+ };
3470
+ }, [
3471
+ agent,
3472
+ handleStateUpdate,
3473
+ hasStateValues
3474
+ ]);
3475
+ return (0, react.useMemo)(() => {
3476
+ if (!agent) {
3477
+ const noop = () => {};
3478
+ const noopAsync = async () => {};
3479
+ const initialState = ("state" in options && options.state) ?? ("initialState" in options && options.initialState) ?? {};
3480
+ return {
3481
+ name: options.name,
3482
+ nodeName,
3483
+ threadId: void 0,
3484
+ running: false,
3485
+ state: initialState,
3486
+ setState: noop,
3487
+ start: noop,
3488
+ stop: noop,
3489
+ run: noopAsync
3490
+ };
3491
+ }
3492
+ return {
3493
+ name: agent?.agentId ?? options.name,
3494
+ nodeName,
3495
+ threadId: agent.threadId,
3496
+ running: agent.isRunning,
3497
+ state: agent.state,
3498
+ setState: handleStateUpdate,
3499
+ start: agent.runAgent,
3500
+ stop: agent.abortRun,
3501
+ run: agent.runAgent
3502
+ };
3503
+ }, [
3504
+ agent?.state,
3505
+ agent?.runAgent,
3506
+ agent?.abortRun,
3507
+ agent?.runAgent,
3508
+ agent?.threadId,
3509
+ agent?.isRunning,
3510
+ agent?.agentId,
3511
+ handleStateUpdate,
3512
+ options.name
3513
+ ]);
3514
+ }
3515
+ const isExternalStateManagement = (options) => {
3516
+ return "state" in options && "setState" in options;
3517
+ };
3518
+
3519
+ //#endregion
3520
+ //#region src/hooks/use-copilot-runtime-client.ts
3521
+ const useCopilotRuntimeClient = (options) => {
3522
+ const { setBannerError } = useToast();
3523
+ const { showDevConsole, onError, ...runtimeOptions } = options;
3524
+ const lastStructuredErrorRef = (0, react.useRef)(null);
3525
+ const traceUIError = async (error, originalError) => {
3526
+ try {
3527
+ await onError({
3528
+ type: "error",
3529
+ timestamp: Date.now(),
3530
+ context: {
3531
+ source: "ui",
3532
+ request: {
3533
+ operation: "runtimeClient",
3534
+ url: runtimeOptions.url,
3535
+ startTime: Date.now()
3536
+ },
3537
+ technical: {
3538
+ environment: "browser",
3539
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0,
3540
+ stackTrace: originalError instanceof Error ? originalError.stack : void 0
3541
+ }
3542
+ },
3543
+ error
3544
+ });
3545
+ } catch (error) {
3546
+ console.error("Error in onError handler:", error);
3547
+ }
3548
+ };
3549
+ return (0, react.useMemo)(() => {
3550
+ return new _copilotkit_runtime_client_gql.CopilotRuntimeClient({
3551
+ ...runtimeOptions,
3552
+ handleGQLErrors: (error) => {
3553
+ if (error.graphQLErrors?.length) {
3554
+ const graphQLErrors = error.graphQLErrors;
3555
+ const routeError = (gqlError) => {
3556
+ if (gqlError.extensions?.visibility === _copilotkit_shared.ErrorVisibility.SILENT) {
3557
+ console.error("CopilotKit Silent Error:", gqlError.message);
3558
+ return;
3559
+ }
3560
+ const now = Date.now();
3561
+ const errorMessage = gqlError.message;
3562
+ if (lastStructuredErrorRef.current && lastStructuredErrorRef.current.message === errorMessage && now - lastStructuredErrorRef.current.timestamp < 150) return;
3563
+ lastStructuredErrorRef.current = {
3564
+ message: errorMessage,
3565
+ timestamp: now
3566
+ };
3567
+ const ckError = createStructuredError(gqlError);
3568
+ if (ckError) {
3569
+ setBannerError(ckError);
3570
+ traceUIError(ckError, gqlError);
3571
+ } else {
3572
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
3573
+ message: gqlError.message,
3574
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
3575
+ });
3576
+ setBannerError(fallbackError);
3577
+ traceUIError(fallbackError, gqlError);
3578
+ }
3579
+ };
3580
+ graphQLErrors.forEach(routeError);
3581
+ } else {
3582
+ const fallbackError = new _copilotkit_shared.CopilotKitError({
3583
+ message: error?.message || String(error),
3584
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
3585
+ });
3586
+ setBannerError(fallbackError);
3587
+ traceUIError(fallbackError, error);
3588
+ }
3589
+ },
3590
+ handleGQLWarning: (message) => {
3591
+ console.warn(message);
3592
+ setBannerError(new _copilotkit_shared.CopilotKitError({
3593
+ message,
3594
+ code: _copilotkit_shared.CopilotKitErrorCode.UNKNOWN
3595
+ }));
3596
+ }
3597
+ });
3598
+ }, [
3599
+ runtimeOptions,
3600
+ setBannerError,
3601
+ onError
3602
+ ]);
3603
+ };
3604
+ function createStructuredError(gqlError) {
3605
+ const extensions = gqlError.extensions;
3606
+ const originalError = extensions?.originalError;
3607
+ const message = originalError?.message || gqlError.message;
3608
+ const code = extensions?.code;
3609
+ if (code) return new _copilotkit_shared.CopilotKitError({
3610
+ message,
3611
+ code
3612
+ });
3613
+ if (originalError?.stack?.includes("CopilotApiDiscoveryError")) return new _copilotkit_shared.CopilotKitApiDiscoveryError({ message });
3614
+ if (originalError?.stack?.includes("CopilotKitRemoteEndpointDiscoveryError")) return new _copilotkit_shared.CopilotKitRemoteEndpointDiscoveryError({ message });
3615
+ if (originalError?.stack?.includes("CopilotKitAgentDiscoveryError")) return new _copilotkit_shared.CopilotKitAgentDiscoveryError({
3616
+ agentName: "",
3617
+ availableAgents: []
3618
+ });
3619
+ return null;
3620
+ }
3621
+
3622
+ //#endregion
3623
+ //#region src/hooks/use-copilot-authenticated-action.ts
3624
+ /**
3625
+ * Hook to create an authenticated action that requires user sign-in before execution.
3626
+ *
3627
+ * @remarks
3628
+ * This feature is only available when using CopilotKit's hosted cloud service.
3629
+ * To use this feature, sign up at https://cloud.copilotkit.ai to get your publicApiKey.
3630
+ *
3631
+ * @param action - The frontend action to be wrapped with authentication
3632
+ * @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed
3633
+ */
3634
+ function useCopilotAuthenticatedAction_c(action, dependencies) {
3635
+ const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
3636
+ const pendingActionRef = (0, react.useRef)(null);
3637
+ const executeAction = (0, react.useCallback)((props) => {
3638
+ if (typeof action.render === "function") return action.render(props);
3639
+ return action.render || react.default.createElement(react.Fragment);
3640
+ }, [action]);
3641
+ const wrappedRender = (0, react.useCallback)((props) => {
3642
+ if (!Object.values(authStates_c || {}).some((state) => state.status === "authenticated")) {
3643
+ pendingActionRef.current = props;
3644
+ return authConfig_c?.SignInComponent ? react.default.createElement(authConfig_c.SignInComponent, { onSignInComplete: (authState) => {
3645
+ setAuthStates_c?.((prev) => ({
3646
+ ...prev,
3647
+ [action.name]: authState
3648
+ }));
3649
+ if (pendingActionRef.current) {
3650
+ executeAction(pendingActionRef.current);
3651
+ pendingActionRef.current = null;
3652
+ }
3653
+ } }) : react.default.createElement(react.Fragment);
3654
+ }
3655
+ return executeAction(props);
3656
+ }, [
3657
+ action,
3658
+ authStates_c,
3659
+ setAuthStates_c
3660
+ ]);
3661
+ useCopilotAction({
3662
+ ...action,
3663
+ render: wrappedRender
3664
+ }, dependencies);
3665
+ }
3666
+
3667
+ //#endregion
3668
+ //#region src/hooks/use-langgraph-interrupt.ts
3669
+ function useLangGraphInterrupt(action, dependencies) {
3670
+ const { setInterruptAction, removeInterruptAction, interruptActions, threadId } = (0, react.useContext)(CopilotContext);
3671
+ const { addToast } = useToast();
3672
+ const actionId = (0, _copilotkit_shared.dataToUUID)(action, "lgAction");
3673
+ (0, react.useEffect)(() => {
3674
+ if (!action) return;
3675
+ setInterruptAction({
3676
+ ...action,
3677
+ id: actionId
3678
+ });
3679
+ return () => {
3680
+ removeInterruptAction(actionId);
3681
+ };
3682
+ }, [
3683
+ setInterruptAction,
3684
+ removeInterruptAction,
3685
+ threadId,
3686
+ actionId,
3687
+ ...dependencies || []
3688
+ ]);
3689
+ }
3690
+
3691
+ //#endregion
3692
+ //#region src/hooks/use-copilot-additional-instructions.ts
3693
+ /**
3694
+ * `useCopilotAdditionalInstructions` is a React hook that provides additional instructions
3695
+ * to the Copilot.
3696
+ *
3697
+ * ## Usage
3698
+ *
3699
+ * ### Simple Usage
3700
+ *
3701
+ * In its most basic usage, useCopilotAdditionalInstructions accepts a single string argument
3702
+ * representing the instructions to be added to the Copilot.
3703
+ *
3704
+ * ```tsx
3705
+ * import { useCopilotAdditionalInstructions } from "@copilotkit/react-core";
3706
+ *
3707
+ * export function MyComponent() {
3708
+ * useCopilotAdditionalInstructions({
3709
+ * instructions: "Do not answer questions about the weather.",
3710
+ * });
3711
+ * }
3712
+ * ```
3713
+ *
3714
+ * ### Conditional Usage
3715
+ *
3716
+ * You can also conditionally add instructions based on the state of your app.
3717
+ *
3718
+ * ```tsx
3719
+ * import { useCopilotAdditionalInstructions } from "@copilotkit/react-core";
3720
+ *
3721
+ * export function MyComponent() {
3722
+ * const [showInstructions, setShowInstructions] = useState(false);
3723
+ *
3724
+ * useCopilotAdditionalInstructions({
3725
+ * available: showInstructions ? "enabled" : "disabled",
3726
+ * instructions: "Do not answer questions about the weather.",
3727
+ * });
3728
+ * }
3729
+ * ```
3730
+ */
3731
+ /**
3732
+ * Adds the given instructions to the Copilot context.
3733
+ */
3734
+ function useCopilotAdditionalInstructions({ instructions, available = "enabled" }, dependencies) {
3735
+ const { setAdditionalInstructions } = useCopilotContext();
3736
+ (0, react.useEffect)(() => {
3737
+ if (available === "disabled") return;
3738
+ setAdditionalInstructions((prevInstructions) => [...prevInstructions || [], instructions]);
3739
+ return () => {
3740
+ setAdditionalInstructions((prevInstructions) => prevInstructions?.filter((instruction) => instruction !== instructions) || []);
3741
+ };
3742
+ }, [
3743
+ available,
3744
+ instructions,
3745
+ setAdditionalInstructions,
3746
+ ...dependencies || []
3747
+ ]);
3748
+ }
3749
+
3750
+ //#endregion
3751
+ //#region src/hooks/use-default-tool.ts
3752
+ function useDefaultTool(tool, dependencies) {
3753
+ useCopilotAction({
3754
+ ...tool,
3755
+ name: "*"
3756
+ }, dependencies);
3757
+ }
3758
+
3759
+ //#endregion
3760
+ //#region src/hooks/use-copilot-chat-suggestions.tsx
3761
+ /**
3762
+ * <Callout type="warning">
3763
+ * useCopilotChatSuggestions is experimental. The interface is not final and
3764
+ * can change without notice.
3765
+ * </Callout>
3766
+ *
3767
+ * `useCopilotReadable` is a React hook that provides app-state and other information
3768
+ * to the Copilot. Optionally, the hook can also handle hierarchical state within your
3769
+ * application, passing these parent-child relationships to the Copilot.
3770
+ *
3771
+ * <br/>
3772
+ * <img src="https://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif" width="500" />
3773
+ *
3774
+ * ## Usage
3775
+ *
3776
+ * ### Install Dependencies
3777
+ *
3778
+ * This component is part of the [@copilotkit/react-ui](https://npmjs.com/package/@copilotkit/react-ui) package.
3779
+ *
3780
+ * ```shell npm2yarn \"@copilotkit/react-ui"\
3781
+ * npm install @copilotkit/react-core @copilotkit/react-ui
3782
+ * ```
3783
+ *
3784
+ * ### Simple Usage
3785
+ *
3786
+ * ```tsx
3787
+ * import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
3788
+ *
3789
+ * export function MyComponent() {
3790
+ * const [employees, setEmployees] = useState([]);
3791
+ *
3792
+ * useCopilotChatSuggestions({
3793
+ * instructions: `The following employees are on duty: ${JSON.stringify(employees)}`,
3794
+ * });
3795
+ * }
3796
+ * ```
3797
+ *
3798
+ * ### Dependency Management
3799
+ *
3800
+ * ```tsx
3801
+ * import { useCopilotChatSuggestions } from "@copilotkit/react-ui";
3802
+ *
3803
+ * export function MyComponent() {
3804
+ * useCopilotChatSuggestions(
3805
+ * {
3806
+ * instructions: "Suggest the most relevant next actions.",
3807
+ * },
3808
+ * [appState],
3809
+ * );
3810
+ * }
3811
+ * ```
3812
+ *
3813
+ * In the example above, the suggestions are generated based on the given instructions.
3814
+ * The hook monitors `appState`, and updates suggestions accordingly whenever it changes.
3815
+ *
3816
+ * ### Behavior and Lifecycle
3817
+ *
3818
+ * The hook registers the configuration with the chat context upon component mount and
3819
+ * removes it on unmount, ensuring a clean and efficient lifecycle management.
3820
+ */
3821
+ function useCopilotChatSuggestions(config, dependencies = []) {
3822
+ const resolvedAgentId = (0, _copilotkitnext_react.useCopilotChatConfiguration)()?.agentId ?? "default";
3823
+ const available = (config.available === "enabled" ? "always" : config.available) ?? "before-first-message";
3824
+ (0, _copilotkitnext_react.useConfigureSuggestions)({
3825
+ ...config,
3826
+ available,
3827
+ consumerAgentId: resolvedAgentId
3828
+ }, dependencies);
3829
+ }
3830
+
3831
+ //#endregion
3832
+ //#region src/types/frontend-action.ts
3833
+ function processActionsForRuntimeRequest(actions) {
3834
+ return actions.filter((action) => action.available !== _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction).map((action) => {
3835
+ let available = _copilotkit_runtime_client_gql.ActionInputAvailability.Enabled;
3836
+ if (action.disabled) available = _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled;
3837
+ else if (action.available === "disabled") available = _copilotkit_runtime_client_gql.ActionInputAvailability.Disabled;
3838
+ else if (action.available === "remote") available = _copilotkit_runtime_client_gql.ActionInputAvailability.Remote;
3839
+ return {
3840
+ name: action.name,
3841
+ description: action.description || "",
3842
+ jsonSchema: JSON.stringify((0, _copilotkit_shared.actionParametersToJsonSchema)(action.parameters || [])),
3843
+ available
3844
+ };
3845
+ });
3846
+ }
3847
+
3848
+ //#endregion
3849
+ //#region src/lib/copilot-task.ts
3850
+ /**
3851
+ * This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](/reference/v1/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](/reference/v1/hooks/useCopilotAction), or you can provide your own context and actions.
3852
+ *
3853
+ * ## Example
3854
+ * In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do.
3855
+ *
3856
+ * ```tsx
3857
+ * import { CopilotTask, useCopilotContext } from "@copilotkit/react-core";
3858
+ *
3859
+ * export function MyComponent() {
3860
+ * const context = useCopilotContext();
3861
+ *
3862
+ * const task = new CopilotTask({
3863
+ * instructions: "Set a random message",
3864
+ * actions: [
3865
+ * {
3866
+ * name: "setMessage",
3867
+ * description: "Set the message.",
3868
+ * argumentAnnotations: [
3869
+ * {
3870
+ * name: "message",
3871
+ * type: "string",
3872
+ * description:
3873
+ * "A message to display.",
3874
+ * required: true,
3875
+ * },
3876
+ * ],
3877
+ * }
3878
+ * ]
3879
+ * });
3880
+ *
3881
+ * const executeTask = async () => {
3882
+ * await task.run(context, action);
3883
+ * }
3884
+ *
3885
+ * return (
3886
+ * <>
3887
+ * <button onClick={executeTask}>
3888
+ * Execute task
3889
+ * </button>
3890
+ * </>
3891
+ * )
3892
+ * }
3893
+ * ```
3894
+ *
3895
+ * Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/src/v1.x/examples/next-openai/src/app/presentation/page.tsx) for a more complete example.
3896
+ */
3897
+ var CopilotTask = class {
3898
+ constructor(config) {
3899
+ this.instructions = config.instructions;
3900
+ this.actions = config.actions || [];
3901
+ this.includeCopilotReadable = config.includeCopilotReadable !== false;
3902
+ this.includeCopilotActions = config.includeCopilotActions !== false;
3903
+ this.forwardedParameters = config.forwardedParameters;
3904
+ }
3905
+ /**
3906
+ * Run the task.
3907
+ * @param context The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context.
3908
+ * @param data The data to use for the task.
3909
+ */
3910
+ async run(context, data) {
3911
+ const actions = this.includeCopilotActions ? Object.assign({}, context.actions) : {};
3912
+ for (const fn of this.actions) actions[fn.name] = fn;
3913
+ let contextString = "";
3914
+ if (data) contextString = (typeof data === "string" ? data : JSON.stringify(data)) + "\n\n";
3915
+ if (this.includeCopilotReadable) contextString += context.getContextString([], defaultCopilotContextCategories);
3916
+ const messages = [new _copilotkit_runtime_client_gql.TextMessage({
3917
+ content: taskSystemMessage(contextString, this.instructions),
3918
+ role: _copilotkit_runtime_client_gql.Role.System
3919
+ })];
3920
+ const response = await new _copilotkit_runtime_client_gql.CopilotRuntimeClient({
3921
+ url: context.copilotApiConfig.chatApiEndpoint,
3922
+ publicApiKey: context.copilotApiConfig.publicApiKey,
3923
+ headers: context.copilotApiConfig.headers,
3924
+ credentials: context.copilotApiConfig.credentials
3925
+ }).generateCopilotResponse({
3926
+ data: {
3927
+ frontend: {
3928
+ actions: processActionsForRuntimeRequest(Object.values(actions)),
3929
+ url: window.location.href
3930
+ },
3931
+ messages: (0, _copilotkit_runtime_client_gql.convertMessagesToGqlInput)((0, _copilotkit_runtime_client_gql.filterAgentStateMessages)(messages)),
3932
+ metadata: { requestType: _copilotkit_runtime_client_gql.CopilotRequestType.Task },
3933
+ forwardedParameters: {
3934
+ toolChoice: "required",
3935
+ ...this.forwardedParameters ?? {}
3936
+ }
3937
+ },
3938
+ properties: context.copilotApiConfig.properties
3939
+ }).toPromise();
3940
+ const functionCallHandler = context.getFunctionCallHandler(actions);
3941
+ const functionCalls = (0, _copilotkit_runtime_client_gql.convertGqlOutputToMessages)(response.data?.generateCopilotResponse?.messages || []).filter((m) => m.isActionExecutionMessage());
3942
+ for (const functionCall of functionCalls) await functionCallHandler({
3943
+ messages,
3944
+ name: functionCall.name,
3945
+ args: functionCall.arguments
3946
+ });
3947
+ }
3948
+ };
3949
+ function taskSystemMessage(contextString, instructions) {
3950
+ return `
3951
+ Please act as an efficient, competent, conscientious, and industrious professional assistant.
3952
+
3953
+ 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.
3954
+ Always be polite and respectful, and prefer brevity over verbosity.
3955
+
3956
+ The user has provided you with the following context:
3957
+ \`\`\`
3958
+ ${contextString}
3959
+ \`\`\`
3960
+
3961
+ They have also provided you with functions you can call to initiate actions on their behalf.
3962
+
3963
+ Please assist them as best you can.
3964
+
3965
+ This is not a conversation, so please do not ask questions. Just call a function without saying anything else.
3966
+
3967
+ The user has given you the following task to complete:
3968
+
3969
+ \`\`\`
3970
+ ${instructions}
3971
+ \`\`\`
3972
+ `;
3973
+ }
3974
+
3975
+ //#endregion
3976
+ exports.CoAgentStateRendersContext = CoAgentStateRendersContext;
3977
+ exports.CoAgentStateRendersProvider = CoAgentStateRendersProvider;
3978
+ exports.CopilotContext = CopilotContext;
3979
+ exports.CopilotKit = CopilotKit;
3980
+ exports.CopilotMessagesContext = CopilotMessagesContext;
3981
+ exports.CopilotTask = CopilotTask;
3982
+ exports.SUGGESTION_RETRY_CONFIG = SUGGESTION_RETRY_CONFIG;
3983
+ exports.ThreadsContext = ThreadsContext;
3984
+ exports.ThreadsProvider = ThreadsProvider;
3985
+ exports.defaultCopilotContextCategories = defaultCopilotContextCategories;
3986
+ exports.shouldShowDevConsole = shouldShowDevConsole;
3987
+ exports.useCoAgent = useCoAgent;
3988
+ exports.useCoAgentStateRender = useCoAgentStateRender;
3989
+ exports.useCoAgentStateRenders = useCoAgentStateRenders;
3990
+ exports.useCopilotAction = useCopilotAction;
3991
+ exports.useCopilotAdditionalInstructions = useCopilotAdditionalInstructions;
3992
+ exports.useCopilotAuthenticatedAction_c = useCopilotAuthenticatedAction_c;
3993
+ exports.useCopilotChat = useCopilotChat;
3994
+ exports.useCopilotChatHeadless_c = useCopilotChatHeadless_c;
3995
+ exports.useCopilotChatInternal = useCopilotChatInternal;
3996
+ exports.useCopilotChatSuggestions = useCopilotChatSuggestions;
3997
+ exports.useCopilotContext = useCopilotContext;
3998
+ exports.useCopilotMessagesContext = useCopilotMessagesContext;
3999
+ exports.useCopilotReadable = useCopilotReadable;
4000
+ exports.useCopilotRuntimeClient = useCopilotRuntimeClient;
4001
+ exports.useDefaultTool = useDefaultTool;
4002
+ exports.useFrontendTool = useFrontendTool;
4003
+ exports.useHumanInTheLoop = useHumanInTheLoop;
4004
+ exports.useLangGraphInterrupt = useLangGraphInterrupt;
4005
+ exports.useLangGraphInterruptRender = useLangGraphInterruptRender;
4006
+ exports.useLazyToolRenderer = useLazyToolRenderer;
4007
+ exports.useMakeCopilotDocumentReadable = useMakeCopilotDocumentReadable;
4008
+ exports.useRenderToolCall = useRenderToolCall;
4009
+ exports.useThreads = useThreads;
4010
+ //# sourceMappingURL=index.cjs.map