@copilotkit/shared 2.0.0-next.1 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (592) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +93 -12
  3. package/dist/_virtual/_rolldown/runtime.cjs +29 -0
  4. package/dist/a2ui-envelope.cjs +154 -0
  5. package/dist/a2ui-envelope.cjs.map +1 -0
  6. package/dist/a2ui-envelope.d.cts +101 -0
  7. package/dist/a2ui-envelope.d.cts.map +1 -0
  8. package/dist/a2ui-envelope.d.mts +101 -0
  9. package/dist/a2ui-envelope.d.mts.map +1 -0
  10. package/dist/a2ui-envelope.mjs +151 -0
  11. package/dist/a2ui-envelope.mjs.map +1 -0
  12. package/dist/a2ui-prompts.cjs +259 -0
  13. package/dist/a2ui-prompts.cjs.map +1 -0
  14. package/dist/a2ui-prompts.d.cts +79 -0
  15. package/dist/a2ui-prompts.d.cts.map +1 -0
  16. package/dist/a2ui-prompts.d.mts +79 -0
  17. package/dist/a2ui-prompts.d.mts.map +1 -0
  18. package/dist/a2ui-prompts.mjs +251 -0
  19. package/dist/a2ui-prompts.mjs.map +1 -0
  20. package/dist/attachments/content.cjs +17 -0
  21. package/dist/attachments/content.cjs.map +1 -0
  22. package/dist/attachments/content.d.cts +9 -0
  23. package/dist/attachments/content.d.cts.map +1 -0
  24. package/dist/attachments/content.d.mts +9 -0
  25. package/dist/attachments/content.d.mts.map +1 -0
  26. package/dist/attachments/content.mjs +16 -0
  27. package/dist/attachments/content.mjs.map +1 -0
  28. package/dist/attachments/types.d.cts +64 -0
  29. package/dist/attachments/types.d.cts.map +1 -0
  30. package/dist/attachments/types.d.mts +64 -0
  31. package/dist/attachments/types.d.mts.map +1 -0
  32. package/dist/attachments/utils.cjs +137 -0
  33. package/dist/attachments/utils.cjs.map +1 -0
  34. package/dist/attachments/utils.d.cts +44 -0
  35. package/dist/attachments/utils.d.cts.map +1 -0
  36. package/dist/attachments/utils.d.mts +44 -0
  37. package/dist/attachments/utils.d.mts.map +1 -0
  38. package/dist/attachments/utils.mjs +129 -0
  39. package/dist/attachments/utils.mjs.map +1 -0
  40. package/dist/constants/index.cjs +25 -0
  41. package/dist/constants/index.cjs.map +1 -0
  42. package/dist/constants/index.d.cts +17 -0
  43. package/dist/constants/index.d.cts.map +1 -0
  44. package/dist/constants/index.d.mts +17 -0
  45. package/dist/constants/index.d.mts.map +1 -0
  46. package/dist/constants/index.mjs +17 -12
  47. package/dist/constants/index.mjs.map +1 -1
  48. package/dist/debug-event-envelope.d.cts +13 -0
  49. package/dist/debug-event-envelope.d.cts.map +1 -0
  50. package/dist/debug-event-envelope.d.mts +13 -0
  51. package/dist/debug-event-envelope.d.mts.map +1 -0
  52. package/dist/debug.cjs +38 -0
  53. package/dist/debug.cjs.map +1 -0
  54. package/dist/debug.d.cts +29 -0
  55. package/dist/debug.d.cts.map +1 -0
  56. package/dist/debug.d.mts +29 -0
  57. package/dist/debug.d.mts.map +1 -0
  58. package/dist/debug.mjs +37 -0
  59. package/dist/debug.mjs.map +1 -0
  60. package/dist/event-transforms/index.cjs +15 -0
  61. package/dist/event-transforms/index.d.cts +4 -0
  62. package/dist/event-transforms/index.d.mts +4 -0
  63. package/dist/event-transforms/index.mjs +5 -0
  64. package/dist/event-transforms/open-generative-ui-middleware.cjs +286 -0
  65. package/dist/event-transforms/open-generative-ui-middleware.cjs.map +1 -0
  66. package/dist/event-transforms/open-generative-ui-middleware.d.cts +60 -0
  67. package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +1 -0
  68. package/dist/event-transforms/open-generative-ui-middleware.d.mts +60 -0
  69. package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +1 -0
  70. package/dist/event-transforms/open-generative-ui-middleware.mjs +283 -0
  71. package/dist/event-transforms/open-generative-ui-middleware.mjs.map +1 -0
  72. package/dist/event-transforms/recorded-events.cjs +59 -0
  73. package/dist/event-transforms/recorded-events.cjs.map +1 -0
  74. package/dist/event-transforms/recorded-events.d.cts +23 -0
  75. package/dist/event-transforms/recorded-events.d.cts.map +1 -0
  76. package/dist/event-transforms/recorded-events.d.mts +23 -0
  77. package/dist/event-transforms/recorded-events.d.mts.map +1 -0
  78. package/dist/event-transforms/recorded-events.mjs +58 -0
  79. package/dist/event-transforms/recorded-events.mjs.map +1 -0
  80. package/dist/finalize-events.cjs +186 -0
  81. package/dist/finalize-events.cjs.map +1 -0
  82. package/dist/finalize-events.d.cts +40 -0
  83. package/dist/finalize-events.d.cts.map +1 -0
  84. package/dist/finalize-events.d.mts +40 -0
  85. package/dist/finalize-events.d.mts.map +1 -0
  86. package/dist/finalize-events.mjs +184 -0
  87. package/dist/finalize-events.mjs.map +1 -0
  88. package/dist/generative-ui/basic-functions.cjs +177 -0
  89. package/dist/generative-ui/basic-functions.cjs.map +1 -0
  90. package/dist/generative-ui/basic-functions.d.cts +108 -0
  91. package/dist/generative-ui/basic-functions.d.cts.map +1 -0
  92. package/dist/generative-ui/basic-functions.d.mts +108 -0
  93. package/dist/generative-ui/basic-functions.d.mts.map +1 -0
  94. package/dist/generative-ui/basic-functions.mjs +167 -0
  95. package/dist/generative-ui/basic-functions.mjs.map +1 -0
  96. package/dist/generative-ui/child-refs.cjs +161 -0
  97. package/dist/generative-ui/child-refs.cjs.map +1 -0
  98. package/dist/generative-ui/child-refs.d.cts +68 -0
  99. package/dist/generative-ui/child-refs.d.cts.map +1 -0
  100. package/dist/generative-ui/child-refs.d.mts +68 -0
  101. package/dist/generative-ui/child-refs.d.mts.map +1 -0
  102. package/dist/generative-ui/child-refs.mjs +152 -0
  103. package/dist/generative-ui/child-refs.mjs.map +1 -0
  104. package/dist/generative-ui/is-record.cjs +10 -0
  105. package/dist/generative-ui/is-record.cjs.map +1 -0
  106. package/dist/generative-ui/is-record.mjs +9 -0
  107. package/dist/generative-ui/is-record.mjs.map +1 -0
  108. package/dist/generative-ui/prompt.cjs +91 -0
  109. package/dist/generative-ui/prompt.cjs.map +1 -0
  110. package/dist/generative-ui/prompt.d.cts +13 -0
  111. package/dist/generative-ui/prompt.d.cts.map +1 -0
  112. package/dist/generative-ui/prompt.d.mts +13 -0
  113. package/dist/generative-ui/prompt.d.mts.map +1 -0
  114. package/dist/generative-ui/prompt.mjs +90 -0
  115. package/dist/generative-ui/prompt.mjs.map +1 -0
  116. package/dist/generative-ui/render-ui-args.cjs +160 -0
  117. package/dist/generative-ui/render-ui-args.cjs.map +1 -0
  118. package/dist/generative-ui/render-ui-args.d.cts +40 -0
  119. package/dist/generative-ui/render-ui-args.d.cts.map +1 -0
  120. package/dist/generative-ui/render-ui-args.d.mts +40 -0
  121. package/dist/generative-ui/render-ui-args.d.mts.map +1 -0
  122. package/dist/generative-ui/render-ui-args.mjs +159 -0
  123. package/dist/generative-ui/render-ui-args.mjs.map +1 -0
  124. package/dist/generative-ui/types.cjs +101 -0
  125. package/dist/generative-ui/types.cjs.map +1 -0
  126. package/dist/generative-ui/types.d.cts +270 -0
  127. package/dist/generative-ui/types.d.cts.map +1 -0
  128. package/dist/generative-ui/types.d.mts +270 -0
  129. package/dist/generative-ui/types.d.mts.map +1 -0
  130. package/dist/generative-ui/types.mjs +86 -0
  131. package/dist/generative-ui/types.mjs.map +1 -0
  132. package/dist/generative-ui/validate-operation.cjs +405 -0
  133. package/dist/generative-ui/validate-operation.cjs.map +1 -0
  134. package/dist/generative-ui/validate-operation.d.cts +86 -0
  135. package/dist/generative-ui/validate-operation.d.cts.map +1 -0
  136. package/dist/generative-ui/validate-operation.d.mts +86 -0
  137. package/dist/generative-ui/validate-operation.d.mts.map +1 -0
  138. package/dist/generative-ui/validate-operation.mjs +399 -0
  139. package/dist/generative-ui/validate-operation.mjs.map +1 -0
  140. package/dist/index.cjs +233 -0
  141. package/dist/index.cjs.map +1 -0
  142. package/dist/index.d.cts +80 -0
  143. package/dist/index.d.cts.map +1 -0
  144. package/dist/index.d.mts +80 -0
  145. package/dist/index.d.mts.map +1 -0
  146. package/dist/index.mjs +78 -123
  147. package/dist/index.mjs.map +1 -1
  148. package/dist/index.umd.js +3979 -0
  149. package/dist/index.umd.js.map +1 -0
  150. package/dist/intelligence-routing-fields.cjs +35 -0
  151. package/dist/intelligence-routing-fields.cjs.map +1 -0
  152. package/dist/intelligence-routing-fields.d.cts +18 -0
  153. package/dist/intelligence-routing-fields.d.cts.map +1 -0
  154. package/dist/intelligence-routing-fields.d.mts +18 -0
  155. package/dist/intelligence-routing-fields.d.mts.map +1 -0
  156. package/dist/intelligence-routing-fields.mjs +34 -0
  157. package/dist/intelligence-routing-fields.mjs.map +1 -0
  158. package/dist/logger.cjs +7 -0
  159. package/dist/logger.cjs.map +1 -0
  160. package/dist/logger.d.cts +5 -0
  161. package/dist/logger.d.cts.map +1 -0
  162. package/dist/logger.d.mts +5 -0
  163. package/dist/logger.d.mts.map +1 -0
  164. package/dist/logger.mjs +6 -0
  165. package/dist/logger.mjs.map +1 -0
  166. package/dist/open-generative-ui-prompts.cjs +8 -0
  167. package/dist/open-generative-ui-prompts.cjs.map +1 -0
  168. package/dist/open-generative-ui-prompts.d.cts +6 -0
  169. package/dist/open-generative-ui-prompts.d.cts.map +1 -0
  170. package/dist/open-generative-ui-prompts.d.mts +6 -0
  171. package/dist/open-generative-ui-prompts.d.mts.map +1 -0
  172. package/dist/open-generative-ui-prompts.mjs +7 -0
  173. package/dist/open-generative-ui-prompts.mjs.map +1 -0
  174. package/dist/package.cjs +12 -0
  175. package/dist/package.cjs.map +1 -0
  176. package/dist/package.mjs +6 -0
  177. package/dist/package.mjs.map +1 -0
  178. package/dist/standard-schema.cjs +31 -0
  179. package/dist/standard-schema.cjs.map +1 -0
  180. package/dist/standard-schema.d.cts +33 -0
  181. package/dist/standard-schema.d.cts.map +1 -0
  182. package/dist/standard-schema.d.mts +33 -0
  183. package/dist/standard-schema.d.mts.map +1 -0
  184. package/dist/standard-schema.mjs +30 -0
  185. package/dist/standard-schema.mjs.map +1 -0
  186. package/dist/telemetry/events.d.cts +72 -0
  187. package/dist/telemetry/events.d.cts.map +1 -0
  188. package/dist/telemetry/events.d.mts +72 -0
  189. package/dist/telemetry/events.d.mts.map +1 -0
  190. package/dist/telemetry/index.cjs +18 -0
  191. package/dist/telemetry/index.d.cts +5 -0
  192. package/dist/telemetry/index.d.mts +5 -0
  193. package/dist/telemetry/index.mjs +6 -12
  194. package/dist/telemetry/lambda-client.cjs +91 -0
  195. package/dist/telemetry/lambda-client.cjs.map +1 -0
  196. package/dist/telemetry/lambda-client.d.cts +31 -0
  197. package/dist/telemetry/lambda-client.d.cts.map +1 -0
  198. package/dist/telemetry/lambda-client.d.mts +31 -0
  199. package/dist/telemetry/lambda-client.d.mts.map +1 -0
  200. package/dist/telemetry/lambda-client.mjs +87 -0
  201. package/dist/telemetry/lambda-client.mjs.map +1 -0
  202. package/dist/telemetry/model-host.cjs +104 -0
  203. package/dist/telemetry/model-host.cjs.map +1 -0
  204. package/dist/telemetry/model-host.d.cts +26 -0
  205. package/dist/telemetry/model-host.d.cts.map +1 -0
  206. package/dist/telemetry/model-host.d.mts +26 -0
  207. package/dist/telemetry/model-host.d.mts.map +1 -0
  208. package/dist/telemetry/model-host.mjs +102 -0
  209. package/dist/telemetry/model-host.mjs.map +1 -0
  210. package/dist/telemetry/sampling.cjs +50 -0
  211. package/dist/telemetry/sampling.cjs.map +1 -0
  212. package/dist/telemetry/sampling.d.cts +57 -0
  213. package/dist/telemetry/sampling.d.cts.map +1 -0
  214. package/dist/telemetry/sampling.d.mts +57 -0
  215. package/dist/telemetry/sampling.d.mts.map +1 -0
  216. package/dist/telemetry/sampling.mjs +44 -0
  217. package/dist/telemetry/sampling.mjs.map +1 -0
  218. package/dist/telemetry/telemetry-client.cjs +165 -0
  219. package/dist/telemetry/telemetry-client.cjs.map +1 -0
  220. package/dist/telemetry/telemetry-client.d.cts +87 -0
  221. package/dist/telemetry/telemetry-client.d.cts.map +1 -0
  222. package/dist/telemetry/telemetry-client.d.mts +87 -0
  223. package/dist/telemetry/telemetry-client.d.mts.map +1 -0
  224. package/dist/telemetry/telemetry-client.mjs +162 -9
  225. package/dist/telemetry/telemetry-client.mjs.map +1 -1
  226. package/dist/telemetry/telemetry-disabled.cjs +20 -0
  227. package/dist/telemetry/telemetry-disabled.cjs.map +1 -0
  228. package/dist/telemetry/telemetry-disabled.d.cts +16 -0
  229. package/dist/telemetry/telemetry-disabled.d.cts.map +1 -0
  230. package/dist/telemetry/telemetry-disabled.d.mts +16 -0
  231. package/dist/telemetry/telemetry-disabled.d.mts.map +1 -0
  232. package/dist/telemetry/telemetry-disabled.mjs +19 -0
  233. package/dist/telemetry/telemetry-disabled.mjs.map +1 -0
  234. package/dist/telemetry/utils.cjs +14 -0
  235. package/dist/telemetry/utils.cjs.map +1 -0
  236. package/dist/telemetry/utils.mjs +12 -8
  237. package/dist/telemetry/utils.mjs.map +1 -1
  238. package/dist/transcription-errors.cjs +84 -0
  239. package/dist/transcription-errors.cjs.map +1 -0
  240. package/dist/transcription-errors.d.cts +52 -0
  241. package/dist/transcription-errors.d.cts.map +1 -0
  242. package/dist/transcription-errors.d.mts +52 -0
  243. package/dist/transcription-errors.d.mts.map +1 -0
  244. package/dist/transcription-errors.mjs +82 -0
  245. package/dist/transcription-errors.mjs.map +1 -0
  246. package/dist/types/{action.d.ts → action.d.cts} +32 -32
  247. package/dist/types/action.d.cts.map +1 -0
  248. package/dist/types/action.d.mts +59 -0
  249. package/dist/types/action.d.mts.map +1 -0
  250. package/dist/types/copilot-cloud-config.d.cts +15 -0
  251. package/dist/types/copilot-cloud-config.d.cts.map +1 -0
  252. package/dist/types/copilot-cloud-config.d.mts +15 -0
  253. package/dist/types/copilot-cloud-config.d.mts.map +1 -0
  254. package/dist/types/error.d.cts +57 -0
  255. package/dist/types/error.d.cts.map +1 -0
  256. package/dist/types/error.d.mts +57 -0
  257. package/dist/types/error.d.mts.map +1 -0
  258. package/dist/types/message.d.cts +42 -0
  259. package/dist/types/message.d.cts.map +1 -0
  260. package/dist/types/message.d.mts +42 -0
  261. package/dist/types/message.d.mts.map +1 -0
  262. package/dist/types/openai-assistant.d.cts +55 -0
  263. package/dist/types/openai-assistant.d.cts.map +1 -0
  264. package/dist/types/openai-assistant.d.mts +55 -0
  265. package/dist/types/openai-assistant.d.mts.map +1 -0
  266. package/dist/types/utility.d.cts +6 -0
  267. package/dist/types/utility.d.cts.map +1 -0
  268. package/dist/types/utility.d.mts +6 -0
  269. package/dist/types/utility.d.mts.map +1 -0
  270. package/dist/utils/clipboard.cjs +28 -0
  271. package/dist/utils/clipboard.cjs.map +1 -0
  272. package/dist/utils/clipboard.d.cts +14 -0
  273. package/dist/utils/clipboard.d.cts.map +1 -0
  274. package/dist/utils/clipboard.d.mts +14 -0
  275. package/dist/utils/clipboard.d.mts.map +1 -0
  276. package/dist/utils/clipboard.mjs +27 -0
  277. package/dist/utils/clipboard.mjs.map +1 -0
  278. package/dist/utils/conditions.cjs +32 -0
  279. package/dist/utils/conditions.cjs.map +1 -0
  280. package/dist/utils/{conditions.d.ts → conditions.d.cts} +16 -11
  281. package/dist/utils/conditions.d.cts.map +1 -0
  282. package/dist/utils/conditions.d.mts +31 -0
  283. package/dist/utils/conditions.d.mts.map +1 -0
  284. package/dist/utils/conditions.mjs +30 -6
  285. package/dist/utils/conditions.mjs.map +1 -1
  286. package/dist/utils/console-styling.cjs +91 -0
  287. package/dist/utils/console-styling.cjs.map +1 -0
  288. package/dist/utils/console-styling.d.cts +65 -0
  289. package/dist/utils/console-styling.d.cts.map +1 -0
  290. package/dist/utils/console-styling.d.mts +65 -0
  291. package/dist/utils/console-styling.d.mts.map +1 -0
  292. package/dist/utils/console-styling.mjs +83 -15
  293. package/dist/utils/console-styling.mjs.map +1 -1
  294. package/dist/utils/dashboard-url.cjs +19 -0
  295. package/dist/utils/dashboard-url.cjs.map +1 -0
  296. package/dist/utils/dashboard-url.mjs +18 -0
  297. package/dist/utils/dashboard-url.mjs.map +1 -0
  298. package/dist/utils/errors.cjs +439 -0
  299. package/dist/utils/errors.cjs.map +1 -0
  300. package/dist/utils/{errors.d.ts → errors.d.cts} +188 -156
  301. package/dist/utils/errors.d.cts.map +1 -0
  302. package/dist/utils/errors.d.mts +312 -0
  303. package/dist/utils/errors.d.mts.map +1 -0
  304. package/dist/utils/errors.mjs +416 -63
  305. package/dist/utils/errors.mjs.map +1 -1
  306. package/dist/utils/index.cjs +105 -0
  307. package/dist/utils/index.cjs.map +1 -0
  308. package/dist/utils/index.d.cts +58 -0
  309. package/dist/utils/index.d.cts.map +1 -0
  310. package/dist/utils/index.d.mts +58 -0
  311. package/dist/utils/index.d.mts.map +1 -0
  312. package/dist/utils/index.mjs +97 -107
  313. package/dist/utils/index.mjs.map +1 -1
  314. package/dist/utils/inspector-learning.cjs +217 -0
  315. package/dist/utils/inspector-learning.cjs.map +1 -0
  316. package/dist/utils/inspector-learning.d.cts +104 -0
  317. package/dist/utils/inspector-learning.d.cts.map +1 -0
  318. package/dist/utils/inspector-learning.d.mts +104 -0
  319. package/dist/utils/inspector-learning.d.mts.map +1 -0
  320. package/dist/utils/inspector-learning.mjs +215 -0
  321. package/dist/utils/inspector-learning.mjs.map +1 -0
  322. package/dist/utils/inspector-metadata.cjs +146 -0
  323. package/dist/utils/inspector-metadata.cjs.map +1 -0
  324. package/dist/utils/inspector-metadata.d.cts +55 -0
  325. package/dist/utils/inspector-metadata.d.cts.map +1 -0
  326. package/dist/utils/inspector-metadata.d.mts +55 -0
  327. package/dist/utils/inspector-metadata.d.mts.map +1 -0
  328. package/dist/utils/inspector-metadata.mjs +146 -0
  329. package/dist/utils/inspector-metadata.mjs.map +1 -0
  330. package/dist/utils/inspector-visibility.cjs +13 -0
  331. package/dist/utils/inspector-visibility.cjs.map +1 -0
  332. package/dist/utils/inspector-visibility.d.cts +18 -0
  333. package/dist/utils/inspector-visibility.d.cts.map +1 -0
  334. package/dist/utils/inspector-visibility.d.mts +18 -0
  335. package/dist/utils/inspector-visibility.d.mts.map +1 -0
  336. package/dist/utils/inspector-visibility.mjs +12 -0
  337. package/dist/utils/inspector-visibility.mjs.map +1 -0
  338. package/dist/utils/json-schema.cjs +215 -0
  339. package/dist/utils/json-schema.cjs.map +1 -0
  340. package/dist/utils/{json-schema.d.ts → json-schema.d.cts} +20 -18
  341. package/dist/utils/json-schema.d.cts.map +1 -0
  342. package/dist/utils/json-schema.d.mts +36 -0
  343. package/dist/utils/json-schema.d.mts.map +1 -0
  344. package/dist/utils/json-schema.mjs +210 -12
  345. package/dist/utils/json-schema.mjs.map +1 -1
  346. package/dist/utils/random-id.cjs +38 -0
  347. package/dist/utils/random-id.cjs.map +1 -0
  348. package/dist/utils/{random-id.d.ts → random-id.d.cts} +3 -1
  349. package/dist/utils/random-id.d.cts.map +1 -0
  350. package/dist/utils/random-id.d.mts +8 -0
  351. package/dist/utils/random-id.d.mts.map +1 -0
  352. package/dist/utils/random-id.mjs +33 -12
  353. package/dist/utils/random-id.mjs.map +1 -1
  354. package/dist/utils/requests.cjs +58 -0
  355. package/dist/utils/requests.cjs.map +1 -0
  356. package/dist/utils/{requests.d.ts → requests.d.cts} +3 -1
  357. package/dist/utils/requests.d.cts.map +1 -0
  358. package/dist/utils/requests.d.mts +12 -0
  359. package/dist/utils/requests.d.mts.map +1 -0
  360. package/dist/utils/requests.mjs +56 -6
  361. package/dist/utils/requests.mjs.map +1 -1
  362. package/dist/utils/row-render-keys.cjs +206 -0
  363. package/dist/utils/row-render-keys.cjs.map +1 -0
  364. package/dist/utils/row-render-keys.d.cts +65 -0
  365. package/dist/utils/row-render-keys.d.cts.map +1 -0
  366. package/dist/utils/row-render-keys.d.mts +65 -0
  367. package/dist/utils/row-render-keys.d.mts.map +1 -0
  368. package/dist/utils/row-render-keys.mjs +201 -0
  369. package/dist/utils/row-render-keys.mjs.map +1 -0
  370. package/dist/utils/types.cjs +9 -0
  371. package/dist/utils/types.cjs.map +1 -0
  372. package/dist/utils/types.d.cts +122 -0
  373. package/dist/utils/types.d.cts.map +1 -0
  374. package/dist/utils/types.d.mts +122 -0
  375. package/dist/utils/types.d.mts.map +1 -0
  376. package/dist/utils/types.mjs +6 -1
  377. package/dist/utils/types.mjs.map +1 -1
  378. package/package.json +74 -40
  379. package/scripts/verify-cjs-exports.cjs +16 -0
  380. package/src/__tests__/a2ui-envelope.test.ts +434 -0
  381. package/src/__tests__/a2ui-prompts.test.ts +362 -0
  382. package/src/__tests__/debug.test.ts +116 -0
  383. package/src/__tests__/license-context.test.ts +253 -0
  384. package/src/__tests__/root-entry-browser-safety.test.ts +91 -0
  385. package/src/__tests__/standard-schema-types.test.ts +144 -0
  386. package/src/__tests__/standard-schema.test.ts +359 -0
  387. package/src/__tests__/zod-regression.test.ts +319 -0
  388. package/src/a2ui-envelope.ts +309 -0
  389. package/src/a2ui-prompts.ts +322 -0
  390. package/src/attachments/__tests__/utils.test.ts +214 -0
  391. package/src/attachments/content.test.ts +48 -0
  392. package/src/attachments/content.ts +16 -0
  393. package/src/attachments/index.ts +21 -0
  394. package/src/attachments/types.ts +77 -0
  395. package/src/attachments/utils.ts +169 -0
  396. package/src/constants/index.ts +14 -1
  397. package/src/debug-event-envelope.ts +9 -0
  398. package/src/debug.ts +55 -0
  399. package/src/event-transforms/index.ts +5 -0
  400. package/src/event-transforms/open-generative-ui-middleware.ts +392 -0
  401. package/src/event-transforms/recorded-events.test.ts +166 -0
  402. package/src/event-transforms/recorded-events.ts +74 -0
  403. package/src/finalize-events.test.ts +284 -0
  404. package/src/finalize-events.ts +260 -0
  405. package/src/generative-ui/__tests__/render-ui-args.test.ts +175 -0
  406. package/src/generative-ui/__tests__/validate-operation.test.ts +977 -0
  407. package/src/generative-ui/basic-functions.ts +282 -0
  408. package/src/generative-ui/child-refs.ts +210 -0
  409. package/src/generative-ui/index.ts +6 -0
  410. package/src/generative-ui/is-record.ts +4 -0
  411. package/src/generative-ui/prompt.ts +174 -0
  412. package/src/generative-ui/render-ui-args.ts +199 -0
  413. package/src/generative-ui/types.ts +314 -0
  414. package/src/generative-ui/validate-operation.ts +723 -0
  415. package/src/index.ts +190 -1
  416. package/src/intelligence-routing-fields.test.ts +51 -0
  417. package/src/intelligence-routing-fields.ts +40 -0
  418. package/src/logger.ts +1 -0
  419. package/src/open-generative-ui-prompts.ts +20 -0
  420. package/src/standard-schema.ts +82 -0
  421. package/src/telemetry/events.ts +37 -10
  422. package/src/telemetry/index.ts +8 -0
  423. package/src/telemetry/lambda-client.test.ts +446 -0
  424. package/src/telemetry/lambda-client.ts +194 -0
  425. package/src/telemetry/model-host.test.ts +145 -0
  426. package/src/telemetry/model-host.ts +156 -0
  427. package/src/telemetry/sampling.test.ts +65 -0
  428. package/src/telemetry/sampling.ts +103 -0
  429. package/src/telemetry/telemetry-blank-license-identity.test.ts +128 -0
  430. package/src/telemetry/telemetry-client.test.ts +798 -0
  431. package/src/telemetry/telemetry-client.ts +223 -37
  432. package/src/telemetry/telemetry-disabled.ts +22 -0
  433. package/src/telemetry/utils.ts +0 -24
  434. package/src/transcription-errors.ts +99 -0
  435. package/src/types/__tests__/message.test.ts +62 -0
  436. package/src/types/action.ts +9 -5
  437. package/src/types/error.ts +11 -2
  438. package/src/types/message.ts +33 -5
  439. package/src/types/openai-assistant.ts +6 -2
  440. package/src/utils/__tests__/clipboard.test.ts +87 -0
  441. package/src/utils/__tests__/conditions.test.ts +161 -0
  442. package/src/utils/__tests__/json-schema.test.ts +812 -0
  443. package/src/utils/__tests__/row-render-keys.test.ts +388 -0
  444. package/src/utils/clipboard.ts +23 -0
  445. package/src/utils/conditions.ts +27 -9
  446. package/src/utils/console-styling.ts +10 -8
  447. package/src/utils/dashboard-url.ts +17 -0
  448. package/src/utils/errors.ts +55 -22
  449. package/src/utils/index.ts +70 -1
  450. package/src/utils/inspector-learning.test.ts +423 -0
  451. package/src/utils/inspector-learning.ts +523 -0
  452. package/src/utils/inspector-metadata.test.ts +743 -0
  453. package/src/utils/inspector-metadata.ts +263 -0
  454. package/src/utils/inspector-visibility.test.ts +43 -0
  455. package/src/utils/inspector-visibility.ts +17 -0
  456. package/src/utils/json-schema.ts +156 -12
  457. package/src/utils/random-id.ts +5 -2
  458. package/src/utils/requests.ts +3 -1
  459. package/src/utils/row-render-keys.ts +263 -0
  460. package/src/utils/types.ts +128 -1
  461. package/src/utils.test.ts +137 -0
  462. package/tsconfig.json +10 -2
  463. package/tsdown.config.ts +49 -0
  464. package/vitest.config.mjs +11 -0
  465. package/CHANGELOG.md +0 -1817
  466. package/dist/chunk-2OJ5OJ2D.mjs +0 -1
  467. package/dist/chunk-2OJ5OJ2D.mjs.map +0 -1
  468. package/dist/chunk-64DYJ27R.mjs +0 -201
  469. package/dist/chunk-64DYJ27R.mjs.map +0 -1
  470. package/dist/chunk-6QGXWNS5.mjs +0 -34
  471. package/dist/chunk-6QGXWNS5.mjs.map +0 -1
  472. package/dist/chunk-6W2UEO2M.mjs +0 -94
  473. package/dist/chunk-6W2UEO2M.mjs.map +0 -1
  474. package/dist/chunk-7DJDTRNX.mjs +0 -426
  475. package/dist/chunk-7DJDTRNX.mjs.map +0 -1
  476. package/dist/chunk-A66772CV.mjs +0 -107
  477. package/dist/chunk-A66772CV.mjs.map +0 -1
  478. package/dist/chunk-BOKE4OKY.mjs +0 -41
  479. package/dist/chunk-BOKE4OKY.mjs.map +0 -1
  480. package/dist/chunk-FCCOSO5L.mjs +0 -1
  481. package/dist/chunk-FCCOSO5L.mjs.map +0 -1
  482. package/dist/chunk-GYZIHHE6.mjs +0 -13
  483. package/dist/chunk-GYZIHHE6.mjs.map +0 -1
  484. package/dist/chunk-IAFBVORQ.mjs +0 -1
  485. package/dist/chunk-IAFBVORQ.mjs.map +0 -1
  486. package/dist/chunk-JAAUCDUR.mjs +0 -38
  487. package/dist/chunk-JAAUCDUR.mjs.map +0 -1
  488. package/dist/chunk-MSUB6DGR.mjs +0 -1
  489. package/dist/chunk-MSUB6DGR.mjs.map +0 -1
  490. package/dist/chunk-N5EP5OD5.mjs +0 -1
  491. package/dist/chunk-N5EP5OD5.mjs.map +0 -1
  492. package/dist/chunk-NAFEBKSO.mjs +0 -1
  493. package/dist/chunk-NAFEBKSO.mjs.map +0 -1
  494. package/dist/chunk-P7STFMPO.mjs +0 -1
  495. package/dist/chunk-P7STFMPO.mjs.map +0 -1
  496. package/dist/chunk-PL5WNHFZ.mjs +0 -50
  497. package/dist/chunk-PL5WNHFZ.mjs.map +0 -1
  498. package/dist/chunk-UYARLQNA.mjs +0 -1
  499. package/dist/chunk-UYARLQNA.mjs.map +0 -1
  500. package/dist/chunk-XEMZTHQZ.mjs +0 -67
  501. package/dist/chunk-XEMZTHQZ.mjs.map +0 -1
  502. package/dist/chunk-XTHC46M2.mjs +0 -1
  503. package/dist/chunk-XTHC46M2.mjs.map +0 -1
  504. package/dist/constants/index.d.ts +0 -6
  505. package/dist/constants/index.js +0 -40
  506. package/dist/constants/index.js.map +0 -1
  507. package/dist/index.d.ts +0 -25
  508. package/dist/index.js +0 -1098
  509. package/dist/index.js.map +0 -1
  510. package/dist/telemetry/events.d.ts +0 -45
  511. package/dist/telemetry/events.js +0 -19
  512. package/dist/telemetry/events.js.map +0 -1
  513. package/dist/telemetry/events.mjs +0 -1
  514. package/dist/telemetry/events.mjs.map +0 -1
  515. package/dist/telemetry/index.d.ts +0 -3
  516. package/dist/telemetry/index.js +0 -188
  517. package/dist/telemetry/index.js.map +0 -1
  518. package/dist/telemetry/index.mjs.map +0 -1
  519. package/dist/telemetry/scarf-client.d.ts +0 -7
  520. package/dist/telemetry/scarf-client.js +0 -59
  521. package/dist/telemetry/scarf-client.js.map +0 -1
  522. package/dist/telemetry/scarf-client.mjs +0 -7
  523. package/dist/telemetry/scarf-client.mjs.map +0 -1
  524. package/dist/telemetry/security-check.d.ts +0 -2
  525. package/dist/telemetry/security-check.js +0 -2
  526. package/dist/telemetry/security-check.js.map +0 -1
  527. package/dist/telemetry/security-check.mjs +0 -1
  528. package/dist/telemetry/security-check.mjs.map +0 -1
  529. package/dist/telemetry/telemetry-client.d.ts +0 -40
  530. package/dist/telemetry/telemetry-client.js +0 -186
  531. package/dist/telemetry/telemetry-client.js.map +0 -1
  532. package/dist/telemetry/utils.d.ts +0 -8
  533. package/dist/telemetry/utils.js +0 -69
  534. package/dist/telemetry/utils.js.map +0 -1
  535. package/dist/types/action.js +0 -19
  536. package/dist/types/action.js.map +0 -1
  537. package/dist/types/action.mjs +0 -2
  538. package/dist/types/action.mjs.map +0 -1
  539. package/dist/types/copilot-cloud-config.d.ts +0 -13
  540. package/dist/types/copilot-cloud-config.js +0 -19
  541. package/dist/types/copilot-cloud-config.js.map +0 -1
  542. package/dist/types/copilot-cloud-config.mjs +0 -2
  543. package/dist/types/copilot-cloud-config.mjs.map +0 -1
  544. package/dist/types/error.d.ts +0 -55
  545. package/dist/types/error.js +0 -19
  546. package/dist/types/error.js.map +0 -1
  547. package/dist/types/error.mjs +0 -2
  548. package/dist/types/error.mjs.map +0 -1
  549. package/dist/types/index.d.ts +0 -7
  550. package/dist/types/index.js +0 -19
  551. package/dist/types/index.js.map +0 -1
  552. package/dist/types/index.mjs +0 -8
  553. package/dist/types/index.mjs.map +0 -1
  554. package/dist/types/message.d.ts +0 -26
  555. package/dist/types/message.js +0 -19
  556. package/dist/types/message.js.map +0 -1
  557. package/dist/types/message.mjs +0 -2
  558. package/dist/types/message.mjs.map +0 -1
  559. package/dist/types/openai-assistant.d.ts +0 -53
  560. package/dist/types/openai-assistant.js +0 -19
  561. package/dist/types/openai-assistant.js.map +0 -1
  562. package/dist/types/openai-assistant.mjs +0 -2
  563. package/dist/types/openai-assistant.mjs.map +0 -1
  564. package/dist/types/utility.d.ts +0 -6
  565. package/dist/types/utility.js +0 -19
  566. package/dist/types/utility.js.map +0 -1
  567. package/dist/types/utility.mjs +0 -2
  568. package/dist/types/utility.mjs.map +0 -1
  569. package/dist/utils/conditions.js +0 -74
  570. package/dist/utils/conditions.js.map +0 -1
  571. package/dist/utils/console-styling.d.ts +0 -84
  572. package/dist/utils/console-styling.js +0 -123
  573. package/dist/utils/console-styling.js.map +0 -1
  574. package/dist/utils/errors.js +0 -443
  575. package/dist/utils/errors.js.map +0 -1
  576. package/dist/utils/index.d.ts +0 -32
  577. package/dist/utils/index.js +0 -927
  578. package/dist/utils/index.js.map +0 -1
  579. package/dist/utils/json-schema.js +0 -228
  580. package/dist/utils/json-schema.js.map +0 -1
  581. package/dist/utils/random-id.js +0 -68
  582. package/dist/utils/random-id.js.map +0 -1
  583. package/dist/utils/requests.js +0 -91
  584. package/dist/utils/requests.js.map +0 -1
  585. package/dist/utils/types.d.ts +0 -20
  586. package/dist/utils/types.js +0 -19
  587. package/dist/utils/types.js.map +0 -1
  588. package/jest.config.js +0 -5
  589. package/src/telemetry/scarf-client.ts +0 -39
  590. package/src/telemetry/security-check.ts +0 -0
  591. package/src/utils/json-schema.test.ts +0 -383
  592. package/tsup.config.ts +0 -11
@@ -0,0 +1,3979 @@
1
+ (function(global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('graphql'), require('zod'), require('uuid'), require('partial-json'), require('@ag-ui/client')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'graphql', 'zod', 'uuid', 'partial-json', '@ag-ui/client'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitShared = {}), global.GraphQL,global.Zod,global.UUID,global.PartialJSON,global.AgUIClient));
5
+ })(this, function(exports, graphql, zod, uuid, partial_json, _ag_ui_client) {
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
+ //#region \0rolldown/runtime.js
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
17
+ key = keys[i];
18
+ if (!__hasOwnProp.call(to, key) && key !== except) {
19
+ __defProp(to, key, {
20
+ get: ((k) => from[k]).bind(null, key),
21
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
22
+ });
23
+ }
24
+ }
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+
33
+ //#endregion
34
+ partial_json = __toESM(partial_json);
35
+
36
+ //#region src/utils/clipboard.ts
37
+ /**
38
+ * Safely copies text to the clipboard.
39
+ *
40
+ * Checks that the Clipboard API is available before attempting the write,
41
+ * and catches any errors (e.g. permission denied, insecure context).
42
+ *
43
+ * @param text - The text to copy to the clipboard.
44
+ * @returns `true` if the text was successfully copied, `false` otherwise.
45
+ */
46
+ async function copyToClipboard(text) {
47
+ var _navigator$clipboard;
48
+ if (!((_navigator$clipboard = navigator.clipboard) === null || _navigator$clipboard === void 0 ? void 0 : _navigator$clipboard.writeText)) {
49
+ console.error("Clipboard API is not available");
50
+ return false;
51
+ }
52
+ try {
53
+ await navigator.clipboard.writeText(text);
54
+ return true;
55
+ } catch (err) {
56
+ console.error("Failed to copy to clipboard:", err);
57
+ return false;
58
+ }
59
+ }
60
+
61
+ //#endregion
62
+ //#region src/utils/conditions.ts
63
+ function executeConditions({ conditions, value }) {
64
+ if (!(conditions === null || conditions === void 0 ? void 0 : conditions.length)) return true;
65
+ return conditions.every((condition) => executeCondition(condition, value));
66
+ }
67
+ function executeCondition(condition, value) {
68
+ const targetValue = condition.path ? getValueFromPath(value, condition.path) : value;
69
+ switch (condition.rule) {
70
+ case "AND": return condition.conditions.every((c) => executeCondition(c, value));
71
+ case "OR": return condition.conditions.some((c) => executeCondition(c, value));
72
+ case "NOT": return !condition.conditions.every((c) => executeCondition(c, value));
73
+ case "EQUALS": return targetValue === condition.value;
74
+ case "NOT_EQUALS": return targetValue !== condition.value;
75
+ case "GREATER_THAN": return targetValue > condition.value;
76
+ case "LESS_THAN": return targetValue < condition.value;
77
+ case "CONTAINS": return Array.isArray(targetValue) && targetValue.includes(condition.value);
78
+ case "NOT_CONTAINS": return Array.isArray(targetValue) && !targetValue.includes(condition.value);
79
+ case "MATCHES": return new RegExp(condition.value).test(String(targetValue));
80
+ case "STARTS_WITH": return String(targetValue).startsWith(condition.value);
81
+ case "ENDS_WITH": return String(targetValue).endsWith(condition.value);
82
+ case "EXISTS": return targetValue !== void 0 && targetValue !== null;
83
+ case "NOT_EXISTS": return targetValue === void 0 || targetValue === null;
84
+ }
85
+ }
86
+ function getValueFromPath(obj, path) {
87
+ return path.split(".").reduce((acc, part) => acc === null || acc === void 0 ? void 0 : acc[part], obj);
88
+ }
89
+
90
+ //#endregion
91
+ //#region src/utils/console-styling.ts
92
+ /**
93
+ * Console styling utilities for CopilotKit branded messages
94
+ * Provides consistent, readable colors across light and dark console themes
95
+ */
96
+ /**
97
+ * Color palette optimized for console readability
98
+ */
99
+ const ConsoleColors = {
100
+ primary: "#007acc",
101
+ success: "#22c55e",
102
+ feature: "#a855f7",
103
+ cta: "#ef4444",
104
+ info: "#06b6d4",
105
+ inherit: "inherit",
106
+ warning: "#f59e0b"
107
+ };
108
+ /**
109
+ * Console style templates for common patterns
110
+ */
111
+ const ConsoleStyles = {
112
+ header: `color: ${ConsoleColors.warning}; font-weight: bold; font-size: 16px;`,
113
+ section: `color: ${ConsoleColors.success}; font-weight: bold;`,
114
+ highlight: `color: ${ConsoleColors.feature}; font-weight: bold;`,
115
+ cta: `color: ${ConsoleColors.success}; font-weight: bold;`,
116
+ info: `color: ${ConsoleColors.info}; font-weight: bold;`,
117
+ link: `color: ${ConsoleColors.primary}; text-decoration: underline;`,
118
+ body: `color: ${ConsoleColors.inherit};`,
119
+ warning: `color: ${ConsoleColors.cta}; font-weight: bold;`
120
+ };
121
+ /**
122
+ * Styled console message for CopilotKit Platform promotion
123
+ * Displays a beautiful, branded advertisement in the console
124
+ */
125
+ function logCopilotKitPlatformMessage() {
126
+ console.log(`%cCopilotKit Warning%c
127
+
128
+ useCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. Headless UI requires a CopilotKit Intelligence license key, available for free at:
129
+
130
+ %chttps://dashboard.operations.copilotkit.ai%c
131
+
132
+ Alternatively, useCopilotChat is available for basic programmatic control, and does not require a license key.
133
+
134
+ To learn more about CopilotKit Intelligence, read the documentation here:
135
+
136
+ %chttps://docs.copilotkit.ai/intelligence/overview%c`, ConsoleStyles.header, ConsoleStyles.body, ConsoleStyles.cta, ConsoleStyles.body, ConsoleStyles.link, ConsoleStyles.body);
137
+ }
138
+ function publicApiKeyRequired(feature) {
139
+ console.log(`
140
+ %cCopilotKit Warning%c \n
141
+ In order to use ${feature}, you need to add your CopilotKit license key, available for free at https://dashboard.operations.copilotkit.ai.
142
+ `.trim(), ConsoleStyles.header, ConsoleStyles.body);
143
+ }
144
+ /**
145
+ * Create a styled console message with custom content
146
+ *
147
+ * @param template - Template string with %c placeholders
148
+ * @param styles - Array of style strings matching the %c placeholders
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * logStyled(
153
+ * '%cCopilotKit%c Welcome to the platform!',
154
+ * [ConsoleStyles.header, ConsoleStyles.body]
155
+ * );
156
+ * ```
157
+ */
158
+ function logStyled(template, styles) {
159
+ console.log(template, ...styles);
160
+ }
161
+ /**
162
+ * Quick styled console methods for common use cases
163
+ */
164
+ const styledConsole = {
165
+ success: (message) => logStyled(`%c✅ ${message}`, [ConsoleStyles.section]),
166
+ info: (message) => logStyled(`%cℹ️ ${message}`, [ConsoleStyles.info]),
167
+ feature: (message) => logStyled(`%c✨ ${message}`, [ConsoleStyles.highlight]),
168
+ cta: (message) => logStyled(`%c🚀 ${message}`, [ConsoleStyles.cta]),
169
+ logCopilotKitPlatformMessage,
170
+ publicApiKeyRequired
171
+ };
172
+
173
+ //#endregion
174
+ //#region src/utils/errors.ts
175
+ let Severity = /* @__PURE__ */ function(Severity) {
176
+ Severity["CRITICAL"] = "critical";
177
+ Severity["WARNING"] = "warning";
178
+ Severity["INFO"] = "info";
179
+ return Severity;
180
+ }({});
181
+ let ErrorVisibility = /* @__PURE__ */ function(ErrorVisibility) {
182
+ ErrorVisibility["BANNER"] = "banner";
183
+ ErrorVisibility["TOAST"] = "toast";
184
+ ErrorVisibility["SILENT"] = "silent";
185
+ ErrorVisibility["DEV_ONLY"] = "dev_only";
186
+ return ErrorVisibility;
187
+ }({});
188
+ const ERROR_NAMES = {
189
+ COPILOT_ERROR: "CopilotError",
190
+ COPILOT_API_DISCOVERY_ERROR: "CopilotApiDiscoveryError",
191
+ COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR: "CopilotKitRemoteEndpointDiscoveryError",
192
+ COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
193
+ COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
194
+ COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
195
+ RESOLVED_COPILOT_KIT_ERROR: "ResolvedCopilotKitError",
196
+ CONFIGURATION_ERROR: "ConfigurationError",
197
+ MISSING_PUBLIC_API_KEY_ERROR: "MissingPublicApiKeyError",
198
+ UPGRADE_REQUIRED_ERROR: "UpgradeRequiredError"
199
+ };
200
+ const BANNER_ERROR_NAMES = [
201
+ ERROR_NAMES.CONFIGURATION_ERROR,
202
+ ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR,
203
+ ERROR_NAMES.UPGRADE_REQUIRED_ERROR,
204
+ ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR,
205
+ ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR,
206
+ ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR
207
+ ];
208
+ const COPILOT_CLOUD_ERROR_NAMES = BANNER_ERROR_NAMES;
209
+ let CopilotKitErrorCode = /* @__PURE__ */ function(CopilotKitErrorCode) {
210
+ CopilotKitErrorCode["NETWORK_ERROR"] = "NETWORK_ERROR";
211
+ CopilotKitErrorCode["NOT_FOUND"] = "NOT_FOUND";
212
+ CopilotKitErrorCode["AGENT_NOT_FOUND"] = "AGENT_NOT_FOUND";
213
+ CopilotKitErrorCode["API_NOT_FOUND"] = "API_NOT_FOUND";
214
+ CopilotKitErrorCode["REMOTE_ENDPOINT_NOT_FOUND"] = "REMOTE_ENDPOINT_NOT_FOUND";
215
+ CopilotKitErrorCode["AUTHENTICATION_ERROR"] = "AUTHENTICATION_ERROR";
216
+ CopilotKitErrorCode["MISUSE"] = "MISUSE";
217
+ CopilotKitErrorCode["UNKNOWN"] = "UNKNOWN";
218
+ CopilotKitErrorCode["VERSION_MISMATCH"] = "VERSION_MISMATCH";
219
+ CopilotKitErrorCode["CONFIGURATION_ERROR"] = "CONFIGURATION_ERROR";
220
+ CopilotKitErrorCode["MISSING_PUBLIC_API_KEY_ERROR"] = "MISSING_PUBLIC_API_KEY_ERROR";
221
+ CopilotKitErrorCode["UPGRADE_REQUIRED_ERROR"] = "UPGRADE_REQUIRED_ERROR";
222
+ return CopilotKitErrorCode;
223
+ }({});
224
+ const BASE_URL = "https://docs.copilotkit.ai";
225
+ const getSeeMoreMarkdown = (link) => `See more: [${link}](${link})`;
226
+ const ERROR_CONFIG = {
227
+ [CopilotKitErrorCode.NETWORK_ERROR]: {
228
+ statusCode: 503,
229
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,
230
+ visibility: ErrorVisibility.BANNER,
231
+ severity: Severity.CRITICAL
232
+ },
233
+ [CopilotKitErrorCode.NOT_FOUND]: {
234
+ statusCode: 404,
235
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,
236
+ visibility: ErrorVisibility.BANNER,
237
+ severity: Severity.CRITICAL
238
+ },
239
+ [CopilotKitErrorCode.AGENT_NOT_FOUND]: {
240
+ statusCode: 500,
241
+ troubleshootingUrl: `${BASE_URL}/langgraph-python/coagent-troubleshooting/common-coagent-issues#i-am-getting-agent-not-found-error`,
242
+ visibility: ErrorVisibility.BANNER,
243
+ severity: Severity.CRITICAL
244
+ },
245
+ [CopilotKitErrorCode.API_NOT_FOUND]: {
246
+ statusCode: 404,
247
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#network-errors-api-not-found`,
248
+ visibility: ErrorVisibility.BANNER,
249
+ severity: Severity.CRITICAL
250
+ },
251
+ [CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND]: {
252
+ statusCode: 404,
253
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues#remote-endpoint-not-found-error`,
254
+ visibility: ErrorVisibility.BANNER,
255
+ severity: Severity.CRITICAL
256
+ },
257
+ [CopilotKitErrorCode.AUTHENTICATION_ERROR]: {
258
+ statusCode: 401,
259
+ troubleshootingUrl: `${BASE_URL}/troubleshooting/common-issues`,
260
+ visibility: ErrorVisibility.BANNER,
261
+ severity: Severity.CRITICAL
262
+ },
263
+ [CopilotKitErrorCode.MISUSE]: {
264
+ statusCode: 400,
265
+ troubleshootingUrl: null,
266
+ visibility: ErrorVisibility.DEV_ONLY,
267
+ severity: Severity.WARNING
268
+ },
269
+ [CopilotKitErrorCode.UNKNOWN]: {
270
+ statusCode: 500,
271
+ visibility: ErrorVisibility.TOAST,
272
+ severity: Severity.CRITICAL
273
+ },
274
+ [CopilotKitErrorCode.CONFIGURATION_ERROR]: {
275
+ statusCode: 400,
276
+ troubleshootingUrl: null,
277
+ severity: Severity.WARNING,
278
+ visibility: ErrorVisibility.BANNER
279
+ },
280
+ [CopilotKitErrorCode.MISSING_PUBLIC_API_KEY_ERROR]: {
281
+ statusCode: 400,
282
+ troubleshootingUrl: null,
283
+ severity: Severity.CRITICAL,
284
+ visibility: ErrorVisibility.BANNER
285
+ },
286
+ [CopilotKitErrorCode.UPGRADE_REQUIRED_ERROR]: {
287
+ statusCode: 402,
288
+ troubleshootingUrl: null,
289
+ severity: Severity.WARNING,
290
+ visibility: ErrorVisibility.BANNER
291
+ },
292
+ [CopilotKitErrorCode.VERSION_MISMATCH]: {
293
+ statusCode: 400,
294
+ troubleshootingUrl: null,
295
+ visibility: ErrorVisibility.DEV_ONLY,
296
+ severity: Severity.INFO
297
+ }
298
+ };
299
+ var CopilotKitError = class extends graphql.GraphQLError {
300
+ constructor({ message = "Unknown error occurred", code, severity, visibility }) {
301
+ var _ref;
302
+ const name = ERROR_NAMES.COPILOT_ERROR;
303
+ const config = ERROR_CONFIG[code];
304
+ const { statusCode } = config;
305
+ const resolvedVisibility = (_ref = visibility !== null && visibility !== void 0 ? visibility : config.visibility) !== null && _ref !== void 0 ? _ref : ErrorVisibility.TOAST;
306
+ const resolvedSeverity = severity !== null && severity !== void 0 ? severity : "severity" in config ? config.severity : void 0;
307
+ super(message, { extensions: {
308
+ name,
309
+ statusCode,
310
+ code,
311
+ visibility: resolvedVisibility,
312
+ severity: resolvedSeverity,
313
+ troubleshootingUrl: "troubleshootingUrl" in config ? config.troubleshootingUrl : null,
314
+ originalError: {
315
+ message,
316
+ stack: (/* @__PURE__ */ new Error()).stack
317
+ }
318
+ } });
319
+ this.code = code;
320
+ this.name = name;
321
+ this.statusCode = statusCode;
322
+ this.severity = resolvedSeverity;
323
+ this.visibility = resolvedVisibility;
324
+ }
325
+ };
326
+ /**
327
+ * Error thrown when we can identify wrong usage of our components.
328
+ * This helps us notify the developer before real errors can happen
329
+ *
330
+ * @extends CopilotKitError
331
+ */
332
+ var CopilotKitMisuseError = class extends CopilotKitError {
333
+ constructor({ message, code = CopilotKitErrorCode.MISUSE }) {
334
+ const docsLink = "troubleshootingUrl" in ERROR_CONFIG[code] && ERROR_CONFIG[code].troubleshootingUrl ? getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl) : null;
335
+ const finalMessage = docsLink ? `${message}.\n\n${docsLink}` : message;
336
+ super({
337
+ message: finalMessage,
338
+ code
339
+ });
340
+ this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
341
+ }
342
+ };
343
+ const getVersionMismatchErrorMessage = ({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) => `Version mismatch detected: @copilotkit/runtime@${runtimeVersion !== null && runtimeVersion !== void 0 ? runtimeVersion : ""} is not compatible with @copilotkit/react-core@${reactCoreVersion} and @copilotkit/runtime-client-gql@${runtimeClientGqlVersion}. Please ensure all installed copilotkit packages are on the same version.`;
344
+ /**
345
+ * Error thrown when CPK versions does not match
346
+ *
347
+ * @extends CopilotKitError
348
+ */
349
+ var CopilotKitVersionMismatchError = class extends CopilotKitError {
350
+ constructor({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) {
351
+ const code = CopilotKitErrorCode.VERSION_MISMATCH;
352
+ super({
353
+ message: getVersionMismatchErrorMessage({
354
+ reactCoreVersion,
355
+ runtimeVersion,
356
+ runtimeClientGqlVersion
357
+ }),
358
+ code
359
+ });
360
+ this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
361
+ }
362
+ };
363
+ /**
364
+ * Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.
365
+ * This typically occurs when:
366
+ * - The API endpoint URL is invalid or misconfigured
367
+ * - The API service is not running at the expected location
368
+ * - There are network/firewall issues preventing access
369
+ *
370
+ * @extends CopilotKitError
371
+ */
372
+ var CopilotKitApiDiscoveryError = class extends CopilotKitError {
373
+ constructor(params = {}) {
374
+ var _params$url, _params$message, _params$code;
375
+ const url = (_params$url = params.url) !== null && _params$url !== void 0 ? _params$url : "";
376
+ let operationSuffix = "";
377
+ if (url === null || url === void 0 ? void 0 : url.includes("/info")) operationSuffix = `when fetching CopilotKit info`;
378
+ else if (url.includes("/actions/execute")) operationSuffix = `when attempting to execute actions.`;
379
+ else if (url.includes("/agents/state")) operationSuffix = `when attempting to get agent state.`;
380
+ else if (url.includes("/agents/execute")) operationSuffix = `when attempting to execute agent(s).`;
381
+ const message = (_params$message = params.message) !== null && _params$message !== void 0 ? _params$message : params.url ? `Failed to find CopilotKit API endpoint at url ${params.url} ${operationSuffix}` : `Failed to find CopilotKit API endpoint.`;
382
+ const code = (_params$code = params.code) !== null && _params$code !== void 0 ? _params$code : CopilotKitErrorCode.API_NOT_FOUND;
383
+ const errorMessage = `${message}.\n\n${getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl)}`;
384
+ super({
385
+ message: errorMessage,
386
+ code
387
+ });
388
+ this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
389
+ }
390
+ };
391
+ /**
392
+ * This error is used for endpoints specified in runtime's remote endpoints. If they cannot be contacted
393
+ * This typically occurs when:
394
+ * - The API endpoint URL is invalid or misconfigured
395
+ * - The API service is not running at the expected location
396
+ *
397
+ * @extends CopilotKitApiDiscoveryError
398
+ */
399
+ var CopilotKitRemoteEndpointDiscoveryError = class extends CopilotKitApiDiscoveryError {
400
+ constructor(params) {
401
+ var _params$message2;
402
+ const message = (_params$message2 = params === null || params === void 0 ? void 0 : params.message) !== null && _params$message2 !== void 0 ? _params$message2 : (params === null || params === void 0 ? void 0 : params.url) ? `Failed to find or contact remote endpoint at url ${params.url}` : "Failed to find or contact remote endpoint";
403
+ const code = CopilotKitErrorCode.REMOTE_ENDPOINT_NOT_FOUND;
404
+ super({
405
+ message,
406
+ code
407
+ });
408
+ this.name = ERROR_NAMES.COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR;
409
+ }
410
+ };
411
+ /**
412
+ * Error thrown when a LangGraph agent cannot be found or accessed.
413
+ * This typically occurs when:
414
+ * - The specified agent name does not exist in the deployment
415
+ * - The agent configuration is invalid or missing
416
+ * - The agent service is not properly deployed or initialized
417
+ *
418
+ * @extends CopilotKitError
419
+ */
420
+ var CopilotKitAgentDiscoveryError = class extends CopilotKitError {
421
+ constructor(params) {
422
+ const { agentName, availableAgents } = params;
423
+ const code = CopilotKitErrorCode.AGENT_NOT_FOUND;
424
+ const seeMore = getSeeMoreMarkdown(ERROR_CONFIG[code].troubleshootingUrl);
425
+ let message;
426
+ if (availableAgents.length) {
427
+ const agentList = availableAgents.map((agent) => agent.name).join(", ");
428
+ if (agentName) message = `Agent '${agentName}' was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${seeMore}`;
429
+ else message = `The requested agent was not found. Available agents are: ${agentList}. Please verify the agent name in your configuration and ensure it matches one of the available agents.\n\n${seeMore}`;
430
+ } else message = `${agentName ? `Agent '${agentName}'` : "The requested agent"} was not found. Please set up at least one agent before proceeding. ${seeMore}`;
431
+ super({
432
+ message,
433
+ code
434
+ });
435
+ this.name = ERROR_NAMES.COPILOT_KIT_AGENT_DISCOVERY_ERROR;
436
+ }
437
+ };
438
+ /**
439
+ * Handles low-level networking errors that occur before a request reaches the server.
440
+ * These errors arise from issues in the underlying communication infrastructure rather than
441
+ * application-level logic or server responses. Typically used to handle "fetch failed" errors
442
+ * where no HTTP status code is available.
443
+ *
444
+ * Common scenarios include:
445
+ * - Connection failures (ECONNREFUSED) when server is down/unreachable
446
+ * - DNS resolution failures (ENOTFOUND) when domain can't be resolved
447
+ * - Timeouts (ETIMEDOUT) when request takes too long
448
+ * - Protocol/transport layer errors like SSL/TLS issues
449
+ */
450
+ var CopilotKitLowLevelError = class extends CopilotKitError {
451
+ constructor({ error, url, message }) {
452
+ let code = CopilotKitErrorCode.NETWORK_ERROR;
453
+ const errorCode = error.code;
454
+ const errorMessage = message !== null && message !== void 0 ? message : resolveLowLevelErrorMessage({
455
+ errorCode,
456
+ url
457
+ });
458
+ super({
459
+ message: errorMessage,
460
+ code
461
+ });
462
+ this.name = ERROR_NAMES.COPILOT_KIT_LOW_LEVEL_ERROR;
463
+ }
464
+ };
465
+ /**
466
+ * Generic catch-all error handler for HTTP responses from the CopilotKit API where a status code is available.
467
+ * Used when we receive an HTTP error status and wish to handle broad range of them
468
+ *
469
+ * This differs from CopilotKitLowLevelError in that:
470
+ * - ResolvedCopilotKitError: Server was reached and returned an HTTP status
471
+ * - CopilotKitLowLevelError: Error occurred before reaching server (e.g. network failure)
472
+ *
473
+ * @param status - The HTTP status code received from the API response
474
+ * @param message - Optional error message to include
475
+ * @param code - Optional specific CopilotKitErrorCode to override default behavior
476
+ *
477
+ * Default behavior:
478
+ * - 400 Bad Request: Maps to CopilotKitApiDiscoveryError
479
+ * - All other status codes: Maps to UNKNOWN error code if no specific code provided
480
+ */
481
+ var ResolvedCopilotKitError = class extends CopilotKitError {
482
+ constructor({ status, message, code, isRemoteEndpoint, url }) {
483
+ let resolvedCode = code;
484
+ if (!resolvedCode) switch (status) {
485
+ case 400: throw new CopilotKitApiDiscoveryError({
486
+ message,
487
+ url
488
+ });
489
+ case 404: throw isRemoteEndpoint ? new CopilotKitRemoteEndpointDiscoveryError({
490
+ message,
491
+ url
492
+ }) : new CopilotKitApiDiscoveryError({
493
+ message,
494
+ url
495
+ });
496
+ default:
497
+ resolvedCode = CopilotKitErrorCode.UNKNOWN;
498
+ break;
499
+ }
500
+ super({
501
+ message,
502
+ code: resolvedCode
503
+ });
504
+ this.name = ERROR_NAMES.RESOLVED_COPILOT_KIT_ERROR;
505
+ }
506
+ };
507
+ var ConfigurationError = class extends CopilotKitError {
508
+ constructor(message) {
509
+ super({
510
+ message,
511
+ code: CopilotKitErrorCode.CONFIGURATION_ERROR
512
+ });
513
+ this.name = ERROR_NAMES.CONFIGURATION_ERROR;
514
+ this.severity = Severity.WARNING;
515
+ }
516
+ };
517
+ var MissingPublicApiKeyError = class extends ConfigurationError {
518
+ constructor(message) {
519
+ super(message);
520
+ this.name = ERROR_NAMES.MISSING_PUBLIC_API_KEY_ERROR;
521
+ this.severity = Severity.CRITICAL;
522
+ }
523
+ };
524
+ var UpgradeRequiredError = class extends ConfigurationError {
525
+ constructor(message) {
526
+ super(message);
527
+ this.name = ERROR_NAMES.UPGRADE_REQUIRED_ERROR;
528
+ this.severity = Severity.WARNING;
529
+ }
530
+ };
531
+ /**
532
+ * Checks if an error is already a structured CopilotKit error.
533
+ * This utility centralizes the logic for detecting structured errors across the codebase.
534
+ *
535
+ * @param error - The error to check
536
+ * @returns true if the error is already structured, false otherwise
537
+ */
538
+ function isStructuredCopilotKitError(error) {
539
+ var _error$extensions;
540
+ return error instanceof CopilotKitError || error instanceof CopilotKitLowLevelError || (error === null || error === void 0 ? void 0 : error.name) && error.name.includes("CopilotKit") || (error === null || error === void 0 || (_error$extensions = error.extensions) === null || _error$extensions === void 0 ? void 0 : _error$extensions.code) !== void 0;
541
+ }
542
+ /**
543
+ * Returns the error as-is if it's already structured, otherwise converts it using the provided converter function.
544
+ * This utility centralizes the pattern of preserving structured errors while converting unstructured ones.
545
+ *
546
+ * @param error - The error to process
547
+ * @param converter - Function to convert unstructured errors to structured ones
548
+ * @returns The structured error
549
+ */
550
+ function ensureStructuredError(error, converter) {
551
+ return isStructuredCopilotKitError(error) ? error : converter(error);
552
+ }
553
+ async function getPossibleVersionMismatch({ runtimeVersion, runtimeClientGqlVersion }) {
554
+ if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion) return;
555
+ if (COPILOTKIT_VERSION !== runtimeVersion || COPILOTKIT_VERSION !== runtimeClientGqlVersion || runtimeVersion !== runtimeClientGqlVersion) return {
556
+ runtimeVersion,
557
+ runtimeClientGqlVersion,
558
+ reactCoreVersion: COPILOTKIT_VERSION,
559
+ message: getVersionMismatchErrorMessage({
560
+ runtimeVersion,
561
+ runtimeClientGqlVersion,
562
+ reactCoreVersion: COPILOTKIT_VERSION
563
+ })
564
+ };
565
+ }
566
+ const resolveLowLevelErrorMessage = ({ errorCode, url }) => {
567
+ const troubleshootingLink = ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;
568
+ const genericMessage = (description = `Failed to fetch from url ${url}.`) => `${description}.
569
+
570
+ Possible reasons:
571
+ - -The server may have an error preventing it from returning a response (Check the server logs for more info).
572
+ - -The server might be down or unreachable
573
+ - -There might be a network issue (e.g., DNS failure, connection timeout)
574
+ - -The URL might be incorrect
575
+ - -The server is not running on the specified port
576
+
577
+ ${getSeeMoreMarkdown(troubleshootingLink)}`;
578
+ if (url.includes("/info")) return genericMessage(`Failed to fetch CopilotKit agents/action information from url ${url}.`);
579
+ if (url.includes("/actions/execute")) return genericMessage(`Fetch call to ${url} to execute actions failed.`);
580
+ if (url.includes("/agents/state")) return genericMessage(`Fetch call to ${url} to get agent state failed.`);
581
+ if (url.includes("/agents/execute")) return genericMessage(`Fetch call to ${url} to execute agent(s) failed.`);
582
+ switch (errorCode) {
583
+ case "ECONNREFUSED": return `Connection to ${url} was refused. Ensure the server is running and accessible.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
584
+ case "ENOTFOUND": return `The server on ${url} could not be found. Check the URL or your network configuration.\n\n${getSeeMoreMarkdown(ERROR_CONFIG[CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl)}`;
585
+ case "ETIMEDOUT": return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
586
+ default: return;
587
+ }
588
+ };
589
+
590
+ //#endregion
591
+ //#region src/utils/json-schema.ts
592
+ function actionParametersToJsonSchema(actionParameters) {
593
+ let parameters = {};
594
+ for (let parameter of actionParameters || []) parameters[parameter.name] = convertAttribute(parameter);
595
+ let requiredParameterNames = [];
596
+ for (let arg of actionParameters || []) if (arg.required !== false) requiredParameterNames.push(arg.name);
597
+ return {
598
+ type: "object",
599
+ properties: parameters,
600
+ required: requiredParameterNames
601
+ };
602
+ }
603
+ function jsonSchemaToActionParameters(jsonSchema) {
604
+ if (jsonSchema.type !== "object" || !jsonSchema.properties) return [];
605
+ const parameters = [];
606
+ const requiredFields = jsonSchema.required || [];
607
+ for (const [name, schema] of Object.entries(jsonSchema.properties)) {
608
+ const parameter = convertJsonSchemaToParameter(name, schema, requiredFields.includes(name));
609
+ parameters.push(parameter);
610
+ }
611
+ return parameters;
612
+ }
613
+ function convertJsonSchemaToParameter(name, schema, isRequired) {
614
+ const baseParameter = {
615
+ name,
616
+ description: schema.description
617
+ };
618
+ if (!isRequired) baseParameter.required = false;
619
+ if (Array.isArray(schema.type)) {
620
+ const types = schema.type;
621
+ const hasNull = types.includes("null");
622
+ const nonNullTypes = types.filter((t) => t !== "null");
623
+ const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
624
+ return convertJsonSchemaToParameter(name, {
625
+ ...schema,
626
+ type: resolvedType
627
+ }, hasNull ? false : isRequired);
628
+ }
629
+ switch (schema.type) {
630
+ case "string": return {
631
+ ...baseParameter,
632
+ type: "string",
633
+ ...schema.enum && { enum: schema.enum }
634
+ };
635
+ case "number":
636
+ case "boolean": return {
637
+ ...baseParameter,
638
+ type: schema.type
639
+ };
640
+ case "object":
641
+ if (schema.properties) {
642
+ const attributes = [];
643
+ const requiredFields = schema.required || [];
644
+ for (const [propName, propSchema] of Object.entries(schema.properties)) attributes.push(convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)));
645
+ return {
646
+ ...baseParameter,
647
+ type: "object",
648
+ attributes
649
+ };
650
+ }
651
+ return {
652
+ ...baseParameter,
653
+ type: "object"
654
+ };
655
+ case "array": if (schema.items.type === "object" && "properties" in schema.items) {
656
+ const attributes = [];
657
+ const requiredFields = schema.items.required || [];
658
+ for (const [propName, propSchema] of Object.entries(schema.items.properties || {})) attributes.push(convertJsonSchemaToParameter(propName, propSchema, requiredFields.includes(propName)));
659
+ return {
660
+ ...baseParameter,
661
+ type: "object[]",
662
+ attributes
663
+ };
664
+ } else if (schema.items.type === "array") throw new Error("Nested arrays are not supported");
665
+ else return {
666
+ ...baseParameter,
667
+ type: `${schema.items.type}[]`
668
+ };
669
+ default: return {
670
+ ...baseParameter,
671
+ type: "string"
672
+ };
673
+ }
674
+ }
675
+ function convertAttribute(attribute) {
676
+ switch (attribute.type) {
677
+ case "string": return {
678
+ type: "string",
679
+ description: attribute.description,
680
+ ...attribute.enum && { enum: attribute.enum }
681
+ };
682
+ case "number":
683
+ case "boolean": return {
684
+ type: attribute.type,
685
+ description: attribute.description
686
+ };
687
+ case "object":
688
+ case "object[]":
689
+ var _attribute$attributes, _attribute$attributes2;
690
+ const properties = (_attribute$attributes = attribute.attributes) === null || _attribute$attributes === void 0 ? void 0 : _attribute$attributes.reduce((acc, attr) => {
691
+ acc[attr.name] = convertAttribute(attr);
692
+ return acc;
693
+ }, {});
694
+ const required = (_attribute$attributes2 = attribute.attributes) === null || _attribute$attributes2 === void 0 ? void 0 : _attribute$attributes2.filter((attr) => attr.required !== false).map((attr) => attr.name);
695
+ if (attribute.type === "object[]") return {
696
+ type: "array",
697
+ items: {
698
+ type: "object",
699
+ ...properties && { properties },
700
+ ...required && required.length > 0 && { required }
701
+ },
702
+ description: attribute.description
703
+ };
704
+ return {
705
+ type: "object",
706
+ description: attribute.description,
707
+ ...properties && { properties },
708
+ ...required && required.length > 0 && { required }
709
+ };
710
+ default:
711
+ var _attribute$type;
712
+ if ((_attribute$type = attribute.type) === null || _attribute$type === void 0 ? void 0 : _attribute$type.endsWith("[]")) return {
713
+ type: "array",
714
+ items: { type: attribute.type.slice(0, -2) },
715
+ description: attribute.description
716
+ };
717
+ return {
718
+ type: "string",
719
+ description: attribute.description
720
+ };
721
+ }
722
+ }
723
+ function convertJsonSchemaToZodSchema(jsonSchema, required, definitions, visitedRefs) {
724
+ var _ref, _jsonSchema$anyOf, _jsonSchema$type;
725
+ if (jsonSchema.$ref && definitions) {
726
+ const refPath = jsonSchema.$ref.replace(/^#\/\$defs\/|^#\/definitions\//, "");
727
+ const refs = visitedRefs !== null && visitedRefs !== void 0 ? visitedRefs : /* @__PURE__ */ new Set();
728
+ if (refs.has(refPath)) {
729
+ console.warn(`[CopilotKit] Circular $ref detected for "${refPath}" — falling back to z.any()`);
730
+ let schema = zod.z.any();
731
+ if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
732
+ return required ? schema : schema.optional();
733
+ }
734
+ const resolved = definitions[refPath];
735
+ if (resolved) {
736
+ const nextRefs = new Set(refs);
737
+ nextRefs.add(refPath);
738
+ return convertJsonSchemaToZodSchema(resolved, required, definitions, nextRefs);
739
+ }
740
+ }
741
+ const defs = (_ref = definitions !== null && definitions !== void 0 ? definitions : jsonSchema.$defs) !== null && _ref !== void 0 ? _ref : jsonSchema.definitions;
742
+ if (Array.isArray(jsonSchema.type)) {
743
+ const types = jsonSchema.type;
744
+ const hasNull = types.includes("null");
745
+ const nonNullTypes = types.filter((t) => t !== "null");
746
+ const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
747
+ const innerSchema = convertJsonSchemaToZodSchema({
748
+ ...jsonSchema,
749
+ type: resolvedType
750
+ }, true, defs, visitedRefs);
751
+ let schema = hasNull ? zod.z.union([innerSchema, zod.z.null()]) : innerSchema;
752
+ if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
753
+ return required ? schema : schema.optional();
754
+ }
755
+ const unionVariants = (_jsonSchema$anyOf = jsonSchema.anyOf) !== null && _jsonSchema$anyOf !== void 0 ? _jsonSchema$anyOf : jsonSchema.oneOf;
756
+ if (Array.isArray(unionVariants) && unionVariants.length > 0) {
757
+ if (unionVariants.length === 1) return convertJsonSchemaToZodSchema(unionVariants[0], required, defs, visitedRefs);
758
+ const schemas = unionVariants.map((v) => convertJsonSchemaToZodSchema(v, true, defs, visitedRefs));
759
+ let schema = zod.z.union(schemas);
760
+ if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
761
+ return required ? schema : schema.optional();
762
+ }
763
+ if (jsonSchema.type === "object") {
764
+ const spec = {};
765
+ if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) return !required ? zod.z.object(spec).optional() : zod.z.object(spec);
766
+ for (const [key, value] of Object.entries(jsonSchema.properties)) spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false, defs, visitedRefs);
767
+ let schema = zod.z.object(spec).describe(jsonSchema.description);
768
+ return required ? schema : schema.optional();
769
+ } else if (jsonSchema.type === "string") {
770
+ if (jsonSchema.enum && jsonSchema.enum.length > 0) {
771
+ let schema = zod.z.enum(jsonSchema.enum).describe(jsonSchema.description);
772
+ return required ? schema : schema.optional();
773
+ }
774
+ let schema = zod.z.string().describe(jsonSchema.description);
775
+ return required ? schema : schema.optional();
776
+ } else if (jsonSchema.type === "number" || jsonSchema.type === "integer") {
777
+ let schema = zod.z.number().describe(jsonSchema.description);
778
+ return required ? schema : schema.optional();
779
+ } else if (jsonSchema.type === "boolean") {
780
+ let schema = zod.z.boolean().describe(jsonSchema.description);
781
+ return required ? schema : schema.optional();
782
+ } else if (jsonSchema.type === "array") {
783
+ let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true, defs, visitedRefs);
784
+ let schema = zod.z.array(itemSchema).describe(jsonSchema.description);
785
+ return required ? schema : schema.optional();
786
+ } else if (jsonSchema.type === "null") {
787
+ let schema = zod.z.null().describe(jsonSchema.description);
788
+ return required ? schema : schema.optional();
789
+ }
790
+ console.warn(`[CopilotKit] Unsupported JSON schema type "${(_jsonSchema$type = jsonSchema.type) !== null && _jsonSchema$type !== void 0 ? _jsonSchema$type : "unknown"}" — falling back to z.any()`);
791
+ let schema = zod.z.any();
792
+ if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
793
+ return required ? schema : schema.optional();
794
+ }
795
+ function getZodParameters(parameters) {
796
+ if (!parameters) return zod.z.object({});
797
+ return convertJsonSchemaToZodSchema(actionParametersToJsonSchema(parameters), true);
798
+ }
799
+
800
+ //#endregion
801
+ //#region src/utils/dashboard-url.ts
802
+ /**
803
+ * Checks dashboard navigation transport and credentials only.
804
+ * Callers must separately enforce the configured origin and allowed paths.
805
+ * This policy does not authorize server-side requests.
806
+ */
807
+ function isSafeDashboardUrl(url) {
808
+ const local = [
809
+ "localhost",
810
+ "127.0.0.1",
811
+ "[::1]"
812
+ ].includes(url.hostname) || /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+localhost$/u.test(url.hostname);
813
+ return !url.username && !url.password && (url.protocol === "https:" || url.protocol === "http:" && local);
814
+ }
815
+
816
+ //#endregion
817
+ //#region src/utils/inspector-metadata.ts
818
+ function isRecord$1(value) {
819
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
820
+ try {
821
+ const prototype = Object.getPrototypeOf(value);
822
+ return prototype === Object.prototype || prototype === null;
823
+ } catch (_unused) {
824
+ return false;
825
+ }
826
+ }
827
+ function readOwnDataProperty(value, key) {
828
+ try {
829
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
830
+ return descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0;
831
+ } catch (_unused2) {
832
+ return;
833
+ }
834
+ }
835
+ function parseNonBlankString(value) {
836
+ if (typeof value !== "string") return;
837
+ const parsed = value.trim();
838
+ return parsed.length > 0 ? parsed : void 0;
839
+ }
840
+ function parseIdentity(value) {
841
+ if (!isRecord$1(value)) return;
842
+ const organizationName = parseNonBlankString(value.organizationName);
843
+ const projectName = parseNonBlankString(value.projectName);
844
+ if (organizationName === void 0 || projectName === void 0) return;
845
+ return {
846
+ organizationName,
847
+ projectName
848
+ };
849
+ }
850
+ function parsePlan(value) {
851
+ if (!isRecord$1(value)) return;
852
+ const code = parseNonBlankString(value.code);
853
+ const label = parseNonBlankString(value.label);
854
+ if (code === void 0 || label === void 0) return;
855
+ return {
856
+ code,
857
+ label
858
+ };
859
+ }
860
+ function parseLicense(value) {
861
+ if (!isRecord$1(value)) return;
862
+ switch (value.state) {
863
+ case "valid":
864
+ case "none":
865
+ case "expired":
866
+ case "unknown": return { state: value.state };
867
+ default: return;
868
+ }
869
+ }
870
+ function parseActionKind(value) {
871
+ switch (value) {
872
+ case "manage_plan":
873
+ case "renew":
874
+ case "enable_intelligence": return value;
875
+ default: return;
876
+ }
877
+ }
878
+ function parseSafeActionUrl(value) {
879
+ const url = parseNonBlankString(value);
880
+ if (url === void 0 || url.includes("?") || url.includes("#")) return;
881
+ const authorityStart = url.indexOf("://");
882
+ if (authorityStart < 1) return;
883
+ const authorityAndPath = url.slice(authorityStart + 3);
884
+ const pathStart = authorityAndPath.indexOf("/");
885
+ if ((pathStart === -1 ? authorityAndPath : authorityAndPath.slice(0, pathStart)).includes("@")) return;
886
+ let parsed;
887
+ try {
888
+ parsed = new URL(url);
889
+ } catch (_unused3) {
890
+ return;
891
+ }
892
+ if (parsed.hostname.length === 0 || parsed.username || parsed.password) return;
893
+ return isSafeDashboardUrl(parsed) ? url : void 0;
894
+ }
895
+ function parseAction(value) {
896
+ if (!isRecord$1(value)) return;
897
+ const kind = parseActionKind(value.kind);
898
+ const url = parseSafeActionUrl(value.url);
899
+ if (kind === void 0 || url === void 0) return;
900
+ return {
901
+ kind,
902
+ url
903
+ };
904
+ }
905
+ function isFiniteNonnegativeInteger(value) {
906
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
907
+ }
908
+ function parseUsageLimit(value) {
909
+ if (!isRecord$1(value)) return;
910
+ if (value.kind === "finite") {
911
+ if (typeof value.value !== "number" || !Number.isSafeInteger(value.value) || value.value < 1) return;
912
+ return {
913
+ kind: "finite",
914
+ value: value.value
915
+ };
916
+ }
917
+ if (value.kind === "unlimited") return { kind: "unlimited" };
918
+ if (value.kind === "unknown") return { kind: "unknown" };
919
+ }
920
+ function parseUsage(value) {
921
+ if (!isRecord$1(value)) return;
922
+ const limit = parseUsageLimit(value.limit);
923
+ const used = value.used;
924
+ if (!isFiniteNonnegativeInteger(used) || limit === void 0) return;
925
+ const rawExpiringSoonCount = readOwnDataProperty(value, "expiringSoonCount");
926
+ const expiringSoonCount = isFiniteNonnegativeInteger(rawExpiringSoonCount) ? rawExpiringSoonCount : void 0;
927
+ return {
928
+ used,
929
+ limit,
930
+ ...expiringSoonCount === void 0 ? {} : { expiringSoonCount }
931
+ };
932
+ }
933
+ /**
934
+ * Parses untrusted inspector metadata without letting one invalid optional
935
+ * module hide the other valid modules.
936
+ *
937
+ * @param value - The decoded runtime response body.
938
+ * @returns Normalized version 1 metadata, or `undefined` for an unsupported
939
+ * top-level payload.
940
+ */
941
+ function parseInspectorMetadataV1(value) {
942
+ if (!isRecord$1(value) || value.schemaVersion !== 1) return;
943
+ const identity = parseIdentity(value.identity);
944
+ const plan = parsePlan(value.plan);
945
+ const license = parseLicense(value.license);
946
+ const action = parseAction(value.action);
947
+ const usage = parseUsage(value.usage);
948
+ return {
949
+ schemaVersion: 1,
950
+ ...identity === void 0 ? {} : { identity },
951
+ ...plan === void 0 ? {} : { plan },
952
+ ...license === void 0 ? {} : { license },
953
+ ...action === void 0 ? {} : { action },
954
+ ...usage === void 0 ? {} : { usage }
955
+ };
956
+ }
957
+
958
+ //#endregion
959
+ //#region src/utils/inspector-learning.ts
960
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
961
+ const string = (value, maximum) => typeof value === "string" && value.trim().length > 0 && value.length <= maximum;
962
+ const integer = (value, minimum = 0) => typeof value === "number" && Number.isSafeInteger(value) && value >= minimum;
963
+ const date = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value));
964
+ /**
965
+ * Accepts only the configured Intelligence web-app origin.
966
+ *
967
+ * Learning links are server-authored actions. Treating every HTTPS origin as
968
+ * trusted would let a misconfigured or compromised upstream turn Inspector
969
+ * copy into a navigation primitive for an arbitrary site.
970
+ */
971
+ function parseInspectorLearningUrl(value, trustedOrigin) {
972
+ if (typeof value !== "string" || value.length > 4e3 || typeof trustedOrigin !== "string" || trustedOrigin.length > 2e3) return;
973
+ try {
974
+ const parsed = new URL(value);
975
+ const configured = new URL(trustedOrigin);
976
+ if (parsed.username || parsed.password || configured.username || configured.password || configured.pathname !== "/" || configured.search || configured.hash || !isSafeDashboardUrl(configured) || parsed.origin !== configured.origin) return;
977
+ return parsed.toString();
978
+ } catch (_unused) {
979
+ return;
980
+ }
981
+ }
982
+ /** Validates the canonical dashboard route after the origin check. */
983
+ function validLearningPath(value, kind) {
984
+ const url = new URL(value);
985
+ if (url.search || url.hash) return false;
986
+ if (kind === "learning") return url.pathname === "/learning" || /^\/o\/[^/]+\/[^/]+\/learning(?:\/[^/]+)?$/u.test(url.pathname);
987
+ return kind === "candidates" ? /^\/o\/[^/]+\/[^/]+\/learning\/[^/]+\/skills$/u.test(url.pathname) : /^\/o\/[^/]+\/[^/]+\/learning\/[^/]+\/analysis-results$/u.test(url.pathname);
988
+ }
989
+ function parseEvidence(value) {
990
+ if (record(value) && value.status === "unavailable") return Object.keys(value).length === 1 ? { status: "unavailable" } : void 0;
991
+ if (!record(value) || value.status !== "available" || !string(value.threadId, 128) || !date(value.updatedAt)) return;
992
+ if (value.threadName !== null && !(typeof value.threadName === "string" && value.threadName.length <= 4e3)) return;
993
+ if (!Array.isArray(value.messageIds) || value.messageIds.length > 200 || !value.messageIds.every((id) => string(id, 128))) return;
994
+ return {
995
+ status: "available",
996
+ threadId: value.threadId,
997
+ threadName: value.threadName,
998
+ messageIds: [...value.messageIds],
999
+ updatedAt: value.updatedAt
1000
+ };
1001
+ }
1002
+ function parseTrajectoryEvidence(value, webAppOrigin) {
1003
+ if (record(value) && value.status === "unavailable") return Object.keys(value).length === 1 ? { status: "unavailable" } : void 0;
1004
+ if (!record(value) || value.status !== "available" || !string(value.trajectoryId, 128) || !integer(value.eventCount)) return;
1005
+ const url = parseInspectorLearningUrl(value.url, webAppOrigin);
1006
+ if (!url) return void 0;
1007
+ return {
1008
+ status: "available",
1009
+ trajectoryId: value.trajectoryId,
1010
+ eventCount: value.eventCount,
1011
+ url
1012
+ };
1013
+ }
1014
+ function parseInsight(value, webAppOrigin) {
1015
+ if (!record(value) || !string(value.id, 128) || !string(value.statement, 4e3) || !string(value.impact, 4e3) || !integer(value.totalThreadCount) || typeof value.evidenceTruncated !== "boolean" || !Array.isArray(value.evidence) || value.evidence.length > 100) return;
1016
+ const evidence = value.evidence.map(parseEvidence);
1017
+ if (evidence.some((item) => item === void 0)) return void 0;
1018
+ const insight = {
1019
+ id: value.id,
1020
+ statement: value.statement,
1021
+ impact: value.impact,
1022
+ totalThreadCount: value.totalThreadCount,
1023
+ evidenceTruncated: value.evidenceTruncated,
1024
+ evidence
1025
+ };
1026
+ let totalTrajectoryCount;
1027
+ if (value.totalTrajectoryCount !== void 0) {
1028
+ if (!integer(value.totalTrajectoryCount)) return void 0;
1029
+ totalTrajectoryCount = value.totalTrajectoryCount;
1030
+ }
1031
+ let trajectoryEvidence;
1032
+ if (value.trajectoryEvidence !== void 0) {
1033
+ if (!Array.isArray(value.trajectoryEvidence) || value.trajectoryEvidence.length > 100) return;
1034
+ const parsed = value.trajectoryEvidence.map((item) => parseTrajectoryEvidence(item, webAppOrigin));
1035
+ if (parsed.some((item) => item === void 0)) return void 0;
1036
+ trajectoryEvidence = parsed;
1037
+ }
1038
+ return {
1039
+ ...insight,
1040
+ ...totalTrajectoryCount === void 0 ? {} : { totalTrajectoryCount },
1041
+ ...trajectoryEvidence === void 0 ? {} : { trajectoryEvidence }
1042
+ };
1043
+ }
1044
+ function parseSkill(value, webAppOrigin) {
1045
+ if (!record(value) || !string(value.id, 128) || !string(value.name, 128) || !string(value.description, 4e3) || !integer(value.revision, 1) || typeof value.skillMd !== "string" || value.skillMd.length > 131072) return;
1046
+ const sourceInsight = value.sourceInsight === null ? null : parseInsight(value.sourceInsight, webAppOrigin);
1047
+ if (sourceInsight === void 0) return void 0;
1048
+ return {
1049
+ id: value.id,
1050
+ name: value.name,
1051
+ description: value.description,
1052
+ revision: value.revision,
1053
+ skillMd: value.skillMd,
1054
+ sourceInsight
1055
+ };
1056
+ }
1057
+ function parsePage(value, pageSize, parseItem) {
1058
+ if (!record(value) || !integer(value.page, 1) || value.pageSize !== pageSize || !integer(value.total) || !integer(value.totalPages) || !Array.isArray(value.items) || value.items.length > pageSize) return;
1059
+ const items = value.items.map(parseItem);
1060
+ if (items.some((item) => item === void 0)) return void 0;
1061
+ if (value.total === 0) {
1062
+ if (value.page !== 1 || value.totalPages !== 0 || items.length !== 0) return;
1063
+ } else {
1064
+ const totalPages = Math.ceil(value.total / pageSize);
1065
+ const expectedItems = Math.min(pageSize, value.total - (value.page - 1) * pageSize);
1066
+ if (value.totalPages !== totalPages || value.page > totalPages || items.length !== expectedItems) return;
1067
+ }
1068
+ return {
1069
+ page: value.page,
1070
+ pageSize,
1071
+ total: value.total,
1072
+ totalPages: value.totalPages,
1073
+ items
1074
+ };
1075
+ }
1076
+ function parseConfiguration(value) {
1077
+ if (!record(value)) return void 0;
1078
+ if (value.state === "not_configured" || value.state === "selection_required") return { state: value.state };
1079
+ if (value.state === "invalid" && (value.reason === "container" || value.reason === "instrumentation")) return {
1080
+ state: value.state,
1081
+ reason: value.reason
1082
+ };
1083
+ if (value.state === "configured" && record(value.container) && string(value.container.id, 128) && string(value.container.name, 128)) return {
1084
+ state: "configured",
1085
+ container: {
1086
+ id: value.container.id,
1087
+ name: value.container.name
1088
+ }
1089
+ };
1090
+ }
1091
+ const runStatuses = new Set([
1092
+ "queued",
1093
+ "freezing",
1094
+ "batching",
1095
+ "reducing",
1096
+ "finalizing",
1097
+ "succeeded",
1098
+ "failed"
1099
+ ]);
1100
+ /** Validates and copies an untrusted Learning snapshot at each process boundary. */
1101
+ function parseInspectorLearningSnapshotV1(value) {
1102
+ if (!record(value) || value.schemaVersion !== 1 || !string(value.projectKey, 128) || !string(value.snapshotVersion, 128) || !integer(value.pendingThreadCount) || !integer(value.pendingCandidateCount) || !record(value.run) || typeof value.run.hasActiveRun !== "boolean" || typeof value.run.hasEverSucceeded !== "boolean") return;
1103
+ const originUrl = parseInspectorLearningUrl(value.webAppOrigin, value.webAppOrigin);
1104
+ if (!originUrl || new URL(originUrl).pathname !== "/") return void 0;
1105
+ const webAppOrigin = new URL(originUrl).origin;
1106
+ const configuration = parseConfiguration(value.configuration);
1107
+ const skillsPage = parsePage(value.skillsPage, 3, (item) => parseSkill(item, webAppOrigin));
1108
+ const insightsPage = parsePage(value.insightsPage, 4, (item) => parseInsight(item, webAppOrigin));
1109
+ if (!configuration || !skillsPage || !insightsPage) return void 0;
1110
+ let latest = null;
1111
+ if (value.run.latest !== null) {
1112
+ const latestRun = value.run.latest;
1113
+ if (!record(latestRun)) return;
1114
+ const { status, completedAt } = latestRun;
1115
+ if (typeof status !== "string" || !runStatuses.has(status) || completedAt !== null && !date(completedAt)) return void 0;
1116
+ latest = {
1117
+ status,
1118
+ completedAt
1119
+ };
1120
+ }
1121
+ if (!record(value.links)) return void 0;
1122
+ const learning = parseInspectorLearningUrl(value.links.learning, webAppOrigin);
1123
+ const candidates = value.links.candidates === null ? null : parseInspectorLearningUrl(value.links.candidates, webAppOrigin);
1124
+ const runs = value.links.runs === null ? null : parseInspectorLearningUrl(value.links.runs, webAppOrigin);
1125
+ if (!learning || candidates === void 0 || runs === void 0 || !validLearningPath(learning, "learning") || candidates !== null && !validLearningPath(candidates, "candidates") || runs !== null && !validLearningPath(runs, "runs") || value.pendingThreadCount > 0 && runs === null || value.pendingCandidateCount > 0 && candidates === null) return void 0;
1126
+ return {
1127
+ schemaVersion: 1,
1128
+ projectKey: value.projectKey,
1129
+ snapshotVersion: value.snapshotVersion,
1130
+ webAppOrigin,
1131
+ configuration,
1132
+ pendingThreadCount: value.pendingThreadCount,
1133
+ run: {
1134
+ hasActiveRun: value.run.hasActiveRun,
1135
+ hasEverSucceeded: value.run.hasEverSucceeded,
1136
+ latest
1137
+ },
1138
+ pendingCandidateCount: value.pendingCandidateCount,
1139
+ skillsPage,
1140
+ insightsPage,
1141
+ links: {
1142
+ learning,
1143
+ candidates,
1144
+ runs
1145
+ }
1146
+ };
1147
+ }
1148
+ /** Normalizes the browser-owned request without accepting container scope. */
1149
+ function parseInspectorLearningRequestV1(value) {
1150
+ if (!record(value)) return void 0;
1151
+ if (Object.keys(value).some((key) => ![
1152
+ "agentId",
1153
+ "skillsPage",
1154
+ "insightsPage"
1155
+ ].includes(key))) return;
1156
+ const agentId = value.agentId;
1157
+ const skillsPage = value.skillsPage;
1158
+ const insightsPage = value.insightsPage;
1159
+ if (agentId !== void 0 && !string(agentId, 128)) return void 0;
1160
+ if (skillsPage !== void 0 && !integer(skillsPage, 1)) return void 0;
1161
+ if (insightsPage !== void 0 && !integer(insightsPage, 1)) return void 0;
1162
+ return {
1163
+ ...agentId === void 0 ? {} : { agentId },
1164
+ ...skillsPage === void 0 ? {} : { skillsPage },
1165
+ ...insightsPage === void 0 ? {} : { insightsPage }
1166
+ };
1167
+ }
1168
+
1169
+ //#endregion
1170
+ //#region src/utils/inspector-visibility.ts
1171
+ /**
1172
+ * The Inspector is a development-only browser tool. Consumers may disable it,
1173
+ * but an explicit `true` never overrides a production or server environment.
1174
+ */
1175
+ function shouldEnableInspector({ enableInspector, isBrowser, isDevelopment }) {
1176
+ return isBrowser && isDevelopment && enableInspector !== false;
1177
+ }
1178
+
1179
+ //#endregion
1180
+ //#region src/utils/types.ts
1181
+ const RUNTIME_MODE_SSE = "sse";
1182
+ const RUNTIME_MODE_INTELLIGENCE = "intelligence";
1183
+
1184
+ //#endregion
1185
+ //#region src/utils/random-id.ts
1186
+ function randomId() {
1187
+ return "ck-" + (0, uuid.v4)();
1188
+ }
1189
+ function randomUUID() {
1190
+ return (0, uuid.v4)();
1191
+ }
1192
+ /**
1193
+ * Recursively converts an object to a serializable form by converting functions to their string representation.
1194
+ */
1195
+ function toSerializable(value) {
1196
+ if (typeof value === "function") return value.toString();
1197
+ if (Array.isArray(value)) return value.map(toSerializable);
1198
+ if (value !== null && typeof value === "object") {
1199
+ const result = {};
1200
+ for (const key of Object.keys(value)) result[key] = toSerializable(value[key]);
1201
+ return result;
1202
+ }
1203
+ return value;
1204
+ }
1205
+ function dataToUUID(input, namespace) {
1206
+ const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
1207
+ const boundNamespace = namespace ? (0, uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
1208
+ return (0, uuid.v5)(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
1209
+ }
1210
+ function isValidUUID(uuid$1) {
1211
+ return (0, uuid.validate)(uuid$1);
1212
+ }
1213
+
1214
+ //#endregion
1215
+ //#region src/utils/requests.ts
1216
+ /**
1217
+ * Safely read a Response/Request body with sensible defaults:
1218
+ * - clones the response/request to avoid consuming the original response/request
1219
+ * - Skips GET/HEAD
1220
+ * - Tries JSON first regardless of content-type
1221
+ * - Falls back to text and optionally parses when it "looks" like JSON
1222
+ */
1223
+ async function readBody(r) {
1224
+ const method = "method" in r ? r.method.toUpperCase() : void 0;
1225
+ if (method === "GET" || method === "HEAD") return;
1226
+ if (!("body" in r) || r.body == null) return;
1227
+ try {
1228
+ return await r.clone().json();
1229
+ } catch (_unused) {
1230
+ try {
1231
+ const text = await r.clone().text();
1232
+ const trimmed = text.trim();
1233
+ if (trimmed.length === 0) return text;
1234
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
1235
+ return JSON.parse(trimmed);
1236
+ } catch (_unused2) {
1237
+ return text;
1238
+ }
1239
+ return text;
1240
+ } catch (_unused3) {
1241
+ try {
1242
+ var _c$body;
1243
+ const stream = (_c$body = r.clone().body) !== null && _c$body !== void 0 ? _c$body : null;
1244
+ if (!stream) return void 0;
1245
+ const reader = stream.getReader();
1246
+ const decoder = new TextDecoder();
1247
+ let out = "";
1248
+ while (true) {
1249
+ const { done, value } = await reader.read();
1250
+ if (done) break;
1251
+ if (typeof value === "string") out += value;
1252
+ else out += decoder.decode(value, { stream: true });
1253
+ }
1254
+ out += decoder.decode();
1255
+ const trimmed = out.trim();
1256
+ if (trimmed.length === 0) return out;
1257
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
1258
+ return JSON.parse(trimmed);
1259
+ } catch (_unused4) {
1260
+ return out;
1261
+ }
1262
+ return out;
1263
+ } catch (_unused5) {
1264
+ return;
1265
+ }
1266
+ }
1267
+ }
1268
+ }
1269
+
1270
+ //#endregion
1271
+ //#region src/utils/row-render-keys.ts
1272
+ /**
1273
+ * Stable per-row view keys for chat transcripts, across backends that re-key a
1274
+ * message mid-stream. Shared by every frontend package, because the defect and
1275
+ * the correlation signal are in the message stream, not in any one framework.
1276
+ *
1277
+ * ## The problem
1278
+ *
1279
+ * A message's canonical `id` is not stable within a turn. LangChain stamps a
1280
+ * placeholder id on the first streamed chunk when the provider didn't supply
1281
+ * one (`chat_models.py`: `if chunk.message.id is None: chunk.message.id =
1282
+ * "lc_run-" + "-" + run_id`), then prefers any provider-assigned id it sees
1283
+ * while merging chunks (`messages/ai.py`, "Ranks are defined by the order of
1284
+ * preference"). The `MESSAGES_SNAPSHOT` therefore carries the provider's final
1285
+ * id (e.g. `resp_…`) for a message the client already knows as `lc_run--…`.
1286
+ *
1287
+ * Every framework destroys and recreates a row whose key changes, so keying
1288
+ * rows by `id` turned that swap into the visible HITL chat flash, where a
1289
+ * rendered approval card appears to reset during a tool's
1290
+ * `executing → complete` transition.
1291
+ *
1292
+ * This is provider-conditional: providers that stamp an id on every chunk (so
1293
+ * `chunk.message.id is None` never holds) never trigger a rename.
1294
+ *
1295
+ * ## The approach
1296
+ *
1297
+ * Tool-call ids survive the rename, so they are used as *anchors*: the first
1298
+ * message seen carrying a given tool call records the key it was assigned, and
1299
+ * any later message carrying that same tool call reuses it. The store is an
1300
+ * override table consulted before falling back to `message.id`. Resolving only
1301
+ * reads it; each render that reaches the DOM then records what it rendered:
1302
+ *
1303
+ * ```text
1304
+ * render 1 id=lc_run--1 no tools key = message.id = lc_run--1
1305
+ * commit 1 store {}
1306
+ * render 2 id=lc_run--1 tc call_A key = message.id = lc_run--1
1307
+ * commit 2 store { tc:call_A -> lc_run--1 }
1308
+ * render 3 id=resp_1 tc call_A key = store[tc:call_A]
1309
+ * = lc_run--1 (row survives)
1310
+ * commit 3 store unchanged
1311
+ * ```
1312
+ *
1313
+ * Recording the anchor at commit 2 — while the id is still stable — is what
1314
+ * makes render 3 resolvable. Note the fix does not depend on render 2
1315
+ * existing: a message born already carrying a tool call anchors on the first
1316
+ * render that commits it, under whatever id it holds then.
1317
+ *
1318
+ * ## Why an override table rather than keying rows by tool-call id
1319
+ *
1320
+ * Deriving the key from the tool call directly (`tc:<id>` whenever a tool call
1321
+ * is present) needs no state, but changes the key the moment a tool call
1322
+ * *appears* — so an assistant message that streams text and then calls a tool
1323
+ * is torn down on that transition, for every provider, whether or not it
1324
+ * renames. That trades a conditional flash for an unconditional one. Recording
1325
+ * an override keeps the key the row already had.
1326
+ *
1327
+ * ## Cost
1328
+ *
1329
+ * The store holds only `tc:<toolCallId>` entries, so a conversation with no
1330
+ * tool calls keeps an empty store and behaviour byte-identical to keying by
1331
+ * `id`. Size is bounded to the tool calls of the currently-rendered messages
1332
+ * (see `pruneRowKeyStore`), not the conversation length. Deleting the store
1333
+ * reverts to plain `id` keying.
1334
+ *
1335
+ * ## Known gaps
1336
+ *
1337
+ * - A text-only assistant message has no anchor, so it still re-keys. No
1338
+ * client-side correlation signal exists for it; the fix is stable ids
1339
+ * upstream.
1340
+ * - If the tool call's arrival and the id swap land in the same update, the
1341
+ * intermediate state never renders, the anchor is never recorded, and the
1342
+ * row is recreated as before. Correlating in the event-apply layer (i.e. in
1343
+ * the AG-UI client, which observes every intermediate state) would be immune.
1344
+ */
1345
+ const TOOL_ANCHOR_PREFIX = "tc:";
1346
+ function createRowKeyStore() {
1347
+ return {
1348
+ overrides: /* @__PURE__ */ new Map(),
1349
+ ambiguous: /* @__PURE__ */ new Set()
1350
+ };
1351
+ }
1352
+ /**
1353
+ * Anchors a message contributes. Only assistant tool calls qualify: LangChain's
1354
+ * id preference applies when merging `AIMessageChunk`s, so user message ids are
1355
+ * not renamed, and `role: "tool"` messages are not rendered as rows. Every tool
1356
+ * call is used (not just the first) so the anchor survives tool-call reordering
1357
+ * between snapshots.
1358
+ */
1359
+ function toolAnchorsOf(message) {
1360
+ if ((message === null || message === void 0 ? void 0 : message.role) !== "assistant") return [];
1361
+ const toolCalls = message.toolCalls;
1362
+ if (!(toolCalls === null || toolCalls === void 0 ? void 0 : toolCalls.length)) return [];
1363
+ const anchors = [];
1364
+ for (const toolCall of toolCalls) if (toolCall === null || toolCall === void 0 ? void 0 : toolCall.id) anchors.push(`${TOOL_ANCHOR_PREFIX}${toolCall.id}`);
1365
+ return anchors;
1366
+ }
1367
+ /**
1368
+ * Resolves the row key for every message, returned by position.
1369
+ *
1370
+ * Pure: it reads `store` and never writes to it. Every framework here may
1371
+ * evaluate a render pass whose result never reaches the DOM — an abandoned
1372
+ * concurrent render in React, a discarded `computed` evaluation in Vue or
1373
+ * Angular. An anchor recorded by such a pass would vend its key to the pass
1374
+ * that does render, re-keying the row the user is looking at, which is the
1375
+ * teardown this module exists to prevent. Anchors are recorded by
1376
+ * `commitRowKeyStore`, from whichever phase each framework runs after the DOM
1377
+ * is updated.
1378
+ *
1379
+ * Uniqueness is structural rather than assumed: a caller that does not
1380
+ * deduplicate can pass two rows with the same id, and an override can vend a
1381
+ * key equal to a later message's own id.
1382
+ */
1383
+ function resolveRowRenderKeys(store, messages) {
1384
+ const keys = [];
1385
+ const claimed = /* @__PURE__ */ new Set();
1386
+ messages.forEach((message, index) => {
1387
+ var _key;
1388
+ const anchors = toolAnchorsOf(message);
1389
+ let key;
1390
+ for (const anchor of anchors) {
1391
+ if (store.ambiguous.has(anchor)) continue;
1392
+ const recorded = store.overrides.get(anchor);
1393
+ if (recorded !== void 0 && !claimed.has(recorded)) {
1394
+ key = recorded;
1395
+ break;
1396
+ }
1397
+ }
1398
+ (_key = key) !== null && _key !== void 0 || (key = (message === null || message === void 0 ? void 0 : message.id) || `index-${index}`);
1399
+ if (claimed.has(key)) {
1400
+ let suffix = 2;
1401
+ while (claimed.has(`${key}:${suffix}`)) suffix += 1;
1402
+ key = `${key}:${suffix}`;
1403
+ }
1404
+ keys.push(key);
1405
+ claimed.add(key);
1406
+ });
1407
+ return keys;
1408
+ }
1409
+ /**
1410
+ * `message.id` → row key, for callers that render by message rather than by
1411
+ * position. `messages` must be deduplicated: duplicate ids would overwrite
1412
+ * each other in the returned map.
1413
+ */
1414
+ function resolveRowRenderKeysById(store, messages) {
1415
+ const keys = resolveRowRenderKeys(store, messages);
1416
+ const byId = /* @__PURE__ */ new Map();
1417
+ messages.forEach((message, index) => {
1418
+ const key = keys[index];
1419
+ if (key !== void 0) byId.set(message.id, key);
1420
+ });
1421
+ return byId;
1422
+ }
1423
+ /**
1424
+ * Records the anchors of a rendered list, then bounds the store to it. Call
1425
+ * from the phase that runs after the DOM is updated, never while resolving —
1426
+ * see `resolveRowRenderKeys`.
1427
+ *
1428
+ * Re-resolving here reproduces the keys the rows were rendered with, because
1429
+ * the store cannot change between a render and its own post-render phase.
1430
+ *
1431
+ * An anchor carried by two rows in the same list is marked ambiguous rather
1432
+ * than recorded. Recording it would give the first row's key to whichever row
1433
+ * outlived the other, and with it that row's DOM and component state.
1434
+ */
1435
+ function commitRowKeyStore(store, messages) {
1436
+ const keys = resolveRowRenderKeys(store, messages);
1437
+ const anchorCounts = /* @__PURE__ */ new Map();
1438
+ for (const message of messages) for (const anchor of toolAnchorsOf(message)) {
1439
+ var _anchorCounts$get;
1440
+ anchorCounts.set(anchor, ((_anchorCounts$get = anchorCounts.get(anchor)) !== null && _anchorCounts$get !== void 0 ? _anchorCounts$get : 0) + 1);
1441
+ }
1442
+ store.ambiguous.clear();
1443
+ for (const [anchor, count] of anchorCounts) if (count > 1) {
1444
+ store.ambiguous.add(anchor);
1445
+ store.overrides.delete(anchor);
1446
+ }
1447
+ messages.forEach((message, index) => {
1448
+ const key = keys[index];
1449
+ if (key === void 0) return;
1450
+ for (const anchor of toolAnchorsOf(message)) {
1451
+ if (store.ambiguous.has(anchor)) continue;
1452
+ if (!store.overrides.has(anchor)) store.overrides.set(anchor, key);
1453
+ }
1454
+ });
1455
+ pruneRowKeyStore(store, messages);
1456
+ }
1457
+ /**
1458
+ * Drops anchors no longer present in `messages`, bounding the store to the
1459
+ * tool calls of the currently-rendered messages. Called by
1460
+ * `commitRowKeyStore`; like it, this writes to the store and so belongs after
1461
+ * the DOM is updated, never while resolving.
1462
+ *
1463
+ * Pruned entries are unreachable by construction: `resolveRowRenderKeys` only
1464
+ * looks up anchors belonging to messages in the list it is given.
1465
+ */
1466
+ function pruneRowKeyStore(store, messages) {
1467
+ const live = /* @__PURE__ */ new Set();
1468
+ for (const message of messages) for (const anchor of toolAnchorsOf(message)) live.add(anchor);
1469
+ for (const anchor of store.overrides.keys()) if (!live.has(anchor)) store.overrides.delete(anchor);
1470
+ for (const anchor of store.ambiguous) if (!live.has(anchor)) store.ambiguous.delete(anchor);
1471
+ }
1472
+
1473
+ //#endregion
1474
+ //#region src/utils/index.ts
1475
+ /**
1476
+ * Safely parses a JSON string into an object
1477
+ * @param json The JSON string to parse
1478
+ * @param fallback Optional fallback value to return if parsing fails. If not provided or set to "unset", returns null
1479
+ * @returns The parsed JSON object, or the fallback value (or null) if parsing fails
1480
+ */
1481
+ function parseJson(json, fallback = "unset") {
1482
+ try {
1483
+ return JSON.parse(json);
1484
+ } catch (_unused) {
1485
+ return fallback === "unset" ? null : fallback;
1486
+ }
1487
+ }
1488
+ const PARTIAL_JSON_ALLOW = partial_json.Allow.ALL & ~partial_json.Allow.NUM;
1489
+ /**
1490
+ * Parses a partial/incomplete JSON string, returning as much valid data as possible.
1491
+ * Falls back to an empty object if parsing fails entirely.
1492
+ */
1493
+ function partialJSONParse(json) {
1494
+ try {
1495
+ const parsed = partial_json.parse(json, PARTIAL_JSON_ALLOW);
1496
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1497
+ return {};
1498
+ } catch (_unused2) {
1499
+ return {};
1500
+ }
1501
+ }
1502
+ /**
1503
+ * Returns an exponential backoff function suitable for Phoenix.js
1504
+ * `reconnectAfterMs` and `rejoinAfterMs` options.
1505
+ *
1506
+ * @param baseMs - Initial delay for the first retry attempt.
1507
+ * @param maxMs - Upper bound — delays are capped at this value.
1508
+ *
1509
+ * Phoenix calls the returned function with a 1-based `tries` count.
1510
+ * The delay doubles on each attempt: baseMs, 2×baseMs, 4×baseMs, …, maxMs.
1511
+ */
1512
+ function phoenixExponentialBackoff(baseMs, maxMs) {
1513
+ return (tries) => Math.min(baseMs * 2 ** (tries - 1), maxMs);
1514
+ }
1515
+ /**
1516
+ * Maps an array of items to a new array, skipping items that throw errors during mapping
1517
+ * @param items The array to map
1518
+ * @param callback The mapping function to apply to each item
1519
+ * @returns A new array containing only the successfully mapped items
1520
+ */
1521
+ function tryMap(items, callback) {
1522
+ return items.reduce((acc, item, index, array) => {
1523
+ try {
1524
+ acc.push(callback(item, index, array));
1525
+ } catch (error) {
1526
+ console.error(error);
1527
+ }
1528
+ return acc;
1529
+ }, []);
1530
+ }
1531
+ /**
1532
+ * Checks if the current environment is macOS
1533
+ * @returns {boolean} True if running on macOS, false otherwise
1534
+ */
1535
+ function isMacOS() {
1536
+ return /Mac|iMac|Macintosh/i.test(navigator.userAgent);
1537
+ }
1538
+ /**
1539
+ * Safely parses a JSON string into a tool arguments object.
1540
+ * Returns the parsed object only if it's a plain object (not an array, null, etc.).
1541
+ * Falls back to an empty object for any non-object JSON value or parse failure.
1542
+ */
1543
+ function safeParseToolArgs(raw) {
1544
+ try {
1545
+ const parsed = JSON.parse(raw);
1546
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
1547
+ console.warn(`[CopilotKit] Tool arguments parsed to non-object (${typeof parsed}), falling back to empty object`);
1548
+ return {};
1549
+ } catch (_unused3) {
1550
+ console.warn("[CopilotKit] Failed to parse tool arguments, falling back to empty object");
1551
+ return {};
1552
+ }
1553
+ }
1554
+
1555
+ //#endregion
1556
+ //#region src/constants/index.ts
1557
+ const COPILOT_CLOUD_API_URL = "https://api.cloud.copilotkit.ai";
1558
+ const COPILOT_CLOUD_VERSION = "v1";
1559
+ const COPILOT_CLOUD_CHAT_URL = `${COPILOT_CLOUD_API_URL}/copilotkit/${COPILOT_CLOUD_VERSION}`;
1560
+ const COPILOT_CLOUD_PUBLIC_API_KEY_HEADER = "X-CopilotCloud-Public-Api-Key";
1561
+ const DEFAULT_AGENT_ID = "default";
1562
+ /**
1563
+ * `RUN_ERROR` code the runtime sends when a run is rejected because the
1564
+ * thread already has one in flight. CopilotKit core reports it as
1565
+ * `agent_thread_locked`.
1566
+ */
1567
+ const THREAD_ALREADY_RUNNING_ERROR_CODE = "THREAD_ALREADY_RUNNING";
1568
+ /** Phoenix channel event name used for all AG-UI events. */
1569
+ const AG_UI_CHANNEL_EVENT = "ag-ui";
1570
+
1571
+ //#endregion
1572
+ //#region src/telemetry/telemetry-disabled.ts
1573
+ /**
1574
+ * Checks if telemetry is disabled via environment variables.
1575
+ * Users can opt out by setting:
1576
+ * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
1577
+ * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
1578
+ *
1579
+ * Lives in its own module so that the browser-facing root entry can
1580
+ * re-export it without pulling in `telemetry-client.ts`, whose
1581
+ * `@segment/analytics-node` import drags Node built-ins into browser
1582
+ * bundler module graphs. See the note in `../index.ts`.
1583
+ */
1584
+ function isTelemetryDisabled() {
1585
+ return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
1586
+ }
1587
+
1588
+ //#endregion
1589
+ //#region src/telemetry/sampling.ts
1590
+ /** The rate a sink that takes every event is "gated" at. */
1591
+ const UNSAMPLED_RATE = 1;
1592
+ /** Identifies which client emitted an event. */
1593
+ const TELEMETRY_EMITTER_V1 = "v1-shared";
1594
+ const TELEMETRY_EMITTER_V2 = "v2-runtime";
1595
+ /**
1596
+ * Which public API surface the developer built against.
1597
+ *
1598
+ * Separate from {@link TelemetryEmitter} on purpose. The emitter names a
1599
+ * client library, and there are six of them across four languages; the
1600
+ * surface answers the question anyone actually asks of this data, which
1601
+ * is how much traffic still arrives through the deprecated v1 API. The
1602
+ * native runtimes (Go, Python, Ruby, .NET) expose v2 only, so they report
1603
+ * `v2` without having a v1 notion of their own.
1604
+ */
1605
+ const TELEMETRY_SURFACE_V1 = "v1";
1606
+ const TELEMETRY_SURFACE_V2 = "v2";
1607
+ /**
1608
+ * Compute the sampling block for one captured event.
1609
+ *
1610
+ * `telemetryId` is the caller's parsed license telemetry_id, or null when
1611
+ * anonymous — it decides the branch, and is deliberately not returned:
1612
+ * only the non-PII shape below travels on the event.
1613
+ *
1614
+ * `sampleRate` is the rate of the wire this copy travels on, so an
1615
+ * unsampled sink passes {@link UNSAMPLED_RATE}. Call it once per wire:
1616
+ * the v1 client sends one capture to two wires gated differently, and a
1617
+ * shared block would misweight one of them.
1618
+ */
1619
+ function computeSamplingMeta({ telemetryId, sampleRate }) {
1620
+ const identified = Boolean(telemetryId);
1621
+ const effectiveSampleRate = identified ? 1 : sampleRate;
1622
+ return {
1623
+ sampleRate: effectiveSampleRate,
1624
+ sampleRateAdjustmentFactor: 1 - effectiveSampleRate,
1625
+ sampleWeight: 1 / effectiveSampleRate,
1626
+ telemetry_identified: identified
1627
+ };
1628
+ }
1629
+
1630
+ //#endregion
1631
+ //#region src/telemetry/model-host.ts
1632
+ /**
1633
+ * Every value `classifyModelHost` can return.
1634
+ *
1635
+ * `other` means a host we observed and did not recognize: a gateway, a proxy,
1636
+ * or a vendor we have no rule for. `unknown` means we never saw a host at all,
1637
+ * which is the case when a caller hands us an already-built LanguageModel.
1638
+ * The two are not interchangeable — one is an unrecognized answer, the other
1639
+ * is a missing one, and they need different follow-up.
1640
+ */
1641
+ const MODEL_HOST_CLASSES = [
1642
+ "openai",
1643
+ "azure",
1644
+ "openrouter",
1645
+ "anthropic",
1646
+ "google",
1647
+ "vertex",
1648
+ "bedrock",
1649
+ "groq",
1650
+ "unify",
1651
+ "minimax",
1652
+ "local",
1653
+ "other",
1654
+ "unknown"
1655
+ ];
1656
+ /**
1657
+ * Host suffixes mapped to their vendor.
1658
+ *
1659
+ * Matched on label boundaries, never as substrings, so
1660
+ * `myresource.openai.azure.com.attacker.test` does not read as Azure.
1661
+ */
1662
+ const HOST_SUFFIXES = [
1663
+ ["openai.azure.com", "azure"],
1664
+ ["services.ai.azure.com", "azure"],
1665
+ ["cognitiveservices.azure.com", "azure"],
1666
+ ["azure-api.net", "azure"],
1667
+ ["api.openai.com", "openai"],
1668
+ ["openrouter.ai", "openrouter"],
1669
+ ["api.anthropic.com", "anthropic"],
1670
+ ["generativelanguage.googleapis.com", "google"],
1671
+ ["aiplatform.googleapis.com", "vertex"],
1672
+ ["api.groq.com", "groq"],
1673
+ ["api.unify.ai", "unify"],
1674
+ ["api.minimax.io", "minimax"],
1675
+ ["api.minimaxi.com", "minimax"]
1676
+ ];
1677
+ /** Suffixes that mean the model runs on the same machine or private network. */
1678
+ const LOCAL_SUFFIXES = [
1679
+ "localhost",
1680
+ "local",
1681
+ "internal",
1682
+ "docker.internal"
1683
+ ];
1684
+ /** Matches `<region>-aiplatform.googleapis.com` and the Bedrock regional hosts. */
1685
+ const REGIONAL_HOST_PATTERNS = [[/^[a-z0-9-]+-aiplatform\.googleapis\.com$/, "vertex"], [/^bedrock[a-z0-9.-]*\.[a-z0-9-]+\.amazonaws\.com$/, "bedrock"]];
1686
+ /** True when `host` equals `suffix` or sits directly beneath it. */
1687
+ function matchesSuffix(host, suffix) {
1688
+ return host === suffix || host.endsWith(`.${suffix}`);
1689
+ }
1690
+ /** True for loopback, unspecified, and RFC 1918 private addresses. */
1691
+ function isPrivateAddress(host) {
1692
+ if (host === "127.0.0.1" || host === "0.0.0.0" || host === "::1") return true;
1693
+ if (host.startsWith("127.")) return true;
1694
+ if (host.startsWith("10.") || host.startsWith("192.168.")) return true;
1695
+ const privateClassB = /^172\.(\d{1,3})\./.exec(host);
1696
+ if (privateClassB) {
1697
+ const secondOctet = Number(privateClassB[1]);
1698
+ return secondOctet >= 16 && secondOctet <= 31;
1699
+ }
1700
+ return false;
1701
+ }
1702
+ /**
1703
+ * Reduce a model endpoint to one of {@link MODEL_HOST_CLASSES}.
1704
+ *
1705
+ * @param baseUrl The endpoint the provider was configured with. Absent when
1706
+ * the provider was left on its own default, which is why `providerDefault`
1707
+ * exists: "no base URL, provider is openai" means api.openai.com.
1708
+ * @param providerDefault What to report when no base URL was supplied. Callers
1709
+ * that genuinely cannot observe a host — a pre-built LanguageModel handed in
1710
+ * by the developer — leave this alone and get `unknown`.
1711
+ */
1712
+ function classifyModelHost(baseUrl, providerDefault = "unknown") {
1713
+ const trimmed = baseUrl === null || baseUrl === void 0 ? void 0 : baseUrl.trim();
1714
+ if (!trimmed) return providerDefault;
1715
+ let host;
1716
+ try {
1717
+ host = new URL(trimmed).hostname.toLowerCase();
1718
+ } catch (_unused) {
1719
+ return "other";
1720
+ }
1721
+ host = host.replace(/^\[|\]$/g, "");
1722
+ if (!host) return "other";
1723
+ if (isPrivateAddress(host)) return "local";
1724
+ for (const suffix of LOCAL_SUFFIXES) if (matchesSuffix(host, suffix)) return "local";
1725
+ for (const [suffix, hostClass] of HOST_SUFFIXES) if (matchesSuffix(host, suffix)) return hostClass;
1726
+ for (const [pattern, hostClass] of REGIONAL_HOST_PATTERNS) if (pattern.test(host)) return hostClass;
1727
+ return "other";
1728
+ }
1729
+
1730
+ //#endregion
1731
+ //#region src/telemetry/lambda-client.ts
1732
+ var _process$env;
1733
+ const TELEMETRY_SINK_URL = typeof process !== "undefined" && ((_process$env = process.env) === null || _process$env === void 0 ? void 0 : _process$env.COPILOTKIT_TELEMETRY_URL) || "https://telemetry.copilotkit.ai/ingest";
1734
+ const FETCH_TIMEOUT_MS = 3e3;
1735
+ const TELEMETRY_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
1736
+ /**
1737
+ * Return the first telemetry identity accepted by the ingest service.
1738
+ *
1739
+ * Empty and whitespace-only values are unconfigured placeholders and must not
1740
+ * suppress a later identity source. Leading and trailing HTTP spaces and tabs
1741
+ * are removed before validation. The ingest service accepts 1 to 128 ASCII
1742
+ * letters, digits, underscores, and hyphens.
1743
+ *
1744
+ * @internal
1745
+ */
1746
+ function firstNonBlankTelemetryId(...candidates) {
1747
+ for (const candidate of candidates) {
1748
+ if (candidate === void 0) continue;
1749
+ const normalized = candidate.replace(/^[\t ]+|[\t ]+$/g, "");
1750
+ if (TELEMETRY_ID_PATTERN.test(normalized)) return normalized;
1751
+ }
1752
+ }
1753
+ const STRIPPED_KEYS = new Set(["cloud.public_api_key", "cloud.publicApiKey"]);
1754
+ function stripCloudKeys(obj) {
1755
+ if (!obj) return {};
1756
+ const out = {};
1757
+ for (const [k, v] of Object.entries(obj)) if (!STRIPPED_KEYS.has(k)) out[k] = v;
1758
+ return out;
1759
+ }
1760
+ function parseTelemetryIdFromLicense(token) {
1761
+ if (!token) return null;
1762
+ const parts = token.split(".");
1763
+ if (parts.length !== 3) return null;
1764
+ try {
1765
+ var _firstNonBlankTelemet;
1766
+ const payload = parts[1];
1767
+ if (!/^[A-Za-z0-9_-]+$/.test(payload) || payload.length % 4 === 1) return null;
1768
+ let b64 = payload.replace(/-/g, "+").replace(/_/g, "/");
1769
+ const padding = (4 - b64.length % 4) % 4;
1770
+ b64 += "=".repeat(padding);
1771
+ const json = typeof Buffer !== "undefined" ? Buffer.from(b64, "base64").toString("utf8") : new TextDecoder().decode(Uint8Array.from(atob(b64), (character) => character.charCodeAt(0)));
1772
+ const decoded = JSON.parse(json);
1773
+ return (_firstNonBlankTelemet = firstNonBlankTelemetryId(typeof decoded.telemetry_id === "string" ? decoded.telemetry_id : void 0)) !== null && _firstNonBlankTelemet !== void 0 ? _firstNonBlankTelemet : null;
1774
+ } catch (_unused) {
1775
+ return null;
1776
+ }
1777
+ }
1778
+ function parseAndWarnTelemetryId(licenseToken) {
1779
+ const telemetryId = parseTelemetryIdFromLicense(licenseToken);
1780
+ if (!telemetryId) console.warn("[CopilotKit] License token did not yield a telemetry_id; telemetry events will be sent anonymously.");
1781
+ return telemetryId;
1782
+ }
1783
+ async function send(opts) {
1784
+ try {
1785
+ var _firstNonBlankTelemet2, _opts$packageVersion;
1786
+ const body = JSON.stringify({
1787
+ event: opts.event,
1788
+ properties: stripCloudKeys(opts.properties),
1789
+ global_properties: stripCloudKeys(opts.globalProperties),
1790
+ package: {
1791
+ name: opts.packageName,
1792
+ version: opts.packageVersion
1793
+ },
1794
+ ts: Math.floor(Date.now() / 1e3)
1795
+ });
1796
+ const telemetryId = (_firstNonBlankTelemet2 = firstNonBlankTelemetryId(opts.telemetryId)) !== null && _firstNonBlankTelemet2 !== void 0 ? _firstNonBlankTelemet2 : parseTelemetryIdFromLicense(opts.licenseToken);
1797
+ const headers = {
1798
+ "Content-Type": "application/json",
1799
+ "User-Agent": opts.packageName ? `CopilotKit-Runtime/${(_opts$packageVersion = opts.packageVersion) !== null && _opts$packageVersion !== void 0 ? _opts$packageVersion : "unknown"} (${opts.packageName})` : "CopilotKit-Runtime"
1800
+ };
1801
+ if (telemetryId) headers["X-CopilotKit-Telemetry-Id"] = telemetryId;
1802
+ const controller = new AbortController();
1803
+ const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
1804
+ try {
1805
+ await fetch(TELEMETRY_SINK_URL, {
1806
+ method: "POST",
1807
+ headers,
1808
+ body,
1809
+ signal: controller.signal
1810
+ });
1811
+ } finally {
1812
+ clearTimeout(timeoutId);
1813
+ }
1814
+ } catch (_unused2) {}
1815
+ }
1816
+ const lambdaClient = { send };
1817
+
1818
+ //#endregion
1819
+ //#region src/debug.ts
1820
+ /** The all-off config used when debug is falsy. */
1821
+ const DEBUG_OFF = {
1822
+ enabled: false,
1823
+ events: false,
1824
+ lifecycle: false,
1825
+ verbose: false
1826
+ };
1827
+ /**
1828
+ * Normalizes a DebugConfig value into a ResolvedDebugConfig.
1829
+ *
1830
+ * - `false` / `undefined` → all off
1831
+ * - `true` → events + lifecycle on, verbose off (no PII in logs)
1832
+ * - object → merges with defaults (events: true, lifecycle: true, verbose: false)
1833
+ */
1834
+ function resolveDebugConfig(debug) {
1835
+ var _debug$events, _debug$lifecycle, _debug$verbose;
1836
+ if (!debug) return DEBUG_OFF;
1837
+ if (debug === true) return {
1838
+ enabled: true,
1839
+ events: true,
1840
+ lifecycle: true,
1841
+ verbose: false
1842
+ };
1843
+ const events = (_debug$events = debug.events) !== null && _debug$events !== void 0 ? _debug$events : true;
1844
+ const lifecycle = (_debug$lifecycle = debug.lifecycle) !== null && _debug$lifecycle !== void 0 ? _debug$lifecycle : true;
1845
+ const enabled = events || lifecycle;
1846
+ return {
1847
+ enabled,
1848
+ events,
1849
+ lifecycle,
1850
+ verbose: enabled && ((_debug$verbose = debug.verbose) !== null && _debug$verbose !== void 0 ? _debug$verbose : false)
1851
+ };
1852
+ }
1853
+
1854
+ //#endregion
1855
+ //#region src/standard-schema.ts
1856
+ /**
1857
+ * Check whether a schema implements the Standard JSON Schema V1 protocol.
1858
+ */
1859
+ function hasStandardJsonSchema(schema) {
1860
+ const props = schema["~standard"];
1861
+ return props != null && typeof props === "object" && "jsonSchema" in props && props.jsonSchema != null && typeof props.jsonSchema === "object" && "input" in props.jsonSchema && typeof props.jsonSchema.input === "function";
1862
+ }
1863
+ /**
1864
+ * Convert any StandardSchemaV1-compatible schema to a JSON Schema object.
1865
+ *
1866
+ * Strategy:
1867
+ * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
1868
+ * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
1869
+ * 2. If the schema exposes a `toJSONSchema()` method (Zod v4), call it directly.
1870
+ * 3. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
1871
+ * injected `zodToJsonSchema()` function.
1872
+ * 4. Otherwise throw a descriptive error.
1873
+ */
1874
+ function schemaToJsonSchema(schema, options) {
1875
+ if (hasStandardJsonSchema(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
1876
+ if (typeof schema.toJSONSchema === "function") return schema.toJSONSchema();
1877
+ const vendor = schema["~standard"].vendor;
1878
+ if (vendor === "zod" && (options === null || options === void 0 ? void 0 : options.zodToJsonSchema)) return options.zodToJsonSchema(schema, { $refStrategy: "none" });
1879
+ throw new Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${vendor}") does not implement Standard JSON Schema V1 and no zodToJsonSchema fallback is available. Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) or pass a zodToJsonSchema function in options.`);
1880
+ }
1881
+
1882
+ //#endregion
1883
+ //#region src/attachments/content.ts
1884
+ /** Build the AG-UI content part used when sending a ready attachment. */
1885
+ function createAttachmentContent(attachment) {
1886
+ return {
1887
+ type: attachment.type,
1888
+ source: attachment.source,
1889
+ metadata: {
1890
+ ...attachment.filename ? { filename: attachment.filename } : {},
1891
+ ...attachment.metadata
1892
+ }
1893
+ };
1894
+ }
1895
+
1896
+ //#endregion
1897
+ //#region src/attachments/utils.ts
1898
+ const DEFAULT_MAX_SIZE = 20 * 1024 * 1024;
1899
+ /**
1900
+ * Derive the attachment modality from a MIME type string.
1901
+ */
1902
+ function getModalityFromMimeType(mimeType) {
1903
+ if (mimeType.startsWith("image/")) return "image";
1904
+ if (mimeType.startsWith("audio/")) return "audio";
1905
+ if (mimeType.startsWith("video/")) return "video";
1906
+ return "document";
1907
+ }
1908
+ /**
1909
+ * Format a byte count as a human-readable file size string.
1910
+ */
1911
+ function formatFileSize(bytes) {
1912
+ if (bytes < 1024) return `${bytes} B`;
1913
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
1914
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
1915
+ }
1916
+ /**
1917
+ * Check if a file exceeds the maximum allowed size.
1918
+ */
1919
+ function exceedsMaxSize(file, maxSize = DEFAULT_MAX_SIZE) {
1920
+ return file.size > maxSize;
1921
+ }
1922
+ /**
1923
+ * Read a File as a base64 string (without the data URL prefix).
1924
+ */
1925
+ function readFileAsBase64(file) {
1926
+ return new Promise((resolve, reject) => {
1927
+ const reader = new FileReader();
1928
+ reader.onload = (e) => {
1929
+ var _e$target;
1930
+ const result = (_e$target = e.target) === null || _e$target === void 0 ? void 0 : _e$target.result;
1931
+ const base64 = result === null || result === void 0 ? void 0 : result.split(",")[1];
1932
+ if (base64) resolve(base64);
1933
+ else reject(/* @__PURE__ */ new Error("Failed to read file as base64"));
1934
+ };
1935
+ reader.onerror = reject;
1936
+ reader.readAsDataURL(file);
1937
+ });
1938
+ }
1939
+ /**
1940
+ * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).
1941
+ * Returns undefined if thumbnail generation fails or if called outside a browser environment.
1942
+ */
1943
+ function generateVideoThumbnail(file) {
1944
+ if (typeof document === "undefined") return Promise.resolve(void 0);
1945
+ return new Promise((resolve) => {
1946
+ let resolved = false;
1947
+ const video = document.createElement("video");
1948
+ const canvas = document.createElement("canvas");
1949
+ const url = URL.createObjectURL(file);
1950
+ const cleanup = (result) => {
1951
+ if (resolved) return;
1952
+ resolved = true;
1953
+ URL.revokeObjectURL(url);
1954
+ resolve(result);
1955
+ };
1956
+ const timeout = setTimeout(() => {
1957
+ console.warn(`[CopilotKit] generateVideoThumbnail: timed out for file "${file.name}"`);
1958
+ cleanup(void 0);
1959
+ }, 1e4);
1960
+ video.preload = "metadata";
1961
+ video.muted = true;
1962
+ video.playsInline = true;
1963
+ video.onloadeddata = () => {
1964
+ video.currentTime = .1;
1965
+ };
1966
+ video.onseeked = () => {
1967
+ clearTimeout(timeout);
1968
+ canvas.width = video.videoWidth;
1969
+ canvas.height = video.videoHeight;
1970
+ const ctx = canvas.getContext("2d");
1971
+ if (ctx) {
1972
+ ctx.drawImage(video, 0, 0);
1973
+ cleanup(canvas.toDataURL("image/jpeg", .7));
1974
+ } else {
1975
+ console.warn("[CopilotKit] generateVideoThumbnail: could not get 2d canvas context");
1976
+ cleanup(void 0);
1977
+ }
1978
+ };
1979
+ video.onerror = () => {
1980
+ clearTimeout(timeout);
1981
+ console.warn(`[CopilotKit] generateVideoThumbnail: video element error for file "${file.name}"`);
1982
+ cleanup(void 0);
1983
+ };
1984
+ video.src = url;
1985
+ });
1986
+ }
1987
+ /**
1988
+ * Check if a file's MIME type matches an accept filter string.
1989
+ * Handles file extensions (e.g. ".pdf"), MIME wildcards ("image/*"), and comma-separated lists.
1990
+ */
1991
+ function matchesAcceptFilter(file, accept) {
1992
+ if (!accept || accept === "*/*") return true;
1993
+ return accept.split(",").map((f) => f.trim()).some((filter) => {
1994
+ if (filter.startsWith(".")) {
1995
+ var _file$name;
1996
+ return ((_file$name = file.name) !== null && _file$name !== void 0 ? _file$name : "").toLowerCase().endsWith(filter.toLowerCase());
1997
+ }
1998
+ if (filter.endsWith("/*")) {
1999
+ const prefix = filter.slice(0, -2);
2000
+ return file.type.startsWith(prefix + "/");
2001
+ }
2002
+ return file.type === filter;
2003
+ });
2004
+ }
2005
+ /**
2006
+ * Convert an InputContentSource to a usable URL string.
2007
+ * For data sources, returns a base64 data URL; for URL sources, returns the URL directly.
2008
+ * A provider file handle (AG-UI 1.0 `file` source) has no address a browser
2009
+ * can load, so it returns an empty string and the caller shows no preview.
2010
+ */
2011
+ function getSourceUrl(source) {
2012
+ if (source.type === "url") return source.value;
2013
+ if (source.type === "file") return "";
2014
+ return `data:${source.mimeType};base64,${source.value}`;
2015
+ }
2016
+ /**
2017
+ * Return a short human-readable label for a document MIME type (e.g. "PDF", "DOC").
2018
+ */
2019
+ function getDocumentIcon(mimeType) {
2020
+ if (mimeType.includes("pdf")) return "PDF";
2021
+ if (mimeType.includes("sheet") || mimeType.includes("excel")) return "XLS";
2022
+ if (mimeType.includes("presentation") || mimeType.includes("powerpoint")) return "PPT";
2023
+ if (mimeType.includes("word") || mimeType.includes("document")) return "DOC";
2024
+ if (mimeType.includes("text/")) return "TXT";
2025
+ return "FILE";
2026
+ }
2027
+
2028
+ //#endregion
2029
+ //#region src/logger.ts
2030
+ const logger = console;
2031
+
2032
+ //#endregion
2033
+ //#region src/finalize-events.ts
2034
+ const defaultStopMessage = "Run stopped by user";
2035
+ const defaultAbruptEndMessage = "Run ended without emitting a terminal event";
2036
+ /**
2037
+ * Incremental finalizer for a streamed AG-UI run. Feed every event to
2038
+ * `observe`; when the stream ends without a terminal event, `finalize` returns
2039
+ * the closers for reasoning, text messages and tool calls still open plus a
2040
+ * terminal event. AG-UI 1.0 fails a run that ends with reasoning still open,
2041
+ * so reasoning is closed too. It also fails a RUN_FINISHED while a subagent
2042
+ * is still open, so a stop closes open subagents as well; a RUN_ERROR
2043
+ * abandons them, which the protocol allows. Closed lifecycles are forgotten at once and payloads are never kept,
2044
+ * so a caller does not have to retain the event array for this purpose.
2045
+ */
2046
+ function createRunEventFinalizer() {
2047
+ const openMessageIds = /* @__PURE__ */ new Set();
2048
+ const openReasoningMessageIds = /* @__PURE__ */ new Set();
2049
+ const openReasoningSpanIds = /* @__PURE__ */ new Set();
2050
+ const openToolCalls = /* @__PURE__ */ new Map();
2051
+ const openSubagentRunIds = /* @__PURE__ */ new Set();
2052
+ let runIdentity = {};
2053
+ let terminalEventObserved = false;
2054
+ const clearOpen = () => {
2055
+ openMessageIds.clear();
2056
+ openReasoningMessageIds.clear();
2057
+ openReasoningSpanIds.clear();
2058
+ openToolCalls.clear();
2059
+ openSubagentRunIds.clear();
2060
+ };
2061
+ const observe = (event) => {
2062
+ if (terminalEventObserved) return;
2063
+ switch (event.type) {
2064
+ case _ag_ui_client.EventType.RUN_STARTED: {
2065
+ const { threadId, runId } = event;
2066
+ runIdentity = {
2067
+ threadId,
2068
+ runId
2069
+ };
2070
+ break;
2071
+ }
2072
+ case _ag_ui_client.EventType.REASONING_START:
2073
+ case _ag_ui_client.EventType.REASONING_END:
2074
+ case _ag_ui_client.EventType.REASONING_MESSAGE_START:
2075
+ case _ag_ui_client.EventType.REASONING_MESSAGE_END: {
2076
+ const messageId = event.messageId;
2077
+ if (typeof messageId !== "string") break;
2078
+ const open = event.type === _ag_ui_client.EventType.REASONING_START || event.type === _ag_ui_client.EventType.REASONING_END ? openReasoningSpanIds : openReasoningMessageIds;
2079
+ if (event.type === _ag_ui_client.EventType.REASONING_START || event.type === _ag_ui_client.EventType.REASONING_MESSAGE_START) open.add(messageId);
2080
+ else open.delete(messageId);
2081
+ break;
2082
+ }
2083
+ case _ag_ui_client.EventType.TEXT_MESSAGE_START: {
2084
+ const messageId = event.messageId;
2085
+ if (messageId) openMessageIds.add(messageId);
2086
+ break;
2087
+ }
2088
+ case _ag_ui_client.EventType.TEXT_MESSAGE_END: {
2089
+ const messageId = event.messageId;
2090
+ if (typeof messageId === "string") openMessageIds.delete(messageId);
2091
+ break;
2092
+ }
2093
+ case _ag_ui_client.EventType.TOOL_CALL_START: {
2094
+ const toolCallId = event.toolCallId;
2095
+ if (toolCallId && !openToolCalls.has(toolCallId)) openToolCalls.set(toolCallId, {
2096
+ hasEnd: false,
2097
+ hasResult: false
2098
+ });
2099
+ break;
2100
+ }
2101
+ case _ag_ui_client.EventType.TOOL_CALL_END:
2102
+ case _ag_ui_client.EventType.TOOL_CALL_RESULT: {
2103
+ const toolCallId = event.toolCallId;
2104
+ if (!toolCallId) break;
2105
+ const info = openToolCalls.get(toolCallId);
2106
+ if (!info) break;
2107
+ if (event.type === _ag_ui_client.EventType.TOOL_CALL_END) info.hasEnd = true;
2108
+ else info.hasResult = true;
2109
+ if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);
2110
+ break;
2111
+ }
2112
+ case _ag_ui_client.EventType.SUBAGENT_STARTED:
2113
+ case _ag_ui_client.EventType.SUBAGENT_FINISHED:
2114
+ case _ag_ui_client.EventType.SUBAGENT_ERROR: {
2115
+ const subagentRunId = event.subagentRunId;
2116
+ if (!subagentRunId) break;
2117
+ if (event.type === _ag_ui_client.EventType.SUBAGENT_STARTED) openSubagentRunIds.add(subagentRunId);
2118
+ else openSubagentRunIds.delete(subagentRunId);
2119
+ break;
2120
+ }
2121
+ case _ag_ui_client.EventType.RUN_FINISHED:
2122
+ case _ag_ui_client.EventType.RUN_ERROR:
2123
+ terminalEventObserved = true;
2124
+ clearOpen();
2125
+ break;
2126
+ default: break;
2127
+ }
2128
+ };
2129
+ const finalize = (options = {}) => {
2130
+ if (terminalEventObserved) return [];
2131
+ const { stopRequested = false, interruptionMessage } = options;
2132
+ const resolvedStopMessage = interruptionMessage !== null && interruptionMessage !== void 0 ? interruptionMessage : defaultStopMessage;
2133
+ const resolvedAbruptMessage = interruptionMessage && interruptionMessage !== defaultStopMessage ? interruptionMessage : defaultAbruptEndMessage;
2134
+ const appended = [];
2135
+ for (const messageId of openReasoningMessageIds) appended.push({
2136
+ type: _ag_ui_client.EventType.REASONING_MESSAGE_END,
2137
+ messageId
2138
+ });
2139
+ for (const messageId of openReasoningSpanIds) appended.push({
2140
+ type: _ag_ui_client.EventType.REASONING_END,
2141
+ messageId
2142
+ });
2143
+ for (const messageId of openMessageIds) appended.push({
2144
+ type: _ag_ui_client.EventType.TEXT_MESSAGE_END,
2145
+ messageId
2146
+ });
2147
+ for (const [toolCallId, info] of openToolCalls) {
2148
+ if (!info.hasEnd) appended.push({
2149
+ type: _ag_ui_client.EventType.TOOL_CALL_END,
2150
+ toolCallId
2151
+ });
2152
+ if (!info.hasResult) appended.push({
2153
+ type: _ag_ui_client.EventType.TOOL_CALL_RESULT,
2154
+ toolCallId,
2155
+ messageId: `${toolCallId}-result`,
2156
+ role: "tool",
2157
+ content: JSON.stringify(stopRequested ? {
2158
+ status: "stopped",
2159
+ reason: "stop_requested",
2160
+ message: resolvedStopMessage
2161
+ } : {
2162
+ status: "error",
2163
+ reason: "missing_terminal_event",
2164
+ message: resolvedAbruptMessage
2165
+ })
2166
+ });
2167
+ }
2168
+ if (stopRequested) {
2169
+ const openIds = [...openSubagentRunIds];
2170
+ for (let index = openIds.length - 1; index >= 0; index -= 1) appended.push({
2171
+ type: _ag_ui_client.EventType.SUBAGENT_ERROR,
2172
+ subagentRunId: openIds[index],
2173
+ message: resolvedStopMessage,
2174
+ code: "CANCELLED"
2175
+ });
2176
+ appended.push({
2177
+ type: _ag_ui_client.EventType.RUN_FINISHED,
2178
+ ...runIdentity.threadId !== void 0 ? { threadId: runIdentity.threadId } : {},
2179
+ ...runIdentity.runId !== void 0 ? { runId: runIdentity.runId } : {},
2180
+ ...options.protocolVersion !== void 0 ? { outcome: { type: "cancelled" } } : {}
2181
+ });
2182
+ } else {
2183
+ const errorEvent = {
2184
+ type: _ag_ui_client.EventType.RUN_ERROR,
2185
+ message: resolvedAbruptMessage,
2186
+ code: "INCOMPLETE_STREAM"
2187
+ };
2188
+ appended.push(errorEvent);
2189
+ }
2190
+ terminalEventObserved = true;
2191
+ clearOpen();
2192
+ return appended;
2193
+ };
2194
+ return {
2195
+ observe,
2196
+ finalize
2197
+ };
2198
+ }
2199
+ /**
2200
+ * Array form of {@link createRunEventFinalizer} for callers that already keep
2201
+ * the run's events (runners persist them). Appends the closers to `events` in
2202
+ * place and returns them.
2203
+ */
2204
+ function finalizeRunEvents(events, options = {}) {
2205
+ const finalizer = createRunEventFinalizer();
2206
+ for (const event of events) finalizer.observe(event);
2207
+ const appended = finalizer.finalize(options);
2208
+ events.push(...appended);
2209
+ return appended;
2210
+ }
2211
+
2212
+ //#endregion
2213
+ //#region src/intelligence-routing-fields.ts
2214
+ /**
2215
+ * The only AG-UI 1.0 events whose schema declares `threadId` and `runId`.
2216
+ * Plain literals, not `EventType`: a value import of `@ag-ui/client` here put
2217
+ * the client and its zod validators into the initial chunk of every app that
2218
+ * imports `@copilotkit/shared`.
2219
+ */
2220
+ const RUN_IDENTITY_EVENTS = new Set(["RUN_STARTED", "RUN_FINISHED"]);
2221
+ /**
2222
+ * Removes the routing fields that the Intelligence runner stamps on every
2223
+ * event it sends to the gateway (`thread_id`, `run_id`, and `threadId` /
2224
+ * `runId` on events that do not declare them).
2225
+ *
2226
+ * The gateway relays these payloads unchanged. AG-UI 1.0 strips unknown
2227
+ * fields before subscribers see them and warns once per field, per event,
2228
+ * so a streamed answer would log hundreds of warnings. Call this where a
2229
+ * gateway payload enters an AG-UI pipeline. The gateway still receives the
2230
+ * fields, because the runner adds them after this point.
2231
+ */
2232
+ function stripIntelligenceRoutingFields(event) {
2233
+ const record = event;
2234
+ const keepRunIdentity = RUN_IDENTITY_EVENTS.has(record.type);
2235
+ if (!("thread_id" in record) && !("run_id" in record) && (keepRunIdentity || !("threadId" in record) && !("runId" in record))) return event;
2236
+ const { thread_id: _t, run_id: _r, ...rest } = record;
2237
+ if (!keepRunIdentity) {
2238
+ delete rest.threadId;
2239
+ delete rest.runId;
2240
+ }
2241
+ return rest;
2242
+ }
2243
+
2244
+ //#endregion
2245
+ //#region src/transcription-errors.ts
2246
+ /**
2247
+ * Error codes for transcription HTTP responses.
2248
+ * Uses snake_case to align with existing CopilotKitCoreErrorCode pattern.
2249
+ * These codes are returned by the runtime and parsed by the client.
2250
+ */
2251
+ let TranscriptionErrorCode = /* @__PURE__ */ function(TranscriptionErrorCode) {
2252
+ /** Transcription service not configured in runtime */
2253
+ TranscriptionErrorCode["SERVICE_NOT_CONFIGURED"] = "service_not_configured";
2254
+ /** Audio format not supported */
2255
+ TranscriptionErrorCode["INVALID_AUDIO_FORMAT"] = "invalid_audio_format";
2256
+ /** Audio file is too long */
2257
+ TranscriptionErrorCode["AUDIO_TOO_LONG"] = "audio_too_long";
2258
+ /** Audio file is empty or too short */
2259
+ TranscriptionErrorCode["AUDIO_TOO_SHORT"] = "audio_too_short";
2260
+ /** Rate limited by transcription provider */
2261
+ TranscriptionErrorCode["RATE_LIMITED"] = "rate_limited";
2262
+ /** Authentication failed with transcription provider */
2263
+ TranscriptionErrorCode["AUTH_FAILED"] = "auth_failed";
2264
+ /** Transcription provider returned an error */
2265
+ TranscriptionErrorCode["PROVIDER_ERROR"] = "provider_error";
2266
+ /** Network error during transcription */
2267
+ TranscriptionErrorCode["NETWORK_ERROR"] = "network_error";
2268
+ /** Invalid request format */
2269
+ TranscriptionErrorCode["INVALID_REQUEST"] = "invalid_request";
2270
+ return TranscriptionErrorCode;
2271
+ }({});
2272
+ /**
2273
+ * Helper functions to create transcription error responses.
2274
+ * Used by the runtime to return consistent error responses.
2275
+ */
2276
+ const TranscriptionErrors = {
2277
+ serviceNotConfigured: () => ({
2278
+ error: TranscriptionErrorCode.SERVICE_NOT_CONFIGURED,
2279
+ message: "Transcription service is not configured",
2280
+ retryable: false
2281
+ }),
2282
+ invalidAudioFormat: (format, supported) => ({
2283
+ error: TranscriptionErrorCode.INVALID_AUDIO_FORMAT,
2284
+ message: `Unsupported audio format: ${format}. Supported: ${supported.join(", ")}`,
2285
+ retryable: false
2286
+ }),
2287
+ invalidRequest: (details) => ({
2288
+ error: TranscriptionErrorCode.INVALID_REQUEST,
2289
+ message: details,
2290
+ retryable: false
2291
+ }),
2292
+ rateLimited: () => ({
2293
+ error: TranscriptionErrorCode.RATE_LIMITED,
2294
+ message: "Rate limited. Please try again later.",
2295
+ retryable: true
2296
+ }),
2297
+ authFailed: () => ({
2298
+ error: TranscriptionErrorCode.AUTH_FAILED,
2299
+ message: "Authentication failed with transcription provider",
2300
+ retryable: false
2301
+ }),
2302
+ providerError: (message) => ({
2303
+ error: TranscriptionErrorCode.PROVIDER_ERROR,
2304
+ message,
2305
+ retryable: true
2306
+ }),
2307
+ networkError: (message = "Network error during transcription") => ({
2308
+ error: TranscriptionErrorCode.NETWORK_ERROR,
2309
+ message,
2310
+ retryable: true
2311
+ }),
2312
+ audioTooLong: () => ({
2313
+ error: TranscriptionErrorCode.AUDIO_TOO_LONG,
2314
+ message: "Audio file is too long",
2315
+ retryable: false
2316
+ }),
2317
+ audioTooShort: () => ({
2318
+ error: TranscriptionErrorCode.AUDIO_TOO_SHORT,
2319
+ message: "Audio is too short to transcribe",
2320
+ retryable: false
2321
+ })
2322
+ };
2323
+
2324
+ //#endregion
2325
+ //#region package.json
2326
+ var version = "2.0.0-rc.1";
2327
+
2328
+ //#endregion
2329
+ //#region src/generative-ui/basic-functions.ts
2330
+ /**
2331
+ * The callers of an app function that names none: the renderer only, as
2332
+ * in A2UI 1.0. The agent calls a function with `callRendererFunction` only
2333
+ * when its declaration allows it (`"rendererOrAgent"` or `"agentOnly"`).
2334
+ * The manifests and the exported catalog write the value out.
2335
+ */
2336
+ const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS = "rendererOnly";
2337
+ /**
2338
+ * Who may call a function, from its permissions. A function that needs a
2339
+ * user gesture is for the renderer only, whatever `allowedCallers` says.
2340
+ *
2341
+ * @example
2342
+ * ```ts
2343
+ * functionCallers({}); // { renderer: true, agent: true }
2344
+ * functionCallers({ allowedCallers: "rendererOnly" }); // { renderer: true, agent: false }
2345
+ * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }
2346
+ * ```
2347
+ */
2348
+ function functionCallers(fn) {
2349
+ var _fn$allowedCallers;
2350
+ if (fn.requiresUserActivation) return {
2351
+ renderer: true,
2352
+ agent: false
2353
+ };
2354
+ const callers = (_fn$allowedCallers = fn.allowedCallers) !== null && _fn$allowedCallers !== void 0 ? _fn$allowedCallers : GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;
2355
+ return {
2356
+ renderer: callers !== "agentOnly",
2357
+ agent: callers !== "rendererOnly"
2358
+ };
2359
+ }
2360
+ /** Marks a table of built-in functions as callable by the renderer only. */
2361
+ function rendererOnly(functions) {
2362
+ return Object.fromEntries(Object.entries(functions).map(([name, info]) => [name, {
2363
+ ...info,
2364
+ allowedCallers: "rendererOnly"
2365
+ }]));
2366
+ }
2367
+ /**
2368
+ * The basic functions by name. A `{"@call"}` in a prop, in an event
2369
+ * binding, or in a `callRendererFunction` may name any of them without a
2370
+ * declaration in `createGenerativeUI({ functions })`.
2371
+ */
2372
+ const A2UI_BASIC_FUNCTIONS = rendererOnly({
2373
+ required: {
2374
+ description: "Valid when the value is not empty",
2375
+ parameters: "{ value: unknown }",
2376
+ returnType: "validationResult"
2377
+ },
2378
+ regex: {
2379
+ description: "Valid when the value matches the pattern",
2380
+ parameters: "{ value: string; pattern: string }",
2381
+ returnType: "validationResult"
2382
+ },
2383
+ length: {
2384
+ description: "Valid when the length of the value is within min and max",
2385
+ parameters: "{ value: string; min?: number; max?: number }",
2386
+ returnType: "validationResult"
2387
+ },
2388
+ numeric: {
2389
+ description: "Valid when the value is a number within min and max",
2390
+ parameters: "{ value: number; min?: number; max?: number }",
2391
+ returnType: "validationResult"
2392
+ },
2393
+ email: {
2394
+ description: "Valid when the value is an email address",
2395
+ parameters: "{ value: string }",
2396
+ returnType: "validationResult"
2397
+ },
2398
+ formatString: {
2399
+ description: "Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\${ is a literal",
2400
+ parameters: "{ value: string }",
2401
+ returnType: "string"
2402
+ },
2403
+ formatNumber: {
2404
+ description: "The number in the locale of the user",
2405
+ parameters: "{ value: number; decimals?: number; grouping?: boolean }",
2406
+ returnType: "string"
2407
+ },
2408
+ formatCurrency: {
2409
+ description: "The amount as money, with an ISO 4217 currency code",
2410
+ parameters: "{ value: number; currency: string; decimals?: number; grouping?: boolean }",
2411
+ returnType: "string"
2412
+ },
2413
+ formatDate: {
2414
+ description: "A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"",
2415
+ parameters: "{ value: string | number; format: string }",
2416
+ returnType: "string"
2417
+ },
2418
+ pluralize: {
2419
+ description: "The string of the plural category of the value",
2420
+ parameters: "{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }",
2421
+ returnType: "string"
2422
+ },
2423
+ openUrl: {
2424
+ description: "Opens an http(s) URL in a new tab. Only from an event",
2425
+ parameters: "{ url: string }",
2426
+ returnType: "void",
2427
+ requiresUserActivation: true
2428
+ },
2429
+ and: {
2430
+ description: "True when every value is true",
2431
+ parameters: "{ values: boolean[] }",
2432
+ returnType: "boolean"
2433
+ },
2434
+ or: {
2435
+ description: "True when any value is true",
2436
+ parameters: "{ values: boolean[] }",
2437
+ returnType: "boolean"
2438
+ },
2439
+ not: {
2440
+ description: "The negated value",
2441
+ parameters: "{ value: boolean }",
2442
+ returnType: "boolean"
2443
+ }
2444
+ });
2445
+ /**
2446
+ * The value functions that CopilotKit adds to the basic catalog, because
2447
+ * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named
2448
+ * args, and `series` builds a computed list. A catalog may declare its own
2449
+ * functions in A2UI, so these are regular catalog functions to the model;
2450
+ * a renderer without them rejects the call instead of misrendering.
2451
+ */
2452
+ const COPILOTKIT_FUNCTIONS = rendererOnly({
2453
+ calc: {
2454
+ description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name",
2455
+ parameters: "{ expression: string; [name: string]: number | string | boolean }",
2456
+ returnType: "any",
2457
+ extension: true
2458
+ },
2459
+ series: {
2460
+ description: "A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.",
2461
+ parameters: "{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }",
2462
+ returnType: "array",
2463
+ extension: true
2464
+ }
2465
+ });
2466
+ /** Every function a `{"@call"}` may name without a declaration: basic and CopilotKit. */
2467
+ const GENERATIVE_UI_FUNCTIONS = {
2468
+ ...A2UI_BASIC_FUNCTIONS,
2469
+ ...COPILOTKIT_FUNCTIONS
2470
+ };
2471
+ /** The name of the system function that gives the index of a template item. */
2472
+ const A2UI_INDEX_FUNCTION = "@index";
2473
+ /** True for a built-in function name: basic, CopilotKit, or `@index`. */
2474
+ function isA2UIBasicFunction(name) {
2475
+ return name === A2UI_INDEX_FUNCTION || Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name);
2476
+ }
2477
+ /**
2478
+ * True for a built-in function that a prop or a check may call: every one
2479
+ * except the functions that need a user gesture.
2480
+ */
2481
+ function isA2UIValueFunction(name) {
2482
+ if (name === A2UI_INDEX_FUNCTION) return true;
2483
+ const info = Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
2484
+ return info !== void 0 && !info.requiresUserActivation;
2485
+ }
2486
+ /** `{ "@call": "<name>", "args"?: {...} }`: a function call value. */
2487
+ function isCallBinding(value) {
2488
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value["@call"] === "string";
2489
+ }
2490
+ function isValidationResult(value) {
2491
+ return typeof value === "object" && value !== null && !Array.isArray(value) && typeof value.valid === "boolean";
2492
+ }
2493
+
2494
+ //#endregion
2495
+ //#region src/generative-ui/is-record.ts
2496
+ /** True for a plain object: not null, not an array. Internal, not exported. */
2497
+ function isRecord(value) {
2498
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2499
+ }
2500
+
2501
+ //#endregion
2502
+ //#region src/generative-ui/child-refs.ts
2503
+ /**
2504
+ * How A2UI 1.0 marks a prop that holds a component reference: the JSON
2505
+ * Schema of the prop is a `$ref` to one of these two common types.
2506
+ * Validators and renderers find the children of a component by these refs,
2507
+ * at any depth of the props schema.
2508
+ */
2509
+ const A2UI_COMPONENT_ID_REF = "common_types.json#/$defs/ComponentId";
2510
+ const A2UI_CHILD_LIST_REF = "common_types.json#/$defs/ChildList";
2511
+ /**
2512
+ * The start of the `description` that marks a schema as a component
2513
+ * reference before it is turned into JSON Schema. `child()` and
2514
+ * `childList()` set it; a schema from another library can set a description
2515
+ * that starts with the same mark to get the same effect. What follows the
2516
+ * mark (after a space) stays as the description of the reference.
2517
+ */
2518
+ const A2UI_COMPONENT_ID_MARK = "@a2ui/ComponentId";
2519
+ const A2UI_CHILD_LIST_MARK = "@a2ui/ChildList";
2520
+ /** The ref kind of a JSON Schema node, or `undefined` for a plain value. */
2521
+ function childRefKind(schema) {
2522
+ const ref = schema.$ref;
2523
+ if (ref === A2UI_COMPONENT_ID_REF) return "single";
2524
+ if (ref === A2UI_CHILD_LIST_REF) return "multiple";
2525
+ }
2526
+ /**
2527
+ * Turns the reference marks of a JSON Schema into A2UI `$ref`s, in place of
2528
+ * the marked node. The mark is the `description` set by `child()` and
2529
+ * `childList()`; after this, the node is `{ "$ref": "common_types.json#/..." }`.
2530
+ */
2531
+ function applyChildRefMarks(schema) {
2532
+ const marked = (description, mark, ref) => {
2533
+ if (typeof description !== "string" || !description.startsWith(mark)) return;
2534
+ const rest = description.slice(mark.length).trim();
2535
+ return rest === "" ? { $ref: ref } : {
2536
+ $ref: ref,
2537
+ description: rest
2538
+ };
2539
+ };
2540
+ const visit = (node) => {
2541
+ var _marked;
2542
+ if (Array.isArray(node)) return node.map(visit);
2543
+ if (!isRecord(node)) return node;
2544
+ const reference = (_marked = marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF)) !== null && _marked !== void 0 ? _marked : marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);
2545
+ if (reference) return reference;
2546
+ return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, visit(value)]));
2547
+ };
2548
+ return visit(schema);
2549
+ }
2550
+ /**
2551
+ * Every component reference in a props schema, with its path. Walks
2552
+ * `properties`, array `items`, and the variants of `anyOf` / `oneOf` /
2553
+ * `allOf`. A union counts as a reference only when every alternative is
2554
+ * one of the same kind: a prop that is text in one branch and a child in
2555
+ * another cannot be told apart from its value, so it stays data.
2556
+ */
2557
+ function collectChildRefs(schema) {
2558
+ const refs = [];
2559
+ const seen = /* @__PURE__ */ new Set();
2560
+ const add = (path, kind) => {
2561
+ const key = path.join("\0");
2562
+ if (seen.has(key)) return;
2563
+ seen.add(key);
2564
+ refs.push({
2565
+ path,
2566
+ kind
2567
+ });
2568
+ };
2569
+ const visit = (node, path) => {
2570
+ if (!isRecord(node)) return;
2571
+ const kind = childRefKind(node);
2572
+ if (kind) return add(path, kind);
2573
+ for (const list of [node.anyOf, node.oneOf]) {
2574
+ if (!Array.isArray(list) || list.length === 0) continue;
2575
+ const kinds = list.map((variant) => isRecord(variant) ? childRefKind(variant) : void 0);
2576
+ const [first] = kinds;
2577
+ if (first && kinds.every((k) => k === first)) add(path, first);
2578
+ else if (kinds.every((k) => k === void 0)) {
2579
+ const perVariant = list.map((variant) => collectChildRefs(variant));
2580
+ const key = (ref) => `${ref.kind}\u0000${ref.path.join("\0")}`;
2581
+ perVariant[0].filter((ref) => perVariant.every((refs) => refs.some((r) => key(r) === key(ref)))).forEach((ref) => add([...path, ...ref.path], ref.kind));
2582
+ }
2583
+ }
2584
+ if (Array.isArray(node.allOf)) node.allOf.forEach((variant) => visit(variant, path));
2585
+ if (isRecord(node.properties)) for (const [key, value] of Object.entries(node.properties)) visit(value, [...path, key]);
2586
+ if (isRecord(node.items)) visit(node.items, [...path, "*"]);
2587
+ };
2588
+ visit(schema, []);
2589
+ return refs;
2590
+ }
2591
+ /**
2592
+ * The component ids at the references of one component node: a string id,
2593
+ * a list of ids, or the `componentId` of a template, at every ref path.
2594
+ * Bound or computed values are not ids and are left out.
2595
+ */
2596
+ function childIdsAtRefs(component, refs) {
2597
+ const ids = [];
2598
+ const collect = (value) => {
2599
+ if (typeof value === "string") ids.push(value);
2600
+ else if (Array.isArray(value)) value.forEach((id) => typeof id === "string" && ids.push(id));
2601
+ else if (isRecord(value) && typeof value.componentId === "string") ids.push(value.componentId);
2602
+ };
2603
+ const visit = (value, path) => {
2604
+ if (path.length === 0) return collect(value);
2605
+ const [head, ...rest] = path;
2606
+ if (head === "*") {
2607
+ if (Array.isArray(value)) value.forEach((item) => visit(item, rest));
2608
+ return;
2609
+ }
2610
+ if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) visit(value[head], rest);
2611
+ };
2612
+ for (const ref of refs) visit(component, ref.path);
2613
+ return ids;
2614
+ }
2615
+ /**
2616
+ * True when a reference of the component is bound or computed (`{"@path"}`,
2617
+ * `{"@call"}`) at the ref itself or above it, so its ids are known only
2618
+ * at render time.
2619
+ */
2620
+ function hasBoundChildRef(component, refs) {
2621
+ const isDynamic = (value) => isRecord(value) && ("@path" in value || "@call" in value);
2622
+ const visit = (value, path) => {
2623
+ if (isDynamic(value)) return true;
2624
+ if (path.length === 0) return false;
2625
+ const [head, ...rest] = path;
2626
+ if (head === "*") return Array.isArray(value) && value.some((item) => visit(item, rest));
2627
+ return isRecord(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
2628
+ };
2629
+ return refs.some((ref) => visit(component, ref.path));
2630
+ }
2631
+ /**
2632
+ * Walks `value` along a ref path and replaces what sits at the end with
2633
+ * `replace(found)`. Objects and arrays on the way are copied; everything
2634
+ * else keeps its identity. Missing keys are left alone.
2635
+ */
2636
+ function mapAtChildRef(value, path, replace) {
2637
+ if (path.length === 0) return replace(value);
2638
+ const [head, ...rest] = path;
2639
+ if (head === "*") {
2640
+ if (!Array.isArray(value)) return value;
2641
+ return value.map((item) => mapAtChildRef(item, rest, replace));
2642
+ }
2643
+ if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) return value;
2644
+ return {
2645
+ ...value,
2646
+ [head]: mapAtChildRef(value[head], rest, replace)
2647
+ };
2648
+ }
2649
+
2650
+ //#endregion
2651
+ //#region src/generative-ui/types.ts
2652
+ /** A2UI protocol version used on the wire. */
2653
+ const A2UI_VERSION = "v1.0";
2654
+ /** Activity type of a generated surface message. */
2655
+ const GENERATIVE_UI_ACTIVITY_TYPE = "generative-ui-surface";
2656
+ /** Activity type of a function call that the agent asks the client to run. */
2657
+ const GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE = "generative-ui-function-call";
2658
+ /** Tool the model calls to render or update surfaces. */
2659
+ const GENERATIVE_UI_RENDER_TOOL = "render_ui";
2660
+ /** Target id of the chat transcript. */
2661
+ const GENERATIVE_UI_CHAT_TARGET = "chat";
2662
+ /** Component id every surface renders from. */
2663
+ const GENERATIVE_UI_ROOT_ID = "root";
2664
+ /**
2665
+ * Whether the agent may call renderer functions with `callRendererFunction`.
2666
+ * Off for now: the result goes back as a developer message, and not every
2667
+ * backend keeps that message where the model reads it in order. While off,
2668
+ * the prompts do not mention the operation, the validator rejects it, and
2669
+ * the dispatcher refuses the agent, whatever a declaration's
2670
+ * `allowedCallers` says. The code and its tests stay for when it is on.
2671
+ */
2672
+ const GENERATIVE_UI_AGENT_FUNCTION_CALLS = false;
2673
+ /** The reason an agent function call is rejected while they are off. */
2674
+ const GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON = "callRendererFunction is not supported in this version: the agent cannot call renderer functions until their results can be sent back to it reliably";
2675
+ /** Activity message id of a surface. One message per surface. */
2676
+ function generativeUISurfaceMessageId(surfaceId) {
2677
+ return `genui:${surfaceId}`;
2678
+ }
2679
+ /**
2680
+ * Activity message id of an agent-called function. One message per
2681
+ * `functionCallId`.
2682
+ *
2683
+ * @param functionCallId - The `functionCallId` of the `callRendererFunction` operation.
2684
+ *
2685
+ * @example
2686
+ * ```ts
2687
+ * generativeUIFunctionCallMessageId("f1"); // "genui-fn:f1"
2688
+ * ```
2689
+ */
2690
+ function generativeUIFunctionCallMessageId(functionCallId) {
2691
+ return `genui-fn:${functionCallId}`;
2692
+ }
2693
+ /**
2694
+ * The keys of the A2UI 1.0 component envelope next to `id` and
2695
+ * `component`: `catalogId`, `accessibility` and `metadata`. They are not
2696
+ * props of the component. The renderer reads `accessibility` and ignores
2697
+ * the other two.
2698
+ */
2699
+ const A2UI_COMPONENT_ENVELOPE_KEYS = new Set([
2700
+ "catalogId",
2701
+ "accessibility",
2702
+ "metadata"
2703
+ ]);
2704
+ /** Most component names that one target can list. */
2705
+ const GENERATIVE_UI_MAX_TARGET_COMPONENTS = 100;
2706
+ /** Most rejections that a surface summary lists. */
2707
+ const GENERATIVE_UI_MAX_SUMMARY_REJECTIONS = 20;
2708
+ /** Most characters of one rejection in a surface summary. */
2709
+ const GENERATIVE_UI_MAX_REJECTION_LENGTH = 500;
2710
+ /**
2711
+ * The action message of a user event, with the A2UI field names. Takes the
2712
+ * time of the call when the event has no timestamp.
2713
+ *
2714
+ * @example
2715
+ * ```ts
2716
+ * toA2UIActionMessage({ name: "buy", surfaceId: "s1", componentId: "b", context: { sku: "a" } });
2717
+ * // { version: "v1.0", action: { name: "buy", surfaceId: "s1", sourceComponentId: "b", timestamp: "2026-…", context: { sku: "a" } } }
2718
+ * ```
2719
+ */
2720
+ function toA2UIActionMessage(event) {
2721
+ var _event$timestamp;
2722
+ return {
2723
+ version: A2UI_VERSION,
2724
+ action: {
2725
+ name: event.name,
2726
+ surfaceId: event.surfaceId,
2727
+ sourceComponentId: event.componentId,
2728
+ timestamp: (_event$timestamp = event.timestamp) !== null && _event$timestamp !== void 0 ? _event$timestamp : (/* @__PURE__ */ new Date()).toISOString(),
2729
+ ...event.userMessage === void 0 ? {} : { userMessage: event.userMessage },
2730
+ context: event.context
2731
+ }
2732
+ };
2733
+ }
2734
+
2735
+ //#endregion
2736
+ //#region src/a2ui-prompts.ts
2737
+ /**
2738
+ * Default A2UI generation and design guideline prompts.
2739
+ *
2740
+ * These are the canonical prompt fragments that instruct an LLM how to call
2741
+ * the render_a2ui tool, how to bind data, and how to style surfaces.
2742
+ */
2743
+ /**
2744
+ * Generation guidelines — protocol rules, tool arguments, path rules,
2745
+ * data model format, and form/two-way-binding instructions.
2746
+ */
2747
+ const A2UI_DEFAULT_GENERATION_GUIDELINES = `\
2748
+ Generate A2UI v0.9 JSON.
2749
+
2750
+ ## A2UI Protocol Instructions
2751
+
2752
+ A2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.
2753
+
2754
+ CRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:
2755
+ - surfaceId: A unique ID for the surface (e.g. "product-comparison")
2756
+ - components: REQUIRED — the A2UI component array. NEVER omit this. Only use
2757
+ components listed in the Available Components schema provided as context.
2758
+ - data: OPTIONAL — a JSON object written to the root of the surface data model.
2759
+ Use for pre-filling form values or providing data for path-bound components.
2760
+ - every component must have the "component" field specifying the component type.
2761
+ ONLY use component names from the Available Components schema — do NOT invent
2762
+ component names or use names not in the schema.
2763
+
2764
+ COMPONENT ID RULES:
2765
+ - Exactly one component MUST have id="root". This is the surface's entry
2766
+ point — the renderer begins at "root" and walks the child/children tree
2767
+ from there. Every other component must be reachable from "root". If no
2768
+ component has id="root", the surface renders an empty loading placeholder
2769
+ and none of your components will be shown.
2770
+ - Every component ID must be unique within the surface.
2771
+ - A component MUST NOT reference itself as child/children. This causes a
2772
+ circular dependency error. For example, if a component has id="avatar",
2773
+ its child must be a DIFFERENT id (e.g. "avatar-img"), never "avatar".
2774
+ - The child/children tree must be a DAG — no cycles allowed.
2775
+
2776
+ REPEATING CONTENT (TEMPLATES):
2777
+ To repeat a component for each item in an array, use the structural children format:
2778
+ children: { componentId: "card-id", path: "/items" }
2779
+ This tells the renderer to create one instance of "card-id" per item in the "/items" array.
2780
+
2781
+ PATH RULES FOR TEMPLATES:
2782
+ Components inside a repeating template use RELATIVE paths (no leading slash).
2783
+ The path is resolved relative to each array item automatically.
2784
+ If a container has children: { componentId: "card", path: "/items" } and each item
2785
+ has a key "name", use { "path": "name" } (NO leading slash — relative to item).
2786
+ CRITICAL: Do NOT use "/name" (absolute) inside templates — use "name" (relative).
2787
+ The container's path ("/items") uses a leading slash (absolute), but all
2788
+ components INSIDE the template use paths WITHOUT leading slash.
2789
+
2790
+ COMPONENT VALUES — DEFAULT RULE:
2791
+ Use inline literal values for ALL component properties. Pass strings, numbers,
2792
+ arrays, and objects directly on the component. Do NOT use { "path": "..." }
2793
+ objects unless the property's schema explicitly allows it (see exception below).
2794
+ CRITICAL: USING { "path": "..." } ON A PROPERTY THAT DOES NOT DECLARE PATH
2795
+ SUPPORT IN ITS SCHEMA WILL CAUSE A RUNTIME CRASH AND BREAK THE ENTIRE UI.
2796
+ ALWAYS CHECK THE COMPONENT SCHEMA FIRST — IF THE PROPERTY ONLY ACCEPTS A
2797
+ PLAIN TYPE, YOU MUST USE A LITERAL VALUE.
2798
+ VERY IMPORTANT: THE APPLICATION WILL BREAK IF YOU DO NOT FOLLOW THIS RULE!
2799
+
2800
+ For example, a chart's "data" must always be an inline array:
2801
+ "data": [{"label": "Jan", "value": 100}, {"label": "Feb", "value": 200}]
2802
+ A metric's "value" must always be an inline string:
2803
+ "value": "$1,200"
2804
+
2805
+ PATH BINDING EXCEPTION — SCHEMA-DRIVEN:
2806
+ A few properties accept { "path": "/some/path" } as an alternative to a literal
2807
+ value. You can identify these in the Available Components schema: the property
2808
+ will list BOTH a literal type AND an object-with-path option. If a property only
2809
+ shows a single type (string, number, array, etc.), it does NOT support path
2810
+ binding — use a literal value only.
2811
+
2812
+ Path binding is typically used for editable form inputs so the client can write
2813
+ user input back to the data model. When building forms:
2814
+ - Bind input "value" to a data model path: "value": { "path": "/form/name" }
2815
+ - Pre-fill via the "data" tool argument: "data": { "form": { "name": "Alice" } }
2816
+ - Capture values on submit via button action context:
2817
+ "action": { "event": { "name": "submit", "context": { "name": { "path": "/form/name" } } } }
2818
+
2819
+ REPEATING CONTENT uses a structural children format (not the same as value binding):
2820
+ children: { componentId: "card-id", path: "/items" }
2821
+ Components inside templates use RELATIVE paths (no leading slash): { "path": "name" }.`;
2822
+ /**
2823
+ * Design guidelines — visual design rules, component hierarchy tips,
2824
+ * and action handler patterns.
2825
+ */
2826
+ const A2UI_DEFAULT_DESIGN_GUIDELINES = `\
2827
+ Create polished, visually appealing interfaces. ONLY use components listed in the
2828
+ Available Components schema — do NOT use component names that are not in the schema.
2829
+
2830
+ Design principles:
2831
+ - Create clear visual hierarchy within cards and layouts.
2832
+ - Keep cards clean — avoid clutter. Whitespace is good.
2833
+ - Use consistent surfaceIds (lowercase, hyphenated).
2834
+ - NEVER use the same ID for a component and its child — this creates a
2835
+ circular dependency. E.g. if id="avatar", child must NOT be "avatar".
2836
+ - For side-by-side comparisons, use a container with structural children
2837
+ (children: { componentId, path }) to repeat a card template per data item.
2838
+ - Include images when relevant (logos, icons, product photos):
2839
+ - Prefer company logos via Google favicons: https://www.google.com/s2/favicons?domain=example.com&sz=128
2840
+ - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.
2841
+ - For buttons: action MUST use this exact nested format:
2842
+ "action": { "event": { "name": "myAction", "context": { "key": "value" } } }
2843
+ The "event" key holds an OBJECT with "name" (required) and "context" (optional).
2844
+ Do NOT use a flat format like {"event": "name"} — "event" must be an object.
2845
+ - For forms: check the component schema — if an input's "value" property
2846
+ supports path binding, use it for editable fields. The submit button's
2847
+ action context should reference the same paths to capture user input.
2848
+
2849
+ Use the SAME surfaceId as the main surface. Match action names to button action event names.`;
2850
+ /**
2851
+ * When UI helps the user, for both transports: a light nudge to reach for UI
2852
+ * where it conveys the answer better than prose, and to stay in prose
2853
+ * otherwise.
2854
+ */
2855
+ const GENERATIVE_UI_WHEN_TO_SHOW = "Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.";
2856
+ /** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */
2857
+ const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = "Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.";
2858
+ /**
2859
+ * Description of the context entry that carries the compact component schema
2860
+ * in the markdown transport.
2861
+ *
2862
+ * It must not equal `A2UI_SCHEMA_CONTEXT_DESCRIPTION` (the key that
2863
+ * `@ag-ui/a2ui-middleware` stamps for tool mode). The LangGraph and Strands
2864
+ * adapters find that exact string and move the entry into
2865
+ * `state["ag-ui"]["a2ui_schema"]` for the `render_a2ui` tool, so it never
2866
+ * gets to the system prompt. The markdown transport has no tool, so the
2867
+ * schema must stay ordinary context that the model reads as App Context.
2868
+ */
2869
+ const GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION = "Generative UI component schema: the components, props, events, slots, functions, and targets that ```a2ui code fences can use, and the surfaces that already exist.";
2870
+ /** Every optional rule group. Use it when the manifest is not known. */
2871
+ const ALL_GENERATIVE_UI_GUIDE_FEATURES = {
2872
+ functions: true,
2873
+ events: true,
2874
+ templates: true,
2875
+ checks: true
2876
+ };
2877
+ /**
2878
+ * The optional parts of A2UI that a manifest uses, so that a guide sends only
2879
+ * the rules that the model can apply.
2880
+ *
2881
+ * @param manifest - The components and the mounted functions of a run.
2882
+ * @returns Which optional rule groups the guides include.
2883
+ *
2884
+ * @example
2885
+ * ```ts
2886
+ * const guide = buildGenerativeUIMarkdownGuidelines(
2887
+ * generativeUIGuideFeatures(manifest),
2888
+ * );
2889
+ * ```
2890
+ */
2891
+ function generativeUIGuideFeatures(manifest) {
2892
+ const components = Object.values(manifest.components);
2893
+ const hasChildList = (schema) => {
2894
+ if (Array.isArray(schema)) return schema.some(hasChildList);
2895
+ if (typeof schema !== "object" || schema === null) return false;
2896
+ const node = schema;
2897
+ if (node.$ref === A2UI_CHILD_LIST_REF) return true;
2898
+ return Object.values(node).some(hasChildList);
2899
+ };
2900
+ return {
2901
+ functions: Object.keys(manifest.functions).some((name) => !isA2UIBasicFunction(name)),
2902
+ events: components.some((c) => {
2903
+ var _c$events;
2904
+ return Object.keys((_c$events = c.events) !== null && _c$events !== void 0 ? _c$events : {}).length > 0;
2905
+ }),
2906
+ templates: components.some((c) => {
2907
+ var _c$slots;
2908
+ return Object.values((_c$slots = c.slots) !== null && _c$slots !== void 0 ? _c$slots : {}).includes("multiple") || hasChildList(c.props);
2909
+ }),
2910
+ checks: components.some((c) => {
2911
+ const properties = c.props.properties;
2912
+ return typeof properties === "object" && properties !== null && Object.prototype.hasOwnProperty.call(properties, "checks");
2913
+ })
2914
+ };
2915
+ }
2916
+ /** The first rules of every markdown guideline, before the optional groups. */
2917
+ const MARKDOWN_BASE_RULES = [
2918
+ "Write explanations as normal markdown prose outside the fences.",
2919
+ "Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
2920
+ "Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target has \"components\", its surfaces can use only those components.",
2921
+ "Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
2922
+ "Keep each operation whole on its line.",
2923
+ "Give every operation \"version\":\"v1.0\".",
2924
+ `Start a surface with one createSurface. Put all the initial data in "dataModel" and the "root" component in "components". Then write the children in updateComponents lines, so that they show while you write:
2925
+ \`\`\`a2ui
2926
+ {"version":"v1.0","createSurface":{"surfaceId":"plan-picker","dataModel":{ ...initial data... },"components":[{"id":"root","component":"<Name>","children":["seats","pick"]}]}}
2927
+ {"version":"v1.0","updateComponents":{"surfaceId":"plan-picker","components":[ ...the children... ]}}
2928
+ \`\`\``,
2929
+ "Keep \"dataModel\" flat: top-level keys such as \"seats\" or \"form\", never one wrapper object around everything. Check that every { and [ you open in a line is closed.",
2930
+ "Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.",
2931
+ "Use unique ids. Do not make cycles. A component cannot be its own child.",
2932
+ "Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
2933
+ "Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
2934
+ "A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
2935
+ "Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".",
2936
+ "Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
2937
+ "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions under \"functions\" in the schema. Write a literal when the value never changes.",
2938
+ "formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: 'EUR')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.",
2939
+ "${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: 'seats * 29', seats: /seats), currency: 'USD')}. The UI then follows the user's input with no round trip.",
2940
+ "For a computed list (chart data, template items) use series. Its description under \"functions\" in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.",
2941
+ "Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
2942
+ "To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".",
2943
+ "Set \"value\":null to delete the key at \"path\"."
2944
+ ];
2945
+ /** The last rules of every markdown guideline, after the optional groups. */
2946
+ const MARKDOWN_CLOSING_RULES = [
2947
+ "The schema lists the surfaces that already exist under \"surfaces\". \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.",
2948
+ "Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.",
2949
+ "Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
2950
+ "Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
2951
+ "Never wrap the whole reply in a fence."
2952
+ ];
2953
+ /**
2954
+ * Builds the markdown-transport guideline. The model writes A2UI v1.0
2955
+ * operations inside ```a2ui fences between normal markdown prose. The rules
2956
+ * for functions, events, and templates are left out when the manifest has
2957
+ * none of them, so the guideline stays small.
2958
+ *
2959
+ * @param features - The optional rule groups to include. Defaults to all.
2960
+ * @returns The guideline text, one rule per line.
2961
+ */
2962
+ function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES) {
2963
+ const { functions, events, templates, checks } = features;
2964
+ const rules = [...MARKDOWN_BASE_RULES];
2965
+ if (events) rules.push("Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.", functions ? "Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call." : "Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.", "Use {\"event\": ...} to send the interaction back to you as a user message. Put the text of that message in \"userMessage\": {\"event\":{\"name\":\"choose\",\"userMessage\":\"Show me the Team plan\"}}. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".", "To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.", "A button or other event prop without an event or functionCall does nothing.");
2966
+ if (checks) rules.push("Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks.");
2967
+ rules.push("A prop typed componentId takes the id of another component, and a childList takes ids [\"a\",\"b\"]: \"child\":\"card\", \"children\":[\"a\",\"b\"], \"tabs\":[{\"title\":\"Specs\",\"child\":\"specs\"}].");
2968
+ if (templates) rules.push("To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.", "Inside a template, paths are relative to the item (\"name\", not \"/name\").", "Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.");
2969
+ rules.push("Updating a component replaces all of its props. Send every prop again.", "To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.", "Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.");
2970
+ if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) rules.push("To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.", "Give every callRendererFunction a new functionCallId. Call only a function from the schema with \"callers\": \"UI or agent\" or \"agent only\"; a function without \"callers\" is for the UI only. A function with \"callers\": \"agent only\" is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.", "Do not guess the result of a callRendererFunction. Wait for the developer message.");
2971
+ rules.push(...MARKDOWN_CLOSING_RULES);
2972
+ return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.
2973
+
2974
+ ${GENERATIVE_UI_WHEN_TO_SHOW}
2975
+
2976
+ RULES
2977
+ ${rules.map((rule) => `- ${rule}`).join("\n")}
2978
+ `;
2979
+ }
2980
+ /**
2981
+ * The markdown-transport guideline with every rule group. A run sends
2982
+ * `buildGenerativeUIMarkdownGuidelines` for its own manifest instead.
2983
+ */
2984
+ const GENERATIVE_UI_MARKDOWN_GUIDELINES = buildGenerativeUIMarkdownGuidelines();
2985
+
2986
+ //#endregion
2987
+ //#region src/a2ui-envelope.ts
2988
+ /**
2989
+ * The generative UI envelope that the client sends on every run as
2990
+ * `forwardedProps.copilotkit.ui`. It has the A2UI v1.0 renderer capabilities
2991
+ * shape, so a backend that speaks A2UI v1.0 can read the catalog as it is.
2992
+ * CopilotKit data goes in `metadata.extensions`, under `copilotkit_` keys.
2993
+ * The runtime reads it to pick the transport and to build the guide.
2994
+ */
2995
+ /** Top-level `forwardedProps` key that holds the CopilotKit run properties. */
2996
+ const COPILOTKIT_FORWARDED_PROPS_KEY = "copilotkit";
2997
+ /** Version of the envelope shape (not of the UI protocol that it carries). */
2998
+ const COPILOTKIT_UI_ENVELOPE_FORMAT = 3;
2999
+ function isOptionalString(value) {
3000
+ return value === void 0 || typeof value === "string";
3001
+ }
3002
+ function isNonEmptyString(value) {
3003
+ return typeof value === "string" && value !== "";
3004
+ }
3005
+ function isRecordOf(value, isEntry) {
3006
+ return isRecord(value) && Object.values(value).every(isEntry);
3007
+ }
3008
+ /** A function, or an event of a component: a description and a parameter schema. */
3009
+ function isSchemaEntry(value) {
3010
+ return isRecord(value) && isRecord(value.parameters) && isOptionalString(value.description);
3011
+ }
3012
+ function isSlotKind(value) {
3013
+ return value === "single" || value === "multiple";
3014
+ }
3015
+ /**
3016
+ * `validateOperation` reads `properties` and `required` of a props schema,
3017
+ * so those two must have the right shape when they are there.
3018
+ */
3019
+ function isPropsSchema(value) {
3020
+ return isRecord(value) && (value.properties === void 0 || isRecord(value.properties)) && (value.required === void 0 || Array.isArray(value.required) && value.required.every((name) => typeof name === "string"));
3021
+ }
3022
+ function isComponentManifest(value) {
3023
+ var _value$props$properti, _value$slots, _value$events;
3024
+ if (!isRecord(value) || !isPropsSchema(value.props) || !isOptionalString(value.description) || value.events !== void 0 && !isRecordOf(value.events, isSchemaEntry) || value.slots !== void 0 && !isRecordOf(value.slots, isSlotKind)) return false;
3025
+ const order = value.parameterOrder;
3026
+ if (order === void 0) return true;
3027
+ const keys = new Set([
3028
+ ...Object.keys((_value$props$properti = value.props.properties) !== null && _value$props$properti !== void 0 ? _value$props$properti : {}),
3029
+ ...Object.keys((_value$slots = value.slots) !== null && _value$slots !== void 0 ? _value$slots : {}),
3030
+ ...Object.keys((_value$events = value.events) !== null && _value$events !== void 0 ? _value$events : {})
3031
+ ]);
3032
+ return Array.isArray(order) && new Set(order).size === order.length && order.every((key) => typeof key === "string" && keys.has(key));
3033
+ }
3034
+ function isInlineCatalog(value) {
3035
+ return isRecord(value) && isNonEmptyString(value.catalogId) && value.protocolVersion === "1.0" && (value.components === void 0 || isRecordOf(value.components, isComponentManifest)) && isRecordOf(value.functions, isSchemaEntry) && isOptionalString(value.instructions);
3036
+ }
3037
+ function isCapabilities(value) {
3038
+ return isRecord(value) && Array.isArray(value.supportedCatalogIds) && value.supportedCatalogIds.length > 0 && value.supportedCatalogIds.every(isNonEmptyString) && (value.inlineCatalogs === void 0 || Array.isArray(value.inlineCatalogs) && value.inlineCatalogs.every(isInlineCatalog));
3039
+ }
3040
+ /** A short list of component names. */
3041
+ function isComponentNameList(value) {
3042
+ return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_TARGET_COMPONENTS && value.every(isNonEmptyString);
3043
+ }
3044
+ function isTarget(value) {
3045
+ return isRecord(value) && isNonEmptyString(value.id) && (value.kind === "chat" || value.kind === "inline") && isOptionalString(value.description) && (value.components === void 0 || isComponentNameList(value.components));
3046
+ }
3047
+ /** A short list of short strings. The summary limits keep the guide small. */
3048
+ function isRejectionList(value) {
3049
+ return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_SUMMARY_REJECTIONS && value.every((entry) => typeof entry === "string" && entry.length <= GENERATIVE_UI_MAX_REJECTION_LENGTH);
3050
+ }
3051
+ function isSurfaceEntry(value) {
3052
+ return isRecord(value) && isNonEmptyString(value.target) && (value.dataModel === void 0 || isRecord(value.dataModel)) && (value.rejected === void 0 || isRejectionList(value.rejected)) && (value.status === void 0 || value.status === "deleted" || value.status === "failed");
3053
+ }
3054
+ /** Checks the `copilotkit_` keys only. Other extensions can be there too. */
3055
+ function isExtensions(value) {
3056
+ return isRecord(value) && value.copilotkit_format === COPILOTKIT_UI_ENVELOPE_FORMAT && (value.copilotkit_transport === "tool" || value.copilotkit_transport === "markdown") && Array.isArray(value.copilotkit_targets) && value.copilotkit_targets.every(isTarget) && isRecordOf(value.copilotkit_surfaces, isSurfaceEntry) && typeof value.copilotkit_contextSent === "boolean";
3057
+ }
3058
+ function isEnvelope(value) {
3059
+ return isRecord(value) && isCapabilities(value["v1.0"]) && isRecord(value.metadata) && isExtensions(value.metadata.extensions);
3060
+ }
3061
+ /**
3062
+ * Reads the generative UI envelope from the `forwardedProps` of a run.
3063
+ *
3064
+ * The envelope comes from the client, so it is not trusted: every field is
3065
+ * checked. Returns `undefined` when the envelope is not there, or when it is
3066
+ * malformed (for example a wrong `copilotkit_format` or
3067
+ * `copilotkit_transport`, or no catalog id).
3068
+ *
3069
+ * @param forwardedProps - The `forwardedProps` of the run input.
3070
+ *
3071
+ * @example
3072
+ * ```ts
3073
+ * const envelope = readCopilotKitUIEnvelope(input.forwardedProps);
3074
+ * if (envelope?.metadata.extensions.copilotkit_transport === "markdown") {
3075
+ * // The model writes ```a2ui fences. Add no render tool.
3076
+ * }
3077
+ * ```
3078
+ */
3079
+ function readCopilotKitUIEnvelope(forwardedProps) {
3080
+ if (!isRecord(forwardedProps)) return void 0;
3081
+ const namespace = forwardedProps[COPILOTKIT_FORWARDED_PROPS_KEY];
3082
+ if (!isRecord(namespace)) return void 0;
3083
+ const envelope = namespace.ui;
3084
+ return isEnvelope(envelope) ? envelope : void 0;
3085
+ }
3086
+ /**
3087
+ * Turns an envelope into the manifest that the runtime and the prompts use.
3088
+ *
3089
+ * The catalog is the first of `supportedCatalogIds`, and `catalogIds` lists
3090
+ * all of them. The components, functions, and instructions come from the
3091
+ * inline catalog of the first id.
3092
+ * With no such inline catalog, there are no components and no functions.
3093
+ *
3094
+ * The result also has:
3095
+ * - `transport` and `contextSent`, from the extensions.
3096
+ * - `instructions`, when the inline catalog has them.
3097
+ * - `hasComponents`: false when the client left the component schemas out.
3098
+ * The runtime cannot check operations without them.
3099
+ * - `action`: the A2UI action message of the user event that started the
3100
+ * run, when one did.
3101
+ *
3102
+ * @param envelope - An envelope from `readCopilotKitUIEnvelope`.
3103
+ *
3104
+ * @example
3105
+ * ```ts
3106
+ * const envelope = readCopilotKitUIEnvelope(input.forwardedProps);
3107
+ * const manifest = envelope && envelopeToManifest(envelope);
3108
+ * if (manifest?.transport === "tool" && manifest.hasComponents) {
3109
+ * // Add the render tool and validate operations against manifest.components.
3110
+ * }
3111
+ * ```
3112
+ */
3113
+ function envelopeToManifest(envelope) {
3114
+ var _catalog$components, _catalog$functions;
3115
+ const { supportedCatalogIds, inlineCatalogs } = envelope["v1.0"];
3116
+ const catalogId = supportedCatalogIds[0];
3117
+ const catalog = inlineCatalogs === null || inlineCatalogs === void 0 ? void 0 : inlineCatalogs.find((entry) => entry.catalogId === catalogId);
3118
+ const extensions = envelope.metadata.extensions;
3119
+ return {
3120
+ catalogId,
3121
+ catalogIds: supportedCatalogIds,
3122
+ components: (_catalog$components = catalog === null || catalog === void 0 ? void 0 : catalog.components) !== null && _catalog$components !== void 0 ? _catalog$components : {},
3123
+ functions: (_catalog$functions = catalog === null || catalog === void 0 ? void 0 : catalog.functions) !== null && _catalog$functions !== void 0 ? _catalog$functions : {},
3124
+ targets: extensions.copilotkit_targets,
3125
+ surfaces: extensions.copilotkit_surfaces,
3126
+ transport: extensions.copilotkit_transport,
3127
+ contextSent: extensions.copilotkit_contextSent,
3128
+ instructions: catalog === null || catalog === void 0 ? void 0 : catalog.instructions,
3129
+ hasComponents: (catalog === null || catalog === void 0 ? void 0 : catalog.components) !== void 0,
3130
+ ...extensions.copilotkit_action === void 0 ? {} : { action: extensions.copilotkit_action }
3131
+ };
3132
+ }
3133
+
3134
+ //#endregion
3135
+ //#region src/open-generative-ui-prompts.ts
3136
+ /** Shared generation contract for all Open Generative UI renderers. */
3137
+ const GENERATE_SANDBOXED_UI_DESCRIPTION = "Generate sandboxed UI. IMPORTANT: The generated code runs in a sandboxed iframe WITHOUT same-origin access. Do NOT use localStorage, sessionStorage, document.cookie, IndexedDB, or fetch/XMLHttpRequest to same-origin URLs. To communicate with the host application, use Websandbox.connection.remote.<functionName>(args) which returns a Promise.\n\nYou CAN use external libraries from CDNs by including <script> or <link> tags in the HTML <head> (e.g., Chart.js, D3, Three.js, x-data-spreadsheet, etc.). CDN resources load normally inside the sandbox.\n\nPARAMETER ORDER IS CRITICAL — generate parameters in exactly this order:\n1. initialHeight + placeholderMessages (shown to user while generating)\n2. css (all styles FIRST — the user sees a placeholder until CSS is complete)\n3. html (streams in live — the user watches the UI build as HTML is generated)\n4. jsFunctions (reusable helper functions)\n5. jsExpressions (applied one-by-one — the user sees each expression take effect)\n\nINITIALIZATION CONTRACT: jsFunctions and jsExpressions run after the final HTML DOM is ready, in both live generation and saved-thread replay. Define reusable functions in jsFunctions, then initialize the UI directly in the first jsExpressions entry (for example, initializeCalculator()). Attach click/keyboard handlers and set initial display values there. Do NOT wait for DOMContentLoaded, window.onload, or the load event in jsFunctions or jsExpressions: these events may already have fired. Each expression is executed once per rendered sandbox; later expressions must not repeat initialization or reattach the same handlers. Keep initialization self-contained so a new sandbox can reconstruct the UI when a saved thread is opened. If a library loads asynchronously, initialize from its explicit load promise instead of waiting for document readiness.\n\nINTERACTION CONTRACT: Every visible interactive control needs a working handler, including controls created during initialization. If the handlers are supplied through jsFunctions/jsExpressions, initialize them in the first expression; if supplied by an inline HTML script, ensure it runs when the final sandbox mounts and replays. Every user action must update the visible UI to reflect its completed result, including success and error paths. Changing a JavaScript variable alone does not update the DOM. After changing state, call the rendering function or update the displayed element directly. When delegating clicks from a parent element, resolve the clicked control with closest('button') so clicks on nested labels and values work. For a calculator, pressing = must replace the visible expression with the computed answer; metric shortcuts must visibly insert their values. Trace each button handler through its final display update before emitting the tool call.";
3138
+
3139
+ //#endregion
3140
+ //#region src/generative-ui/validate-operation.ts
3141
+ const OPERATION_KINDS = [
3142
+ "createSurface",
3143
+ "updateComponents",
3144
+ "updateDataModel",
3145
+ "deleteSurface",
3146
+ "callRendererFunction"
3147
+ ];
3148
+ const OK = { ok: true };
3149
+ const fail = (reason) => ({
3150
+ ok: false,
3151
+ reason
3152
+ });
3153
+ /** Models write the v0.9 binding from habit. The reason names the v1.0 form. */
3154
+ const V09_PATH_REASON = "bind data with {\"@path\": \"/x\"}, not {\"path\": \"/x\"}";
3155
+ function hasOwn(record, key) {
3156
+ return Object.prototype.hasOwnProperty.call(record, key);
3157
+ }
3158
+ /**
3159
+ * Reads an own property only. Model-controlled keys such as "constructor" or
3160
+ * "toString" must not resolve to Object.prototype members.
3161
+ */
3162
+ function ownValue(record, key) {
3163
+ return record && hasOwn(record, key) ? record[key] : void 0;
3164
+ }
3165
+ function getOperationKind(op) {
3166
+ if (!isRecord(op)) return void 0;
3167
+ const kinds = OPERATION_KINDS.filter((kind) => kind in op);
3168
+ return kinds.length === 1 ? kinds[0] : void 0;
3169
+ }
3170
+ /** The `surfaceId` of a surface operation. `callRendererFunction` has none. */
3171
+ function getOperationSurfaceId(op) {
3172
+ if (!isRecord(op)) return void 0;
3173
+ const kind = getOperationKind(op);
3174
+ if (!kind) return void 0;
3175
+ const payload = op[kind];
3176
+ return isRecord(payload) && typeof payload.surfaceId === "string" ? payload.surfaceId : void 0;
3177
+ }
3178
+ /** `{ "@path": "/x" }`: a data-model binding. */
3179
+ function isPathBinding(value) {
3180
+ return isRecord(value) && typeof value["@path"] === "string" && Object.keys(value).length === 1;
3181
+ }
3182
+ /** `{ "path": "/x" }`: the v0.9 binding, which v1.0 does not accept. */
3183
+ function isV09PathBinding(value) {
3184
+ return isRecord(value) && typeof value.path === "string" && Object.keys(value).length === 1;
3185
+ }
3186
+ /**
3187
+ * `{ "@call": "@index" }` or `{ "@call": "@index", "args": { "offset": 1 } }`:
3188
+ * the 0-based position of the item in a template, plus `offset`.
3189
+ */
3190
+ function isIndexCall(value) {
3191
+ if (!isRecord(value) || value["@call"] !== "@index") return false;
3192
+ if (!Object.keys(value).every((key) => key === "@call" || key === "args")) return false;
3193
+ const { args } = value;
3194
+ if (args === void 0) return true;
3195
+ return isRecord(args) && Object.keys(args).every((key) => key === "offset") && (args.offset === void 0 || Number.isFinite(args.offset));
3196
+ }
3197
+ function isActionBinding(value) {
3198
+ return isRecord(value) && Object.keys(value).length === 1 && (isRecord(value.functionCall) || isRecord(value.event));
3199
+ }
3200
+ /**
3201
+ * Checks one A2UI v1.0 operation against the catalog and the surfaces that
3202
+ * exist. The operation comes from the model, so nothing in it is trusted.
3203
+ *
3204
+ * @param op - The operation, as parsed from JSON.
3205
+ * @param options - The catalog, the known and created surfaces, the
3206
+ * functions that the UI can call, and the components that the target of
3207
+ * the surface takes.
3208
+ *
3209
+ * @example
3210
+ * ```ts
3211
+ * const result = validateOperation(op, { manifest, knownSurfaces });
3212
+ * if (!result.ok) rejected.push({ index, reason: result.reason });
3213
+ * ```
3214
+ */
3215
+ function validateOperation(op, options) {
3216
+ if (!isRecord(op)) return fail("operation must be a JSON object");
3217
+ if (op.version !== A2UI_VERSION) return fail(versionProblem(op.version));
3218
+ const kind = getOperationKind(op);
3219
+ if (!kind) return fail(`operation must contain exactly one of ${OPERATION_KINDS.join(", ")}`);
3220
+ const payload = op[kind];
3221
+ if (kind === "callRendererFunction") {
3222
+ if (!GENERATIVE_UI_AGENT_FUNCTION_CALLS) return fail(GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
3223
+ return validateRendererFunctionCall(payload, options);
3224
+ }
3225
+ if (!isRecord(payload) || typeof payload.surfaceId !== "string" || !payload.surfaceId) return fail(`${kind}.surfaceId is required`);
3226
+ const surfaceId = payload.surfaceId;
3227
+ if (kind === "createSurface") return validateCreateSurface(payload, surfaceId, options);
3228
+ if (!options.knownSurfaces.has(surfaceId)) return fail(`surface "${surfaceId}" does not exist; send createSurface first`);
3229
+ switch (kind) {
3230
+ case "deleteSurface": return OK;
3231
+ case "updateDataModel": return validateDataModelUpdate(payload);
3232
+ case "updateComponents": return validateComponents(payload.components, "updateComponents.components", options);
3233
+ }
3234
+ }
3235
+ function versionProblem(version) {
3236
+ return typeof version === "string" ? `unsupported version "${version}"; use "${A2UI_VERSION}"` : `operation needs "version":"${A2UI_VERSION}"`;
3237
+ }
3238
+ /** A `catalogId` can name the catalog of the run or one of its bases. */
3239
+ function catalogProblem(catalogId, manifest) {
3240
+ var _manifest$catalogIds;
3241
+ const ids = (_manifest$catalogIds = manifest.catalogIds) !== null && _manifest$catalogIds !== void 0 ? _manifest$catalogIds : [manifest.catalogId];
3242
+ if (catalogId === void 0 || ids.includes(catalogId)) return;
3243
+ const names = ids.map((id) => `"${id}"`).join(", ");
3244
+ const use = ids.length === 1 ? names : `one of: ${names}`;
3245
+ return `unknown catalog "${String(catalogId)}"; leave out catalogId or use ${use}`;
3246
+ }
3247
+ function validateCreateSurface(payload, surfaceId, options) {
3248
+ var _options$createdSurfa;
3249
+ if (options.knownSurfaces.has(surfaceId)) return fail(`surface "${surfaceId}" already exists`);
3250
+ if ((_options$createdSurfa = options.createdSurfaces) === null || _options$createdSurfa === void 0 ? void 0 : _options$createdSurfa.has(surfaceId)) return fail(`surface id "${surfaceId}" was used before; use a new surfaceId`);
3251
+ const catalogReason = catalogProblem(payload.catalogId, options.manifest);
3252
+ if (catalogReason) return fail(catalogReason);
3253
+ const { dataModel, components } = payload;
3254
+ if (dataModel !== void 0 && !isRecord(dataModel)) return fail("createSurface.dataModel must be a JSON object");
3255
+ if (components === void 0) return OK;
3256
+ return validateComponents(components, "createSurface.components", options);
3257
+ }
3258
+ function validateRendererFunctionCall(payload, options) {
3259
+ if (!(isRecord(payload) && typeof payload.functionCallId === "string" && payload.functionCallId !== "")) return fail("callRendererFunction.functionCallId must be a non-empty string");
3260
+ const reason = functionCallProblem(payload.callFunction, "callRendererFunction.callFunction", options);
3261
+ return reason ? fail(reason) : OK;
3262
+ }
3263
+ const FORBIDDEN_SEGMENTS = new Set([
3264
+ "__proto__",
3265
+ "constructor",
3266
+ "prototype"
3267
+ ]);
3268
+ function decodeSegment(segment) {
3269
+ return segment.replace(/~([01])/g, (_, g) => g === "1" ? "/" : "~");
3270
+ }
3271
+ function validateDataModelUpdate(payload) {
3272
+ var _payload$path;
3273
+ if (payload.value === void 0) return fail("updateDataModel.value is required; use \"value\":null to delete");
3274
+ const path = (_payload$path = payload.path) !== null && _payload$path !== void 0 ? _payload$path : "/";
3275
+ if (typeof path !== "string" || !path.startsWith("/")) return fail("updateDataModel.path must be an absolute JSON pointer");
3276
+ if (path === "/") {
3277
+ if (!isRecord(payload.value)) return fail("a root updateDataModel value must be a JSON object");
3278
+ return OK;
3279
+ }
3280
+ const reason = pathProblem(path, "updateDataModel.path");
3281
+ return reason ? fail(reason) : OK;
3282
+ }
3283
+ /**
3284
+ * Checks the segments of an absolute JSON pointer ("/a/b") or of a path
3285
+ * relative to a template item ("a/b"). `label` names the field in the reason.
3286
+ */
3287
+ function pathProblem(path, label) {
3288
+ const segments = (path.startsWith("/") ? path.slice(1) : path).split("/");
3289
+ if (segments.some((segment) => segment === "")) return `${label} must not contain empty segments`;
3290
+ const forbidden = segments.map(decodeSegment).find((segment) => FORBIDDEN_SEGMENTS.has(segment));
3291
+ if (forbidden !== void 0) return `path segment "${forbidden}" is not allowed in ${label}`;
3292
+ }
3293
+ function validateComponents(components, label, options) {
3294
+ if (!Array.isArray(components) || components.length === 0) return fail(`${label} must be a non-empty array`);
3295
+ const ids = /* @__PURE__ */ new Set();
3296
+ for (const node of components) {
3297
+ if (!isRecord(node)) return fail("component must be a JSON object");
3298
+ const { id } = node;
3299
+ if (typeof id !== "string" || !id) return fail("id is required");
3300
+ const reason = nodeProblem(node, id, options);
3301
+ if (reason) return fail(`component "${id}": ${reason}`);
3302
+ if (ids.has(id)) return fail(`component "${id}" appears twice in one update`);
3303
+ ids.add(id);
3304
+ }
3305
+ return OK;
3306
+ }
3307
+ function nodeProblem(node, id, options) {
3308
+ if (typeof node.component !== "string") return "component type is required";
3309
+ const entry = ownValue(options.manifest.components, node.component);
3310
+ if (!entry) return `unknown component "${node.component}"`;
3311
+ const { allowedComponents } = options;
3312
+ if (allowedComponents && !allowedComponents.names.has(node.component)) {
3313
+ const names = [...allowedComponents.names].join(", ") || "none";
3314
+ return `"${node.component}" is not allowed in target "${allowedComponents.target}"; use one of: ${names}`;
3315
+ }
3316
+ const { properties, required } = entry.props;
3317
+ const propNames = isRecord(properties) ? Object.keys(properties) : [];
3318
+ const props = Object.entries(node);
3319
+ for (const [key, value] of props) {
3320
+ if (key === "id" || key === "component") continue;
3321
+ if (key === "catalogId") {
3322
+ const reason = catalogProblem(value, options.manifest);
3323
+ if (reason) return `${key}: ${reason}`;
3324
+ continue;
3325
+ }
3326
+ if (key === "metadata") {
3327
+ if (!(isRecord(value) && (value.extensions === void 0 || isRecord(value.extensions)))) return "metadata must be { \"extensions\": { ... } }";
3328
+ continue;
3329
+ }
3330
+ if (key === "accessibility") {
3331
+ const reason = accessibilityProblem(value);
3332
+ if (reason) return `${key}: ${reason}`;
3333
+ continue;
3334
+ }
3335
+ if (ownValue(entry.events, key)) {
3336
+ const reason = actionBindingProblem(value, options);
3337
+ if (reason) return `${key}: ${reason}`;
3338
+ continue;
3339
+ }
3340
+ const slot = ownValue(entry.slots, key);
3341
+ if (slot) {
3342
+ const reason = slotProblem(value, slot, id);
3343
+ if (reason) return `${key}: ${reason}`;
3344
+ continue;
3345
+ }
3346
+ if (!propNames.includes(key)) return `unknown prop "${key}"`;
3347
+ if (isV09PathBinding(value)) return `${key}: ${V09_PATH_REASON}`;
3348
+ const call = findForbiddenCall(value, { allowValueFunctions: true });
3349
+ if (call !== void 0) return `${key}: ${call}; a data prop can call only ${VALUE_FUNCTION_LIST}`;
3350
+ }
3351
+ for (const ref of childRefsOf(entry.props)) {
3352
+ const reason = childRefProblem(node, ref, id);
3353
+ if (reason) return reason;
3354
+ }
3355
+ const requiredNames = Array.isArray(required) ? required : [];
3356
+ for (const name of requiredNames) if (typeof name === "string" && !(name in node)) return `missing required prop "${name}"`;
3357
+ }
3358
+ const ACCESSIBILITY_KEYS = [
3359
+ "label",
3360
+ "description",
3361
+ "live",
3362
+ "hidden"
3363
+ ];
3364
+ const LIVE_VALUES = [
3365
+ "off",
3366
+ "polite",
3367
+ "assertive"
3368
+ ];
3369
+ /**
3370
+ * Checks the `accessibility` of a component envelope: `label` and
3371
+ * `description` are strings or dynamic values, `live` is one of the ARIA
3372
+ * values, `hidden` is a boolean or a dynamic value.
3373
+ */
3374
+ function accessibilityProblem(value) {
3375
+ if (!isRecord(value)) return "must be { \"label\": \"...\", \"description\": \"...\", \"live\": \"polite\", \"hidden\": false }";
3376
+ const isDynamic = (field) => isPathBinding(field) || isCallBinding(field);
3377
+ for (const [key, field] of Object.entries(value)) {
3378
+ if (!ACCESSIBILITY_KEYS.includes(key)) return `unknown key "${key}"`;
3379
+ if (isV09PathBinding(field)) return `${key}: ${V09_PATH_REASON}`;
3380
+ if (isDynamic(field)) {
3381
+ const call = findForbiddenCall(field, { allowValueFunctions: true });
3382
+ if (call !== void 0) return `${key}: ${call}`;
3383
+ continue;
3384
+ }
3385
+ if (key === "live") {
3386
+ if (typeof field !== "string" || !LIVE_VALUES.includes(field)) return `live must be one of ${LIVE_VALUES.join(", ")}`;
3387
+ } else if (key === "hidden") {
3388
+ if (typeof field !== "boolean") return "hidden must be a boolean";
3389
+ } else if (typeof field !== "string") return `${key} must be a string`;
3390
+ }
3391
+ }
3392
+ function actionBindingProblem(value, options) {
3393
+ if (!isRecord(value)) return "must be an action object";
3394
+ const keys = Object.keys(value);
3395
+ if (!(keys.length === 1 && (keys[0] === "functionCall" || keys[0] === "event"))) return "must be { \"event\": ... } or { \"functionCall\": ... }";
3396
+ if (keys[0] === "functionCall") return functionCallProblem(value.functionCall, "functionCall", options);
3397
+ return eventProblem(value.event);
3398
+ }
3399
+ /**
3400
+ * Checks `{ "@call": "<function>", "args": { ... } }`. `label` names the
3401
+ * field in the reason.
3402
+ */
3403
+ function functionCallProblem(call, label, options) {
3404
+ if (!isRecord(call)) return `${label} must be { "@call": "<function>", "args": { ... } }`;
3405
+ const name = call["@call"];
3406
+ if (typeof name !== "string" || !name) return typeof call.call === "string" ? `${label} names the function with "@call", not "call"` : `${label}["@call"] must be a function name`;
3407
+ const { args } = call;
3408
+ if (args !== void 0 && !isRecord(args)) return `${label}.args must be an object`;
3409
+ const catalogReason = catalogProblem(call.catalogId, options.manifest);
3410
+ if (catalogReason) return `${label}: ${catalogReason}`;
3411
+ const argEntries = Object.entries(args !== null && args !== void 0 ? args : {});
3412
+ for (const [key, arg] of argEntries) if (isV09PathBinding(arg)) return `${label}.args.${key}: ${V09_PATH_REASON}`;
3413
+ const appFunctions = options.functions;
3414
+ const declared = appFunctions !== void 0 && hasOwn(appFunctions, name) ? appFunctions[name] : void 0;
3415
+ const builtIn = declared === void 0 && hasOwn(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
3416
+ if (declared === void 0 && builtIn === void 0) return appFunctions === void 0 ? void 0 : `function "${name}" is not exposed to generative UI`;
3417
+ if (declared === void 0 && appFunctions === void 0) return void 0;
3418
+ return callerProblem(name, declared !== null && declared !== void 0 ? declared : builtIn, label.startsWith("callRendererFunction") ? "agent" : "renderer");
3419
+ }
3420
+ /**
3421
+ * Why `caller` may not call a function with these permissions, or
3422
+ * `undefined` when it may. The dispatcher gives the same reasons at run
3423
+ * time, for the calls that are not validated against a function list.
3424
+ */
3425
+ function callerProblem(name, fn, caller) {
3426
+ const callers = functionCallers(fn);
3427
+ if (caller === "agent" && !callers.agent) return fn.requiresUserActivation ? `function "${name}" runs only from a user gesture; the agent cannot call it` : `function "${name}" runs only in the UI (allowedCallers "rendererOnly"); the agent cannot call it`;
3428
+ if (caller === "renderer" && !callers.renderer) return `function "${name}" runs only for the agent (allowedCallers "agentOnly"); the UI cannot call it`;
3429
+ }
3430
+ function eventProblem(event) {
3431
+ if (!isRecord(event) || typeof event.name !== "string" || !event.name) return "event.name is required";
3432
+ const { userMessage, context } = event;
3433
+ if (!(userMessage === void 0 || typeof userMessage === "string" || isPathBinding(userMessage) || isRecord(userMessage) && typeof userMessage["@call"] === "string" && findForbiddenCall(userMessage, { allowValueFunctions: true }) === void 0)) return isV09PathBinding(userMessage) ? `event.userMessage: ${V09_PATH_REASON}` : "event.userMessage must be a string, {\"@path\": \"/x\"} or a function value";
3434
+ if (context === void 0) return void 0;
3435
+ if (!isRecord(context)) return "event.context must be an object";
3436
+ const entries = Object.entries(context);
3437
+ for (const [key, entry] of entries) {
3438
+ if (isV09PathBinding(entry)) return `event.context.${key}: ${V09_PATH_REASON}`;
3439
+ const call = findForbiddenCall(entry, { allowValueFunctions: true });
3440
+ if (call !== void 0) return `event.context.${key}: ${call}; a context value can call only ${VALUE_FUNCTION_LIST}`;
3441
+ }
3442
+ }
3443
+ function slotProblem(value, kind, ownId) {
3444
+ const isTemplate = isRecord(value) && "componentId" in value;
3445
+ if (kind === "single" && isTemplate) return "a template { \"componentId\", \"path\" } is only allowed in a \"multiple\" slot";
3446
+ if (kind === "multiple" && isTemplate) return templateProblem(value, ownId);
3447
+ if (kind === "multiple" && !Array.isArray(value)) return "must be an array of component ids or a template { \"componentId\", \"path\" }";
3448
+ const ids = kind === "multiple" && Array.isArray(value) ? value : [value];
3449
+ for (const id of ids) {
3450
+ if (typeof id !== "string" || !id) return "must reference component ids (strings)";
3451
+ if (id === ownId) return "a component cannot be its own child";
3452
+ }
3453
+ }
3454
+ function templateProblem(template, ownId) {
3455
+ if (!Object.keys(template).every((key) => key === "componentId" || key === "path")) return "a template takes only \"componentId\" and \"path\"";
3456
+ const { componentId, path } = template;
3457
+ if (typeof componentId !== "string" || !componentId) return "template componentId must be a component id";
3458
+ if (componentId === ownId) return "a component cannot be its own child";
3459
+ if (typeof path !== "string" || !path) return "template path must be a JSON pointer or a relative path";
3460
+ return pathProblem(path, "template path");
3461
+ }
3462
+ const VALUE_FUNCTION_LIST = `@index and the built-in functions (${Object.keys(GENERATIVE_UI_FUNCTIONS).filter(isA2UIValueFunction).join(", ")})`;
3463
+ /**
3464
+ * The reason for the first function call in `value` that a data value may
3465
+ * not make, at any depth, or `undefined`. A data value may call `@index`
3466
+ * and, with `allowValueFunctions`, the basic functions that need no user
3467
+ * gesture; the renderer resolves those. An app function, `openUrl`, or an
3468
+ * event binding is not a value.
3469
+ */
3470
+ function findForbiddenCall(value, options) {
3471
+ if (Array.isArray(value)) {
3472
+ for (const item of value) {
3473
+ const reason = findForbiddenCall(item, options);
3474
+ if (reason !== void 0) return reason;
3475
+ }
3476
+ return;
3477
+ }
3478
+ if (!isRecord(value)) return void 0;
3479
+ if (isIndexCall(value)) return void 0;
3480
+ if (value["@call"] === "@index") return "@index takes only an offset";
3481
+ if (typeof value.call === "string") return "name the function with \"@call\", not \"call\"";
3482
+ if ("functionCall" in value) return "an event binding is not a value";
3483
+ const name = value["@call"];
3484
+ if (typeof name === "string") {
3485
+ if (!options.allowValueFunctions || !isA2UIValueFunction(name)) return isA2UIBasicFunction(name) ? `"${name}" runs only from an event` : `"${name}" is not a basic function`;
3486
+ const args = value.args;
3487
+ if (args !== void 0 && !isRecord(args)) return `the args of "${name}" must be an object`;
3488
+ return args === void 0 ? void 0 : findForbiddenCall(args, options);
3489
+ }
3490
+ for (const item of Object.values(value)) {
3491
+ const reason = findForbiddenCall(item, options);
3492
+ if (reason !== void 0) return reason;
3493
+ }
3494
+ }
3495
+ const childRefCache = /* @__PURE__ */ new WeakMap();
3496
+ /** The component references of a props schema, computed once per schema. */
3497
+ function childRefsOf(props) {
3498
+ let refs = childRefCache.get(props);
3499
+ if (!refs) {
3500
+ refs = collectChildRefs(props);
3501
+ childRefCache.set(props, refs);
3502
+ }
3503
+ return refs;
3504
+ }
3505
+ /**
3506
+ * Checks the component ids at one reference of a node: a typed `child()`
3507
+ * or `childList()` prop, at any depth. A missing key is fine; the props
3508
+ * schema reports a required one.
3509
+ */
3510
+ function childRefProblem(node, ref, ownId) {
3511
+ const label = ref.path.filter((step) => step !== "*").join(".");
3512
+ const isDynamic = (value) => isPathBinding(value) || isRecord(value) && "@call" in value;
3513
+ const visit = (value, steps) => {
3514
+ if (isDynamic(value)) return void 0;
3515
+ if (steps.length === 0) {
3516
+ const reason = slotProblem(value, ref.kind, ownId);
3517
+ return reason ? `${label}: ${reason}` : void 0;
3518
+ }
3519
+ const [head, ...rest] = steps;
3520
+ if (head === "*") {
3521
+ if (!Array.isArray(value)) return void 0;
3522
+ for (const item of value) {
3523
+ const reason = visit(item, rest);
3524
+ if (reason) return reason;
3525
+ }
3526
+ return;
3527
+ }
3528
+ if (!isRecord(value) || !hasOwn(value, head)) return void 0;
3529
+ return visit(value[head], rest);
3530
+ };
3531
+ return visit(node, ref.path);
3532
+ }
3533
+
3534
+ //#endregion
3535
+ //#region src/generative-ui/render-ui-args.ts
3536
+ /**
3537
+ * Reads `target` and every complete `operations[]` element from a possibly
3538
+ * truncated `render_ui` argument string.
3539
+ */
3540
+ function extractRenderUIArgs(text) {
3541
+ return new RenderUIArgsScanner().scan(text);
3542
+ }
3543
+ /**
3544
+ * The parser of {@link extractRenderUIArgs}, with its state kept between
3545
+ * calls. Each call scans only the text after the text it scanned before, so
3546
+ * a streamed argument string is scanned once in total.
3547
+ */
3548
+ var RenderUIArgsScanner = class {
3549
+ constructor() {
3550
+ this.result = { operations: [] };
3551
+ this.stack = [];
3552
+ this.inString = false;
3553
+ this.escaped = false;
3554
+ this.stringStart = -1;
3555
+ this.pendingKey = null;
3556
+ this.currentKey = null;
3557
+ this.expectingValue = false;
3558
+ this.inOperations = false;
3559
+ this.elementStart = -1;
3560
+ this.scanned = 0;
3561
+ }
3562
+ /**
3563
+ * Scans `text` from where the last call stopped.
3564
+ *
3565
+ * @param text - The whole text so far. It starts with the text of the
3566
+ * last call.
3567
+ * @returns The result so far. It is the same object on each call.
3568
+ */
3569
+ scan(text) {
3570
+ const { result, stack } = this;
3571
+ let { inString, escaped, stringStart, pendingKey, currentKey, expectingValue, inOperations, elementStart } = this;
3572
+ for (let i = this.scanned; i < text.length; i++) {
3573
+ const ch = text[i];
3574
+ if (inString) {
3575
+ if (escaped) escaped = false;
3576
+ else if (ch === "\\") escaped = true;
3577
+ else if (ch === "\"") {
3578
+ inString = false;
3579
+ if (stack.length === 1) {
3580
+ const literal = text.slice(stringStart, i + 1);
3581
+ if (expectingValue) {
3582
+ if (currentKey === "target") try {
3583
+ result.target = JSON.parse(literal);
3584
+ } catch (_unused) {}
3585
+ expectingValue = false;
3586
+ } else pendingKey = literal;
3587
+ }
3588
+ }
3589
+ continue;
3590
+ }
3591
+ switch (ch) {
3592
+ case "\"":
3593
+ inString = true;
3594
+ stringStart = i;
3595
+ break;
3596
+ case ":":
3597
+ if (stack.length === 1 && pendingKey !== null) {
3598
+ try {
3599
+ currentKey = JSON.parse(pendingKey);
3600
+ } catch (_unused2) {
3601
+ currentKey = null;
3602
+ }
3603
+ pendingKey = null;
3604
+ expectingValue = true;
3605
+ }
3606
+ break;
3607
+ case ",":
3608
+ if (stack.length === 1) {
3609
+ expectingValue = false;
3610
+ currentKey = null;
3611
+ }
3612
+ break;
3613
+ case "{":
3614
+ if (inOperations && stack.length === 2) elementStart = i;
3615
+ stack.push("{");
3616
+ break;
3617
+ case "[":
3618
+ if (stack.length === 1 && expectingValue && currentKey === "operations") inOperations = true;
3619
+ stack.push("[");
3620
+ break;
3621
+ case "}":
3622
+ case "]":
3623
+ stack.pop();
3624
+ if (ch === "}" && inOperations && stack.length === 2 && elementStart >= 0) {
3625
+ result.operations.push(parseObject(text.slice(elementStart, i + 1)));
3626
+ elementStart = -1;
3627
+ }
3628
+ if (ch === "]" && inOperations && stack.length === 1) {
3629
+ inOperations = false;
3630
+ expectingValue = false;
3631
+ }
3632
+ break;
3633
+ }
3634
+ }
3635
+ this.inString = inString;
3636
+ this.escaped = escaped;
3637
+ this.stringStart = stringStart;
3638
+ this.pendingKey = pendingKey;
3639
+ this.currentKey = currentKey;
3640
+ this.expectingValue = expectingValue;
3641
+ this.inOperations = inOperations;
3642
+ this.elementStart = elementStart;
3643
+ this.scanned = text.length;
3644
+ if (elementStart >= 0) result.incompleteOperation = true;
3645
+ else delete result.incompleteOperation;
3646
+ return result;
3647
+ }
3648
+ };
3649
+ function parseObject(raw) {
3650
+ try {
3651
+ const value = JSON.parse(raw);
3652
+ return isRecord(value) ? value : null;
3653
+ } catch (_unused3) {
3654
+ return null;
3655
+ }
3656
+ }
3657
+ /** Feeds streamed argument deltas and reports operations not yet seen. */
3658
+ var RenderUIArgsStream = class {
3659
+ constructor() {
3660
+ this.buffer = "";
3661
+ this.emitted = 0;
3662
+ this.incomplete = false;
3663
+ this.scanner = new RenderUIArgsScanner();
3664
+ }
3665
+ push(delta) {
3666
+ this.buffer += delta;
3667
+ const { target, operations, incompleteOperation } = this.scanner.scan(this.buffer);
3668
+ const newOperations = operations.slice(this.emitted);
3669
+ this.emitted = operations.length;
3670
+ this.incomplete = incompleteOperation === true;
3671
+ return {
3672
+ target,
3673
+ newOperations
3674
+ };
3675
+ }
3676
+ /** Every argument delta received so far, concatenated. */
3677
+ get text() {
3678
+ return this.buffer;
3679
+ }
3680
+ /**
3681
+ * True when the text received so far ends inside an `operations[]` element.
3682
+ * Once the tool call has ended, that element was truncated.
3683
+ */
3684
+ get hasIncompleteOperation() {
3685
+ return this.incomplete;
3686
+ }
3687
+ };
3688
+
3689
+ //#endregion
3690
+ //#region src/generative-ui/prompt.ts
3691
+ const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
3692
+ /** Most characters of the user values of one surface in the guide. */
3693
+ const MAX_USER_VALUES_LENGTH = 500;
3694
+ /** Cuts long text and marks the cut with "...". */
3695
+ function shorten(text) {
3696
+ return text.length > MAX_USER_VALUES_LENGTH ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...` : text;
3697
+ }
3698
+ /**
3699
+ * The guide that the runtime adds as a context entry to a tool-transport run:
3700
+ * the `render_ui` rules, the targets, components, functions, and surfaces of
3701
+ * the manifest. It is in shared so that the inspector shows the same text.
3702
+ */
3703
+ function buildGenerativeUIPrompt(manifest) {
3704
+ const targets = manifest.targets.map((t) => {
3705
+ const place = t.kind === "chat" ? "inside the chat transcript" : "a named area of the app";
3706
+ const limit = t.components ? `; only ${t.components.join(", ") || "no components"}` : "";
3707
+ const description = t.description ? `: ${t.description}` : "";
3708
+ return `- "${t.id}" (${place}${limit})${description}`;
3709
+ }).join("\n");
3710
+ const components = Object.entries(manifest.components).map(([name, c]) => {
3711
+ const lines = [`- **${name}**${c.description ? `: ${c.description}` : ""}`, ` props: ${JSON.stringify(c.props)}`];
3712
+ if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
3713
+ if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
3714
+ return lines.join("\n");
3715
+ }).join("\n");
3716
+ const functions = Object.entries(manifest.functions).map(([name, f]) => {
3717
+ const signature = f.parameters.description;
3718
+ const args = typeof signature === "string" && signature.startsWith("{") && Object.keys(f.parameters).length === 2 ? signature : JSON.stringify(f.parameters);
3719
+ const callers = functionCallers(f);
3720
+ return `- **${name}**${callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? callers.renderer ? " (UI or agent)" : " (agent only)" : ""}${f.description ? `: ${f.description}` : ""}\n args: ${args}`;
3721
+ }).join("\n");
3722
+ const surfaces = Object.entries(manifest.surfaces).map(([id, s]) => {
3723
+ var _s$rejected;
3724
+ const state = s.status === "deleted" ? ", deleted: never use this id again" : s.status === "failed" ? ", not created: send a corrected createSurface with this id" : "";
3725
+ const lines = [`- "${id}" (target "${s.target}"${state})`];
3726
+ if (s.dataModel) lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);
3727
+ for (const rejection of (_s$rejected = s.rejected) !== null && _s$rejected !== void 0 ? _s$rejected : []) lines.push(` rejected: ${rejection}`);
3728
+ return lines.join("\n");
3729
+ }).join("\n");
3730
+ const surfaceNotes = Object.values(manifest.surfaces).some((s) => {
3731
+ var _s$rejected$length, _s$rejected2;
3732
+ return s.dataModel !== void 0 || ((_s$rejected$length = (_s$rejected2 = s.rejected) === null || _s$rejected2 === void 0 ? void 0 : _s$rejected2.length) !== null && _s$rejected$length !== void 0 ? _s$rejected$length : 0) > 0;
3733
+ }) ? "User values are what the user entered, by path. Your writes to those paths are ignored. Rejected operations were dropped: send them again with the problem fixed.\n" : "";
3734
+ const { functions: hasFunctions, events, templates, checks } = generativeUIGuideFeatures(manifest);
3735
+ const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;
3736
+ const operations = [
3737
+ "{\"version\":\"v1.0\",\"createSurface\":{\"surfaceId\":\"<new id>\",\"dataModel\":{...},\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"<child id>\"]}]}}: the first operation of a new surface. \"dataModel\" and \"components\" are optional.",
3738
+ "{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
3739
+ "{\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"<id>\",\"path\":\"/some/path\",\"value\":<json>}}: set the value at \"path\". Always give \"value\". \"value\":null deletes the key at \"path\".",
3740
+ "{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
3741
+ ...agentCalls ? ["{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."] : []
3742
+ ];
3743
+ const rules = [
3744
+ "Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
3745
+ "A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
3746
+ "Stream progressively: put the initial data in \"dataModel\" and the root in \"components\" of the createSurface operation, then send one updateComponents operation per child, so the UI appears while you are still writing. The root must already list the ids of its children in its slot props (for example \"children\":[\"card-1\",\"card-2\"]), even though the children come later. A component that no slot references is never shown.",
3747
+ "Updating a component replaces all of its props, so resend every prop.",
3748
+ "Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
3749
+ ...events ? [hasFunctions ? "Event props take an action. {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}} runs an app function in the browser immediately, and you are not told about it. {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\". Only call functions listed below." : "Event props take an action: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\"."] : [],
3750
+ "To show a different view, create a new surface with a new surfaceId (for example, a checkout form after a cart summary). Update an existing surface only when the user asks to change that same view: then do not send createSurface, use its surfaceId, and pass its existing target. Never reuse an earlier chat surface for a different view, because that replaces the earlier UI and anything the user typed into it.",
3751
+ "Never use a surfaceId again, also after deleteSurface.",
3752
+ "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Only call functions listed below. formatString interpolates ${/path} and ${fn(arg: value)} in its value.",
3753
+ "${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}.",
3754
+ "For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
3755
+ ...checks ? ["Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks."] : [],
3756
+ ...templates ? ["To repeat a component for each item of a list, give a multiple slot a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}. Inside the template, paths are relative to the item (\"name\", not \"/name\"). {\"@call\":\"@index\"} gives the position of the item, from 0; {\"@call\":\"@index\",\"args\":{\"offset\":1}} counts from 1."] : [],
3757
+ ...agentCalls ? ["Give every callRendererFunction a new functionCallId. Call only a function marked (UI or agent) or (agent only); a function with no mark is for the UI only. A function marked (agent only) is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you in a new turn, as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Do not wait for the result in this reply, and do not guess it."] : []
3758
+ ];
3759
+ return [
3760
+ `## Generative UI
3761
+ Call \`${GENERATIVE_UI_RENDER_TOOL}\` to show UI. Arguments: \`target\` first, then \`operations\` (A2UI v1.0 operations, applied in order).
3762
+
3763
+ ${GENERATIVE_UI_WHEN_TO_SHOW}
3764
+
3765
+ Every operation has "version":"v1.0" and exactly one of:
3766
+ ${operations.map((op) => `- ${op}`).join("\n")}
3767
+
3768
+ Rules:
3769
+ ${rules.map((rule, index) => `${index + 1}. ${rule}`).join("\n")}`,
3770
+ `### Targets\n${targets || "- none"}`,
3771
+ `### Components\n${components || "- none"}`,
3772
+ `### Functions\n${functions || "- none"}`,
3773
+ `### Existing surfaces\n${surfaceNotes}${surfaces || "- none"}`
3774
+ ].join("\n\n");
3775
+ }
3776
+
3777
+ //#endregion
3778
+ //#region src/index.ts
3779
+ const COPILOTKIT_VERSION = version;
3780
+ /** Read a record value without traversing its prototype chain. */
3781
+ function getOwnRecordValue(record, key) {
3782
+ return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : void 0;
3783
+ }
3784
+ /** Legacy UI surfaces that remain available for every active entitlement. */
3785
+ function isLegacyUiFeature(feature) {
3786
+ return feature === "chat" || feature === "popup" || feature === "sidebar";
3787
+ }
3788
+ /**
3789
+ * Client-safe license context factory, driven by the license authority the
3790
+ * runtime reports via /info.
3791
+ *
3792
+ * A ready managed entitlement is authoritative in both directions. A ready
3793
+ * active self-hosted entitlement is also authoritative, while an inactive
3794
+ * self-hosted response preserves the legacy signed-license fallback. Active
3795
+ * entitlements supply feature grants and limits; authoritative inactive
3796
+ * entitlements deny every feature and limit. Older runtimes that report only a
3797
+ * status retain the legacy behavior: features are enabled unless the status is
3798
+ * "expired" or "invalid", and no limits are reported. This is inlined here to
3799
+ * avoid importing the full license-verifier bundle (which depends on Node's
3800
+ * `crypto`) into browser bundles.
3801
+ */
3802
+ function createLicenseContextValue(status, runtimeEntitlements) {
3803
+ const readyEntitlement = (runtimeEntitlements === null || runtimeEntitlements === void 0 ? void 0 : runtimeEntitlements.status) === "ready" ? runtimeEntitlements.entitlement : null;
3804
+ const hasUsableSelfHostedLegacyFallback = readyEntitlement && !readyEntitlement.active && readyEntitlement.source === "selfHostedDeploymentLicense" && (status === "valid" || status === "expiring");
3805
+ const featureAuthority = readyEntitlement && !hasUsableSelfHostedLegacyFallback ? readyEntitlement : null;
3806
+ const activeEntitlement = (featureAuthority === null || featureAuthority === void 0 ? void 0 : featureAuthority.active) ? featureAuthority : null;
3807
+ const resolvedStatus = activeEntitlement ? "valid" : (readyEntitlement === null || readyEntitlement === void 0 ? void 0 : readyEntitlement.source) === "managedOrgSubscription" || (readyEntitlement === null || readyEntitlement === void 0 ? void 0 : readyEntitlement.source) === "awsMarketplaceDeploymentLicense" ? "none" : featureAuthority ? status !== null && status !== void 0 ? status : "none" : status !== null && status !== void 0 ? status : null;
3808
+ const featuresEnabled = resolvedStatus !== "expired" && resolvedStatus !== "invalid";
3809
+ return {
3810
+ status: resolvedStatus,
3811
+ license: null,
3812
+ checkFeature: (feature) => {
3813
+ var _getOwnRecordValue;
3814
+ return featureAuthority ? activeEntitlement ? feature === "threads" && Object.prototype.hasOwnProperty.call(activeEntitlement.limits, "threads.max_count") ? true : (_getOwnRecordValue = getOwnRecordValue(activeEntitlement.features, feature)) !== null && _getOwnRecordValue !== void 0 ? _getOwnRecordValue : isLegacyUiFeature(feature) : false : featuresEnabled;
3815
+ },
3816
+ getLimit: (feature) => {
3817
+ var _getOwnRecordValue2;
3818
+ return activeEntitlement ? (_getOwnRecordValue2 = getOwnRecordValue(activeEntitlement.limits, feature)) !== null && _getOwnRecordValue2 !== void 0 ? _getOwnRecordValue2 : null : null;
3819
+ }
3820
+ };
3821
+ }
3822
+
3823
+ //#endregion
3824
+ exports.A2UI_BASIC_FUNCTIONS = A2UI_BASIC_FUNCTIONS;
3825
+ exports.A2UI_CHILD_LIST_MARK = A2UI_CHILD_LIST_MARK;
3826
+ exports.A2UI_CHILD_LIST_REF = A2UI_CHILD_LIST_REF;
3827
+ exports.A2UI_COMPONENT_ENVELOPE_KEYS = A2UI_COMPONENT_ENVELOPE_KEYS;
3828
+ exports.A2UI_COMPONENT_ID_MARK = A2UI_COMPONENT_ID_MARK;
3829
+ exports.A2UI_COMPONENT_ID_REF = A2UI_COMPONENT_ID_REF;
3830
+ exports.A2UI_DEFAULT_DESIGN_GUIDELINES = A2UI_DEFAULT_DESIGN_GUIDELINES;
3831
+ exports.A2UI_DEFAULT_GENERATION_GUIDELINES = A2UI_DEFAULT_GENERATION_GUIDELINES;
3832
+ exports.A2UI_INDEX_FUNCTION = A2UI_INDEX_FUNCTION;
3833
+ exports.A2UI_VERSION = A2UI_VERSION;
3834
+ exports.AG_UI_CHANNEL_EVENT = AG_UI_CHANNEL_EVENT;
3835
+ exports.ALL_GENERATIVE_UI_GUIDE_FEATURES = ALL_GENERATIVE_UI_GUIDE_FEATURES;
3836
+ exports.BANNER_ERROR_NAMES = BANNER_ERROR_NAMES;
3837
+ exports.COPILOTKIT_FORWARDED_PROPS_KEY = COPILOTKIT_FORWARDED_PROPS_KEY;
3838
+ exports.COPILOTKIT_FUNCTIONS = COPILOTKIT_FUNCTIONS;
3839
+ exports.COPILOTKIT_UI_ENVELOPE_FORMAT = COPILOTKIT_UI_ENVELOPE_FORMAT;
3840
+ exports.COPILOTKIT_VERSION = COPILOTKIT_VERSION;
3841
+ exports.COPILOT_CLOUD_API_URL = COPILOT_CLOUD_API_URL;
3842
+ exports.COPILOT_CLOUD_CHAT_URL = COPILOT_CLOUD_CHAT_URL;
3843
+ exports.COPILOT_CLOUD_ERROR_NAMES = COPILOT_CLOUD_ERROR_NAMES;
3844
+ exports.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER = COPILOT_CLOUD_PUBLIC_API_KEY_HEADER;
3845
+ exports.COPILOT_CLOUD_VERSION = COPILOT_CLOUD_VERSION;
3846
+ exports.ConfigurationError = ConfigurationError;
3847
+ exports.ConsoleColors = ConsoleColors;
3848
+ exports.ConsoleStyles = ConsoleStyles;
3849
+ exports.CopilotKitAgentDiscoveryError = CopilotKitAgentDiscoveryError;
3850
+ exports.CopilotKitApiDiscoveryError = CopilotKitApiDiscoveryError;
3851
+ exports.CopilotKitError = CopilotKitError;
3852
+ exports.CopilotKitErrorCode = CopilotKitErrorCode;
3853
+ exports.CopilotKitLowLevelError = CopilotKitLowLevelError;
3854
+ exports.CopilotKitMisuseError = CopilotKitMisuseError;
3855
+ exports.CopilotKitRemoteEndpointDiscoveryError = CopilotKitRemoteEndpointDiscoveryError;
3856
+ exports.CopilotKitVersionMismatchError = CopilotKitVersionMismatchError;
3857
+ exports.DEFAULT_AGENT_ID = DEFAULT_AGENT_ID;
3858
+ exports.ERROR_CONFIG = ERROR_CONFIG;
3859
+ exports.ERROR_NAMES = ERROR_NAMES;
3860
+ exports.ErrorVisibility = ErrorVisibility;
3861
+ exports.GENERATE_SANDBOXED_UI_DESCRIPTION = GENERATE_SANDBOXED_UI_DESCRIPTION;
3862
+ exports.GENERATIVE_UI_ACTIVITY_TYPE = GENERATIVE_UI_ACTIVITY_TYPE;
3863
+ exports.GENERATIVE_UI_AGENT_FUNCTION_CALLS = GENERATIVE_UI_AGENT_FUNCTION_CALLS;
3864
+ exports.GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON = GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON;
3865
+ exports.GENERATIVE_UI_CHAT_TARGET = GENERATIVE_UI_CHAT_TARGET;
3866
+ exports.GENERATIVE_UI_CONTEXT_DESCRIPTION = GENERATIVE_UI_CONTEXT_DESCRIPTION;
3867
+ exports.GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS = GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;
3868
+ exports.GENERATIVE_UI_FUNCTIONS = GENERATIVE_UI_FUNCTIONS;
3869
+ exports.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE = GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE;
3870
+ exports.GENERATIVE_UI_MARKDOWN_GUIDELINES = GENERATIVE_UI_MARKDOWN_GUIDELINES;
3871
+ exports.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION;
3872
+ exports.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION = GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION;
3873
+ exports.GENERATIVE_UI_MAX_REJECTION_LENGTH = GENERATIVE_UI_MAX_REJECTION_LENGTH;
3874
+ exports.GENERATIVE_UI_MAX_SUMMARY_REJECTIONS = GENERATIVE_UI_MAX_SUMMARY_REJECTIONS;
3875
+ exports.GENERATIVE_UI_MAX_TARGET_COMPONENTS = GENERATIVE_UI_MAX_TARGET_COMPONENTS;
3876
+ exports.GENERATIVE_UI_RENDER_TOOL = GENERATIVE_UI_RENDER_TOOL;
3877
+ exports.GENERATIVE_UI_ROOT_ID = GENERATIVE_UI_ROOT_ID;
3878
+ exports.MODEL_HOST_CLASSES = MODEL_HOST_CLASSES;
3879
+ exports.MissingPublicApiKeyError = MissingPublicApiKeyError;
3880
+ exports.RUNTIME_MODE_INTELLIGENCE = RUNTIME_MODE_INTELLIGENCE;
3881
+ exports.RUNTIME_MODE_SSE = RUNTIME_MODE_SSE;
3882
+ exports.RenderUIArgsStream = RenderUIArgsStream;
3883
+ exports.ResolvedCopilotKitError = ResolvedCopilotKitError;
3884
+ exports.Severity = Severity;
3885
+ exports.TELEMETRY_EMITTER_V1 = TELEMETRY_EMITTER_V1;
3886
+ exports.TELEMETRY_EMITTER_V2 = TELEMETRY_EMITTER_V2;
3887
+ exports.TELEMETRY_SURFACE_V1 = TELEMETRY_SURFACE_V1;
3888
+ exports.TELEMETRY_SURFACE_V2 = TELEMETRY_SURFACE_V2;
3889
+ exports.THREAD_ALREADY_RUNNING_ERROR_CODE = THREAD_ALREADY_RUNNING_ERROR_CODE;
3890
+ exports.TranscriptionErrorCode = TranscriptionErrorCode;
3891
+ exports.TranscriptionErrors = TranscriptionErrors;
3892
+ exports.UNSAMPLED_RATE = UNSAMPLED_RATE;
3893
+ exports.UpgradeRequiredError = UpgradeRequiredError;
3894
+ exports.actionParametersToJsonSchema = actionParametersToJsonSchema;
3895
+ exports.applyChildRefMarks = applyChildRefMarks;
3896
+ exports.buildGenerativeUIMarkdownGuidelines = buildGenerativeUIMarkdownGuidelines;
3897
+ exports.buildGenerativeUIPrompt = buildGenerativeUIPrompt;
3898
+ exports.callerProblem = callerProblem;
3899
+ exports.childIdsAtRefs = childIdsAtRefs;
3900
+ exports.childRefKind = childRefKind;
3901
+ exports.classifyModelHost = classifyModelHost;
3902
+ exports.collectChildRefs = collectChildRefs;
3903
+ exports.commitRowKeyStore = commitRowKeyStore;
3904
+ exports.computeSamplingMeta = computeSamplingMeta;
3905
+ exports.convertJsonSchemaToZodSchema = convertJsonSchemaToZodSchema;
3906
+ exports.copyToClipboard = copyToClipboard;
3907
+ exports.createAttachmentContent = createAttachmentContent;
3908
+ exports.createLicenseContextValue = createLicenseContextValue;
3909
+ exports.createRowKeyStore = createRowKeyStore;
3910
+ exports.createRunEventFinalizer = createRunEventFinalizer;
3911
+ exports.dataToUUID = dataToUUID;
3912
+ exports.ensureStructuredError = ensureStructuredError;
3913
+ exports.envelopeToManifest = envelopeToManifest;
3914
+ exports.exceedsMaxSize = exceedsMaxSize;
3915
+ exports.executeConditions = executeConditions;
3916
+ exports.extractRenderUIArgs = extractRenderUIArgs;
3917
+ exports.finalizeRunEvents = finalizeRunEvents;
3918
+ exports.firstNonBlankTelemetryId = firstNonBlankTelemetryId;
3919
+ exports.formatFileSize = formatFileSize;
3920
+ exports.functionCallers = functionCallers;
3921
+ exports.generateVideoThumbnail = generateVideoThumbnail;
3922
+ exports.generativeUIFunctionCallMessageId = generativeUIFunctionCallMessageId;
3923
+ exports.generativeUIGuideFeatures = generativeUIGuideFeatures;
3924
+ exports.generativeUISurfaceMessageId = generativeUISurfaceMessageId;
3925
+ exports.getDocumentIcon = getDocumentIcon;
3926
+ exports.getModalityFromMimeType = getModalityFromMimeType;
3927
+ exports.getOperationKind = getOperationKind;
3928
+ exports.getOperationSurfaceId = getOperationSurfaceId;
3929
+ exports.getPossibleVersionMismatch = getPossibleVersionMismatch;
3930
+ exports.getSourceUrl = getSourceUrl;
3931
+ exports.getZodParameters = getZodParameters;
3932
+ exports.hasBoundChildRef = hasBoundChildRef;
3933
+ exports.isA2UIBasicFunction = isA2UIBasicFunction;
3934
+ exports.isA2UIValueFunction = isA2UIValueFunction;
3935
+ exports.isActionBinding = isActionBinding;
3936
+ exports.isCallBinding = isCallBinding;
3937
+ exports.isIndexCall = isIndexCall;
3938
+ exports.isMacOS = isMacOS;
3939
+ exports.isPathBinding = isPathBinding;
3940
+ exports.isStructuredCopilotKitError = isStructuredCopilotKitError;
3941
+ exports.isTelemetryDisabled = isTelemetryDisabled;
3942
+ exports.isValidUUID = isValidUUID;
3943
+ exports.isValidationResult = isValidationResult;
3944
+ exports.jsonSchemaToActionParameters = jsonSchemaToActionParameters;
3945
+ exports.lambdaClient = lambdaClient;
3946
+ exports.logCopilotKitPlatformMessage = logCopilotKitPlatformMessage;
3947
+ exports.logStyled = logStyled;
3948
+ exports.logger = logger;
3949
+ exports.mapAtChildRef = mapAtChildRef;
3950
+ exports.matchesAcceptFilter = matchesAcceptFilter;
3951
+ exports.parseAndWarnTelemetryId = parseAndWarnTelemetryId;
3952
+ exports.parseInspectorLearningRequestV1 = parseInspectorLearningRequestV1;
3953
+ exports.parseInspectorLearningSnapshotV1 = parseInspectorLearningSnapshotV1;
3954
+ exports.parseInspectorLearningUrl = parseInspectorLearningUrl;
3955
+ exports.parseInspectorMetadataV1 = parseInspectorMetadataV1;
3956
+ exports.parseJson = parseJson;
3957
+ exports.parseTelemetryIdFromLicense = parseTelemetryIdFromLicense;
3958
+ exports.partialJSONParse = partialJSONParse;
3959
+ exports.phoenixExponentialBackoff = phoenixExponentialBackoff;
3960
+ exports.pruneRowKeyStore = pruneRowKeyStore;
3961
+ exports.publicApiKeyRequired = publicApiKeyRequired;
3962
+ exports.randomId = randomId;
3963
+ exports.randomUUID = randomUUID;
3964
+ exports.readBody = readBody;
3965
+ exports.readCopilotKitUIEnvelope = readCopilotKitUIEnvelope;
3966
+ exports.readFileAsBase64 = readFileAsBase64;
3967
+ exports.resolveDebugConfig = resolveDebugConfig;
3968
+ exports.resolveRowRenderKeys = resolveRowRenderKeys;
3969
+ exports.resolveRowRenderKeysById = resolveRowRenderKeysById;
3970
+ exports.safeParseToolArgs = safeParseToolArgs;
3971
+ exports.schemaToJsonSchema = schemaToJsonSchema;
3972
+ exports.shouldEnableInspector = shouldEnableInspector;
3973
+ exports.stripIntelligenceRoutingFields = stripIntelligenceRoutingFields;
3974
+ exports.styledConsole = styledConsole;
3975
+ exports.toA2UIActionMessage = toA2UIActionMessage;
3976
+ exports.tryMap = tryMap;
3977
+ exports.validateOperation = validateOperation;
3978
+ });
3979
+ //# sourceMappingURL=index.umd.js.map