@copilotkit/react-core 1.57.3 → 1.58.0-canary.thread-id-propagation

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 (292) hide show
  1. package/LICENSE +21 -0
  2. package/dist/{copilotkit-CtXcs1ea.cjs → copilotkit-B4ouY7qC.cjs} +14 -3
  3. package/dist/copilotkit-B4ouY7qC.cjs.map +1 -0
  4. package/dist/copilotkit-BK9CVq9A.d.cts.map +1 -1
  5. package/dist/{copilotkit-CC8DjOiC.mjs → copilotkit-L4mM_JqG.mjs} +14 -3
  6. package/dist/copilotkit-L4mM_JqG.mjs.map +1 -0
  7. package/dist/copilotkit-WlmeVijs.d.mts.map +1 -1
  8. package/dist/index.cjs +3 -77
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +2 -2
  11. package/dist/index.d.mts +2 -2
  12. package/dist/index.mjs +3 -77
  13. package/dist/index.mjs.map +1 -1
  14. package/dist/index.umd.js +15 -78
  15. package/dist/index.umd.js.map +1 -1
  16. package/dist/v2/headless.cjs +11 -0
  17. package/dist/v2/headless.cjs.map +1 -1
  18. package/dist/v2/headless.d.cts.map +1 -1
  19. package/dist/v2/headless.d.mts.map +1 -1
  20. package/dist/v2/headless.mjs +11 -0
  21. package/dist/v2/headless.mjs.map +1 -1
  22. package/dist/v2/index.cjs +1 -1
  23. package/dist/v2/index.mjs +1 -1
  24. package/dist/v2/index.umd.js +13 -2
  25. package/dist/v2/index.umd.js.map +1 -1
  26. package/package.json +12 -13
  27. package/skills/react-core/SKILL.md +108 -0
  28. package/skills/react-core/references/agent-access.md +288 -0
  29. package/skills/react-core/references/attachments.md +291 -0
  30. package/skills/react-core/references/capabilities.md +138 -0
  31. package/skills/react-core/references/chat-components.md +221 -0
  32. package/skills/react-core/references/client-side-tools.md +358 -0
  33. package/skills/react-core/references/custom-message-renderers.md +226 -0
  34. package/skills/react-core/references/debug-mode.md +153 -0
  35. package/skills/react-core/references/human-in-the-loop.md +312 -0
  36. package/skills/react-core/references/provider-setup.md +326 -0
  37. package/skills/react-core/references/rendering-activity-messages.md +207 -0
  38. package/skills/react-core/references/rendering-tool-calls.md +319 -0
  39. package/skills/react-core/references/suggestions.md +211 -0
  40. package/skills/react-core/references/switching-agents-recipes.md +160 -0
  41. package/skills/react-core/references/switching-agents.md +231 -0
  42. package/skills/react-core/references/threads.md +226 -0
  43. package/.attw.json +0 -3
  44. package/CHANGELOG.md +0 -5043
  45. package/dist/copilotkit-CC8DjOiC.mjs.map +0 -1
  46. package/dist/copilotkit-CtXcs1ea.cjs.map +0 -1
  47. package/scripts/scope-preflight.mjs +0 -100
  48. package/src/components/CopilotListeners.tsx +0 -137
  49. package/src/components/__tests__/CopilotListeners.test.tsx +0 -38
  50. package/src/components/copilot-provider/__tests__/copilot-messages-key.test.tsx +0 -92
  51. package/src/components/copilot-provider/__tests__/copilotkit-error.test.tsx +0 -77
  52. package/src/components/copilot-provider/__tests__/error-visibility-prod.test.tsx +0 -70
  53. package/src/components/copilot-provider/__tests__/v1-explicit-threadid-bridge.test.tsx +0 -107
  54. package/src/components/copilot-provider/copilot-messages.tsx +0 -314
  55. package/src/components/copilot-provider/copilotkit-props.tsx +0 -214
  56. package/src/components/copilot-provider/copilotkit.tsx +0 -853
  57. package/src/components/copilot-provider/index.ts +0 -3
  58. package/src/components/dev-console/console-trigger.tsx +0 -283
  59. package/src/components/dev-console/developer-console-modal.tsx +0 -1016
  60. package/src/components/dev-console/icons.tsx +0 -106
  61. package/src/components/error-boundary/error-boundary.tsx +0 -99
  62. package/src/components/error-boundary/error-utils.tsx +0 -105
  63. package/src/components/index.ts +0 -1
  64. package/src/components/toast/exclamation-mark-icon.tsx +0 -27
  65. package/src/components/toast/toast-provider.tsx +0 -448
  66. package/src/components/usage-banner.tsx +0 -266
  67. package/src/context/__tests__/threads-context.test.tsx +0 -141
  68. package/src/context/coagent-state-renders-context.tsx +0 -89
  69. package/src/context/copilot-context.tsx +0 -365
  70. package/src/context/copilot-messages-context.tsx +0 -35
  71. package/src/context/index.ts +0 -22
  72. package/src/context/threads-context.tsx +0 -69
  73. package/src/hooks/__tests__/use-coagent-config.test.ts +0 -352
  74. package/src/hooks/__tests__/use-coagent-state-render-bridge.helpers.test.ts +0 -107
  75. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +0 -1209
  76. package/src/hooks/__tests__/use-coagent-state-render.test.tsx +0 -356
  77. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +0 -241
  78. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +0 -72
  79. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +0 -102
  80. package/src/hooks/index.ts +0 -33
  81. package/src/hooks/use-agent-nodename.ts +0 -33
  82. package/src/hooks/use-coagent-state-render-bridge.helpers.ts +0 -345
  83. package/src/hooks/use-coagent-state-render-bridge.tsx +0 -222
  84. package/src/hooks/use-coagent-state-render-registry.ts +0 -230
  85. package/src/hooks/use-coagent-state-render.ts +0 -163
  86. package/src/hooks/use-coagent.ts +0 -377
  87. package/src/hooks/use-configure-chat-suggestions.tsx +0 -96
  88. package/src/hooks/use-copilot-action.ts +0 -245
  89. package/src/hooks/use-copilot-additional-instructions.ts +0 -98
  90. package/src/hooks/use-copilot-authenticated-action.ts +0 -73
  91. package/src/hooks/use-copilot-chat-headless_c.ts +0 -264
  92. package/src/hooks/use-copilot-chat-suggestions.tsx +0 -134
  93. package/src/hooks/use-copilot-chat.ts +0 -132
  94. package/src/hooks/use-copilot-chat_internal.ts +0 -875
  95. package/src/hooks/use-copilot-readable.ts +0 -135
  96. package/src/hooks/use-copilot-runtime-client.ts +0 -178
  97. package/src/hooks/use-default-tool.ts +0 -13
  98. package/src/hooks/use-flat-category-store.ts +0 -109
  99. package/src/hooks/use-frontend-tool.ts +0 -113
  100. package/src/hooks/use-human-in-the-loop.ts +0 -138
  101. package/src/hooks/use-langgraph-interrupt.ts +0 -103
  102. package/src/hooks/use-lazy-tool-renderer.tsx +0 -30
  103. package/src/hooks/use-make-copilot-document-readable.ts +0 -30
  104. package/src/hooks/use-render-tool-call.ts +0 -89
  105. package/src/hooks/use-tree.ts +0 -222
  106. package/src/index.tsx +0 -7
  107. package/src/lib/copilot-task.ts +0 -215
  108. package/src/lib/index.ts +0 -1
  109. package/src/lib/status-checker.ts +0 -67
  110. package/src/setupTests.ts +0 -37
  111. package/src/test-helpers/copilot-context.ts +0 -91
  112. package/src/types/chat-suggestion-configuration.ts +0 -23
  113. package/src/types/coagent-action.ts +0 -35
  114. package/src/types/coagent-state.ts +0 -13
  115. package/src/types/crew.ts +0 -89
  116. package/src/types/document-pointer.ts +0 -7
  117. package/src/types/frontend-action.ts +0 -213
  118. package/src/types/index.ts +0 -17
  119. package/src/types/interrupt-action.ts +0 -58
  120. package/src/types/system-message.ts +0 -4
  121. package/src/utils/dev-console.ts +0 -19
  122. package/src/utils/index.ts +0 -2
  123. package/src/utils/suggestions-constants.ts +0 -8
  124. package/src/utils/utils.test.ts +0 -7
  125. package/src/utils/utils.ts +0 -6
  126. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +0 -240
  127. package/src/v2/__tests__/globalSetup.ts +0 -14
  128. package/src/v2/__tests__/setup.ts +0 -93
  129. package/src/v2/__tests__/utils/test-helpers.tsx +0 -570
  130. package/src/v2/a2ui/A2UICatalogContext.tsx +0 -79
  131. package/src/v2/a2ui/A2UIMessageRenderer.tsx +0 -294
  132. package/src/v2/a2ui/A2UIToolCallRenderer.tsx +0 -290
  133. package/src/v2/components/CopilotKitInspector.tsx +0 -52
  134. package/src/v2/components/MCPAppsActivityRenderer.tsx +0 -815
  135. package/src/v2/components/OpenGenerativeUIRenderer.tsx +0 -598
  136. package/src/v2/components/WildcardToolCallRender.tsx +0 -86
  137. package/src/v2/components/__tests__/OpenGenerativeUIRenderer.test.tsx +0 -665
  138. package/src/v2/components/chat/CopilotChat.tsx +0 -664
  139. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +0 -393
  140. package/src/v2/components/chat/CopilotChatAttachmentQueue.tsx +0 -374
  141. package/src/v2/components/chat/CopilotChatAttachmentRenderer.tsx +0 -159
  142. package/src/v2/components/chat/CopilotChatAudioRecorder.tsx +0 -350
  143. package/src/v2/components/chat/CopilotChatInput.tsx +0 -1412
  144. package/src/v2/components/chat/CopilotChatMessageView.tsx +0 -716
  145. package/src/v2/components/chat/CopilotChatReasoningMessage.tsx +0 -265
  146. package/src/v2/components/chat/CopilotChatSuggestionPill.tsx +0 -59
  147. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +0 -134
  148. package/src/v2/components/chat/CopilotChatToggleButton.tsx +0 -171
  149. package/src/v2/components/chat/CopilotChatToolCallsView.tsx +0 -40
  150. package/src/v2/components/chat/CopilotChatUserMessage.tsx +0 -445
  151. package/src/v2/components/chat/CopilotChatView.tsx +0 -890
  152. package/src/v2/components/chat/CopilotModalHeader.tsx +0 -129
  153. package/src/v2/components/chat/CopilotPopup.tsx +0 -81
  154. package/src/v2/components/chat/CopilotPopupView.tsx +0 -317
  155. package/src/v2/components/chat/CopilotSidebar.tsx +0 -80
  156. package/src/v2/components/chat/CopilotSidebarView.tsx +0 -269
  157. package/src/v2/components/chat/Lightbox.tsx +0 -103
  158. package/src/v2/components/chat/__tests__/CopilotChat.absentThreadConnect.test.tsx +0 -66
  159. package/src/v2/components/chat/__tests__/CopilotChat.attachments.test.tsx +0 -168
  160. package/src/v2/components/chat/__tests__/CopilotChat.e2e.test.tsx +0 -1239
  161. package/src/v2/components/chat/__tests__/CopilotChat.onError.test.tsx +0 -73
  162. package/src/v2/components/chat/__tests__/CopilotChat.slots.e2e.test.tsx +0 -432
  163. package/src/v2/components/chat/__tests__/CopilotChat.suggestionsAlways.test.tsx +0 -183
  164. package/src/v2/components/chat/__tests__/CopilotChat.welcomeGate.test.tsx +0 -184
  165. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +0 -649
  166. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.slots.e2e.test.tsx +0 -624
  167. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.test.tsx +0 -702
  168. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.thumbs.test.tsx +0 -72
  169. package/src/v2/components/chat/__tests__/CopilotChatCopyButton.clipboard.test.tsx +0 -241
  170. package/src/v2/components/chat/__tests__/CopilotChatCssClasses.test.tsx +0 -107
  171. package/src/v2/components/chat/__tests__/CopilotChatInput.slots.e2e.test.tsx +0 -929
  172. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +0 -1567
  173. package/src/v2/components/chat/__tests__/CopilotChatMessageView.slots.e2e.test.tsx +0 -1004
  174. package/src/v2/components/chat/__tests__/CopilotChatMessageView.test.tsx +0 -279
  175. package/src/v2/components/chat/__tests__/CopilotChatPerf.e2e.test.tsx +0 -336
  176. package/src/v2/components/chat/__tests__/CopilotChatPropsRerender.e2e.test.tsx +0 -249
  177. package/src/v2/components/chat/__tests__/CopilotChatSuggestionView.slots.e2e.test.tsx +0 -530
  178. package/src/v2/components/chat/__tests__/CopilotChatToolRendering.e2e.test.tsx +0 -785
  179. package/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx +0 -2416
  180. package/src/v2/components/chat/__tests__/CopilotChatUserMessage.slots.e2e.test.tsx +0 -621
  181. package/src/v2/components/chat/__tests__/CopilotChatView.connectingGate.test.tsx +0 -56
  182. package/src/v2/components/chat/__tests__/CopilotChatView.inputOverlay.test.tsx +0 -264
  183. package/src/v2/components/chat/__tests__/CopilotChatView.onClick.e2e.test.tsx +0 -853
  184. package/src/v2/components/chat/__tests__/CopilotChatView.pinToSend.test.tsx +0 -94
  185. package/src/v2/components/chat/__tests__/CopilotChatView.slots.e2e.test.tsx +0 -1050
  186. package/src/v2/components/chat/__tests__/CopilotModalHeader.slots.e2e.test.tsx +0 -484
  187. package/src/v2/components/chat/__tests__/CopilotPopupView.slots.e2e.test.tsx +0 -612
  188. package/src/v2/components/chat/__tests__/CopilotSidebarView.position.test.tsx +0 -159
  189. package/src/v2/components/chat/__tests__/CopilotSidebarView.slots.e2e.test.tsx +0 -502
  190. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +0 -1068
  191. package/src/v2/components/chat/__tests__/MCPAppsProxy.e2e.test.tsx +0 -589
  192. package/src/v2/components/chat/__tests__/MCPAppsUiMessage.e2e.test.tsx +0 -403
  193. package/src/v2/components/chat/__tests__/copilot-chat-throttle.test.tsx +0 -137
  194. package/src/v2/components/chat/__tests__/normalize-auto-scroll.test.ts +0 -37
  195. package/src/v2/components/chat/__tests__/setup.ts +0 -1
  196. package/src/v2/components/chat/index.ts +0 -90
  197. package/src/v2/components/chat/last-user-message-context.ts +0 -21
  198. package/src/v2/components/chat/normalize-auto-scroll.ts +0 -17
  199. package/src/v2/components/chat/scroll-element-context.ts +0 -13
  200. package/src/v2/components/index.ts +0 -8
  201. package/src/v2/components/intelligence-indicator/IntelligenceIndicator.tsx +0 -286
  202. package/src/v2/components/intelligence-indicator/__tests__/IntelligenceIndicator.e2e.test.tsx +0 -464
  203. package/src/v2/components/intelligence-indicator/index.ts +0 -2
  204. package/src/v2/components/license-warning-banner.tsx +0 -217
  205. package/src/v2/components/ui/button.tsx +0 -124
  206. package/src/v2/components/ui/dropdown-menu.tsx +0 -258
  207. package/src/v2/components/ui/tooltip.tsx +0 -60
  208. package/src/v2/context.ts +0 -62
  209. package/src/v2/headless.ts +0 -64
  210. package/src/v2/hooks/__tests__/standard-schema-types.test.tsx +0 -152
  211. package/src/v2/hooks/__tests__/standard-schema.test.tsx +0 -282
  212. package/src/v2/hooks/__tests__/use-agent-context-timing.e2e.test.tsx +0 -140
  213. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +0 -401
  214. package/src/v2/hooks/__tests__/use-agent-error-state.test.tsx +0 -44
  215. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +0 -211
  216. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +0 -1029
  217. package/src/v2/hooks/__tests__/use-agent.e2e.test.tsx +0 -159
  218. package/src/v2/hooks/__tests__/use-attachments.test.tsx +0 -169
  219. package/src/v2/hooks/__tests__/use-capabilities.test.tsx +0 -76
  220. package/src/v2/hooks/__tests__/use-component.test.tsx +0 -126
  221. package/src/v2/hooks/__tests__/use-configure-suggestions.e2e.test.tsx +0 -696
  222. package/src/v2/hooks/__tests__/use-default-render-tool.test.tsx +0 -153
  223. package/src/v2/hooks/__tests__/use-frontend-tool-available.test.tsx +0 -167
  224. package/src/v2/hooks/__tests__/use-frontend-tool.e2e.test.tsx +0 -2148
  225. package/src/v2/hooks/__tests__/use-human-in-the-loop.e2e.test.tsx +0 -1261
  226. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +0 -397
  227. package/src/v2/hooks/__tests__/use-katex-styles.test.tsx +0 -56
  228. package/src/v2/hooks/__tests__/use-keyboard-height.test.tsx +0 -192
  229. package/src/v2/hooks/__tests__/use-pin-to-send.test.tsx +0 -219
  230. package/src/v2/hooks/__tests__/use-render-custom-messages.test.tsx +0 -55
  231. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +0 -259
  232. package/src/v2/hooks/__tests__/use-suggestions.e2e.test.tsx +0 -524
  233. package/src/v2/hooks/__tests__/use-threads.test.tsx +0 -757
  234. package/src/v2/hooks/__tests__/zod-regression.test.tsx +0 -311
  235. package/src/v2/hooks/index.ts +0 -24
  236. package/src/v2/hooks/use-agent-context.tsx +0 -45
  237. package/src/v2/hooks/use-agent.tsx +0 -227
  238. package/src/v2/hooks/use-attachments.tsx +0 -269
  239. package/src/v2/hooks/use-capabilities.tsx +0 -25
  240. package/src/v2/hooks/use-component.tsx +0 -91
  241. package/src/v2/hooks/use-configure-suggestions.tsx +0 -236
  242. package/src/v2/hooks/use-default-render-tool.tsx +0 -271
  243. package/src/v2/hooks/use-frontend-tool.tsx +0 -46
  244. package/src/v2/hooks/use-human-in-the-loop.tsx +0 -81
  245. package/src/v2/hooks/use-interrupt.tsx +0 -305
  246. package/src/v2/hooks/use-keyboard-height.tsx +0 -67
  247. package/src/v2/hooks/use-pin-to-send.ts +0 -94
  248. package/src/v2/hooks/use-render-activity-message.tsx +0 -72
  249. package/src/v2/hooks/use-render-custom-messages.tsx +0 -93
  250. package/src/v2/hooks/use-render-tool-call.tsx +0 -208
  251. package/src/v2/hooks/use-render-tool.tsx +0 -184
  252. package/src/v2/hooks/use-suggestions.tsx +0 -91
  253. package/src/v2/hooks/use-threads.tsx +0 -325
  254. package/src/v2/hooks/useKatexStyles.ts +0 -27
  255. package/src/v2/index.css +0 -1
  256. package/src/v2/index.ts +0 -27
  257. package/src/v2/lib/__tests__/completePartialMarkdown.test.ts +0 -495
  258. package/src/v2/lib/__tests__/processPartialHtml.test.ts +0 -112
  259. package/src/v2/lib/__tests__/renderSlot.test.tsx +0 -588
  260. package/src/v2/lib/__tests__/slots.test.ts +0 -56
  261. package/src/v2/lib/processPartialHtml.ts +0 -45
  262. package/src/v2/lib/react-core.ts +0 -156
  263. package/src/v2/lib/slots.tsx +0 -184
  264. package/src/v2/lib/transcription-client.ts +0 -184
  265. package/src/v2/lib/utils.ts +0 -8
  266. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +0 -196
  267. package/src/v2/providers/CopilotKitProvider.tsx +0 -800
  268. package/src/v2/providers/SandboxFunctionsContext.ts +0 -10
  269. package/src/v2/providers/__tests__/CopilotChatConfigurationProvider.test.tsx +0 -652
  270. package/src/v2/providers/__tests__/CopilotKitProvider.license.test.tsx +0 -101
  271. package/src/v2/providers/__tests__/CopilotKitProvider.onError.test.tsx +0 -69
  272. package/src/v2/providers/__tests__/CopilotKitProvider.renderCustomMessages.e2e.test.tsx +0 -881
  273. package/src/v2/providers/__tests__/CopilotKitProvider.sandboxFunctions.test.tsx +0 -198
  274. package/src/v2/providers/__tests__/CopilotKitProvider.stability.test.tsx +0 -740
  275. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +0 -713
  276. package/src/v2/providers/__tests__/CopilotKitProvider.wildcard.test.tsx +0 -294
  277. package/src/v2/providers/index.ts +0 -21
  278. package/src/v2/styles/globals.css +0 -349
  279. package/src/v2/types/__tests__/defineToolCallRenderer.test.tsx +0 -525
  280. package/src/v2/types/defineToolCallRenderer.ts +0 -68
  281. package/src/v2/types/frontend-tool.ts +0 -8
  282. package/src/v2/types/human-in-the-loop.ts +0 -33
  283. package/src/v2/types/index.ts +0 -8
  284. package/src/v2/types/interrupt.ts +0 -15
  285. package/src/v2/types/react-activity-message-renderer.ts +0 -27
  286. package/src/v2/types/react-custom-message-renderer.ts +0 -17
  287. package/src/v2/types/react-tool-call-renderer.ts +0 -35
  288. package/src/v2/types/sandbox-function.ts +0 -11
  289. package/tsconfig.json +0 -8
  290. package/tsdown.config.ts +0 -193
  291. package/typedoc.json +0 -4
  292. package/vitest.config.mjs +0 -31
@@ -1,800 +0,0 @@
1
- "use client";
2
-
3
- import type { AbstractAgent } from "@ag-ui/client";
4
- import type { FrontendTool } from "@copilotkit/core";
5
- import type React from "react";
6
- import {
7
- type ReactNode,
8
- useMemo,
9
- useEffect,
10
- useLayoutEffect,
11
- useReducer,
12
- useRef,
13
- useState,
14
- } from "react";
15
- // Context extracted to ../context.ts for cross-platform reuse (React Native)
16
- import {
17
- CopilotKitContext,
18
- type CopilotKitContextValue,
19
- LicenseContext,
20
- } from "../context";
21
- export type { CopilotKitContextValue } from "../context";
22
- export { CopilotKitContext, useLicenseContext } from "../context";
23
- import { z } from "zod";
24
- import { CopilotKitInspector } from "../components/CopilotKitInspector";
25
- import type { Anchor } from "@copilotkit/web-inspector";
26
- import { LicenseWarningBanner } from "../components/license-warning-banner";
27
- import {
28
- createLicenseContextValue,
29
- type LicenseContextValue,
30
- type DebugConfig,
31
- } from "@copilotkit/shared";
32
- import type { CopilotKitCoreErrorCode } from "@copilotkit/core";
33
- import {
34
- MCPAppsActivityContentSchema,
35
- MCPAppsActivityRenderer,
36
- MCPAppsActivityType,
37
- } from "../components/MCPAppsActivityRenderer";
38
- import {
39
- OpenGenerativeUIActivityType,
40
- OpenGenerativeUIContentSchema,
41
- OpenGenerativeUIActivityRenderer,
42
- OpenGenerativeUIToolRenderer,
43
- GenerateSandboxedUiArgsSchema,
44
- } from "../components/OpenGenerativeUIRenderer";
45
- import { createA2UIMessageRenderer } from "../a2ui/A2UIMessageRenderer";
46
- import { A2UIBuiltInToolCallRenderer } from "../a2ui/A2UIToolCallRenderer";
47
- import { A2UICatalogContext } from "../a2ui/A2UICatalogContext";
48
- import { viewerTheme } from "@copilotkit/a2ui-renderer";
49
- import type { Theme as A2UITheme } from "@copilotkit/a2ui-renderer";
50
- import { CopilotKitCoreReact } from "../lib/react-core";
51
- import type {
52
- ReactActivityMessageRenderer,
53
- ReactToolCallRenderer,
54
- } from "../types";
55
- import type { ReactFrontendTool } from "../types/frontend-tool";
56
- import type { ReactHumanInTheLoop } from "../types/human-in-the-loop";
57
- import type { ReactCustomMessageRenderer } from "../types/react-custom-message-renderer";
58
- import type { SandboxFunction } from "../types/sandbox-function";
59
- import { SandboxFunctionsContext } from "./SandboxFunctionsContext";
60
- import { schemaToJsonSchema } from "@copilotkit/shared";
61
- import { zodToJsonSchema } from "zod-to-json-schema";
62
-
63
- const HEADER_NAME = "X-CopilotCloud-Public-Api-Key";
64
- const COPILOT_CLOUD_CHAT_URL = "https://api.cloud.copilotkit.ai/copilotkit/v1";
65
-
66
- const DEFAULT_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follow these design principles inspired by shadcn/ui:
67
-
68
- - Use a minimal, flat aesthetic. Avoid drop shadows and gradients — rely on subtle borders (1px solid, light gray like #e5e7eb) to define surfaces.
69
- - Neutral base palette: white backgrounds, zinc/slate gray text (#09090b for headings, #71717a for secondary text). One accent color for interactive elements.
70
- - Use system font stacks (system-ui, -apple-system, sans-serif) at readable sizes (14px body, 600 weight for headings). Tight line-heights.
71
- - Small, consistent border-radius (6–8px). Cards and containers use border, not shadow, for separation.
72
- - Buttons: solid fill for primary (dark bg, white text), outline for secondary (border + transparent bg). Subtle hover state (slight opacity or background shift).
73
- - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
74
- - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
75
- - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
76
-
77
- const GENERATE_SANDBOXED_UI_DESCRIPTION =
78
- "Generate sandboxed UI. " +
79
- "IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. " +
80
- "Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. " +
81
- "To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\n\n" +
82
- "You CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). " +
83
- "CDN resources load normally inside the sandbox.\n\n" +
84
- "PARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\n" +
85
- "1. initialHeight + placeholderMessages (shown to user while generating)\n" +
86
- "2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\n" +
87
- "3. html (streams in live — the user watches the UI build as HTML is generated)\n" +
88
- "4. jsFunctions (reusable helper functions)\n" +
89
- "5. jsExpressions (applied one-by-one — the user sees each expression take effect)";
90
- // Provider props interface
91
- export interface CopilotKitProviderProps {
92
- children: ReactNode;
93
- runtimeUrl?: string;
94
- headers?: Record<string, string> | (() => Record<string, string>);
95
- /**
96
- * Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies in cross-origin requests).
97
- */
98
- credentials?: RequestCredentials;
99
- /**
100
- * The Copilot Cloud public API key.
101
- */
102
- publicApiKey?: string;
103
- /**
104
- * Alias for `publicApiKey`
105
- **/
106
- publicLicenseKey?: string;
107
- /**
108
- * Signed license token for offline verification of premium features.
109
- * Obtain from https://cloud.copilotkit.ai.
110
- */
111
- licenseToken?: string;
112
- properties?: Record<string, unknown>;
113
- useSingleEndpoint?: boolean;
114
- agents__unsafe_dev_only?: Record<string, AbstractAgent>;
115
- selfManagedAgents?: Record<string, AbstractAgent>;
116
- renderToolCalls?: ReactToolCallRenderer<any>[];
117
- renderActivityMessages?: ReactActivityMessageRenderer<any>[];
118
- renderCustomMessages?: ReactCustomMessageRenderer[];
119
- frontendTools?: ReactFrontendTool[];
120
- humanInTheLoop?: ReactHumanInTheLoop[];
121
- /**
122
- * Configuration for OpenGenerativeUI — sandboxed UI generated by the LLM.
123
- *
124
- * @example
125
- * ```tsx
126
- * <CopilotKit
127
- * runtimeUrl="/api/copilotkit"
128
- * openGenerativeUI={{
129
- * sandboxFunctions: [{ name: "addToCart", description: "…", parameters: schema, handler: fn }],
130
- * }}
131
- * >
132
- * ```
133
- */
134
- openGenerativeUI?: {
135
- /**
136
- * Functions made available inside sandboxed iframes.
137
- * Each function is described to the LLM via agent context and exposed
138
- * via websandbox's `localApi`.
139
- *
140
- * Inside the iframe, call them with:
141
- * ```js
142
- * await Websandbox.connection.remote.<functionName>(args)
143
- * ```
144
- */
145
- sandboxFunctions?: SandboxFunction[];
146
- /**
147
- * Design guidelines injected as agent context for the `generateSandboxedUi` tool.
148
- * Override this to control the visual style of generated UIs.
149
- *
150
- * A sensible default is provided if omitted.
151
- */
152
- designSkill?: string;
153
- };
154
- showDevConsole?: boolean | "auto";
155
- /**
156
- * Error handler called when CopilotKit encounters an error.
157
- * Fires for all error types (runtime connection failures, agent errors, tool errors).
158
- */
159
- onError?: (event: {
160
- error: Error;
161
- code: CopilotKitCoreErrorCode;
162
- context: Record<string, any>;
163
- }) => void | Promise<void>;
164
- /**
165
- * Configuration for the A2UI (Agent-to-UI) renderer.
166
- * The built-in A2UI renderer is activated automatically when the runtime reports
167
- * that `a2ui` is configured in `CopilotRuntime`. This prop is optional and only
168
- * needed if you want to override the default theme.
169
- *
170
- * @example
171
- * ```tsx
172
- * <CopilotKit runtimeUrl="/api/copilotkit" a2ui={{ theme: myCustomTheme }}>
173
- * {children}
174
- * </CopilotKit>
175
- * ```
176
- */
177
- a2ui?: {
178
- /**
179
- * Override the default A2UI viewer theme.
180
- * When omitted, the built-in `viewerTheme` from `@copilotkit/a2ui-renderer` is used.
181
- */
182
- theme?: A2UITheme;
183
- /**
184
- * Optional component catalog to pass to the A2UI renderer.
185
- * When omitted, the default basicCatalog is used.
186
- */
187
- catalog?: any;
188
- /**
189
- * Optional custom loading component shown while an A2UI surface is generating.
190
- * When omitted, a default animated skeleton is shown.
191
- */
192
- loadingComponent?: React.ComponentType;
193
- /**
194
- * When true (the default), the full component schemas from the catalog are
195
- * sent as agent context so the agent knows what components and props are
196
- * available. The A2UI middleware can overwrite this with a server-side
197
- * schema if configured. Set to false to disable.
198
- */
199
- includeSchema?: boolean;
200
- };
201
- /**
202
- * Default throttle interval (in milliseconds) for `useAgent` re-renders
203
- * triggered by `OnMessagesChanged` notifications. This value is used as
204
- * a fallback when neither the `useAgent()` hook nor `<CopilotChat>` /
205
- * `<CopilotSidebar>` / `<CopilotPopup>` specify an explicit `throttleMs`.
206
- *
207
- * @default undefined (components/hooks without an explicit throttleMs will be unthrottled)
208
- */
209
- defaultThrottleMs?: number;
210
- /**
211
- * Default anchor corner for the inspector button and window.
212
- * Only used on first load before the user drags to a custom position.
213
- * Defaults to `{ horizontal: "right", vertical: "top" }`.
214
- */
215
- inspectorDefaultAnchor?: Anchor;
216
- /**
217
- * Enable debug logging for the client-side event pipeline.
218
- */
219
- debug?: DebugConfig;
220
- }
221
-
222
- // Small helper to normalize array props to a stable reference and warn
223
- function useStableArrayProp<T>(
224
- prop: T[] | undefined,
225
- warningMessage?: string,
226
- isMeaningfulChange?: (initial: T[], next: T[]) => boolean,
227
- ): T[] {
228
- const empty = useMemo<T[]>(() => [], []);
229
- const value = prop ?? empty;
230
- const initial = useRef(value);
231
-
232
- useEffect(() => {
233
- if (
234
- warningMessage &&
235
- value !== initial.current &&
236
- (isMeaningfulChange ? isMeaningfulChange(initial.current, value) : true)
237
- ) {
238
- console.error(warningMessage);
239
- }
240
- }, [value, warningMessage]);
241
-
242
- return value;
243
- }
244
-
245
- // Provider component
246
- export const CopilotKitProvider: React.FC<CopilotKitProviderProps> = ({
247
- children,
248
- runtimeUrl,
249
- headers: headersProp = {},
250
- credentials,
251
- publicApiKey,
252
- publicLicenseKey,
253
- licenseToken,
254
- properties = {},
255
- agents__unsafe_dev_only: agents = {},
256
- selfManagedAgents = {},
257
- renderToolCalls,
258
- renderActivityMessages,
259
- renderCustomMessages,
260
- frontendTools,
261
- humanInTheLoop,
262
- openGenerativeUI,
263
- showDevConsole = false,
264
- useSingleEndpoint,
265
- onError,
266
- a2ui,
267
- defaultThrottleMs,
268
- inspectorDefaultAnchor,
269
- debug,
270
- }) => {
271
- const [shouldRenderInspector, setShouldRenderInspector] = useState(false);
272
- const [runtimeA2UIEnabled, setRuntimeA2UIEnabled] = useState(false);
273
- const [runtimeOpenGenUIEnabled, setRuntimeOpenGenUIEnabled] = useState(false);
274
- const openGenUIActive = runtimeOpenGenUIEnabled || !!openGenerativeUI;
275
- const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<
276
- string | undefined
277
- >(undefined);
278
-
279
- useEffect(() => {
280
- if (typeof window === "undefined") {
281
- return;
282
- }
283
-
284
- if (showDevConsole === true) {
285
- // Explicitly show the inspector
286
- setShouldRenderInspector(true);
287
- } else if (showDevConsole === "auto") {
288
- // Show on localhost or 127.0.0.1 only
289
- const localhostHosts = new Set(["localhost", "127.0.0.1"]);
290
- if (localhostHosts.has(window.location.hostname)) {
291
- setShouldRenderInspector(true);
292
- } else {
293
- setShouldRenderInspector(false);
294
- }
295
- } else {
296
- // showDevConsole is false or undefined (default false)
297
- setShouldRenderInspector(false);
298
- }
299
- }, [showDevConsole]);
300
-
301
- // Normalize array props to stable references with clear dev warnings
302
- const renderToolCallsList = useStableArrayProp<ReactToolCallRenderer<any>>(
303
- renderToolCalls,
304
- "renderToolCalls must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.",
305
- (initial, next) => {
306
- // Only warn if the shape (names+agentId) changed. Allow identity changes
307
- // to support updated closures from parents (e.g., Storybook state).
308
- const key = (rc?: ReactToolCallRenderer<unknown>) =>
309
- `${rc?.agentId ?? ""}:${rc?.name ?? ""}`;
310
- const setFrom = (arr: ReactToolCallRenderer<unknown>[]) =>
311
- new Set(arr.map(key));
312
- const a = setFrom(initial);
313
- const b = setFrom(next);
314
- if (a.size !== b.size) return true;
315
- for (const k of a) if (!b.has(k)) return true;
316
- return false;
317
- },
318
- );
319
-
320
- const renderCustomMessagesList =
321
- useStableArrayProp<ReactCustomMessageRenderer>(
322
- renderCustomMessages,
323
- "renderCustomMessages must be a stable array.",
324
- );
325
-
326
- const renderActivityMessagesList = useStableArrayProp<
327
- ReactActivityMessageRenderer<any>
328
- >(renderActivityMessages, "renderActivityMessages must be a stable array.");
329
-
330
- // Built-in activity renderers that are always included
331
- const builtInActivityRenderers = useMemo<
332
- ReactActivityMessageRenderer<any>[]
333
- >(() => {
334
- const renderers: ReactActivityMessageRenderer<any>[] = [
335
- {
336
- activityType: MCPAppsActivityType,
337
- content: MCPAppsActivityContentSchema,
338
- render: MCPAppsActivityRenderer,
339
- },
340
- ];
341
-
342
- if (openGenUIActive) {
343
- renderers.push({
344
- activityType: OpenGenerativeUIActivityType,
345
- content: OpenGenerativeUIContentSchema,
346
- render: OpenGenerativeUIActivityRenderer,
347
- });
348
- }
349
-
350
- if (runtimeA2UIEnabled) {
351
- renderers.unshift(
352
- createA2UIMessageRenderer({
353
- theme: a2ui?.theme ?? viewerTheme,
354
- catalog: a2ui?.catalog,
355
- loadingComponent: a2ui?.loadingComponent,
356
- }),
357
- );
358
- }
359
-
360
- return renderers;
361
- }, [runtimeA2UIEnabled, openGenUIActive, a2ui]);
362
-
363
- // Combine user-provided activity renderers with built-in ones
364
- // User-provided renderers take precedence (come first) so they can override built-ins
365
- const allActivityRenderers = useMemo(() => {
366
- return [...renderActivityMessagesList, ...builtInActivityRenderers];
367
- }, [renderActivityMessagesList, builtInActivityRenderers]);
368
-
369
- const resolvedPublicKey = publicApiKey ?? publicLicenseKey;
370
- const mergedAgents = useMemo(
371
- () => ({ ...agents, ...selfManagedAgents }),
372
- [agents, selfManagedAgents],
373
- );
374
- const hasLocalAgents = mergedAgents && Object.keys(mergedAgents).length > 0;
375
-
376
- // Resolve headers from function or static object
377
- const headers =
378
- typeof headersProp === "function" ? headersProp() : headersProp;
379
-
380
- // Merge a provided publicApiKey into headers (without overwriting an explicit header).
381
- const mergedHeaders = useMemo(() => {
382
- if (!resolvedPublicKey) return headers;
383
- if (headers[HEADER_NAME]) return headers;
384
- return {
385
- ...headers,
386
- [HEADER_NAME]: resolvedPublicKey,
387
- };
388
- }, [headers, resolvedPublicKey]);
389
-
390
- if (!runtimeUrl && !resolvedPublicKey && !hasLocalAgents) {
391
- const message =
392
- "Missing required prop: 'runtimeUrl' or 'publicApiKey' or 'publicLicenseKey'";
393
- if (process.env.NODE_ENV === "production") {
394
- throw new Error(message);
395
- } else {
396
- // In dev/test we warn but allow to facilitate local agents and unit tests.
397
- console.warn(message);
398
- }
399
- }
400
-
401
- const chatApiEndpoint =
402
- runtimeUrl ?? (resolvedPublicKey ? COPILOT_CLOUD_CHAT_URL : undefined);
403
-
404
- const frontendToolsList = useStableArrayProp<ReactFrontendTool>(
405
- frontendTools,
406
- "frontendTools must be a stable array. If you want to dynamically add or remove tools, use `useFrontendTool` instead.",
407
- );
408
- const humanInTheLoopList = useStableArrayProp<ReactHumanInTheLoop>(
409
- humanInTheLoop,
410
- "humanInTheLoop must be a stable array. If you want to dynamically add or remove human-in-the-loop tools, use `useHumanInTheLoop` instead.",
411
- );
412
- const sandboxFunctionsList = useStableArrayProp<SandboxFunction>(
413
- openGenerativeUI?.sandboxFunctions,
414
- "openGenerativeUI.sandboxFunctions must be a stable array.",
415
- );
416
-
417
- // Note: warnings for array identity changes are handled by useStableArrayProp
418
-
419
- // Process humanInTheLoop tools to create handlers and add render components
420
- const processedHumanInTheLoopTools = useMemo(() => {
421
- const processedTools: FrontendTool[] = [];
422
- const processedRenderToolCalls: ReactToolCallRenderer<unknown>[] = [];
423
-
424
- humanInTheLoopList.forEach((tool) => {
425
- // Create a promise-based handler for each human-in-the-loop tool
426
- const frontendTool: FrontendTool = {
427
- name: tool.name,
428
- description: tool.description,
429
- parameters: tool.parameters,
430
- followUp: tool.followUp,
431
- ...(tool.agentId && { agentId: tool.agentId }),
432
- handler: async () => {
433
- // This handler will be replaced by the hook when it runs
434
- // For provider-level tools, we create a basic handler that waits for user interaction
435
- return new Promise((resolve) => {
436
- // The actual implementation will be handled by the render component
437
- // This is a placeholder that the hook will override
438
- console.warn(
439
- `Human-in-the-loop tool '${tool.name}' called but no interactive handler is set up.`,
440
- );
441
- resolve(undefined);
442
- });
443
- },
444
- };
445
- processedTools.push(frontendTool);
446
-
447
- // Add the render component to renderToolCalls
448
- if (tool.render) {
449
- processedRenderToolCalls.push({
450
- name: tool.name,
451
- args: tool.parameters!,
452
- render: tool.render,
453
- ...(tool.agentId && { agentId: tool.agentId }),
454
- } as ReactToolCallRenderer<unknown>);
455
- }
456
- });
457
-
458
- return { tools: processedTools, renderToolCalls: processedRenderToolCalls };
459
- }, [humanInTheLoopList]);
460
-
461
- // Built-in frontend tool for generateSandboxedUi — registered only when the runtime has openGenerativeUI enabled
462
- const builtInFrontendTools = useMemo<ReactFrontendTool[]>(() => {
463
- if (!openGenUIActive) return [];
464
- return [
465
- {
466
- name: "generateSandboxedUi",
467
- description: GENERATE_SANDBOXED_UI_DESCRIPTION,
468
- parameters: GenerateSandboxedUiArgsSchema,
469
- handler: async () => "UI generated",
470
- followUp: true,
471
- render: OpenGenerativeUIToolRenderer,
472
- },
473
- ];
474
- }, [openGenUIActive]);
475
-
476
- // Combine all tools for CopilotKitCore
477
- const allTools = useMemo(() => {
478
- const tools: FrontendTool[] = [];
479
-
480
- // Add frontend tools (user-provided + built-in)
481
- tools.push(...frontendToolsList);
482
- tools.push(...builtInFrontendTools);
483
-
484
- // Add processed human-in-the-loop tools
485
- tools.push(...processedHumanInTheLoopTools.tools);
486
-
487
- return tools;
488
- }, [frontendToolsList, builtInFrontendTools, processedHumanInTheLoopTools]);
489
-
490
- // Combine all render tool calls
491
- const allRenderToolCalls = useMemo(() => {
492
- const combined: ReactToolCallRenderer<unknown>[] = [...renderToolCallsList];
493
-
494
- // Add render components from frontend tools (user-provided + built-in)
495
- [...frontendToolsList, ...builtInFrontendTools].forEach((tool) => {
496
- if (tool.render) {
497
- // For wildcard tools without parameters, default to z.any()
498
- const args =
499
- tool.parameters || (tool.name === "*" ? z.any() : undefined);
500
- if (args) {
501
- combined.push({
502
- name: tool.name,
503
- args: args,
504
- render: tool.render,
505
- } as ReactToolCallRenderer<unknown>);
506
- }
507
- }
508
- });
509
-
510
- // Add render components from human-in-the-loop tools
511
- combined.push(...processedHumanInTheLoopTools.renderToolCalls);
512
-
513
- return combined;
514
- }, [
515
- renderToolCallsList,
516
- frontendToolsList,
517
- builtInFrontendTools,
518
- processedHumanInTheLoopTools,
519
- ]);
520
-
521
- // Stable instance: created once for the provider lifetime.
522
- // Updates are applied via setter effects below rather than recreating the instance.
523
- const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);
524
- if (copilotkitRef.current === null) {
525
- copilotkitRef.current = new CopilotKitCoreReact({
526
- runtimeUrl: chatApiEndpoint,
527
- runtimeTransport:
528
- useSingleEndpoint === true
529
- ? "single"
530
- : useSingleEndpoint === false
531
- ? "rest"
532
- : "auto",
533
- headers: mergedHeaders,
534
- credentials,
535
- properties,
536
- agents__unsafe_dev_only: mergedAgents,
537
- tools: allTools,
538
- renderToolCalls: allRenderToolCalls,
539
- renderActivityMessages: allActivityRenderers,
540
- renderCustomMessages: renderCustomMessagesList,
541
- debug,
542
- });
543
- // Set initial defaultThrottleMs synchronously so child hooks see the
544
- // correct value on their first render (before useEffect fires).
545
- if (defaultThrottleMs !== undefined) {
546
- copilotkitRef.current.setDefaultThrottleMs(defaultThrottleMs);
547
- }
548
- }
549
- const copilotkit = copilotkitRef.current;
550
-
551
- // Sync runtime feature flags from the core once runtime info is fetched
552
- useEffect(() => {
553
- // Check current value immediately (may already be set before subscription)
554
- setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);
555
- const subscription = copilotkit.subscribe({
556
- onRuntimeConnectionStatusChanged: () => {
557
- setRuntimeA2UIEnabled(copilotkit.a2uiEnabled);
558
- setRuntimeOpenGenUIEnabled(copilotkit.openGenerativeUIEnabled);
559
- setRuntimeLicenseStatus(copilotkit.licenseStatus);
560
- },
561
- });
562
- return () => {
563
- subscription.unsubscribe();
564
- };
565
- }, [copilotkit]);
566
-
567
- // Subscribe to render tool calls changes to force re-renders
568
- const [, forceUpdate] = useReducer((x) => x + 1, 0);
569
-
570
- useEffect(() => {
571
- const subscription = copilotkit.subscribe({
572
- onRenderToolCallsChanged: () => {
573
- forceUpdate();
574
- },
575
- });
576
-
577
- return () => {
578
- subscription.unsubscribe();
579
- };
580
- }, [copilotkit]);
581
-
582
- // Track executing tool call IDs at the provider level.
583
- // This is critical for HITL reconnection: when connecting to a thread with
584
- // pending tool calls, the onToolExecutionStart event fires before child components
585
- // (like CopilotChatToolCallsView) mount. By tracking at the provider level,
586
- // we ensure the executing state is captured and available when children mount.
587
- const [executingToolCallIds, setExecutingToolCallIds] = useState<
588
- ReadonlySet<string>
589
- >(() => new Set());
590
-
591
- useEffect(() => {
592
- const subscription = copilotkit.subscribe({
593
- onToolExecutionStart: ({ toolCallId }) => {
594
- setExecutingToolCallIds((prev) => {
595
- if (prev.has(toolCallId)) return prev;
596
- const next = new Set(prev);
597
- next.add(toolCallId);
598
- return next;
599
- });
600
- },
601
- onToolExecutionEnd: ({ toolCallId }) => {
602
- setExecutingToolCallIds((prev) => {
603
- if (!prev.has(toolCallId)) return prev;
604
- const next = new Set(prev);
605
- next.delete(toolCallId);
606
- return next;
607
- });
608
- },
609
- });
610
-
611
- return () => {
612
- subscription.unsubscribe();
613
- };
614
- }, [copilotkit]);
615
-
616
- // onError subscription — forward core errors to user callback
617
- const onErrorRef = useRef(onError);
618
- useEffect(() => {
619
- onErrorRef.current = onError;
620
- }, [onError]);
621
-
622
- useEffect(() => {
623
- const subscription = copilotkit.subscribe({
624
- onError: (event) => {
625
- if (onErrorRef.current) {
626
- onErrorRef.current(event);
627
- } else {
628
- console.error(
629
- `[CopilotKit] Error (${event.code}):`,
630
- event.error,
631
- event.context ?? {},
632
- );
633
- }
634
- },
635
- });
636
-
637
- return () => {
638
- subscription.unsubscribe();
639
- };
640
- }, [copilotkit]);
641
-
642
- useEffect(() => {
643
- copilotkit.setRuntimeUrl(chatApiEndpoint);
644
- copilotkit.setRuntimeTransport(
645
- useSingleEndpoint === true
646
- ? "single"
647
- : useSingleEndpoint === false
648
- ? "rest"
649
- : "auto",
650
- );
651
- copilotkit.setHeaders(mergedHeaders);
652
- copilotkit.setCredentials(credentials);
653
- copilotkit.setProperties(properties);
654
- copilotkit.setAgents__unsafe_dev_only(mergedAgents);
655
- copilotkit.setDebug(debug);
656
- }, [
657
- copilotkit,
658
- chatApiEndpoint,
659
- mergedHeaders,
660
- credentials,
661
- properties,
662
- mergedAgents,
663
- useSingleEndpoint,
664
- debug,
665
- ]);
666
-
667
- // Sync render/tool arrays to the stable instance via setters.
668
- // On mount, the constructor already receives the correct initial values,
669
- // so we skip the first invocation. This is critical because child hooks
670
- // (e.g., useFrontendTool, useHumanInTheLoop) register tools dynamically
671
- // via addTool()/setRenderToolCalls() in their own effects, which fire
672
- // BEFORE parent effects (React fires effects bottom-up). If the parent
673
- // setter effects ran on mount, they would overwrite the children's tools.
674
- const didMountRef = useRef(false);
675
-
676
- useEffect(() => {
677
- if (!didMountRef.current) return;
678
- copilotkit.setTools(allTools);
679
- }, [copilotkit, allTools]);
680
-
681
- useEffect(() => {
682
- if (!didMountRef.current) return;
683
- copilotkit.setRenderToolCalls(allRenderToolCalls);
684
- }, [copilotkit, allRenderToolCalls]);
685
-
686
- useEffect(() => {
687
- if (!didMountRef.current) return;
688
- copilotkit.setRenderActivityMessages(allActivityRenderers);
689
- }, [copilotkit, allActivityRenderers]);
690
-
691
- useEffect(() => {
692
- if (!didMountRef.current) return;
693
- copilotkit.setRenderCustomMessages(renderCustomMessagesList);
694
- }, [copilotkit, renderCustomMessagesList]);
695
-
696
- // Mark mount complete — must be declared AFTER the setter effects
697
- // so it runs last in the effect queue on the initial mount cycle.
698
- useEffect(() => {
699
- didMountRef.current = true;
700
- }, []);
701
-
702
- // Sync defaultThrottleMs to the core instance on prop changes.
703
- // Initial value is set synchronously during instance creation (inside the
704
- // ref-init block above) so child hooks see the correct value on first render.
705
- // This effect handles subsequent updates when the prop changes.
706
- useEffect(() => {
707
- copilotkit.setDefaultThrottleMs(defaultThrottleMs);
708
- }, [copilotkit, defaultThrottleMs]);
709
-
710
- // Register design skill as agent context for the generateSandboxedUi tool
711
- const designSkill = openGenerativeUI?.designSkill ?? DEFAULT_DESIGN_SKILL;
712
-
713
- useLayoutEffect(() => {
714
- if (!copilotkit || !openGenUIActive) return;
715
-
716
- const id = copilotkit.addContext({
717
- description:
718
- "Design guidelines for the generateSandboxedUi tool. Follow these when building UI.",
719
- value: designSkill,
720
- });
721
- return () => {
722
- copilotkit.removeContext(id);
723
- };
724
- }, [copilotkit, designSkill, openGenUIActive]);
725
-
726
- // Register sandbox functions as agent context so the LLM knows how to call them
727
- const sandboxFunctionsDescriptors = useMemo(() => {
728
- if (sandboxFunctionsList.length === 0) return null;
729
- return JSON.stringify(
730
- sandboxFunctionsList.map((fn) => ({
731
- name: fn.name,
732
- description: fn.description,
733
- parameters: schemaToJsonSchema(fn.parameters, { zodToJsonSchema }),
734
- })),
735
- );
736
- }, [sandboxFunctionsList]);
737
-
738
- useLayoutEffect(() => {
739
- if (!copilotkit || !sandboxFunctionsDescriptors || !openGenUIActive) return;
740
-
741
- const id = copilotkit.addContext({
742
- description:
743
- "Sandbox functions available in generated sandboxed UI code. Call via: await Websandbox.connection.remote.<functionName>(args)",
744
- value: sandboxFunctionsDescriptors,
745
- });
746
- return () => {
747
- copilotkit.removeContext(id);
748
- };
749
- }, [copilotkit, sandboxFunctionsDescriptors, openGenUIActive]);
750
-
751
- const contextValue = useMemo<CopilotKitContextValue>(
752
- () => ({ copilotkit, executingToolCallIds }),
753
- [copilotkit, executingToolCallIds],
754
- );
755
-
756
- // License context — driven by server-reported status via /info endpoint
757
- const licenseContextValue = useMemo(
758
- () => createLicenseContextValue(null),
759
- [],
760
- );
761
-
762
- return (
763
- <SandboxFunctionsContext.Provider value={sandboxFunctionsList}>
764
- <CopilotKitContext.Provider value={contextValue}>
765
- <LicenseContext.Provider value={licenseContextValue}>
766
- {runtimeA2UIEnabled && <A2UIBuiltInToolCallRenderer />}
767
- {runtimeA2UIEnabled && (
768
- <A2UICatalogContext
769
- catalog={a2ui?.catalog}
770
- includeSchema={a2ui?.includeSchema}
771
- />
772
- )}
773
- {children}
774
- {shouldRenderInspector ? (
775
- <CopilotKitInspector
776
- core={copilotkit}
777
- defaultAnchor={inspectorDefaultAnchor}
778
- />
779
- ) : null}
780
- {/* License warnings — driven by server-reported status */}
781
- {runtimeLicenseStatus === "none" && !resolvedPublicKey && (
782
- <LicenseWarningBanner type="no_license" />
783
- )}
784
- {runtimeLicenseStatus === "expired" && (
785
- <LicenseWarningBanner type="expired" />
786
- )}
787
- {runtimeLicenseStatus === "invalid" && (
788
- <LicenseWarningBanner type="invalid" />
789
- )}
790
- {runtimeLicenseStatus === "expiring" && (
791
- <LicenseWarningBanner type="expiring" />
792
- )}
793
- </LicenseContext.Provider>
794
- </CopilotKitContext.Provider>
795
- </SandboxFunctionsContext.Provider>
796
- );
797
- };
798
-
799
- // Re-export useCopilotKit from context for backward compatibility
800
- export { useCopilotKit } from "../context";