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