@copilotkit/react-core 1.51.4-next.7 → 1.51.4

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 (301) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +18 -12
  3. package/dist/{chunk-6ESSSQ7Q.mjs → chunk-2RSAYTXH.mjs} +6 -3
  4. package/dist/chunk-2RSAYTXH.mjs.map +1 -0
  5. package/dist/chunk-3LZZ4RVM.mjs +37 -0
  6. package/dist/{chunk-ABWT4DRT.mjs.map → chunk-3LZZ4RVM.mjs.map} +1 -1
  7. package/dist/{chunk-QDES5PDW.mjs → chunk-4ZQYMC5F.mjs} +2 -2
  8. package/dist/{chunk-QDES5PDW.mjs.map → chunk-4ZQYMC5F.mjs.map} +1 -1
  9. package/dist/{chunk-VKNLTZJE.mjs → chunk-6ABVYB2U.mjs} +28 -19
  10. package/dist/chunk-6ABVYB2U.mjs.map +1 -0
  11. package/dist/{chunk-6PUNP7CD.mjs → chunk-6AWG5FWL.mjs} +2 -2
  12. package/dist/chunk-6AWG5FWL.mjs.map +1 -0
  13. package/dist/{chunk-C3YJYDK4.mjs → chunk-7GIBHX6X.mjs} +8 -2
  14. package/dist/chunk-7GIBHX6X.mjs.map +1 -0
  15. package/dist/{chunk-PIF5KJYI.mjs → chunk-7PJKPWMD.mjs} +15 -6
  16. package/dist/chunk-7PJKPWMD.mjs.map +1 -0
  17. package/dist/{chunk-7JTI6ZL4.mjs → chunk-7U3DNFBF.mjs} +6 -3
  18. package/dist/chunk-7U3DNFBF.mjs.map +1 -0
  19. package/dist/{chunk-KNJHRVKW.mjs → chunk-AAGMWZCN.mjs} +45 -14
  20. package/dist/chunk-AAGMWZCN.mjs.map +1 -0
  21. package/dist/{chunk-AFNWX62Q.mjs → chunk-C7HSVDHD.mjs} +10 -4
  22. package/dist/chunk-C7HSVDHD.mjs.map +1 -0
  23. package/dist/{chunk-ZYTXB6HH.mjs → chunk-CZT7JUIM.mjs} +4 -2
  24. package/dist/chunk-CZT7JUIM.mjs.map +1 -0
  25. package/dist/{chunk-BKMJ4LC7.mjs → chunk-G7SUZGGB.mjs} +19 -12
  26. package/dist/chunk-G7SUZGGB.mjs.map +1 -0
  27. package/dist/{chunk-7IBF6RBW.mjs → chunk-GY3FQICF.mjs} +2 -2
  28. package/dist/{chunk-QD7EID4N.mjs → chunk-IHMMKEFG.mjs} +16 -11
  29. package/dist/chunk-IHMMKEFG.mjs.map +1 -0
  30. package/dist/{chunk-YYN33GSG.mjs → chunk-K5OXUXCG.mjs} +14 -11
  31. package/dist/chunk-K5OXUXCG.mjs.map +1 -0
  32. package/dist/{chunk-6ZLPNY7X.mjs → chunk-L7GPCF2V.mjs} +6 -2
  33. package/dist/{chunk-6ZLPNY7X.mjs.map → chunk-L7GPCF2V.mjs.map} +1 -1
  34. package/dist/{chunk-LHERIF3L.mjs → chunk-LD34IXVT.mjs} +8 -5
  35. package/dist/chunk-LD34IXVT.mjs.map +1 -0
  36. package/dist/{chunk-7DTB7S5V.mjs → chunk-LNGBARXE.mjs} +5 -2
  37. package/dist/chunk-LNGBARXE.mjs.map +1 -0
  38. package/dist/{chunk-DQXCQWSG.mjs → chunk-LRPWSPXG.mjs} +85 -50
  39. package/dist/chunk-LRPWSPXG.mjs.map +1 -0
  40. package/dist/{chunk-NBK4KBLX.mjs → chunk-MBJ7OLYI.mjs} +9 -5
  41. package/dist/chunk-MBJ7OLYI.mjs.map +1 -0
  42. package/dist/{chunk-MA3CUMCY.mjs → chunk-P6ZPE4XJ.mjs} +3 -3
  43. package/dist/{chunk-MA3CUMCY.mjs.map → chunk-P6ZPE4XJ.mjs.map} +1 -1
  44. package/dist/{chunk-77IVITG3.mjs → chunk-QXZTCGF4.mjs} +9 -4
  45. package/dist/chunk-QXZTCGF4.mjs.map +1 -0
  46. package/dist/{chunk-VP43SLSZ.mjs → chunk-R2DP4APC.mjs} +10 -5
  47. package/dist/chunk-R2DP4APC.mjs.map +1 -0
  48. package/dist/{chunk-RKTVJRK7.mjs → chunk-R7BV32X4.mjs} +5 -2
  49. package/dist/chunk-R7BV32X4.mjs.map +1 -0
  50. package/dist/{chunk-YCG6SNAU.mjs → chunk-SBRCWA4S.mjs} +186 -32
  51. package/dist/chunk-SBRCWA4S.mjs.map +1 -0
  52. package/dist/{chunk-LMHB2D4J.mjs → chunk-SK2XMJUD.mjs} +13 -4
  53. package/dist/chunk-SK2XMJUD.mjs.map +1 -0
  54. package/dist/{chunk-HE22TZMF.mjs → chunk-SLM6CLAH.mjs} +16 -7
  55. package/dist/chunk-SLM6CLAH.mjs.map +1 -0
  56. package/dist/{chunk-XDFVCQD3.mjs → chunk-SYGQHN3H.mjs} +1 -1
  57. package/dist/{chunk-XDFVCQD3.mjs.map → chunk-SYGQHN3H.mjs.map} +1 -1
  58. package/dist/{chunk-4RRMC7L2.mjs → chunk-SYMT73HM.mjs} +16 -5
  59. package/dist/chunk-SYMT73HM.mjs.map +1 -0
  60. package/dist/{chunk-SRJT5VVY.mjs → chunk-TFZXOEY4.mjs} +6 -4
  61. package/dist/{chunk-SRJT5VVY.mjs.map → chunk-TFZXOEY4.mjs.map} +1 -1
  62. package/dist/{chunk-4CEQJ2X6.mjs → chunk-TPN7WC53.mjs} +4 -2
  63. package/dist/{chunk-4CEQJ2X6.mjs.map → chunk-TPN7WC53.mjs.map} +1 -1
  64. package/dist/{chunk-VGL3DGUW.mjs → chunk-UA23VX5J.mjs} +4 -2
  65. package/dist/chunk-UA23VX5J.mjs.map +1 -0
  66. package/dist/{chunk-VV56AVPB.mjs → chunk-V42VL2JR.mjs} +15 -4
  67. package/dist/chunk-V42VL2JR.mjs.map +1 -0
  68. package/dist/{chunk-RBGVEVWY.mjs → chunk-VZ4NSOFQ.mjs} +4 -4
  69. package/dist/chunk-VZ4NSOFQ.mjs.map +1 -0
  70. package/dist/{chunk-WF65O6HX.mjs → chunk-WRALJIW5.mjs} +18 -5
  71. package/dist/chunk-WRALJIW5.mjs.map +1 -0
  72. package/dist/{chunk-PMAFHQ7P.mjs → chunk-WV2EA7SX.mjs} +1 -1
  73. package/dist/chunk-WV2EA7SX.mjs.map +1 -0
  74. package/dist/{chunk-EFL5OBKN.mjs → chunk-ZP2IMXFY.mjs} +10 -4
  75. package/dist/chunk-ZP2IMXFY.mjs.map +1 -0
  76. package/dist/components/CopilotListeners.js +11 -2
  77. package/dist/components/CopilotListeners.js.map +1 -1
  78. package/dist/components/CopilotListeners.mjs +2 -2
  79. package/dist/components/copilot-provider/copilot-messages.d.ts +1 -1
  80. package/dist/components/copilot-provider/copilot-messages.js +22 -7
  81. package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
  82. package/dist/components/copilot-provider/copilot-messages.mjs +3 -3
  83. package/dist/components/copilot-provider/copilotkit-props.js.map +1 -1
  84. package/dist/components/copilot-provider/copilotkit.js +179 -84
  85. package/dist/components/copilot-provider/copilotkit.js.map +1 -1
  86. package/dist/components/copilot-provider/copilotkit.mjs +16 -16
  87. package/dist/components/copilot-provider/index.js +179 -84
  88. package/dist/components/copilot-provider/index.js.map +1 -1
  89. package/dist/components/copilot-provider/index.mjs +16 -16
  90. package/dist/components/dev-console/console-trigger.d.ts +1 -1
  91. package/dist/components/dev-console/console-trigger.js +227 -42
  92. package/dist/components/dev-console/console-trigger.js.map +1 -1
  93. package/dist/components/dev-console/console-trigger.mjs +24 -8
  94. package/dist/components/dev-console/console-trigger.mjs.map +1 -1
  95. package/dist/components/dev-console/developer-console-modal.d.ts +1 -1
  96. package/dist/components/dev-console/developer-console-modal.js +206 -37
  97. package/dist/components/dev-console/developer-console-modal.js.map +1 -1
  98. package/dist/components/dev-console/developer-console-modal.mjs +3 -3
  99. package/dist/components/dev-console/icons.js +14 -5
  100. package/dist/components/dev-console/icons.js.map +1 -1
  101. package/dist/components/dev-console/icons.mjs +1 -1
  102. package/dist/components/error-boundary/error-boundary.d.ts +1 -1
  103. package/dist/components/error-boundary/error-boundary.js +9 -2
  104. package/dist/components/error-boundary/error-boundary.js.map +1 -1
  105. package/dist/components/error-boundary/error-boundary.mjs +5 -5
  106. package/dist/components/error-boundary/error-utils.js.map +1 -1
  107. package/dist/components/error-boundary/error-utils.mjs +2 -2
  108. package/dist/components/index.js +179 -84
  109. package/dist/components/index.js.map +1 -1
  110. package/dist/components/index.mjs +16 -16
  111. package/dist/components/toast/toast-provider.js +9 -3
  112. package/dist/components/toast/toast-provider.js.map +1 -1
  113. package/dist/components/toast/toast-provider.mjs +1 -1
  114. package/dist/components/usage-banner.js +5 -1
  115. package/dist/components/usage-banner.js.map +1 -1
  116. package/dist/components/usage-banner.mjs +1 -1
  117. package/dist/context/coagent-state-renders-context.d.ts +1 -1
  118. package/dist/context/coagent-state-renders-context.js +15 -10
  119. package/dist/context/coagent-state-renders-context.js.map +1 -1
  120. package/dist/context/coagent-state-renders-context.mjs +1 -1
  121. package/dist/context/copilot-context.js +9 -3
  122. package/dist/context/copilot-context.js.map +1 -1
  123. package/dist/context/copilot-context.mjs +1 -1
  124. package/dist/context/index.js +31 -15
  125. package/dist/context/index.js.map +1 -1
  126. package/dist/context/index.mjs +3 -3
  127. package/dist/context/threads-context.d.ts +1 -1
  128. package/dist/context/threads-context.js +7 -2
  129. package/dist/context/threads-context.js.map +1 -1
  130. package/dist/context/threads-context.mjs +1 -1
  131. package/dist/hooks/index.js +162 -61
  132. package/dist/hooks/index.js.map +1 -1
  133. package/dist/hooks/index.mjs +25 -25
  134. package/dist/hooks/use-coagent-state-render-bridge.helpers.js +7 -1
  135. package/dist/hooks/use-coagent-state-render-bridge.helpers.js.map +1 -1
  136. package/dist/hooks/use-coagent-state-render-bridge.helpers.mjs +1 -1
  137. package/dist/hooks/use-coagent-state-render-bridge.js +31 -15
  138. package/dist/hooks/use-coagent-state-render-bridge.js.map +1 -1
  139. package/dist/hooks/use-coagent-state-render-bridge.mjs +6 -6
  140. package/dist/hooks/use-coagent-state-render-registry.js +14 -3
  141. package/dist/hooks/use-coagent-state-render-registry.js.map +1 -1
  142. package/dist/hooks/use-coagent-state-render-registry.mjs +2 -2
  143. package/dist/hooks/use-coagent-state-render.js +34 -21
  144. package/dist/hooks/use-coagent-state-render.js.map +1 -1
  145. package/dist/hooks/use-coagent-state-render.mjs +4 -4
  146. package/dist/hooks/use-coagent.js +3 -1
  147. package/dist/hooks/use-coagent.js.map +1 -1
  148. package/dist/hooks/use-coagent.mjs +1 -1
  149. package/dist/hooks/use-configure-chat-suggestions.js.map +1 -1
  150. package/dist/hooks/use-configure-chat-suggestions.mjs.map +1 -1
  151. package/dist/hooks/use-copilot-action.js +13 -9
  152. package/dist/hooks/use-copilot-action.js.map +1 -1
  153. package/dist/hooks/use-copilot-action.mjs +4 -4
  154. package/dist/hooks/use-copilot-additional-instructions.d.ts +1 -1
  155. package/dist/hooks/use-copilot-additional-instructions.js +26 -7
  156. package/dist/hooks/use-copilot-additional-instructions.js.map +1 -1
  157. package/dist/hooks/use-copilot-additional-instructions.mjs +2 -2
  158. package/dist/hooks/use-copilot-authenticated-action.js +25 -13
  159. package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
  160. package/dist/hooks/use-copilot-authenticated-action.mjs +6 -6
  161. package/dist/hooks/use-copilot-chat-headless_c.js +81 -27
  162. package/dist/hooks/use-copilot-chat-headless_c.js.map +1 -1
  163. package/dist/hooks/use-copilot-chat-headless_c.mjs +11 -11
  164. package/dist/hooks/use-copilot-chat-suggestions.js.map +1 -1
  165. package/dist/hooks/use-copilot-chat-suggestions.mjs +1 -1
  166. package/dist/hooks/use-copilot-chat.js +81 -27
  167. package/dist/hooks/use-copilot-chat.js.map +1 -1
  168. package/dist/hooks/use-copilot-chat.mjs +11 -11
  169. package/dist/hooks/use-copilot-chat_internal.js +81 -27
  170. package/dist/hooks/use-copilot-chat_internal.js.map +1 -1
  171. package/dist/hooks/use-copilot-chat_internal.mjs +10 -10
  172. package/dist/hooks/use-copilot-runtime-client.js +4 -1
  173. package/dist/hooks/use-copilot-runtime-client.js.map +1 -1
  174. package/dist/hooks/use-copilot-runtime-client.mjs +2 -2
  175. package/dist/hooks/use-default-tool.js +17 -10
  176. package/dist/hooks/use-default-tool.js.map +1 -1
  177. package/dist/hooks/use-default-tool.mjs +5 -5
  178. package/dist/hooks/use-flat-category-store.js +13 -10
  179. package/dist/hooks/use-flat-category-store.js.map +1 -1
  180. package/dist/hooks/use-flat-category-store.mjs +1 -1
  181. package/dist/hooks/use-frontend-tool.js.map +1 -1
  182. package/dist/hooks/use-frontend-tool.mjs +1 -1
  183. package/dist/hooks/use-human-in-the-loop.js.map +1 -1
  184. package/dist/hooks/use-human-in-the-loop.mjs +1 -1
  185. package/dist/hooks/use-langgraph-interrupt-render.js +22 -5
  186. package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
  187. package/dist/hooks/use-langgraph-interrupt-render.mjs +4 -4
  188. package/dist/hooks/use-langgraph-interrupt.js +19 -4
  189. package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
  190. package/dist/hooks/use-langgraph-interrupt.mjs +3 -3
  191. package/dist/hooks/use-make-copilot-document-readable.js +9 -3
  192. package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
  193. package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
  194. package/dist/hooks/use-render-tool-call.d.ts +1 -1
  195. package/dist/hooks/use-render-tool-call.js +13 -9
  196. package/dist/hooks/use-render-tool-call.js.map +1 -1
  197. package/dist/hooks/use-render-tool-call.mjs +1 -1
  198. package/dist/hooks/use-tree.js +4 -1
  199. package/dist/hooks/use-tree.js.map +1 -1
  200. package/dist/hooks/use-tree.mjs +1 -1
  201. package/dist/index.js +311 -130
  202. package/dist/index.js.map +1 -1
  203. package/dist/index.mjs +35 -35
  204. package/dist/index.umd.js +1 -1
  205. package/dist/index.umd.js.map +1 -1
  206. package/dist/lib/copilot-task.js +10 -3
  207. package/dist/lib/copilot-task.js.map +1 -1
  208. package/dist/lib/copilot-task.mjs +18 -18
  209. package/dist/lib/index.js +10 -3
  210. package/dist/lib/index.js.map +1 -1
  211. package/dist/lib/index.mjs +18 -18
  212. package/dist/lib/status-checker.js.map +1 -1
  213. package/dist/lib/status-checker.mjs +1 -1
  214. package/dist/types/coagent-action.js.map +1 -1
  215. package/dist/types/frontend-action.js +3 -1
  216. package/dist/types/frontend-action.js.map +1 -1
  217. package/dist/types/frontend-action.mjs +1 -1
  218. package/dist/types/interrupt-action.js.map +1 -1
  219. package/dist/v2/index.umd.js.map +1 -1
  220. package/jest.config.js +1 -0
  221. package/package.json +7 -8
  222. package/src/__mocks__/analytics-node.js +9 -0
  223. package/src/components/CopilotListeners.tsx +21 -5
  224. package/src/components/copilot-provider/__tests__/copilotkit-error.test.tsx +3 -1
  225. package/src/components/copilot-provider/copilot-messages.tsx +36 -11
  226. package/src/components/copilot-provider/copilotkit-props.tsx +4 -1
  227. package/src/components/copilot-provider/copilotkit.tsx +116 -50
  228. package/src/components/dev-console/console-trigger.tsx +39 -10
  229. package/src/components/dev-console/developer-console-modal.tsx +207 -57
  230. package/src/components/dev-console/icons.tsx +6 -1
  231. package/src/components/error-boundary/error-boundary.tsx +10 -2
  232. package/src/components/error-boundary/error-utils.tsx +8 -3
  233. package/src/components/toast/toast-provider.tsx +16 -6
  234. package/src/components/usage-banner.tsx +9 -2
  235. package/src/context/coagent-state-renders-context.tsx +24 -12
  236. package/src/context/copilot-context.tsx +48 -15
  237. package/src/context/index.ts +8 -2
  238. package/src/context/threads-context.tsx +14 -3
  239. package/src/hooks/__tests__/use-coagent-state-render-bridge.helpers.test.ts +11 -4
  240. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +175 -47
  241. package/src/hooks/__tests__/use-coagent-state-render.test.tsx +31 -10
  242. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +10 -2
  243. package/src/hooks/use-coagent-state-render-bridge.helpers.ts +49 -16
  244. package/src/hooks/use-coagent-state-render-bridge.tsx +30 -13
  245. package/src/hooks/use-coagent-state-render-registry.ts +36 -21
  246. package/src/hooks/use-coagent-state-render.ts +30 -19
  247. package/src/hooks/use-coagent.ts +15 -4
  248. package/src/hooks/use-configure-chat-suggestions.tsx +14 -4
  249. package/src/hooks/use-copilot-action.ts +12 -3
  250. package/src/hooks/use-copilot-additional-instructions.ts +17 -4
  251. package/src/hooks/use-copilot-authenticated-action.ts +4 -1
  252. package/src/hooks/use-copilot-chat-headless_c.ts +8 -2
  253. package/src/hooks/use-copilot-chat-suggestions.tsx +14 -4
  254. package/src/hooks/use-copilot-chat.ts +3 -1
  255. package/src/hooks/use-copilot-chat_internal.ts +72 -19
  256. package/src/hooks/use-copilot-runtime-client.ts +20 -6
  257. package/src/hooks/use-default-tool.ts +8 -2
  258. package/src/hooks/use-flat-category-store.ts +15 -11
  259. package/src/hooks/use-frontend-tool.ts +35 -25
  260. package/src/hooks/use-human-in-the-loop.ts +21 -5
  261. package/src/hooks/use-langgraph-interrupt-render.ts +13 -2
  262. package/src/hooks/use-langgraph-interrupt.ts +13 -3
  263. package/src/hooks/use-render-tool-call.ts +20 -11
  264. package/src/hooks/use-tree.ts +20 -5
  265. package/src/lib/copilot-task.ts +20 -6
  266. package/src/lib/status-checker.ts +4 -1
  267. package/src/types/coagent-action.ts +6 -2
  268. package/src/types/frontend-action.ts +16 -5
  269. package/src/types/interrupt-action.ts +15 -5
  270. package/tsconfig.json +1 -1
  271. package/dist/chunk-4RRMC7L2.mjs.map +0 -1
  272. package/dist/chunk-6ESSSQ7Q.mjs.map +0 -1
  273. package/dist/chunk-6PUNP7CD.mjs.map +0 -1
  274. package/dist/chunk-77IVITG3.mjs.map +0 -1
  275. package/dist/chunk-7DTB7S5V.mjs.map +0 -1
  276. package/dist/chunk-7JTI6ZL4.mjs.map +0 -1
  277. package/dist/chunk-ABWT4DRT.mjs +0 -24
  278. package/dist/chunk-AFNWX62Q.mjs.map +0 -1
  279. package/dist/chunk-BKMJ4LC7.mjs.map +0 -1
  280. package/dist/chunk-C3YJYDK4.mjs.map +0 -1
  281. package/dist/chunk-DQXCQWSG.mjs.map +0 -1
  282. package/dist/chunk-EFL5OBKN.mjs.map +0 -1
  283. package/dist/chunk-HE22TZMF.mjs.map +0 -1
  284. package/dist/chunk-KNJHRVKW.mjs.map +0 -1
  285. package/dist/chunk-LHERIF3L.mjs.map +0 -1
  286. package/dist/chunk-LMHB2D4J.mjs.map +0 -1
  287. package/dist/chunk-NBK4KBLX.mjs.map +0 -1
  288. package/dist/chunk-PIF5KJYI.mjs.map +0 -1
  289. package/dist/chunk-PMAFHQ7P.mjs.map +0 -1
  290. package/dist/chunk-QD7EID4N.mjs.map +0 -1
  291. package/dist/chunk-RBGVEVWY.mjs.map +0 -1
  292. package/dist/chunk-RKTVJRK7.mjs.map +0 -1
  293. package/dist/chunk-VGL3DGUW.mjs.map +0 -1
  294. package/dist/chunk-VKNLTZJE.mjs.map +0 -1
  295. package/dist/chunk-VP43SLSZ.mjs.map +0 -1
  296. package/dist/chunk-VV56AVPB.mjs.map +0 -1
  297. package/dist/chunk-WF65O6HX.mjs.map +0 -1
  298. package/dist/chunk-YCG6SNAU.mjs.map +0 -1
  299. package/dist/chunk-YYN33GSG.mjs.map +0 -1
  300. package/dist/chunk-ZYTXB6HH.mjs.map +0 -1
  301. /package/dist/{chunk-7IBF6RBW.mjs.map → chunk-GY3FQICF.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-coagent-state-render-registry.ts","../../src/hooks/use-coagent-state-render-bridge.helpers.ts"],"sourcesContent":["import { useEffect } from \"react\";\nimport {\n areStatesEquals,\n ClaimAction,\n getEffectiveRunId,\n isPlaceholderMessageId,\n isPlaceholderMessageName,\n readCachedMessageEntry,\n resolveClaim,\n selectSnapshot,\n type Claim,\n type ClaimsByMessageId,\n type SnapshotCaches,\n type StateRenderContext,\n} from \"./use-coagent-state-render-bridge.helpers\";\n\nexport interface StateRenderRegistryInput {\n agentId: string;\n stateRenderId?: string;\n message: { id: string; runId?: string; name?: string };\n messageIndex?: number;\n stateSnapshot?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n claimsRef: React.MutableRefObject<Record<string, Claim>>;\n}\n\nexport interface StateRenderRegistryResult {\n canRender: boolean;\n}\n\nconst LAST_SNAPSHOTS_BY_RENDER_AND_RUN = \"__lastSnapshotsByStateRenderIdAndRun\";\nconst LAST_SNAPSHOTS_BY_MESSAGE = \"__lastSnapshotsByMessageId\";\n\ntype SnapshotByMessageEntry = { snapshot: any; runId?: string } | any;\ntype ClaimsStore = Record<string, Claim> & {\n [LAST_SNAPSHOTS_BY_RENDER_AND_RUN]?: Record<string, any>;\n [LAST_SNAPSHOTS_BY_MESSAGE]?: Record<string, SnapshotByMessageEntry>;\n};\n\nfunction getClaimsStore(\n claimsRef: React.MutableRefObject<Record<string, Claim>>,\n): ClaimsStore {\n return claimsRef.current as ClaimsStore;\n}\n\nfunction getSnapshotCaches(claimsRef: React.MutableRefObject<Record<string, Claim>>): SnapshotCaches {\n const store = getClaimsStore(claimsRef);\n return {\n byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},\n byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {},\n };\n}\n\nexport function useStateRenderRegistry({\n agentId,\n stateRenderId,\n message,\n messageIndex,\n stateSnapshot,\n agentState,\n agentMessages,\n claimsRef,\n}: StateRenderRegistryInput): StateRenderRegistryResult {\n const store = getClaimsStore(claimsRef);\n const runId = message.runId;\n const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];\n const { runId: cachedMessageRunId } = readCachedMessageEntry(cachedMessageEntry);\n const existingClaimRunId = claimsRef.current[message.id]?.runId;\n const effectiveRunId = getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n });\n\n useEffect(() => {\n return () => {\n const existingClaim = claimsRef.current[message.id];\n if (\n existingClaim?.stateSnapshot &&\n Object.keys(existingClaim.stateSnapshot).length > 0\n ) {\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? \"pending\"}`;\n snapshotCache[cacheKey] = existingClaim.stateSnapshot;\n snapshotCache[`${existingClaim.stateRenderId}::latest`] = existingClaim.stateSnapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = {\n snapshot: existingClaim.stateSnapshot,\n runId: existingClaim.runId ?? effectiveRunId,\n };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n delete claimsRef.current[message.id];\n };\n }, [claimsRef, effectiveRunId, message.id]);\n\n if (!stateRenderId) {\n return { canRender: false };\n }\n\n const caches = getSnapshotCaches(claimsRef);\n const existingClaim = claimsRef.current[message.id] as Claim | undefined;\n\n const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } = selectSnapshot({\n messageId: message.id,\n messageName: message.name,\n allowLiveState:\n isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),\n skipLatestCache:\n isPlaceholderMessageName(message.name) || isPlaceholderMessageId(message.id),\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp: stateSnapshot,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n });\n\n const resolution = resolveClaim({\n claims: claimsRef.current as ClaimsByMessageId,\n context: {\n agentId,\n messageId: message.id,\n stateRenderId,\n runId: effectiveRunId,\n messageIndex,\n } satisfies StateRenderContext,\n stateSnapshot: snapshotForClaim,\n });\n\n if (resolution.action === ClaimAction.Block) {\n return { canRender: false };\n }\n\n if (resolution.updateRunId && claimsRef.current[message.id]) {\n claimsRef.current[message.id].runId = resolution.updateRunId;\n }\n\n if (resolution.nextClaim) {\n claimsRef.current[message.id] = resolution.nextClaim;\n }\n\n if (resolution.lockOthers) {\n Object.entries(claimsRef.current).forEach(([id, claim]) => {\n if (id !== message.id && claim.stateRenderId === stateRenderId) {\n claim.locked = true;\n }\n });\n }\n\n if (existingClaim && !existingClaim.locked && agentMessages?.length) {\n const indexInAgentMessages = agentMessages.findIndex((msg: any) => msg.id === message.id);\n if (indexInAgentMessages >= 0 && indexInAgentMessages < agentMessages.length - 1) {\n existingClaim.locked = true;\n }\n }\n\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n const snapshotChanged =\n stateSnapshot &&\n existingSnapshot !== undefined &&\n !areStatesEquals(existingSnapshot, snapshot);\n\n if (\n snapshot &&\n (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) &&\n (!claimsRef.current[message.id].locked || snapshotChanged)\n ) {\n if (!claimsRef.current[message.id].locked || snapshotChanged) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshot;\n snapshotCache[`${stateRenderId}::latest`] = snapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = { snapshot, runId: effectiveRunId };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n if (stateSnapshot) {\n claimsRef.current[message.id].locked = true;\n }\n }\n } else if (snapshotForClaim) {\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n if (!existingSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshotForClaim;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshotForClaim;\n snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = { snapshot: snapshotForClaim, runId: effectiveRunId };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n }\n\n return { canRender: true };\n}\n","import { dataToUUID, parseJson } from \"@copilotkit/shared\";\n\nexport enum RenderStatus {\n InProgress = \"inProgress\",\n Complete = \"complete\",\n}\n\nexport enum ClaimAction {\n Create = \"create\",\n Override = \"override\",\n Existing = \"existing\",\n Block = \"block\",\n}\n\nexport interface StateRenderContext {\n agentId: string;\n stateRenderId: string;\n messageId: string;\n runId: string;\n messageIndex?: number;\n}\n\nexport interface Claim {\n stateRenderId: string;\n runId?: string;\n stateSnapshot?: any;\n locked?: boolean;\n messageIndex?: number;\n}\n\nexport type ClaimsByMessageId = Record<string, Claim>;\n\nexport interface ClaimResolution {\n canRender: boolean;\n action: ClaimAction;\n nextClaim?: Claim;\n lockOthers?: boolean;\n updateRunId?: string;\n}\n\nexport interface SnapshotCaches {\n byStateRenderAndRun: Record<string, any>;\n byMessageId: Record<string, any>;\n}\n\nexport interface SnapshotSelectionInput {\n messageId: string;\n messageName?: string;\n allowLiveState?: boolean;\n skipLatestCache?: boolean;\n stateRenderId?: string;\n effectiveRunId: string;\n stateSnapshotProp?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n existingClaim?: Claim;\n caches: SnapshotCaches;\n}\n\nexport interface SnapshotSelectionResult {\n snapshot?: any;\n hasSnapshotKeys: boolean;\n cachedSnapshot?: any;\n allowEmptySnapshot?: boolean;\n snapshotForClaim?: any;\n}\n\nfunction getStateWithoutConstantKeys(state: any) {\n if (!state) return {};\n const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;\n return stateWithoutConstantKeys;\n}\n\n// Function that compares states, without the constant keys\nexport function areStatesEquals(a: any, b: any) {\n if ((a && !b) || (!a && b)) return false;\n const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;\n const {\n messages: bMessages,\n tools: bTools,\n copilotkit: bCopilotkit,\n ...bWithoutConstantKeys\n } = b;\n\n return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);\n}\n\nexport function isPlaceholderMessageId(messageId: string | undefined) {\n return !!messageId && messageId.startsWith(\"coagent-state-render-\");\n}\n\nexport function isPlaceholderMessageName(messageName: string | undefined) {\n return messageName === \"coagent-state-render\";\n}\n\nexport function readCachedMessageEntry(entry: any): { snapshot?: any; runId?: string } {\n if (!entry || typeof entry !== \"object\") {\n return { snapshot: entry, runId: undefined };\n }\n const snapshot = \"snapshot\" in entry ? entry.snapshot : entry;\n const runId = \"runId\" in entry ? entry.runId : undefined;\n return { snapshot, runId };\n}\n\nexport function getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n}: {\n existingClaimRunId?: string;\n cachedMessageRunId?: string;\n runId?: string;\n}) {\n return existingClaimRunId || cachedMessageRunId || runId || \"pending\";\n}\n\n/**\n * Resolve whether a message can claim a render slot.\n * This is a pure decision function; the caller applies claim mutations.\n */\nexport function resolveClaim({\n claims,\n context,\n stateSnapshot,\n}: {\n claims: ClaimsByMessageId;\n context: StateRenderContext;\n stateSnapshot?: any;\n}): ClaimResolution {\n const { messageId, stateRenderId, runId, messageIndex } = context;\n const existing = claims[messageId];\n\n if (existing) {\n const canRender = existing.stateRenderId === stateRenderId;\n const shouldUpdateRunId =\n canRender && runId && (!existing.runId || existing.runId === \"pending\");\n return {\n canRender,\n action: canRender ? ClaimAction.Existing : ClaimAction.Block,\n updateRunId: shouldUpdateRunId ? runId : undefined,\n };\n }\n\n const normalizedRunId = runId ?? \"pending\";\n const renderClaimedByOtherMessageEntry = Object.entries(claims).find(\n ([, claim]) =>\n claim.stateRenderId === stateRenderId &&\n (claim.runId ?? \"pending\") === normalizedRunId &&\n dataToUUID(getStateWithoutConstantKeys(claim.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(stateSnapshot)),\n );\n\n const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];\n const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];\n\n if (renderClaimedByOtherMessage) {\n if (\n messageIndex !== undefined &&\n renderClaimedByOtherMessage.messageIndex !== undefined &&\n messageIndex > renderClaimedByOtherMessage.messageIndex\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers:\n runId === renderClaimedByOtherMessage.runId || isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (runId && renderClaimedByOtherMessage.runId && runId !== renderClaimedByOtherMessage.runId) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (isPlaceholderMessageId(claimedMessageId)) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: true,\n };\n }\n\n if (\n stateSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId },\n };\n }\n\n return { canRender: false, action: ClaimAction.Block };\n }\n\n if (!runId) {\n return { canRender: false, action: ClaimAction.Block };\n }\n\n return {\n canRender: true,\n action: ClaimAction.Create,\n nextClaim: { stateRenderId, runId, messageIndex },\n };\n}\n\n/**\n * Select the best snapshot to render for this message.\n * Priority order is:\n * 1) explicit message snapshot\n * 2) live agent state (latest assistant only)\n * 3) cached snapshot for message\n * 4) cached snapshot for stateRenderId+runId\n * 5) last cached snapshot for stateRenderId\n */\nexport function selectSnapshot({\n messageId,\n messageName,\n allowLiveState,\n skipLatestCache,\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n}: SnapshotSelectionInput): SnapshotSelectionResult {\n const lastAssistantId = agentMessages\n ? [...agentMessages].reverse().find((msg) => msg.role === \"assistant\")?.id\n : undefined;\n const latestSnapshot =\n stateRenderId !== undefined ? caches.byStateRenderAndRun[`${stateRenderId}::latest`] : undefined;\n const messageIndex = agentMessages\n ? agentMessages.findIndex((msg) => msg.id === messageId)\n : -1;\n const messageRole =\n messageIndex >= 0 && agentMessages ? agentMessages[messageIndex]?.role : undefined;\n let previousUserMessageId: string | undefined;\n if (messageIndex > 0 && agentMessages) {\n for (let i = messageIndex - 1; i >= 0; i -= 1) {\n if (agentMessages[i]?.role === \"user\") {\n previousUserMessageId = agentMessages[i]?.id;\n break;\n }\n }\n }\n const liveStateIsStale =\n stateSnapshotProp === undefined &&\n latestSnapshot !== undefined &&\n agentState !== undefined &&\n areStatesEquals(latestSnapshot, agentState);\n const shouldUseLiveState =\n (Boolean(allowLiveState) || !lastAssistantId || messageId === lastAssistantId) &&\n !liveStateIsStale;\n const snapshot = stateSnapshotProp\n ? parseJson(stateSnapshotProp, stateSnapshotProp)\n : shouldUseLiveState\n ? agentState\n : undefined;\n const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);\n const allowEmptySnapshot =\n snapshot !== undefined &&\n !hasSnapshotKeys &&\n (stateSnapshotProp !== undefined || shouldUseLiveState);\n\n const messageCacheEntry = caches.byMessageId[messageId];\n const cachedMessageSnapshot = readCachedMessageEntry(messageCacheEntry).snapshot;\n const cacheKey =\n stateRenderId !== undefined ? `${stateRenderId}::${effectiveRunId}` : undefined;\n let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];\n if (cachedSnapshot === undefined && cacheKey && caches.byStateRenderAndRun[cacheKey] !== undefined) {\n cachedSnapshot = caches.byStateRenderAndRun[cacheKey];\n }\n if (\n cachedSnapshot === undefined &&\n stateRenderId &&\n previousUserMessageId &&\n caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`] !==\n undefined\n ) {\n cachedSnapshot =\n caches.byStateRenderAndRun[`${stateRenderId}::pending:${previousUserMessageId}`];\n }\n if (\n cachedSnapshot === undefined &&\n !skipLatestCache &&\n stateRenderId &&\n messageRole !== \"assistant\" &&\n (stateSnapshotProp !== undefined ||\n (agentState && Object.keys(agentState).length > 0))\n ) {\n cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];\n }\n\n const snapshotForClaim = existingClaim?.locked\n ? existingClaim.stateSnapshot ?? cachedSnapshot\n : hasSnapshotKeys\n ? snapshot\n : existingClaim?.stateSnapshot ?? cachedSnapshot;\n\n return { snapshot, hasSnapshotKeys, cachedSnapshot, allowEmptySnapshot, snapshotForClaim };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA0B;;;ACA1B,oBAAsC;AAmEtC,SAAS,4BAA4B,OAAY;AAC/C,MAAI,CAAC;AAAO,WAAO,CAAC;AACpB,QAAqE,YAA7D,YAAU,OAAO,WArE3B,IAqEuE,IAA7B,qCAA6B,IAA7B,CAAhC,YAAU,SAAO;AACzB,SAAO;AACT;AAGO,SAAS,gBAAgB,GAAQ,GAAQ;AAC9C,MAAK,KAAK,CAAC,KAAO,CAAC,KAAK;AAAI,WAAO;AACnC,QAAiE,QAAzD,YAAU,OAAO,WA5E3B,IA4EmE,IAAzB,iCAAyB,IAAzB,CAAhC,YAAU,SAAO;AACzB,QAKI,QAJF;AAAA,cAAU;AAAA,IACV,OAAO;AAAA,IACP,YAAY;AAAA,EAhFhB,IAkFM,IADC,iCACD,IADC;AAAA,IAHH;AAAA,IACA;AAAA,IACA;AAAA;AAIF,SAAO,KAAK,UAAU,oBAAoB,MAAM,KAAK,UAAU,oBAAoB;AACrF;AAEO,SAAS,uBAAuB,WAA+B;AACpE,SAAO,CAAC,CAAC,aAAa,UAAU,WAAW,uBAAuB;AACpE;AAEO,SAAS,yBAAyB,aAAiC;AACxE,SAAO,gBAAgB;AACzB;AAEO,SAAS,uBAAuB,OAAgD;AACrF,MAAI,CAAC,SAAS,OAAO,UAAU,UAAU;AACvC,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C,CAAC;AAE3C,mBAAa,QAAQ,EAAE,IAAI,EAAE,UAAU,OAAO,eAAe;AAC7D,YAAM,yBAAyB,IAAI;AACnC,UAAI,eAAe;AACjB,kBAAU,QAAQ,QAAQ,EAAE,EAAE,SAAS;AAAA,MACzC;AAAA,IACF;AAAA,EACF,WAAW,kBAAkB;AAC3B,UAAME,oBAAmB,UAAU,QAAQ,QAAQ,EAAE,EAAE;AACvD,QAAI,CAACA,mBAAkB;AACrB,gBAAU,QAAQ,QAAQ,EAAE,EAAE,gBAAgB;AAC9C,YAAM,gBAAgB,oBAChB,WAAM,gCAAgC,MAAtC,YAA2C,CAAC;AAElD,YAAM,WAAW,GAAG,kBAAkB;AACtC,oBAAc,QAAQ,IAAI;AAC1B,oBAAc,GAAG,uBAAuB,IAAI;AAC5C,YAAM,gCAAgC,IAAI;AAC1C,YAAM,eAAe,oBACf,WAAM,yBAAyB,MAA/B,YAAoC,CAAC;AAE3C,mBAAa,QAAQ,EAAE,IAAI,EAAE,UAAU,kBAAkB,OAAO,eAAe;AAC/E,YAAM,yBAAyB,IAAI;AAAA,IACrC;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,KAAK;AAC3B;","names":["_a","_b","_c","_d","existingClaim","existingSnapshot"]}
1
+ {"version":3,"sources":["../../src/hooks/use-coagent-state-render-registry.ts","../../src/hooks/use-coagent-state-render-bridge.helpers.ts"],"sourcesContent":["import { useEffect } from \"react\";\nimport {\n areStatesEquals,\n ClaimAction,\n getEffectiveRunId,\n isPlaceholderMessageId,\n isPlaceholderMessageName,\n readCachedMessageEntry,\n resolveClaim,\n selectSnapshot,\n type Claim,\n type ClaimsByMessageId,\n type SnapshotCaches,\n type StateRenderContext,\n} from \"./use-coagent-state-render-bridge.helpers\";\n\nexport interface StateRenderRegistryInput {\n agentId: string;\n stateRenderId?: string;\n message: { id: string; runId?: string; name?: string };\n messageIndex?: number;\n stateSnapshot?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n claimsRef: React.MutableRefObject<Record<string, Claim>>;\n}\n\nexport interface StateRenderRegistryResult {\n canRender: boolean;\n}\n\nconst LAST_SNAPSHOTS_BY_RENDER_AND_RUN = \"__lastSnapshotsByStateRenderIdAndRun\";\nconst LAST_SNAPSHOTS_BY_MESSAGE = \"__lastSnapshotsByMessageId\";\n\ntype SnapshotByMessageEntry = { snapshot: any; runId?: string } | any;\ntype ClaimsStore = Record<string, Claim> & {\n [LAST_SNAPSHOTS_BY_RENDER_AND_RUN]?: Record<string, any>;\n [LAST_SNAPSHOTS_BY_MESSAGE]?: Record<string, SnapshotByMessageEntry>;\n};\n\nfunction getClaimsStore(\n claimsRef: React.MutableRefObject<Record<string, Claim>>,\n): ClaimsStore {\n return claimsRef.current as ClaimsStore;\n}\n\nfunction getSnapshotCaches(\n claimsRef: React.MutableRefObject<Record<string, Claim>>,\n): SnapshotCaches {\n const store = getClaimsStore(claimsRef);\n return {\n byStateRenderAndRun: store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {},\n byMessageId: store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {},\n };\n}\n\nexport function useStateRenderRegistry({\n agentId,\n stateRenderId,\n message,\n messageIndex,\n stateSnapshot,\n agentState,\n agentMessages,\n claimsRef,\n}: StateRenderRegistryInput): StateRenderRegistryResult {\n const store = getClaimsStore(claimsRef);\n const runId = message.runId;\n const cachedMessageEntry = store[LAST_SNAPSHOTS_BY_MESSAGE]?.[message.id];\n const { runId: cachedMessageRunId } =\n readCachedMessageEntry(cachedMessageEntry);\n const existingClaimRunId = claimsRef.current[message.id]?.runId;\n const effectiveRunId = getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n });\n\n useEffect(() => {\n return () => {\n const existingClaim = claimsRef.current[message.id];\n if (\n existingClaim?.stateSnapshot &&\n Object.keys(existingClaim.stateSnapshot).length > 0\n ) {\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${existingClaim.stateRenderId}::${existingClaim.runId ?? \"pending\"}`;\n snapshotCache[cacheKey] = existingClaim.stateSnapshot;\n snapshotCache[`${existingClaim.stateRenderId}::latest`] =\n existingClaim.stateSnapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = {\n snapshot: existingClaim.stateSnapshot,\n runId: existingClaim.runId ?? effectiveRunId,\n };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n delete claimsRef.current[message.id];\n };\n }, [claimsRef, effectiveRunId, message.id]);\n\n if (!stateRenderId) {\n return { canRender: false };\n }\n\n const caches = getSnapshotCaches(claimsRef);\n const existingClaim = claimsRef.current[message.id] as Claim | undefined;\n\n const { snapshot, hasSnapshotKeys, allowEmptySnapshot, snapshotForClaim } =\n selectSnapshot({\n messageId: message.id,\n messageName: message.name,\n allowLiveState:\n isPlaceholderMessageName(message.name) ||\n isPlaceholderMessageId(message.id),\n skipLatestCache:\n isPlaceholderMessageName(message.name) ||\n isPlaceholderMessageId(message.id),\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp: stateSnapshot,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n });\n\n const resolution = resolveClaim({\n claims: claimsRef.current as ClaimsByMessageId,\n context: {\n agentId,\n messageId: message.id,\n stateRenderId,\n runId: effectiveRunId,\n messageIndex,\n } satisfies StateRenderContext,\n stateSnapshot: snapshotForClaim,\n });\n\n if (resolution.action === ClaimAction.Block) {\n return { canRender: false };\n }\n\n if (resolution.updateRunId && claimsRef.current[message.id]) {\n claimsRef.current[message.id].runId = resolution.updateRunId;\n }\n\n if (resolution.nextClaim) {\n claimsRef.current[message.id] = resolution.nextClaim;\n }\n\n if (resolution.lockOthers) {\n Object.entries(claimsRef.current).forEach(([id, claim]) => {\n if (id !== message.id && claim.stateRenderId === stateRenderId) {\n claim.locked = true;\n }\n });\n }\n\n if (existingClaim && !existingClaim.locked && agentMessages?.length) {\n const indexInAgentMessages = agentMessages.findIndex(\n (msg: any) => msg.id === message.id,\n );\n if (\n indexInAgentMessages >= 0 &&\n indexInAgentMessages < agentMessages.length - 1\n ) {\n existingClaim.locked = true;\n }\n }\n\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n const snapshotChanged =\n stateSnapshot &&\n existingSnapshot !== undefined &&\n !areStatesEquals(existingSnapshot, snapshot);\n\n if (\n snapshot &&\n (stateSnapshot || hasSnapshotKeys || allowEmptySnapshot) &&\n (!claimsRef.current[message.id].locked || snapshotChanged)\n ) {\n if (!claimsRef.current[message.id].locked || snapshotChanged) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshot;\n snapshotCache[`${stateRenderId}::latest`] = snapshot;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = { snapshot, runId: effectiveRunId };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n if (stateSnapshot) {\n claimsRef.current[message.id].locked = true;\n }\n }\n } else if (snapshotForClaim) {\n const existingSnapshot = claimsRef.current[message.id].stateSnapshot;\n if (!existingSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshotForClaim;\n const snapshotCache = {\n ...(store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] ?? {}),\n };\n const cacheKey = `${stateRenderId}::${effectiveRunId}`;\n snapshotCache[cacheKey] = snapshotForClaim;\n snapshotCache[`${stateRenderId}::latest`] = snapshotForClaim;\n store[LAST_SNAPSHOTS_BY_RENDER_AND_RUN] = snapshotCache;\n const messageCache = {\n ...(store[LAST_SNAPSHOTS_BY_MESSAGE] ?? {}),\n };\n messageCache[message.id] = {\n snapshot: snapshotForClaim,\n runId: effectiveRunId,\n };\n store[LAST_SNAPSHOTS_BY_MESSAGE] = messageCache;\n }\n }\n\n return { canRender: true };\n}\n","import { dataToUUID, parseJson } from \"@copilotkit/shared\";\n\nexport enum RenderStatus {\n InProgress = \"inProgress\",\n Complete = \"complete\",\n}\n\nexport enum ClaimAction {\n Create = \"create\",\n Override = \"override\",\n Existing = \"existing\",\n Block = \"block\",\n}\n\nexport interface StateRenderContext {\n agentId: string;\n stateRenderId: string;\n messageId: string;\n runId: string;\n messageIndex?: number;\n}\n\nexport interface Claim {\n stateRenderId: string;\n runId?: string;\n stateSnapshot?: any;\n locked?: boolean;\n messageIndex?: number;\n}\n\nexport type ClaimsByMessageId = Record<string, Claim>;\n\nexport interface ClaimResolution {\n canRender: boolean;\n action: ClaimAction;\n nextClaim?: Claim;\n lockOthers?: boolean;\n updateRunId?: string;\n}\n\nexport interface SnapshotCaches {\n byStateRenderAndRun: Record<string, any>;\n byMessageId: Record<string, any>;\n}\n\nexport interface SnapshotSelectionInput {\n messageId: string;\n messageName?: string;\n allowLiveState?: boolean;\n skipLatestCache?: boolean;\n stateRenderId?: string;\n effectiveRunId: string;\n stateSnapshotProp?: any;\n agentState?: any;\n agentMessages?: Array<{ id: string; role?: string }>;\n existingClaim?: Claim;\n caches: SnapshotCaches;\n}\n\nexport interface SnapshotSelectionResult {\n snapshot?: any;\n hasSnapshotKeys: boolean;\n cachedSnapshot?: any;\n allowEmptySnapshot?: boolean;\n snapshotForClaim?: any;\n}\n\nfunction getStateWithoutConstantKeys(state: any) {\n if (!state) return {};\n const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;\n return stateWithoutConstantKeys;\n}\n\n// Function that compares states, without the constant keys\nexport function areStatesEquals(a: any, b: any) {\n if ((a && !b) || (!a && b)) return false;\n const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;\n const {\n messages: bMessages,\n tools: bTools,\n copilotkit: bCopilotkit,\n ...bWithoutConstantKeys\n } = b;\n\n return (\n JSON.stringify(aWithoutConstantKeys) ===\n JSON.stringify(bWithoutConstantKeys)\n );\n}\n\nexport function isPlaceholderMessageId(messageId: string | undefined) {\n return !!messageId && messageId.startsWith(\"coagent-state-render-\");\n}\n\nexport function isPlaceholderMessageName(messageName: string | undefined) {\n return messageName === \"coagent-state-render\";\n}\n\nexport function readCachedMessageEntry(entry: any): {\n snapshot?: any;\n runId?: string;\n} {\n if (!entry || typeof entry !== \"object\") {\n return { snapshot: entry, runId: undefined };\n }\n const snapshot = \"snapshot\" in entry ? entry.snapshot : entry;\n const runId = \"runId\" in entry ? entry.runId : undefined;\n return { snapshot, runId };\n}\n\nexport function getEffectiveRunId({\n existingClaimRunId,\n cachedMessageRunId,\n runId,\n}: {\n existingClaimRunId?: string;\n cachedMessageRunId?: string;\n runId?: string;\n}) {\n return existingClaimRunId || cachedMessageRunId || runId || \"pending\";\n}\n\n/**\n * Resolve whether a message can claim a render slot.\n * This is a pure decision function; the caller applies claim mutations.\n */\nexport function resolveClaim({\n claims,\n context,\n stateSnapshot,\n}: {\n claims: ClaimsByMessageId;\n context: StateRenderContext;\n stateSnapshot?: any;\n}): ClaimResolution {\n const { messageId, stateRenderId, runId, messageIndex } = context;\n const existing = claims[messageId];\n\n if (existing) {\n const canRender = existing.stateRenderId === stateRenderId;\n const shouldUpdateRunId =\n canRender && runId && (!existing.runId || existing.runId === \"pending\");\n return {\n canRender,\n action: canRender ? ClaimAction.Existing : ClaimAction.Block,\n updateRunId: shouldUpdateRunId ? runId : undefined,\n };\n }\n\n const normalizedRunId = runId ?? \"pending\";\n const renderClaimedByOtherMessageEntry = Object.entries(claims).find(\n ([, claim]) =>\n claim.stateRenderId === stateRenderId &&\n (claim.runId ?? \"pending\") === normalizedRunId &&\n dataToUUID(getStateWithoutConstantKeys(claim.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(stateSnapshot)),\n );\n\n const renderClaimedByOtherMessage = renderClaimedByOtherMessageEntry?.[1];\n const claimedMessageId = renderClaimedByOtherMessageEntry?.[0];\n\n if (renderClaimedByOtherMessage) {\n if (\n messageIndex !== undefined &&\n renderClaimedByOtherMessage.messageIndex !== undefined &&\n messageIndex > renderClaimedByOtherMessage.messageIndex\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers:\n runId === renderClaimedByOtherMessage.runId ||\n isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (\n runId &&\n renderClaimedByOtherMessage.runId &&\n runId !== renderClaimedByOtherMessage.runId\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: isPlaceholderMessageId(claimedMessageId),\n };\n }\n\n if (isPlaceholderMessageId(claimedMessageId)) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId, messageIndex },\n lockOthers: true,\n };\n }\n\n if (\n stateSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, stateSnapshot)\n ) {\n return {\n canRender: true,\n action: ClaimAction.Override,\n nextClaim: { stateRenderId, runId },\n };\n }\n\n return { canRender: false, action: ClaimAction.Block };\n }\n\n if (!runId) {\n return { canRender: false, action: ClaimAction.Block };\n }\n\n return {\n canRender: true,\n action: ClaimAction.Create,\n nextClaim: { stateRenderId, runId, messageIndex },\n };\n}\n\n/**\n * Select the best snapshot to render for this message.\n * Priority order is:\n * 1) explicit message snapshot\n * 2) live agent state (latest assistant only)\n * 3) cached snapshot for message\n * 4) cached snapshot for stateRenderId+runId\n * 5) last cached snapshot for stateRenderId\n */\nexport function selectSnapshot({\n messageId,\n messageName,\n allowLiveState,\n skipLatestCache,\n stateRenderId,\n effectiveRunId,\n stateSnapshotProp,\n agentState,\n agentMessages,\n existingClaim,\n caches,\n}: SnapshotSelectionInput): SnapshotSelectionResult {\n const lastAssistantId = agentMessages\n ? [...agentMessages].reverse().find((msg) => msg.role === \"assistant\")?.id\n : undefined;\n const latestSnapshot =\n stateRenderId !== undefined\n ? caches.byStateRenderAndRun[`${stateRenderId}::latest`]\n : undefined;\n const messageIndex = agentMessages\n ? agentMessages.findIndex((msg) => msg.id === messageId)\n : -1;\n const messageRole =\n messageIndex >= 0 && agentMessages\n ? agentMessages[messageIndex]?.role\n : undefined;\n let previousUserMessageId: string | undefined;\n if (messageIndex > 0 && agentMessages) {\n for (let i = messageIndex - 1; i >= 0; i -= 1) {\n if (agentMessages[i]?.role === \"user\") {\n previousUserMessageId = agentMessages[i]?.id;\n break;\n }\n }\n }\n const liveStateIsStale =\n stateSnapshotProp === undefined &&\n latestSnapshot !== undefined &&\n agentState !== undefined &&\n areStatesEquals(latestSnapshot, agentState);\n const shouldUseLiveState =\n (Boolean(allowLiveState) ||\n !lastAssistantId ||\n messageId === lastAssistantId) &&\n !liveStateIsStale;\n const snapshot = stateSnapshotProp\n ? parseJson(stateSnapshotProp, stateSnapshotProp)\n : shouldUseLiveState\n ? agentState\n : undefined;\n const hasSnapshotKeys = !!(snapshot && Object.keys(snapshot).length > 0);\n const allowEmptySnapshot =\n snapshot !== undefined &&\n !hasSnapshotKeys &&\n (stateSnapshotProp !== undefined || shouldUseLiveState);\n\n const messageCacheEntry = caches.byMessageId[messageId];\n const cachedMessageSnapshot =\n readCachedMessageEntry(messageCacheEntry).snapshot;\n const cacheKey =\n stateRenderId !== undefined\n ? `${stateRenderId}::${effectiveRunId}`\n : undefined;\n let cachedSnapshot = cachedMessageSnapshot ?? caches.byMessageId[messageId];\n if (\n cachedSnapshot === undefined &&\n cacheKey &&\n caches.byStateRenderAndRun[cacheKey] !== undefined\n ) {\n cachedSnapshot = caches.byStateRenderAndRun[cacheKey];\n }\n if (\n cachedSnapshot === undefined &&\n stateRenderId &&\n previousUserMessageId &&\n caches.byStateRenderAndRun[\n `${stateRenderId}::pending:${previousUserMessageId}`\n ] !== undefined\n ) {\n cachedSnapshot =\n caches.byStateRenderAndRun[\n `${stateRenderId}::pending:${previousUserMessageId}`\n ];\n }\n if (\n cachedSnapshot === undefined &&\n !skipLatestCache &&\n stateRenderId &&\n messageRole !== \"assistant\" &&\n (stateSnapshotProp !== undefined ||\n (agentState && Object.keys(agentState).length > 0))\n ) {\n cachedSnapshot = caches.byStateRenderAndRun[`${stateRenderId}::latest`];\n }\n\n const snapshotForClaim = existingClaim?.locked\n ? (existingClaim.stateSnapshot ?? cachedSnapshot)\n : hasSnapshotKeys\n ? snapshot\n : (existingClaim?.stateSnapshot ?? cachedSnapshot);\n\n return {\n snapshot,\n hasSnapshotKeys,\n cachedSnapshot,\n allowEmptySnapshot,\n snapshotForClaim,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAA0B;;;ACA1B,oBAAsC;AAmEtC,SAAS,4BAA4B,OAAY;AAC/C,MAAI,CAAC;AAAO,WAAO,CAAC;AACpB,QAAqE,YAA7D,YAAU,OAAO,WArE3B,IAqEuE,IAA7B,qCAA6B,IAA7B,CAAhC,YAAU,SAAO;AACzB,SAAO;AACT;AAGO,SAAS,gBAAgB,GAAQ,GAAQ;AAC9C,MAAK,KAAK,CAAC,KAAO,CAAC,KAAK;AAAI,WAAO;AACnC,QAAiE,QAAzD,YAAU,OAAO,WA5E3B,IA4EmE,IAAzB,iCAAyB,IAAzB,CAAhC,YAAU,SAAO;AACzB,QAKI,QAJF;AAAA,cAAU;AAAA,IACV,OAAO;AAAA,IACP,YAAY;AAAA,EAhFhB,IAkFM,IADC,iCACD,IADC;AAAA,IAHH;AAAA,IACA;AAAA,IACA;AAAA;AAIF,SACE,KAAK,UAAU,oBAAoB,MACnC,KAAK,UAAU,oBAAoB;AAEvC;AAEO,SAAS,uBAAuB,WAA+B;AACpE,SAAO,CAAC,CAAC,aAAa,UAAU,WAAW,uBAAuB;AACpE;AAEO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I;AAC1B,oBAAc,GAAG,uBAAuB,IAAI;AAC5C,YAAM,gCAAgC,IAAI;AAC1C,YAAM,eAAe,oBACf,WAAM,yBAAyB,MAA/B,YAAoC,CAAC;AAE3C,mBAAa,QAAQ,EAAE,IAAI,EAAE,UAAU,OAAO,eAAe;AAC7D,YAAM,yBAAyB,IAAI;AACnC,UAAI,eAAe;AACjB,kBAAU,QAAQ,QAAQ,EAAE,EAAE,SAAS;AAAA,MACzC;AAAA,IACF;AAAA,EACF,WAAW,kBAAkB;AAC3B,UAAME,oBAAmB,UAAU,QAAQ,QAAQ,EAAE,EAAE;AACvD,QAAI,CAACA,mBAAkB;AACrB,gBAAU,QAAQ,QAAQ,EAAE,EAAE,gBAAgB;AAC9C,YAAM,gBAAgB,oBAChB,WAAM,gCAAgC,MAAtC,YAA2C,CAAC;AAElD,YAAM,WAAW,GAAG,kBAAkB;AACtC,oBAAc,QAAQ,IAAI;AAC1B,oBAAc,GAAG,uBAAuB,IAAI;AAC5C,YAAM,gCAAgC,IAAI;AAC1C,YAAM,eAAe,oBACf,WAAM,yBAAyB,MAA/B,YAAoC,CAAC;AAE3C,mBAAa,QAAQ,EAAE,IAAI;AAAA,QACzB,UAAU;AAAA,QACV,OAAO;AAAA,MACT;AACA,YAAM,yBAAyB,IAAI;AAAA,IACrC;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,KAAK;AAC3B;","names":["_a","_b","_c","_d","existingClaim","existingSnapshot"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  useStateRenderRegistry
3
- } from "../chunk-77IVITG3.mjs";
4
- import "../chunk-C3YJYDK4.mjs";
3
+ } from "../chunk-QXZTCGF4.mjs";
4
+ import "../chunk-7GIBHX6X.mjs";
5
5
  import "../chunk-SKC7AJIV.mjs";
6
6
  export {
7
7
  useStateRenderRegistry
@@ -86,7 +86,9 @@ var emptyCopilotContext = {
86
86
  },
87
87
  copilotApiConfig: new class {
88
88
  get chatApiEndpoint() {
89
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
89
+ throw new Error(
90
+ "Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!"
91
+ );
90
92
  }
91
93
  get headers() {
92
94
  return {};
@@ -146,7 +148,9 @@ var emptyCopilotContext = {
146
148
  };
147
149
  var CopilotContext = import_react.default.createContext(emptyCopilotContext);
148
150
  function returnAndThrowInDebug(_value) {
149
- throw new Error("Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!");
151
+ throw new Error(
152
+ "Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!"
153
+ );
150
154
  }
151
155
 
152
156
  // src/hooks/use-coagent-state-render.ts
@@ -168,13 +172,13 @@ function useToast() {
168
172
  // src/context/coagent-state-renders-context.tsx
169
173
  var import_react3 = require("react");
170
174
  var import_jsx_runtime2 = require("react/jsx-runtime");
171
- var CoAgentStateRendersContext = (0, import_react3.createContext)(
172
- void 0
173
- );
175
+ var CoAgentStateRendersContext = (0, import_react3.createContext)(void 0);
174
176
  function useCoAgentStateRenders() {
175
177
  const context = (0, import_react3.useContext)(CoAgentStateRendersContext);
176
178
  if (!context) {
177
- throw new Error("useCoAgentStateRenders must be used within CoAgentStateRendersProvider");
179
+ throw new Error(
180
+ "useCoAgentStateRenders must be used within CoAgentStateRendersProvider"
181
+ );
178
182
  }
179
183
  return context;
180
184
  }
@@ -182,7 +186,11 @@ function useCoAgentStateRenders() {
182
186
  // src/hooks/use-coagent-state-render.ts
183
187
  function useCoAgentStateRender(action, dependencies) {
184
188
  const { chatComponentsCache, availableAgents } = (0, import_react4.useContext)(CopilotContext);
185
- const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } = useCoAgentStateRenders();
189
+ const {
190
+ setCoAgentStateRender,
191
+ removeCoAgentStateRender,
192
+ coAgentStateRenders
193
+ } = useCoAgentStateRenders();
186
194
  const idRef = (0, import_react4.useRef)((0, import_shared2.randomId)());
187
195
  const { setBannerError, addToast } = useToast();
188
196
  (0, import_react4.useEffect)(() => {
@@ -190,7 +198,10 @@ function useCoAgentStateRender(action, dependencies) {
190
198
  const message = `(useCoAgentStateRender): Agent "${action.name}" not found. Make sure the agent exists and is properly configured.`;
191
199
  const agentError = new import_shared2.CopilotKitAgentDiscoveryError({
192
200
  agentName: action.name,
193
- availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id }))
201
+ availableAgents: availableAgents.map((a) => ({
202
+ name: a.name,
203
+ id: a.id
204
+ }))
194
205
  });
195
206
  setBannerError(agentError);
196
207
  }
@@ -208,19 +219,21 @@ function useCoAgentStateRender(action, dependencies) {
208
219
  }
209
220
  (0, import_react4.useEffect)(() => {
210
221
  const currentId = idRef.current;
211
- const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {
212
- if (id === currentId)
213
- return false;
214
- if (otherAction.name !== action.name)
215
- return false;
216
- const hasNodeName = !!action.nodeName;
217
- const hasOtherNodeName = !!otherAction.nodeName;
218
- if (!hasNodeName && !hasOtherNodeName)
219
- return true;
220
- if (hasNodeName !== hasOtherNodeName)
221
- return false;
222
- return action.nodeName === otherAction.nodeName;
223
- });
222
+ const hasDuplicate = Object.entries(coAgentStateRenders).some(
223
+ ([id, otherAction]) => {
224
+ if (id === currentId)
225
+ return false;
226
+ if (otherAction.name !== action.name)
227
+ return false;
228
+ const hasNodeName = !!action.nodeName;
229
+ const hasOtherNodeName = !!otherAction.nodeName;
230
+ if (!hasNodeName && !hasOtherNodeName)
231
+ return true;
232
+ if (hasNodeName !== hasOtherNodeName)
233
+ return false;
234
+ return action.nodeName === otherAction.nodeName;
235
+ }
236
+ );
224
237
  if (hasDuplicate) {
225
238
  const 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`;
226
239
  addToast({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-coagent-state-render.ts","../../src/context/copilot-context.tsx","../../src/components/toast/toast-provider.tsx","../../src/context/coagent-state-renders-context.tsx"],"sourcesContent":["/**\n * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * 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.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCoAgentStateRenders } from \"../context/coagent-state-renders-context\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const { chatComponentsCache, availableAgents } = useContext(CopilotContext);\n const { setCoAgentStateRender, removeCoAgentStateRender, coAgentStateRenders } =\n useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({ name: a.name, id: a.id })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n });\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetter,\n QueuedInterruptEvent,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | React.JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | React.JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // registered actions for component-based rendering\n setRegisteredActions: (actionConfig: any) => string;\n removeRegisteredAction: (actionKey: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n interruptActions: Record<string, LangGraphInterruptRender>;\n setInterruptAction: LangGraphInterruptActionSetter;\n removeInterruptAction: (actionId: string) => void;\n interruptEventQueue: Record<string, QueuedInterruptEvent[]>;\n addInterruptEvent: (queuedEvent: QueuedInterruptEvent) => void;\n resolveInterruptEvent: (threadId: string, eventId: string, response: string) => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError: CopilotErrorHandler;\n\n // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (handler: Record<string, CopilotErrorHandler>) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n setRegisteredActions: () => \"\",\n removeRegisteredAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n interruptActions: {},\n setInterruptAction: () => {},\n removeInterruptAction: () => {},\n interruptEventQueue: {},\n addInterruptEvent: () => {},\n resolveInterruptEvent: () => {},\n onError: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(null);\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\"addGraphQLErrorsToast is deprecated. All errors now show as banners.\");\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(/'message':\\s*'([^']+)'/);\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() => window.open(url, \"_blank\", \"noopener,noreferrer\")}\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform = \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","import React, {\n createContext,\n useContext,\n useCallback,\n useState,\n useRef,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\n\ninterface StateRenderClaim {\n stateRenderId: string;\n stateSnapshot?: any;\n runId?: string;\n messageIndex?: number;\n locked?: boolean;\n}\n\ntype ClaimsRef = Record<string, StateRenderClaim>;\n\nexport interface CoAgentStateRendersContextValue {\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n claimsRef: RefObject<ClaimsRef>;\n}\n\nconst CoAgentStateRendersContext = createContext<CoAgentStateRendersContextValue | undefined>(\n undefined,\n);\n\nexport function CoAgentStateRendersProvider({ children }: { children: ReactNode }) {\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const setCoAgentStateRender = useCallback((id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => ({\n ...prevPoints,\n [id]: stateRender,\n }));\n }, []);\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const claimsRef = useRef<ClaimsRef>({});\n\n return (\n <CoAgentStateRendersContext.Provider\n value={{\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n claimsRef,\n }}\n >\n {children}\n </CoAgentStateRendersContext.Provider>\n );\n}\n\nexport function useCoAgentStateRenders() {\n const context = useContext(CoAgentStateRendersContext);\n if (!context) {\n throw new Error(\"useCoAgentStateRenders must be used within CoAgentStateRendersProvider\");\n }\n return context;\n}\n\nexport { CoAgentStateRendersContext };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CA,IAAAA,gBAA8C;;;AChC9C,mBAAkB;AAuOlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,sBAAsB,MAAM;AAAA,EAC5B,wBAAwB,MAAM;AAAA,EAAC;AAAA,EAE/B,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;A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O,iDACzE,0CAA0C,OAAO;AAErD,eAAS;AAAA,QACP,MAAM;AAAA,QACN;AAAA,QACA,IAAI,cAAc,OAAO;AAAA,MAC3B,CAAC;AAAA,IACH;AAAA,EACF,GAAG,CAAC,mBAAmB,CAAC;AAExB,+BAAU,MAAM;AACd,0BAAsB,MAAM,SAAS,MAAa;AAClD,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,oBAAoB,GAAG,IAAI,OAAO;AAAA,IAChE;AACA,WAAO,MAAM;AACX,+BAAyB,MAAM,OAAO;AAAA,IACxC;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA;AAAA,IAEP,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React","import_shared","import_react","import_react","import_jsx_runtime"]}
1
+ {"version":3,"sources":["../../src/hooks/use-coagent-state-render.ts","../../src/context/copilot-context.tsx","../../src/components/toast/toast-provider.tsx","../../src/context/coagent-state-renders-context.tsx"],"sourcesContent":["/**\n * The useCoAgentStateRender hook allows you to render UI or text based components on a Agentic Copilot's state in the chat.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * 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.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId, CopilotKitAgentDiscoveryError } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\nimport { useCoAgentStateRenders } from \"../context/coagent-state-renders-context\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const { chatComponentsCache, availableAgents } = useContext(CopilotContext);\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n } = useCoAgentStateRenders();\n const idRef = useRef<string>(randomId());\n const { setBannerError, addToast } = useToast();\n\n useEffect(() => {\n if (\n availableAgents?.length &&\n !availableAgents.some((a) => a.name === action.name)\n ) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n\n // Route to banner instead of toast for consistency\n const agentError = new CopilotKitAgentDiscoveryError({\n agentName: action.name,\n availableAgents: availableAgents.map((a) => ({\n name: a.name,\n id: a.id,\n })),\n });\n setBannerError(agentError);\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(\n ([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n },\n );\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import {\n CopilotCloudConfig,\n FunctionCallHandler,\n CopilotErrorHandler,\n CopilotKitError,\n} from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId, Tree } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport {\n CoAgentStateRender,\n CoAgentStateRenderProps,\n} from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptRender,\n LangGraphInterruptActionSetter,\n QueuedInterruptEvent,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n\n /**\n * Optional configuration for connecting to Model Context Protocol (MCP) servers.\n * This is typically derived from the CopilotKitProps and used internally.\n * @experimental\n */\n mcpServers?: Array<{ endpoint: string; apiKey?: string }>;\n}\n\nexport type InChatRenderFunction<\n TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>,\n> = (props: TProps) => string | React.JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | React.JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\nexport type ContextTree = Tree;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // registered actions for component-based rendering\n setRegisteredActions: (actionConfig: any) => string;\n removeRegisteredAction: (actionKey: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (\n context: string,\n parentId?: string,\n categories?: string[],\n ) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getAllContext: () => Tree;\n getContextString: (\n documents: DocumentPointer[],\n categories: string[],\n ) => string;\n\n // document context\n addDocumentContext: (\n documentPointer: DocumentPointer,\n categories?: string[],\n ) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: {\n [key: string]: CopilotChatSuggestionConfiguration;\n };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean;\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<\n React.SetStateAction<Record<string, CoagentState>>\n >;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Partial<Pick<ForwardedParametersInput, \"temperature\">>;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<\n React.SetStateAction<Record<ActionName, AuthState>>\n >;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n interruptActions: Record<string, LangGraphInterruptRender>;\n setInterruptAction: LangGraphInterruptActionSetter;\n removeInterruptAction: (actionId: string) => void;\n interruptEventQueue: Record<string, QueuedInterruptEvent[]>;\n addInterruptEvent: (queuedEvent: QueuedInterruptEvent) => void;\n resolveInterruptEvent: (\n threadId: string,\n eventId: string,\n response: string,\n ) => void;\n\n /**\n * Optional trace handler for comprehensive debugging and observability.\n */\n onError: CopilotErrorHandler;\n\n // banner error state\n bannerError: CopilotKitError | null;\n setBannerError: React.Dispatch<React.SetStateAction<CopilotKitError | null>>;\n // Internal error handlers\n // These are used to handle errors that occur during the execution of the chat.\n // They are not intended for use by the developer. A component can register itself an error listener to be activated somewhere else as needed\n internalErrorHandlers: Record<string, CopilotErrorHandler>;\n setInternalErrorHandler: (\n handler: Record<string, CopilotErrorHandler>,\n ) => void;\n removeInternalErrorHandler: (id: string) => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n setRegisteredActions: () => \"\",\n removeRegisteredAction: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n getAllContext: () => [],\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: false,\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n interruptActions: {},\n setInterruptAction: () => {},\n removeInterruptAction: () => {},\n interruptEventQueue: {},\n addInterruptEvent: () => {},\n resolveInterruptEvent: () => {},\n onError: () => {},\n bannerError: null,\n setBannerError: () => {},\n internalErrorHandlers: {},\n setInternalErrorHandler: () => {},\n removeInternalErrorHandler: () => {},\n};\n\nexport const CopilotContext =\n React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\n \"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\",\n );\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { PartialBy, CopilotKitError, Severity } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n // Banner management\n bannerError: CopilotKitError | null;\n setBannerError: (error: CopilotKitError | null) => void;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\n// Helper functions for error banner styling\ntype ErrorSeverity = \"critical\" | \"warning\" | \"info\";\n\ninterface ErrorColors {\n background: string;\n border: string;\n text: string;\n icon: string;\n}\n\nfunction getErrorSeverity(error: CopilotKitError): ErrorSeverity {\n // Use structured error severity if available\n if (error.severity) {\n switch (error.severity) {\n case Severity.CRITICAL:\n return \"critical\";\n case Severity.WARNING:\n return \"warning\";\n case Severity.INFO:\n return \"info\";\n default:\n return \"info\";\n }\n }\n\n // Fallback: Check for API key errors which should always be critical\n const message = error.message.toLowerCase();\n if (\n message.includes(\"api key\") ||\n message.includes(\"401\") ||\n message.includes(\"unauthorized\") ||\n message.includes(\"authentication\") ||\n message.includes(\"incorrect api key\")\n ) {\n return \"critical\";\n }\n\n // Default to info level\n return \"info\";\n}\n\nfunction getErrorColors(severity: ErrorSeverity): ErrorColors {\n switch (severity) {\n case \"critical\":\n return {\n background: \"#fee2e2\",\n border: \"#dc2626\",\n text: \"#7f1d1d\",\n icon: \"#dc2626\",\n };\n case \"warning\":\n return {\n background: \"#fef3c7\",\n border: \"#d97706\",\n text: \"#78350f\",\n icon: \"#d97706\",\n };\n case \"info\":\n return {\n background: \"#dbeafe\",\n border: \"#2563eb\",\n text: \"#1e3a8a\",\n icon: \"#2563eb\",\n };\n }\n}\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const [bannerError, setBannerErrorState] = useState<CopilotKitError | null>(\n null,\n );\n\n const removeToast = useCallback((id: string) => {\n setToasts((prev) => prev.filter((toast) => toast.id !== id));\n }, []);\n\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // Respect the enabled flag for ALL toasts\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id))\n return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled, removeToast],\n );\n\n const setBannerError = useCallback(\n (error: CopilotKitError | null) => {\n // Respect the enabled flag for ALL errors\n if (!enabled && error !== null) {\n return;\n }\n setBannerErrorState(error);\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n // DEPRECATED: All errors now route to banners for consistency\n console.warn(\n \"addGraphQLErrorsToast is deprecated. All errors now show as banners.\",\n );\n // Function kept for backward compatibility - does nothing\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n bannerError,\n setBannerError,\n };\n\n return (\n <ToastContext.Provider value={value}>\n {/* Banner Error Display */}\n {bannerError &&\n (() => {\n const severity = getErrorSeverity(bannerError);\n const colors = getErrorColors(severity);\n\n return (\n <div\n style={{\n position: \"fixed\",\n bottom: \"20px\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 9999,\n backgroundColor: colors.background,\n border: `1px solid ${colors.border}`,\n borderLeft: `4px solid ${colors.border}`,\n borderRadius: \"8px\",\n padding: \"12px 16px\",\n fontSize: \"13px\",\n boxShadow: \"0 4px 12px rgba(0, 0, 0, 0.15)\",\n backdropFilter: \"blur(8px)\",\n maxWidth: \"min(90vw, 700px)\",\n width: \"100%\",\n boxSizing: \"border-box\",\n overflow: \"hidden\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: \"10px\",\n }}\n >\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"8px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n width: \"12px\",\n height: \"12px\",\n borderRadius: \"50%\",\n backgroundColor: colors.border,\n flexShrink: 0,\n }}\n />\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: \"10px\",\n flex: 1,\n minWidth: 0,\n }}\n >\n <div\n style={{\n color: colors.text,\n lineHeight: \"1.4\",\n fontWeight: \"400\",\n fontSize: \"13px\",\n flex: 1,\n wordBreak: \"break-all\",\n overflowWrap: \"break-word\",\n maxWidth: \"550px\",\n overflow: \"hidden\",\n display: \"-webkit-box\",\n WebkitLineClamp: 10,\n WebkitBoxOrient: \"vertical\",\n }}\n >\n {(() => {\n let message = bannerError.message;\n\n // Try to extract the useful message from JSON first\n const jsonMatch = message.match(\n /'message':\\s*'([^']+)'/,\n );\n if (jsonMatch) {\n return jsonMatch[1]; // Return the actual error message\n }\n\n // Strip technical garbage but keep the meaningful message\n message = message.split(\" - \")[0]; // Remove everything after \" - {\"\n message = message.split(\": Error code\")[0]; // Remove \": Error code: 401\"\n message = message.replace(/:\\s*\\d{3}$/, \"\"); // Remove trailing \": 401\"\n message = message.replace(/See more:.*$/g, \"\"); // Remove \"See more\" links\n message = message.trim();\n\n // If it's still garbage (contains { or '), use fallback\n // if (message.includes(\"{\") || message.includes(\"'\")) {\n // return \"Configuration error.... Please check your setup.\";\n // }\n\n return message || \"Configuration error occurred.\";\n })()}\n </div>\n\n {(() => {\n const message = bannerError.message;\n const markdownLinkRegex = /\\[([^\\]]+)\\]\\(([^)]+)\\)/g;\n const plainUrlRegex = /(https?:\\/\\/[^\\s)]+)/g;\n\n // Extract the first URL found\n let url = null;\n let buttonText = \"See More\";\n\n // Check for markdown links first\n const markdownMatch = markdownLinkRegex.exec(message);\n if (markdownMatch) {\n url = markdownMatch[2];\n buttonText = \"See More\";\n } else {\n // Check for plain URLs\n const urlMatch = plainUrlRegex.exec(message);\n if (urlMatch) {\n url = urlMatch[0].replace(/[.,;:'\"]*$/, \"\"); // Remove trailing punctuation\n buttonText = \"See More\";\n }\n }\n\n if (!url) return null;\n\n return (\n <button\n onClick={() =>\n window.open(url, \"_blank\", \"noopener,noreferrer\")\n }\n style={{\n background: colors.border,\n color: \"white\",\n border: \"none\",\n borderRadius: \"5px\",\n padding: \"4px 10px\",\n fontSize: \"11px\",\n fontWeight: \"500\",\n cursor: \"pointer\",\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"0.9\";\n e.currentTarget.style.transform =\n \"translateY(-1px)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.transform = \"translateY(0)\";\n }}\n >\n {buttonText}\n </button>\n );\n })()}\n </div>\n </div>\n <button\n onClick={() => setBannerError(null)}\n style={{\n background: \"transparent\",\n border: \"none\",\n color: colors.text,\n cursor: \"pointer\",\n padding: \"2px\",\n borderRadius: \"3px\",\n fontSize: \"14px\",\n lineHeight: \"1\",\n opacity: 0.6,\n transition: \"all 0.2s ease\",\n flexShrink: 0,\n }}\n title=\"Dismiss\"\n onMouseEnter={(e) => {\n e.currentTarget.style.opacity = \"1\";\n e.currentTarget.style.background = \"rgba(0, 0, 0, 0.05)\";\n }}\n onMouseLeave={(e) => {\n e.currentTarget.style.opacity = \"0.6\";\n e.currentTarget.style.background = \"transparent\";\n }}\n >\n ×\n </button>\n </div>\n </div>\n );\n })()}\n\n {/* Toast Display - Deprecated: All errors now show as banners */}\n {children}\n </ToastContext.Provider>\n );\n}\n\n// Toast component removed - all errors now show as banners for consistency\n","import React, {\n createContext,\n useContext,\n useCallback,\n useState,\n useRef,\n ReactNode,\n RefObject,\n} from \"react\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\n\ninterface StateRenderClaim {\n stateRenderId: string;\n stateSnapshot?: any;\n runId?: string;\n messageIndex?: number;\n locked?: boolean;\n}\n\ntype ClaimsRef = Record<string, StateRenderClaim>;\n\nexport interface CoAgentStateRendersContextValue {\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (\n id: string,\n stateRender: CoAgentStateRender<any>,\n ) => void;\n removeCoAgentStateRender: (id: string) => void;\n claimsRef: RefObject<ClaimsRef>;\n}\n\nconst CoAgentStateRendersContext = createContext<\n CoAgentStateRendersContextValue | undefined\n>(undefined);\n\nexport function CoAgentStateRendersProvider({\n children,\n}: {\n children: ReactNode;\n}) {\n const [coAgentStateRenders, setCoAgentStateRenders] = useState<\n Record<string, CoAgentStateRender<any>>\n >({});\n\n const setCoAgentStateRender = useCallback(\n (id: string, stateRender: CoAgentStateRender<any>) => {\n setCoAgentStateRenders((prevPoints) => ({\n ...prevPoints,\n [id]: stateRender,\n }));\n },\n [],\n );\n\n const removeCoAgentStateRender = useCallback((id: string) => {\n setCoAgentStateRenders((prevPoints) => {\n const newPoints = { ...prevPoints };\n delete newPoints[id];\n return newPoints;\n });\n }, []);\n\n const claimsRef = useRef<ClaimsRef>({});\n\n return (\n <CoAgentStateRendersContext.Provider\n value={{\n coAgentStateRenders,\n setCoAgentStateRender,\n removeCoAgentStateRender,\n claimsRef,\n }}\n >\n {children}\n </CoAgentStateRendersContext.Provider>\n );\n}\n\nexport function useCoAgentStateRenders() {\n const context = useContext(CoAgentStateRendersContext);\n if (!context) {\n throw new Error(\n \"useCoAgentStateRenders must be used within CoAgentStateRendersProvider\",\n );\n }\n return context;\n}\n\nexport { CoAgentStateRendersContext };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CA,IAAAA,gBAA8C;;;AChC9C,mBAAkB;AAiQlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,sBAAsB,MAAM;AAAA,EAC5B,wBAAwB,MAAM;AAAA,EAAC;AAAA,EAE/B,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EACtB,eAAe,MAAM,CAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,wBAAwB,CAAC;AAAA,EACzB,2BAA2B,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAEzD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC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,IAChE;AACA,WAAO,MAAM;AACX,+BAAyB,MAAM,OAAO;AAAA,IACxC;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA;AAAA,IAEP,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React","import_shared","import_react","import_react","import_jsx_runtime"]}
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  useCoAgentStateRender
3
- } from "../chunk-VKNLTZJE.mjs";
4
- import "../chunk-EFL5OBKN.mjs";
5
- import "../chunk-QD7EID4N.mjs";
6
- import "../chunk-AFNWX62Q.mjs";
3
+ } from "../chunk-6ABVYB2U.mjs";
4
+ import "../chunk-ZP2IMXFY.mjs";
5
+ import "../chunk-IHMMKEFG.mjs";
6
+ import "../chunk-C7HSVDHD.mjs";
7
7
  import "../chunk-SKC7AJIV.mjs";
8
8
  export {
9
9
  useCoAgentStateRender
@@ -123,7 +123,9 @@ function useCoAgent(options) {
123
123
  }, [options.config, options.configurable]);
124
124
  const externalStateStr = (0, import_react3.useMemo)(
125
125
  () => isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0,
126
- [isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0]
126
+ [
127
+ isExternalStateManagement(options) ? JSON.stringify(options.state) : void 0
128
+ ]
127
129
  );
128
130
  (0, import_react3.useEffect)(() => {
129
131
  if ((agent == null ? void 0 : agent.state) && isExternalStateManagement(options) && JSON.stringify(options.state) !== JSON.stringify(agent.state)) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-coagent.ts","../../src/hooks/use-agent-nodename.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAgent, useCopilotKit } from \"@copilotkitnext/react\";\nimport { type AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<T> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (...args: any[]) => Promise<any>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(options: UseCoagentOptions<T>): UseCoagentReturnType<T> {\n const { agent } = useAgent({ agentId: options.name });\n const { copilotkit } = useCopilotKit();\n const nodeName = useAgentNodeName(options.name);\n\n const handleStateUpdate = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n if (!agent) return;\n\n if (typeof newState === \"function\") {\n const updater = newState as (prevState: T | undefined) => T;\n agent.setState(updater(agent.state));\n } else {\n agent.setState({ ...agent.state, ...newState });\n }\n },\n [agent?.state, agent?.setState],\n );\n\n useEffect(() => {\n if (!options.config && !options.configurable) return;\n\n let config = options.config ?? {};\n if (options.configurable) {\n config = {\n ...config,\n configurable: {\n ...options.configurable,\n ...config.configurable,\n },\n };\n }\n copilotkit.setProperties(config);\n }, [options.config, options.configurable]);\n\n const externalStateStr = useMemo(\n () => (isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined),\n [isExternalStateManagement(options) ? JSON.stringify(options.state) : undefined],\n );\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (\n agent?.state &&\n isExternalStateManagement(options) &&\n JSON.stringify(options.state) !== JSON.stringify(agent.state)\n ) {\n handleStateUpdate(options.state);\n }\n }, [agent, externalStateStr, handleStateUpdate]);\n\n const hasStateValues = useCallback((value?: Record<string, any>) => {\n return Boolean(value && Object.keys(value).length);\n }, []);\n\n const initialStateRef = useRef<any>(\n isExternalStateManagement(options)\n ? options.state\n : \"initialState\" in options\n ? options.initialState\n : undefined,\n );\n\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n initialStateRef.current = options.state;\n } else if (\"initialState\" in options) {\n initialStateRef.current = options.initialState;\n }\n }, [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : \"initialState\" in options\n ? JSON.stringify(options.initialState)\n : undefined,\n ]);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: (args: any) => {\n if (isExternalStateManagement(options)) {\n options.setState(args.state);\n }\n },\n onRunInitialized: (args: any) => {\n const runHasState = hasStateValues(args.state);\n if (runHasState) {\n handleStateUpdate(args.state);\n return;\n }\n\n if (hasStateValues(agent.state)) {\n return;\n }\n\n if (initialStateRef.current !== undefined) {\n handleStateUpdate(initialStateRef.current);\n }\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent, handleStateUpdate, hasStateValues]);\n\n // Return a consistent shape whether or not the agent is available\n return useMemo<UseCoagentReturnType<T>>(() => {\n if (!agent) {\n const noop = () => {};\n const noopAsync = async () => {};\n const initialState =\n // prefer externally provided state if available\n (\"state\" in options && (options as any).state) ??\n // then initialState if provided\n (\"initialState\" in options && (options as any).initialState) ??\n ({} as T);\n return {\n name: options.name,\n nodeName,\n threadId: undefined,\n running: false,\n state: initialState as T,\n setState: noop,\n start: noop,\n stop: noop,\n run: noopAsync,\n };\n }\n\n return {\n name: agent?.agentId ?? options.name,\n nodeName,\n threadId: agent.threadId,\n running: agent.isRunning,\n state: agent.state,\n setState: handleStateUpdate,\n // TODO: start and run both have same thing. need to figure out\n start: agent.runAgent,\n stop: agent.abortRun,\n run: agent.runAgent,\n };\n }, [\n agent?.state,\n agent?.runAgent,\n agent?.abortRun,\n agent?.runAgent,\n agent?.threadId,\n agent?.isRunning,\n agent?.agentId,\n handleStateUpdate,\n options.name,\n ]);\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n","import { useEffect, useRef } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgent } from \"@copilotkitnext/react\";\n\nexport function useAgentNodeName(agentName?: string) {\n const { agent } = useAgent({ agentId: agentName });\n const nodeNameRef = useRef<string>(\"start\");\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStepStartedEvent: ({ event }) => {\n nodeNameRef.current = event.stepName;\n },\n onRunStartedEvent: () => {\n nodeNameRef.current = \"start\";\n },\n onRunFinishedEvent: () => {\n nodeNameRef.current = \"end\";\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent]);\n\n return nodeNameRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA0FA,IAAAA,gBAAkE;AAElE,IAAAA,gBAAwC;;;AC5FxC,mBAAkC;AAElC,IAAAC,gBAAyB;AAElB,SAAS,iBAAiB,WAAoB;AACnD,QAAM,EAAE,MAAM,QAAI,wBAAS,EAAE,SAAS,UAAU,CAAC;AACjD,QAAM,kBAAc,qBAAe,OAAO;AAE1C,8BAAU,MAAM;AACd,QAAI,CAAC;AAAO;AACZ,UAAM,aAA8B;AAAA,MAClC,oBAAoB,CAAC,EAAE,MAAM,MAAM;AACjC,oBAAY,UAAU,MAAM;AAAA,MAC9B;AAAA,MACA,mBAAmB,MAAM;AACvB,oBAAY,UAAU;AAAA,MACxB;AAAA,MACA,oBAAoB,MAAM;AACxB,oBAAY,UAAU;AAAA,MACxB;AAAA,IACF;AAEA,UAAM,eAAe,MAAM,UAAU,UAAU;AAC/C,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO,YAAY;AACrB;;;AD+KO,SAAS,WAAoB,SAAwD;AAC1F,QAAM,EAAE,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AA;AAAA,UAEA,kBAAkB,WAAY,QAAgB;AAAA,cAF9C,YAGA,CAAC;AAAA;AACJ,aAAO;AAAA,QACL,MAAM,QAAQ;AAAA,QACd;AAAA,QACA,UAAU;AAAA,QACV,SAAS;AAAA,QACT,OAAO;AAAA,QACP,UAAU;AAAA,QACV,OAAO;AAAA,QACP,MAAM;AAAA,QACN,KAAK;AAAA,MACP;AAAA,IACF;AAEA,WAAO;AAAA,MACL,OAAM,oCAAO,YAAP,YAAkB,QAAQ;AAAA,MAChC;AAAA,MACA,UAAU,MAAM;AAAA,MAChB,SAAS,MAAM;AAAA,MACf,OAAO,MAAM;AAAA,MACb,UAAU;AAAA;AAAA,MAEV,OAAO,MAAM;AAAA,MACb,MAAM,MAAM;AAAA,MACZ,KAAK,MAAM;AAAA,IACb;AAAA,EACF,GAAG;AAAA,IACD,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACH;AAEA,IAAM,4BAA4B,CAChC,YAC8C;AAC9C,SAAO,WAAW,WAAW,cAAc;AAC7C;","names":["import_react","import_react"]}
1
+ {"version":3,"sources":["../../src/hooks/use-coagent.ts","../../src/hooks/use-agent-nodename.ts"],"sourcesContent":["/**\n * <Callout type=\"info\">\n * Usage of this hook assumes some additional setup in your application, for more information\n * on that see the CoAgents <span className=\"text-blue-500\">[getting started guide](/coagents/quickstart/langgraph)</span>.\n * </Callout>\n * <Frame className=\"my-12\">\n * <img\n * src=\"https://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif\"\n * alt=\"CoAgents demonstration\"\n * className=\"w-auto\"\n * />\n * </Frame>\n *\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of an agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences agentic copilots, or CoAgents for short.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgent } from \"@copilotkit/react-core\";\n *\n * type AgentState = {\n * count: number;\n * }\n *\n * const agent = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * ```\n *\n * `useCoAgent` returns an object with the following properties:\n *\n * ```tsx\n * const {\n * name, // The name of the agent currently being used.\n * nodeName, // The name of the current LangGraph node.\n * state, // The current state of the agent.\n * setState, // A function to update the state of the agent.\n * running, // A boolean indicating if the agent is currently running.\n * start, // A function to start the agent.\n * stop, // A function to stop the agent.\n * run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run.\n * } = agent;\n * ```\n *\n * Finally we can leverage these properties to create reactive experiences with the agent!\n *\n * ```tsx\n * const { state, setState } = useCoAgent<AgentState>({\n * name: \"my-agent\",\n * initialState: {\n * count: 0,\n * },\n * });\n *\n * return (\n * <div>\n * <p>Count: {state.count}</p>\n * <button onClick={() => setState({ count: state.count + 1 })}>Increment</button>\n * </div>\n * );\n * ```\n *\n * This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa.\n *\n * ## Parameters\n * <PropertyReference name=\"options\" type=\"UseCoagentOptions<T>\" required>\n * The options to use when creating the coagent.\n * <PropertyReference name=\"name\" type=\"string\" required>\n * The name of the agent to use.\n * </PropertyReference>\n * <PropertyReference name=\"initialState\" type=\"T | any\">\n * The initial state of the agent.\n * </PropertyReference>\n * <PropertyReference name=\"state\" type=\"T | any\">\n * State to manage externally if you are using this hook with external state management.\n * </PropertyReference>\n * <PropertyReference name=\"setState\" type=\"(newState: T | ((prevState: T | undefined) => T)) => void\">\n * A function to update the state of the agent if you are using this hook with external state management.\n * </PropertyReference>\n * </PropertyReference>\n */\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Message } from \"@copilotkit/shared\";\nimport { useAgent, useCopilotKit } from \"@copilotkitnext/react\";\nimport { type AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgentNodeName } from \"./use-agent-nodename\";\n\ninterface UseCoagentOptionsBase {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * @deprecated - use \"config.configurable\"\n * Config to pass to a LangGraph Agent\n */\n configurable?: Record<string, any>;\n /**\n * Config to pass to a LangGraph Agent\n */\n config?: {\n configurable?: Record<string, any>;\n [key: string]: any;\n };\n}\n\ninterface WithInternalStateManagementAndInitial<\n T,\n> extends UseCoagentOptionsBase {\n /**\n * The initial state of the agent.\n */\n initialState: T;\n}\n\ninterface WithInternalStateManagement extends UseCoagentOptionsBase {\n /**\n * Optional initialState with default type any\n */\n initialState?: any;\n}\n\ninterface WithExternalStateManagement<T> extends UseCoagentOptionsBase {\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n}\n\ntype UseCoagentOptions<T> =\n | WithInternalStateManagementAndInitial<T>\n | WithInternalStateManagement\n | WithExternalStateManagement<T>;\n\nexport interface UseCoagentReturnType<T> {\n /**\n * The name of the agent being used.\n */\n name: string;\n /**\n * The name of the current LangGraph node.\n */\n nodeName?: string;\n /**\n * The ID of the thread the agent is running in.\n */\n threadId?: string;\n /**\n * A boolean indicating if the agent is currently running.\n */\n running: boolean;\n /**\n * The current state of the agent.\n */\n state: T;\n /**\n * A function to update the state of the agent.\n */\n setState: (newState: T | ((prevState: T | undefined) => T)) => void;\n /**\n * A function to start the agent.\n */\n start: () => void;\n /**\n * A function to stop the agent.\n */\n stop: () => void;\n /**\n * A function to re-run the agent. The hint function can be used to provide a hint to the agent\n * about why it is being re-run again.\n */\n run: (...args: any[]) => Promise<any>;\n}\n\nexport interface HintFunctionParams {\n /**\n * The previous state of the agent.\n */\n previousState: any;\n /**\n * The current state of the agent.\n */\n currentState: any;\n}\n\nexport type HintFunction = (params: HintFunctionParams) => Message | undefined;\n\n/**\n * This hook is used to integrate an agent into your application. With its use, you can\n * render and update the state of the agent, allowing for a dynamic and interactive experience.\n * We call these shared state experiences \"agentic copilots\". To get started using agentic copilots, which\n * we refer to as CoAgents, checkout the documentation at https://docs.copilotkit.ai/coagents/quickstart/langgraph.\n */\nexport function useCoAgent<T = any>(\n options: UseCoagentOptions<T>,\n): UseCoagentReturnType<T> {\n const { agent } = useAgent({ agentId: options.name });\n const { copilotkit } = useCopilotKit();\n const nodeName = useAgentNodeName(options.name);\n\n const handleStateUpdate = useCallback(\n (newState: T | ((prevState: T | undefined) => T)) => {\n if (!agent) return;\n\n if (typeof newState === \"function\") {\n const updater = newState as (prevState: T | undefined) => T;\n agent.setState(updater(agent.state));\n } else {\n agent.setState({ ...agent.state, ...newState });\n }\n },\n [agent?.state, agent?.setState],\n );\n\n useEffect(() => {\n if (!options.config && !options.configurable) return;\n\n let config = options.config ?? {};\n if (options.configurable) {\n config = {\n ...config,\n configurable: {\n ...options.configurable,\n ...config.configurable,\n },\n };\n }\n copilotkit.setProperties(config);\n }, [options.config, options.configurable]);\n\n const externalStateStr = useMemo(\n () =>\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : undefined,\n ],\n );\n\n // Sync internal state with external state if state management is external\n useEffect(() => {\n if (\n agent?.state &&\n isExternalStateManagement(options) &&\n JSON.stringify(options.state) !== JSON.stringify(agent.state)\n ) {\n handleStateUpdate(options.state);\n }\n }, [agent, externalStateStr, handleStateUpdate]);\n\n const hasStateValues = useCallback((value?: Record<string, any>) => {\n return Boolean(value && Object.keys(value).length);\n }, []);\n\n const initialStateRef = useRef<any>(\n isExternalStateManagement(options)\n ? options.state\n : \"initialState\" in options\n ? options.initialState\n : undefined,\n );\n\n useEffect(() => {\n if (isExternalStateManagement(options)) {\n initialStateRef.current = options.state;\n } else if (\"initialState\" in options) {\n initialStateRef.current = options.initialState;\n }\n }, [\n isExternalStateManagement(options)\n ? JSON.stringify(options.state)\n : \"initialState\" in options\n ? JSON.stringify(options.initialState)\n : undefined,\n ]);\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStateChanged: (args: any) => {\n if (isExternalStateManagement(options)) {\n options.setState(args.state);\n }\n },\n onRunInitialized: (args: any) => {\n const runHasState = hasStateValues(args.state);\n if (runHasState) {\n handleStateUpdate(args.state);\n return;\n }\n\n if (hasStateValues(agent.state)) {\n return;\n }\n\n if (initialStateRef.current !== undefined) {\n handleStateUpdate(initialStateRef.current);\n }\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent, handleStateUpdate, hasStateValues]);\n\n // Return a consistent shape whether or not the agent is available\n return useMemo<UseCoagentReturnType<T>>(() => {\n if (!agent) {\n const noop = () => {};\n const noopAsync = async () => {};\n const initialState =\n // prefer externally provided state if available\n (\"state\" in options && (options as any).state) ??\n // then initialState if provided\n (\"initialState\" in options && (options as any).initialState) ??\n ({} as T);\n return {\n name: options.name,\n nodeName,\n threadId: undefined,\n running: false,\n state: initialState as T,\n setState: noop,\n start: noop,\n stop: noop,\n run: noopAsync,\n };\n }\n\n return {\n name: agent?.agentId ?? options.name,\n nodeName,\n threadId: agent.threadId,\n running: agent.isRunning,\n state: agent.state,\n setState: handleStateUpdate,\n // TODO: start and run both have same thing. need to figure out\n start: agent.runAgent,\n stop: agent.abortRun,\n run: agent.runAgent,\n };\n }, [\n agent?.state,\n agent?.runAgent,\n agent?.abortRun,\n agent?.runAgent,\n agent?.threadId,\n agent?.isRunning,\n agent?.agentId,\n handleStateUpdate,\n options.name,\n ]);\n}\n\nconst isExternalStateManagement = <T>(\n options: UseCoagentOptions<T>,\n): options is WithExternalStateManagement<T> => {\n return \"state\" in options && \"setState\" in options;\n};\n","import { useEffect, useRef } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useAgent } from \"@copilotkitnext/react\";\n\nexport function useAgentNodeName(agentName?: string) {\n const { agent } = useAgent({ agentId: agentName });\n const nodeNameRef = useRef<string>(\"start\");\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStepStartedEvent: ({ event }) => {\n nodeNameRef.current = event.stepName;\n },\n onRunStartedEvent: () => {\n nodeNameRef.current = \"start\";\n },\n onRunFinishedEvent: () => {\n nodeNameRef.current = \"end\";\n },\n };\n\n const subscription = agent.subscribe(subscriber);\n return () => {\n subscription.unsubscribe();\n };\n }, [agent]);\n\n return nodeNameRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA0FA,IAAAA,gBAAkE;AAElE,IAAAA,gBAAwC;;;AC5FxC,mBAAkC;AAElC,IAAAC,gBAAyB;AAElB,SAAS,iBAAiB,WAAoB;AACnD,QAAM,EAAE,MAAM,QAAI,wBAAS,EAAE,SAAS,UAAU,CAAC;AACjD,QAAM,kBAAc,qBAAe,OAAO;AAE1C,8BAAU,MAAM;AACd,QAAI,CAAC;AAAO;AACZ,UAAM,aAA8B;AAAA,MAClC,oBAAoB,CAAC,EAAE,MAAM,MAAM;AACjC,oBAAY,UAAU,MAAM;AAAA,MAC9B;AAAA,MACA,mBAAmB,MAAM;AACvB,oBAAY,UAAU;AAAA,MACxB;AAAA,MACA,oBAAoB,MAAM;AACxB,oBAAY,UAAU;AAAA,MACxB;AAAA,IACF;AAEA,UAAM,eAAe,MAAM,UAAU,UAAU;AAC/C,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,KAAK,CAAC;AAEV,SAAO,YAAY;AACrB;;;ADiLO,SAAS,WACd,SACyB;AACzB,QAAM,EAAE,MAAM,QAAI,wBAAS,EAAE,SAAS,QAAQ,KAAK,CAAC;AACpD,QAAM,EAAE,WAAW,QAAI,6BAAc;AACrC,QAAM,WAAW,iBAAiB,QAAQ,IAAI;AAE9C,QAAM,wBAAoB;AAAA,IACxB,CAAC,aAAoD;AACnD,UAAI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,UAAU;AAAA,QACV,OAAO;AAAA,QACP,MAAM;AAAA,QACN,KAAK;AAAA,MACP;AAAA,IACF;AAEA,WAAO;AAAA,MACL,OAAM,oCAAO,YAAP,YAAkB,QAAQ;AAAA,MAChC;AAAA,MACA,UAAU,MAAM;AAAA,MAChB,SAAS,MAAM;AAAA,MACf,OAAO,MAAM;AAAA,MACb,UAAU;AAAA;AAAA,MAEV,OAAO,MAAM;AAAA,MACb,MAAM,MAAM;AAAA,MACZ,KAAK,MAAM;AAAA,IACb;AAAA,EACF,GAAG;AAAA,IACD,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP,+BAAO;AAAA,IACP;AAAA,IACA,QAAQ;AAAA,EACV,CAAC;AACH;AAEA,IAAM,4BAA4B,CAChC,YAC8C;AAC9C,SAAO,WAAW,WAAW,cAAc;AAC7C;","names":["import_react","import_react"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCoAgent
3
- } from "../chunk-ZYTXB6HH.mjs";
3
+ } from "../chunk-CZT7JUIM.mjs";
4
4
  import "../chunk-I76HKHPJ.mjs";
5
5
  import "../chunk-SKC7AJIV.mjs";
6
6
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-configure-chat-suggestions.tsx"],"sourcesContent":["import {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\nimport { useCopilotContext } from \"../context\";\nimport { useEffect, useMemo } from \"react\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> & Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<StaticSuggestionsConfig, \"suggestions\"> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?: \"enabled\" | \"disabled\" | \"always\" | \"before-first-message\" | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useConfigureChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n): ReturnType<typeof useSuggestions> {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { copilotkit } = useCopilotKit();\n\n const available = config.available === \"enabled\" ? \"always\" : config.available;\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n\n const result = useSuggestions({ agentId: resolvedAgentId });\n\n useEffect(() => {\n if (finalSuggestionConfig.available === \"disabled\") return;\n const subscription = copilotkit.subscribe({\n onAgentsChanged: () => {\n // When agents change, check if our target agent now exists and reload\n const agent = copilotkit.getAgent(resolvedAgentId);\n if (agent && !agent.isRunning && !result.suggestions.length) {\n copilotkit.reloadSuggestions(resolvedAgentId);\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [resolvedAgentId]);\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAKO;AAGP,IAAAA,gBAAmC;AAwC5B,SAAS,4BACd,QACA,eAAsB,CAAC,GACY;AAnDrC;AAoDE,QAAM,qBAAiB,0CAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AACnD,QAAM,EAAE,WAAW,QAAI,4BAAc;AAErC,QAAM,YAAY,OAAO,cAAc,YAAY,WAAW,OAAO;AAErE,QAAM,wBAAwB,iCACzB,SADyB;AAAA,IAE5B;AAAA,IACA,iBAAiB;AAAA;AAAA,EACnB;AACA,4CAAwB,uBAAuB,YAAY;AAE3D,QAAM,aAAS,6BAAe,EAAE,SAAS,gBAAgB,CAAC;AAE1D,+BAAU,MAAM;AACd,QAAI,sBAAsB,cAAc;AAAY;AACpD,UAAM,eAAe,WAAW,UAAU;AAAA,MACxC,iBAAiB,MAAM;AAErB,cAAM,QAAQ,WAAW,SAAS,eAAe;AACjD,YAAI,SAAS,CAAC,MAAM,aAAa,CAAC,OAAO,YAAY,QAAQ;AAC3D,qBAAW,kBAAkB,eAAe;AAAA,QAC9C;AAAA,MACF;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,SAAO;AACT;","names":["import_react"]}
1
+ {"version":3,"sources":["../../src/hooks/use-configure-chat-suggestions.tsx"],"sourcesContent":["import {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\nimport { useCopilotContext } from \"../context\";\nimport { useEffect, useMemo } from \"react\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?:\n | \"enabled\"\n | \"disabled\"\n | \"always\"\n | \"before-first-message\"\n | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useConfigureChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n): ReturnType<typeof useSuggestions> {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { copilotkit } = useCopilotKit();\n\n const available =\n config.available === \"enabled\" ? \"always\" : config.available;\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n\n const result = useSuggestions({ agentId: resolvedAgentId });\n\n useEffect(() => {\n if (finalSuggestionConfig.available === \"disabled\") return;\n const subscription = copilotkit.subscribe({\n onAgentsChanged: () => {\n // When agents change, check if our target agent now exists and reload\n const agent = copilotkit.getAgent(resolvedAgentId);\n if (agent && !agent.isRunning && !result.suggestions.length) {\n copilotkit.reloadSuggestions(resolvedAgentId);\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [resolvedAgentId]);\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAKO;AAGP,IAAAA,gBAAmC;AAiD5B,SAAS,4BACd,QACA,eAAsB,CAAC,GACY;AA5DrC;AA6DE,QAAM,qBAAiB,0CAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AACnD,QAAM,EAAE,WAAW,QAAI,4BAAc;AAErC,QAAM,YACJ,OAAO,cAAc,YAAY,WAAW,OAAO;AAErD,QAAM,wBAAwB,iCACzB,SADyB;AAAA,IAE5B;AAAA,IACA,iBAAiB;AAAA;AAAA,EACnB;AACA,4CAAwB,uBAAuB,YAAY;AAE3D,QAAM,aAAS,6BAAe,EAAE,SAAS,gBAAgB,CAAC;AAE1D,+BAAU,MAAM;AACd,QAAI,sBAAsB,cAAc;AAAY;AACpD,UAAM,eAAe,WAAW,UAAU;AAAA,MACxC,iBAAiB,MAAM;AAErB,cAAM,QAAQ,WAAW,SAAS,eAAe;AACjD,YAAI,SAAS,CAAC,MAAM,aAAa,CAAC,OAAO,YAAY,QAAQ;AAC3D,qBAAW,kBAAkB,eAAe;AAAA,QAC9C;AAAA,MACF;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,SAAO;AACT;","names":["import_react"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/hooks/use-configure-chat-suggestions.tsx"],"sourcesContent":["import {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\nimport { useCopilotContext } from \"../context\";\nimport { useEffect, useMemo } from \"react\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> & Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<StaticSuggestionsConfig, \"suggestions\"> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?: \"enabled\" | \"disabled\" | \"always\" | \"before-first-message\" | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useConfigureChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n): ReturnType<typeof useSuggestions> {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { copilotkit } = useCopilotKit();\n\n const available = config.available === \"enabled\" ? \"always\" : config.available;\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n\n const result = useSuggestions({ agentId: resolvedAgentId });\n\n useEffect(() => {\n if (finalSuggestionConfig.available === \"disabled\") return;\n const subscription = copilotkit.subscribe({\n onAgentsChanged: () => {\n // When agents change, check if our target agent now exists and reload\n const agent = copilotkit.getAgent(resolvedAgentId);\n if (agent && !agent.isRunning && !result.suggestions.length) {\n copilotkit.reloadSuggestions(resolvedAgentId);\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [resolvedAgentId]);\n\n return result;\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,iBAA0B;AAwC5B,SAAS,4BACd,QACA,eAAsB,CAAC,GACY;AAnDrC;AAoDE,QAAM,iBAAiB,4BAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AACnD,QAAM,EAAE,WAAW,IAAI,cAAc;AAErC,QAAM,YAAY,OAAO,cAAc,YAAY,WAAW,OAAO;AAErE,QAAM,wBAAwB,iCACzB,SADyB;AAAA,IAE5B;AAAA,IACA,iBAAiB;AAAA;AAAA,EACnB;AACA,0BAAwB,uBAAuB,YAAY;AAE3D,QAAM,SAAS,eAAe,EAAE,SAAS,gBAAgB,CAAC;AAE1D,YAAU,MAAM;AACd,QAAI,sBAAsB,cAAc;AAAY;AACpD,UAAM,eAAe,WAAW,UAAU;AAAA,MACxC,iBAAiB,MAAM;AAErB,cAAM,QAAQ,WAAW,SAAS,eAAe;AACjD,YAAI,SAAS,CAAC,MAAM,aAAa,CAAC,OAAO,YAAY,QAAQ;AAC3D,qBAAW,kBAAkB,eAAe;AAAA,QAC9C;AAAA,MACF;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/hooks/use-configure-chat-suggestions.tsx"],"sourcesContent":["import {\n useConfigureSuggestions,\n useCopilotChatConfiguration,\n useCopilotKit,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { StaticSuggestionsConfig, Suggestion } from \"@copilotkitnext/core\";\nimport { useCopilotContext } from \"../context\";\nimport { useEffect, useMemo } from \"react\";\n\ntype StaticSuggestionInput = Omit<Suggestion, \"isLoading\"> &\n Partial<Pick<Suggestion, \"isLoading\">>;\n\ntype StaticSuggestionsConfigInput = Omit<\n StaticSuggestionsConfig,\n \"suggestions\"\n> & {\n suggestions: StaticSuggestionInput[];\n};\n\ntype DynamicSuggestionsConfigInput = {\n /**\n * A prompt or instructions for the GPT to generate suggestions.\n */\n instructions: string;\n /**\n * The minimum number of suggestions to generate. Defaults to `1`.\n * @default 1\n */\n minSuggestions?: number;\n /**\n * The maximum number of suggestions to generate. Defaults to `3`.\n * @default 1\n */\n maxSuggestions?: number;\n\n /**\n * Whether the suggestions are available. Defaults to `enabled`.\n * @default enabled\n */\n available?:\n | \"enabled\"\n | \"disabled\"\n | \"always\"\n | \"before-first-message\"\n | \"after-first-message\";\n\n /**\n * An optional class name to apply to the suggestions.\n */\n className?: string;\n};\n\nexport type UseCopilotChatSuggestionsConfiguration =\n | DynamicSuggestionsConfigInput\n | StaticSuggestionsConfigInput;\n\nexport function useConfigureChatSuggestions(\n config: UseCopilotChatSuggestionsConfiguration,\n dependencies: any[] = [],\n): ReturnType<typeof useSuggestions> {\n const existingConfig = useCopilotChatConfiguration();\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { copilotkit } = useCopilotKit();\n\n const available =\n config.available === \"enabled\" ? \"always\" : config.available;\n\n const finalSuggestionConfig = {\n ...config,\n available,\n consumerAgentId: resolvedAgentId, // Use chatConfig.agentId here\n };\n useConfigureSuggestions(finalSuggestionConfig, dependencies);\n\n const result = useSuggestions({ agentId: resolvedAgentId });\n\n useEffect(() => {\n if (finalSuggestionConfig.available === \"disabled\") return;\n const subscription = copilotkit.subscribe({\n onAgentsChanged: () => {\n // When agents change, check if our target agent now exists and reload\n const agent = copilotkit.getAgent(resolvedAgentId);\n if (agent && !agent.isRunning && !result.suggestions.length) {\n copilotkit.reloadSuggestions(resolvedAgentId);\n }\n },\n });\n\n return () => {\n subscription.unsubscribe();\n };\n }, [resolvedAgentId]);\n\n return result;\n}\n"],"mappings":";;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,iBAA0B;AAiD5B,SAAS,4BACd,QACA,eAAsB,CAAC,GACY;AA5DrC;AA6DE,QAAM,iBAAiB,4BAA4B;AACnD,QAAM,mBAAkB,sDAAgB,YAAhB,YAA2B;AACnD,QAAM,EAAE,WAAW,IAAI,cAAc;AAErC,QAAM,YACJ,OAAO,cAAc,YAAY,WAAW,OAAO;AAErD,QAAM,wBAAwB,iCACzB,SADyB;AAAA,IAE5B;AAAA,IACA,iBAAiB;AAAA;AAAA,EACnB;AACA,0BAAwB,uBAAuB,YAAY;AAE3D,QAAM,SAAS,eAAe,EAAE,SAAS,gBAAgB,CAAC;AAE1D,YAAU,MAAM;AACd,QAAI,sBAAsB,cAAc;AAAY;AACpD,UAAM,eAAe,WAAW,UAAU;AAAA,MACxC,iBAAiB,MAAM;AAErB,cAAM,QAAQ,WAAW,SAAS,eAAe;AACjD,YAAI,SAAS,CAAC,MAAM,aAAa,CAAC,OAAO,YAAY,QAAQ;AAC3D,qBAAW,kBAAkB,eAAe;AAAA,QAC9C;AAAA,MACF;AAAA,IACF,CAAC;AAED,WAAO,MAAM;AACX,mBAAa,YAAY;AAAA,IAC3B;AAAA,EACF,GAAG,CAAC,eAAe,CAAC;AAEpB,SAAO;AACT;","names":[]}