@copilotkit/react-core 2.0.0-next.1 → 2.0.0-rc.0

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 (538) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -12
  3. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts +954 -0
  4. package/dist/MarkdownRendererContext-B4Us6mwL.d.cts.map +1 -0
  5. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts +954 -0
  6. package/dist/MarkdownRendererContext-CRKFzsEB.d.mts.map +1 -0
  7. package/dist/MarkdownSurfaces-C2XZISKn.cjs +3964 -0
  8. package/dist/MarkdownSurfaces-C2XZISKn.cjs.map +1 -0
  9. package/dist/MarkdownSurfaces-ChSlVYOk.mjs +3655 -0
  10. package/dist/MarkdownSurfaces-ChSlVYOk.mjs.map +1 -0
  11. package/dist/context.cjs +144 -0
  12. package/dist/context.cjs.map +1 -0
  13. package/dist/context.d.cts +166 -0
  14. package/dist/context.d.cts.map +1 -0
  15. package/dist/context.d.mts +166 -0
  16. package/dist/context.d.mts.map +1 -0
  17. package/dist/context.mjs +136 -0
  18. package/dist/context.mjs.map +1 -0
  19. package/dist/generative-ui.cjs +8151 -0
  20. package/dist/generative-ui.cjs.map +1 -0
  21. package/dist/generative-ui.d.cts +4952 -0
  22. package/dist/generative-ui.d.cts.map +1 -0
  23. package/dist/generative-ui.d.mts +4952 -0
  24. package/dist/generative-ui.d.mts.map +1 -0
  25. package/dist/generative-ui.mjs +8137 -0
  26. package/dist/generative-ui.mjs.map +1 -0
  27. package/dist/headless.cjs +1927 -0
  28. package/dist/headless.cjs.map +1 -0
  29. package/dist/headless.d.cts +1117 -0
  30. package/dist/headless.d.cts.map +1 -0
  31. package/dist/headless.d.mts +1008 -0
  32. package/dist/headless.d.mts.map +1 -0
  33. package/dist/headless.mjs +1869 -0
  34. package/dist/headless.mjs.map +1 -0
  35. package/dist/index.cjs +15576 -0
  36. package/dist/index.cjs.map +1 -0
  37. package/dist/index.css +2 -0
  38. package/dist/index.d.cts +3450 -0
  39. package/dist/index.d.cts.map +1 -0
  40. package/dist/index.d.mts +3433 -0
  41. package/dist/index.d.mts.map +1 -0
  42. package/dist/index.mjs +13927 -146
  43. package/dist/index.mjs.map +1 -1
  44. package/dist/index.umd.js +18856 -0
  45. package/dist/index.umd.js.map +1 -0
  46. package/package.json +124 -52
  47. package/CHANGELOG.md +0 -4210
  48. package/dist/chunk-2IDV5OHF.mjs +0 -11
  49. package/dist/chunk-2IDV5OHF.mjs.map +0 -1
  50. package/dist/chunk-36KQV2NA.mjs +0 -1
  51. package/dist/chunk-36KQV2NA.mjs.map +0 -1
  52. package/dist/chunk-3V5TOYKW.mjs +0 -120
  53. package/dist/chunk-3V5TOYKW.mjs.map +0 -1
  54. package/dist/chunk-4CEQJ2X6.mjs +0 -31
  55. package/dist/chunk-4CEQJ2X6.mjs.map +0 -1
  56. package/dist/chunk-4RRMC7L2.mjs +0 -32
  57. package/dist/chunk-4RRMC7L2.mjs.map +0 -1
  58. package/dist/chunk-4YZA2BZC.mjs +0 -551
  59. package/dist/chunk-4YZA2BZC.mjs.map +0 -1
  60. package/dist/chunk-53K6WNJG.mjs +0 -36
  61. package/dist/chunk-53K6WNJG.mjs.map +0 -1
  62. package/dist/chunk-6ESSSQ7Q.mjs +0 -134
  63. package/dist/chunk-6ESSSQ7Q.mjs.map +0 -1
  64. package/dist/chunk-6PUNP7CD.mjs +0 -102
  65. package/dist/chunk-6PUNP7CD.mjs.map +0 -1
  66. package/dist/chunk-6YOKPWQ7.mjs +0 -1
  67. package/dist/chunk-6YOKPWQ7.mjs.map +0 -1
  68. package/dist/chunk-6ZLPNY7X.mjs +0 -225
  69. package/dist/chunk-6ZLPNY7X.mjs.map +0 -1
  70. package/dist/chunk-7DTB7S5V.mjs +0 -83
  71. package/dist/chunk-7DTB7S5V.mjs.map +0 -1
  72. package/dist/chunk-7IBF6RBW.mjs +0 -23
  73. package/dist/chunk-7IBF6RBW.mjs.map +0 -1
  74. package/dist/chunk-A6NKSGH3.mjs +0 -1
  75. package/dist/chunk-A6NKSGH3.mjs.map +0 -1
  76. package/dist/chunk-ABWT4DRT.mjs +0 -24
  77. package/dist/chunk-ABWT4DRT.mjs.map +0 -1
  78. package/dist/chunk-AFNWX62Q.mjs +0 -110
  79. package/dist/chunk-AFNWX62Q.mjs.map +0 -1
  80. package/dist/chunk-BUSWSDYO.mjs +0 -17
  81. package/dist/chunk-BUSWSDYO.mjs.map +0 -1
  82. package/dist/chunk-CDUIA2WM.mjs +0 -60
  83. package/dist/chunk-CDUIA2WM.mjs.map +0 -1
  84. package/dist/chunk-CYDWEPFL.mjs +0 -1
  85. package/dist/chunk-CYDWEPFL.mjs.map +0 -1
  86. package/dist/chunk-DMLQZG75.mjs +0 -25
  87. package/dist/chunk-DMLQZG75.mjs.map +0 -1
  88. package/dist/chunk-E7SE25ZU.mjs +0 -59
  89. package/dist/chunk-E7SE25ZU.mjs.map +0 -1
  90. package/dist/chunk-EFL5OBKN.mjs +0 -310
  91. package/dist/chunk-EFL5OBKN.mjs.map +0 -1
  92. package/dist/chunk-F555TVE4.mjs +0 -33
  93. package/dist/chunk-F555TVE4.mjs.map +0 -1
  94. package/dist/chunk-FD6FGKYY.mjs +0 -1
  95. package/dist/chunk-FD6FGKYY.mjs.map +0 -1
  96. package/dist/chunk-FDOMAPJY.mjs +0 -59
  97. package/dist/chunk-FDOMAPJY.mjs.map +0 -1
  98. package/dist/chunk-FQFXYAV7.mjs +0 -86
  99. package/dist/chunk-FQFXYAV7.mjs.map +0 -1
  100. package/dist/chunk-GPEJNVE5.mjs +0 -80
  101. package/dist/chunk-GPEJNVE5.mjs.map +0 -1
  102. package/dist/chunk-HE22TZMF.mjs +0 -186
  103. package/dist/chunk-HE22TZMF.mjs.map +0 -1
  104. package/dist/chunk-I76HKHPJ.mjs +0 -32
  105. package/dist/chunk-I76HKHPJ.mjs.map +0 -1
  106. package/dist/chunk-ICIK2BSB.mjs +0 -17
  107. package/dist/chunk-ICIK2BSB.mjs.map +0 -1
  108. package/dist/chunk-JD7BAH7U.mjs +0 -1
  109. package/dist/chunk-JD7BAH7U.mjs.map +0 -1
  110. package/dist/chunk-LHERIF3L.mjs +0 -83
  111. package/dist/chunk-LHERIF3L.mjs.map +0 -1
  112. package/dist/chunk-LSHFN2Y5.mjs +0 -349
  113. package/dist/chunk-LSHFN2Y5.mjs.map +0 -1
  114. package/dist/chunk-LUGEI4YQ.mjs +0 -1
  115. package/dist/chunk-LUGEI4YQ.mjs.map +0 -1
  116. package/dist/chunk-NB2FKV2V.mjs +0 -1
  117. package/dist/chunk-NB2FKV2V.mjs.map +0 -1
  118. package/dist/chunk-NBK4KBLX.mjs +0 -54
  119. package/dist/chunk-NBK4KBLX.mjs.map +0 -1
  120. package/dist/chunk-O7ARI5CV.mjs +0 -31
  121. package/dist/chunk-O7ARI5CV.mjs.map +0 -1
  122. package/dist/chunk-PIF5KJYI.mjs +0 -103
  123. package/dist/chunk-PIF5KJYI.mjs.map +0 -1
  124. package/dist/chunk-PMAFHQ7P.mjs +0 -65
  125. package/dist/chunk-PMAFHQ7P.mjs.map +0 -1
  126. package/dist/chunk-QNUAXSDP.mjs +0 -166
  127. package/dist/chunk-QNUAXSDP.mjs.map +0 -1
  128. package/dist/chunk-RKTVJRK7.mjs +0 -143
  129. package/dist/chunk-RKTVJRK7.mjs.map +0 -1
  130. package/dist/chunk-SKC7AJIV.mjs +0 -61
  131. package/dist/chunk-SKC7AJIV.mjs.map +0 -1
  132. package/dist/chunk-SPCZTZCY.mjs +0 -1
  133. package/dist/chunk-SPCZTZCY.mjs.map +0 -1
  134. package/dist/chunk-VV56AVPB.mjs +0 -125
  135. package/dist/chunk-VV56AVPB.mjs.map +0 -1
  136. package/dist/chunk-WF65O6HX.mjs +0 -66
  137. package/dist/chunk-WF65O6HX.mjs.map +0 -1
  138. package/dist/chunk-XDFVCQD3.mjs +0 -27
  139. package/dist/chunk-XDFVCQD3.mjs.map +0 -1
  140. package/dist/chunk-YCG6SNAU.mjs +0 -759
  141. package/dist/chunk-YCG6SNAU.mjs.map +0 -1
  142. package/dist/chunk-YTQHRJUA.mjs +0 -86
  143. package/dist/chunk-YTQHRJUA.mjs.map +0 -1
  144. package/dist/chunk-YYN33GSG.mjs +0 -73
  145. package/dist/chunk-YYN33GSG.mjs.map +0 -1
  146. package/dist/chunk-Z6JV2LRY.mjs +0 -37
  147. package/dist/chunk-Z6JV2LRY.mjs.map +0 -1
  148. package/dist/chunk-ZVF5Q6IH.mjs +0 -29
  149. package/dist/chunk-ZVF5Q6IH.mjs.map +0 -1
  150. package/dist/chunk-ZYTXB6HH.mjs +0 -151
  151. package/dist/chunk-ZYTXB6HH.mjs.map +0 -1
  152. package/dist/components/CopilotListeners.d.ts +0 -3
  153. package/dist/components/CopilotListeners.js +0 -101
  154. package/dist/components/CopilotListeners.js.map +0 -1
  155. package/dist/components/CopilotListeners.mjs +0 -9
  156. package/dist/components/CopilotListeners.mjs.map +0 -1
  157. package/dist/components/copilot-provider/copilot-messages.d.ts +0 -24
  158. package/dist/components/copilot-provider/copilot-messages.js +0 -351
  159. package/dist/components/copilot-provider/copilot-messages.js.map +0 -1
  160. package/dist/components/copilot-provider/copilot-messages.mjs +0 -16
  161. package/dist/components/copilot-provider/copilot-messages.mjs.map +0 -1
  162. package/dist/components/copilot-provider/copilotkit-props.d.ts +0 -160
  163. package/dist/components/copilot-provider/copilotkit-props.js +0 -19
  164. package/dist/components/copilot-provider/copilotkit-props.js.map +0 -1
  165. package/dist/components/copilot-provider/copilotkit-props.mjs +0 -1
  166. package/dist/components/copilot-provider/copilotkit-props.mjs.map +0 -1
  167. package/dist/components/copilot-provider/copilotkit.d.ts +0 -19
  168. package/dist/components/copilot-provider/copilotkit.js +0 -1960
  169. package/dist/components/copilot-provider/copilotkit.js.map +0 -1
  170. package/dist/components/copilot-provider/copilotkit.mjs +0 -31
  171. package/dist/components/copilot-provider/copilotkit.mjs.map +0 -1
  172. package/dist/components/copilot-provider/index.d.ts +0 -14
  173. package/dist/components/copilot-provider/index.js +0 -1960
  174. package/dist/components/copilot-provider/index.js.map +0 -1
  175. package/dist/components/copilot-provider/index.mjs +0 -30
  176. package/dist/components/copilot-provider/index.mjs.map +0 -1
  177. package/dist/components/dev-console/console-trigger.d.ts +0 -8
  178. package/dist/components/dev-console/console-trigger.js +0 -1202
  179. package/dist/components/dev-console/console-trigger.js.map +0 -1
  180. package/dist/components/dev-console/console-trigger.mjs +0 -233
  181. package/dist/components/dev-console/console-trigger.mjs.map +0 -1
  182. package/dist/components/dev-console/developer-console-modal.d.ts +0 -10
  183. package/dist/components/dev-console/developer-console-modal.js +0 -987
  184. package/dist/components/dev-console/developer-console-modal.js.map +0 -1
  185. package/dist/components/dev-console/developer-console-modal.mjs +0 -12
  186. package/dist/components/dev-console/developer-console-modal.mjs.map +0 -1
  187. package/dist/components/dev-console/icons.d.ts +0 -9
  188. package/dist/components/dev-console/icons.js +0 -131
  189. package/dist/components/dev-console/icons.js.map +0 -1
  190. package/dist/components/dev-console/icons.mjs +0 -16
  191. package/dist/components/dev-console/icons.mjs.map +0 -1
  192. package/dist/components/error-boundary/error-boundary.d.ts +0 -31
  193. package/dist/components/error-boundary/error-boundary.js +0 -500
  194. package/dist/components/error-boundary/error-boundary.js.map +0 -1
  195. package/dist/components/error-boundary/error-boundary.mjs +0 -15
  196. package/dist/components/error-boundary/error-boundary.mjs.map +0 -1
  197. package/dist/components/error-boundary/error-utils.d.ts +0 -11
  198. package/dist/components/error-boundary/error-utils.js +0 -190
  199. package/dist/components/error-boundary/error-utils.js.map +0 -1
  200. package/dist/components/error-boundary/error-utils.mjs +0 -14
  201. package/dist/components/error-boundary/error-utils.mjs.map +0 -1
  202. package/dist/components/index.d.ts +0 -14
  203. package/dist/components/index.js +0 -1960
  204. package/dist/components/index.js.map +0 -1
  205. package/dist/components/index.mjs +0 -31
  206. package/dist/components/index.mjs.map +0 -1
  207. package/dist/components/toast/exclamation-mark-icon.d.ts +0 -9
  208. package/dist/components/toast/exclamation-mark-icon.js +0 -55
  209. package/dist/components/toast/exclamation-mark-icon.js.map +0 -1
  210. package/dist/components/toast/exclamation-mark-icon.mjs +0 -8
  211. package/dist/components/toast/exclamation-mark-icon.mjs.map +0 -1
  212. package/dist/components/toast/toast-provider.d.ts +0 -27
  213. package/dist/components/toast/toast-provider.js +0 -347
  214. package/dist/components/toast/toast-provider.js.map +0 -1
  215. package/dist/components/toast/toast-provider.mjs +0 -10
  216. package/dist/components/toast/toast-provider.mjs.map +0 -1
  217. package/dist/components/usage-banner.d.ts +0 -29
  218. package/dist/components/usage-banner.js +0 -247
  219. package/dist/components/usage-banner.js.map +0 -1
  220. package/dist/components/usage-banner.mjs +0 -12
  221. package/dist/components/usage-banner.mjs.map +0 -1
  222. package/dist/context/coagent-state-renders-context.d.ts +0 -24
  223. package/dist/context/coagent-state-renders-context.js +0 -91
  224. package/dist/context/coagent-state-renders-context.js.map +0 -1
  225. package/dist/context/coagent-state-renders-context.mjs +0 -12
  226. package/dist/context/coagent-state-renders-context.mjs.map +0 -1
  227. package/dist/context/copilot-context.d.ts +0 -10
  228. package/dist/context/copilot-context.js +0 -161
  229. package/dist/context/copilot-context.js.map +0 -1
  230. package/dist/context/copilot-context.mjs +0 -10
  231. package/dist/context/copilot-context.mjs.map +0 -1
  232. package/dist/context/copilot-messages-context.d.ts +0 -18
  233. package/dist/context/copilot-messages-context.js +0 -60
  234. package/dist/context/copilot-messages-context.js.map +0 -1
  235. package/dist/context/copilot-messages-context.mjs +0 -10
  236. package/dist/context/copilot-messages-context.mjs.map +0 -1
  237. package/dist/context/index.d.ts +0 -15
  238. package/dist/context/index.js +0 -285
  239. package/dist/context/index.js.map +0 -1
  240. package/dist/context/index.mjs +0 -33
  241. package/dist/context/index.mjs.map +0 -1
  242. package/dist/context/threads-context.d.ts +0 -16
  243. package/dist/context/threads-context.js +0 -59
  244. package/dist/context/threads-context.js.map +0 -1
  245. package/dist/context/threads-context.mjs +0 -12
  246. package/dist/context/threads-context.mjs.map +0 -1
  247. package/dist/copilot-context-ec77e921.d.ts +0 -209
  248. package/dist/hooks/index.d.ts +0 -33
  249. package/dist/hooks/index.js +0 -1774
  250. package/dist/hooks/index.js.map +0 -1
  251. package/dist/hooks/index.mjs +0 -91
  252. package/dist/hooks/index.mjs.map +0 -1
  253. package/dist/hooks/use-agent-nodename.d.ts +0 -3
  254. package/dist/hooks/use-agent-nodename.js +0 -56
  255. package/dist/hooks/use-agent-nodename.js.map +0 -1
  256. package/dist/hooks/use-agent-nodename.mjs +0 -8
  257. package/dist/hooks/use-agent-nodename.mjs.map +0 -1
  258. package/dist/hooks/use-coagent-state-render-bridge.d.ts +0 -100
  259. package/dist/hooks/use-coagent-state-render-bridge.js +0 -214
  260. package/dist/hooks/use-coagent-state-render-bridge.js.map +0 -1
  261. package/dist/hooks/use-coagent-state-render-bridge.mjs +0 -15
  262. package/dist/hooks/use-coagent-state-render-bridge.mjs.map +0 -1
  263. package/dist/hooks/use-coagent-state-render.d.ts +0 -55
  264. package/dist/hooks/use-coagent-state-render.js +0 -255
  265. package/dist/hooks/use-coagent-state-render.js.map +0 -1
  266. package/dist/hooks/use-coagent-state-render.mjs +0 -11
  267. package/dist/hooks/use-coagent-state-render.mjs.map +0 -1
  268. package/dist/hooks/use-coagent.d.ts +0 -192
  269. package/dist/hooks/use-coagent.js +0 -233
  270. package/dist/hooks/use-coagent.js.map +0 -1
  271. package/dist/hooks/use-coagent.mjs +0 -9
  272. package/dist/hooks/use-coagent.mjs.map +0 -1
  273. package/dist/hooks/use-configure-chat-suggestions.d.ts +0 -36
  274. package/dist/hooks/use-configure-chat-suggestions.js +0 -79
  275. package/dist/hooks/use-configure-chat-suggestions.js.map +0 -1
  276. package/dist/hooks/use-configure-chat-suggestions.mjs +0 -47
  277. package/dist/hooks/use-configure-chat-suggestions.mjs.map +0 -1
  278. package/dist/hooks/use-copilot-action.d.ts +0 -103
  279. package/dist/hooks/use-copilot-action.js +0 -295
  280. package/dist/hooks/use-copilot-action.js.map +0 -1
  281. package/dist/hooks/use-copilot-action.mjs +0 -11
  282. package/dist/hooks/use-copilot-action.mjs.map +0 -1
  283. package/dist/hooks/use-copilot-additional-instructions.d.ts +0 -26
  284. package/dist/hooks/use-copilot-additional-instructions.js +0 -177
  285. package/dist/hooks/use-copilot-additional-instructions.js.map +0 -1
  286. package/dist/hooks/use-copilot-additional-instructions.mjs +0 -9
  287. package/dist/hooks/use-copilot-additional-instructions.mjs.map +0 -1
  288. package/dist/hooks/use-copilot-authenticated-action.d.ts +0 -18
  289. package/dist/hooks/use-copilot-authenticated-action.js +0 -462
  290. package/dist/hooks/use-copilot-authenticated-action.js.map +0 -1
  291. package/dist/hooks/use-copilot-authenticated-action.mjs +0 -13
  292. package/dist/hooks/use-copilot-authenticated-action.mjs.map +0 -1
  293. package/dist/hooks/use-copilot-chat-headless_c.d.ts +0 -25
  294. package/dist/hooks/use-copilot-chat-headless_c.js +0 -1044
  295. package/dist/hooks/use-copilot-chat-headless_c.js.map +0 -1
  296. package/dist/hooks/use-copilot-chat-headless_c.mjs +0 -24
  297. package/dist/hooks/use-copilot-chat-headless_c.mjs.map +0 -1
  298. package/dist/hooks/use-copilot-chat-suggestions.d.ts +0 -35
  299. package/dist/hooks/use-copilot-chat-suggestions.js +0 -60
  300. package/dist/hooks/use-copilot-chat-suggestions.js.map +0 -1
  301. package/dist/hooks/use-copilot-chat-suggestions.mjs +0 -8
  302. package/dist/hooks/use-copilot-chat-suggestions.mjs.map +0 -1
  303. package/dist/hooks/use-copilot-chat.d.ts +0 -92
  304. package/dist/hooks/use-copilot-chat.js +0 -978
  305. package/dist/hooks/use-copilot-chat.js.map +0 -1
  306. package/dist/hooks/use-copilot-chat.mjs +0 -21
  307. package/dist/hooks/use-copilot-chat.mjs.map +0 -1
  308. package/dist/hooks/use-copilot-chat_internal.d.ts +0 -244
  309. package/dist/hooks/use-copilot-chat_internal.js +0 -976
  310. package/dist/hooks/use-copilot-chat_internal.js.map +0 -1
  311. package/dist/hooks/use-copilot-chat_internal.mjs +0 -22
  312. package/dist/hooks/use-copilot-chat_internal.mjs.map +0 -1
  313. package/dist/hooks/use-copilot-readable.d.ts +0 -37
  314. package/dist/hooks/use-copilot-readable.js +0 -61
  315. package/dist/hooks/use-copilot-readable.js.map +0 -1
  316. package/dist/hooks/use-copilot-readable.mjs +0 -8
  317. package/dist/hooks/use-copilot-readable.mjs.map +0 -1
  318. package/dist/hooks/use-copilot-runtime-client.d.ts +0 -10
  319. package/dist/hooks/use-copilot-runtime-client.js +0 -203
  320. package/dist/hooks/use-copilot-runtime-client.js.map +0 -1
  321. package/dist/hooks/use-copilot-runtime-client.mjs +0 -9
  322. package/dist/hooks/use-copilot-runtime-client.mjs.map +0 -1
  323. package/dist/hooks/use-default-tool.d.ts +0 -8
  324. package/dist/hooks/use-default-tool.js +0 -302
  325. package/dist/hooks/use-default-tool.js.map +0 -1
  326. package/dist/hooks/use-default-tool.mjs +0 -12
  327. package/dist/hooks/use-default-tool.mjs.map +0 -1
  328. package/dist/hooks/use-flat-category-store.d.ts +0 -9
  329. package/dist/hooks/use-flat-category-store.js +0 -93
  330. package/dist/hooks/use-flat-category-store.js.map +0 -1
  331. package/dist/hooks/use-flat-category-store.mjs +0 -8
  332. package/dist/hooks/use-flat-category-store.mjs.map +0 -1
  333. package/dist/hooks/use-frontend-tool.d.ts +0 -11
  334. package/dist/hooks/use-frontend-tool.js +0 -104
  335. package/dist/hooks/use-frontend-tool.js.map +0 -1
  336. package/dist/hooks/use-frontend-tool.mjs +0 -8
  337. package/dist/hooks/use-frontend-tool.mjs.map +0 -1
  338. package/dist/hooks/use-human-in-the-loop.d.ts +0 -13
  339. package/dist/hooks/use-human-in-the-loop.js +0 -122
  340. package/dist/hooks/use-human-in-the-loop.js.map +0 -1
  341. package/dist/hooks/use-human-in-the-loop.mjs +0 -8
  342. package/dist/hooks/use-human-in-the-loop.mjs.map +0 -1
  343. package/dist/hooks/use-langgraph-interrupt-render.d.ts +0 -6
  344. package/dist/hooks/use-langgraph-interrupt-render.js +0 -318
  345. package/dist/hooks/use-langgraph-interrupt-render.js.map +0 -1
  346. package/dist/hooks/use-langgraph-interrupt-render.mjs +0 -14
  347. package/dist/hooks/use-langgraph-interrupt-render.mjs.map +0 -1
  348. package/dist/hooks/use-langgraph-interrupt.d.ts +0 -14
  349. package/dist/hooks/use-langgraph-interrupt.js +0 -201
  350. package/dist/hooks/use-langgraph-interrupt.js.map +0 -1
  351. package/dist/hooks/use-langgraph-interrupt.mjs +0 -10
  352. package/dist/hooks/use-langgraph-interrupt.mjs.map +0 -1
  353. package/dist/hooks/use-lazy-tool-renderer.d.ts +0 -6
  354. package/dist/hooks/use-lazy-tool-renderer.js +0 -53
  355. package/dist/hooks/use-lazy-tool-renderer.js.map +0 -1
  356. package/dist/hooks/use-lazy-tool-renderer.mjs +0 -8
  357. package/dist/hooks/use-lazy-tool-renderer.mjs.map +0 -1
  358. package/dist/hooks/use-make-copilot-document-readable.d.ts +0 -12
  359. package/dist/hooks/use-make-copilot-document-readable.js +0 -176
  360. package/dist/hooks/use-make-copilot-document-readable.js.map +0 -1
  361. package/dist/hooks/use-make-copilot-document-readable.mjs +0 -9
  362. package/dist/hooks/use-make-copilot-document-readable.mjs.map +0 -1
  363. package/dist/hooks/use-render-tool-call.d.ts +0 -12
  364. package/dist/hooks/use-render-tool-call.js +0 -90
  365. package/dist/hooks/use-render-tool-call.js.map +0 -1
  366. package/dist/hooks/use-render-tool-call.mjs +0 -8
  367. package/dist/hooks/use-render-tool-call.mjs.map +0 -1
  368. package/dist/hooks/use-tree.d.ts +0 -19
  369. package/dist/hooks/use-tree.js +0 -175
  370. package/dist/hooks/use-tree.js.map +0 -1
  371. package/dist/hooks/use-tree.mjs +0 -8
  372. package/dist/hooks/use-tree.mjs.map +0 -1
  373. package/dist/index.d.ts +0 -43
  374. package/dist/index.js +0 -3528
  375. package/dist/index.js.map +0 -1
  376. package/dist/lib/copilot-task.d.ts +0 -97
  377. package/dist/lib/copilot-task.js +0 -194
  378. package/dist/lib/copilot-task.js.map +0 -1
  379. package/dist/lib/copilot-task.mjs +0 -31
  380. package/dist/lib/copilot-task.mjs.map +0 -1
  381. package/dist/lib/index.d.ts +0 -11
  382. package/dist/lib/index.js +0 -196
  383. package/dist/lib/index.js.map +0 -1
  384. package/dist/lib/index.mjs +0 -32
  385. package/dist/lib/index.mjs.map +0 -1
  386. package/dist/lib/status-checker.d.ts +0 -17
  387. package/dist/lib/status-checker.js +0 -102
  388. package/dist/lib/status-checker.js.map +0 -1
  389. package/dist/lib/status-checker.mjs +0 -8
  390. package/dist/lib/status-checker.mjs.map +0 -1
  391. package/dist/setupTests.d.ts +0 -2
  392. package/dist/setupTests.js +0 -26
  393. package/dist/setupTests.js.map +0 -1
  394. package/dist/setupTests.mjs +0 -24
  395. package/dist/setupTests.mjs.map +0 -1
  396. package/dist/types/chat-suggestion-configuration.d.ts +0 -22
  397. package/dist/types/chat-suggestion-configuration.js +0 -19
  398. package/dist/types/chat-suggestion-configuration.js.map +0 -1
  399. package/dist/types/chat-suggestion-configuration.mjs +0 -1
  400. package/dist/types/chat-suggestion-configuration.mjs.map +0 -1
  401. package/dist/types/coagent-action.d.ts +0 -29
  402. package/dist/types/coagent-action.js +0 -19
  403. package/dist/types/coagent-action.js.map +0 -1
  404. package/dist/types/coagent-action.mjs +0 -1
  405. package/dist/types/coagent-action.mjs.map +0 -1
  406. package/dist/types/coagent-state.d.ts +0 -15
  407. package/dist/types/coagent-state.js +0 -19
  408. package/dist/types/coagent-state.js.map +0 -1
  409. package/dist/types/coagent-state.mjs +0 -1
  410. package/dist/types/coagent-state.mjs.map +0 -1
  411. package/dist/types/crew.d.ts +0 -79
  412. package/dist/types/crew.js +0 -19
  413. package/dist/types/crew.js.map +0 -1
  414. package/dist/types/crew.mjs +0 -2
  415. package/dist/types/crew.mjs.map +0 -1
  416. package/dist/types/document-pointer.d.ts +0 -9
  417. package/dist/types/document-pointer.js +0 -19
  418. package/dist/types/document-pointer.js.map +0 -1
  419. package/dist/types/document-pointer.mjs +0 -1
  420. package/dist/types/document-pointer.mjs.map +0 -1
  421. package/dist/types/frontend-action.d.ts +0 -127
  422. package/dist/types/frontend-action.js +0 -53
  423. package/dist/types/frontend-action.js.map +0 -1
  424. package/dist/types/frontend-action.mjs +0 -8
  425. package/dist/types/frontend-action.mjs.map +0 -1
  426. package/dist/types/index.d.ts +0 -12
  427. package/dist/types/index.js +0 -19
  428. package/dist/types/index.js.map +0 -1
  429. package/dist/types/index.mjs +0 -4
  430. package/dist/types/index.mjs.map +0 -1
  431. package/dist/types/interrupt-action.d.ts +0 -10
  432. package/dist/types/interrupt-action.js +0 -19
  433. package/dist/types/interrupt-action.js.map +0 -1
  434. package/dist/types/interrupt-action.mjs +0 -2
  435. package/dist/types/interrupt-action.mjs.map +0 -1
  436. package/dist/types/system-message.d.ts +0 -3
  437. package/dist/types/system-message.js +0 -19
  438. package/dist/types/system-message.js.map +0 -1
  439. package/dist/types/system-message.mjs +0 -1
  440. package/dist/types/system-message.mjs.map +0 -1
  441. package/dist/utils/dev-console.d.ts +0 -3
  442. package/dist/utils/dev-console.js +0 -41
  443. package/dist/utils/dev-console.js.map +0 -1
  444. package/dist/utils/dev-console.mjs +0 -8
  445. package/dist/utils/dev-console.mjs.map +0 -1
  446. package/dist/utils/index.d.ts +0 -2
  447. package/dist/utils/index.js +0 -52
  448. package/dist/utils/index.js.map +0 -1
  449. package/dist/utils/index.mjs +0 -13
  450. package/dist/utils/index.mjs.map +0 -1
  451. package/dist/utils/suggestions-constants.d.ts +0 -9
  452. package/dist/utils/suggestions-constants.js +0 -35
  453. package/dist/utils/suggestions-constants.js.map +0 -1
  454. package/dist/utils/suggestions-constants.mjs +0 -8
  455. package/dist/utils/suggestions-constants.mjs.map +0 -1
  456. package/dist/utils/utils.d.ts +0 -2
  457. package/dist/utils/utils.js +0 -19
  458. package/dist/utils/utils.js.map +0 -1
  459. package/dist/utils/utils.mjs +0 -1
  460. package/dist/utils/utils.mjs.map +0 -1
  461. package/dist/v2/index.css +0 -4
  462. package/dist/v2/index.css.map +0 -1
  463. package/dist/v2/index.d.ts +0 -2
  464. package/dist/v2/index.js +0 -27
  465. package/dist/v2/index.js.map +0 -1
  466. package/dist/v2/index.mjs +0 -6
  467. package/dist/v2/index.mjs.map +0 -1
  468. package/jest.config.js +0 -25
  469. package/src/components/CopilotListeners.tsx +0 -81
  470. package/src/components/copilot-provider/__tests__/copilotkit-error.test.tsx +0 -75
  471. package/src/components/copilot-provider/copilot-messages.tsx +0 -274
  472. package/src/components/copilot-provider/copilotkit-props.tsx +0 -169
  473. package/src/components/copilot-provider/copilotkit.tsx +0 -671
  474. package/src/components/copilot-provider/index.ts +0 -3
  475. package/src/components/dev-console/console-trigger.tsx +0 -254
  476. package/src/components/dev-console/developer-console-modal.tsx +0 -866
  477. package/src/components/dev-console/icons.tsx +0 -101
  478. package/src/components/error-boundary/error-boundary.tsx +0 -91
  479. package/src/components/error-boundary/error-utils.tsx +0 -100
  480. package/src/components/index.ts +0 -1
  481. package/src/components/toast/exclamation-mark-icon.tsx +0 -27
  482. package/src/components/toast/toast-provider.tsx +0 -363
  483. package/src/components/usage-banner.tsx +0 -259
  484. package/src/context/coagent-state-renders-context.tsx +0 -76
  485. package/src/context/copilot-context.tsx +0 -332
  486. package/src/context/copilot-messages-context.tsx +0 -35
  487. package/src/context/index.ts +0 -16
  488. package/src/context/threads-context.tsx +0 -41
  489. package/src/hooks/__tests__/use-coagent-config.test.ts +0 -351
  490. package/src/hooks/index.ts +0 -34
  491. package/src/hooks/use-agent-nodename.ts +0 -30
  492. package/src/hooks/use-coagent-state-render-bridge.tsx +0 -293
  493. package/src/hooks/use-coagent-state-render.ts +0 -152
  494. package/src/hooks/use-coagent.ts +0 -366
  495. package/src/hooks/use-configure-chat-suggestions.tsx +0 -86
  496. package/src/hooks/use-copilot-action.ts +0 -236
  497. package/src/hooks/use-copilot-additional-instructions.ts +0 -85
  498. package/src/hooks/use-copilot-authenticated-action.ts +0 -70
  499. package/src/hooks/use-copilot-chat-headless_c.ts +0 -258
  500. package/src/hooks/use-copilot-chat-suggestions.tsx +0 -124
  501. package/src/hooks/use-copilot-chat.ts +0 -130
  502. package/src/hooks/use-copilot-chat_internal.ts +0 -696
  503. package/src/hooks/use-copilot-readable.ts +0 -135
  504. package/src/hooks/use-copilot-runtime-client.ts +0 -164
  505. package/src/hooks/use-default-tool.ts +0 -7
  506. package/src/hooks/use-flat-category-store.ts +0 -105
  507. package/src/hooks/use-frontend-tool.ts +0 -96
  508. package/src/hooks/use-human-in-the-loop.ts +0 -122
  509. package/src/hooks/use-langgraph-interrupt-render.ts +0 -136
  510. package/src/hooks/use-langgraph-interrupt.ts +0 -36
  511. package/src/hooks/use-lazy-tool-renderer.tsx +0 -30
  512. package/src/hooks/use-make-copilot-document-readable.ts +0 -30
  513. package/src/hooks/use-render-tool-call.ts +0 -80
  514. package/src/hooks/use-tree.ts +0 -207
  515. package/src/index.tsx +0 -7
  516. package/src/lib/copilot-task.ts +0 -201
  517. package/src/lib/index.ts +0 -1
  518. package/src/lib/status-checker.ts +0 -64
  519. package/src/setupTests.ts +0 -26
  520. package/src/types/chat-suggestion-configuration.ts +0 -23
  521. package/src/types/coagent-action.ts +0 -31
  522. package/src/types/coagent-state.ts +0 -13
  523. package/src/types/crew.ts +0 -89
  524. package/src/types/document-pointer.ts +0 -7
  525. package/src/types/frontend-action.ts +0 -202
  526. package/src/types/index.ts +0 -17
  527. package/src/types/interrupt-action.ts +0 -43
  528. package/src/types/system-message.ts +0 -4
  529. package/src/utils/dev-console.ts +0 -19
  530. package/src/utils/index.ts +0 -2
  531. package/src/utils/suggestions-constants.ts +0 -8
  532. package/src/utils/utils.test.ts +0 -7
  533. package/src/utils/utils.ts +0 -8
  534. package/src/v2/index.css +0 -1
  535. package/src/v2/index.ts +0 -4
  536. package/tsconfig.json +0 -8
  537. package/tsup.config.ts +0 -16
  538. package/typedoc.json +0 -4
@@ -0,0 +1,3964 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) {
13
+ __defProp(to, key, {
14
+ get: ((k) => from[k]).bind(null, key),
15
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
16
+ });
17
+ }
18
+ }
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+
27
+ //#endregion
28
+ let _copilotkit_core = require("@copilotkit/core");
29
+ let react = require("react");
30
+ react = __toESM(react);
31
+ let react_jsx_runtime = require("react/jsx-runtime");
32
+ let _copilotkit_markdown_renderer_react = require("@copilotkit/markdown-renderer/react");
33
+ let _copilotkit_markdown_renderer = require("@copilotkit/markdown-renderer");
34
+ let tailwind_merge = require("tailwind-merge");
35
+ let _copilotkit_shared = require("@copilotkit/shared");
36
+ let _copilotkit_react_core_context = require("@copilotkit/react-core/context");
37
+ let zod = require("zod");
38
+ let zod_to_json_schema = require("zod-to-json-schema");
39
+
40
+ //#region src/components/chat/StreamingMarkdownDefaultRenderer.tsx
41
+ const defaultNodeRenderers = (0, _copilotkit_markdown_renderer_react.createStreamingMarkdownNodeRenderers)({ codeBlock: ({ node }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
42
+ className: "cpk:overflow-x-auto cpk:rounded-lg cpk:bg-muted cpk:text-foreground cpk:p-3",
43
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
44
+ "data-code-info": node.info ?? void 0,
45
+ children: node.text
46
+ })
47
+ }) });
48
+ /**
49
+ * react-core's built-in default markdown renderer — a thin adapter over
50
+ * `@copilotkit/markdown-renderer`'s streaming renderer. Maps the pluggable
51
+ * renderer contract (`{ content, isStreaming, className }`) onto the streaming
52
+ * renderer for streaming-safe incremental rendering + per-token animation.
53
+ * Still overridable via the slot/provider pluggable interface.
54
+ */
55
+ function StreamingMarkdownDefaultRenderer({ content, isStreaming, className, nodeRenderers, caret, options, onLinkClick, onCitationClick }) {
56
+ const mergedNodeRenderers = (0, react.useMemo)(() => nodeRenderers ? (0, _copilotkit_markdown_renderer_react.createStreamingMarkdownNodeRenderers)({
57
+ ...defaultNodeRenderers,
58
+ ...nodeRenderers
59
+ }) : defaultNodeRenderers, [nodeRenderers]);
60
+ if (!content) return null;
61
+ (0, _copilotkit_markdown_renderer.warnUnsupportedRichSyntaxOnce)(content);
62
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_copilotkit_markdown_renderer_react.StreamingMarkdownRenderer, {
63
+ className,
64
+ isComplete: !isStreaming,
65
+ caret: caret ?? !!isStreaming,
66
+ nodeRenderers: mergedNodeRenderers,
67
+ options,
68
+ onLinkClick,
69
+ onCitationClick,
70
+ children: content
71
+ });
72
+ }
73
+ StreamingMarkdownDefaultRenderer.displayName = "StreamingMarkdownDefaultRenderer";
74
+
75
+ //#endregion
76
+ //#region src/lib/shallow-stable-ref.ts
77
+ /**
78
+ * Shallow equality comparison for objects.
79
+ */
80
+ function shallowEqual(obj1, obj2) {
81
+ const keys1 = Object.keys(obj1);
82
+ const keys2 = Object.keys(obj2);
83
+ if (keys1.length !== keys2.length) return false;
84
+ for (const key of keys1) if (obj1[key] !== obj2[key]) return false;
85
+ return true;
86
+ }
87
+ /**
88
+ * Returns true only for plain JS objects (`{}`), excluding arrays, Dates,
89
+ * class instances, and other exotic objects that happen to have typeof "object".
90
+ */
91
+ function isPlainObject(obj) {
92
+ return obj !== null && typeof obj === "object" && Object.prototype.toString.call(obj) === "[object Object]";
93
+ }
94
+ /**
95
+ * Returns the same reference as long as the value is shallowly equal to the
96
+ * previous render's value.
97
+ *
98
+ * - Identical references bail out immediately (O(1)).
99
+ * - Plain objects ({}) are shallow-compared key-by-key.
100
+ * - Arrays, Dates, class instances, functions, and primitives are compared by
101
+ * reference only — shallowEqual is never called on non-plain objects, which
102
+ * avoids incorrect equality for e.g. [1,2] vs [1,2] (different arrays).
103
+ *
104
+ * Typical use: stabilize inline slot props so MemoizedSlotWrapper's shallow
105
+ * equality check isn't defeated by a new object reference on every render.
106
+ */
107
+ function useShallowStableRef(value) {
108
+ const ref = (0, react.useRef)(value);
109
+ if (ref.current === value) return ref.current;
110
+ if (isPlainObject(ref.current) && isPlainObject(value)) {
111
+ if (shallowEqual(ref.current, value)) return ref.current;
112
+ }
113
+ ref.current = value;
114
+ return ref.current;
115
+ }
116
+
117
+ //#endregion
118
+ //#region src/providers/CopilotChatConfigurationProvider.tsx
119
+ const CopilotChatDefaultLabels = {
120
+ chatInputPlaceholder: "Type a message...",
121
+ chatInputToolbarStartTranscribeButtonLabel: "Transcribe",
122
+ chatInputToolbarCancelTranscribeButtonLabel: "Cancel",
123
+ chatInputToolbarFinishTranscribeButtonLabel: "Finish",
124
+ chatInputToolbarAddButtonLabel: "Add attachments",
125
+ chatInputToolbarToolsButtonLabel: "Tools",
126
+ chatInputToolbarSendButtonLabel: "Send message",
127
+ chatInputToolbarStopButtonLabel: "Stop",
128
+ assistantMessageToolbarCopyCodeLabel: "Copy",
129
+ assistantMessageToolbarCopyCodeCopiedLabel: "Copied",
130
+ assistantMessageToolbarCopyMessageLabel: "Copy",
131
+ assistantMessageToolbarInspectorLabel: "View in Inspector",
132
+ assistantMessageToolbarInspectorDescription: "Open this message in the Inspector",
133
+ assistantMessageToolbarInspectorLocalOnlyLabel: "Local only",
134
+ assistantMessageToolbarInspectorLocalOnlyDescription: "Only visible on localhost or loopback hosts in development. Never shown in production.",
135
+ assistantMessageToolbarInspectorTitle: "CopilotKit Inspector",
136
+ assistantMessageToolbarInspectorHideLabel: "Hide this icon",
137
+ assistantMessageToolbarInspectorHideDescription: "Until you reload this page",
138
+ assistantMessageToolbarThumbsUpLabel: "Good response",
139
+ assistantMessageToolbarThumbsDownLabel: "Bad response",
140
+ assistantMessageFeedbackCommentPlaceholder: "Add a comment (optional)",
141
+ assistantMessageFeedbackCommentSubmitLabel: "Send comment",
142
+ assistantMessageToolbarReadAloudLabel: "Read aloud",
143
+ assistantMessageToolbarRegenerateLabel: "Regenerate",
144
+ userMessageToolbarCopyMessageLabel: "Copy",
145
+ userMessageToolbarEditMessageLabel: "Edit",
146
+ userMessageToolbarPreviousBranchLabel: "Previous branch",
147
+ userMessageToolbarNextBranchLabel: "Next branch",
148
+ chatDisclaimerText: "AI can make mistakes. Please verify important information.",
149
+ chatToggleOpenLabel: "Open chat",
150
+ chatToggleCloseLabel: "Close chat",
151
+ chatScrollToBottomLabel: "Scroll to bottom",
152
+ modalHeaderTitle: "CopilotKit Chat",
153
+ welcomeMessageText: "How can I help you today?",
154
+ reasoningMessageThinkingLabel: "Thinking…",
155
+ chatInputSlashMenuLabel: "Slash commands",
156
+ chatInputSlashMenuEmptyText: "No commands found",
157
+ attachmentRemoveButtonLabel: "Remove attachment",
158
+ attachmentPlayVideoButtonLabel: "Play video",
159
+ attachmentPreviewCloseButtonLabel: "Close preview",
160
+ modalHeaderCloseButtonLabel: "Close",
161
+ modalHeaderThreadsButtonLabel: "Open threads",
162
+ sidebarLabel: "Copilot chat sidebar"
163
+ };
164
+ /**
165
+ * Mobile breakpoint below which the chat modal and the thread-list drawer are
166
+ * mutually exclusive. At or above this width both surfaces may coexist. This
167
+ * mirrors the `(max-width: 767px)` / `(min-width: 768px)` split already used by
168
+ * CopilotChatInput and CopilotSidebarView.
169
+ */
170
+ const MOBILE_MAX_WIDTH_PX = 767;
171
+ /**
172
+ * Reports whether the current viewport is in the mobile range (`<768px`), where
173
+ * the chat modal and drawer must not be open simultaneously. SSR-safe and
174
+ * defensive against environments without `matchMedia` (treated as desktop, so
175
+ * no mutual-exclusion constraint is applied).
176
+ *
177
+ * @returns `true` when the viewport is mobile-width, `false` otherwise.
178
+ */
179
+ function isMobileViewport() {
180
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
181
+ return window.matchMedia(`(max-width: ${MOBILE_MAX_WIDTH_PX}px)`).matches;
182
+ }
183
+ const CopilotChatConfiguration = (0, react.createContext)(null);
184
+ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId, hasExplicitThreadId, isModalDefaultOpen }) => {
185
+ const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
186
+ const stableLabels = useShallowStableRef(labels);
187
+ const mergedLabels = (0, react.useMemo)(() => ({
188
+ ...CopilotChatDefaultLabels,
189
+ ...parentConfig?.labels,
190
+ ...stableLabels
191
+ }), [stableLabels, parentConfig?.labels]);
192
+ const providerAgentId = (0, _copilotkit_react_core_context.useDefaultAgentId)();
193
+ const resolvedAgentId = agentId ?? parentConfig?.agentId ?? providerAgentId ?? _copilotkit_shared.DEFAULT_AGENT_ID;
194
+ const threadIdPropIsAuthoritative = threadId !== void 0 && hasExplicitThreadId !== false;
195
+ const isThreadIdControlled = threadIdPropIsAuthoritative;
196
+ const [activeThreadOverride, setActiveThreadOverride] = (0, react.useState)(null);
197
+ const resolvedThreadId = (0, react.useMemo)(() => {
198
+ if (threadIdPropIsAuthoritative) return threadId;
199
+ if (activeThreadOverride) return activeThreadOverride.threadId;
200
+ if (parentConfig?.threadId) return parentConfig.threadId;
201
+ if (threadId) return threadId;
202
+ return (0, _copilotkit_shared.randomUUID)();
203
+ }, [
204
+ threadIdPropIsAuthoritative,
205
+ threadId,
206
+ parentConfig?.threadId,
207
+ activeThreadOverride
208
+ ]);
209
+ const copilotkit = (0, react.useContext)(_copilotkit_react_core_context.CopilotKitContext)?.copilotkit;
210
+ const openThreadRef = (0, react.useRef)(null);
211
+ const latestThreadIdRef = (0, react.useRef)(resolvedThreadId);
212
+ latestThreadIdRef.current = resolvedThreadId;
213
+ (0, react.useEffect)(() => {
214
+ if (copilotkit === void 0) return;
215
+ const registration = copilotkit.registerOpenThread({
216
+ agentId: resolvedAgentId,
217
+ threadId: latestThreadIdRef.current
218
+ });
219
+ openThreadRef.current = registration;
220
+ return () => {
221
+ registration.unregister();
222
+ openThreadRef.current = null;
223
+ };
224
+ }, [copilotkit, resolvedAgentId]);
225
+ (0, react.useEffect)(() => {
226
+ openThreadRef.current?.update(resolvedThreadId);
227
+ }, [resolvedThreadId]);
228
+ const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
229
+ const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen ?? true);
230
+ const hasExplicitDefault = isModalDefaultOpen !== void 0;
231
+ const setAndSync = (0, react.useCallback)((open) => {
232
+ setInternalModalOpen(open);
233
+ parentConfig?.setModalOpen(open);
234
+ }, [parentConfig?.setModalOpen]);
235
+ const isMounted = (0, react.useRef)(false);
236
+ (0, react.useEffect)(() => {
237
+ if (!hasExplicitDefault) return;
238
+ if (!isMounted.current) {
239
+ isMounted.current = true;
240
+ return;
241
+ }
242
+ if (parentConfig?.isModalOpen === void 0) return;
243
+ setInternalModalOpen(parentConfig.isModalOpen);
244
+ }, [parentConfig?.isModalOpen, hasExplicitDefault]);
245
+ const resolvedIsModalOpen = hasExplicitDefault ? internalModalOpen : parentConfig?.isModalOpen ?? internalModalOpen;
246
+ const resolvedSetModalOpen = hasExplicitDefault ? setAndSync : parentConfig?.setModalOpen ?? setInternalModalOpen;
247
+ const [ownDrawerOpen, setOwnDrawerOpen] = (0, react.useState)(false);
248
+ const [ownDrawerCount, setOwnDrawerCount] = (0, react.useState)(0);
249
+ const modalCloseRef = (0, react.useRef)(() => {});
250
+ modalCloseRef.current = resolvedSetModalOpen;
251
+ const registeredModalClosersRef = (0, react.useRef)([]);
252
+ const ownRegisterModalCloser = (0, react.useCallback)((closeModal) => {
253
+ registeredModalClosersRef.current.push(closeModal);
254
+ return () => {
255
+ registeredModalClosersRef.current = registeredModalClosersRef.current.filter((entry) => entry !== closeModal);
256
+ };
257
+ }, []);
258
+ const ownSetDrawerOpen = (0, react.useCallback)((open) => {
259
+ setOwnDrawerOpen(open);
260
+ if (open && isMobileViewport()) {
261
+ const registered = registeredModalClosersRef.current;
262
+ (registered.length > 0 ? registered[registered.length - 1] : modalCloseRef.current)(false);
263
+ }
264
+ }, []);
265
+ const ownRegisterDrawer = (0, react.useCallback)(() => {
266
+ setOwnDrawerCount((count) => count + 1);
267
+ return () => {
268
+ setOwnDrawerCount((count) => Math.max(0, count - 1));
269
+ };
270
+ }, []);
271
+ const resolvedDrawerOpen = parentConfig ? parentConfig.drawerOpen : ownDrawerOpen;
272
+ const resolvedSetDrawerOpen = parentConfig ? parentConfig.setDrawerOpen : ownSetDrawerOpen;
273
+ const resolvedDrawerRegistered = parentConfig ? parentConfig.drawerRegistered : ownDrawerCount > 0;
274
+ const resolvedRegisterDrawer = parentConfig ? parentConfig.registerDrawer : ownRegisterDrawer;
275
+ const resolvedRegisterModalCloser = parentConfig ? parentConfig.ɵregisterModalCloser : ownRegisterModalCloser;
276
+ (0, react.useEffect)(() => {
277
+ if (!hasExplicitDefault) return;
278
+ return resolvedRegisterModalCloser(resolvedSetModalOpen);
279
+ }, [
280
+ hasExplicitDefault,
281
+ resolvedRegisterModalCloser,
282
+ resolvedSetModalOpen
283
+ ]);
284
+ const isThreadIdControlledRef = (0, react.useRef)(isThreadIdControlled);
285
+ isThreadIdControlledRef.current = isThreadIdControlled;
286
+ const ownSetActiveThreadId = (0, react.useCallback)((id, options) => {
287
+ setActiveThreadOverride({
288
+ threadId: id,
289
+ explicit: options?.explicit ?? true
290
+ });
291
+ }, []);
292
+ const ownStartNewThread = (0, react.useCallback)(() => {
293
+ setActiveThreadOverride({
294
+ threadId: (0, _copilotkit_shared.randomUUID)(),
295
+ explicit: false
296
+ });
297
+ }, []);
298
+ const parentSetActiveThreadId = parentConfig?.setActiveThreadId;
299
+ const parentStartNewThread = parentConfig?.startNewThread;
300
+ const resolvedSetActiveThreadId = (0, react.useCallback)((id, options) => {
301
+ if (isThreadIdControlledRef.current) {
302
+ console.warn("[CopilotKit] Ignoring setActiveThreadId(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
303
+ return;
304
+ }
305
+ if (parentSetActiveThreadId) {
306
+ parentSetActiveThreadId(id, options);
307
+ return;
308
+ }
309
+ ownSetActiveThreadId(id, options);
310
+ }, [parentSetActiveThreadId, ownSetActiveThreadId]);
311
+ const resolvedStartNewThread = (0, react.useCallback)(() => {
312
+ if (isThreadIdControlledRef.current) {
313
+ console.warn("[CopilotKit] Ignoring startNewThread(): threadId is controlled via the `threadId` prop on CopilotChatConfigurationProvider.");
314
+ return;
315
+ }
316
+ if (parentStartNewThread) {
317
+ parentStartNewThread();
318
+ return;
319
+ }
320
+ ownStartNewThread();
321
+ }, [parentStartNewThread, ownStartNewThread]);
322
+ const setModalOpenWithDrawerExclusion = (0, react.useCallback)((open) => {
323
+ if (open && isMobileViewport()) resolvedSetDrawerOpen(false);
324
+ resolvedSetModalOpen(open);
325
+ }, [resolvedSetModalOpen, resolvedSetDrawerOpen]);
326
+ const configurationValue = (0, react.useMemo)(() => ({
327
+ labels: mergedLabels,
328
+ agentId: resolvedAgentId,
329
+ threadId: resolvedThreadId,
330
+ hasExplicitThreadId: resolvedHasExplicitThreadId,
331
+ isModalOpen: resolvedIsModalOpen,
332
+ setModalOpen: setModalOpenWithDrawerExclusion,
333
+ drawerOpen: resolvedDrawerOpen,
334
+ setDrawerOpen: resolvedSetDrawerOpen,
335
+ drawerRegistered: resolvedDrawerRegistered,
336
+ registerDrawer: resolvedRegisterDrawer,
337
+ ɵregisterModalCloser: resolvedRegisterModalCloser,
338
+ setActiveThreadId: resolvedSetActiveThreadId,
339
+ startNewThread: resolvedStartNewThread
340
+ }), [
341
+ mergedLabels,
342
+ resolvedAgentId,
343
+ resolvedThreadId,
344
+ resolvedHasExplicitThreadId,
345
+ resolvedIsModalOpen,
346
+ setModalOpenWithDrawerExclusion,
347
+ resolvedDrawerOpen,
348
+ resolvedSetDrawerOpen,
349
+ resolvedDrawerRegistered,
350
+ resolvedRegisterDrawer,
351
+ resolvedRegisterModalCloser,
352
+ resolvedSetActiveThreadId,
353
+ resolvedStartNewThread
354
+ ]);
355
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
356
+ value: configurationValue,
357
+ children
358
+ });
359
+ };
360
+ const useCopilotChatConfiguration = () => {
361
+ return (0, react.useContext)(CopilotChatConfiguration);
362
+ };
363
+ /**
364
+ * Reports modal open/close requests to the host, and — when `open` is
365
+ * supplied — makes the modal state of an already-established chat
366
+ * configuration **controlled** for the subtree it wraps.
367
+ *
368
+ * This is deliberately a scope component rather than another mode inside
369
+ * {@link CopilotChatConfigurationProvider}. The provider resolves modal state
370
+ * across a nested chain (own state, parent sync, drawer mutual-exclusion, the
371
+ * modal-closer registry); a controlled branch inside that resolution would add
372
+ * a fourth interacting mode. Overriding the context for the subtree instead
373
+ * leaves every one of those paths untouched:
374
+ *
375
+ * - `isModalOpen` is replaced with the host's `open`, so the rendered surface
376
+ * follows the prop from the very first frame (no open-then-close flash).
377
+ * - `setModalOpen` still calls the underlying setter, so the existing
378
+ * parent-sync and drawer mutual-exclusion side effects continue to run, and
379
+ * *then* reports the request through `onOpenChange`.
380
+ * - The wrapped setter is registered as the modal closer, so the drawer's
381
+ * mobile mutual-exclusion reaches the host instead of silently flipping
382
+ * state that nothing displays.
383
+ *
384
+ * A host that supplies `open` and ignores `onOpenChange` gets a modal pinned
385
+ * to `open`, which is the standard controlled-component contract. A host that
386
+ * supplies only `onOpenChange` is notified while the modal keeps managing
387
+ * itself.
388
+ *
389
+ * Renders `children` unchanged when no chat configuration is in scope.
390
+ */
391
+ const ControlledModalOpenScope = ({ children, open, onOpenChange }) => {
392
+ const parentConfig = (0, react.useContext)(CopilotChatConfiguration);
393
+ const parentSetModalOpen = parentConfig?.setModalOpen;
394
+ const registerModalCloser = parentConfig?.ɵregisterModalCloser;
395
+ const setModalOpen = (0, react.useCallback)((next) => {
396
+ parentSetModalOpen?.(next);
397
+ onOpenChange?.(next);
398
+ }, [parentSetModalOpen, onOpenChange]);
399
+ (0, react.useEffect)(() => {
400
+ if (!registerModalCloser) return;
401
+ return registerModalCloser(setModalOpen);
402
+ }, [registerModalCloser, setModalOpen]);
403
+ const configurationValue = (0, react.useMemo)(() => parentConfig ? {
404
+ ...parentConfig,
405
+ isModalOpen: open ?? parentConfig.isModalOpen,
406
+ setModalOpen
407
+ } : null, [
408
+ parentConfig,
409
+ open,
410
+ setModalOpen
411
+ ]);
412
+ if (!configurationValue) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children });
413
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(CopilotChatConfiguration.Provider, {
414
+ value: configurationValue,
415
+ children
416
+ });
417
+ };
418
+ ControlledModalOpenScope.displayName = "ControlledModalOpenScope";
419
+
420
+ //#endregion
421
+ //#region src/lib/slots.tsx
422
+ /**
423
+ * Check if a value is a React component type (function, class, forwardRef, memo, etc.)
424
+ */
425
+ function isReactComponentType(value) {
426
+ if (typeof value === "function") return true;
427
+ if (value && typeof value === "object" && "$$typeof" in value && !react.default.isValidElement(value)) return true;
428
+ return false;
429
+ }
430
+ /**
431
+ * Internal function to render a slot value as a React element (non-memoized).
432
+ */
433
+ function renderSlotElement(slot, DefaultComponent, props) {
434
+ if (typeof slot === "string") {
435
+ const existingClassName = props.className;
436
+ return react.default.createElement(DefaultComponent, {
437
+ ...props,
438
+ className: (0, tailwind_merge.twMerge)(existingClassName, slot)
439
+ });
440
+ }
441
+ if (isReactComponentType(slot)) return react.default.createElement(slot, props);
442
+ if (slot && typeof slot === "object" && !react.default.isValidElement(slot)) return react.default.createElement(DefaultComponent, {
443
+ ...props,
444
+ ...slot
445
+ });
446
+ return react.default.createElement(DefaultComponent, props);
447
+ }
448
+ /**
449
+ * Internal memoized wrapper component for renderSlot.
450
+ * Uses forwardRef to support ref forwarding.
451
+ */
452
+ const MemoizedSlotWrapper = react.default.memo(react.default.forwardRef(function MemoizedSlotWrapper(props, ref) {
453
+ const { $slot, $component, ...rest } = props;
454
+ return renderSlotElement($slot, $component, ref !== null ? {
455
+ ...rest,
456
+ ref
457
+ } : rest);
458
+ }), (prev, next) => {
459
+ if (prev.$slot !== next.$slot) return false;
460
+ if (prev.$component !== next.$component) return false;
461
+ const { $slot: _ps, $component: _pc, ...prevRest } = prev;
462
+ const { $slot: _ns, $component: _nc, ...nextRest } = next;
463
+ return shallowEqual(prevRest, nextRest);
464
+ });
465
+ /**
466
+ * Renders a slot value as a memoized React element.
467
+ * Automatically prevents unnecessary re-renders using shallow prop comparison.
468
+ * Supports ref forwarding.
469
+ *
470
+ * @example
471
+ * renderSlot(customInput, CopilotChatInput, { onSubmit: handleSubmit })
472
+ */
473
+ function renderSlot(slot, DefaultComponent, props) {
474
+ return react.default.createElement(MemoizedSlotWrapper, {
475
+ ...props,
476
+ $slot: slot,
477
+ $component: DefaultComponent
478
+ });
479
+ }
480
+
481
+ //#endregion
482
+ //#region src/providers/MarkdownRendererContext.tsx
483
+ const MarkdownRendererContext = (0, react.createContext)(void 0);
484
+ const MarkdownRendererProvider = ({ renderer, children }) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownRendererContext.Provider, {
485
+ value: renderer,
486
+ children
487
+ });
488
+ /**
489
+ * The markdown renderer set at the provider level, or `undefined` when none was
490
+ * supplied. Message components fall back to the built-in
491
+ * `StreamingMarkdownDefaultRenderer` (via `CopilotChatAssistantMessage.MarkdownRenderer`)
492
+ * when this is `undefined`.
493
+ */
494
+ function useMarkdownRenderer() {
495
+ return (0, react.useContext)(MarkdownRendererContext);
496
+ }
497
+
498
+ //#endregion
499
+ //#region src/types/defineToolCallRenderer.ts
500
+ function defineToolCallRenderer(def) {
501
+ const argsSchema = def.name === "*" && !def.args ? zod.z.any() : def.args;
502
+ return {
503
+ name: def.name,
504
+ args: argsSchema,
505
+ render: def.render,
506
+ ...def.agentId ? { agentId: def.agentId } : {},
507
+ ...def.group ? { group: true } : {}
508
+ };
509
+ }
510
+
511
+ //#endregion
512
+ //#region src/generative-ui/json-schema.ts
513
+ /**
514
+ * JSON Schema for a Standard Schema (zod v3 via zod-to-json-schema),
515
+ * inlined, no `$schema`. A prop marked by `child()` or `childList()`
516
+ * becomes an A2UI `$ref` to `ComponentId` or `ChildList`.
517
+ */
518
+ function toJsonSchema(schema) {
519
+ const { $schema: _omit, ...rest } = (0, _copilotkit_shared.schemaToJsonSchema)(schema, { zodToJsonSchema: (s) => (0, zod_to_json_schema.zodToJsonSchema)(s, { $refStrategy: "none" }) });
520
+ return (0, _copilotkit_shared.applyChildRefMarks)(rest);
521
+ }
522
+
523
+ //#endregion
524
+ //#region src/generative-ui/catalog.ts
525
+ /** The A2UI component envelope: `id`, `component`, `catalogId`, `accessibility`, `metadata`. */
526
+ const RESERVED_KEYS = new Set([
527
+ "id",
528
+ "component",
529
+ ..._copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS
530
+ ]);
531
+ /** The id of the catalog that declared each component, for the inspector. */
532
+ const componentCatalogs = /* @__PURE__ */ new WeakMap();
533
+ /**
534
+ * The id of the catalog that declared each component of `ui`. A component
535
+ * from `extends` keeps the id of its base. Not exported from the package.
536
+ */
537
+ function componentCatalogIds(ui) {
538
+ return componentCatalogs.get(ui) ?? /* @__PURE__ */ new Map();
539
+ }
540
+ /**
541
+ * The catalogs that an operation can name: the id of `ui`, then the ids of
542
+ * the catalogs in its `extends` that declared a component. Not exported
543
+ * from the package.
544
+ */
545
+ function catalogIdsOf(ui) {
546
+ const declared = componentCatalogs.get(ui)?.values() ?? [];
547
+ return [...new Set([ui.id, ...declared])];
548
+ }
549
+ /**
550
+ * Experimental. Declares the components the model can render, the app state
551
+ * they read, and the functions they call.
552
+ *
553
+ * - A prop with the name of a top-level state key is bound to that state.
554
+ * - `bind: { prop: (state, props) => value }` binds a prop to a selector.
555
+ * - An event binds to the function with its name, else to the name without
556
+ * `on` (`onAddToCart` calls `addToCart`).
557
+ * - `writable: ["value"]` gives the component a `setValue` prop. See
558
+ * `GenerativeUIComponentDefinition.writable`.
559
+ *
560
+ * The model does not see bound props or matched events.
561
+ *
562
+ * @param config - `id`, then optional `extends`, `state`, `functions` and
563
+ * `overrides`, then `components`. Put `state` before `components`, so the selectors
564
+ * get typed state.
565
+ * @throws Error when a name comes from two places, an override names no
566
+ * component of the bases, `props` is not an object
567
+ * schema with a JSON Schema, a key is reserved or used
568
+ * twice on a component, an event matches two functions, an unmatched event
569
+ * has no `parameters`, a `bind` key is not a prop, a `writable` key is not
570
+ * a prop or is a bound prop, or a setter name is already a key of the
571
+ * component. Also throws when `parameterOrder` contains duplicate or unknown
572
+ * keys, or an ordered component declares integer-index keys whose JSON object
573
+ * enumeration order cannot be controlled.
574
+ *
575
+ * @example
576
+ * ```ts
577
+ * const ui = createGenerativeUI({
578
+ * id: "acme/store@1",
579
+ * state: { cart: cartSchema },
580
+ * functions: { addToCart: { parameters: z.object({ productId: z.string() }) } },
581
+ * components: {
582
+ * CartSummary: {
583
+ * component: CartSummary,
584
+ * props: z.object({ count: z.number() }),
585
+ * bind: { count: (state) => state.cart.count },
586
+ * },
587
+ * },
588
+ * });
589
+ * ```
590
+ */
591
+ function createGenerativeUI(config) {
592
+ return buildGenerativeUI(config);
593
+ }
594
+ function buildGenerativeUI(config) {
595
+ const where = `generative UI "${config.id}"`;
596
+ const state = /* @__PURE__ */ new Map();
597
+ const functions = /* @__PURE__ */ new Map();
598
+ const definitions = /* @__PURE__ */ new Map();
599
+ const catalogs = /* @__PURE__ */ new Map();
600
+ function add(map, kind, name, value) {
601
+ if (map.has(name)) throw new Error(`[generativeUI] ${kind} "${name}" is defined more than once in ${where}.`);
602
+ map.set(name, value);
603
+ }
604
+ const bases = config.extends ?? [];
605
+ for (const base of bases) {
606
+ for (const [name, schema] of base.state) add(state, "State key", name, schema);
607
+ for (const [name, fn] of base.functions) add(functions, "Function", name, fn);
608
+ const baseCatalogs = componentCatalogIds(base);
609
+ for (const [name, component] of base.components) {
610
+ add(definitions, "Component", name, component);
611
+ catalogs.set(name, baseCatalogs.get(name) ?? base.id);
612
+ }
613
+ }
614
+ for (const [name, override] of Object.entries(config.overrides ?? {})) {
615
+ const base = definitions.get(name);
616
+ if (!base) throw new Error(`[generativeUI] Override "${name}" is not a component of the bases of ${where}.`);
617
+ definitions.set(name, {
618
+ ...base,
619
+ component: override.component
620
+ });
621
+ }
622
+ for (const [name, schema] of Object.entries(config.state ?? {})) add(state, "State key", name, schema);
623
+ for (const [name, fn] of Object.entries(config.functions ?? {})) add(functions, "Function", name, fn);
624
+ for (const [name, fn] of functions) if (fn.requiresUserActivation === true && fn.allowedCallers !== void 0 && fn.allowedCallers !== "rendererOnly") throw new Error(`[generativeUI] Function "${name}" in ${where} requires user activation, so its allowedCallers must be "rendererOnly", not "${fn.allowedCallers}".`);
625
+ for (const [name, component] of Object.entries(config.components)) {
626
+ add(definitions, "Component", name, component);
627
+ catalogs.set(name, config.id);
628
+ }
629
+ const components = /* @__PURE__ */ new Map();
630
+ const manifestComponents = {};
631
+ for (const [name, definition] of definitions) {
632
+ const { component, manifest } = resolveComponent(name, definition, {
633
+ state,
634
+ functions,
635
+ where
636
+ });
637
+ components.set(name, component);
638
+ manifestComponents[name] = manifest;
639
+ }
640
+ return withOmit({
641
+ id: config.id,
642
+ state,
643
+ functions,
644
+ components,
645
+ manifestComponents
646
+ }, catalogs);
647
+ }
648
+ /** Adds the `omit` method to the data of a generative UI. */
649
+ function withOmit(data, catalogs) {
650
+ const omit = (names) => {
651
+ for (const name of names) if (!data.components.has(name)) throw new Error(`[generativeUI] Cannot omit "${name}": it is not a component of generative UI "${data.id}".`);
652
+ const isKept = (name) => !names.includes(name);
653
+ return withOmit({
654
+ id: data.id,
655
+ state: data.state,
656
+ functions: data.functions,
657
+ components: new Map([...data.components].filter(([name]) => isKept(name))),
658
+ manifestComponents: Object.fromEntries(Object.entries(data.manifestComponents).filter(([name]) => isKept(name)))
659
+ }, catalogs);
660
+ };
661
+ const ui = {
662
+ ...data,
663
+ omit
664
+ };
665
+ componentCatalogs.set(ui, catalogs);
666
+ return ui;
667
+ }
668
+ /** Builds the selectors, the event map and the manifest of one component. */
669
+ function resolveComponent(name, definition, context) {
670
+ const propsJson = propsJsonSchema(name, definition, context.where);
671
+ const propKeys = Object.keys(propsJson.properties);
672
+ assertDisjointKeys(name, definition, propKeys);
673
+ assertParameterOrder(name, definition, propKeys);
674
+ const selectors = {};
675
+ for (const key of propKeys) if (context.state.has(key)) selectors[key] = (state) => state[key];
676
+ const bind = definition.bind ?? {};
677
+ for (const [key, selector] of Object.entries(bind)) {
678
+ if (!propKeys.includes(key)) throw new Error(`[generativeUI] bind key "${key}" is not a prop of component "${name}" in ${context.where}.`);
679
+ selectors[key] = selector;
680
+ }
681
+ const eventFunctions = {};
682
+ const modelEvents = {};
683
+ const events = definition.events ?? {};
684
+ for (const [eventName, event] of Object.entries(events)) {
685
+ const functionName = matchFunction(eventName, name, context);
686
+ if (functionName !== void 0) {
687
+ const matched = context.functions.get(functionName);
688
+ if (matched && !(0, _copilotkit_shared.functionCallers)(matched).renderer) throw new Error(`[generativeUI] Event "${eventName}" of component "${name}" matches function "${functionName}", which the UI cannot call (allowedCallers "agentOnly") in ${context.where}.`);
689
+ eventFunctions[eventName] = functionName;
690
+ continue;
691
+ }
692
+ if (!event.parameters) throw new Error(`[generativeUI] Event "${eventName}" of component "${name}" matches no function in ${context.where}, so it needs "parameters".`);
693
+ modelEvents[eventName] = {
694
+ ...event.description ? { description: event.description } : {},
695
+ parameters: toJsonSchema(event.parameters)
696
+ };
697
+ }
698
+ assertWritable(name, definition, propKeys, selectors, context.where);
699
+ return {
700
+ component: {
701
+ component: definition.component,
702
+ description: definition.description,
703
+ parameterOrder: definition.parameterOrder?.slice(),
704
+ props: definition.props,
705
+ bind: definition.bind,
706
+ events: definition.events,
707
+ slots: definition.slots,
708
+ writable: definition.writable,
709
+ accessibility: definition.accessibility ?? "wrapper",
710
+ selectors,
711
+ eventFunctions,
712
+ propKeys,
713
+ childRefs: (0, _copilotkit_shared.collectChildRefs)(propsJson)
714
+ },
715
+ manifest: toManifest(definition, modelPropsJsonSchema(propsJson, selectors), modelEvents)
716
+ };
717
+ }
718
+ /** The JSON Schema of `props`. A component without `props` has none. */
719
+ function propsJsonSchema(name, definition, where) {
720
+ if (!definition.props) return {
721
+ type: "object",
722
+ properties: {}
723
+ };
724
+ const json = toJsonSchema(definition.props);
725
+ const { properties } = json;
726
+ if (!(typeof properties === "object" && properties !== null && !Array.isArray(properties))) throw new Error(`[generativeUI] the props of component "${name}" in ${where} must be an object schema.`);
727
+ return json;
728
+ }
729
+ /**
730
+ * What the model sees of the props: the JSON Schema without the bound props,
731
+ * and with no other keys allowed.
732
+ */
733
+ function modelPropsJsonSchema(json, bound) {
734
+ const isModelKey = (key) => !Object.hasOwn(bound, key);
735
+ const { properties, required, additionalProperties: _additionalProperties, ...rest } = json;
736
+ const modelRequired = Array.isArray(required) ? required.filter((key) => isModelKey(String(key))) : [];
737
+ return {
738
+ ...rest,
739
+ type: "object",
740
+ properties: Object.fromEntries(Object.entries(properties).filter(([key]) => isModelKey(key))),
741
+ ...modelRequired.length > 0 ? { required: modelRequired } : {},
742
+ additionalProperties: false
743
+ };
744
+ }
745
+ /** `onAddToCart` to `addToCart`. `undefined` when the name has no `on` prefix. */
746
+ function withoutOnPrefix(eventName) {
747
+ if (!(eventName.length > 2 && eventName.startsWith("on"))) return void 0;
748
+ return eventName.charAt(2).toLowerCase() + eventName.slice(3);
749
+ }
750
+ /** The declared function an event calls, or `undefined` when none matches. */
751
+ function matchFunction(eventName, componentName, context) {
752
+ const exact = context.functions.has(eventName) ? eventName : void 0;
753
+ const stripped = withoutOnPrefix(eventName);
754
+ const fromPrefix = stripped !== void 0 && context.functions.has(stripped) ? stripped : void 0;
755
+ if (exact !== void 0 && fromPrefix !== void 0) throw new Error(`[generativeUI] Event "${eventName}" of component "${componentName}" matches two functions, "${exact}" and "${fromPrefix}", in ${context.where}.`);
756
+ return exact ?? fromPrefix;
757
+ }
758
+ /** The setter prop of a writable prop: `value` gives `setValue`. */
759
+ function setterNameOf(key) {
760
+ return `set${key.charAt(0).toUpperCase()}${key.slice(1)}`;
761
+ }
762
+ /** Why a `writable` key is not valid, or `undefined` when it is valid. */
763
+ function writableProblem(key, definition, propKeys, selectors) {
764
+ if (Object.hasOwn(definition.events ?? {}, key)) return "an event";
765
+ if (Object.hasOwn(definition.slots ?? {}, key)) return "a slot";
766
+ if (!propKeys.includes(key)) return "not a prop";
767
+ if (Object.hasOwn(selectors, key)) return "a bound prop";
768
+ }
769
+ function assertWritable(name, definition, propKeys, selectors, where) {
770
+ const writable = definition.writable ?? [];
771
+ const keys = new Set([
772
+ ...propKeys,
773
+ ...Object.keys(definition.events ?? {}),
774
+ ...Object.keys(definition.slots ?? {})
775
+ ]);
776
+ for (const key of writable) {
777
+ const problem = writableProblem(key, definition, propKeys, selectors);
778
+ if (problem) throw new Error(`[generativeUI] writable key "${key}" of component "${name}" is ${problem} in ${where}.`);
779
+ const setter = setterNameOf(key);
780
+ if (keys.has(setter)) throw new Error(`[generativeUI] the setter "${setter}" of writable key "${key}" is already a key of component "${name}" in ${where}.`);
781
+ }
782
+ }
783
+ function assertDisjointKeys(name, definition, propKeys) {
784
+ const seen = /* @__PURE__ */ new Set();
785
+ const keys = [
786
+ ...propKeys,
787
+ ...Object.keys(definition.events ?? {}),
788
+ ...Object.keys(definition.slots ?? {})
789
+ ];
790
+ for (const key of keys) {
791
+ if (RESERVED_KEYS.has(key)) throw new Error(`[generativeUI] "${key}" is reserved by A2UI and cannot be a prop, event or slot of component "${name}".`);
792
+ if (seen.has(key)) throw new Error(`[generativeUI] "${key}" is declared as more than one of prop, event, slot on component "${name}".`);
793
+ seen.add(key);
794
+ }
795
+ }
796
+ function assertParameterOrder(name, definition, propKeys) {
797
+ const order = definition.parameterOrder;
798
+ if (order === void 0) return;
799
+ const keys = new Set([
800
+ ...propKeys,
801
+ ...Object.keys(definition.slots ?? {}),
802
+ ...Object.keys(definition.events ?? {})
803
+ ]);
804
+ if ([...keys].some((key) => {
805
+ const index = Number(key);
806
+ return Number.isInteger(index) && index >= 0 && index < 2 ** 32 - 1 && String(index) === key;
807
+ })) throw new Error(`[generativeUI] Component "${name}" with parameterOrder cannot declare integer-index keys: JSON object enumeration sorts them numerically before other keys, ignoring the requested order.`);
808
+ if (!Array.isArray(order) || new Set(order).size !== order.length || order.some((key) => !keys.has(key))) throw new Error(`[generativeUI] parameterOrder of component "${name}" must contain unique declared prop, slot or event names.`);
809
+ }
810
+ function toManifest(definition, modelProps, modelEvents) {
811
+ const manifest = { props: modelProps };
812
+ if (definition.description) manifest.description = definition.description;
813
+ if (Object.keys(modelEvents).length > 0) manifest.events = modelEvents;
814
+ if (definition.slots) manifest.slots = { ...definition.slots };
815
+ if (definition.parameterOrder !== void 0) {
816
+ const visible = new Set([
817
+ ...Object.keys(modelProps.properties ?? {}),
818
+ ...Object.keys(definition.slots ?? {}),
819
+ ...Object.keys(modelEvents)
820
+ ]);
821
+ manifest.parameterOrder = [...new Set([...definition.parameterOrder.filter((key) => visible.has(key)), ...visible])];
822
+ }
823
+ return manifest;
824
+ }
825
+
826
+ //#endregion
827
+ //#region src/generative-ui/is-record.ts
828
+ /** True for a plain object: not null, not an array. Internal, not exported. */
829
+ function isRecord(value) {
830
+ return typeof value === "object" && value !== null && !Array.isArray(value);
831
+ }
832
+
833
+ //#endregion
834
+ //#region src/generative-ui/errors.ts
835
+ var GenerativeUIError = class extends Error {
836
+ constructor(code, message) {
837
+ super(message);
838
+ this.name = "GenerativeUIError";
839
+ this.code = code;
840
+ }
841
+ };
842
+
843
+ //#endregion
844
+ //#region src/generative-ui/functions.ts
845
+ /**
846
+ * The renderer-side functions of the A2UI 1.0 basic catalog. Each one takes
847
+ * resolved args (no bindings left in them) and gives a plain value. They
848
+ * run synchronously, so a prop bound to one updates in the same render as
849
+ * the data it reads. The signatures the model sees are in
850
+ * `@copilotkit/shared` (`A2UI_BASIC_FUNCTIONS`).
851
+ */
852
+ /** Thrown for a bad call: an unknown function, bad args, or a bad value. */
853
+ var ExpressionError = class extends Error {
854
+ constructor(message) {
855
+ super(message);
856
+ this.name = "ExpressionError";
857
+ }
858
+ };
859
+ /** The boolean of a DynamicBoolean: a ValidationResult counts as `valid`. */
860
+ function truthOf(value) {
861
+ if ((0, _copilotkit_shared.isValidationResult)(value)) return value.valid;
862
+ return Boolean(value);
863
+ }
864
+ const valid = () => ({ valid: true });
865
+ /** A failed result. `code` names the failure, the same for every locale. */
866
+ const invalid = (message, code) => ({
867
+ valid: false,
868
+ message,
869
+ code
870
+ });
871
+ function text(value) {
872
+ if (value === void 0 || value === null) return "";
873
+ return typeof value === "string" ? value : String(value);
874
+ }
875
+ function numberOf$1(value) {
876
+ if (typeof value === "number") return value;
877
+ if (typeof value === "string" && value.trim() !== "") return Number(value);
878
+ return NaN;
879
+ }
880
+ function optionalNumber(value, name) {
881
+ if (value === void 0 || value === null) return void 0;
882
+ const parsed = numberOf$1(value);
883
+ if (Number.isNaN(parsed)) throw new ExpressionError(`${name} must be a number`);
884
+ return parsed;
885
+ }
886
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
887
+ /** The locale of the user. `undefined` lets Intl pick the default. */
888
+ function locale() {
889
+ return typeof navigator !== "undefined" ? navigator.language : void 0;
890
+ }
891
+ function numberFormat(args, options) {
892
+ const decimals = optionalNumber(args.decimals, "decimals");
893
+ return new Intl.NumberFormat(locale(), {
894
+ ...options,
895
+ useGrouping: args.grouping !== false,
896
+ ...decimals === void 0 ? {} : {
897
+ minimumFractionDigits: decimals,
898
+ maximumFractionDigits: decimals
899
+ }
900
+ });
901
+ }
902
+ /** A date from an ISO string, a timestamp, or a Date. */
903
+ function dateOf(value) {
904
+ const date = value instanceof Date ? value : typeof value === "number" ? new Date(value) : typeof value === "string" ? new Date(/^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T00:00` : value) : void 0;
905
+ if (date === void 0 || Number.isNaN(date.getTime())) throw new ExpressionError("value must be a date");
906
+ return date;
907
+ }
908
+ const pad = (value, width) => String(value).padStart(width, "0");
909
+ /**
910
+ * A TR35 field is a run of one letter ("EEE" is one abbreviated weekday,
911
+ * not three), and text in single quotes is literal. Letters that are not
912
+ * fields stay as they are.
913
+ */
914
+ const DATE_FIELD = /([A-Za-z])\1*|'(?:[^']|'')*'/g;
915
+ function formatDatePattern(date, pattern) {
916
+ const parts = (options) => new Intl.DateTimeFormat(locale(), options).format(date);
917
+ const hours12 = date.getHours() % 12 || 12;
918
+ const numeric = (value, width) => width >= 2 ? pad(value, 2) : String(value);
919
+ return pattern.replace(DATE_FIELD, (token) => {
920
+ if (token.startsWith("'")) return token.slice(1, -1).replace(/''/g, "'");
921
+ const width = token.length;
922
+ switch (token[0]) {
923
+ case "y": return width === 2 ? pad(date.getFullYear() % 100, 2) : String(date.getFullYear());
924
+ case "M":
925
+ if (width >= 4) return parts({ month: "long" });
926
+ if (width === 3) return parts({ month: "short" });
927
+ return numeric(date.getMonth() + 1, width);
928
+ case "d": return numeric(date.getDate(), width);
929
+ case "E": return parts({ weekday: width >= 4 ? "long" : "short" });
930
+ case "H": return numeric(date.getHours(), width);
931
+ case "h": return numeric(hours12, width);
932
+ case "m": return pad(date.getMinutes(), 2);
933
+ case "s": return pad(date.getSeconds(), 2);
934
+ case "a": return date.getHours() < 12 ? "AM" : "PM";
935
+ default: return token;
936
+ }
937
+ });
938
+ }
939
+ /** Opens an http(s) URL in a new tab. Any other scheme is refused. */
940
+ function openUrlSafely(url) {
941
+ if (typeof url !== "string" || url === "") throw new ExpressionError("url must be a string");
942
+ if (typeof window === "undefined") return;
943
+ let parsed;
944
+ try {
945
+ parsed = new URL(url, window.location.href);
946
+ } catch {
947
+ throw new ExpressionError(`"${url}" is not a URL`);
948
+ }
949
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") throw new ExpressionError(`openUrl takes only http(s) URLs, not ${parsed.protocol}`);
950
+ window.open(parsed.href, "_blank", "noopener,noreferrer");
951
+ }
952
+ /**
953
+ * The basic functions, except `formatString`, which needs the resolver.
954
+ * `calc` and `series` are added by `resolve.ts`, which imports both.
955
+ */
956
+ const BASIC_FUNCTIONS = {
957
+ required: ({ value }) => {
958
+ return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0 ? invalid("Required", "required") : valid();
959
+ },
960
+ regex: ({ value, pattern }) => {
961
+ if (typeof pattern !== "string") throw new ExpressionError("pattern must be a string");
962
+ let expression;
963
+ try {
964
+ expression = new RegExp(pattern, "u");
965
+ } catch {
966
+ throw new ExpressionError(`"${pattern}" is not a regular expression`);
967
+ }
968
+ return expression.test(text(value)) ? valid() : invalid("Invalid format", "pattern");
969
+ },
970
+ length: ({ value, min, max }) => {
971
+ const size = text(value).length;
972
+ const low = optionalNumber(min, "min");
973
+ const high = optionalNumber(max, "max");
974
+ if (low !== void 0 && size < low) return invalid(`At least ${low} characters`, "tooShort");
975
+ if (high !== void 0 && size > high) return invalid(`At most ${high} characters`, "tooLong");
976
+ return valid();
977
+ },
978
+ numeric: ({ value, min, max }) => {
979
+ const parsed = numberOf$1(value);
980
+ if (Number.isNaN(parsed)) return invalid("Must be a number", "notANumber");
981
+ const low = optionalNumber(min, "min");
982
+ const high = optionalNumber(max, "max");
983
+ if (low !== void 0 && parsed < low) return invalid(`At least ${low}`, "tooSmall");
984
+ if (high !== void 0 && parsed > high) return invalid(`At most ${high}`, "tooLarge");
985
+ return valid();
986
+ },
987
+ email: ({ value }) => EMAIL.test(text(value)) ? valid() : invalid("Invalid email address", "email"),
988
+ formatNumber: (args) => {
989
+ const parsed = numberOf$1(args.value);
990
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
991
+ return numberFormat(args, {}).format(parsed);
992
+ },
993
+ formatCurrency: (args) => {
994
+ const parsed = numberOf$1(args.value);
995
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
996
+ if (typeof args.currency !== "string" || args.currency === "") throw new ExpressionError("currency must be an ISO 4217 code");
997
+ try {
998
+ return numberFormat(args, {
999
+ style: "currency",
1000
+ currency: args.currency
1001
+ }).format(parsed);
1002
+ } catch {
1003
+ throw new ExpressionError(`"${args.currency}" is not a currency code`);
1004
+ }
1005
+ },
1006
+ formatDate: ({ value, format }) => {
1007
+ if (typeof format !== "string") throw new ExpressionError("format must be a string");
1008
+ return formatDatePattern(dateOf(value), format);
1009
+ },
1010
+ pluralize: (args) => {
1011
+ const parsed = numberOf$1(args.value);
1012
+ if (Number.isNaN(parsed)) throw new ExpressionError("value must be a number");
1013
+ const category = new Intl.PluralRules(locale()).select(parsed);
1014
+ return text((parsed === 0 ? args.zero : void 0) ?? args[category] ?? args.other);
1015
+ },
1016
+ and: ({ values }) => {
1017
+ if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
1018
+ return values.every(truthOf);
1019
+ },
1020
+ or: ({ values }) => {
1021
+ if (!Array.isArray(values)) throw new ExpressionError("values must be a list");
1022
+ return values.some(truthOf);
1023
+ },
1024
+ not: ({ value }) => !truthOf(value),
1025
+ openUrl: ({ url }) => {
1026
+ openUrlSafely(url);
1027
+ }
1028
+ };
1029
+ /** True when the basic function `name` must run from a user gesture. */
1030
+ function requiresUserActivation(name) {
1031
+ return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.requiresUserActivation === true;
1032
+ }
1033
+ /** True when a basic function gives a ValidationResult. */
1034
+ function givesValidationResult(name) {
1035
+ return _copilotkit_shared.GENERATIVE_UI_FUNCTIONS[name]?.returnType === "validationResult";
1036
+ }
1037
+
1038
+ //#endregion
1039
+ //#region src/generative-ui/markdown/source.ts
1040
+ /**
1041
+ * Values by key, from the latest build. A value that a build does not use
1042
+ * is dropped at the end of that build, so the cache does not grow.
1043
+ */
1044
+ var BuildMemo = class {
1045
+ constructor() {
1046
+ this.previous = /* @__PURE__ */ new Map();
1047
+ this.current = /* @__PURE__ */ new Map();
1048
+ }
1049
+ /**
1050
+ * The value of `key`. It is computed when no earlier value is there, or
1051
+ * when `isFresh` says that the earlier value is out of date.
1052
+ */
1053
+ get(key, compute, isFresh = () => true) {
1054
+ let value = this.current.get(key) ?? this.previous.get(key);
1055
+ if (value === void 0 || !isFresh(value)) value = compute();
1056
+ this.current.set(key, value);
1057
+ return value;
1058
+ }
1059
+ endBuild() {
1060
+ this.previous = this.current;
1061
+ this.current = /* @__PURE__ */ new Map();
1062
+ }
1063
+ };
1064
+ /** The results of the builds of one thread. See `BuildMarkdownSurfacesOptions.cache`. */
1065
+ var MarkdownBuildCache = class {
1066
+ constructor() {
1067
+ this.segments = new BuildMemo();
1068
+ this.fences = new BuildMemo();
1069
+ this.drafts = new BuildMemo();
1070
+ this.readdressed = /* @__PURE__ */ new WeakMap();
1071
+ }
1072
+ endBuild() {
1073
+ this.segments.endBuild();
1074
+ this.fences.endBuild();
1075
+ this.drafts.endBuild();
1076
+ }
1077
+ };
1078
+ /** True when both lists hold the same objects in the same order. */
1079
+ function sameItems(a, b) {
1080
+ return a.length === b.length && a.every((item, index) => item === b[index]);
1081
+ }
1082
+ function isString(value) {
1083
+ return typeof value === "string";
1084
+ }
1085
+ /** The key of one fence of one message. */
1086
+ function fenceKey(messageId, fenceIndex) {
1087
+ return `${messageId}:${fenceIndex}`;
1088
+ }
1089
+ /**
1090
+ * The operations of a fence body. While the fence streams, the last object
1091
+ * can be unfinished. Of an unfinished updateComponents or createSurface, the
1092
+ * components that are complete render at once (a createSurface also keeps
1093
+ * its data model when all of it arrived). Any other unfinished object is
1094
+ * left out, because a part of a data model value can still change. A final
1095
+ * fence keeps what can be saved from an unfinished object.
1096
+ */
1097
+ function fenceOperations(text, isStreaming) {
1098
+ const parsed = (0, _copilotkit_core.extractFenceOperations)(text);
1099
+ if (!isStreaming || parsed.partialObject === null) return parsed.operations;
1100
+ const complete = (0, _copilotkit_core.extractFenceOperations)(text.slice(0, text.length - parsed.partialObject.length)).operations;
1101
+ const partial = parsed.operations.length > complete.length ? parsed.operations[parsed.operations.length - 1] : void 0;
1102
+ return partial !== void 0 && (isRecord(partial.updateComponents) || isRecord(partial.createSurface)) ? [...complete, partial] : complete;
1103
+ }
1104
+ /**
1105
+ * An inline createSurface becomes a createSurface with only its surfaceId
1106
+ * and catalog, then an updateDataModel for its data model, then an
1107
+ * updateComponents for its components. The prose lift and the split per
1108
+ * component read only updateComponents, so they then work for an inline
1109
+ * surface too. A createSurface with a data model or components of a wrong
1110
+ * shape does not change, so that validation rejects it with the reason.
1111
+ */
1112
+ function expandInlineCreate(operations) {
1113
+ return operations.flatMap((op) => {
1114
+ const create = op.createSurface;
1115
+ if (!isRecord(create)) return [op];
1116
+ const { dataModel, components, ...rest } = create;
1117
+ const hasData = isRecord(dataModel);
1118
+ const hasComponents = Array.isArray(components) && components.length > 0;
1119
+ if (!((dataModel === void 0 || hasData) && (components === void 0 || hasComponents)) || !hasData && !hasComponents) return [op];
1120
+ const { surfaceId } = create;
1121
+ const expanded = [{
1122
+ ...op,
1123
+ createSurface: rest
1124
+ }];
1125
+ if (hasData) expanded.push({
1126
+ version: op.version,
1127
+ updateDataModel: {
1128
+ surfaceId,
1129
+ path: "/",
1130
+ value: dataModel
1131
+ }
1132
+ });
1133
+ if (hasComponents) expanded.push({
1134
+ version: op.version,
1135
+ updateComponents: {
1136
+ surfaceId,
1137
+ components
1138
+ }
1139
+ });
1140
+ return expanded;
1141
+ });
1142
+ }
1143
+ /**
1144
+ * Each updateComponents becomes one operation per component, in order. The
1145
+ * complete components of a streaming line then give the same first
1146
+ * operations as the finished line, so the operation list only grows and the
1147
+ * manager never has to start the surface again.
1148
+ */
1149
+ function splitComponentUpdates(operations) {
1150
+ return operations.flatMap((op) => {
1151
+ const update = op.updateComponents;
1152
+ if (!isRecord(update) || !Array.isArray(update.components)) return [op];
1153
+ if (update.components.length <= 1) return [op];
1154
+ return update.components.map((component) => ({
1155
+ ...op,
1156
+ updateComponents: {
1157
+ ...update,
1158
+ components: [component]
1159
+ }
1160
+ }));
1161
+ });
1162
+ }
1163
+ /** createSurface first, the other operations after it in their order. */
1164
+ function createSurfaceFirst(operations) {
1165
+ const creates = operations.filter((op) => isRecord(op.createSurface));
1166
+ const others = operations.filter((op) => !isRecord(op.createSurface));
1167
+ return [...creates, ...others];
1168
+ }
1169
+ /** True when the component of `name` has the prop `prop`. */
1170
+ function hasProp(ui, name, prop) {
1171
+ const properties = ui.manifestComponents[name]?.props.properties;
1172
+ return isRecord(properties) && Object.hasOwn(properties, prop);
1173
+ }
1174
+ const childRefCache = /* @__PURE__ */ new WeakMap();
1175
+ /** The ids in a slot value: an id, a list of ids, or a template. */
1176
+ function slotIds(value) {
1177
+ if (typeof value === "string") return [value];
1178
+ if (Array.isArray(value)) return value.filter(isString);
1179
+ return isRecord(value) && isString(value.componentId) ? [value.componentId] : [];
1180
+ }
1181
+ /**
1182
+ * A reader of the ids a component renders beyond `child` and `children`:
1183
+ * its declared slots (the `trigger` and `content` of a Modal) and its typed
1184
+ * child references (the `child` of each entry of `tabs`), from its catalog
1185
+ * entry. The prose lift follows these ids like `children`, so a panel is
1186
+ * never cut off from its Tabs. A reference that is bound to the data
1187
+ * model is "unknown": its ids exist only at render time.
1188
+ */
1189
+ function childIdsReader(ui) {
1190
+ return (component) => {
1191
+ const name = component.component;
1192
+ const entry = typeof name === "string" && Object.hasOwn(ui.manifestComponents, name) ? ui.manifestComponents[name] : void 0;
1193
+ if (!entry) return [];
1194
+ const ids = [];
1195
+ for (const slot of Object.keys(entry.slots ?? {})) if (slot !== "child" && slot !== "children") ids.push(...slotIds(component[slot]));
1196
+ let refs = childRefCache.get(entry.props);
1197
+ if (!refs) {
1198
+ refs = (0, _copilotkit_shared.collectChildRefs)(entry.props);
1199
+ childRefCache.set(entry.props, refs);
1200
+ }
1201
+ if (refs.length === 0) return ids;
1202
+ if ((0, _copilotkit_shared.hasBoundChildRef)(component, refs)) return "unknown";
1203
+ return [...ids, ...(0, _copilotkit_shared.childIdsAtRefs)(component, refs)];
1204
+ };
1205
+ }
1206
+ /** Every component of the operations by id, last definition wins. */
1207
+ function collectComponents(operations) {
1208
+ const byId = /* @__PURE__ */ new Map();
1209
+ for (const op of operations) {
1210
+ const update = op.updateComponents;
1211
+ const list = isRecord(update) ? update.components : void 0;
1212
+ if (!Array.isArray(list)) continue;
1213
+ for (const component of list) if (isRecord(component) && isString(component.id)) byId.set(component.id, component);
1214
+ }
1215
+ return [...byId.values()];
1216
+ }
1217
+ /**
1218
+ * The data model must not be shared between two surfaces. A data model
1219
+ * keeps the object it gets, so an input in one surface would change the
1220
+ * data of the other one.
1221
+ */
1222
+ function cloneData(value) {
1223
+ return value === void 0 ? void 0 : structuredClone(value);
1224
+ }
1225
+ /** The operation sent to `surfaceId`, with a copy of its data model value. */
1226
+ function readdress(op, surfaceId) {
1227
+ const kind = (0, _copilotkit_shared.getOperationKind)(op);
1228
+ const payload = kind ? op[kind] : void 0;
1229
+ if (!kind || !isRecord(payload)) return op;
1230
+ const next = {
1231
+ ...payload,
1232
+ surfaceId
1233
+ };
1234
+ if (kind === "updateDataModel" && "value" in payload) next.value = cloneData(payload.value);
1235
+ return {
1236
+ ...op,
1237
+ [kind]: next
1238
+ };
1239
+ }
1240
+ /**
1241
+ * The operations of one sub-surface. Each updateComponents keeps only the
1242
+ * components of the sub-surface, with its own root. The other operations
1243
+ * are sent to the sub-surface. The order stays the same, so a new operation
1244
+ * of the fence only adds operations at the end.
1245
+ */
1246
+ function subSurfaceOperations(operations, components, surfaceId) {
1247
+ const root = components.find((c) => c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID);
1248
+ const ids = new Set(components.map((c) => c.id));
1249
+ const out = [];
1250
+ for (const op of operations) {
1251
+ const update = op.updateComponents;
1252
+ if (!isRecord(update) || !Array.isArray(update.components)) {
1253
+ out.push(readdress(op, surfaceId));
1254
+ continue;
1255
+ }
1256
+ const kept = update.components.filter((c) => isRecord(c) && ids.has(c.id)).map((c) => isRecord(c) && c.id === _copilotkit_shared.GENERATIVE_UI_ROOT_ID ? root : c);
1257
+ if (kept.length === 0) continue;
1258
+ out.push({
1259
+ ...op,
1260
+ updateComponents: {
1261
+ ...update,
1262
+ surfaceId,
1263
+ components: kept
1264
+ }
1265
+ });
1266
+ }
1267
+ return out;
1268
+ }
1269
+ /**
1270
+ * Prose lift. Text components in the main stack of the surface (titles,
1271
+ * paragraphs, text lists and the dividers between them) become chat
1272
+ * markdown. The surface splits around them: the first surface keeps
1273
+ * `surfaceId`, the next ones are `<surfaceId>#1`, `<surfaceId>#2`, and so
1274
+ * on. A surface with no prose comes back as one part with the same
1275
+ * operations.
1276
+ */
1277
+ function liftProse(operations, surfaceId, childIds) {
1278
+ const components = collectComponents(operations);
1279
+ const segments = (0, _copilotkit_core.segmentSurfaceProse)(components, { childIds });
1280
+ const [first] = segments;
1281
+ if (segments.length === 1 && first?.kind === "surface" && first.components === components) return [{
1282
+ kind: "surface",
1283
+ surfaceId,
1284
+ operations
1285
+ }];
1286
+ let surfaceIndex = 0;
1287
+ return segments.map((segment) => {
1288
+ if (segment.kind === "markdown") return segment;
1289
+ const id = surfaceIndex === 0 ? surfaceId : `${surfaceId}#${surfaceIndex}`;
1290
+ surfaceIndex++;
1291
+ return {
1292
+ kind: "surface",
1293
+ surfaceId: id,
1294
+ operations: subSurfaceOperations(operations, segment.components, id)
1295
+ };
1296
+ });
1297
+ }
1298
+ /** `validateOperation`, with the operation typed when it is valid. */
1299
+ function checkOperation(op, options) {
1300
+ const validation = (0, _copilotkit_shared.validateOperation)(op, options);
1301
+ if (!validation.ok) return validation;
1302
+ return {
1303
+ ok: true,
1304
+ operation: op
1305
+ };
1306
+ }
1307
+ /**
1308
+ * The content of one surface. Each operation is validated against the
1309
+ * manifest. A valid operation goes in `operations`. A rejected one goes in
1310
+ * `rejected`, with its position and the reason.
1311
+ */
1312
+ function surfaceContent(surfaceId, draft, operations, options) {
1313
+ const { ui, functions } = options;
1314
+ const knownSurfaces = /* @__PURE__ */ new Set();
1315
+ const manifest = {
1316
+ catalogId: ui.id,
1317
+ catalogIds: catalogIdsOf(ui),
1318
+ components: ui.manifestComponents
1319
+ };
1320
+ const valid = [];
1321
+ const rejected = [];
1322
+ operations.forEach((op, index) => {
1323
+ const result = checkOperation(op, {
1324
+ manifest,
1325
+ knownSurfaces,
1326
+ functions
1327
+ });
1328
+ if (!result.ok) {
1329
+ rejected.push({
1330
+ index,
1331
+ reason: result.reason
1332
+ });
1333
+ return;
1334
+ }
1335
+ valid.push(result.operation);
1336
+ const kind = (0, _copilotkit_shared.getOperationKind)(result.operation);
1337
+ if (kind === "createSurface") knownSurfaces.add(surfaceId);
1338
+ if (kind === "deleteSurface") knownSurfaces.delete(surfaceId);
1339
+ });
1340
+ const create = valid.find((op) => "createSurface" in op);
1341
+ return {
1342
+ surfaceId,
1343
+ target: draft.target,
1344
+ catalogId: create?.createSurface.catalogId ?? ui.id,
1345
+ operations: valid,
1346
+ status: draft.streaming ? "streaming" : "ready",
1347
+ rejected
1348
+ };
1349
+ }
1350
+ /**
1351
+ * Builds the surfaces of a thread from the ```a2ui fences of its assistant
1352
+ * messages, in message order.
1353
+ *
1354
+ * - Operations are grouped by surfaceId across all messages. An operation
1355
+ * with no surfaceId goes to the first surface of its fence, else to
1356
+ * `<messageId>-<fenceIndex>`.
1357
+ * - The fence that first writes a surface creates it. The `target=<id>` of
1358
+ * that fence sets the target. With no target, the surface goes to the
1359
+ * chat.
1360
+ * - A later fence of the same reply for the same surfaceId updates it. A
1361
+ * later reply that reuses the id of a chat surface gets a surface of its
1362
+ * own, `<id>@<messageId>`. A page target is updated from any reply.
1363
+ * - The status is "streaming" while the creating fence streams, else
1364
+ * "ready".
1365
+ * - Each operation is validated with `validateOperation`. Rejected ones are
1366
+ * left out and listed in `rejected`.
1367
+ * - Chat surfaces get the prose lift: informational cards lose their box,
1368
+ * and prose becomes markdown that renders between sub-surfaces
1369
+ * (`<surfaceId>#<n>`). An inline createSurface is split into its
1370
+ * createSurface, updateDataModel and updateComponents first.
1371
+ * - A `callRendererFunction` line is not part of a surface. It goes to
1372
+ * `functionCalls`. A streaming line gives nothing, so a function never
1373
+ * runs with a part of its args.
1374
+ *
1375
+ * The function is pure. Call it again on each stream update. The manager
1376
+ * applies only the new operations, so unchanged surfaces do not render
1377
+ * again.
1378
+ *
1379
+ * @param messages - The messages of one thread.
1380
+ * @param options - The generative UI, its declared functions, and whether
1381
+ * the last message can still grow.
1382
+ * @returns `surfaces`, one content for each surface and sub-surface;
1383
+ * `fences`, the blocks that each fence renders, by `fenceKey` (a fence
1384
+ * that is not in `fences` renders nothing); `functionCalls`, the function
1385
+ * calls of the fences in order; and `parts`, the surface ids of the parts
1386
+ * of each surface, by surface id.
1387
+ *
1388
+ * @example
1389
+ * ```ts
1390
+ * const { surfaces } = buildMarkdownSurfaces(agent.messages, {
1391
+ * ui,
1392
+ * functions: {},
1393
+ * running: agent.isRunning,
1394
+ * });
1395
+ * for (const content of surfaces) manager.ingest(threadId, agentId, content);
1396
+ * ```
1397
+ */
1398
+ function buildMarkdownSurfaces(messages, options) {
1399
+ const { ui, cache } = options;
1400
+ const drafts = /* @__PURE__ */ new Map();
1401
+ const readdressOnce = (op, surfaceId) => {
1402
+ if (!cache) return readdress(op, surfaceId);
1403
+ let copies = cache.readdressed.get(op);
1404
+ if (!copies) {
1405
+ copies = /* @__PURE__ */ new Map();
1406
+ cache.readdressed.set(op, copies);
1407
+ }
1408
+ let copy = copies.get(surfaceId);
1409
+ if (!copy) {
1410
+ copy = readdress(op, surfaceId);
1411
+ copies.set(surfaceId, copy);
1412
+ }
1413
+ return copy;
1414
+ };
1415
+ /** The surfaces that each fence created, in order. */
1416
+ const created = /* @__PURE__ */ new Map();
1417
+ const functionCalls = [];
1418
+ /** The message that owns each chat surface id, by the id the model wrote. */
1419
+ const chatOwners = /* @__PURE__ */ new Map();
1420
+ const lastMessage = messages[messages.length - 1];
1421
+ /**
1422
+ * A chat surface belongs to the reply that wrote it: the chat is a
1423
+ * transcript, so a later reply that reuses an id gets a surface of its
1424
+ * own (`<id>@<messageId>`) instead of changing the earlier reply. A fence
1425
+ * for a page target keeps its id, because a target is a place on the
1426
+ * page that a later reply updates on purpose.
1427
+ */
1428
+ const scopedSurfaceId = (requested, messageId, target) => {
1429
+ if (target !== void 0) return requested;
1430
+ const owner = chatOwners.get(requested);
1431
+ if (owner === void 0) {
1432
+ chatOwners.set(requested, messageId);
1433
+ return requested;
1434
+ }
1435
+ return owner === messageId ? requested : `${requested}@${messageId}`;
1436
+ };
1437
+ for (const message of messages) {
1438
+ if (message.role !== "assistant" || !isString(message.content)) continue;
1439
+ const isLastMessage = message === lastMessage;
1440
+ const content = message.content;
1441
+ const segments = cache ? cache.segments.get(content, () => (0, _copilotkit_core.splitA2UIMarkdown)(content)) : (0, _copilotkit_core.splitA2UIMarkdown)(content);
1442
+ for (const segment of segments) {
1443
+ if (segment.type !== "a2ui") continue;
1444
+ const isStreaming = !segment.closed && isLastMessage && options.running;
1445
+ const parseFence = () => {
1446
+ const parsed = fenceOperations(segment.text, isStreaming);
1447
+ const { functionCalls } = (0, _copilotkit_core.prepareSurfaceOperations)({
1448
+ operations: parsed,
1449
+ fallbackSurfaceId: "",
1450
+ catalogId: ui.id
1451
+ });
1452
+ return {
1453
+ operations: parsed,
1454
+ functionCalls
1455
+ };
1456
+ };
1457
+ const fence = cache ? cache.fences.get(`${isStreaming}:${segment.text}`, parseFence) : parseFence();
1458
+ const { operations } = fence;
1459
+ const key = fenceKey(message.id, segment.index);
1460
+ const fenceSurfaceId = operations.map(_copilotkit_core.getMarkdownOperationSurfaceId).find(isString) ?? `${message.id}-${segment.index}`;
1461
+ for (const operation of fence.functionCalls) functionCalls.push({
1462
+ messageId: message.id,
1463
+ fenceIndex: segment.index,
1464
+ operation
1465
+ });
1466
+ const surfaceOperations = operations.filter((op) => (0, _copilotkit_shared.getOperationKind)(op) !== "callRendererFunction");
1467
+ for (const op of surfaceOperations) {
1468
+ const requested = (0, _copilotkit_core.getMarkdownOperationSurfaceId)(op) ?? fenceSurfaceId;
1469
+ const surfaceId = scopedSurfaceId(requested, message.id, segment.target);
1470
+ let draft = drafts.get(surfaceId);
1471
+ if (!draft) {
1472
+ draft = {
1473
+ surfaceId,
1474
+ target: segment.target ?? _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
1475
+ operations: [],
1476
+ streaming: isStreaming
1477
+ };
1478
+ drafts.set(surfaceId, draft);
1479
+ created.set(key, [...created.get(key) ?? [], surfaceId]);
1480
+ }
1481
+ draft.operations.push(surfaceId === requested ? op : readdressOnce(op, surfaceId));
1482
+ }
1483
+ }
1484
+ }
1485
+ const canFlattenCards = hasProp(ui, "Card", "variant");
1486
+ const surfaces = [];
1487
+ const partsBySurface = /* @__PURE__ */ new Map();
1488
+ const childIds = childIdsReader(ui);
1489
+ const buildDraft = (draft) => {
1490
+ const operations = splitComponentUpdates(expandInlineCreate(createSurfaceFirst((0, _copilotkit_core.prepareSurfaceOperations)({
1491
+ operations: draft.operations,
1492
+ fallbackSurfaceId: draft.surfaceId,
1493
+ catalogId: ui.id,
1494
+ catalogIds: catalogIdsOf(ui)
1495
+ }).operations)));
1496
+ const parts = draft.target === _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET ? liftProse(canFlattenCards ? (0, _copilotkit_core.flattenInformationalCards)(operations, { childIds }) : operations, draft.surfaceId, childIds) : [{
1497
+ kind: "surface",
1498
+ surfaceId: draft.surfaceId,
1499
+ operations
1500
+ }];
1501
+ const contents = parts.flatMap((part) => part.kind === "surface" ? [surfaceContent(part.surfaceId, draft, part.operations, options)] : []);
1502
+ return {
1503
+ ...draft,
1504
+ parts,
1505
+ contents
1506
+ };
1507
+ };
1508
+ for (const draft of drafts.values()) {
1509
+ const built = cache ? cache.drafts.get(draft.surfaceId, () => buildDraft(draft), (last) => last.target === draft.target && last.streaming === draft.streaming && sameItems(last.operations, draft.operations)) : buildDraft(draft);
1510
+ partsBySurface.set(draft.surfaceId, built.parts);
1511
+ surfaces.push(...built.contents);
1512
+ }
1513
+ cache?.endBuild();
1514
+ /** The surface ids of the parts of each split surface, by surface id. */
1515
+ const parts = /* @__PURE__ */ new Map();
1516
+ for (const [surfaceId, surfaceParts] of partsBySurface) {
1517
+ const ids = surfaceParts.flatMap((part) => part.kind === "surface" ? [part.surfaceId] : []);
1518
+ parts.set(surfaceId, ids);
1519
+ }
1520
+ const fences = /* @__PURE__ */ new Map();
1521
+ for (const [key, surfaceIds] of created) {
1522
+ const blocks = [];
1523
+ for (const surfaceId of surfaceIds) {
1524
+ if (drafts.get(surfaceId)?.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) continue;
1525
+ for (const part of partsBySurface.get(surfaceId) ?? []) blocks.push(part.kind === "markdown" ? part : {
1526
+ kind: "surface",
1527
+ surfaceId: part.surfaceId
1528
+ });
1529
+ }
1530
+ if (blocks.length > 0) fences.set(key, blocks);
1531
+ }
1532
+ return {
1533
+ surfaces,
1534
+ fences,
1535
+ functionCalls,
1536
+ parts
1537
+ };
1538
+ }
1539
+ /** The declared functions, as `validateOperation` takes them. */
1540
+ function declaredFunctions(ui) {
1541
+ const functions = {};
1542
+ for (const [name, fn] of ui.functions) try {
1543
+ functions[name] = {
1544
+ ...fn.description ? { description: fn.description } : {},
1545
+ parameters: toJsonSchema(fn.parameters)
1546
+ };
1547
+ } catch {
1548
+ functions[name] = { parameters: {} };
1549
+ }
1550
+ return functions;
1551
+ }
1552
+ /** True when `list` starts with all the items of `prefix`. */
1553
+ function startsWith(list, prefix) {
1554
+ return list.length >= prefix.length && prefix.every((item, index) => item === list[index]);
1555
+ }
1556
+ /** A content that deletes a surface that the fences no longer write. */
1557
+ function removalContent(surfaceId, catalogId) {
1558
+ return {
1559
+ surfaceId,
1560
+ target: _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET,
1561
+ catalogId,
1562
+ status: "ready",
1563
+ rejected: [],
1564
+ operations: [{
1565
+ version: _copilotkit_shared.A2UI_VERSION,
1566
+ createSurface: {
1567
+ surfaceId,
1568
+ catalogId
1569
+ }
1570
+ }, {
1571
+ version: _copilotkit_shared.A2UI_VERSION,
1572
+ deleteSurface: { surfaceId }
1573
+ }]
1574
+ };
1575
+ }
1576
+ /**
1577
+ * The markdown transport source of one surface manager. It turns the
1578
+ * messages of a thread into surfaces in the manager, and keeps the blocks
1579
+ * that each fence renders.
1580
+ */
1581
+ var MarkdownSurfaceSource = class {
1582
+ constructor(manager, ui) {
1583
+ this.manager = manager;
1584
+ this.ui = ui;
1585
+ this.fences = /* @__PURE__ */ new Map();
1586
+ this.ingested = /* @__PURE__ */ new Map();
1587
+ this.contents = /* @__PURE__ */ new Map();
1588
+ this.caches = /* @__PURE__ */ new Map();
1589
+ this.functions = declaredFunctions(ui);
1590
+ }
1591
+ /**
1592
+ * Builds the surfaces of `threadId` from `messages` and gives them to the
1593
+ * manager. A surface that an earlier sync of the thread made, and that the
1594
+ * messages no longer write, is deleted. Other threads do not change.
1595
+ *
1596
+ * @param threadId - The thread of the messages.
1597
+ * @param agentId - The agent that owns the thread.
1598
+ * @param messages - All messages of the thread.
1599
+ * @param options - `running`: the last message can still grow.
1600
+ * @returns The function calls of the fences, in order. The source does
1601
+ * not run them.
1602
+ */
1603
+ sync(threadId, agentId, messages, options) {
1604
+ let cache = this.caches.get(threadId);
1605
+ if (!cache) {
1606
+ cache = new MarkdownBuildCache();
1607
+ this.caches.set(threadId, cache);
1608
+ }
1609
+ const result = buildMarkdownSurfaces(messages, {
1610
+ ui: this.ui,
1611
+ functions: this.functions,
1612
+ running: options.running,
1613
+ cache
1614
+ });
1615
+ this.fences.set(threadId, result.fences);
1616
+ for (const parts of result.parts.values()) this.manager.linkSurfaces(threadId, parts);
1617
+ const previous = this.ingested.get(threadId) ?? /* @__PURE__ */ new Map();
1618
+ const previousContents = this.contents.get(threadId) ?? /* @__PURE__ */ new Map();
1619
+ const next = /* @__PURE__ */ new Map();
1620
+ const nextContents = /* @__PURE__ */ new Map();
1621
+ for (const content of result.surfaces) {
1622
+ nextContents.set(content.surfaceId, content);
1623
+ const before = previous.get(content.surfaceId);
1624
+ if (before && previousContents.get(content.surfaceId) === content) {
1625
+ next.set(content.surfaceId, before);
1626
+ continue;
1627
+ }
1628
+ const fingerprints = content.operations.map((op) => JSON.stringify(op));
1629
+ if (before && !startsWith(fingerprints, before)) this.manager.ingest(threadId, agentId, {
1630
+ ...content,
1631
+ operations: []
1632
+ });
1633
+ this.manager.ingest(threadId, agentId, content);
1634
+ next.set(content.surfaceId, fingerprints);
1635
+ }
1636
+ for (const surfaceId of previous.keys()) {
1637
+ if (next.has(surfaceId)) continue;
1638
+ this.manager.ingest(threadId, agentId, removalContent(surfaceId, this.ui.id));
1639
+ }
1640
+ this.ingested.set(threadId, next);
1641
+ this.contents.set(threadId, nextContents);
1642
+ return result.functionCalls;
1643
+ }
1644
+ /**
1645
+ * The blocks that a fence renders in the chat, from the latest sync of the
1646
+ * thread. `undefined` when the fence renders nothing: it updates a surface
1647
+ * of an earlier fence, its surface is for a named target, or it has no
1648
+ * complete operation yet.
1649
+ */
1650
+ getFenceBlocks(threadId, messageId, fenceIndex) {
1651
+ return this.fences.get(threadId)?.get(fenceKey(messageId, fenceIndex));
1652
+ }
1653
+ };
1654
+ const sources = /* @__PURE__ */ new WeakMap();
1655
+ /**
1656
+ * The markdown source of a generative UI runtime. There is one source for
1657
+ * each surface manager. The root syncs it, and the chat messages read the
1658
+ * fence blocks from it.
1659
+ */
1660
+ function getMarkdownSurfaceSource(runtime) {
1661
+ let source = sources.get(runtime.manager);
1662
+ if (!source) {
1663
+ source = new MarkdownSurfaceSource(runtime.manager, runtime.ui);
1664
+ sources.set(runtime.manager, source);
1665
+ }
1666
+ return source;
1667
+ }
1668
+
1669
+ //#endregion
1670
+ //#region src/generative-ui/calc.ts
1671
+ const MAX_SERIES = 1e3;
1672
+ const OPERATORS = [
1673
+ "&&",
1674
+ "||",
1675
+ "==",
1676
+ "!=",
1677
+ "<=",
1678
+ ">=",
1679
+ "<",
1680
+ ">",
1681
+ "+",
1682
+ "-",
1683
+ "*",
1684
+ "/",
1685
+ "%",
1686
+ "(",
1687
+ ")",
1688
+ ",",
1689
+ "?",
1690
+ ":",
1691
+ "!"
1692
+ ];
1693
+ function tokenize(source) {
1694
+ const tokens = [];
1695
+ let i = 0;
1696
+ while (i < source.length) {
1697
+ const char = source[i];
1698
+ if (/\s/.test(char)) {
1699
+ i++;
1700
+ continue;
1701
+ }
1702
+ if (/[0-9.]/.test(char)) {
1703
+ const match = /^\d*\.?\d+(?:[eE][-+]?\d+)?|^\d+\.?/.exec(source.slice(i));
1704
+ if (!match) throw new ExpressionError(`calc: bad number at "${source.slice(i, i + 8)}"`);
1705
+ tokens.push({
1706
+ kind: "number",
1707
+ value: Number(match[0])
1708
+ });
1709
+ i += match[0].length;
1710
+ continue;
1711
+ }
1712
+ if (char === "'" || char === "\"") {
1713
+ let value = "";
1714
+ i++;
1715
+ while (i < source.length && source[i] !== char) {
1716
+ if (source[i] === "\\" && i + 1 < source.length) i++;
1717
+ value += source[i++];
1718
+ }
1719
+ if (i >= source.length) throw new ExpressionError("calc: unclosed string");
1720
+ i++;
1721
+ tokens.push({
1722
+ kind: "string",
1723
+ value
1724
+ });
1725
+ continue;
1726
+ }
1727
+ if (/[A-Za-z_]/.test(char)) {
1728
+ const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(i));
1729
+ tokens.push({
1730
+ kind: "name",
1731
+ value: match[0]
1732
+ });
1733
+ i += match[0].length;
1734
+ continue;
1735
+ }
1736
+ const op = OPERATORS.find((candidate) => source.startsWith(candidate, i));
1737
+ if (!op) throw new ExpressionError(`calc: unexpected "${char}"`);
1738
+ tokens.push({
1739
+ kind: "op",
1740
+ value: op
1741
+ });
1742
+ i += op.length;
1743
+ }
1744
+ tokens.push({ kind: "end" });
1745
+ return tokens;
1746
+ }
1747
+ function numberOf(value, what) {
1748
+ if (typeof value === "number") {
1749
+ if (!Number.isFinite(value)) throw new ExpressionError(`calc: ${what} is not finite`);
1750
+ return value;
1751
+ }
1752
+ if (typeof value === "boolean") return value ? 1 : 0;
1753
+ if (typeof value === "string" && value.trim() !== "") {
1754
+ const parsed = Number(value);
1755
+ if (Number.isFinite(parsed)) return parsed;
1756
+ }
1757
+ if (value === null || value === void 0) throw new ExpressionError(`calc: ${what} has no value`);
1758
+ throw new ExpressionError(`calc: ${what} is not a number`);
1759
+ }
1760
+ function describe(value) {
1761
+ return typeof value === "string" ? `"${value}"` : String(value);
1762
+ }
1763
+ const MATH = {
1764
+ min: (args) => Math.min(...args),
1765
+ max: (args) => Math.max(...args),
1766
+ abs: ([x]) => Math.abs(x),
1767
+ floor: ([x]) => Math.floor(x),
1768
+ ceil: ([x]) => Math.ceil(x),
1769
+ round: ([x, decimals = 0]) => {
1770
+ const factor = 10 ** Math.trunc(decimals);
1771
+ return Math.round(x * factor) / factor;
1772
+ }
1773
+ };
1774
+ var CalcParser = class {
1775
+ constructor(tokens, scope, source) {
1776
+ this.tokens = tokens;
1777
+ this.scope = scope;
1778
+ this.source = source;
1779
+ this.pos = 0;
1780
+ this.skipDepth = 0;
1781
+ }
1782
+ parse() {
1783
+ const value = this.ternary();
1784
+ if (this.tokens[this.pos].kind !== "end") this.fail(`unexpected "${this.text(this.tokens[this.pos])}"`);
1785
+ return value;
1786
+ }
1787
+ fail(what) {
1788
+ throw new ExpressionError(`calc: ${what} in "${this.source}"`);
1789
+ }
1790
+ text(token) {
1791
+ return token.kind === "end" ? "end" : String(token.value);
1792
+ }
1793
+ peekOp(...ops) {
1794
+ const token = this.tokens[this.pos];
1795
+ return token.kind === "op" && ops.includes(token.value) ? token.value : void 0;
1796
+ }
1797
+ expectOp(op) {
1798
+ if (this.peekOp(op) === void 0) this.fail(`expected "${op}" but found "${this.text(this.tokens[this.pos])}"`);
1799
+ this.pos++;
1800
+ }
1801
+ /**
1802
+ * Parses a part of the expression that the result does not need (the
1803
+ * other branch of `?:`, the right side of a decided `&&` or `||`). It
1804
+ * still has to be parsed to find where it ends, so syntax errors are
1805
+ * reported, but no value is checked or computed: `n == 0 ? 0 : 10 / n`
1806
+ * is a valid guard.
1807
+ */
1808
+ skipped(parse) {
1809
+ this.skipDepth++;
1810
+ try {
1811
+ parse();
1812
+ } finally {
1813
+ this.skipDepth--;
1814
+ }
1815
+ return null;
1816
+ }
1817
+ /** The number of a value, or 0 while skipping. */
1818
+ num(value, what) {
1819
+ return this.skipDepth > 0 ? 0 : numberOf(value, what);
1820
+ }
1821
+ ternary() {
1822
+ const condition = this.or();
1823
+ if (this.peekOp("?") === void 0) return condition;
1824
+ this.pos++;
1825
+ const takesFirst = truthOf(condition);
1826
+ const whenTrue = takesFirst ? this.ternary() : this.skipped(() => this.ternary());
1827
+ this.expectOp(":");
1828
+ const whenFalse = takesFirst ? this.skipped(() => this.ternary()) : this.ternary();
1829
+ return takesFirst ? whenTrue : whenFalse;
1830
+ }
1831
+ or() {
1832
+ let left = this.and();
1833
+ while (this.peekOp("||")) {
1834
+ this.pos++;
1835
+ if (truthOf(left)) {
1836
+ this.skipped(() => this.and());
1837
+ left = true;
1838
+ } else left = truthOf(this.and());
1839
+ }
1840
+ return left;
1841
+ }
1842
+ and() {
1843
+ let left = this.equality();
1844
+ while (this.peekOp("&&")) {
1845
+ this.pos++;
1846
+ if (!truthOf(left)) {
1847
+ this.skipped(() => this.equality());
1848
+ left = false;
1849
+ } else left = truthOf(this.equality());
1850
+ }
1851
+ return left;
1852
+ }
1853
+ equality() {
1854
+ let left = this.comparison();
1855
+ for (let op = this.peekOp("==", "!="); op; op = this.peekOp("==", "!=")) {
1856
+ this.pos++;
1857
+ const right = this.comparison();
1858
+ const isEqual = typeof left === "number" || typeof right === "number" ? this.num(left, "the left side of ==") === this.num(right, "the right side of ==") : left === right;
1859
+ left = op === "==" ? isEqual : !isEqual;
1860
+ }
1861
+ return left;
1862
+ }
1863
+ comparison() {
1864
+ let left = this.additive();
1865
+ for (let op = this.peekOp("<", "<=", ">", ">="); op; op = this.peekOp("<", "<=", ">", ">=")) {
1866
+ this.pos++;
1867
+ const a = this.num(left, `the left side of ${op}`);
1868
+ const b = this.num(this.additive(), `the right side of ${op}`);
1869
+ left = op === "<" ? a < b : op === "<=" ? a <= b : op === ">" ? a > b : a >= b;
1870
+ }
1871
+ return left;
1872
+ }
1873
+ additive() {
1874
+ let left = this.multiplicative();
1875
+ for (let op = this.peekOp("+", "-"); op; op = this.peekOp("+", "-")) {
1876
+ this.pos++;
1877
+ const right = this.multiplicative();
1878
+ if (op === "+" && (typeof left === "string" || typeof right === "string")) left = `${left ?? ""}${right ?? ""}`;
1879
+ else {
1880
+ const a = this.num(left, `the left side of ${op}`);
1881
+ const b = this.num(right, `the right side of ${op}`);
1882
+ left = op === "+" ? a + b : a - b;
1883
+ }
1884
+ }
1885
+ return left;
1886
+ }
1887
+ multiplicative() {
1888
+ let left = this.unary();
1889
+ for (let op = this.peekOp("*", "/", "%"); op; op = this.peekOp("*", "/", "%")) {
1890
+ this.pos++;
1891
+ const a = this.num(left, `the left side of ${op}`);
1892
+ const b = this.num(this.unary(), `the right side of ${op}`);
1893
+ if (op !== "*" && b === 0 && this.skipDepth === 0) this.fail("division by zero");
1894
+ left = op === "*" ? a * b : op === "/" ? a / b : a % b;
1895
+ }
1896
+ return left;
1897
+ }
1898
+ unary() {
1899
+ if (this.peekOp("-")) {
1900
+ this.pos++;
1901
+ return -this.num(this.unary(), "the operand of -");
1902
+ }
1903
+ if (this.peekOp("!")) {
1904
+ this.pos++;
1905
+ return !truthOf(this.unary());
1906
+ }
1907
+ return this.primary();
1908
+ }
1909
+ primary() {
1910
+ const token = this.tokens[this.pos++];
1911
+ switch (token.kind) {
1912
+ case "number": return token.value;
1913
+ case "string": return token.value;
1914
+ case "name": return this.name(token.value);
1915
+ case "op":
1916
+ if (token.value === "(") {
1917
+ const value = this.ternary();
1918
+ this.expectOp(")");
1919
+ return value;
1920
+ }
1921
+ return this.fail(`unexpected "${token.value}"`);
1922
+ case "end": return this.fail("missing value");
1923
+ }
1924
+ }
1925
+ name(name) {
1926
+ if (name === "true") return true;
1927
+ if (name === "false") return false;
1928
+ if (name === "null") return null;
1929
+ if (this.peekOp("(")) {
1930
+ this.pos++;
1931
+ const args = [];
1932
+ if (this.peekOp(")") === void 0) for (;;) {
1933
+ args.push(this.num(this.ternary(), `an argument of ${name}`));
1934
+ if (this.peekOp(",") === void 0) break;
1935
+ this.pos++;
1936
+ }
1937
+ this.expectOp(")");
1938
+ if (this.skipDepth > 0) return null;
1939
+ const fn = Object.prototype.hasOwnProperty.call(MATH, name) ? MATH[name] : void 0;
1940
+ if (!fn) this.fail(`unknown function ${name}`);
1941
+ if (args.length === 0) this.fail(`${name} needs an argument`);
1942
+ return fn(args);
1943
+ }
1944
+ if (this.skipDepth > 0) return null;
1945
+ if (!Object.prototype.hasOwnProperty.call(this.scope, name)) this.fail(`unknown name ${name}; pass it as an arg`);
1946
+ const value = this.scope[name];
1947
+ if (value !== null && typeof value !== "number" && typeof value !== "string" && typeof value !== "boolean") this.fail(`${name} is not a number, text or boolean (${describe(value)})`);
1948
+ return value;
1949
+ }
1950
+ };
1951
+ /**
1952
+ * Evaluates `expression` with the names in `scope`. Gives a number, a
1953
+ * string, a boolean or null. Throws an {@link ExpressionError} for a bad
1954
+ * expression or a missing name.
1955
+ */
1956
+ function evaluateCalc(expression, scope) {
1957
+ if (typeof expression !== "string" || expression.trim() === "") throw new ExpressionError("calc: expression must be a string");
1958
+ return new CalcParser(tokenize(expression), scope, expression).parse();
1959
+ }
1960
+ /** The `calc` function: the expression is `args.expression`, the rest is the scope. */
1961
+ function calc(args) {
1962
+ const { expression, ...scope } = args;
1963
+ return evaluateCalc(expression, scope);
1964
+ }
1965
+ const WHOLE_EXPRESSION = /^\$\{([^}]*)\}$/;
1966
+ /**
1967
+ * Fills `item` for one iteration: a string that is one `${...}` gives the
1968
+ * typed value of the expression, a string with `${...}` inside it is
1969
+ * interpolated as text, and objects and arrays are walked.
1970
+ */
1971
+ function fillItem(item, scope) {
1972
+ if (typeof item === "string") {
1973
+ const whole = WHOLE_EXPRESSION.exec(item);
1974
+ if (whole) return evaluateCalc(whole[1], scope);
1975
+ return item.replace(/\$\{([^}]*)\}/g, (_, expression) => {
1976
+ const value = evaluateCalc(expression, scope);
1977
+ return value === null ? "" : String(value);
1978
+ });
1979
+ }
1980
+ if (Array.isArray(item)) return item.map((entry) => fillItem(entry, scope));
1981
+ if (typeof item === "object" && item !== null) return Object.fromEntries(Object.entries(item).map(([key, value]) => [key, fillItem(value, scope)]));
1982
+ return item;
1983
+ }
1984
+ /**
1985
+ * The `series` function: `count` copies of `item`, with the loop variable
1986
+ * (`variable`, default "i") counting from `start` (default 1) and the other
1987
+ * args in scope of the `${...}` expressions of the item.
1988
+ */
1989
+ function series(args) {
1990
+ const { count, item, variable, start, ...scope } = args;
1991
+ const length = numberOf(count, "count");
1992
+ if (!Number.isInteger(length) || length < 0) throw new ExpressionError("series: count must be a whole number");
1993
+ if (length > MAX_SERIES) throw new ExpressionError(`series: count is at most ${MAX_SERIES}`);
1994
+ if (item === void 0) throw new ExpressionError("series: item is required");
1995
+ const name = variable === void 0 ? "i" : variable;
1996
+ if (typeof name !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new ExpressionError("series: variable must be a name");
1997
+ const first = start === void 0 ? 1 : numberOf(start, "start");
1998
+ return Array.from({ length }, (_, index) => fillItem(item, {
1999
+ ...scope,
2000
+ [name]: first + index
2001
+ }));
2002
+ }
2003
+
2004
+ //#endregion
2005
+ //#region src/generative-ui/resolve.ts
2006
+ BASIC_FUNCTIONS.calc = calc;
2007
+ BASIC_FUNCTIONS.series = series;
2008
+ const NO_DATA = { get: () => void 0 };
2009
+ BASIC_FUNCTIONS.formatString = (args) => resolveDynamicValue({
2010
+ "@call": "formatString",
2011
+ args
2012
+ }, {
2013
+ data: NO_DATA,
2014
+ basePath: void 0
2015
+ }).value;
2016
+ /** Adds one segment to a JSON pointer: ("/items", "0") gives "/items/0". */
2017
+ function joinPath(base, segment) {
2018
+ return base === "/" ? `/${segment}` : `${base}/${segment}`;
2019
+ }
2020
+ /**
2021
+ * The absolute data model path of a binding. A path without a leading "/"
2022
+ * is relative to the current template item, or to the root outside of one.
2023
+ */
2024
+ function resolvePath(path, basePath) {
2025
+ if (path.startsWith("/")) return path;
2026
+ return joinPath(basePath ?? "/", path);
2027
+ }
2028
+ /**
2029
+ * The index of the template item at `basePath`: its last segment.
2030
+ * `undefined` outside of a template.
2031
+ */
2032
+ function templateIndex(basePath) {
2033
+ if (basePath === void 0) return void 0;
2034
+ const index = Number(basePath.slice(basePath.lastIndexOf("/") + 1));
2035
+ return Number.isInteger(index) ? index : void 0;
2036
+ }
2037
+ /** The value of a ValidationResult where a boolean is expected. */
2038
+ function coerce(value, keep) {
2039
+ return !keep && (0, _copilotkit_shared.isValidationResult)(value) ? value.valid : value;
2040
+ }
2041
+ /**
2042
+ * Resolves `value`. `keepValidation` keeps a ValidationResult as it is; by
2043
+ * default it becomes its `valid` boolean, which is what every prop except
2044
+ * a check condition wants.
2045
+ */
2046
+ function walk(value, state, keepValidation, scope = "outside") {
2047
+ if (Array.isArray(value)) {
2048
+ let changed = false;
2049
+ const itemScope = scope === "list" ? "check" : "outside";
2050
+ const items = value.map((item) => {
2051
+ const next = walk(item, state, keepValidation, itemScope);
2052
+ if (next !== item) changed = true;
2053
+ return next;
2054
+ });
2055
+ return changed ? items : value;
2056
+ }
2057
+ if (!isRecord(value)) return value;
2058
+ if ((0, _copilotkit_shared.isPathBinding)(value)) {
2059
+ const path = resolvePath(value["@path"], state.context.basePath);
2060
+ state.paths.add(path);
2061
+ return state.context.data.get(path);
2062
+ }
2063
+ if ((0, _copilotkit_shared.isCallBinding)(value)) return call(value, state, keepValidation);
2064
+ if ((0, _copilotkit_shared.isActionBinding)(value)) return value;
2065
+ let changed = false;
2066
+ const entries = Object.entries(value).map(([key, item]) => {
2067
+ const next = walk(item, state, keepValidation || scope === "check" && key === "condition", key === "checks" ? "list" : "outside");
2068
+ if (next !== item) changed = true;
2069
+ return [key, next];
2070
+ });
2071
+ return changed ? Object.fromEntries(entries) : value;
2072
+ }
2073
+ function call(binding, state, keepValidation) {
2074
+ const name = binding["@call"];
2075
+ const rawArgs = binding.args ?? {};
2076
+ if (!isRecord(rawArgs)) throw new ExpressionError(`the args of "${name}" must be an object`);
2077
+ if (name === _copilotkit_shared.A2UI_INDEX_FUNCTION) {
2078
+ const index = templateIndex(state.context.basePath);
2079
+ if (index === void 0) return void 0;
2080
+ const offset = walk(rawArgs.offset, state, false);
2081
+ return index + (typeof offset === "number" ? offset : 0);
2082
+ }
2083
+ if (name === "formatString") {
2084
+ const template = walk(rawArgs.value, state, false);
2085
+ if (typeof template !== "string") throw new ExpressionError("formatString takes a string value");
2086
+ return formatString(template, state);
2087
+ }
2088
+ const fn = Object.prototype.hasOwnProperty.call(BASIC_FUNCTIONS, name) ? BASIC_FUNCTIONS[name] : void 0;
2089
+ if (!fn) throw new ExpressionError(`"${name}" is not a basic function`);
2090
+ if (requiresUserActivation(name)) throw new ExpressionError(`"${name}" is not a value; bind it as the functionCall of an event`);
2091
+ const result = fn(walk(rawArgs, state, false));
2092
+ return givesValidationResult(name) ? coerce(result, keepValidation) : result;
2093
+ }
2094
+ function resolveDynamicValue(value, context, options = {}) {
2095
+ const result = tryResolveDynamicValue(value, context, options);
2096
+ if (!result.ok) throw result.error;
2097
+ return result;
2098
+ }
2099
+ /**
2100
+ * Like {@link resolveDynamicValue}, but a failure comes back as a result
2101
+ * with the paths read so far, so the caller can keep watching them: a
2102
+ * function that fails on an empty field works once the user fills it.
2103
+ */
2104
+ function tryResolveDynamicValue(value, context, options = {}) {
2105
+ const state = {
2106
+ context,
2107
+ paths: /* @__PURE__ */ new Set()
2108
+ };
2109
+ try {
2110
+ return {
2111
+ ok: true,
2112
+ value: walk(value, state, options.keepValidation ?? false, options.isChecks ? "list" : "outside"),
2113
+ paths: state.paths
2114
+ };
2115
+ } catch (error) {
2116
+ return {
2117
+ ok: false,
2118
+ error: error instanceof Error ? error : new Error(String(error)),
2119
+ paths: state.paths
2120
+ };
2121
+ }
2122
+ }
2123
+ /** True when `value` holds a `{"@path"}` or `{"@call"}` at any depth. */
2124
+ function containsDynamicValue(value) {
2125
+ if (Array.isArray(value)) return value.some(containsDynamicValue);
2126
+ if (!isRecord(value)) return false;
2127
+ if ((0, _copilotkit_shared.isPathBinding)(value) || (0, _copilotkit_shared.isCallBinding)(value)) return true;
2128
+ if ((0, _copilotkit_shared.isActionBinding)(value)) return false;
2129
+ return Object.values(value).some(containsDynamicValue);
2130
+ }
2131
+ /**
2132
+ * The `${...}` grammar of `formatString`:
2133
+ *
2134
+ * expression := path | literal | call
2135
+ * path := "/" segments | identifier ("/" segments)*
2136
+ * literal := 'text' | "text" | number | true | false | null
2137
+ * call := identifier "(" [ name ":" expression ("," name ":" expression)* ] ")"
2138
+ *
2139
+ * A `\${` in the template is a literal `${`.
2140
+ */
2141
+ function formatString(template, state) {
2142
+ let out = "";
2143
+ let index = 0;
2144
+ while (index < template.length) {
2145
+ const start = template.indexOf("${", index);
2146
+ if (start === -1) {
2147
+ out += template.slice(index);
2148
+ break;
2149
+ }
2150
+ if (start > 0 && template[start - 1] === "\\") {
2151
+ out += `${template.slice(index, start - 1)}\${`;
2152
+ index = start + 2;
2153
+ continue;
2154
+ }
2155
+ out += template.slice(index, start);
2156
+ const end = matchingBrace(template, start + 2);
2157
+ if (end === -1) throw new ExpressionError("formatString: unclosed ${");
2158
+ const value = new ExpressionParser(template.slice(start + 2, end).trim(), state).parse();
2159
+ out += value === void 0 || value === null ? "" : String(value);
2160
+ index = end + 1;
2161
+ }
2162
+ return out;
2163
+ }
2164
+ /** The index of the `}` that closes the block opened at `from`, or -1. */
2165
+ function matchingBrace(template, from) {
2166
+ let depth = 1;
2167
+ let quote;
2168
+ for (let i = from; i < template.length; i++) {
2169
+ const char = template[i];
2170
+ if (quote) {
2171
+ if (char === "\\") i++;
2172
+ else if (char === quote) quote = void 0;
2173
+ continue;
2174
+ }
2175
+ if (char === "'" || char === "\"") quote = char;
2176
+ else if (char === "{") depth++;
2177
+ else if (char === "}" && --depth === 0) return i;
2178
+ }
2179
+ return -1;
2180
+ }
2181
+ const IDENTIFIER = /@?[A-Za-z_][A-Za-z0-9_-]*/y;
2182
+ const NUMBER = /-?\d+(?:\.\d+)?/y;
2183
+ const PATH_SEGMENT = /[^\s,():'"]+/y;
2184
+ var ExpressionParser = class {
2185
+ constructor(source, state) {
2186
+ this.source = source;
2187
+ this.state = state;
2188
+ this.pos = 0;
2189
+ }
2190
+ parse() {
2191
+ const value = this.expression();
2192
+ this.skipSpace();
2193
+ if (this.pos < this.source.length) throw new ExpressionError(`formatString: unexpected "${this.source.slice(this.pos)}" in \${${this.source}}`);
2194
+ return value;
2195
+ }
2196
+ fail(what) {
2197
+ throw new ExpressionError(`formatString: ${what} in \${${this.source}}`);
2198
+ }
2199
+ skipSpace() {
2200
+ while (this.pos < this.source.length && /\s/.test(this.source[this.pos])) this.pos++;
2201
+ }
2202
+ match(pattern) {
2203
+ pattern.lastIndex = this.pos;
2204
+ const found = pattern.exec(this.source);
2205
+ if (!found) return void 0;
2206
+ this.pos = pattern.lastIndex;
2207
+ return found[0];
2208
+ }
2209
+ expression() {
2210
+ this.skipSpace();
2211
+ const char = this.source[this.pos];
2212
+ if (char === void 0) this.fail("missing expression");
2213
+ if (char === "'" || char === "\"") return this.quoted(char);
2214
+ if (char === "/") return this.path(this.match(PATH_SEGMENT) ?? "/");
2215
+ const number = this.match(NUMBER);
2216
+ if (number !== void 0) return Number(number);
2217
+ const name = this.match(IDENTIFIER);
2218
+ if (name === void 0) this.fail(`unexpected "${char}"`);
2219
+ if (name === "true") return true;
2220
+ if (name === "false") return false;
2221
+ if (name === "null") return null;
2222
+ this.skipSpace();
2223
+ if (this.source[this.pos] === "(") return this.call(name);
2224
+ if (name.startsWith("@")) return call({ "@call": name }, this.state, false);
2225
+ const rest = this.source[this.pos] === "/" ? this.match(PATH_SEGMENT) : "";
2226
+ return this.path(`${name}${rest ?? ""}`);
2227
+ }
2228
+ quoted(quote) {
2229
+ let value = "";
2230
+ this.pos++;
2231
+ while (this.pos < this.source.length) {
2232
+ const char = this.source[this.pos++];
2233
+ if (char === "\\" && this.pos < this.source.length) value += this.source[this.pos++];
2234
+ else if (char === quote) return value;
2235
+ else value += char;
2236
+ }
2237
+ return this.fail("unclosed string");
2238
+ }
2239
+ path(path) {
2240
+ const absolute = resolvePath(path, this.state.context.basePath);
2241
+ this.state.paths.add(absolute);
2242
+ return this.state.context.data.get(absolute);
2243
+ }
2244
+ call(name) {
2245
+ this.pos++;
2246
+ const args = {};
2247
+ this.skipSpace();
2248
+ if (this.source[this.pos] === ")") {
2249
+ this.pos++;
2250
+ return call({
2251
+ "@call": name,
2252
+ args
2253
+ }, this.state, false);
2254
+ }
2255
+ for (;;) {
2256
+ this.skipSpace();
2257
+ const key = this.match(IDENTIFIER);
2258
+ if (key === void 0) this.fail("expected an argument name");
2259
+ this.skipSpace();
2260
+ if (this.source[this.pos] !== ":") this.fail(`expected ":" after ${key}`);
2261
+ this.pos++;
2262
+ args[key] = this.expression();
2263
+ this.skipSpace();
2264
+ const next = this.source[this.pos++];
2265
+ if (next === ")") break;
2266
+ if (next !== ",") this.fail(`expected "," or ")" after ${key}`);
2267
+ }
2268
+ return call({
2269
+ "@call": name,
2270
+ args
2271
+ }, this.state, false);
2272
+ }
2273
+ };
2274
+
2275
+ //#endregion
2276
+ //#region src/generative-ui/schema.ts
2277
+ const ASYNC_ISSUE = { message: "the schema validates asynchronously; component props and state need a schema that validates synchronously" };
2278
+ function toResult(result) {
2279
+ return result.issues ? {
2280
+ success: false,
2281
+ issues: result.issues
2282
+ } : {
2283
+ success: true,
2284
+ data: result.value
2285
+ };
2286
+ }
2287
+ /**
2288
+ * Validates `value` with `schema`. The result comes back at once when the
2289
+ * schema validates synchronously, else as a promise.
2290
+ */
2291
+ function validateSchema(schema, value) {
2292
+ const result = schema["~standard"].validate(value);
2293
+ return result instanceof Promise ? result.then(toResult) : toResult(result);
2294
+ }
2295
+ /**
2296
+ * Validates `value` synchronously, for code that runs during render. A
2297
+ * schema that validates asynchronously fails with an issue that says so.
2298
+ */
2299
+ function validateSchemaSync(schema, value) {
2300
+ const result = validateSchema(schema, value);
2301
+ if (!(result instanceof Promise)) return result;
2302
+ result.catch(() => {});
2303
+ return {
2304
+ success: false,
2305
+ issues: [ASYNC_ISSUE]
2306
+ };
2307
+ }
2308
+ /** True for the issue that `validateSchemaSync` gives for an async schema. */
2309
+ function isAsyncIssue(issue) {
2310
+ return issue === ASYNC_ISSUE;
2311
+ }
2312
+ /** The first key of an issue path: the prop the issue is about. */
2313
+ function issueKey(issue) {
2314
+ const first = issue.path?.[0];
2315
+ const key = typeof first === "object" ? first.key : first;
2316
+ return key === void 0 ? void 0 : String(key);
2317
+ }
2318
+ /**
2319
+ * `props` without the top-level props whose `null` the schema rejected, or
2320
+ * `undefined` when there are none. A model writes `null` for "not set" (an
2321
+ * empty selection, a value it has not filled yet), and A2UI deletes a data
2322
+ * model key that is set to `null`, so a rejected `null` is read as an unset
2323
+ * prop. A prop whose schema accepts `null` keeps it.
2324
+ */
2325
+ function withoutRejectedNulls(props, issues) {
2326
+ const rejected = /* @__PURE__ */ new Set();
2327
+ for (const issue of issues) {
2328
+ const key = issueKey(issue);
2329
+ if (key !== void 0 && issue.path?.length === 1 && props[key] === null) rejected.add(key);
2330
+ }
2331
+ if (rejected.size === 0) return void 0;
2332
+ return Object.fromEntries(Object.entries(props).filter(([key]) => !rejected.has(key)));
2333
+ }
2334
+ /** `"a.b: message; c: message"`. A path-less issue gets `fallback`. */
2335
+ function formatIssues(issues, fallback = "props") {
2336
+ return issues.map((issue) => {
2337
+ return `${(issue.path ?? []).map((segment) => String(typeof segment === "object" ? segment.key : segment)).join(".") || fallback}: ${issue.message}`;
2338
+ }).join("; ");
2339
+ }
2340
+
2341
+ //#endregion
2342
+ //#region src/generative-ui/runtime-context.ts
2343
+ const GenerativeUIRuntimeContext = (0, react.createContext)(null);
2344
+ function useGenerativeUIRuntime() {
2345
+ return (0, react.useContext)(GenerativeUIRuntimeContext);
2346
+ }
2347
+ function useRequiredGenerativeUIRuntime() {
2348
+ const runtime = (0, react.useContext)(GenerativeUIRuntimeContext);
2349
+ if (!runtime) throw new Error("Generative UI components must be rendered inside <CopilotKitProvider generativeUI={{ ui }}>.");
2350
+ return runtime;
2351
+ }
2352
+ /**
2353
+ * Reports an error without ever throwing: `reportError` reaches host code
2354
+ * (`onError`), and a throwing host callback must not break rendering or an
2355
+ * event handler.
2356
+ */
2357
+ function reportErrorSafely(runtime, info) {
2358
+ try {
2359
+ runtime.reportError(info);
2360
+ } catch {}
2361
+ }
2362
+ const GenerativeUINodeContext = (0, react.createContext)(null);
2363
+
2364
+ //#endregion
2365
+ //#region src/generative-ui/hooks.ts
2366
+ const noopSubscribe$1 = () => () => {};
2367
+ const zero = () => 0;
2368
+ /** Re-renders on any surface-manager change. */
2369
+ function useManagerVersion(runtime) {
2370
+ return (0, react.useSyncExternalStore)(runtime?.manager.subscribe ?? noopSubscribe$1, runtime?.manager.getVersion ?? zero, zero);
2371
+ }
2372
+ /**
2373
+ * Experimental. Gives one key of the app state declared in
2374
+ * `createGenerativeUI({ state })` its value. Bound props of generated
2375
+ * components read it. The model does not see it.
2376
+ *
2377
+ * The key is set on mount and when the value changes (compared as JSON). It
2378
+ * is removed on unmount.
2379
+ *
2380
+ * @param ui - The object from `createGenerativeUI`. It gives the key and the
2381
+ * value their types.
2382
+ * @param key - A top-level key of `state`.
2383
+ * @param value - The value of that key. It must fit the key's schema.
2384
+ *
2385
+ * @example
2386
+ * ```tsx
2387
+ * useGenerativeUIState(storeUI, "cart", { count, total, coupon, items });
2388
+ * ```
2389
+ */
2390
+ function useGenerativeUIState(ui, key, value) {
2391
+ const runtime = useRequiredGenerativeUIRuntime();
2392
+ const serialized = JSON.stringify(value);
2393
+ (0, react.useEffect)(() => {
2394
+ const raw = JSON.parse(serialized ?? "null");
2395
+ let current = true;
2396
+ const apply = (parsed) => {
2397
+ if (!current) return;
2398
+ if (parsed.success) {
2399
+ runtime.manager.setState(key, parsed.data);
2400
+ return;
2401
+ }
2402
+ runtime.manager.removeState(key);
2403
+ if (process.env.NODE_ENV !== "production") console.error(`[generativeUI] useGenerativeUIState: invalid value for "${key}": ${formatIssues(parsed.issues, "value")}`);
2404
+ };
2405
+ const schema = runtime.ui.state.get(key);
2406
+ const parsed = schema ? validateSchema(schema, raw) : {
2407
+ success: true,
2408
+ data: raw
2409
+ };
2410
+ if (parsed instanceof Promise) parsed.then(apply);
2411
+ else apply(parsed);
2412
+ return () => {
2413
+ current = false;
2414
+ };
2415
+ }, [
2416
+ runtime,
2417
+ key,
2418
+ serialized
2419
+ ]);
2420
+ (0, react.useEffect)(() => () => runtime.manager.removeState(key), [runtime, key]);
2421
+ }
2422
+ /**
2423
+ * Experimental. Mounts the handler of a function declared in
2424
+ * `createGenerativeUI({ functions })`. Generated UI can call the function
2425
+ * only while exactly one handler for it is mounted.
2426
+ *
2427
+ * The handler gets the parsed arguments: schema defaults are set. It can
2428
+ * change on each render. The latest handler always runs, and the hook does
2429
+ * not register again.
2430
+ *
2431
+ * @param ui - The object from `createGenerativeUI`. It gives the name and the
2432
+ * handler arguments their types.
2433
+ * @param name - A key of `functions`.
2434
+ * @param handler - Runs when generated UI calls the function. Its return
2435
+ * value goes back to the caller as `{ ok: true, result }`.
2436
+ *
2437
+ * @example
2438
+ * ```tsx
2439
+ * useGenerativeUIFunction(storeUI, "addToCart", ({ productId, quantity }) =>
2440
+ * cart.addItem(productId, quantity),
2441
+ * );
2442
+ * ```
2443
+ */
2444
+ function useGenerativeUIFunction(ui, name, handler) {
2445
+ const runtime = useRequiredGenerativeUIRuntime();
2446
+ const latest = (0, react.useRef)(handler);
2447
+ latest.current = handler;
2448
+ (0, react.useEffect)(() => runtime.dispatcher.register(name, latest), [runtime, name]);
2449
+ }
2450
+
2451
+ //#endregion
2452
+ //#region src/generative-ui/boundaries.tsx
2453
+ function DefaultNodeFallback({ message, componentId, retry }) {
2454
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2455
+ role: "alert",
2456
+ "data-generative-ui-error": componentId,
2457
+ style: {
2458
+ border: "1px solid #fca5a5",
2459
+ background: "#fef2f2",
2460
+ color: "#991b1b",
2461
+ borderRadius: 8,
2462
+ padding: "8px 12px",
2463
+ fontSize: 13
2464
+ },
2465
+ children: [
2466
+ "Couldn’t display this part: ",
2467
+ message,
2468
+ retry && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
2469
+ type: "button",
2470
+ onClick: retry,
2471
+ style: {
2472
+ marginLeft: 8,
2473
+ textDecoration: "underline"
2474
+ },
2475
+ children: "Retry"
2476
+ })
2477
+ ]
2478
+ });
2479
+ }
2480
+ /**
2481
+ * A child that has not streamed yet renders nothing. The prose keeps
2482
+ * streaming above the surface, and each component appears as soon as it is
2483
+ * complete. A grey block in its place would read as a broken layout.
2484
+ */
2485
+ function NodePlaceholder(_props) {
2486
+ return null;
2487
+ }
2488
+ /** Per-node boundary. Resets on retry or a new agent revision, not on data ticks. */
2489
+ var NodeBoundary = class extends react.Component {
2490
+ constructor(..._args) {
2491
+ super(..._args);
2492
+ this.state = {
2493
+ error: null,
2494
+ revision: this.props.revision
2495
+ };
2496
+ this.retry = () => this.setState({ error: null });
2497
+ }
2498
+ static getDerivedStateFromError(error) {
2499
+ return { error };
2500
+ }
2501
+ static getDerivedStateFromProps(props, state) {
2502
+ return props.revision !== state.revision ? {
2503
+ error: null,
2504
+ revision: props.revision
2505
+ } : null;
2506
+ }
2507
+ componentDidCatch(error) {
2508
+ const { runtime, surfaceId, componentId } = this.props;
2509
+ reportErrorSafely(runtime, {
2510
+ kind: "render",
2511
+ surfaceId,
2512
+ componentId,
2513
+ error
2514
+ });
2515
+ }
2516
+ render() {
2517
+ const { error } = this.state;
2518
+ if (!error) return this.props.children;
2519
+ const { runtime, surfaceId, componentId } = this.props;
2520
+ const fallback = runtime.errorFallback;
2521
+ return fallback ? fallback({
2522
+ error,
2523
+ retry: this.retry,
2524
+ surfaceId,
2525
+ componentId
2526
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2527
+ message: error.message,
2528
+ componentId,
2529
+ retry: this.retry
2530
+ });
2531
+ }
2532
+ };
2533
+ /** Outer boundary: a failure here must not reach the chat or the host page. */
2534
+ var SurfaceBoundary = class extends react.Component {
2535
+ constructor(..._args2) {
2536
+ super(..._args2);
2537
+ this.state = { error: null };
2538
+ }
2539
+ static getDerivedStateFromError(error) {
2540
+ return { error };
2541
+ }
2542
+ componentDidCatch(error) {
2543
+ reportErrorSafely(this.props.runtime, {
2544
+ kind: "render",
2545
+ surfaceId: this.props.surfaceId,
2546
+ error
2547
+ });
2548
+ }
2549
+ render() {
2550
+ if (!this.state.error) return this.props.children;
2551
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2552
+ message: "this generated UI failed to render",
2553
+ componentId: "surface"
2554
+ });
2555
+ }
2556
+ };
2557
+
2558
+ //#endregion
2559
+ //#region src/generative-ui/accessibility.ts
2560
+ const LIVE = new Set([
2561
+ "off",
2562
+ "polite",
2563
+ "assertive"
2564
+ ]);
2565
+ /**
2566
+ * The accessibility of a component from its resolved `accessibility`
2567
+ * value. Fields of the wrong type are left out: a label that is still a
2568
+ * binding, or a list, names nothing.
2569
+ */
2570
+ function readAccessibility(value) {
2571
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return;
2572
+ const { label, description, live, hidden } = value;
2573
+ const result = {};
2574
+ if (typeof label === "string" && label !== "") result.label = label;
2575
+ if (typeof description === "string" && description !== "") result.description = description;
2576
+ if (typeof live === "string" && LIVE.has(live)) result.live = live;
2577
+ if (typeof hidden === "boolean") result.hidden = hidden;
2578
+ return Object.keys(result).length > 0 ? result : void 0;
2579
+ }
2580
+ /**
2581
+ * The ARIA attributes for an `accessibility`. `live: "off"` is written out:
2582
+ * a region inherits the live setting of its ancestors, and a `status` role
2583
+ * is live on its own, so only the explicit value silences it.
2584
+ *
2585
+ * @example
2586
+ * ```ts
2587
+ * accessibilityAttributes({ label: "Totals", live: "polite" });
2588
+ * // { "aria-label": "Totals", "aria-live": "polite" }
2589
+ * ```
2590
+ */
2591
+ function accessibilityAttributes(accessibility) {
2592
+ if (!accessibility) return {};
2593
+ const { label, description, live, hidden } = accessibility;
2594
+ return {
2595
+ ...label === void 0 ? {} : { "aria-label": label },
2596
+ ...description === void 0 ? {} : { "aria-description": description },
2597
+ ...live === void 0 ? {} : { "aria-live": live },
2598
+ ...hidden ? { "aria-hidden": true } : {}
2599
+ };
2600
+ }
2601
+ /**
2602
+ * Experimental. The ARIA attributes of the `accessibility` that the model
2603
+ * gave the component being rendered, to spread on its root element. The
2604
+ * standard components do this; a custom component does it itself:
2605
+ *
2606
+ * @example
2607
+ * ```tsx
2608
+ * function Panel({ children }: { children?: ReactNode }) {
2609
+ * const aria = useGenerativeUIAccessibility();
2610
+ * return <section {...aria}>{children}</section>;
2611
+ * }
2612
+ * ```
2613
+ *
2614
+ * Outside of generated UI it gives `{}`.
2615
+ */
2616
+ function useGenerativeUIAccessibility() {
2617
+ const accessibility = (0, react.useContext)(GenerativeUINodeContext)?.accessibility;
2618
+ return (0, react.useMemo)(() => accessibilityAttributes(accessibility), [accessibility]);
2619
+ }
2620
+ /**
2621
+ * The role of a container that the envelope names. A generic element
2622
+ * cannot carry a name, so a label or a description makes it a `group`,
2623
+ * unless the component has a role of its own.
2624
+ */
2625
+ function namedRole(aria, explicit) {
2626
+ if (explicit !== void 0) return explicit;
2627
+ return aria["aria-label"] !== void 0 || aria["aria-description"] !== void 0 ? "group" : void 0;
2628
+ }
2629
+ /**
2630
+ * The part of the attributes for the focusable control of a labelled pair:
2631
+ * its name and its description. ARIA names are not inherited, so the
2632
+ * wrapper of a control cannot name it.
2633
+ */
2634
+ function controlAria(aria) {
2635
+ const { "aria-label": label, "aria-description": description } = aria;
2636
+ return {
2637
+ ...label === void 0 ? {} : { "aria-label": label },
2638
+ ...description === void 0 ? {} : { "aria-description": description }
2639
+ };
2640
+ }
2641
+ /**
2642
+ * The part of the attributes for the wrapper around a control: hidden and
2643
+ * live cover the label and the control together.
2644
+ */
2645
+ function wrapperAria(aria) {
2646
+ const { "aria-hidden": hidden, "aria-live": live } = aria;
2647
+ return {
2648
+ ...hidden === void 0 ? {} : { "aria-hidden": hidden },
2649
+ ...live === void 0 ? {} : { "aria-live": live }
2650
+ };
2651
+ }
2652
+
2653
+ //#endregion
2654
+ //#region src/generative-ui/events.ts
2655
+ /**
2656
+ * The context of a running event binding: it reads the surface data model
2657
+ * and resolves relative paths against the template item of the component.
2658
+ * A function that needs a user gesture (openUrl) is not a value here
2659
+ * either; it runs through the dispatcher as the binding's functionCall.
2660
+ */
2661
+ function eventContext(surface, basePath) {
2662
+ return {
2663
+ data: surface.model.dataModel,
2664
+ basePath
2665
+ };
2666
+ }
2667
+ /**
2668
+ * A value of an event binding with its dynamic values resolved: `{"@path"}`
2669
+ * bindings and function values, at any depth.
2670
+ */
2671
+ function resolveValue(surface, basePath, value) {
2672
+ return resolveDynamicValue(value, eventContext(surface, basePath)).value;
2673
+ }
2674
+ /**
2675
+ * The entries of an args or context record, each resolved on its own. The
2676
+ * record is not resolved as a whole, because a record with one `event` or
2677
+ * `functionCall` key would look like an action binding and stay as it is.
2678
+ */
2679
+ function resolveValues(surface, basePath, values) {
2680
+ return Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [key, resolveValue(surface, basePath, value)]));
2681
+ }
2682
+ /**
2683
+ * The `userMessage` of an event binding, as text. A `{"@path"}` or a
2684
+ * function value is resolved. `undefined` when there is no message, or
2685
+ * the value is not a string.
2686
+ */
2687
+ function resolveUserMessage(surface, basePath, userMessage) {
2688
+ const value = resolveValue(surface, basePath, userMessage);
2689
+ return typeof value === "string" ? value : void 0;
2690
+ }
2691
+ /**
2692
+ * Validates the component's args with the event `parameters`, then runs
2693
+ * `send` with them. Never throws: every failure is reported and becomes
2694
+ * `{ ok: false, error }`.
2695
+ */
2696
+ async function runEvent(call, send) {
2697
+ const { runtime, surface, componentId, name, parameters, args } = call;
2698
+ const origin = {
2699
+ surfaceId: surface.surfaceId,
2700
+ componentId
2701
+ };
2702
+ try {
2703
+ if (!parameters) return await send(args ?? {}, origin);
2704
+ const result = validateSchema(parameters, args ?? {});
2705
+ const parsed = result instanceof Promise ? await result : result;
2706
+ if (!parsed.success) {
2707
+ const error = new GenerativeUIError("invalid_event_args", `${name}: ${formatIssues(parsed.issues, "args")}`);
2708
+ reportErrorSafely(runtime, {
2709
+ kind: "event",
2710
+ ...origin,
2711
+ error
2712
+ });
2713
+ return {
2714
+ ok: false,
2715
+ error
2716
+ };
2717
+ }
2718
+ return await send(parsed.data ?? {}, origin);
2719
+ } catch (cause) {
2720
+ const error = new GenerativeUIError("event_forward_failed", `${name}: ${cause instanceof Error ? cause.message : String(cause)}`);
2721
+ reportErrorSafely(runtime, {
2722
+ kind: "event",
2723
+ ...origin,
2724
+ error
2725
+ });
2726
+ return {
2727
+ ok: false,
2728
+ error
2729
+ };
2730
+ }
2731
+ }
2732
+ /**
2733
+ * Runs one call of an event that the model bound: validates the component's
2734
+ * args, merges them with the args from the binding (binding literals win),
2735
+ * then calls a declared function or forwards an agent event. Never throws.
2736
+ */
2737
+ function invokeBoundEvent(params) {
2738
+ const { runtime, surface, binding, basePath } = params;
2739
+ return runEvent(params, (args, origin) => {
2740
+ const componentArgs = args;
2741
+ if ("functionCall" in binding) return runtime.dispatcher.invoke(binding.functionCall["@call"], {
2742
+ ...componentArgs,
2743
+ ...resolveValues(surface, basePath, binding.functionCall.args)
2744
+ }, origin);
2745
+ const { event } = binding;
2746
+ const forwarded = {
2747
+ name: event.name,
2748
+ ...origin,
2749
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2750
+ userMessage: resolveUserMessage(surface, basePath, event.userMessage),
2751
+ context: {
2752
+ ...componentArgs,
2753
+ ...resolveValues(surface, basePath, event.context)
2754
+ }
2755
+ };
2756
+ return runtime.forwardEvent(forwarded, surface.agentId);
2757
+ });
2758
+ }
2759
+ /**
2760
+ * Runs one call of an event that matches a declared function: validates the
2761
+ * component's args with the event `parameters` (if any), then calls the
2762
+ * function, which validates them with its own schema. Never throws.
2763
+ */
2764
+ function invokeMatchedEvent(params) {
2765
+ const { runtime, functionName } = params;
2766
+ return runEvent(params, (componentArgs, origin) => runtime.dispatcher.invoke(functionName, componentArgs, origin));
2767
+ }
2768
+
2769
+ //#endregion
2770
+ //#region src/generative-ui/theme.ts
2771
+ /**
2772
+ * The built-in dark values. The light values are the fallbacks in the
2773
+ * components, so a surface is light when no variable is set.
2774
+ */
2775
+ const DARK_THEME = {
2776
+ "--a2ui-color-text-default": "#ececec",
2777
+ "--a2ui-color-text-prose": "#ececec",
2778
+ "--a2ui-color-text-primary": "#ececec",
2779
+ "--a2ui-color-text-emphasis": "#fff",
2780
+ "--a2ui-color-text-secondary": "#b4b4b4",
2781
+ "--a2ui-color-text-tertiary": "#8e8e8e",
2782
+ "--a2ui-color-text-success": "#4fd1a5",
2783
+ "--a2ui-color-text-info": "#6cb6ff",
2784
+ "--a2ui-color-text-warning": "#e3b341",
2785
+ "--a2ui-color-text-caution": "#e3b341",
2786
+ "--a2ui-color-text-danger": "#ff7b72",
2787
+ "--a2ui-color-text-discovery": "#bc9cff",
2788
+ "--a2ui-color-surface": "#1f1f1f",
2789
+ "--a2ui-color-surface-secondary": "#2a2a2a",
2790
+ "--a2ui-color-surface-tertiary": "#3a3a3a",
2791
+ "--a2ui-color-surface-elevated": "#262626",
2792
+ "--a2ui-color-surface-elevated-secondary": "#2f2f2f",
2793
+ "--a2ui-color-surface-inverted": "#f2f2f2",
2794
+ "--a2ui-color-surface-soft": "#232323",
2795
+ "--a2ui-color-info": "rgba(80, 160, 255, 0.14)",
2796
+ "--a2ui-color-warning": "rgba(240, 180, 60, 0.14)",
2797
+ "--a2ui-color-caution": "rgba(240, 180, 60, 0.14)",
2798
+ "--a2ui-color-success": "rgba(60, 200, 150, 0.14)",
2799
+ "--a2ui-color-danger": "rgba(255, 110, 100, 0.14)",
2800
+ "--a2ui-color-discovery": "rgba(170, 130, 255, 0.14)",
2801
+ "--a2ui-color-info-soft": "rgba(80, 160, 255, 0.08)",
2802
+ "--a2ui-color-warning-soft": "rgba(240, 180, 60, 0.08)",
2803
+ "--a2ui-color-caution-soft": "rgba(240, 180, 60, 0.08)",
2804
+ "--a2ui-color-success-soft": "rgba(60, 200, 150, 0.08)",
2805
+ "--a2ui-color-danger-soft": "rgba(255, 110, 100, 0.08)",
2806
+ "--a2ui-color-discovery-soft": "rgba(170, 130, 255, 0.08)",
2807
+ "--a2ui-color-info-solid": "#3b8eea",
2808
+ "--a2ui-color-warning-solid": "#c99a2e",
2809
+ "--a2ui-color-caution-solid": "#c99a2e",
2810
+ "--a2ui-color-success-solid": "#2fae86",
2811
+ "--a2ui-color-danger-solid": "#e5534b",
2812
+ "--a2ui-color-discovery-solid": "#9a6ff0",
2813
+ "--a2ui-color-border-default": "rgba(255, 255, 255, 0.12)",
2814
+ "--a2ui-color-border-subtle": "rgba(255, 255, 255, 0.06)",
2815
+ "--a2ui-color-border-strong": "#4a4a4a",
2816
+ "--a2ui-color-border-info": "#2f5f8f",
2817
+ "--a2ui-color-border-warning": "#6b5420",
2818
+ "--a2ui-color-border-caution": "#6b5420",
2819
+ "--a2ui-color-border-success": "#1f5f4b",
2820
+ "--a2ui-color-border-danger": "#7a2f2b",
2821
+ "--a2ui-color-border-discovery": "#4f3a80",
2822
+ "--a2ui-color-border-control": "rgba(255, 255, 255, 0.2)",
2823
+ "--a2ui-color-accent": "#f2f2f2",
2824
+ "--a2ui-color-on-accent": "#0d0d0d",
2825
+ "--a2ui-color-panel": "#262626",
2826
+ "--a2ui-color-control": "#2f2f2f",
2827
+ "--a2ui-color-focus": "#3b9bff",
2828
+ "--a2ui-color-shimmer": "rgba(255, 255, 255, 0.12)",
2829
+ "--a2ui-color-chart-cursor": "rgba(255, 255, 255, 0.06)",
2830
+ "--a2ui-color-slider-track": "rgba(255, 255, 255, 0.1)",
2831
+ "--a2ui-color-badge-secondary": "rgba(255, 255, 255, 0.08)",
2832
+ "--a2ui-color-highlight-green": "#1d4a37",
2833
+ "--a2ui-color-highlight-orange": "#4d3418",
2834
+ "--a2ui-color-highlight-pink": "#4d2338",
2835
+ "--a2ui-shadow-xs": "0 1px 2px rgba(0, 0, 0, 0.5)",
2836
+ "--a2ui-shadow-sm": "0 1px 3px rgba(0, 0, 0, 0.5)",
2837
+ "--a2ui-shadow-soft": "0 1px 3px rgba(0, 0, 0, 0.3)",
2838
+ "--a2ui-shadow-md": "0 4px 12px rgba(0, 0, 0, 0.4)"
2839
+ };
2840
+ const VARIABLE_NAME = /^--a2ui-[a-z0-9-]+$/;
2841
+ const UNSAFE_VALUE = /[{};<>]/;
2842
+ /** Matches the `dark` class on an ancestor of a surface, or on the surface. */
2843
+ const DARK = ":where(.dark)";
2844
+ /** The default dark values, as a rule that any theme rule beats. */
2845
+ const DARK_THEME_CSS = `:where(.dark .a2ui-surface,.a2ui-surface.dark){${declarations(DARK_THEME)}}`;
2846
+ function declarations(values) {
2847
+ return Object.entries(values ?? {}).filter(([name, value]) => VARIABLE_NAME.test(name) && typeof value === "string" && !UNSAFE_VALUE.test(value)).map(([name, value]) => `${name}:${value}`).join(";");
2848
+ }
2849
+ /** A short, stable id for a stylesheet. */
2850
+ function hashOf(text) {
2851
+ let hash = 5381;
2852
+ for (let index = 0; index < text.length; index++) hash = hash * 33 ^ text.charCodeAt(index);
2853
+ return `t${(hash >>> 0).toString(36)}`;
2854
+ }
2855
+ /**
2856
+ * The stylesheet of a theme: its values on the surfaces that carry its id,
2857
+ * then its dark values in dark mode. `undefined` when the theme sets no
2858
+ * variable. Values that could break out of the rule are left out.
2859
+ *
2860
+ * @example
2861
+ * ```ts
2862
+ * themeStyleSheet({ "--a2ui-color-accent": "red" });
2863
+ * // { id: "t…", css: '.a2ui-surface[data-a2ui-theme="t…"]{--a2ui-color-accent:red}' }
2864
+ * ```
2865
+ */
2866
+ function themeStyleSheet(theme) {
2867
+ const { dark, ...base } = theme ?? {};
2868
+ const both = declarations(base);
2869
+ const darkOnly = declarations(dark);
2870
+ if (!both && !darkOnly) return void 0;
2871
+ const id = hashOf(`${both}|${darkOnly}`);
2872
+ const self = `.a2ui-surface[data-a2ui-theme="${id}"]`;
2873
+ return {
2874
+ id,
2875
+ css: [both && `${self}{${both}}`, darkOnly && `${DARK} ${self},${self}${DARK}{${darkOnly}}`].filter(Boolean).join("")
2876
+ };
2877
+ }
2878
+
2879
+ //#endregion
2880
+ //#region src/generative-ui/SurfaceView.tsx
2881
+ const NO_ANCESTORS = [];
2882
+ const ROOT_STYLE = { display: "contents" };
2883
+ const undefinedSnapshot = () => void 0;
2884
+ const noopSubscribe = () => () => {};
2885
+ const zeroSnapshot = () => 0;
2886
+ /** A "multiple" slot value that repeats a component for each list item. */
2887
+ function isTemplateChildren(value) {
2888
+ return typeof value === "object" && value !== null && "componentId" in value && typeof value.componentId === "string" && "path" in value && typeof value.path === "string";
2889
+ }
2890
+ function SurfaceView({ surface }) {
2891
+ const runtime = useRequiredGenerativeUIRuntime();
2892
+ const { theme } = runtime;
2893
+ const sheet = (0, react.useMemo)(() => themeStyleSheet(theme), [theme]);
2894
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2895
+ className: "a2ui-surface",
2896
+ "data-generative-ui-root": surface.surfaceId,
2897
+ "data-a2ui-theme": sheet?.id,
2898
+ style: ROOT_STYLE,
2899
+ children: [sheet ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("style", { dangerouslySetInnerHTML: { __html: sheet.css } }) : null, /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceBoundary, {
2900
+ surfaceId: surface.surfaceId,
2901
+ runtime,
2902
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
2903
+ surface,
2904
+ componentId: _copilotkit_shared.GENERATIVE_UI_ROOT_ID,
2905
+ basePath: void 0,
2906
+ ancestors: NO_ANCESTORS
2907
+ })
2908
+ })]
2909
+ });
2910
+ }
2911
+ /**
2912
+ * Resolves a component by id. Subscribes to the manager rather than web_core's
2913
+ * `onCreated`/`onDeleted`: web_core's EventEmitter awaits each listener in turn,
2914
+ * so with several subscribers (one per slotted child, or one per mount of the
2915
+ * same surface) all but the first are notified a microtask late. That is only
2916
+ * visible inside synchronous flushes such as `act()` / `flushSync`, where the
2917
+ * old tree would still be on screen, but it makes updates order-dependent.
2918
+ * The manager notifies synchronously once an ingest has been fully applied.
2919
+ */
2920
+ function useComponentModel(manager, model, id) {
2921
+ return (0, react.useSyncExternalStore)(manager.subscribe, () => model.componentsModel.get(id), undefinedSnapshot);
2922
+ }
2923
+ /** Same reasoning as `useComponentModel`: never rely on web_core's emitters. */
2924
+ function useComponentProperties(manager, component) {
2925
+ return (0, react.useSyncExternalStore)(manager.subscribe, () => component?.properties, undefinedSnapshot);
2926
+ }
2927
+ /**
2928
+ * The id of a node in the ancestor list. A template renders the same
2929
+ * component once per item, so the item path is part of the id. A real cycle
2930
+ * repeats both.
2931
+ */
2932
+ function scopedId(componentId, basePath) {
2933
+ return `${basePath ?? ""}#${componentId}`;
2934
+ }
2935
+ const NodeView = (0, react.memo)(function NodeView({ surface, componentId, basePath, ancestors }) {
2936
+ const runtime = useRequiredGenerativeUIRuntime();
2937
+ const component = useComponentModel(runtime.manager, surface.model, componentId);
2938
+ const properties = useComponentProperties(runtime.manager, component);
2939
+ if (ancestors.includes(scopedId(componentId, basePath))) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2940
+ message: `cyclic reference to ${componentId}`,
2941
+ componentId
2942
+ });
2943
+ if (!component || !properties) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodePlaceholder, { componentId });
2944
+ const definition = runtime.ui.components.get(component.type);
2945
+ if (!definition) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
2946
+ message: `unknown component "${component.type}"`,
2947
+ componentId
2948
+ });
2949
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeBoundary, {
2950
+ surfaceId: surface.surfaceId,
2951
+ componentId,
2952
+ revision: properties,
2953
+ runtime,
2954
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ResolvedNode, {
2955
+ surface,
2956
+ componentId,
2957
+ definition,
2958
+ properties,
2959
+ runtime,
2960
+ basePath,
2961
+ ancestors
2962
+ })
2963
+ }, component.type);
2964
+ });
2965
+ /**
2966
+ * Renders the component of a template once for each item of the list at the
2967
+ * template path, keyed by index. Renders nothing when there is no list.
2968
+ */
2969
+ function TemplateChildren({ surface, template, basePath, ancestors }) {
2970
+ const dataModel = surface.model.dataModel;
2971
+ const listPath = resolvePath(template.path, basePath);
2972
+ const subscribe = (0, react.useCallback)((onChange) => {
2973
+ const subscription = dataModel.subscribe(listPath, onChange);
2974
+ return () => subscription.unsubscribe();
2975
+ }, [dataModel, listPath]);
2976
+ const getCount = () => {
2977
+ const list = dataModel.get(listPath);
2978
+ return Array.isArray(list) ? list.length : 0;
2979
+ };
2980
+ const count = (0, react.useSyncExternalStore)(subscribe, getCount, zeroSnapshot);
2981
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: Array.from({ length: count }, (_, index) => index).map((index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
2982
+ surface,
2983
+ componentId: template.componentId,
2984
+ basePath: joinPath(listPath, String(index)),
2985
+ ancestors
2986
+ }, index)) });
2987
+ }
2988
+ /**
2989
+ * The props the model sets, with their dynamic values resolved from the
2990
+ * surface data model: `{"@path"}` bindings, `{"@call"}` function values and
2991
+ * `{"@call":"@index"}` in a template, at any depth. A literal writable prop
2992
+ * that the component set shows the local value from `overrides`. Bound
2993
+ * props, events and slots are left out, and so are the keys of the A2UI
2994
+ * component envelope; `accessibility` is resolved the same way and given
2995
+ * on its own.
2996
+ *
2997
+ * A prop is resolved again only when its raw value or a data model value it
2998
+ * read has changed, so the result keeps its identity otherwise. A function
2999
+ * value that cannot be computed gives a problem instead of values.
3000
+ */
3001
+ function useModelDataProps(surface, definition, properties, basePath, overrides) {
3002
+ const dataModel = surface.model.dataModel;
3003
+ const units = (0, react.useMemo)(() => {
3004
+ const list = [];
3005
+ for (const key of Object.keys(properties)) {
3006
+ if (definition.events?.[key] || definition.slots?.[key] || Object.hasOwn(definition.selectors, key) || _copilotkit_shared.A2UI_COMPONENT_ENVELOPE_KEYS.has(key)) continue;
3007
+ list.push({
3008
+ key,
3009
+ raw: properties[key]
3010
+ });
3011
+ }
3012
+ const a11y = properties.accessibility;
3013
+ if (typeof a11y === "object" && a11y !== null && !Array.isArray(a11y)) for (const [field, raw] of Object.entries(a11y)) list.push({
3014
+ key: `accessibility/${field}`,
3015
+ raw,
3016
+ field
3017
+ });
3018
+ return list;
3019
+ }, [properties, definition]);
3020
+ const [, rerender] = (0, react.useReducer)((n) => n + 1, 0);
3021
+ const cache = (0, react.useRef)(/* @__PURE__ */ new Map());
3022
+ const values = {};
3023
+ const a11yValues = {};
3024
+ const paths = /* @__PURE__ */ new Set();
3025
+ let problem;
3026
+ const next = /* @__PURE__ */ new Map();
3027
+ for (const { key, raw, field } of units) {
3028
+ const cached = cache.current.get(key);
3029
+ const isFresh = cached !== void 0 && cached.raw === raw && cached.basePath === basePath && [...cached.reads].every(([path, value]) => Object.is(dataModel.get(path), value));
3030
+ const resolve = () => {
3031
+ const resolved = tryResolveDynamicValue(raw, {
3032
+ data: dataModel,
3033
+ basePath
3034
+ }, { isChecks: key === "checks" });
3035
+ const reads = /* @__PURE__ */ new Map();
3036
+ for (const path of resolved.paths) reads.set(path, dataModel.get(path));
3037
+ return {
3038
+ raw,
3039
+ basePath,
3040
+ reads,
3041
+ outcome: resolved.ok ? {
3042
+ ok: true,
3043
+ value: resolved.value
3044
+ } : {
3045
+ ok: false,
3046
+ message: resolved.error.message
3047
+ }
3048
+ };
3049
+ };
3050
+ const entry = isFresh && cached ? cached : resolve();
3051
+ next.set(key, entry);
3052
+ if (field !== void 0) {
3053
+ if (entry.outcome.ok) a11yValues[field] = entry.outcome.value;
3054
+ } else if (entry.outcome.ok) values[key] = entry.outcome.value;
3055
+ else problem ??= `${key}: ${entry.outcome.message}`;
3056
+ for (const path of entry.reads.keys()) paths.add(path);
3057
+ }
3058
+ cache.current = next;
3059
+ const accessibility = readAccessibility(a11yValues);
3060
+ for (const [key, value] of Object.entries(overrides)) if (!(0, _copilotkit_shared.isPathBinding)(properties[key])) values[key] = value;
3061
+ const rendered = (0, react.useRef)(next);
3062
+ rendered.current = next;
3063
+ const pathKey = [...paths].sort().join("\n");
3064
+ (0, react.useEffect)(() => {
3065
+ const list = pathKey === "" ? [] : pathKey.split("\n");
3066
+ const onChange = () => {
3067
+ cache.current = /* @__PURE__ */ new Map();
3068
+ rerender();
3069
+ };
3070
+ const subscriptions = list.map((path) => dataModel.subscribe(path, onChange));
3071
+ if ([...rendered.current.values()].some((entry) => [...entry.reads].some(([path, value]) => !Object.is(dataModel.get(path), value)))) rerender();
3072
+ return () => subscriptions.forEach((s) => s.unsubscribe());
3073
+ }, [dataModel, pathKey]);
3074
+ const stable = (0, react.useRef)({
3075
+ ok: true,
3076
+ values: {},
3077
+ accessibility: void 0
3078
+ });
3079
+ const result = problem === void 0 ? {
3080
+ ok: true,
3081
+ values,
3082
+ accessibility
3083
+ } : {
3084
+ ok: false,
3085
+ problem
3086
+ };
3087
+ const last = stable.current;
3088
+ if (!(result.ok && last.ok ? shallowEqual(last.values, result.values) && shallowEqual(last.accessibility ?? {}, result.accessibility ?? {}) : !result.ok && !last.ok && last.problem === result.problem)) stable.current = result;
3089
+ return stable.current;
3090
+ }
3091
+ const NO_SELECTION = {
3092
+ ok: true,
3093
+ values: {}
3094
+ };
3095
+ function isSameSelection(a, b) {
3096
+ if (a.ok && b.ok) return shallowEqual(a.values, b.values);
3097
+ if (!a.ok && !b.ok) return a.problem === b.problem;
3098
+ return false;
3099
+ }
3100
+ /** Runs every selector of a node. A selector that throws gives a problem. */
3101
+ function select(definition, state, modelProps) {
3102
+ const values = {};
3103
+ const selectors = Object.entries(definition.selectors);
3104
+ for (const [key, selector] of selectors) try {
3105
+ values[key] = selector(state, modelProps);
3106
+ } catch (error) {
3107
+ return {
3108
+ ok: false,
3109
+ problem: `${key}: selector threw: ${error instanceof Error ? error.message : String(error)}`
3110
+ };
3111
+ }
3112
+ return {
3113
+ ok: true,
3114
+ values
3115
+ };
3116
+ }
3117
+ /**
3118
+ * The values of the bound props of a node, read from the app state.
3119
+ *
3120
+ * The selectors run again only when the state object or the parsed model
3121
+ * props change. When the new values are shallow-equal to the last ones, the
3122
+ * last snapshot is kept. So the node re-renders only when a selected value
3123
+ * changes. A selector that returns a new array on each call cannot cause a
3124
+ * render loop: with the same inputs, the cached snapshot comes back.
3125
+ *
3126
+ * A node without bound props does not subscribe to the state.
3127
+ */
3128
+ function useSelection(manager, definition, modelProps) {
3129
+ const hasSelectors = Object.keys(definition.selectors).length > 0;
3130
+ const cache = (0, react.useRef)(void 0);
3131
+ const getSnapshot = () => {
3132
+ if (!hasSelectors || modelProps === void 0) return NO_SELECTION;
3133
+ const state = manager.getState();
3134
+ const cached = cache.current;
3135
+ if (cached !== void 0 && cached.state === state && cached.modelProps === modelProps) return cached.selection;
3136
+ const next = select(definition, state, modelProps);
3137
+ const selection = cached !== void 0 && isSameSelection(cached.selection, next) ? cached.selection : next;
3138
+ cache.current = {
3139
+ state,
3140
+ modelProps,
3141
+ selection
3142
+ };
3143
+ return selection;
3144
+ };
3145
+ return (0, react.useSyncExternalStore)(hasSelectors ? manager.subscribe : noopSubscribe, getSnapshot, getSnapshot);
3146
+ }
3147
+ /**
3148
+ * Checks the model-set props with the props schema before the selectors run.
3149
+ * The bound props are not set yet, so their issues do not count. Neither do
3150
+ * issues with no path (a check over several props), which the full check
3151
+ * after the selectors reports.
3152
+ */
3153
+ function checkModelProps(definition, modelData) {
3154
+ if (!definition.props) return {
3155
+ ok: true,
3156
+ values: {}
3157
+ };
3158
+ let values = modelData;
3159
+ let result = validateSchemaSync(definition.props, values);
3160
+ if (!result.success) {
3161
+ const unset = withoutRejectedNulls(values, result.issues);
3162
+ if (unset) {
3163
+ values = unset;
3164
+ result = validateSchemaSync(definition.props, values);
3165
+ }
3166
+ }
3167
+ if (!result.success) {
3168
+ const issues = result.issues.filter((issue) => {
3169
+ const key = issueKey(issue);
3170
+ return key === void 0 ? isAsyncIssue(issue) : !Object.hasOwn(definition.selectors, key);
3171
+ });
3172
+ if (issues.length > 0) return {
3173
+ ok: false,
3174
+ problem: formatIssues(issues)
3175
+ };
3176
+ }
3177
+ return {
3178
+ ok: true,
3179
+ values
3180
+ };
3181
+ }
3182
+ /**
3183
+ * The data props of a node, in three steps: check the model-set props with
3184
+ * the props schema, run the selectors with them, then parse all props with
3185
+ * the props schema. Gives the reason when a step fails.
3186
+ */
3187
+ function useDataProps(runtime, surface, definition, properties, basePath, overrides) {
3188
+ const modelData = useModelDataProps(surface, definition, properties, basePath, overrides);
3189
+ const modelCheck = (0, react.useMemo)(() => modelData.ok ? checkModelProps(definition, modelData.values) : modelData, [definition, modelData]);
3190
+ const selection = useSelection(runtime.manager, definition, modelCheck.ok ? modelCheck.values : void 0);
3191
+ const accessibility = modelData.ok ? modelData.accessibility : void 0;
3192
+ return (0, react.useMemo)(() => {
3193
+ if (!modelCheck.ok) return modelCheck;
3194
+ if (!selection.ok) return selection;
3195
+ if (!definition.props) return {
3196
+ ok: true,
3197
+ props: {},
3198
+ accessibility
3199
+ };
3200
+ const input = {
3201
+ ...modelCheck.values,
3202
+ ...selection.values
3203
+ };
3204
+ let parsed = validateSchemaSync(definition.props, input);
3205
+ if (!parsed.success) {
3206
+ const unset = withoutRejectedNulls(input, parsed.issues);
3207
+ if (unset) parsed = validateSchemaSync(definition.props, unset);
3208
+ }
3209
+ if (!parsed.success) return {
3210
+ ok: false,
3211
+ problem: formatIssues(parsed.issues)
3212
+ };
3213
+ return {
3214
+ ok: true,
3215
+ props: parsed.data,
3216
+ accessibility
3217
+ };
3218
+ }, [
3219
+ definition,
3220
+ modelCheck,
3221
+ selection,
3222
+ accessibility
3223
+ ]);
3224
+ }
3225
+ /**
3226
+ * The event props of a node. A matched event (one that matches a declared
3227
+ * function) is always bound. An unmatched event is bound only when the model
3228
+ * bound it.
3229
+ */
3230
+ function useEventProps(runtime, surface, componentId, definition, properties, basePath) {
3231
+ const latest = (0, react.useRef)(properties);
3232
+ latest.current = properties;
3233
+ const boundNames = Object.keys(definition.events ?? {}).filter((name) => Object.hasOwn(definition.eventFunctions, name) || (0, _copilotkit_shared.isActionBinding)(properties[name])).join("|");
3234
+ return (0, react.useMemo)(() => {
3235
+ const handlers = {};
3236
+ const names = boundNames ? boundNames.split("|") : [];
3237
+ for (const name of names) {
3238
+ const call = {
3239
+ runtime,
3240
+ surface,
3241
+ componentId,
3242
+ name,
3243
+ parameters: definition.events?.[name]?.parameters
3244
+ };
3245
+ const functionName = Object.hasOwn(definition.eventFunctions, name) ? definition.eventFunctions[name] : void 0;
3246
+ handlers[name] = functionName === void 0 ? (args) => invokeBoundEvent({
3247
+ ...call,
3248
+ binding: latest.current[name],
3249
+ basePath,
3250
+ args
3251
+ }) : (args) => invokeMatchedEvent({
3252
+ ...call,
3253
+ functionName,
3254
+ args
3255
+ });
3256
+ }
3257
+ return handlers;
3258
+ }, [
3259
+ boundNames,
3260
+ runtime,
3261
+ surface,
3262
+ componentId,
3263
+ definition,
3264
+ basePath
3265
+ ]);
3266
+ }
3267
+ /**
3268
+ * The setter props of a node: `setValue` for the writable prop `value`. For
3269
+ * a prop the model bound to `{"@path"}`, the setter writes the data model
3270
+ * and makes the path user-owned. For a literal prop, it sets `overrides`, a
3271
+ * local value of this mounted node. The setters keep their identity.
3272
+ */
3273
+ function useSetterProps(runtime, surface, componentId, definition, properties, basePath) {
3274
+ const [overrides, setOverrides] = (0, react.useState)({});
3275
+ const latest = (0, react.useRef)(properties);
3276
+ latest.current = properties;
3277
+ return {
3278
+ overrides,
3279
+ setters: (0, react.useMemo)(() => {
3280
+ const result = {};
3281
+ const writable = definition.writable ?? [];
3282
+ for (const key of writable) result[setterNameOf(key)] = (value) => {
3283
+ const binding = latest.current[key];
3284
+ if (!(0, _copilotkit_shared.isPathBinding)(binding)) {
3285
+ setOverrides((current) => ({
3286
+ ...current,
3287
+ [key]: value
3288
+ }));
3289
+ return;
3290
+ }
3291
+ try {
3292
+ runtime.manager.setOwnedValue(surface.key, resolvePath(binding["@path"], basePath), value);
3293
+ } catch (cause) {
3294
+ const message = cause instanceof Error ? cause.message : String(cause);
3295
+ reportErrorSafely(runtime, {
3296
+ kind: "props",
3297
+ surfaceId: surface.surfaceId,
3298
+ componentId,
3299
+ error: /* @__PURE__ */ new Error(`${setterNameOf(key)}: ${message}`)
3300
+ });
3301
+ }
3302
+ };
3303
+ return result;
3304
+ }, [
3305
+ runtime,
3306
+ surface,
3307
+ componentId,
3308
+ definition,
3309
+ basePath
3310
+ ])
3311
+ };
3312
+ }
3313
+ function useSlotProps(surface, definition, properties, componentId, basePath, ancestors) {
3314
+ return (0, react.useMemo)(() => {
3315
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
3316
+ const slots = {};
3317
+ for (const [name, kind] of Object.entries(definition.slots ?? {})) {
3318
+ const value = properties[name];
3319
+ if (kind === "single" && typeof value === "string") slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
3320
+ surface,
3321
+ componentId: value,
3322
+ basePath,
3323
+ ancestors: childAncestors
3324
+ });
3325
+ else if (kind === "multiple" && isTemplateChildren(value)) slots[name] = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
3326
+ surface,
3327
+ template: value,
3328
+ basePath,
3329
+ ancestors: childAncestors
3330
+ });
3331
+ else if (kind === "multiple" && Array.isArray(value)) slots[name] = [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
3332
+ surface,
3333
+ componentId: id,
3334
+ basePath,
3335
+ ancestors: childAncestors
3336
+ }, id));
3337
+ }
3338
+ return slots;
3339
+ }, [
3340
+ surface,
3341
+ definition,
3342
+ properties,
3343
+ componentId,
3344
+ basePath,
3345
+ ancestors
3346
+ ]);
3347
+ }
3348
+ /**
3349
+ * The parsed data props with every typed child reference (`child()`,
3350
+ * `childList()`, at any depth) replaced by the rendered component. Without
3351
+ * references, the parsed props come back as they are.
3352
+ */
3353
+ function useChildRefProps(surface, refs, props, componentId, basePath, ancestors) {
3354
+ return (0, react.useMemo)(() => {
3355
+ if (props === void 0 || refs.length === 0) return props;
3356
+ const childAncestors = [...ancestors, scopedId(componentId, basePath)];
3357
+ const render = (kind, value) => {
3358
+ if (kind === "single") return typeof value === "string" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
3359
+ surface,
3360
+ componentId: value,
3361
+ basePath,
3362
+ ancestors: childAncestors
3363
+ }) : void 0;
3364
+ if (isTemplateChildren(value)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TemplateChildren, {
3365
+ surface,
3366
+ template: value,
3367
+ basePath,
3368
+ ancestors: childAncestors
3369
+ });
3370
+ if (!Array.isArray(value)) return void 0;
3371
+ return [...new Set(value.filter((id) => typeof id === "string"))].map((id) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NodeView, {
3372
+ surface,
3373
+ componentId: id,
3374
+ basePath,
3375
+ ancestors: childAncestors
3376
+ }, id));
3377
+ };
3378
+ let result = props;
3379
+ for (const ref of refs) result = (0, _copilotkit_shared.mapAtChildRef)(result, ref.path, (found) => render(ref.kind, found));
3380
+ return result;
3381
+ }, [
3382
+ surface,
3383
+ refs,
3384
+ props,
3385
+ componentId,
3386
+ basePath,
3387
+ ancestors
3388
+ ]);
3389
+ }
3390
+ function ResolvedNode({ surface, componentId, definition, properties, runtime, basePath, ancestors }) {
3391
+ const { overrides, setters } = useSetterProps(runtime, surface, componentId, definition, properties, basePath);
3392
+ const dataProps = useDataProps(runtime, surface, definition, properties, basePath, overrides);
3393
+ const eventProps = useEventProps(runtime, surface, componentId, definition, properties, basePath);
3394
+ const slotProps = useSlotProps(surface, definition, properties, componentId, basePath, ancestors);
3395
+ const childRefProps = useChildRefProps(surface, definition.childRefs, dataProps.ok ? dataProps.props : void 0, componentId, basePath, ancestors);
3396
+ const accessibility = dataProps.ok ? dataProps.accessibility : void 0;
3397
+ const nodeContext = (0, react.useMemo)(() => ({
3398
+ surfaceKey: surface.key,
3399
+ surfaceId: surface.surfaceId,
3400
+ componentId,
3401
+ accessibility
3402
+ }), [
3403
+ surface.key,
3404
+ surface.surfaceId,
3405
+ componentId,
3406
+ accessibility
3407
+ ]);
3408
+ const problem = dataProps.ok ? void 0 : dataProps.problem;
3409
+ (0, react.useEffect)(() => {
3410
+ if (problem) reportErrorSafely(runtime, {
3411
+ kind: "props",
3412
+ surfaceId: surface.surfaceId,
3413
+ componentId,
3414
+ error: /* @__PURE__ */ new Error(`Invalid props: ${problem}`)
3415
+ });
3416
+ }, [
3417
+ problem,
3418
+ runtime,
3419
+ surface.surfaceId,
3420
+ componentId
3421
+ ]);
3422
+ if (!dataProps.ok) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DefaultNodeFallback, {
3423
+ message: `invalid props (${problem})`,
3424
+ componentId
3425
+ });
3426
+ const Component = definition.component;
3427
+ const rendered = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, {
3428
+ ...childRefProps,
3429
+ ...eventProps,
3430
+ ...slotProps,
3431
+ ...setters
3432
+ });
3433
+ const hasEnvelope = properties.accessibility !== void 0 && definition.accessibility !== "self";
3434
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(GenerativeUINodeContext.Provider, {
3435
+ value: nodeContext,
3436
+ children: hasEnvelope ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
3437
+ "data-a2ui-accessibility": "",
3438
+ style: ROOT_STYLE,
3439
+ ...wrapperAria(accessibilityAttributes(accessibility)),
3440
+ children: rendered
3441
+ }) : rendered
3442
+ });
3443
+ }
3444
+
3445
+ //#endregion
3446
+ //#region src/generative-ui/chat.tsx
3447
+ const GenerativeUIChatSlotContext = (0, react.createContext)(void 0);
3448
+ function DefaultGenerativeUIChatCard({ surfaceId, isStreaming, error, children }) {
3449
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3450
+ "data-generative-ui-chat-surface": surfaceId,
3451
+ className: "cpk:my-2 cpk:w-full cpk:rounded-xl cpk:border cpk:border-gray-200 cpk:p-3",
3452
+ children: [children, error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3453
+ role: "alert",
3454
+ className: "cpk:mt-2 cpk:text-xs cpk:text-red-600",
3455
+ children: "Part of this UI couldn't be shown."
3456
+ })]
3457
+ });
3458
+ }
3459
+ const ContentSchema = zod.z.object({
3460
+ surfaceId: zod.z.string(),
3461
+ target: zod.z.string(),
3462
+ catalogId: zod.z.string(),
3463
+ operations: zod.z.array(zod.z.any()),
3464
+ status: zod.z.enum([
3465
+ "streaming",
3466
+ "ready",
3467
+ "error"
3468
+ ]),
3469
+ rejected: zod.z.array(zod.z.object({
3470
+ index: zod.z.number(),
3471
+ reason: zod.z.string()
3472
+ })).default([])
3473
+ }).passthrough();
3474
+ function GenerativeUIChatActivity({ content, agent }) {
3475
+ const runtime = useGenerativeUIRuntime();
3476
+ const threadId = useCopilotChatConfiguration()?.threadId ?? agent?.threadId;
3477
+ const Wrapper = (0, react.useContext)(GenerativeUIChatSlotContext) ?? DefaultGenerativeUIChatCard;
3478
+ useManagerVersion(runtime);
3479
+ (0, react.useLayoutEffect)(() => {
3480
+ if (runtime && threadId) runtime.manager.ingest(threadId, agent?.agentId, content);
3481
+ }, [
3482
+ runtime,
3483
+ threadId,
3484
+ agent?.agentId,
3485
+ content
3486
+ ]);
3487
+ if (!runtime || !threadId || content.target !== _copilotkit_shared.GENERATIVE_UI_CHAT_TARGET) return null;
3488
+ const surface = runtime.manager.getSurface(threadId, content.surfaceId) ?? runtime.manager.getFailedSurface(threadId, content.surfaceId);
3489
+ if (!surface) return null;
3490
+ const rejected = [...content.rejected ?? [], ...surface.clientRejected];
3491
+ const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
3492
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
3493
+ surfaceId: content.surfaceId,
3494
+ isStreaming: content.status === "streaming",
3495
+ error,
3496
+ rejected,
3497
+ children: surface.failed ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceView, { surface })
3498
+ });
3499
+ }
3500
+ function createGenerativeUIActivityRenderer() {
3501
+ return {
3502
+ activityType: _copilotkit_shared.GENERATIVE_UI_ACTIVITY_TYPE,
3503
+ content: ContentSchema,
3504
+ render: GenerativeUIChatActivity
3505
+ };
3506
+ }
3507
+ /**
3508
+ * Shows nothing in the chat for an agent-called function. The root reads the
3509
+ * function-call activities from the messages and runs them. This renderer
3510
+ * only keeps a wildcard ("*") activity renderer from showing them.
3511
+ */
3512
+ function createGenerativeUIFunctionCallActivityRenderer() {
3513
+ return {
3514
+ activityType: _copilotkit_shared.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE,
3515
+ content: zod.z.unknown(),
3516
+ render: () => null
3517
+ };
3518
+ }
3519
+ /** Hides the raw `render_ui` tool call; the surface activity owns the UX. */
3520
+ function GenerativeUIToolCallRenderer() {
3521
+ const { copilotkit } = (0, _copilotkit_react_core_context.useCopilotKit)();
3522
+ (0, react.useEffect)(() => {
3523
+ const renderer = defineToolCallRenderer({
3524
+ name: _copilotkit_shared.GENERATIVE_UI_RENDER_TOOL,
3525
+ args: zod.z.any(),
3526
+ render: () => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, {})
3527
+ });
3528
+ const existing = copilotkit._renderToolCalls ?? [];
3529
+ copilotkit.setRenderToolCalls([...existing.filter((rc) => rc.name !== _copilotkit_shared.GENERATIVE_UI_RENDER_TOOL), renderer]);
3530
+ }, [copilotkit]);
3531
+ return null;
3532
+ }
3533
+
3534
+ //#endregion
3535
+ //#region src/generative-ui/markdown/ProviderMarkdown.tsx
3536
+ /**
3537
+ * Markdown prose inside generative UI, rendered like the chat text around
3538
+ * it: the renderer set on the provider when there is one, else the built-in
3539
+ * streaming renderer. Config passed here wins over provider config.
3540
+ */
3541
+ function ProviderMarkdown({ content, isStreaming, className, ...config }) {
3542
+ const renderer = useMarkdownRenderer();
3543
+ if (renderer && isReactComponentType(renderer)) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(renderer, {
3544
+ content,
3545
+ isStreaming,
3546
+ className
3547
+ });
3548
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(StreamingMarkdownDefaultRenderer, {
3549
+ ...renderer,
3550
+ ...config,
3551
+ content,
3552
+ isStreaming,
3553
+ className
3554
+ });
3555
+ }
3556
+
3557
+ //#endregion
3558
+ //#region src/generative-ui/markdown/MarkdownSurfaces.tsx
3559
+ const FADE_STYLE_ID = "a2ui-markdown-fade";
3560
+ /**
3561
+ * Components fade in as they stream: each element that appears under a
3562
+ * markdown surface runs the keyframes once on mount. React keeps the keys
3563
+ * stable per component id, so an element that is already there never
3564
+ * animates again. SVG internals are left out: a chart library re-creates
3565
+ * its nodes on each render, and a fade on each of them would read as the
3566
+ * chart flashing whenever a sibling arrives. The fade runs under reduced
3567
+ * motion too, because it moves nothing.
3568
+ */
3569
+ const FADE_CSS = ["@keyframes a2ui-fade-in{from{opacity:0}}", "[data-a2ui-markdown-surface] .a2ui-surface *:not(svg):not(svg *){animation:a2ui-fade-in .35s ease-out backwards}"].join("\n");
3570
+ const noEffect = () => {};
3571
+ const useInjectEffect = typeof document === "undefined" ? noEffect : react.useInsertionEffect;
3572
+ function useFadeStyles() {
3573
+ useInjectEffect(() => {
3574
+ if (document.getElementById(FADE_STYLE_ID)) return;
3575
+ const style = document.createElement("style");
3576
+ style.id = FADE_STYLE_ID;
3577
+ style.textContent = FADE_CSS;
3578
+ document.head.appendChild(style);
3579
+ }, []);
3580
+ }
3581
+ /**
3582
+ * The default wrapper of a chat surface in the markdown transport. It draws
3583
+ * no box: a surface sits in the flow of the reply like a paragraph, and a
3584
+ * Card draws its own box when it is interactive. Nothing shows while the
3585
+ * surface streams. A rejected operation gets one line.
3586
+ */
3587
+ function DefaultMarkdownChatSurface({ surfaceId, error, children }) {
3588
+ useFadeStyles();
3589
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
3590
+ "data-generative-ui-chat-surface": surfaceId,
3591
+ "data-a2ui-markdown-surface": surfaceId,
3592
+ className: "cpk:relative cpk:my-4 cpk:flex cpk:w-full cpk:min-w-0 cpk:max-w-full cpk:flex-col",
3593
+ children: [children, error && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
3594
+ role: "alert",
3595
+ className: "cpk:mt-2 cpk:text-xs cpk:text-red-600",
3596
+ children: "Part of this UI couldn't be shown."
3597
+ })]
3598
+ });
3599
+ }
3600
+ /**
3601
+ * One chat surface in the chat wrapper. Nothing renders until the surface
3602
+ * has its root component, so a half-streamed fence shows no empty card.
3603
+ */
3604
+ function ChatSurface({ runtime, threadId, surfaceId, Wrapper }) {
3605
+ const surface = runtime.manager.getSurface(threadId, surfaceId) ?? runtime.manager.getFailedSurface(threadId, surfaceId);
3606
+ const root = surface?.model.componentsModel.get(_copilotkit_shared.GENERATIVE_UI_ROOT_ID);
3607
+ if (!surface || !root && !surface.failed) return null;
3608
+ const rejected = [...surface.serverRejected, ...surface.clientRejected];
3609
+ const error = rejected.length ? new Error(`${rejected.length} UI update(s) could not be shown`, { cause: rejected }) : void 0;
3610
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
3611
+ surfaceId,
3612
+ isStreaming: surface.status === "streaming",
3613
+ error,
3614
+ rejected,
3615
+ children: surface.failed ? null : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SurfaceView, { surface })
3616
+ });
3617
+ }
3618
+ /** The blocks of one fence: lifted prose and chat surfaces, in order. */
3619
+ function FenceBlocks({ blocks, runtime, threadId, isStreaming, markdownProps }) {
3620
+ const Wrapper = (0, react.useContext)(GenerativeUIChatSlotContext) ?? DefaultMarkdownChatSurface;
3621
+ let surfaceCount = 0;
3622
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: blocks.map((block, index) => {
3623
+ if (block.kind === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProviderMarkdown, {
3624
+ ...markdownProps,
3625
+ content: block.markdown,
3626
+ isStreaming: isStreaming && index === blocks.length - 1
3627
+ }, `md-${surfaceCount}`);
3628
+ surfaceCount++;
3629
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ChatSurface, {
3630
+ runtime,
3631
+ threadId,
3632
+ surfaceId: block.surfaceId,
3633
+ Wrapper
3634
+ }, block.surfaceId);
3635
+ }) });
3636
+ }
3637
+ /**
3638
+ * Experimental. Renders an assistant message of the markdown transport.
3639
+ * Prose renders as markdown. In place of each ```a2ui fence:
3640
+ *
3641
+ * - the fence that created a chat surface renders that surface (and the
3642
+ * prose lifted out of it) in the chat wrapper;
3643
+ * - every other fence renders nothing: a fence that updates the surface of
3644
+ * an earlier fence, or a fence for a named target, which
3645
+ * `<GenerativeUISurface id>` renders.
3646
+ *
3647
+ * Use it inside `<CopilotKitProvider generativeUI={{ ui, transport: "markdown" }}>`.
3648
+ * `CopilotChatAssistantMessage` uses it there on its own.
3649
+ *
3650
+ * @example
3651
+ * ```tsx
3652
+ * <MarkdownSurfaces content={message.content} messageId={message.id} />
3653
+ * ```
3654
+ */
3655
+ function MarkdownSurfaces({ content, messageId, isStreaming = false, ...markdownProps }) {
3656
+ const runtime = useRequiredGenerativeUIRuntime();
3657
+ const chatThreadId = useCopilotChatConfiguration()?.threadId;
3658
+ useManagerVersion(runtime);
3659
+ const segments = (0, react.useMemo)(() => (0, _copilotkit_core.splitA2UIMarkdown)(content), [content]);
3660
+ const threadId = chatThreadId ?? runtime.manager.getActiveThread();
3661
+ const source = getMarkdownSurfaceSource(runtime);
3662
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: segments.map((segment, index) => {
3663
+ const isLast = index === segments.length - 1;
3664
+ if (segment.type === "markdown") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ProviderMarkdown, {
3665
+ ...markdownProps,
3666
+ content: segment.text,
3667
+ isStreaming: isStreaming && isLast
3668
+ }, `md-${index}`);
3669
+ const blocks = threadId ? source.getFenceBlocks(threadId, messageId, segment.index) : void 0;
3670
+ if (!threadId || !blocks) return null;
3671
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FenceBlocks, {
3672
+ blocks,
3673
+ runtime,
3674
+ threadId,
3675
+ isStreaming: isStreaming && isLast,
3676
+ markdownProps
3677
+ }, `a2ui-${segment.index}`);
3678
+ }) });
3679
+ }
3680
+
3681
+ //#endregion
3682
+ Object.defineProperty(exports, 'BASIC_FUNCTIONS', {
3683
+ enumerable: true,
3684
+ get: function () {
3685
+ return BASIC_FUNCTIONS;
3686
+ }
3687
+ });
3688
+ Object.defineProperty(exports, 'ControlledModalOpenScope', {
3689
+ enumerable: true,
3690
+ get: function () {
3691
+ return ControlledModalOpenScope;
3692
+ }
3693
+ });
3694
+ Object.defineProperty(exports, 'CopilotChatConfigurationProvider', {
3695
+ enumerable: true,
3696
+ get: function () {
3697
+ return CopilotChatConfigurationProvider;
3698
+ }
3699
+ });
3700
+ Object.defineProperty(exports, 'CopilotChatDefaultLabels', {
3701
+ enumerable: true,
3702
+ get: function () {
3703
+ return CopilotChatDefaultLabels;
3704
+ }
3705
+ });
3706
+ Object.defineProperty(exports, 'DARK_THEME_CSS', {
3707
+ enumerable: true,
3708
+ get: function () {
3709
+ return DARK_THEME_CSS;
3710
+ }
3711
+ });
3712
+ Object.defineProperty(exports, 'DefaultGenerativeUIChatCard', {
3713
+ enumerable: true,
3714
+ get: function () {
3715
+ return DefaultGenerativeUIChatCard;
3716
+ }
3717
+ });
3718
+ Object.defineProperty(exports, 'ExpressionError', {
3719
+ enumerable: true,
3720
+ get: function () {
3721
+ return ExpressionError;
3722
+ }
3723
+ });
3724
+ Object.defineProperty(exports, 'GenerativeUIChatSlotContext', {
3725
+ enumerable: true,
3726
+ get: function () {
3727
+ return GenerativeUIChatSlotContext;
3728
+ }
3729
+ });
3730
+ Object.defineProperty(exports, 'GenerativeUIError', {
3731
+ enumerable: true,
3732
+ get: function () {
3733
+ return GenerativeUIError;
3734
+ }
3735
+ });
3736
+ Object.defineProperty(exports, 'GenerativeUINodeContext', {
3737
+ enumerable: true,
3738
+ get: function () {
3739
+ return GenerativeUINodeContext;
3740
+ }
3741
+ });
3742
+ Object.defineProperty(exports, 'GenerativeUIRuntimeContext', {
3743
+ enumerable: true,
3744
+ get: function () {
3745
+ return GenerativeUIRuntimeContext;
3746
+ }
3747
+ });
3748
+ Object.defineProperty(exports, 'GenerativeUIToolCallRenderer', {
3749
+ enumerable: true,
3750
+ get: function () {
3751
+ return GenerativeUIToolCallRenderer;
3752
+ }
3753
+ });
3754
+ Object.defineProperty(exports, 'MarkdownRendererProvider', {
3755
+ enumerable: true,
3756
+ get: function () {
3757
+ return MarkdownRendererProvider;
3758
+ }
3759
+ });
3760
+ Object.defineProperty(exports, 'MarkdownSurfaces', {
3761
+ enumerable: true,
3762
+ get: function () {
3763
+ return MarkdownSurfaces;
3764
+ }
3765
+ });
3766
+ Object.defineProperty(exports, 'ProviderMarkdown', {
3767
+ enumerable: true,
3768
+ get: function () {
3769
+ return ProviderMarkdown;
3770
+ }
3771
+ });
3772
+ Object.defineProperty(exports, 'StreamingMarkdownDefaultRenderer', {
3773
+ enumerable: true,
3774
+ get: function () {
3775
+ return StreamingMarkdownDefaultRenderer;
3776
+ }
3777
+ });
3778
+ Object.defineProperty(exports, 'SurfaceView', {
3779
+ enumerable: true,
3780
+ get: function () {
3781
+ return SurfaceView;
3782
+ }
3783
+ });
3784
+ Object.defineProperty(exports, '__toESM', {
3785
+ enumerable: true,
3786
+ get: function () {
3787
+ return __toESM;
3788
+ }
3789
+ });
3790
+ Object.defineProperty(exports, 'catalogIdsOf', {
3791
+ enumerable: true,
3792
+ get: function () {
3793
+ return catalogIdsOf;
3794
+ }
3795
+ });
3796
+ Object.defineProperty(exports, 'componentCatalogIds', {
3797
+ enumerable: true,
3798
+ get: function () {
3799
+ return componentCatalogIds;
3800
+ }
3801
+ });
3802
+ Object.defineProperty(exports, 'containsDynamicValue', {
3803
+ enumerable: true,
3804
+ get: function () {
3805
+ return containsDynamicValue;
3806
+ }
3807
+ });
3808
+ Object.defineProperty(exports, 'controlAria', {
3809
+ enumerable: true,
3810
+ get: function () {
3811
+ return controlAria;
3812
+ }
3813
+ });
3814
+ Object.defineProperty(exports, 'createGenerativeUI', {
3815
+ enumerable: true,
3816
+ get: function () {
3817
+ return createGenerativeUI;
3818
+ }
3819
+ });
3820
+ Object.defineProperty(exports, 'createGenerativeUIActivityRenderer', {
3821
+ enumerable: true,
3822
+ get: function () {
3823
+ return createGenerativeUIActivityRenderer;
3824
+ }
3825
+ });
3826
+ Object.defineProperty(exports, 'createGenerativeUIFunctionCallActivityRenderer', {
3827
+ enumerable: true,
3828
+ get: function () {
3829
+ return createGenerativeUIFunctionCallActivityRenderer;
3830
+ }
3831
+ });
3832
+ Object.defineProperty(exports, 'defineToolCallRenderer', {
3833
+ enumerable: true,
3834
+ get: function () {
3835
+ return defineToolCallRenderer;
3836
+ }
3837
+ });
3838
+ Object.defineProperty(exports, 'formatIssues', {
3839
+ enumerable: true,
3840
+ get: function () {
3841
+ return formatIssues;
3842
+ }
3843
+ });
3844
+ Object.defineProperty(exports, 'getMarkdownSurfaceSource', {
3845
+ enumerable: true,
3846
+ get: function () {
3847
+ return getMarkdownSurfaceSource;
3848
+ }
3849
+ });
3850
+ Object.defineProperty(exports, 'isAsyncIssue', {
3851
+ enumerable: true,
3852
+ get: function () {
3853
+ return isAsyncIssue;
3854
+ }
3855
+ });
3856
+ Object.defineProperty(exports, 'isReactComponentType', {
3857
+ enumerable: true,
3858
+ get: function () {
3859
+ return isReactComponentType;
3860
+ }
3861
+ });
3862
+ Object.defineProperty(exports, 'isRecord', {
3863
+ enumerable: true,
3864
+ get: function () {
3865
+ return isRecord;
3866
+ }
3867
+ });
3868
+ Object.defineProperty(exports, 'issueKey', {
3869
+ enumerable: true,
3870
+ get: function () {
3871
+ return issueKey;
3872
+ }
3873
+ });
3874
+ Object.defineProperty(exports, 'namedRole', {
3875
+ enumerable: true,
3876
+ get: function () {
3877
+ return namedRole;
3878
+ }
3879
+ });
3880
+ Object.defineProperty(exports, 'renderSlot', {
3881
+ enumerable: true,
3882
+ get: function () {
3883
+ return renderSlot;
3884
+ }
3885
+ });
3886
+ Object.defineProperty(exports, 'toJsonSchema', {
3887
+ enumerable: true,
3888
+ get: function () {
3889
+ return toJsonSchema;
3890
+ }
3891
+ });
3892
+ Object.defineProperty(exports, 'useCopilotChatConfiguration', {
3893
+ enumerable: true,
3894
+ get: function () {
3895
+ return useCopilotChatConfiguration;
3896
+ }
3897
+ });
3898
+ Object.defineProperty(exports, 'useGenerativeUIAccessibility', {
3899
+ enumerable: true,
3900
+ get: function () {
3901
+ return useGenerativeUIAccessibility;
3902
+ }
3903
+ });
3904
+ Object.defineProperty(exports, 'useGenerativeUIFunction', {
3905
+ enumerable: true,
3906
+ get: function () {
3907
+ return useGenerativeUIFunction;
3908
+ }
3909
+ });
3910
+ Object.defineProperty(exports, 'useGenerativeUIRuntime', {
3911
+ enumerable: true,
3912
+ get: function () {
3913
+ return useGenerativeUIRuntime;
3914
+ }
3915
+ });
3916
+ Object.defineProperty(exports, 'useGenerativeUIState', {
3917
+ enumerable: true,
3918
+ get: function () {
3919
+ return useGenerativeUIState;
3920
+ }
3921
+ });
3922
+ Object.defineProperty(exports, 'useManagerVersion', {
3923
+ enumerable: true,
3924
+ get: function () {
3925
+ return useManagerVersion;
3926
+ }
3927
+ });
3928
+ Object.defineProperty(exports, 'useMarkdownRenderer', {
3929
+ enumerable: true,
3930
+ get: function () {
3931
+ return useMarkdownRenderer;
3932
+ }
3933
+ });
3934
+ Object.defineProperty(exports, 'useRequiredGenerativeUIRuntime', {
3935
+ enumerable: true,
3936
+ get: function () {
3937
+ return useRequiredGenerativeUIRuntime;
3938
+ }
3939
+ });
3940
+ Object.defineProperty(exports, 'useShallowStableRef', {
3941
+ enumerable: true,
3942
+ get: function () {
3943
+ return useShallowStableRef;
3944
+ }
3945
+ });
3946
+ Object.defineProperty(exports, 'validateSchemaSync', {
3947
+ enumerable: true,
3948
+ get: function () {
3949
+ return validateSchemaSync;
3950
+ }
3951
+ });
3952
+ Object.defineProperty(exports, 'withoutRejectedNulls', {
3953
+ enumerable: true,
3954
+ get: function () {
3955
+ return withoutRejectedNulls;
3956
+ }
3957
+ });
3958
+ Object.defineProperty(exports, 'wrapperAria', {
3959
+ enumerable: true,
3960
+ get: function () {
3961
+ return wrapperAria;
3962
+ }
3963
+ });
3964
+ //# sourceMappingURL=MarkdownSurfaces-C2XZISKn.cjs.map