@copilotkit/shared 2.0.0-rc.5 → 2.0.0-rc.51

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 (569) hide show
  1. package/README.md +4 -15
  2. package/dist/a2ui-envelope.cjs +3 -3
  3. package/dist/a2ui-envelope.cjs.map +1 -1
  4. package/dist/a2ui-envelope.d.cts +1 -1
  5. package/dist/a2ui-envelope.d.cts.map +1 -1
  6. package/dist/a2ui-envelope.d.mts +1 -1
  7. package/dist/a2ui-envelope.d.mts.map +1 -1
  8. package/dist/a2ui-envelope.mjs +3 -3
  9. package/dist/a2ui-envelope.mjs.map +1 -1
  10. package/dist/a2ui-prompts.cjs +21 -62
  11. package/dist/a2ui-prompts.cjs.map +1 -1
  12. package/dist/a2ui-prompts.d.cts +8 -1
  13. package/dist/a2ui-prompts.d.cts.map +1 -1
  14. package/dist/a2ui-prompts.d.mts +8 -1
  15. package/dist/a2ui-prompts.d.mts.map +1 -1
  16. package/dist/a2ui-prompts.mjs +22 -62
  17. package/dist/a2ui-prompts.mjs.map +1 -1
  18. package/dist/attachments/types.d.cts +1 -3
  19. package/dist/attachments/types.d.cts.map +1 -1
  20. package/dist/attachments/types.d.mts +1 -3
  21. package/dist/attachments/types.d.mts.map +1 -1
  22. package/dist/attachments/utils.cjs +16 -5
  23. package/dist/attachments/utils.cjs.map +1 -1
  24. package/dist/attachments/utils.d.cts +3 -1
  25. package/dist/attachments/utils.d.cts.map +1 -1
  26. package/dist/attachments/utils.d.mts +3 -1
  27. package/dist/attachments/utils.d.mts.map +1 -1
  28. package/dist/attachments/utils.mjs +16 -5
  29. package/dist/attachments/utils.mjs.map +1 -1
  30. package/dist/finalize-events.cjs +16 -0
  31. package/dist/finalize-events.cjs.map +1 -1
  32. package/dist/finalize-events.d.cts.map +1 -1
  33. package/dist/finalize-events.d.mts.map +1 -1
  34. package/dist/finalize-events.mjs +16 -0
  35. package/dist/finalize-events.mjs.map +1 -1
  36. package/dist/generative-ui/basic-functions.cjs +1 -1
  37. package/dist/generative-ui/basic-functions.cjs.map +1 -1
  38. package/dist/generative-ui/basic-functions.mjs +1 -1
  39. package/dist/generative-ui/basic-functions.mjs.map +1 -1
  40. package/dist/generative-ui/catalog/catalog-export.cjs +329 -0
  41. package/dist/generative-ui/catalog/catalog-export.cjs.map +1 -0
  42. package/dist/generative-ui/catalog/catalog-export.d.cts +92 -0
  43. package/dist/generative-ui/catalog/catalog-export.d.cts.map +1 -0
  44. package/dist/generative-ui/catalog/catalog-export.d.mts +92 -0
  45. package/dist/generative-ui/catalog/catalog-export.d.mts.map +1 -0
  46. package/dist/generative-ui/catalog/catalog-export.mjs +328 -0
  47. package/dist/generative-ui/catalog/catalog-export.mjs.map +1 -0
  48. package/dist/generative-ui/catalog/catalog.cjs +315 -0
  49. package/dist/generative-ui/catalog/catalog.cjs.map +1 -0
  50. package/dist/generative-ui/catalog/catalog.d.cts +407 -0
  51. package/dist/generative-ui/catalog/catalog.d.cts.map +1 -0
  52. package/dist/generative-ui/catalog/catalog.d.mts +407 -0
  53. package/dist/generative-ui/catalog/catalog.d.mts.map +1 -0
  54. package/dist/generative-ui/catalog/catalog.mjs +312 -0
  55. package/dist/generative-ui/catalog/catalog.mjs.map +1 -0
  56. package/dist/generative-ui/catalog/errors.cjs +13 -0
  57. package/dist/generative-ui/catalog/errors.cjs.map +1 -0
  58. package/dist/generative-ui/catalog/errors.d.cts +46 -0
  59. package/dist/generative-ui/catalog/errors.d.cts.map +1 -0
  60. package/dist/generative-ui/catalog/errors.d.mts +46 -0
  61. package/dist/generative-ui/catalog/errors.d.mts.map +1 -0
  62. package/dist/generative-ui/catalog/errors.mjs +12 -0
  63. package/dist/generative-ui/catalog/errors.mjs.map +1 -0
  64. package/dist/generative-ui/catalog/index.d.mts +6 -0
  65. package/dist/generative-ui/catalog/json-schema.cjs +16 -0
  66. package/dist/generative-ui/catalog/json-schema.cjs.map +1 -0
  67. package/dist/generative-ui/catalog/json-schema.d.cts +12 -0
  68. package/dist/generative-ui/catalog/json-schema.d.cts.map +1 -0
  69. package/dist/generative-ui/catalog/json-schema.d.mts +12 -0
  70. package/dist/generative-ui/catalog/json-schema.d.mts.map +1 -0
  71. package/dist/generative-ui/catalog/json-schema.mjs +16 -0
  72. package/dist/generative-ui/catalog/json-schema.mjs.map +1 -0
  73. package/dist/generative-ui/catalog/refs.cjs +21 -0
  74. package/dist/generative-ui/catalog/refs.cjs.map +1 -0
  75. package/dist/generative-ui/catalog/refs.d.cts +55 -0
  76. package/dist/generative-ui/catalog/refs.d.cts.map +1 -0
  77. package/dist/generative-ui/catalog/refs.d.mts +55 -0
  78. package/dist/generative-ui/catalog/refs.d.mts.map +1 -0
  79. package/dist/generative-ui/catalog/refs.mjs +18 -0
  80. package/dist/generative-ui/catalog/refs.mjs.map +1 -0
  81. package/dist/generative-ui/catalog/schema.cjs +74 -0
  82. package/dist/generative-ui/catalog/schema.cjs.map +1 -0
  83. package/dist/generative-ui/catalog/schema.d.cts +43 -0
  84. package/dist/generative-ui/catalog/schema.d.cts.map +1 -0
  85. package/dist/generative-ui/catalog/schema.d.mts +43 -0
  86. package/dist/generative-ui/catalog/schema.d.mts.map +1 -0
  87. package/dist/generative-ui/catalog/schema.mjs +68 -0
  88. package/dist/generative-ui/catalog/schema.mjs.map +1 -0
  89. package/dist/generative-ui/child-refs.cjs +3 -3
  90. package/dist/generative-ui/child-refs.cjs.map +1 -1
  91. package/dist/generative-ui/child-refs.d.cts.map +1 -1
  92. package/dist/generative-ui/child-refs.d.mts.map +1 -1
  93. package/dist/generative-ui/child-refs.mjs +3 -3
  94. package/dist/generative-ui/child-refs.mjs.map +1 -1
  95. package/dist/generative-ui/clone-value.cjs +364 -0
  96. package/dist/generative-ui/clone-value.cjs.map +1 -0
  97. package/dist/generative-ui/clone-value.d.cts +51 -0
  98. package/dist/generative-ui/clone-value.d.cts.map +1 -0
  99. package/dist/generative-ui/clone-value.d.mts +51 -0
  100. package/dist/generative-ui/clone-value.d.mts.map +1 -0
  101. package/dist/generative-ui/clone-value.mjs +363 -0
  102. package/dist/generative-ui/clone-value.mjs.map +1 -0
  103. package/dist/generative-ui/compact-schema.cjs +187 -0
  104. package/dist/generative-ui/compact-schema.cjs.map +1 -0
  105. package/dist/generative-ui/compact-schema.d.cts +55 -0
  106. package/dist/generative-ui/compact-schema.d.cts.map +1 -0
  107. package/dist/generative-ui/compact-schema.d.mts +55 -0
  108. package/dist/generative-ui/compact-schema.d.mts.map +1 -0
  109. package/dist/generative-ui/compact-schema.mjs +185 -0
  110. package/dist/generative-ui/compact-schema.mjs.map +1 -0
  111. package/dist/generative-ui/index.cjs +286 -0
  112. package/dist/generative-ui/index.d.cts +39 -0
  113. package/dist/generative-ui/index.d.mts +41 -0
  114. package/dist/generative-ui/index.mjs +40 -0
  115. package/dist/generative-ui/is-record.cjs +6 -1
  116. package/dist/generative-ui/is-record.cjs.map +1 -1
  117. package/dist/generative-ui/is-record.d.cts +8 -0
  118. package/dist/generative-ui/is-record.d.cts.map +1 -0
  119. package/dist/generative-ui/is-record.d.mts +8 -0
  120. package/dist/generative-ui/is-record.d.mts.map +1 -0
  121. package/dist/generative-ui/is-record.mjs +6 -2
  122. package/dist/generative-ui/is-record.mjs.map +1 -1
  123. package/dist/generative-ui/prompt-spec.cjs +225 -0
  124. package/dist/generative-ui/prompt-spec.cjs.map +1 -0
  125. package/dist/generative-ui/prompt-spec.d.cts +94 -0
  126. package/dist/generative-ui/prompt-spec.d.cts.map +1 -0
  127. package/dist/generative-ui/prompt-spec.d.mts +94 -0
  128. package/dist/generative-ui/prompt-spec.d.mts.map +1 -0
  129. package/dist/generative-ui/prompt-spec.mjs +220 -0
  130. package/dist/generative-ui/prompt-spec.mjs.map +1 -0
  131. package/dist/generative-ui/prompt.cjs +10 -36
  132. package/dist/generative-ui/prompt.cjs.map +1 -1
  133. package/dist/generative-ui/prompt.d.cts +2 -1
  134. package/dist/generative-ui/prompt.d.cts.map +1 -1
  135. package/dist/generative-ui/prompt.d.mts +2 -1
  136. package/dist/generative-ui/prompt.d.mts.map +1 -1
  137. package/dist/generative-ui/prompt.mjs +12 -38
  138. package/dist/generative-ui/prompt.mjs.map +1 -1
  139. package/dist/generative-ui/render-ui-args.cjs +1 -0
  140. package/dist/generative-ui/render-ui-args.cjs.map +1 -1
  141. package/dist/generative-ui/render-ui-args.d.cts.map +1 -1
  142. package/dist/generative-ui/render-ui-args.d.mts.map +1 -1
  143. package/dist/generative-ui/render-ui-args.mjs +1 -0
  144. package/dist/generative-ui/render-ui-args.mjs.map +1 -1
  145. package/dist/generative-ui/schema-render.cjs +243 -0
  146. package/dist/generative-ui/schema-render.cjs.map +1 -0
  147. package/dist/generative-ui/schema-render.d.cts +44 -0
  148. package/dist/generative-ui/schema-render.d.cts.map +1 -0
  149. package/dist/generative-ui/schema-render.d.mts +44 -0
  150. package/dist/generative-ui/schema-render.d.mts.map +1 -0
  151. package/dist/generative-ui/schema-render.mjs +240 -0
  152. package/dist/generative-ui/schema-render.mjs.map +1 -0
  153. package/dist/generative-ui/standard/chart-config.cjs +347 -0
  154. package/dist/generative-ui/standard/chart-config.cjs.map +1 -0
  155. package/dist/generative-ui/standard/chart-config.d.cts +97 -0
  156. package/dist/generative-ui/standard/chart-config.d.cts.map +1 -0
  157. package/dist/generative-ui/standard/chart-config.d.mts +97 -0
  158. package/dist/generative-ui/standard/chart-config.d.mts.map +1 -0
  159. package/dist/generative-ui/standard/chart-config.mjs +342 -0
  160. package/dist/generative-ui/standard/chart-config.mjs.map +1 -0
  161. package/dist/generative-ui/standard/chart.cjs +56 -0
  162. package/dist/generative-ui/standard/chart.cjs.map +1 -0
  163. package/dist/generative-ui/standard/chart.d.cts +62 -0
  164. package/dist/generative-ui/standard/chart.d.cts.map +1 -0
  165. package/dist/generative-ui/standard/chart.d.mts +62 -0
  166. package/dist/generative-ui/standard/chart.d.mts.map +1 -0
  167. package/dist/generative-ui/standard/chart.mjs +54 -0
  168. package/dist/generative-ui/standard/chart.mjs.map +1 -0
  169. package/dist/generative-ui/standard/checks.cjs +74 -0
  170. package/dist/generative-ui/standard/checks.cjs.map +1 -0
  171. package/dist/generative-ui/standard/checks.d.cts +56 -0
  172. package/dist/generative-ui/standard/checks.d.cts.map +1 -0
  173. package/dist/generative-ui/standard/checks.d.mts +56 -0
  174. package/dist/generative-ui/standard/checks.d.mts.map +1 -0
  175. package/dist/generative-ui/standard/checks.mjs +71 -0
  176. package/dist/generative-ui/standard/checks.mjs.map +1 -0
  177. package/dist/generative-ui/standard/components.cjs +23 -0
  178. package/dist/generative-ui/standard/components.cjs.map +1 -0
  179. package/dist/generative-ui/standard/components.d.cts +24 -0
  180. package/dist/generative-ui/standard/components.d.cts.map +1 -0
  181. package/dist/generative-ui/standard/components.d.mts +24 -0
  182. package/dist/generative-ui/standard/components.d.mts.map +1 -0
  183. package/dist/generative-ui/standard/components.mjs +22 -0
  184. package/dist/generative-ui/standard/components.mjs.map +1 -0
  185. package/dist/generative-ui/standard/composites.cjs +143 -0
  186. package/dist/generative-ui/standard/composites.cjs.map +1 -0
  187. package/dist/generative-ui/standard/composites.d.cts +233 -0
  188. package/dist/generative-ui/standard/composites.d.cts.map +1 -0
  189. package/dist/generative-ui/standard/composites.d.mts +233 -0
  190. package/dist/generative-ui/standard/composites.d.mts.map +1 -0
  191. package/dist/generative-ui/standard/composites.mjs +132 -0
  192. package/dist/generative-ui/standard/composites.mjs.map +1 -0
  193. package/dist/generative-ui/standard/data.cjs +176 -0
  194. package/dist/generative-ui/standard/data.cjs.map +1 -0
  195. package/dist/generative-ui/standard/data.d.cts +365 -0
  196. package/dist/generative-ui/standard/data.d.cts.map +1 -0
  197. package/dist/generative-ui/standard/data.d.mts +365 -0
  198. package/dist/generative-ui/standard/data.d.mts.map +1 -0
  199. package/dist/generative-ui/standard/data.mjs +167 -0
  200. package/dist/generative-ui/standard/data.mjs.map +1 -0
  201. package/dist/generative-ui/standard/declarations.cjs +40 -0
  202. package/dist/generative-ui/standard/declarations.cjs.map +1 -0
  203. package/dist/generative-ui/standard/declarations.d.cts +2570 -0
  204. package/dist/generative-ui/standard/declarations.d.cts.map +1 -0
  205. package/dist/generative-ui/standard/declarations.d.mts +2571 -0
  206. package/dist/generative-ui/standard/declarations.d.mts.map +1 -0
  207. package/dist/generative-ui/standard/declarations.mjs +39 -0
  208. package/dist/generative-ui/standard/declarations.mjs.map +1 -0
  209. package/dist/generative-ui/standard/feedback.cjs +97 -0
  210. package/dist/generative-ui/standard/feedback.cjs.map +1 -0
  211. package/dist/generative-ui/standard/feedback.d.cts +133 -0
  212. package/dist/generative-ui/standard/feedback.d.cts.map +1 -0
  213. package/dist/generative-ui/standard/feedback.d.mts +133 -0
  214. package/dist/generative-ui/standard/feedback.d.mts.map +1 -0
  215. package/dist/generative-ui/standard/feedback.mjs +90 -0
  216. package/dist/generative-ui/standard/feedback.mjs.map +1 -0
  217. package/dist/generative-ui/standard/index.d.mts +20 -0
  218. package/dist/generative-ui/standard/inputs.cjs +333 -0
  219. package/dist/generative-ui/standard/inputs.cjs.map +1 -0
  220. package/dist/generative-ui/standard/inputs.d.cts +1128 -0
  221. package/dist/generative-ui/standard/inputs.d.cts.map +1 -0
  222. package/dist/generative-ui/standard/inputs.d.mts +1128 -0
  223. package/dist/generative-ui/standard/inputs.d.mts.map +1 -0
  224. package/dist/generative-ui/standard/inputs.mjs +318 -0
  225. package/dist/generative-ui/standard/inputs.mjs.map +1 -0
  226. package/dist/generative-ui/standard/layout.cjs +289 -0
  227. package/dist/generative-ui/standard/layout.cjs.map +1 -0
  228. package/dist/generative-ui/standard/layout.d.cts +1974 -0
  229. package/dist/generative-ui/standard/layout.d.cts.map +1 -0
  230. package/dist/generative-ui/standard/layout.d.mts +1975 -0
  231. package/dist/generative-ui/standard/layout.d.mts.map +1 -0
  232. package/dist/generative-ui/standard/layout.mjs +269 -0
  233. package/dist/generative-ui/standard/layout.mjs.map +1 -0
  234. package/dist/generative-ui/standard/map-helpers.cjs +104 -0
  235. package/dist/generative-ui/standard/map-helpers.cjs.map +1 -0
  236. package/dist/generative-ui/standard/map-helpers.d.cts +88 -0
  237. package/dist/generative-ui/standard/map-helpers.d.cts.map +1 -0
  238. package/dist/generative-ui/standard/map-helpers.d.mts +88 -0
  239. package/dist/generative-ui/standard/map-helpers.d.mts.map +1 -0
  240. package/dist/generative-ui/standard/map-helpers.mjs +95 -0
  241. package/dist/generative-ui/standard/map-helpers.mjs.map +1 -0
  242. package/dist/generative-ui/standard/map.cjs +27 -0
  243. package/dist/generative-ui/standard/map.cjs.map +1 -0
  244. package/dist/generative-ui/standard/map.d.cts +31 -0
  245. package/dist/generative-ui/standard/map.d.cts.map +1 -0
  246. package/dist/generative-ui/standard/map.d.mts +31 -0
  247. package/dist/generative-ui/standard/map.d.mts.map +1 -0
  248. package/dist/generative-ui/standard/map.mjs +25 -0
  249. package/dist/generative-ui/standard/map.mjs.map +1 -0
  250. package/dist/generative-ui/standard/media.cjs +215 -0
  251. package/dist/generative-ui/standard/media.cjs.map +1 -0
  252. package/dist/generative-ui/standard/media.d.cts +396 -0
  253. package/dist/generative-ui/standard/media.d.cts.map +1 -0
  254. package/dist/generative-ui/standard/media.d.mts +396 -0
  255. package/dist/generative-ui/standard/media.d.mts.map +1 -0
  256. package/dist/generative-ui/standard/media.mjs +205 -0
  257. package/dist/generative-ui/standard/media.mjs.map +1 -0
  258. package/dist/generative-ui/standard/parameter-order.cjs +231 -0
  259. package/dist/generative-ui/standard/parameter-order.cjs.map +1 -0
  260. package/dist/generative-ui/standard/parameter-order.d.cts +84 -0
  261. package/dist/generative-ui/standard/parameter-order.d.cts.map +1 -0
  262. package/dist/generative-ui/standard/parameter-order.d.mts +84 -0
  263. package/dist/generative-ui/standard/parameter-order.d.mts.map +1 -0
  264. package/dist/generative-ui/standard/parameter-order.mjs +230 -0
  265. package/dist/generative-ui/standard/parameter-order.mjs.map +1 -0
  266. package/dist/generative-ui/standard/style-helpers.cjs +151 -0
  267. package/dist/generative-ui/standard/style-helpers.cjs.map +1 -0
  268. package/dist/generative-ui/standard/style-helpers.d.cts +56 -0
  269. package/dist/generative-ui/standard/style-helpers.d.cts.map +1 -0
  270. package/dist/generative-ui/standard/style-helpers.d.mts +56 -0
  271. package/dist/generative-ui/standard/style-helpers.d.mts.map +1 -0
  272. package/dist/generative-ui/standard/style-helpers.mjs +142 -0
  273. package/dist/generative-ui/standard/style-helpers.mjs.map +1 -0
  274. package/dist/generative-ui/standard/styles.cjs +62 -0
  275. package/dist/generative-ui/standard/styles.cjs.map +1 -0
  276. package/dist/generative-ui/standard/styles.d.cts +17 -0
  277. package/dist/generative-ui/standard/styles.d.cts.map +1 -0
  278. package/dist/generative-ui/standard/styles.d.mts +17 -0
  279. package/dist/generative-ui/standard/styles.d.mts.map +1 -0
  280. package/dist/generative-ui/standard/styles.mjs +60 -0
  281. package/dist/generative-ui/standard/styles.mjs.map +1 -0
  282. package/dist/generative-ui/standard/text.cjs +226 -0
  283. package/dist/generative-ui/standard/text.cjs.map +1 -0
  284. package/dist/generative-ui/standard/text.d.cts +522 -0
  285. package/dist/generative-ui/standard/text.d.cts.map +1 -0
  286. package/dist/generative-ui/standard/text.d.mts +522 -0
  287. package/dist/generative-ui/standard/text.d.mts.map +1 -0
  288. package/dist/generative-ui/standard/text.mjs +209 -0
  289. package/dist/generative-ui/standard/text.mjs.map +1 -0
  290. package/dist/generative-ui/standard/theme.cjs +115 -0
  291. package/dist/generative-ui/standard/theme.cjs.map +1 -0
  292. package/dist/generative-ui/standard/theme.d.cts +60 -0
  293. package/dist/generative-ui/standard/theme.d.cts.map +1 -0
  294. package/dist/generative-ui/standard/theme.d.mts +60 -0
  295. package/dist/generative-ui/standard/theme.d.mts.map +1 -0
  296. package/dist/generative-ui/standard/theme.mjs +112 -0
  297. package/dist/generative-ui/standard/theme.mjs.map +1 -0
  298. package/dist/generative-ui/standard/tokens.cjs +336 -0
  299. package/dist/generative-ui/standard/tokens.cjs.map +1 -0
  300. package/dist/generative-ui/standard/tokens.d.cts +76 -0
  301. package/dist/generative-ui/standard/tokens.d.cts.map +1 -0
  302. package/dist/generative-ui/standard/tokens.d.mts +76 -0
  303. package/dist/generative-ui/standard/tokens.d.mts.map +1 -0
  304. package/dist/generative-ui/standard/tokens.mjs +305 -0
  305. package/dist/generative-ui/standard/tokens.mjs.map +1 -0
  306. package/dist/generative-ui/standard/url.cjs +54 -0
  307. package/dist/generative-ui/standard/url.cjs.map +1 -0
  308. package/dist/generative-ui/standard/url.d.cts +32 -0
  309. package/dist/generative-ui/standard/url.d.cts.map +1 -0
  310. package/dist/generative-ui/standard/url.d.mts +32 -0
  311. package/dist/generative-ui/standard/url.d.mts.map +1 -0
  312. package/dist/generative-ui/standard/url.mjs +50 -0
  313. package/dist/generative-ui/standard/url.mjs.map +1 -0
  314. package/dist/generative-ui/thrown.cjs +69 -0
  315. package/dist/generative-ui/thrown.cjs.map +1 -0
  316. package/dist/generative-ui/thrown.d.cts +21 -0
  317. package/dist/generative-ui/thrown.d.cts.map +1 -0
  318. package/dist/generative-ui/thrown.d.mts +21 -0
  319. package/dist/generative-ui/thrown.d.mts.map +1 -0
  320. package/dist/generative-ui/thrown.mjs +67 -0
  321. package/dist/generative-ui/thrown.mjs.map +1 -0
  322. package/dist/generative-ui/types.cjs +2 -2
  323. package/dist/generative-ui/types.cjs.map +1 -1
  324. package/dist/generative-ui/types.d.cts +20 -7
  325. package/dist/generative-ui/types.d.cts.map +1 -1
  326. package/dist/generative-ui/types.d.mts +20 -7
  327. package/dist/generative-ui/types.d.mts.map +1 -1
  328. package/dist/generative-ui/types.mjs +2 -2
  329. package/dist/generative-ui/types.mjs.map +1 -1
  330. package/dist/generative-ui/validate-operation.cjs +2 -2
  331. package/dist/generative-ui/validate-operation.cjs.map +1 -1
  332. package/dist/generative-ui/validate-operation.mjs +2 -2
  333. package/dist/generative-ui/validate-operation.mjs.map +1 -1
  334. package/dist/index.cjs +18 -15
  335. package/dist/index.cjs.map +1 -1
  336. package/dist/index.d.cts +18 -17
  337. package/dist/index.d.cts.map +1 -1
  338. package/dist/index.d.mts +18 -17
  339. package/dist/index.d.mts.map +1 -1
  340. package/dist/index.mjs +10 -8
  341. package/dist/index.mjs.map +1 -1
  342. package/dist/index.umd.js +1233 -456
  343. package/dist/index.umd.js.map +1 -1
  344. package/dist/package.cjs +1 -1
  345. package/dist/package.mjs +1 -1
  346. package/dist/standard-schema.cjs +20 -7
  347. package/dist/standard-schema.cjs.map +1 -1
  348. package/dist/standard-schema.d.cts +15 -16
  349. package/dist/standard-schema.d.cts.map +1 -1
  350. package/dist/standard-schema.d.mts +15 -16
  351. package/dist/standard-schema.d.mts.map +1 -1
  352. package/dist/standard-schema.mjs +20 -8
  353. package/dist/standard-schema.mjs.map +1 -1
  354. package/dist/telemetry/lambda-client.cjs +1 -1
  355. package/dist/telemetry/lambda-client.cjs.map +1 -1
  356. package/dist/telemetry/lambda-client.d.cts.map +1 -1
  357. package/dist/telemetry/lambda-client.d.mts.map +1 -1
  358. package/dist/telemetry/lambda-client.mjs +1 -1
  359. package/dist/telemetry/lambda-client.mjs.map +1 -1
  360. package/dist/telemetry/telemetry-disabled.cjs +0 -5
  361. package/dist/telemetry/telemetry-disabled.cjs.map +1 -1
  362. package/dist/telemetry/telemetry-disabled.d.cts +0 -5
  363. package/dist/telemetry/telemetry-disabled.d.cts.map +1 -1
  364. package/dist/telemetry/telemetry-disabled.d.mts +0 -5
  365. package/dist/telemetry/telemetry-disabled.d.mts.map +1 -1
  366. package/dist/telemetry/telemetry-disabled.mjs +0 -5
  367. package/dist/telemetry/telemetry-disabled.mjs.map +1 -1
  368. package/dist/types/message.d.cts +1 -18
  369. package/dist/types/message.d.cts.map +1 -1
  370. package/dist/types/message.d.mts +1 -18
  371. package/dist/types/message.d.mts.map +1 -1
  372. package/dist/utils/errors.cjs +5 -42
  373. package/dist/utils/errors.cjs.map +1 -1
  374. package/dist/utils/errors.d.cts +16 -34
  375. package/dist/utils/errors.d.cts.map +1 -1
  376. package/dist/utils/errors.d.mts +16 -34
  377. package/dist/utils/errors.d.mts.map +1 -1
  378. package/dist/utils/errors.mjs +6 -41
  379. package/dist/utils/errors.mjs.map +1 -1
  380. package/dist/utils/index.cjs +0 -2
  381. package/dist/utils/index.cjs.map +1 -1
  382. package/dist/utils/index.d.cts +5 -7
  383. package/dist/utils/index.d.cts.map +1 -1
  384. package/dist/utils/index.d.mts +5 -7
  385. package/dist/utils/index.d.mts.map +1 -1
  386. package/dist/utils/index.mjs +4 -6
  387. package/dist/utils/index.mjs.map +1 -1
  388. package/dist/utils/inspector-visibility.cjs +25 -3
  389. package/dist/utils/inspector-visibility.cjs.map +1 -1
  390. package/dist/utils/inspector-visibility.d.cts +26 -3
  391. package/dist/utils/inspector-visibility.d.cts.map +1 -1
  392. package/dist/utils/inspector-visibility.d.mts +26 -3
  393. package/dist/utils/inspector-visibility.d.mts.map +1 -1
  394. package/dist/utils/inspector-visibility.mjs +25 -4
  395. package/dist/utils/inspector-visibility.mjs.map +1 -1
  396. package/dist/utils/json-schema.cjs +4 -79
  397. package/dist/utils/json-schema.cjs.map +1 -1
  398. package/dist/utils/json-schema.d.cts +1 -4
  399. package/dist/utils/json-schema.d.cts.map +1 -1
  400. package/dist/utils/json-schema.d.mts +1 -4
  401. package/dist/utils/json-schema.d.mts.map +1 -1
  402. package/dist/utils/json-schema.mjs +5 -78
  403. package/dist/utils/json-schema.mjs.map +1 -1
  404. package/dist/utils/random-id.cjs +13 -26
  405. package/dist/utils/random-id.cjs.map +1 -1
  406. package/dist/utils/random-id.d.cts +6 -3
  407. package/dist/utils/random-id.d.cts.map +1 -1
  408. package/dist/utils/random-id.d.mts +6 -3
  409. package/dist/utils/random-id.d.mts.map +1 -1
  410. package/dist/utils/random-id.mjs +14 -25
  411. package/dist/utils/random-id.mjs.map +1 -1
  412. package/dist/utils/types.cjs.map +1 -1
  413. package/dist/utils/types.d.cts +5 -12
  414. package/dist/utils/types.d.cts.map +1 -1
  415. package/dist/utils/types.d.mts +5 -12
  416. package/dist/utils/types.d.mts.map +1 -1
  417. package/dist/utils/types.mjs.map +1 -1
  418. package/package.json +19 -32
  419. package/scripts/verify-cjs-exports.cjs +1 -1
  420. package/src/__tests__/a2ui-envelope.test.ts +38 -13
  421. package/src/__tests__/a2ui-prompts.test.ts +47 -14
  422. package/src/__tests__/fixtures/prompt-goldens.json +354 -0
  423. package/src/__tests__/prompt-spec.test.ts +191 -0
  424. package/src/__tests__/root-entry-browser-safety.test.ts +5 -7
  425. package/src/__tests__/schema-render.test.ts +323 -0
  426. package/src/__tests__/standard-schema.test.ts +61 -101
  427. package/src/a2ui-envelope.ts +9 -7
  428. package/src/a2ui-prompts.ts +47 -96
  429. package/src/attachments/__tests__/utils.test.ts +22 -0
  430. package/src/attachments/types.ts +1 -3
  431. package/src/attachments/utils.ts +23 -5
  432. package/src/finalize-events.ts +16 -0
  433. package/src/generative-ui/__tests__/clone-value-differential.test.ts +480 -0
  434. package/src/generative-ui/__tests__/clone-value.test.ts +226 -0
  435. package/src/generative-ui/__tests__/render-ui-args.test.ts +7 -7
  436. package/src/generative-ui/__tests__/validate-operation.test.ts +19 -13
  437. package/src/generative-ui/base.ts +9 -0
  438. package/src/generative-ui/basic-functions.ts +1 -1
  439. package/src/generative-ui/catalog/catalog-export.ts +478 -0
  440. package/src/generative-ui/catalog/catalog.ts +1167 -0
  441. package/src/generative-ui/catalog/errors.ts +102 -0
  442. package/src/generative-ui/catalog/index.ts +6 -0
  443. package/src/generative-ui/catalog/json-schema.ts +14 -0
  444. package/src/generative-ui/catalog/refs.ts +87 -0
  445. package/src/generative-ui/catalog/schema.ts +107 -0
  446. package/src/generative-ui/child-refs.ts +5 -4
  447. package/src/generative-ui/clone-value.ts +511 -0
  448. package/src/generative-ui/compact-schema.ts +277 -0
  449. package/src/generative-ui/index.ts +14 -0
  450. package/src/generative-ui/is-record.ts +6 -1
  451. package/src/generative-ui/prompt-spec.ts +335 -0
  452. package/src/generative-ui/prompt.ts +25 -75
  453. package/src/generative-ui/render-ui-args.ts +3 -0
  454. package/src/generative-ui/schema-render.ts +378 -0
  455. package/src/generative-ui/standard/__tests__/standard-helpers.test.ts +407 -0
  456. package/src/generative-ui/standard/__tests__/theme.test.ts +61 -0
  457. package/src/generative-ui/standard/__tests__/tokens.test.ts +139 -0
  458. package/src/generative-ui/standard/chart-config.ts +434 -0
  459. package/src/generative-ui/standard/chart.ts +79 -0
  460. package/src/generative-ui/standard/checks.ts +98 -0
  461. package/src/generative-ui/standard/components.ts +35 -0
  462. package/src/generative-ui/standard/composites.ts +158 -0
  463. package/src/generative-ui/standard/data.ts +213 -0
  464. package/src/generative-ui/standard/declarations.ts +57 -0
  465. package/src/generative-ui/standard/feedback.ts +105 -0
  466. package/src/generative-ui/standard/index.ts +55 -0
  467. package/src/generative-ui/standard/inputs.ts +423 -0
  468. package/src/generative-ui/standard/layout.ts +312 -0
  469. package/src/generative-ui/standard/map-helpers.ts +155 -0
  470. package/src/generative-ui/standard/map.ts +32 -0
  471. package/src/generative-ui/standard/media.ts +265 -0
  472. package/src/generative-ui/standard/parameter-order.ts +155 -0
  473. package/src/generative-ui/standard/style-helpers.ts +170 -0
  474. package/src/generative-ui/standard/styles.ts +79 -0
  475. package/src/generative-ui/standard/text.ts +210 -0
  476. package/src/generative-ui/standard/theme.ts +198 -0
  477. package/src/generative-ui/standard/tokens.ts +317 -0
  478. package/src/generative-ui/standard/url.ts +51 -0
  479. package/src/generative-ui/thrown.ts +90 -0
  480. package/src/generative-ui/types.ts +23 -7
  481. package/src/generative-ui/validate-operation.ts +2 -2
  482. package/src/index.ts +9 -17
  483. package/src/standard-schema.ts +24 -27
  484. package/src/telemetry/lambda-client.ts +8 -3
  485. package/src/telemetry/model-host.test.ts +2 -5
  486. package/src/telemetry/telemetry-disabled.ts +0 -5
  487. package/src/types/message.ts +1 -19
  488. package/src/utils/__tests__/errors.test.ts +44 -0
  489. package/src/utils/__tests__/json-schema.test.ts +3 -479
  490. package/src/utils/__tests__/random-id.test.ts +37 -0
  491. package/src/utils/errors.ts +28 -85
  492. package/src/utils/index.ts +0 -2
  493. package/src/utils/inspector-visibility.test.ts +26 -0
  494. package/src/utils/inspector-visibility.ts +35 -3
  495. package/src/utils/json-schema.ts +5 -152
  496. package/src/utils/random-id.ts +17 -37
  497. package/src/utils/types.ts +4 -11
  498. package/tsconfig.json +3 -1
  499. package/tsdown.config.ts +2 -19
  500. package/dist/event-transforms/index.cjs +0 -15
  501. package/dist/event-transforms/index.d.cts +0 -4
  502. package/dist/event-transforms/index.d.mts +0 -4
  503. package/dist/event-transforms/index.mjs +0 -5
  504. package/dist/event-transforms/open-generative-ui-middleware.cjs +0 -286
  505. package/dist/event-transforms/open-generative-ui-middleware.cjs.map +0 -1
  506. package/dist/event-transforms/open-generative-ui-middleware.d.cts +0 -60
  507. package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +0 -1
  508. package/dist/event-transforms/open-generative-ui-middleware.d.mts +0 -60
  509. package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +0 -1
  510. package/dist/event-transforms/open-generative-ui-middleware.mjs +0 -283
  511. package/dist/event-transforms/open-generative-ui-middleware.mjs.map +0 -1
  512. package/dist/event-transforms/recorded-events.cjs +0 -59
  513. package/dist/event-transforms/recorded-events.cjs.map +0 -1
  514. package/dist/event-transforms/recorded-events.d.cts +0 -23
  515. package/dist/event-transforms/recorded-events.d.cts.map +0 -1
  516. package/dist/event-transforms/recorded-events.d.mts +0 -23
  517. package/dist/event-transforms/recorded-events.d.mts.map +0 -1
  518. package/dist/event-transforms/recorded-events.mjs +0 -58
  519. package/dist/event-transforms/recorded-events.mjs.map +0 -1
  520. package/dist/telemetry/events.d.cts +0 -72
  521. package/dist/telemetry/events.d.cts.map +0 -1
  522. package/dist/telemetry/events.d.mts +0 -72
  523. package/dist/telemetry/events.d.mts.map +0 -1
  524. package/dist/telemetry/index.cjs +0 -18
  525. package/dist/telemetry/index.d.cts +0 -5
  526. package/dist/telemetry/index.d.mts +0 -5
  527. package/dist/telemetry/index.mjs +0 -6
  528. package/dist/telemetry/telemetry-client.cjs +0 -165
  529. package/dist/telemetry/telemetry-client.cjs.map +0 -1
  530. package/dist/telemetry/telemetry-client.d.cts +0 -87
  531. package/dist/telemetry/telemetry-client.d.cts.map +0 -1
  532. package/dist/telemetry/telemetry-client.d.mts +0 -87
  533. package/dist/telemetry/telemetry-client.d.mts.map +0 -1
  534. package/dist/telemetry/telemetry-client.mjs +0 -164
  535. package/dist/telemetry/telemetry-client.mjs.map +0 -1
  536. package/dist/telemetry/utils.cjs +0 -14
  537. package/dist/telemetry/utils.cjs.map +0 -1
  538. package/dist/telemetry/utils.mjs +0 -13
  539. package/dist/telemetry/utils.mjs.map +0 -1
  540. package/dist/utils/conditions.cjs +0 -32
  541. package/dist/utils/conditions.cjs.map +0 -1
  542. package/dist/utils/conditions.d.cts +0 -31
  543. package/dist/utils/conditions.d.cts.map +0 -1
  544. package/dist/utils/conditions.d.mts +0 -31
  545. package/dist/utils/conditions.d.mts.map +0 -1
  546. package/dist/utils/conditions.mjs +0 -31
  547. package/dist/utils/conditions.mjs.map +0 -1
  548. package/dist/utils/console-styling.cjs +0 -91
  549. package/dist/utils/console-styling.cjs.map +0 -1
  550. package/dist/utils/console-styling.d.cts +0 -65
  551. package/dist/utils/console-styling.d.cts.map +0 -1
  552. package/dist/utils/console-styling.d.mts +0 -65
  553. package/dist/utils/console-styling.d.mts.map +0 -1
  554. package/dist/utils/console-styling.mjs +0 -85
  555. package/dist/utils/console-styling.mjs.map +0 -1
  556. package/src/__tests__/zod-regression.test.ts +0 -319
  557. package/src/event-transforms/index.ts +0 -5
  558. package/src/event-transforms/open-generative-ui-middleware.ts +0 -392
  559. package/src/event-transforms/recorded-events.test.ts +0 -166
  560. package/src/event-transforms/recorded-events.ts +0 -74
  561. package/src/telemetry/events.ts +0 -68
  562. package/src/telemetry/index.ts +0 -9
  563. package/src/telemetry/telemetry-blank-license-identity.test.ts +0 -128
  564. package/src/telemetry/telemetry-client.test.ts +0 -798
  565. package/src/telemetry/telemetry-client.ts +0 -328
  566. package/src/telemetry/utils.ts +0 -15
  567. package/src/utils/__tests__/conditions.test.ts +0 -161
  568. package/src/utils/conditions.ts +0 -116
  569. package/src/utils/console-styling.ts +0 -126
@@ -1,6 +1,6 @@
1
1
  import { isA2UIBasicFunction } from "./generative-ui/basic-functions.mjs";
2
2
  import { A2UI_CHILD_LIST_REF } from "./generative-ui/child-refs.mjs";
3
- import { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from "./generative-ui/types.mjs";
3
+ import { GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW, GENERATIVE_UI_WHEN_TO_SHOW, GUIDE_COMPONENTS, defaultGenerativeUIPromptSpec, generativeUIPromptFeatures, selectPromptItems } from "./generative-ui/prompt-spec.mjs";
4
4
 
5
5
  //#region src/a2ui-prompts.ts
6
6
  /**
@@ -116,12 +116,6 @@ Design principles:
116
116
  action context should reference the same paths to capture user input.
117
117
 
118
118
  Use the SAME surfaceId as the main surface. Match action names to button action event names.`;
119
- /**
120
- * When UI helps the user, for both transports: a light nudge to reach for UI
121
- * where it conveys the answer better than prose, and to stay in prose
122
- * otherwise.
123
- */
124
- 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.";
125
119
  /** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */
126
120
  const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = "Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.";
127
121
  /**
@@ -167,6 +161,7 @@ function generativeUIGuideFeatures(manifest) {
167
161
  return Object.values(node).some(hasChildList);
168
162
  };
169
163
  return {
164
+ components: Object.keys(manifest.components),
170
165
  functions: Object.keys(manifest.functions).some((name) => !isA2UIBasicFunction(name)),
171
166
  events: components.some((c) => Object.keys(c.events ?? {}).length > 0),
172
167
  templates: components.some((c) => Object.values(c.slots ?? {}).includes("multiple") || hasChildList(c.props)),
@@ -176,43 +171,18 @@ function generativeUIGuideFeatures(manifest) {
176
171
  })
177
172
  };
178
173
  }
179
- /** The first rules of every markdown guideline, before the optional groups. */
180
- const MARKDOWN_BASE_RULES = [
181
- "Write explanations as normal markdown prose outside the fences.",
182
- "Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
183
- "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.",
184
- "Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
185
- "Keep each operation whole on its line.",
186
- "Give every operation \"version\":\"v1.0\".",
187
- `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:
188
- \`\`\`a2ui
189
- {"version":"v1.0","createSurface":{"surfaceId":"plan-picker","dataModel":{ ...initial data... },"components":[{"id":"root","component":"<Name>","children":["seats","pick"]}]}}
190
- {"version":"v1.0","updateComponents":{"surfaceId":"plan-picker","components":[ ...the children... ]}}
191
- \`\`\``,
192
- "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.",
193
- "Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.",
194
- "Use unique ids. Do not make cycles. A component cannot be its own child.",
195
- "Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
196
- "Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
197
- "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.",
198
- "Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".",
199
- "Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
200
- "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.",
201
- "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.",
202
- "${...} 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.",
203
- "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.",
204
- "Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
205
- "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\".",
206
- "Set \"value\":null to delete the key at \"path\"."
207
- ];
208
- /** The last rules of every markdown guideline, after the optional groups. */
209
- const MARKDOWN_CLOSING_RULES = [
210
- "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.",
211
- "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.",
212
- "Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
213
- "Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
214
- "Never wrap the whole reply in a fence."
215
- ];
174
+ /**
175
+ * Whether a guide line names only standard components (`GUIDE_COMPONENTS`,
176
+ * also in the plural) that the catalog has. With no catalog, every line fits.
177
+ */
178
+ function namesOnlyCatalogComponents(catalog) {
179
+ if (!catalog) return () => true;
180
+ const has = new Set(catalog);
181
+ return (line) => (line.match(/\b[A-Z][A-Za-z0-9]*\b/g) ?? []).every((word) => {
182
+ const name = !GUIDE_COMPONENTS.has(word) && word.endsWith("s") ? word.slice(0, -1) : word;
183
+ return !GUIDE_COMPONENTS.has(name) || has.has(name);
184
+ });
185
+ }
216
186
  /**
217
187
  * Builds the markdown-transport guideline. The model writes A2UI v1.0
218
188
  * operations inside ```a2ui fences between normal markdown prose. The rules
@@ -220,25 +190,15 @@ const MARKDOWN_CLOSING_RULES = [
220
190
  * none of them, so the guideline stays small.
221
191
  *
222
192
  * @param features - The optional rule groups to include. Defaults to all.
193
+ * @param spec - The wording. Defaults to the prompts that ship.
223
194
  * @returns The guideline text, one rule per line.
224
195
  */
225
- function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES) {
226
- const { functions, events, templates, checks } = features;
227
- const rules = [...MARKDOWN_BASE_RULES];
228
- 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.");
229
- 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.");
230
- 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\"}].");
231
- 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}}.");
232
- 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.");
233
- 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.");
234
- rules.push(...MARKDOWN_CLOSING_RULES);
235
- return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.
236
-
237
- ${GENERATIVE_UI_WHEN_TO_SHOW}
238
-
239
- RULES
240
- ${rules.map((rule) => `- ${rule}`).join("\n")}
241
- `;
196
+ function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES, spec = defaultGenerativeUIPromptSpec()) {
197
+ const { intro, rules } = spec.markdown;
198
+ const fits = namesOnlyCatalogComponents(features.components);
199
+ const selected = selectPromptItems(rules, generativeUIPromptFeatures(features)).filter(fits);
200
+ const whenToShow = spec.markdown.whenToShow.split("\n").filter(fits).join("\n");
201
+ return `${intro}\n\n${whenToShow ? `${whenToShow}\n\n` : ""}RULES\n${selected.map((rule) => `- ${rule}`).join("\n")}\n`;
242
202
  }
243
203
  /**
244
204
  * The markdown-transport guideline with every rule group. A run sends
@@ -247,5 +207,5 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
247
207
  const GENERATIVE_UI_MARKDOWN_GUIDELINES = buildGenerativeUIMarkdownGuidelines();
248
208
 
249
209
  //#endregion
250
- export { A2UI_DEFAULT_DESIGN_GUIDELINES, A2UI_DEFAULT_GENERATION_GUIDELINES, ALL_GENERATIVE_UI_GUIDE_FEATURES, GENERATIVE_UI_MARKDOWN_GUIDELINES, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, GENERATIVE_UI_WHEN_TO_SHOW, buildGenerativeUIMarkdownGuidelines, generativeUIGuideFeatures };
210
+ export { A2UI_DEFAULT_DESIGN_GUIDELINES, A2UI_DEFAULT_GENERATION_GUIDELINES, ALL_GENERATIVE_UI_GUIDE_FEATURES, GENERATIVE_UI_MARKDOWN_GUIDELINES, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, buildGenerativeUIMarkdownGuidelines, generativeUIGuideFeatures };
251
211
  //# sourceMappingURL=a2ui-prompts.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"a2ui-prompts.mjs","names":[],"sources":["../src/a2ui-prompts.ts"],"sourcesContent":["import { isA2UIBasicFunction } from \"./generative-ui/basic-functions\";\nimport { A2UI_CHILD_LIST_REF } from \"./generative-ui/child-refs\";\nimport { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from \"./generative-ui/types\";\nimport type { GenerativeUIManifest } from \"./generative-ui/types\";\n/**\n * Default A2UI generation and design guideline prompts.\n *\n * These are the canonical prompt fragments that instruct an LLM how to call\n * the render_a2ui tool, how to bind data, and how to style surfaces.\n */\n\n/**\n * Generation guidelines — protocol rules, tool arguments, path rules,\n * data model format, and form/two-way-binding instructions.\n */\nexport const A2UI_DEFAULT_GENERATION_GUIDELINES = `\\\nGenerate A2UI v0.9 JSON.\n\n## A2UI Protocol Instructions\n\nA2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.\n\nCRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:\n- surfaceId: A unique ID for the surface (e.g. \"product-comparison\")\n- components: REQUIRED — the A2UI component array. NEVER omit this. Only use\n components listed in the Available Components schema provided as context.\n- data: OPTIONAL — a JSON object written to the root of the surface data model.\n Use for pre-filling form values or providing data for path-bound components.\n- every component must have the \"component\" field specifying the component type.\n ONLY use component names from the Available Components schema — do NOT invent\n component names or use names not in the schema.\n\nCOMPONENT ID RULES:\n- Exactly one component MUST have id=\"root\". This is the surface's entry\n point — the renderer begins at \"root\" and walks the child/children tree\n from there. Every other component must be reachable from \"root\". If no\n component has id=\"root\", the surface renders an empty loading placeholder\n and none of your components will be shown.\n- Every component ID must be unique within the surface.\n- A component MUST NOT reference itself as child/children. This causes a\n circular dependency error. For example, if a component has id=\"avatar\",\n its child must be a DIFFERENT id (e.g. \"avatar-img\"), never \"avatar\".\n- The child/children tree must be a DAG — no cycles allowed.\n\nREPEATING CONTENT (TEMPLATES):\nTo repeat a component for each item in an array, use the structural children format:\n children: { componentId: \"card-id\", path: \"/items\" }\nThis tells the renderer to create one instance of \"card-id\" per item in the \"/items\" array.\n\nPATH RULES FOR TEMPLATES:\nComponents inside a repeating template use RELATIVE paths (no leading slash).\nThe path is resolved relative to each array item automatically.\nIf a container has children: { componentId: \"card\", path: \"/items\" } and each item\nhas a key \"name\", use { \"path\": \"name\" } (NO leading slash — relative to item).\nCRITICAL: Do NOT use \"/name\" (absolute) inside templates — use \"name\" (relative).\nThe container's path (\"/items\") uses a leading slash (absolute), but all\ncomponents INSIDE the template use paths WITHOUT leading slash.\n\nCOMPONENT VALUES — DEFAULT RULE:\nUse inline literal values for ALL component properties. Pass strings, numbers,\narrays, and objects directly on the component. Do NOT use { \"path\": \"...\" }\nobjects unless the property's schema explicitly allows it (see exception below).\nCRITICAL: USING { \"path\": \"...\" } ON A PROPERTY THAT DOES NOT DECLARE PATH\nSUPPORT IN ITS SCHEMA WILL CAUSE A RUNTIME CRASH AND BREAK THE ENTIRE UI.\nALWAYS CHECK THE COMPONENT SCHEMA FIRST — IF THE PROPERTY ONLY ACCEPTS A\nPLAIN TYPE, YOU MUST USE A LITERAL VALUE.\nVERY IMPORTANT: THE APPLICATION WILL BREAK IF YOU DO NOT FOLLOW THIS RULE!\n\nFor example, a chart's \"data\" must always be an inline array:\n \"data\": [{\"label\": \"Jan\", \"value\": 100}, {\"label\": \"Feb\", \"value\": 200}]\nA metric's \"value\" must always be an inline string:\n \"value\": \"$1,200\"\n\nPATH BINDING EXCEPTION — SCHEMA-DRIVEN:\nA few properties accept { \"path\": \"/some/path\" } as an alternative to a literal\nvalue. You can identify these in the Available Components schema: the property\nwill list BOTH a literal type AND an object-with-path option. If a property only\nshows a single type (string, number, array, etc.), it does NOT support path\nbinding — use a literal value only.\n\nPath binding is typically used for editable form inputs so the client can write\nuser input back to the data model. When building forms:\n- Bind input \"value\" to a data model path: \"value\": { \"path\": \"/form/name\" }\n- Pre-fill via the \"data\" tool argument: \"data\": { \"form\": { \"name\": \"Alice\" } }\n- Capture values on submit via button action context:\n \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"name\": { \"path\": \"/form/name\" } } } }\n\nREPEATING CONTENT uses a structural children format (not the same as value binding):\n children: { componentId: \"card-id\", path: \"/items\" }\nComponents inside templates use RELATIVE paths (no leading slash): { \"path\": \"name\" }.`;\n\n/**\n * Design guidelines — visual design rules, component hierarchy tips,\n * and action handler patterns.\n */\nexport const A2UI_DEFAULT_DESIGN_GUIDELINES = `\\\nCreate polished, visually appealing interfaces. ONLY use components listed in the\nAvailable Components schema — do NOT use component names that are not in the schema.\n\nDesign principles:\n- Create clear visual hierarchy within cards and layouts.\n- Keep cards clean — avoid clutter. Whitespace is good.\n- Use consistent surfaceIds (lowercase, hyphenated).\n- NEVER use the same ID for a component and its child — this creates a\n circular dependency. E.g. if id=\"avatar\", child must NOT be \"avatar\".\n- For side-by-side comparisons, use a container with structural children\n (children: { componentId, path }) to repeat a card template per data item.\n- Include images when relevant (logos, icons, product photos):\n - Prefer company logos via Google favicons: https://www.google.com/s2/favicons?domain=example.com&sz=128\n - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.\n- For buttons: action MUST use this exact nested format:\n \"action\": { \"event\": { \"name\": \"myAction\", \"context\": { \"key\": \"value\" } } }\n The \"event\" key holds an OBJECT with \"name\" (required) and \"context\" (optional).\n Do NOT use a flat format like {\"event\": \"name\"} — \"event\" must be an object.\n- For forms: check the component schema — if an input's \"value\" property\n supports path binding, use it for editable fields. The submit button's\n action context should reference the same paths to capture user input.\n\nUse the SAME surfaceId as the main surface. Match action names to button action event names.`;\n\n/**\n * When UI helps the user, for both transports: a light nudge to reach for UI\n * where it conveys the answer better than prose, and to stay in prose\n * otherwise.\n */\nexport const GENERATIVE_UI_WHEN_TO_SHOW =\n \"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.\";\n\n/** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION =\n \"Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.\";\n\n/**\n * Description of the context entry that carries the compact component schema\n * in the markdown transport.\n *\n * It must not equal `A2UI_SCHEMA_CONTEXT_DESCRIPTION` (the key that\n * `@ag-ui/a2ui-middleware` stamps for tool mode). The LangGraph and Strands\n * adapters find that exact string and move the entry into\n * `state[\"ag-ui\"][\"a2ui_schema\"]` for the `render_a2ui` tool, so it never\n * gets to the system prompt. The markdown transport has no tool, so the\n * schema must stay ordinary context that the model reads as App Context.\n */\nexport const GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION =\n \"Generative UI component schema: the components, props, events, slots, functions, and targets that ```a2ui code fences can use, and the surfaces that already exist.\";\n\n/** Which optional parts of A2UI a manifest uses. The guides leave out the rules for the others. */\nexport interface GenerativeUIGuideFeatures {\n /** A function is mounted: function calls and callRendererFunction. */\n functions: boolean;\n /** A component has an event prop. */\n events: boolean;\n /** A component has a \"multiple\" slot, which takes templates and @index. */\n templates: boolean;\n /** A component has a \"checks\" prop: validation rules on inputs. */\n checks: boolean;\n}\n\n/** Every optional rule group. Use it when the manifest is not known. */\nexport const ALL_GENERATIVE_UI_GUIDE_FEATURES: GenerativeUIGuideFeatures = {\n functions: true,\n events: true,\n templates: true,\n checks: true,\n};\n\n/**\n * The optional parts of A2UI that a manifest uses, so that a guide sends only\n * the rules that the model can apply.\n *\n * @param manifest - The components and the mounted functions of a run.\n * @returns Which optional rule groups the guides include.\n *\n * @example\n * ```ts\n * const guide = buildGenerativeUIMarkdownGuidelines(\n * generativeUIGuideFeatures(manifest),\n * );\n * ```\n */\nexport function generativeUIGuideFeatures(\n manifest: Pick<GenerativeUIManifest, \"components\" | \"functions\">,\n): GenerativeUIGuideFeatures {\n const components = Object.values(manifest.components);\n const hasChildList = (schema: unknown): boolean => {\n if (Array.isArray(schema)) return schema.some(hasChildList);\n if (typeof schema !== \"object\" || schema === null) return false;\n const node = schema as Record<string, unknown>;\n if (node.$ref === A2UI_CHILD_LIST_REF) return true;\n return Object.values(node).some(hasChildList);\n };\n return {\n // App functions only: the built-in ones are always there and have\n // their own rules.\n functions: Object.keys(manifest.functions).some(\n (name) => !isA2UIBasicFunction(name),\n ),\n events: components.some((c) => Object.keys(c.events ?? {}).length > 0),\n templates: components.some(\n (c) =>\n Object.values(c.slots ?? {}).includes(\"multiple\") ||\n hasChildList(c.props),\n ),\n checks: components.some((c) => {\n const properties = c.props.properties;\n return (\n typeof properties === \"object\" &&\n properties !== null &&\n Object.prototype.hasOwnProperty.call(properties, \"checks\")\n );\n }),\n };\n}\n\n/** The first rules of every markdown guideline, before the optional groups. */\nconst MARKDOWN_BASE_RULES = [\n \"Write explanations as normal markdown prose outside the fences.\",\n \"Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.\",\n '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.',\n \"Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.\",\n \"Keep each operation whole on its line.\",\n 'Give every operation \"version\":\"v1.0\".',\n `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:\n \\`\\`\\`a2ui\n {\"version\":\"v1.0\",\"createSurface\":{\"surfaceId\":\"plan-picker\",\"dataModel\":{ ...initial data... },\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"seats\",\"pick\"]}]}}\n {\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"plan-picker\",\"components\":[ ...the children... ]}}\n \\`\\`\\``,\n '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.',\n 'Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.',\n \"Use unique ids. Do not make cycles. A component cannot be its own child.\",\n 'Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.',\n 'Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.',\n '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.',\n 'Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".',\n 'Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.',\n '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.',\n '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.',\n '${...} 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.',\n '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.',\n 'Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user\\'s input goes to that path.',\n '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\".',\n 'Set \"value\":null to delete the key at \"path\".',\n];\n\n/** The last rules of every markdown guideline, after the optional groups. */\nconst MARKDOWN_CLOSING_RULES = [\n '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.',\n \"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.\",\n \"Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.\",\n \"Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.\",\n \"Never wrap the whole reply in a fence.\",\n];\n\n/**\n * Builds the markdown-transport guideline. The model writes A2UI v1.0\n * operations inside ```a2ui fences between normal markdown prose. The rules\n * for functions, events, and templates are left out when the manifest has\n * none of them, so the guideline stays small.\n *\n * @param features - The optional rule groups to include. Defaults to all.\n * @returns The guideline text, one rule per line.\n */\nexport function buildGenerativeUIMarkdownGuidelines(\n features: GenerativeUIGuideFeatures = ALL_GENERATIVE_UI_GUIDE_FEATURES,\n) {\n const { functions, events, templates, checks } = features;\n const rules = [...MARKDOWN_BASE_RULES];\n if (events) {\n rules.push(\n 'Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.',\n functions\n ? '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.'\n : '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.',\n '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\".',\n 'To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.',\n \"A button or other event prop without an event or functionCall does nothing.\",\n );\n }\n if (checks) {\n rules.push(\n '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.',\n );\n }\n rules.push(\n '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\"}].',\n );\n if (templates) {\n rules.push(\n 'To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.',\n 'Inside a template, paths are relative to the item (\"name\", not \"/name\").',\n 'Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.',\n );\n }\n rules.push(\n \"Updating a component replaces all of its props. Send every prop again.\",\n \"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.\",\n \"Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.\",\n );\n if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) {\n rules.push(\n '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.',\n '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.',\n '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.',\n \"Do not guess the result of a callRendererFunction. Wait for the developer message.\",\n );\n }\n rules.push(...MARKDOWN_CLOSING_RULES);\n return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nRULES\n${rules.map((rule) => `- ${rule}`).join(\"\\n\")}\n`;\n}\n\n/**\n * The markdown-transport guideline with every rule group. A run sends\n * `buildGenerativeUIMarkdownGuidelines` for its own manifest instead.\n */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES =\n buildGenerativeUIMarkdownGuidelines();\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFlD,MAAa,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8B9C,MAAa,6BACX;;AAGF,MAAa,gDACX;;;;;;;;;;;;AAaF,MAAa,oDACX;;AAeF,MAAa,mCAA8D;CACzE,WAAW;CACX,QAAQ;CACR,WAAW;CACX,QAAQ;CACT;;;;;;;;;;;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AM,KACJ,2IACA,gFACA,2JACD;AAEH,OAAM,KACJ,0EACA,+UACA,4GACD;AACD,KAAI,aAAa,mCACf,OAAM,KACJ,kQACA,gTACA,wQACA,qFACD;AAEH,OAAM,KAAK,GAAG,uBAAuB;AACrC,QAAO;;EAEP,2BAA2B;;;EAG3B,MAAM,KAAK,SAAS,KAAK,OAAO,CAAC,KAAK,KAAK,CAAC;;;;;;;AAQ9C,MAAa,oCACX,qCAAqC"}
1
+ {"version":3,"file":"a2ui-prompts.mjs","names":[],"sources":["../src/a2ui-prompts.ts"],"sourcesContent":["import { isA2UIBasicFunction } from \"./generative-ui/basic-functions\";\nimport { A2UI_CHILD_LIST_REF } from \"./generative-ui/child-refs\";\nimport type { GenerativeUIManifest } from \"./generative-ui/types\";\nimport {\n defaultGenerativeUIPromptSpec,\n GUIDE_COMPONENTS,\n generativeUIPromptFeatures,\n selectPromptItems,\n} from \"./generative-ui/prompt-spec\";\nimport type { GenerativeUIPromptSpec } from \"./generative-ui/prompt-spec\";\nexport {\n GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW,\n GENERATIVE_UI_WHEN_TO_SHOW,\n} from \"./generative-ui/prompt-spec\";\n/**\n * Default A2UI generation and design guideline prompts.\n *\n * These are the canonical prompt fragments that instruct an LLM how to call\n * the render_a2ui tool, how to bind data, and how to style surfaces.\n */\n\n/**\n * Generation guidelines — protocol rules, tool arguments, path rules,\n * data model format, and form/two-way-binding instructions.\n */\nexport const A2UI_DEFAULT_GENERATION_GUIDELINES = `\\\nGenerate A2UI v0.9 JSON.\n\n## A2UI Protocol Instructions\n\nA2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.\n\nCRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:\n- surfaceId: A unique ID for the surface (e.g. \"product-comparison\")\n- components: REQUIRED — the A2UI component array. NEVER omit this. Only use\n components listed in the Available Components schema provided as context.\n- data: OPTIONAL — a JSON object written to the root of the surface data model.\n Use for pre-filling form values or providing data for path-bound components.\n- every component must have the \"component\" field specifying the component type.\n ONLY use component names from the Available Components schema — do NOT invent\n component names or use names not in the schema.\n\nCOMPONENT ID RULES:\n- Exactly one component MUST have id=\"root\". This is the surface's entry\n point — the renderer begins at \"root\" and walks the child/children tree\n from there. Every other component must be reachable from \"root\". If no\n component has id=\"root\", the surface renders an empty loading placeholder\n and none of your components will be shown.\n- Every component ID must be unique within the surface.\n- A component MUST NOT reference itself as child/children. This causes a\n circular dependency error. For example, if a component has id=\"avatar\",\n its child must be a DIFFERENT id (e.g. \"avatar-img\"), never \"avatar\".\n- The child/children tree must be a DAG — no cycles allowed.\n\nREPEATING CONTENT (TEMPLATES):\nTo repeat a component for each item in an array, use the structural children format:\n children: { componentId: \"card-id\", path: \"/items\" }\nThis tells the renderer to create one instance of \"card-id\" per item in the \"/items\" array.\n\nPATH RULES FOR TEMPLATES:\nComponents inside a repeating template use RELATIVE paths (no leading slash).\nThe path is resolved relative to each array item automatically.\nIf a container has children: { componentId: \"card\", path: \"/items\" } and each item\nhas a key \"name\", use { \"path\": \"name\" } (NO leading slash — relative to item).\nCRITICAL: Do NOT use \"/name\" (absolute) inside templates — use \"name\" (relative).\nThe container's path (\"/items\") uses a leading slash (absolute), but all\ncomponents INSIDE the template use paths WITHOUT leading slash.\n\nCOMPONENT VALUES — DEFAULT RULE:\nUse inline literal values for ALL component properties. Pass strings, numbers,\narrays, and objects directly on the component. Do NOT use { \"path\": \"...\" }\nobjects unless the property's schema explicitly allows it (see exception below).\nCRITICAL: USING { \"path\": \"...\" } ON A PROPERTY THAT DOES NOT DECLARE PATH\nSUPPORT IN ITS SCHEMA WILL CAUSE A RUNTIME CRASH AND BREAK THE ENTIRE UI.\nALWAYS CHECK THE COMPONENT SCHEMA FIRST — IF THE PROPERTY ONLY ACCEPTS A\nPLAIN TYPE, YOU MUST USE A LITERAL VALUE.\nVERY IMPORTANT: THE APPLICATION WILL BREAK IF YOU DO NOT FOLLOW THIS RULE!\n\nFor example, a chart's \"data\" must always be an inline array:\n \"data\": [{\"label\": \"Jan\", \"value\": 100}, {\"label\": \"Feb\", \"value\": 200}]\nA metric's \"value\" must always be an inline string:\n \"value\": \"$1,200\"\n\nPATH BINDING EXCEPTION — SCHEMA-DRIVEN:\nA few properties accept { \"path\": \"/some/path\" } as an alternative to a literal\nvalue. You can identify these in the Available Components schema: the property\nwill list BOTH a literal type AND an object-with-path option. If a property only\nshows a single type (string, number, array, etc.), it does NOT support path\nbinding — use a literal value only.\n\nPath binding is typically used for editable form inputs so the client can write\nuser input back to the data model. When building forms:\n- Bind input \"value\" to a data model path: \"value\": { \"path\": \"/form/name\" }\n- Pre-fill via the \"data\" tool argument: \"data\": { \"form\": { \"name\": \"Alice\" } }\n- Capture values on submit via button action context:\n \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"name\": { \"path\": \"/form/name\" } } } }\n\nREPEATING CONTENT uses a structural children format (not the same as value binding):\n children: { componentId: \"card-id\", path: \"/items\" }\nComponents inside templates use RELATIVE paths (no leading slash): { \"path\": \"name\" }.`;\n\n/**\n * Design guidelines — visual design rules, component hierarchy tips,\n * and action handler patterns.\n */\nexport const A2UI_DEFAULT_DESIGN_GUIDELINES = `\\\nCreate polished, visually appealing interfaces. ONLY use components listed in the\nAvailable Components schema — do NOT use component names that are not in the schema.\n\nDesign principles:\n- Create clear visual hierarchy within cards and layouts.\n- Keep cards clean — avoid clutter. Whitespace is good.\n- Use consistent surfaceIds (lowercase, hyphenated).\n- NEVER use the same ID for a component and its child — this creates a\n circular dependency. E.g. if id=\"avatar\", child must NOT be \"avatar\".\n- For side-by-side comparisons, use a container with structural children\n (children: { componentId, path }) to repeat a card template per data item.\n- Include images when relevant (logos, icons, product photos):\n - Prefer company logos via Google favicons: https://www.google.com/s2/favicons?domain=example.com&sz=128\n - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.\n- For buttons: action MUST use this exact nested format:\n \"action\": { \"event\": { \"name\": \"myAction\", \"context\": { \"key\": \"value\" } } }\n The \"event\" key holds an OBJECT with \"name\" (required) and \"context\" (optional).\n Do NOT use a flat format like {\"event\": \"name\"} — \"event\" must be an object.\n- For forms: check the component schema — if an input's \"value\" property\n supports path binding, use it for editable fields. The submit button's\n action context should reference the same paths to capture user input.\n\nUse the SAME surfaceId as the main surface. Match action names to button action event names.`;\n\n/** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION =\n \"Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.\";\n\n/**\n * Description of the context entry that carries the compact component schema\n * in the markdown transport.\n *\n * It must not equal `A2UI_SCHEMA_CONTEXT_DESCRIPTION` (the key that\n * `@ag-ui/a2ui-middleware` stamps for tool mode). The LangGraph and Strands\n * adapters find that exact string and move the entry into\n * `state[\"ag-ui\"][\"a2ui_schema\"]` for the `render_a2ui` tool, so it never\n * gets to the system prompt. The markdown transport has no tool, so the\n * schema must stay ordinary context that the model reads as App Context.\n */\nexport const GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION =\n \"Generative UI component schema: the components, props, events, slots, functions, and targets that ```a2ui code fences can use, and the surfaces that already exist.\";\n\n/** Which optional parts of A2UI a manifest uses. The guides leave out the rules for the others. */\nexport interface GenerativeUIGuideFeatures {\n /** A function is mounted: function calls and callRendererFunction. */\n functions: boolean;\n /** A component has an event prop. */\n events: boolean;\n /** A component has a \"multiple\" slot, which takes templates and @index. */\n templates: boolean;\n /** A component has a \"checks\" prop: validation rules on inputs. */\n checks: boolean;\n /**\n * The component names of the catalog. A guide line that names a standard\n * component missing from it is left out. Unset keeps every line.\n */\n components?: readonly string[];\n}\n\n/** Every optional rule group. Use it when the manifest is not known. */\nexport const ALL_GENERATIVE_UI_GUIDE_FEATURES: GenerativeUIGuideFeatures = {\n functions: true,\n events: true,\n templates: true,\n checks: true,\n};\n\n/**\n * The optional parts of A2UI that a manifest uses, so that a guide sends only\n * the rules that the model can apply.\n *\n * @param manifest - The components and the mounted functions of a run.\n * @returns Which optional rule groups the guides include.\n *\n * @example\n * ```ts\n * const guide = buildGenerativeUIMarkdownGuidelines(\n * generativeUIGuideFeatures(manifest),\n * );\n * ```\n */\nexport function generativeUIGuideFeatures(\n manifest: Pick<GenerativeUIManifest, \"components\" | \"functions\">,\n): GenerativeUIGuideFeatures {\n const components = Object.values(manifest.components);\n const hasChildList = (schema: unknown): boolean => {\n if (Array.isArray(schema)) return schema.some(hasChildList);\n if (typeof schema !== \"object\" || schema === null) return false;\n const node = schema as Record<string, unknown>;\n if (node.$ref === A2UI_CHILD_LIST_REF) return true;\n return Object.values(node).some(hasChildList);\n };\n return {\n components: Object.keys(manifest.components),\n // App functions only: the built-in ones are always there and have\n // their own rules.\n functions: Object.keys(manifest.functions).some(\n (name) => !isA2UIBasicFunction(name),\n ),\n events: components.some((c) => Object.keys(c.events ?? {}).length > 0),\n templates: components.some(\n (c) =>\n Object.values(c.slots ?? {}).includes(\"multiple\") ||\n hasChildList(c.props),\n ),\n checks: components.some((c) => {\n const properties = c.props.properties;\n return (\n typeof properties === \"object\" &&\n properties !== null &&\n Object.prototype.hasOwnProperty.call(properties, \"checks\")\n );\n }),\n };\n}\n\n/**\n * Whether a guide line names only standard components (`GUIDE_COMPONENTS`,\n * also in the plural) that the catalog has. With no catalog, every line fits.\n */\nfunction namesOnlyCatalogComponents(catalog: readonly string[] | undefined) {\n if (!catalog) return () => true;\n const has = new Set(catalog);\n return (line: string) =>\n (line.match(/\\b[A-Z][A-Za-z0-9]*\\b/g) ?? []).every((word) => {\n const name =\n !GUIDE_COMPONENTS.has(word) && word.endsWith(\"s\")\n ? word.slice(0, -1)\n : word;\n return !GUIDE_COMPONENTS.has(name) || has.has(name);\n });\n}\n\n/**\n * Builds the markdown-transport guideline. The model writes A2UI v1.0\n * operations inside ```a2ui fences between normal markdown prose. The rules\n * for functions, events, and templates are left out when the manifest has\n * none of them, so the guideline stays small.\n *\n * @param features - The optional rule groups to include. Defaults to all.\n * @param spec - The wording. Defaults to the prompts that ship.\n * @returns The guideline text, one rule per line.\n */\nexport function buildGenerativeUIMarkdownGuidelines(\n features: GenerativeUIGuideFeatures = ALL_GENERATIVE_UI_GUIDE_FEATURES,\n spec: GenerativeUIPromptSpec = defaultGenerativeUIPromptSpec(),\n) {\n const { intro, rules } = spec.markdown;\n const fits = namesOnlyCatalogComponents(features.components);\n const selected = selectPromptItems(\n rules,\n generativeUIPromptFeatures(features),\n ).filter(fits);\n const whenToShow = spec.markdown.whenToShow\n .split(\"\\n\")\n .filter(fits)\n .join(\"\\n\");\n const when = whenToShow ? `${whenToShow}\\n\\n` : \"\";\n return `${intro}\\n\\n${when}RULES\\n${selected.map((rule) => `- ${rule}`).join(\"\\n\")}\\n`;\n}\n\n/**\n * The markdown-transport guideline with every rule group. A run sends\n * `buildGenerativeUIMarkdownGuidelines` for its own manifest instead.\n */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES =\n buildGenerativeUIMarkdownGuidelines();\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFlD,MAAa,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;AA0B9C,MAAa,gDACX;;;;;;;;;;;;AAaF,MAAa,oDACX;;AAoBF,MAAa,mCAA8D;CACzE,WAAW;CACX,QAAQ;CACR,WAAW;CACX,QAAQ;CACT;;;;;;;;;;;;;;;AAgBD,SAAgB,0BACd,UAC2B;CAC3B,MAAM,aAAa,OAAO,OAAO,SAAS,WAAW;CACrD,MAAM,gBAAgB,WAA6B;AACjD,MAAI,MAAM,QAAQ,OAAO,CAAE,QAAO,OAAO,KAAK,aAAa;AAC3D,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;EAC1D,MAAM,OAAO;AACb,MAAI,KAAK,SAAS,oBAAqB,QAAO;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SAAS,SAAS,KAAK,SAAS,KAAK,OAAO,CAAC,KAAK,KAAK,CAAC;;;;;;AAOrF,MAAa,oCACX,qCAAqC"}
@@ -37,9 +37,7 @@ interface AttachmentsConfig {
37
37
  * called concurrently unless you raise this. Files past the limit wait for a
38
38
  * free slot; `Infinity` lifts it. The limit covers everything in flight, so
39
39
  * two selections dropped or pasted at once share the slots rather than each
40
- * taking the full number.
41
- * Honored by the React `useAttachments` hook — the Vue and Angular bindings
42
- * still upload serially.
40
+ * taking the full number. React, Vue and Angular all honor it.
43
41
  */
44
42
  maxConcurrentUploads?: number;
45
43
  /** Custom upload handler. Return an InputContentSource with optional metadata. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":[],"sources":["../../src/attachments/types.ts"],"mappings":";;;UAKiB,0BAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;;EAEA,QAAA,GAAW,MAAA;AAAA;AAAA,UAGI,yBAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;EANiB;EAQjB,QAAA,GAAW,MAAA;AAAA;AAAA,KAGD,sBAAA,GACR,0BAAA,GACA,yBAAA;AAAA,KAEQ,2BAAA;AAAA,UAKK,qBAAA;EAhBf;EAkBA,MAAA,EAAQ,2BAAA;EAhBR;EAkBA,IAAA,EAAM,IAAA;EAhBK;EAkBX,OAAA;AAAA;AAAA,UAGe,iBAAA;EAlBiB;EAoBhC,OAAA;EAnBE;EAqBF,MAAA;EAlBU;EAoBV,OAAA;;;;AAfF;;;;;;EAyBE,oBAAA;EArBM;EAuBN,QAAA,IACE,IAAA,EAAM,IAAA,KACH,sBAAA,GAAyB,OAAA,CAAQ,sBAAA;EAvB/B;EAyBP,cAAA,IAAkB,KAAA,EAAO,qBAAA;AAAA;AAAA,KAGf,kBAAA;AAAA,UAEK,UAAA;EACf,EAAA;EACA,IAAA,EAAM,kBAAA;EACN,MAAA,EAAQ,sBAAA,GAAyB,qBAAA;EACjC,QAAA;EACA,IAAA;EACA,MAAA;EACA,SAAA;EAhCA;EAkCA,QAAA,GAAW,MAAA;AAAA"}
1
+ {"version":3,"file":"types.d.cts","names":[],"sources":["../../src/attachments/types.ts"],"mappings":";;;UAKiB,0BAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;;EAEA,QAAA,GAAW,MAAA;AAAA;AAAA,UAGI,yBAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;EANiB;EAQjB,QAAA,GAAW,MAAA;AAAA;AAAA,KAGD,sBAAA,GACR,0BAAA,GACA,yBAAA;AAAA,KAEQ,2BAAA;AAAA,UAKK,qBAAA;EAhBf;EAkBA,MAAA,EAAQ,2BAAA;EAhBR;EAkBA,IAAA,EAAM,IAAA;EAhBK;EAkBX,OAAA;AAAA;AAAA,UAGe,iBAAA;EAlBiB;EAoBhC,OAAA;EAnBE;EAqBF,MAAA;EAlBU;EAoBV,OAAA;;;;AAfF;;;;EAuBE,oBAAA;EArBQ;EAuBR,QAAA,IACE,IAAA,EAAM,IAAA,KACH,sBAAA,GAAyB,OAAA,CAAQ,sBAAA;EAvBhC;EAyBN,cAAA,IAAkB,KAAA,EAAO,qBAAA;AAAA;AAAA,KAGf,kBAAA;AAAA,UAEK,UAAA;EACf,EAAA;EACA,IAAA,EAAM,kBAAA;EACN,MAAA,EAAQ,sBAAA,GAAyB,qBAAA;EACjC,QAAA;EACA,IAAA;EACA,MAAA;EACA,SAAA;EAZ8C;EAc9C,QAAA,GAAW,MAAA;AAAA"}
@@ -37,9 +37,7 @@ interface AttachmentsConfig {
37
37
  * called concurrently unless you raise this. Files past the limit wait for a
38
38
  * free slot; `Infinity` lifts it. The limit covers everything in flight, so
39
39
  * two selections dropped or pasted at once share the slots rather than each
40
- * taking the full number.
41
- * Honored by the React `useAttachments` hook — the Vue and Angular bindings
42
- * still upload serially.
40
+ * taking the full number. React, Vue and Angular all honor it.
43
41
  */
44
42
  maxConcurrentUploads?: number;
45
43
  /** Custom upload handler. Return an InputContentSource with optional metadata. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../src/attachments/types.ts"],"mappings":";;;UAKiB,0BAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;;EAEA,QAAA,GAAW,MAAA;AAAA;AAAA,UAGI,yBAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;EANiB;EAQjB,QAAA,GAAW,MAAA;AAAA;AAAA,KAGD,sBAAA,GACR,0BAAA,GACA,yBAAA;AAAA,KAEQ,2BAAA;AAAA,UAKK,qBAAA;EAhBf;EAkBA,MAAA,EAAQ,2BAAA;EAhBR;EAkBA,IAAA,EAAM,IAAA;EAhBK;EAkBX,OAAA;AAAA;AAAA,UAGe,iBAAA;EAlBiB;EAoBhC,OAAA;EAnBE;EAqBF,MAAA;EAlBU;EAoBV,OAAA;;;;AAfF;;;;;;EAyBE,oBAAA;EArBM;EAuBN,QAAA,IACE,IAAA,EAAM,IAAA,KACH,sBAAA,GAAyB,OAAA,CAAQ,sBAAA;EAvB/B;EAyBP,cAAA,IAAkB,KAAA,EAAO,qBAAA;AAAA;AAAA,KAGf,kBAAA;AAAA,UAEK,UAAA;EACf,EAAA;EACA,IAAA,EAAM,kBAAA;EACN,MAAA,EAAQ,sBAAA,GAAyB,qBAAA;EACjC,QAAA;EACA,IAAA;EACA,MAAA;EACA,SAAA;EAhCA;EAkCA,QAAA,GAAW,MAAA;AAAA"}
1
+ {"version":3,"file":"types.d.mts","names":[],"sources":["../../src/attachments/types.ts"],"mappings":";;;UAKiB,0BAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;;EAEA,QAAA,GAAW,MAAA;AAAA;AAAA,UAGI,yBAAA;EACf,IAAA;EACA,KAAA;EACA,QAAA;EANiB;EAQjB,QAAA,GAAW,MAAA;AAAA;AAAA,KAGD,sBAAA,GACR,0BAAA,GACA,yBAAA;AAAA,KAEQ,2BAAA;AAAA,UAKK,qBAAA;EAhBf;EAkBA,MAAA,EAAQ,2BAAA;EAhBR;EAkBA,IAAA,EAAM,IAAA;EAhBK;EAkBX,OAAA;AAAA;AAAA,UAGe,iBAAA;EAlBiB;EAoBhC,OAAA;EAnBE;EAqBF,MAAA;EAlBU;EAoBV,OAAA;;;;AAfF;;;;EAuBE,oBAAA;EArBQ;EAuBR,QAAA,IACE,IAAA,EAAM,IAAA,KACH,sBAAA,GAAyB,OAAA,CAAQ,sBAAA;EAvBhC;EAyBN,cAAA,IAAkB,KAAA,EAAO,qBAAA;AAAA;AAAA,KAGf,kBAAA;AAAA,UAEK,UAAA;EACf,EAAA;EACA,IAAA,EAAM,kBAAA;EACN,MAAA,EAAQ,sBAAA,GAAyB,qBAAA;EACjC,QAAA;EACA,IAAA;EACA,MAAA;EACA,SAAA;EAZ8C;EAc9C,QAAA,GAAW,MAAA;AAAA"}
@@ -41,15 +41,26 @@ function readFileAsBase64(file) {
41
41
  }
42
42
  /**
43
43
  * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).
44
- * Returns undefined if thumbnail generation fails or if called outside a browser environment.
44
+ * Returns undefined if thumbnail generation fails, if called outside a browser environment,
45
+ * or if `file` is not a `Blob` the browser can read (React Native for web passes a
46
+ * native file's description). Never rejects.
45
47
  */
46
48
  function generateVideoThumbnail(file) {
47
- if (typeof document === "undefined") return Promise.resolve(void 0);
49
+ if (typeof document === "undefined" || typeof Blob === "undefined" || !(file instanceof Blob)) return Promise.resolve(void 0);
48
50
  return new Promise((resolve) => {
49
51
  let resolved = false;
50
- const video = document.createElement("video");
51
- const canvas = document.createElement("canvas");
52
- const url = URL.createObjectURL(file);
52
+ let url;
53
+ let video;
54
+ let canvas;
55
+ try {
56
+ video = document.createElement("video");
57
+ canvas = document.createElement("canvas");
58
+ url = URL.createObjectURL(file);
59
+ } catch (error) {
60
+ console.warn(`[CopilotKit] generateVideoThumbnail: could not read file "${file.name}"`, error);
61
+ resolve(void 0);
62
+ return;
63
+ }
53
64
  const cleanup = (result) => {
54
65
  if (resolved) return;
55
66
  resolved = true;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","names":[],"sources":["../../src/attachments/utils.ts"],"sourcesContent":["import type { AttachmentModality } from \"./types\";\nimport type { InputContentSource } from \"../types/message\";\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\n/**\n * Derive the attachment modality from a MIME type string.\n */\nexport function getModalityFromMimeType(mimeType: string): AttachmentModality {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n/**\n * Format a byte count as a human-readable file size string.\n */\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check if a file exceeds the maximum allowed size.\n */\nexport function exceedsMaxSize(\n file: File,\n maxSize: number = DEFAULT_MAX_SIZE,\n): boolean {\n return file.size > maxSize;\n}\n\n/**\n * Read a File as a base64 string (without the data URL prefix).\n */\nexport function readFileAsBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (e) => {\n const result = e.target?.result as string;\n const base64 = result?.split(\",\")[1];\n if (base64) {\n resolve(base64);\n } else {\n reject(new Error(\"Failed to read file as base64\"));\n }\n };\n reader.onerror = reject;\n reader.readAsDataURL(file);\n });\n}\n\n/**\n * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).\n * Returns undefined if thumbnail generation fails or if called outside a browser environment.\n */\nexport function generateVideoThumbnail(\n file: File,\n): Promise<string | undefined> {\n if (typeof document === \"undefined\") {\n return Promise.resolve(undefined);\n }\n return new Promise((resolve) => {\n let resolved = false;\n const video = document.createElement(\"video\");\n const canvas = document.createElement(\"canvas\");\n const url = URL.createObjectURL(file);\n\n const cleanup = (result: string | undefined) => {\n if (resolved) return;\n resolved = true;\n URL.revokeObjectURL(url);\n resolve(result);\n };\n\n const timeout = setTimeout(() => {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: timed out for file \"${file.name}\"`,\n );\n cleanup(undefined);\n }, 10000);\n\n video.preload = \"metadata\";\n video.muted = true;\n video.playsInline = true;\n\n video.onloadeddata = () => {\n video.currentTime = 0.1;\n };\n\n video.onseeked = () => {\n clearTimeout(timeout);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(video, 0, 0);\n const thumbnail = canvas.toDataURL(\"image/jpeg\", 0.7);\n cleanup(thumbnail);\n } else {\n console.warn(\n \"[CopilotKit] generateVideoThumbnail: could not get 2d canvas context\",\n );\n cleanup(undefined);\n }\n };\n\n video.onerror = () => {\n clearTimeout(timeout);\n console.warn(\n `[CopilotKit] generateVideoThumbnail: video element error for file \"${file.name}\"`,\n );\n cleanup(undefined);\n };\n\n video.src = url;\n });\n}\n\n/**\n * Check if a file's MIME type matches an accept filter string.\n * Handles file extensions (e.g. \".pdf\"), MIME wildcards (\"image/*\"), and comma-separated lists.\n */\nexport function matchesAcceptFilter(file: File, accept: string): boolean {\n if (!accept || accept === \"*/*\") return true;\n\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return (file.name ?? \"\").toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.type.startsWith(prefix + \"/\");\n }\n return file.type === filter;\n });\n}\n\n/**\n * Convert an InputContentSource to a usable URL string.\n * For data sources, returns a base64 data URL; for URL sources, returns the URL directly.\n * A provider file handle (AG-UI 1.0 `file` source) has no address a browser\n * can load, so it returns an empty string and the caller shows no preview.\n */\nexport function getSourceUrl(source: InputContentSource): string {\n if (source.type === \"url\") {\n return source.value;\n }\n if (source.type === \"file\") {\n return \"\";\n }\n return `data:${source.mimeType};base64,${source.value}`;\n}\n\n/**\n * Return a short human-readable label for a document MIME type (e.g. \"PDF\", \"DOC\").\n */\nexport function getDocumentIcon(mimeType: string): string {\n if (mimeType.includes(\"pdf\")) return \"PDF\";\n if (mimeType.includes(\"sheet\") || mimeType.includes(\"excel\")) return \"XLS\";\n if (mimeType.includes(\"presentation\") || mimeType.includes(\"powerpoint\"))\n return \"PPT\";\n if (mimeType.includes(\"word\") || mimeType.includes(\"document\")) return \"DOC\";\n if (mimeType.includes(\"text/\")) return \"TXT\";\n return \"FILE\";\n}\n"],"mappings":";;AAGA,MAAM,mBAAmB,KAAK,OAAO;;;;AAKrC,SAAgB,wBAAwB,UAAsC;AAC5E,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,QAAO;;;;;AAMT,SAAgB,eAAe,OAAuB;AACpD,KAAI,QAAQ,KAAM,QAAO,GAAG,MAAM;AAClC,KAAI,QAAQ,OAAO,KAAM,QAAO,IAAI,QAAQ,MAAM,QAAQ,EAAE,CAAC;AAC7D,QAAO,IAAI,SAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;;;;AAM/C,SAAgB,eACd,MACA,UAAkB,kBACT;AACT,QAAO,KAAK,OAAO;;;;;AAMrB,SAAgB,iBAAiB,MAA6B;AAC5D,QAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,IAAI,YAAY;AAC/B,SAAO,UAAU,MAAM;GAErB,MAAM,UADS,EAAE,QAAQ,SACF,MAAM,IAAI,CAAC;AAClC,OAAI,OACF,SAAQ,OAAO;OAEf,wBAAO,IAAI,MAAM,gCAAgC,CAAC;;AAGtD,SAAO,UAAU;AACjB,SAAO,cAAc,KAAK;GAC1B;;;;;;AAOJ,SAAgB,uBACd,MAC6B;AAC7B,KAAI,OAAO,aAAa,YACtB,QAAO,QAAQ,QAAQ,OAAU;AAEnC,QAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,WAAW;EACf,M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;;;;;;;AASJ,SAAgB,aAAa,QAAoC;AAC/D,KAAI,OAAO,SAAS,MAClB,QAAO,OAAO;AAEhB,KAAI,OAAO,SAAS,OAClB,QAAO;AAET,QAAO,QAAQ,OAAO,SAAS,UAAU,OAAO;;;;;AAMlD,SAAgB,gBAAgB,UAA0B;AACxD,KAAI,SAAS,SAAS,MAAM,CAAE,QAAO;AACrC,KAAI,SAAS,SAAS,QAAQ,IAAI,SAAS,SAAS,QAAQ,CAAE,QAAO;AACrE,KAAI,SAAS,SAAS,eAAe,IAAI,SAAS,SAAS,aAAa,CACtE,QAAO;AACT,KAAI,SAAS,SAAS,OAAO,IAAI,SAAS,SAAS,WAAW,CAAE,QAAO;AACvE,KAAI,SAAS,SAAS,QAAQ,CAAE,QAAO;AACvC,QAAO"}
1
+ {"version":3,"file":"utils.cjs","names":[],"sources":["../../src/attachments/utils.ts"],"sourcesContent":["import type { AttachmentModality } from \"./types\";\nimport type { InputContentSource } from \"../types/message\";\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\n/**\n * Derive the attachment modality from a MIME type string.\n */\nexport function getModalityFromMimeType(mimeType: string): AttachmentModality {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n/**\n * Format a byte count as a human-readable file size string.\n */\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check if a file exceeds the maximum allowed size.\n */\nexport function exceedsMaxSize(\n file: File,\n maxSize: number = DEFAULT_MAX_SIZE,\n): boolean {\n return file.size > maxSize;\n}\n\n/**\n * Read a File as a base64 string (without the data URL prefix).\n */\nexport function readFileAsBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (e) => {\n const result = e.target?.result as string;\n const base64 = result?.split(\",\")[1];\n if (base64) {\n resolve(base64);\n } else {\n reject(new Error(\"Failed to read file as base64\"));\n }\n };\n reader.onerror = reject;\n reader.readAsDataURL(file);\n });\n}\n\n/**\n * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).\n * Returns undefined if thumbnail generation fails, if called outside a browser environment,\n * or if `file` is not a `Blob` the browser can read (React Native for web passes a\n * native file's description). Never rejects.\n */\nexport function generateVideoThumbnail(\n file: File,\n): Promise<string | undefined> {\n if (\n typeof document === \"undefined\" ||\n typeof Blob === \"undefined\" ||\n !(file instanceof Blob)\n ) {\n return Promise.resolve(undefined);\n }\n return new Promise((resolve) => {\n let resolved = false;\n let url: string;\n let video: HTMLVideoElement;\n let canvas: HTMLCanvasElement;\n try {\n video = document.createElement(\"video\");\n canvas = document.createElement(\"canvas\");\n url = URL.createObjectURL(file);\n } catch (error) {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: could not read file \"${file.name}\"`,\n error,\n );\n resolve(undefined);\n return;\n }\n\n const cleanup = (result: string | undefined) => {\n if (resolved) return;\n resolved = true;\n URL.revokeObjectURL(url);\n resolve(result);\n };\n\n const timeout = setTimeout(() => {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: timed out for file \"${file.name}\"`,\n );\n cleanup(undefined);\n }, 10000);\n\n video.preload = \"metadata\";\n video.muted = true;\n video.playsInline = true;\n\n video.onloadeddata = () => {\n video.currentTime = 0.1;\n };\n\n video.onseeked = () => {\n clearTimeout(timeout);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(video, 0, 0);\n const thumbnail = canvas.toDataURL(\"image/jpeg\", 0.7);\n cleanup(thumbnail);\n } else {\n console.warn(\n \"[CopilotKit] generateVideoThumbnail: could not get 2d canvas context\",\n );\n cleanup(undefined);\n }\n };\n\n video.onerror = () => {\n clearTimeout(timeout);\n console.warn(\n `[CopilotKit] generateVideoThumbnail: video element error for file \"${file.name}\"`,\n );\n cleanup(undefined);\n };\n\n video.src = url;\n });\n}\n\n/**\n * Check if a file's MIME type matches an accept filter string.\n * Handles file extensions (e.g. \".pdf\"), MIME wildcards (\"image/*\"), and comma-separated lists.\n */\nexport function matchesAcceptFilter(file: File, accept: string): boolean {\n if (!accept || accept === \"*/*\") return true;\n\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return (file.name ?? \"\").toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.type.startsWith(prefix + \"/\");\n }\n return file.type === filter;\n });\n}\n\n/**\n * Convert an InputContentSource to a usable URL string.\n * For data sources, returns a base64 data URL; for URL sources, returns the URL directly.\n * A provider file handle (AG-UI 1.0 `file` source) has no address a browser\n * can load, so it returns an empty string and the caller shows no preview.\n */\nexport function getSourceUrl(source: InputContentSource): string {\n if (source.type === \"url\") {\n return source.value;\n }\n if (source.type === \"file\") {\n return \"\";\n }\n return `data:${source.mimeType};base64,${source.value}`;\n}\n\n/**\n * Return a short human-readable label for a document MIME type (e.g. \"PDF\", \"DOC\").\n */\nexport function getDocumentIcon(mimeType: string): string {\n if (mimeType.includes(\"pdf\")) return \"PDF\";\n if (mimeType.includes(\"sheet\") || mimeType.includes(\"excel\")) return \"XLS\";\n if (mimeType.includes(\"presentation\") || mimeType.includes(\"powerpoint\"))\n return \"PPT\";\n if (mimeType.includes(\"word\") || mimeType.includes(\"document\")) return \"DOC\";\n if (mimeType.includes(\"text/\")) return \"TXT\";\n return \"FILE\";\n}\n"],"mappings":";;AAGA,MAAM,mBAAmB,KAAK,OAAO;;;;AAKrC,SAAgB,wBAAwB,UAAsC;AAC5E,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WA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S,eAAe,IAAI,SAAS,SAAS,aAAa,CACtE,QAAO;AACT,KAAI,SAAS,SAAS,OAAO,IAAI,SAAS,SAAS,WAAW,CAAE,QAAO;AACvE,KAAI,SAAS,SAAS,QAAQ,CAAE,QAAO;AACvC,QAAO"}
@@ -20,7 +20,9 @@ declare function exceedsMaxSize(file: File, maxSize?: number): boolean;
20
20
  declare function readFileAsBase64(file: File): Promise<string>;
21
21
  /**
22
22
  * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).
23
- * Returns undefined if thumbnail generation fails or if called outside a browser environment.
23
+ * Returns undefined if thumbnail generation fails, if called outside a browser environment,
24
+ * or if `file` is not a `Blob` the browser can read (React Native for web passes a
25
+ * native file's description). Never rejects.
24
26
  */
25
27
  declare function generateVideoThumbnail(file: File): Promise<string | undefined>;
26
28
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","names":[],"sources":["../../src/attachments/utils.ts"],"mappings":";;;;;;AAQA;iBAAgB,uBAAA,CAAwB,QAAA,WAAmB,kBAAA;;;;iBAU3C,cAAA,CAAe,KAAA;;;;iBASf,cAAA,CACd,IAAA,EAAM,IAAA,EACN,OAAA;AAFF;;;AAAA,iBAUgB,gBAAA,CAAiB,IAAA,EAAM,IAAA,GAAO,OAAA;;;;;iBAqB9B,sBAAA,CACd,IAAA,EAAM,IAAA,GACL,OAAA;AAvBH;;;;AAAA,iBAwFgB,mBAAA,CAAoB,IAAA,EAAM,IAAA,EAAM,MAAA;;;;;AAnEhD;;iBAyFgB,YAAA,CAAa,MAAA,EAAQ,kBAAA;;;;iBAarB,eAAA,CAAgB,QAAA"}
1
+ {"version":3,"file":"utils.d.cts","names":[],"sources":["../../src/attachments/utils.ts"],"mappings":";;;;;;AAQA;iBAAgB,uBAAA,CAAwB,QAAA,WAAmB,kBAAA;;;;iBAU3C,cAAA,CAAe,KAAA;;;;iBASf,cAAA,CACd,IAAA,EAAM,IAAA,EACN,OAAA;AAFF;;;AAAA,iBAUgB,gBAAA,CAAiB,IAAA,EAAM,IAAA,GAAO,OAAA;;;;;;AAA9C;iBAuBgB,sBAAA,CACd,IAAA,EAAM,IAAA,GACL,OAAA;;;;;iBAiFa,mBAAA,CAAoB,IAAA,EAAM,IAAA,EAAM,MAAA;;;AAnFhD;;;;iBAyGgB,YAAA,CAAa,MAAA,EAAQ,kBAAA;;;;iBAarB,eAAA,CAAgB,QAAA"}
@@ -20,7 +20,9 @@ declare function exceedsMaxSize(file: File, maxSize?: number): boolean;
20
20
  declare function readFileAsBase64(file: File): Promise<string>;
21
21
  /**
22
22
  * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).
23
- * Returns undefined if thumbnail generation fails or if called outside a browser environment.
23
+ * Returns undefined if thumbnail generation fails, if called outside a browser environment,
24
+ * or if `file` is not a `Blob` the browser can read (React Native for web passes a
25
+ * native file's description). Never rejects.
24
26
  */
25
27
  declare function generateVideoThumbnail(file: File): Promise<string | undefined>;
26
28
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../../src/attachments/utils.ts"],"mappings":";;;;;;AAQA;iBAAgB,uBAAA,CAAwB,QAAA,WAAmB,kBAAA;;;;iBAU3C,cAAA,CAAe,KAAA;;;;iBASf,cAAA,CACd,IAAA,EAAM,IAAA,EACN,OAAA;AAFF;;;AAAA,iBAUgB,gBAAA,CAAiB,IAAA,EAAM,IAAA,GAAO,OAAA;;;;;iBAqB9B,sBAAA,CACd,IAAA,EAAM,IAAA,GACL,OAAA;AAvBH;;;;AAAA,iBAwFgB,mBAAA,CAAoB,IAAA,EAAM,IAAA,EAAM,MAAA;;;;;AAnEhD;;iBAyFgB,YAAA,CAAa,MAAA,EAAQ,kBAAA;;;;iBAarB,eAAA,CAAgB,QAAA"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../../src/attachments/utils.ts"],"mappings":";;;;;;AAQA;iBAAgB,uBAAA,CAAwB,QAAA,WAAmB,kBAAA;;;;iBAU3C,cAAA,CAAe,KAAA;;;;iBASf,cAAA,CACd,IAAA,EAAM,IAAA,EACN,OAAA;AAFF;;;AAAA,iBAUgB,gBAAA,CAAiB,IAAA,EAAM,IAAA,GAAO,OAAA;;;;;;AAA9C;iBAuBgB,sBAAA,CACd,IAAA,EAAM,IAAA,GACL,OAAA;;;;;iBAiFa,mBAAA,CAAoB,IAAA,EAAM,IAAA,EAAM,MAAA;;;AAnFhD;;;;iBAyGgB,YAAA,CAAa,MAAA,EAAQ,kBAAA;;;;iBAarB,eAAA,CAAgB,QAAA"}
@@ -40,15 +40,26 @@ function readFileAsBase64(file) {
40
40
  }
41
41
  /**
42
42
  * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).
43
- * Returns undefined if thumbnail generation fails or if called outside a browser environment.
43
+ * Returns undefined if thumbnail generation fails, if called outside a browser environment,
44
+ * or if `file` is not a `Blob` the browser can read (React Native for web passes a
45
+ * native file's description). Never rejects.
44
46
  */
45
47
  function generateVideoThumbnail(file) {
46
- if (typeof document === "undefined") return Promise.resolve(void 0);
48
+ if (typeof document === "undefined" || typeof Blob === "undefined" || !(file instanceof Blob)) return Promise.resolve(void 0);
47
49
  return new Promise((resolve) => {
48
50
  let resolved = false;
49
- const video = document.createElement("video");
50
- const canvas = document.createElement("canvas");
51
- const url = URL.createObjectURL(file);
51
+ let url;
52
+ let video;
53
+ let canvas;
54
+ try {
55
+ video = document.createElement("video");
56
+ canvas = document.createElement("canvas");
57
+ url = URL.createObjectURL(file);
58
+ } catch (error) {
59
+ console.warn(`[CopilotKit] generateVideoThumbnail: could not read file "${file.name}"`, error);
60
+ resolve(void 0);
61
+ return;
62
+ }
52
63
  const cleanup = (result) => {
53
64
  if (resolved) return;
54
65
  resolved = true;
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","names":[],"sources":["../../src/attachments/utils.ts"],"sourcesContent":["import type { AttachmentModality } from \"./types\";\nimport type { InputContentSource } from \"../types/message\";\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\n/**\n * Derive the attachment modality from a MIME type string.\n */\nexport function getModalityFromMimeType(mimeType: string): AttachmentModality {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n/**\n * Format a byte count as a human-readable file size string.\n */\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check if a file exceeds the maximum allowed size.\n */\nexport function exceedsMaxSize(\n file: File,\n maxSize: number = DEFAULT_MAX_SIZE,\n): boolean {\n return file.size > maxSize;\n}\n\n/**\n * Read a File as a base64 string (without the data URL prefix).\n */\nexport function readFileAsBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (e) => {\n const result = e.target?.result as string;\n const base64 = result?.split(\",\")[1];\n if (base64) {\n resolve(base64);\n } else {\n reject(new Error(\"Failed to read file as base64\"));\n }\n };\n reader.onerror = reject;\n reader.readAsDataURL(file);\n });\n}\n\n/**\n * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).\n * Returns undefined if thumbnail generation fails or if called outside a browser environment.\n */\nexport function generateVideoThumbnail(\n file: File,\n): Promise<string | undefined> {\n if (typeof document === \"undefined\") {\n return Promise.resolve(undefined);\n }\n return new Promise((resolve) => {\n let resolved = false;\n const video = document.createElement(\"video\");\n const canvas = document.createElement(\"canvas\");\n const url = URL.createObjectURL(file);\n\n const cleanup = (result: string | undefined) => {\n if (resolved) return;\n resolved = true;\n URL.revokeObjectURL(url);\n resolve(result);\n };\n\n const timeout = setTimeout(() => {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: timed out for file \"${file.name}\"`,\n );\n cleanup(undefined);\n }, 10000);\n\n video.preload = \"metadata\";\n video.muted = true;\n video.playsInline = true;\n\n video.onloadeddata = () => {\n video.currentTime = 0.1;\n };\n\n video.onseeked = () => {\n clearTimeout(timeout);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(video, 0, 0);\n const thumbnail = canvas.toDataURL(\"image/jpeg\", 0.7);\n cleanup(thumbnail);\n } else {\n console.warn(\n \"[CopilotKit] generateVideoThumbnail: could not get 2d canvas context\",\n );\n cleanup(undefined);\n }\n };\n\n video.onerror = () => {\n clearTimeout(timeout);\n console.warn(\n `[CopilotKit] generateVideoThumbnail: video element error for file \"${file.name}\"`,\n );\n cleanup(undefined);\n };\n\n video.src = url;\n });\n}\n\n/**\n * Check if a file's MIME type matches an accept filter string.\n * Handles file extensions (e.g. \".pdf\"), MIME wildcards (\"image/*\"), and comma-separated lists.\n */\nexport function matchesAcceptFilter(file: File, accept: string): boolean {\n if (!accept || accept === \"*/*\") return true;\n\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return (file.name ?? \"\").toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.type.startsWith(prefix + \"/\");\n }\n return file.type === filter;\n });\n}\n\n/**\n * Convert an InputContentSource to a usable URL string.\n * For data sources, returns a base64 data URL; for URL sources, returns the URL directly.\n * A provider file handle (AG-UI 1.0 `file` source) has no address a browser\n * can load, so it returns an empty string and the caller shows no preview.\n */\nexport function getSourceUrl(source: InputContentSource): string {\n if (source.type === \"url\") {\n return source.value;\n }\n if (source.type === \"file\") {\n return \"\";\n }\n return `data:${source.mimeType};base64,${source.value}`;\n}\n\n/**\n * Return a short human-readable label for a document MIME type (e.g. \"PDF\", \"DOC\").\n */\nexport function getDocumentIcon(mimeType: string): string {\n if (mimeType.includes(\"pdf\")) return \"PDF\";\n if (mimeType.includes(\"sheet\") || mimeType.includes(\"excel\")) return \"XLS\";\n if (mimeType.includes(\"presentation\") || mimeType.includes(\"powerpoint\"))\n return \"PPT\";\n if (mimeType.includes(\"word\") || mimeType.includes(\"document\")) return \"DOC\";\n if (mimeType.includes(\"text/\")) return \"TXT\";\n return \"FILE\";\n}\n"],"mappings":";AAGA,MAAM,mBAAmB,KAAK,OAAO;;;;AAKrC,SAAgB,wBAAwB,UAAsC;AAC5E,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,QAAO;;;;;AAMT,SAAgB,eAAe,OAAuB;AACpD,KAAI,QAAQ,KAAM,QAAO,GAAG,MAAM;AAClC,KAAI,QAAQ,OAAO,KAAM,QAAO,IAAI,QAAQ,MAAM,QAAQ,EAAE,CAAC;AAC7D,QAAO,IAAI,SAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;;;;AAM/C,SAAgB,eACd,MACA,UAAkB,kBACT;AACT,QAAO,KAAK,OAAO;;;;;AAMrB,SAAgB,iBAAiB,MAA6B;AAC5D,QAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,SAAS,IAAI,YAAY;AAC/B,SAAO,UAAU,MAAM;GAErB,MAAM,UADS,EAAE,QAAQ,SACF,MAAM,IAAI,CAAC;AAClC,OAAI,OACF,SAAQ,OAAO;OAEf,wBAAO,IAAI,MAAM,gCAAgC,CAAC;;AAGtD,SAAO,UAAU;AACjB,SAAO,cAAc,KAAK;GAC1B;;;;;;AAOJ,SAAgB,uBACd,MAC6B;AAC7B,KAAI,OAAO,aAAa,YACtB,QAAO,QAAQ,QAAQ,OAAU;AAEnC,QAAO,IAAI,SAAS,YAAY;EAC9B,IAAI,WAAW;EACf,MAAM,QAAQ,SAAS,cAAc,QAAQ;EAC7C,MAAM,SAAS,SAAS,cAAc,SAAS;EAC/C,MAAM,MAAM,IAAI,gBAAgB,KAAK;EAErC,MAAM,WAAW,W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AAQ,OAAO,SAAS,UAAU,OAAO;;;;;AAMlD,SAAgB,gBAAgB,UAA0B;AACxD,KAAI,SAAS,SAAS,MAAM,CAAE,QAAO;AACrC,KAAI,SAAS,SAAS,QAAQ,IAAI,SAAS,SAAS,QAAQ,CAAE,QAAO;AACrE,KAAI,SAAS,SAAS,eAAe,IAAI,SAAS,SAAS,aAAa,CACtE,QAAO;AACT,KAAI,SAAS,SAAS,OAAO,IAAI,SAAS,SAAS,WAAW,CAAE,QAAO;AACvE,KAAI,SAAS,SAAS,QAAQ,CAAE,QAAO;AACvC,QAAO"}
1
+ {"version":3,"file":"utils.mjs","names":[],"sources":["../../src/attachments/utils.ts"],"sourcesContent":["import type { AttachmentModality } from \"./types\";\nimport type { InputContentSource } from \"../types/message\";\n\nconst DEFAULT_MAX_SIZE = 20 * 1024 * 1024; // 20MB\n\n/**\n * Derive the attachment modality from a MIME type string.\n */\nexport function getModalityFromMimeType(mimeType: string): AttachmentModality {\n if (mimeType.startsWith(\"image/\")) return \"image\";\n if (mimeType.startsWith(\"audio/\")) return \"audio\";\n if (mimeType.startsWith(\"video/\")) return \"video\";\n return \"document\";\n}\n\n/**\n * Format a byte count as a human-readable file size string.\n */\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Check if a file exceeds the maximum allowed size.\n */\nexport function exceedsMaxSize(\n file: File,\n maxSize: number = DEFAULT_MAX_SIZE,\n): boolean {\n return file.size > maxSize;\n}\n\n/**\n * Read a File as a base64 string (without the data URL prefix).\n */\nexport function readFileAsBase64(file: File): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = (e) => {\n const result = e.target?.result as string;\n const base64 = result?.split(\",\")[1];\n if (base64) {\n resolve(base64);\n } else {\n reject(new Error(\"Failed to read file as base64\"));\n }\n };\n reader.onerror = reject;\n reader.readAsDataURL(file);\n });\n}\n\n/**\n * Generate a thumbnail data URL from a video file by capturing a frame near the start (at 0.1s).\n * Returns undefined if thumbnail generation fails, if called outside a browser environment,\n * or if `file` is not a `Blob` the browser can read (React Native for web passes a\n * native file's description). Never rejects.\n */\nexport function generateVideoThumbnail(\n file: File,\n): Promise<string | undefined> {\n if (\n typeof document === \"undefined\" ||\n typeof Blob === \"undefined\" ||\n !(file instanceof Blob)\n ) {\n return Promise.resolve(undefined);\n }\n return new Promise((resolve) => {\n let resolved = false;\n let url: string;\n let video: HTMLVideoElement;\n let canvas: HTMLCanvasElement;\n try {\n video = document.createElement(\"video\");\n canvas = document.createElement(\"canvas\");\n url = URL.createObjectURL(file);\n } catch (error) {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: could not read file \"${file.name}\"`,\n error,\n );\n resolve(undefined);\n return;\n }\n\n const cleanup = (result: string | undefined) => {\n if (resolved) return;\n resolved = true;\n URL.revokeObjectURL(url);\n resolve(result);\n };\n\n const timeout = setTimeout(() => {\n console.warn(\n `[CopilotKit] generateVideoThumbnail: timed out for file \"${file.name}\"`,\n );\n cleanup(undefined);\n }, 10000);\n\n video.preload = \"metadata\";\n video.muted = true;\n video.playsInline = true;\n\n video.onloadeddata = () => {\n video.currentTime = 0.1;\n };\n\n video.onseeked = () => {\n clearTimeout(timeout);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n const ctx = canvas.getContext(\"2d\");\n if (ctx) {\n ctx.drawImage(video, 0, 0);\n const thumbnail = canvas.toDataURL(\"image/jpeg\", 0.7);\n cleanup(thumbnail);\n } else {\n console.warn(\n \"[CopilotKit] generateVideoThumbnail: could not get 2d canvas context\",\n );\n cleanup(undefined);\n }\n };\n\n video.onerror = () => {\n clearTimeout(timeout);\n console.warn(\n `[CopilotKit] generateVideoThumbnail: video element error for file \"${file.name}\"`,\n );\n cleanup(undefined);\n };\n\n video.src = url;\n });\n}\n\n/**\n * Check if a file's MIME type matches an accept filter string.\n * Handles file extensions (e.g. \".pdf\"), MIME wildcards (\"image/*\"), and comma-separated lists.\n */\nexport function matchesAcceptFilter(file: File, accept: string): boolean {\n if (!accept || accept === \"*/*\") return true;\n\n const filters = accept.split(\",\").map((f) => f.trim());\n return filters.some((filter) => {\n if (filter.startsWith(\".\")) {\n return (file.name ?? \"\").toLowerCase().endsWith(filter.toLowerCase());\n }\n if (filter.endsWith(\"/*\")) {\n const prefix = filter.slice(0, -2);\n return file.type.startsWith(prefix + \"/\");\n }\n return file.type === filter;\n });\n}\n\n/**\n * Convert an InputContentSource to a usable URL string.\n * For data sources, returns a base64 data URL; for URL sources, returns the URL directly.\n * A provider file handle (AG-UI 1.0 `file` source) has no address a browser\n * can load, so it returns an empty string and the caller shows no preview.\n */\nexport function getSourceUrl(source: InputContentSource): string {\n if (source.type === \"url\") {\n return source.value;\n }\n if (source.type === \"file\") {\n return \"\";\n }\n return `data:${source.mimeType};base64,${source.value}`;\n}\n\n/**\n * Return a short human-readable label for a document MIME type (e.g. \"PDF\", \"DOC\").\n */\nexport function getDocumentIcon(mimeType: string): string {\n if (mimeType.includes(\"pdf\")) return \"PDF\";\n if (mimeType.includes(\"sheet\") || mimeType.includes(\"excel\")) return \"XLS\";\n if (mimeType.includes(\"presentation\") || mimeType.includes(\"powerpoint\"))\n return \"PPT\";\n if (mimeType.includes(\"word\") || mimeType.includes(\"document\")) return \"DOC\";\n if (mimeType.includes(\"text/\")) return \"TXT\";\n return \"FILE\";\n}\n"],"mappings":";AAGA,MAAM,mBAAmB,KAAK,OAAO;;;;AAKrC,SAAgB,wBAAwB,UAAsC;AAC5E,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,KAAI,SAAS,WAAW,SAAS,CAAE,QAAO;AAC1C,QAAO;;;;;AAMT,SAAgB,eAAe,OAAuB;AACpD,KAAI,QAAQ,KAAM,QAAO,GAAG,MAAM;AAClC,KAAI,QAAQ,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AAS,QAAQ,CAAE,QAAO;AACvC,QAAO"}
@@ -94,6 +94,22 @@ function createRunEventFinalizer() {
94
94
  terminalEventObserved = true;
95
95
  clearOpen();
96
96
  break;
97
+ case _ag_ui_client.EventType.TEXT_MESSAGE_CONTENT:
98
+ case _ag_ui_client.EventType.TEXT_MESSAGE_CHUNK:
99
+ case _ag_ui_client.EventType.TOOL_CALL_ARGS:
100
+ case _ag_ui_client.EventType.TOOL_CALL_CHUNK:
101
+ case _ag_ui_client.EventType.STATE_SNAPSHOT:
102
+ case _ag_ui_client.EventType.STATE_DELTA:
103
+ case _ag_ui_client.EventType.MESSAGES_SNAPSHOT:
104
+ case _ag_ui_client.EventType.ACTIVITY_SNAPSHOT:
105
+ case _ag_ui_client.EventType.ACTIVITY_DELTA:
106
+ case _ag_ui_client.EventType.RAW:
107
+ case _ag_ui_client.EventType.CUSTOM:
108
+ case _ag_ui_client.EventType.STEP_STARTED:
109
+ case _ag_ui_client.EventType.STEP_FINISHED:
110
+ case _ag_ui_client.EventType.REASONING_MESSAGE_CONTENT:
111
+ case _ag_ui_client.EventType.REASONING_MESSAGE_CHUNK:
112
+ case _ag_ui_client.EventType.REASONING_ENCRYPTED_VALUE:
97
113
  default: break;
98
114
  }
99
115
  };
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.cjs","names":["EventType"],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n /**\n * The `protocolVersion` the client declared on its RunAgentInput. When it is\n * set, a stopped run finishes with the AG-UI 1.0 `cancelled` outcome. A\n * client that declares no version predates 1.0 and cannot parse that\n * outcome, so it gets the plain RUN_FINISHED it always got.\n */\n protocolVersion?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for reasoning, text messages and tool calls still open plus a\n * terminal event. AG-UI 1.0 fails a run that ends with reasoning still open,\n * so reasoning is closed too. It also fails a RUN_FINISHED while a subagent\n * is still open, so a stop closes open subagents as well; a RUN_ERROR\n * abandons them, which the protocol allows. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openReasoningMessageIds = new Set<string>();\n const openReasoningSpanIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n // Insertion order is start order, so closing in reverse closes children first.\n const openSubagentRunIds = new Set<string>();\n let runIdentity: { threadId?: string; runId?: string } = {};\n let terminalEventObserved = false;\n\n const clearOpen = () => {\n openMessageIds.clear();\n openReasoningMessageIds.clear();\n openReasoningSpanIds.clear();\n openToolCalls.clear();\n openSubagentRunIds.clear();\n };\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.RUN_STARTED: {\n const { threadId, runId } = event as {\n threadId?: string;\n runId?: string;\n };\n runIdentity = { threadId, runId };\n break;\n }\n case EventType.REASONING_START:\n case EventType.REASONING_END:\n case EventType.REASONING_MESSAGE_START:\n case EventType.REASONING_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId !== \"string\") break;\n const open =\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_END\n ? openReasoningSpanIds\n : openReasoningMessageIds;\n if (\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_MESSAGE_START\n ) {\n open.add(messageId);\n } else {\n open.delete(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.SUBAGENT_STARTED:\n case EventType.SUBAGENT_FINISHED:\n case EventType.SUBAGENT_ERROR: {\n const subagentRunId = (event as { subagentRunId?: string })\n .subagentRunId;\n if (!subagentRunId) break;\n if (event.type === EventType.SUBAGENT_STARTED) {\n openSubagentRunIds.add(subagentRunId);\n } else {\n openSubagentRunIds.delete(subagentRunId);\n }\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n clearOpen();\n break;\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n // A reasoning message closes before the span that holds it.\n for (const messageId of openReasoningMessageIds) {\n appended.push({\n type: EventType.REASONING_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n for (const messageId of openReasoningSpanIds) {\n appended.push({ type: EventType.REASONING_END, messageId } as BaseEvent);\n }\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n // Newest first, so a nested subagent closes before its parent. An index\n // loop, because `toReversed` is ES2023 and this package targets older.\n const openIds = [...openSubagentRunIds];\n for (let index = openIds.length - 1; index >= 0; index -= 1) {\n appended.push({\n type: EventType.SUBAGENT_ERROR,\n subagentRunId: openIds[index],\n message: resolvedStopMessage,\n code: \"CANCELLED\",\n } as BaseEvent);\n }\n appended.push({\n type: EventType.RUN_FINISHED,\n ...(runIdentity.threadId !== undefined\n ? { threadId: runIdentity.threadId }\n : {}),\n ...(runIdentity.runId !== undefined\n ? { runId: runIdentity.runId }\n : {}),\n ...(options.protocolVersion !== undefined\n ? { outcome: { type: \"cancelled\" } }\n : {}),\n } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n clearOpen();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n"],"mappings":";;;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;;;;;;;;;;;AAiBhC,SAAgB,0BAA6C;CAC3D,MAAM,iCAAiB,IAAI,KAAa;CACxC,MAAM,0CAA0B,IAAI,KAAa;CACjD,MAAM,uCAAuB,IAAI,KAAa;CAC9C,MAAM,gCAAgB,IAAI,KAA2B;CAErD,MAAM,qCAAqB,IAAI,KAAa;CAC5C,IAAI,cAAqD,EAAE;CAC3D,IAAI,wBAAwB;CAE5B,MAAM,kBAAkB;AACtB,iBAAe,OAAO;AACtB,0BAAwB,OAAO;AAC/B,uBAAqB,OAAO;AAC5B,gBAAc,OAAO;AACrB,qBAAmB,OAAO;;CAG5B,MAAM,WAAW,UAAqB;AACpC,MAAI,sBAAuB;AAE3B,UAAQ,MAAM,MAAd;GACE,KAAKA,wBAAU,aAAa;IAC1B,MAAM,EAAE,UAAU,UAAU;AAI5B,kBAAc;KAAE;KAAU;KAAO;AACjC;;GAEF,KAAKA,wBAAU;GACf,KAAKA,wBAAU;GACf,KAAKA,wBAAU;GACf,KAAKA,wBAAU,uBAAuB;IACpC,MAAM,YAAa,MAAiC;AACpD,QAAI,OAAO,cAAc,SAAU;IACnC,MAAM,OACJ,MAAM,SAASA,wBAAU,mBACzB,MAAM,SAASA,wBAAU,gBACrB,uBACA;AACN,QACE,MAAM,SAASA,wBAAU,mBACzB,MAAM,SAASA,wBAAU,wBAEzB,MAAK,IAAI,UAAU;QAEnB,MAAK,OAAO,UAAU;AAExB;;GAEF,KAAKA,wBAAU,oBAAoB;IACjC,MAAM,YAAa,MAAiC;AACpD,QAAI,UAAW,gBAAe,IAAI,UAAU;AAC5C;;GA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WAAW,UAAU,SAAS,QAAQ;AAC5C,QAAO,KAAK,GAAG,SAAS;AACxB,QAAO"}
1
+ {"version":3,"file":"finalize-events.cjs","names":["EventType"],"sources":["../src/finalize-events.ts"],"sourcesContent":["import type { BaseEvent, RunErrorEvent } from \"@ag-ui/client\";\nimport { EventType } from \"@ag-ui/client\";\n\nexport interface FinalizeRunOptions {\n stopRequested?: boolean;\n interruptionMessage?: string;\n /**\n * The `protocolVersion` the client declared on its RunAgentInput. When it is\n * set, a stopped run finishes with the AG-UI 1.0 `cancelled` outcome. A\n * client that declares no version predates 1.0 and cannot parse that\n * outcome, so it gets the plain RUN_FINISHED it always got.\n */\n protocolVersion?: string;\n}\n\nexport interface RunEventFinalizer {\n /** Observe one streamed event. Only the ids of open lifecycles are kept. */\n observe(event: BaseEvent): void;\n /** Return the events that close an interrupted or abruptly ended stream. */\n finalize(options?: FinalizeRunOptions): BaseEvent[];\n}\n\nconst defaultStopMessage = \"Run stopped by user\";\nconst defaultAbruptEndMessage = \"Run ended without emitting a terminal event\";\n\ninterface OpenToolCall {\n hasEnd: boolean;\n hasResult: boolean;\n}\n\n/**\n * Incremental finalizer for a streamed AG-UI run. Feed every event to\n * `observe`; when the stream ends without a terminal event, `finalize` returns\n * the closers for reasoning, text messages and tool calls still open plus a\n * terminal event. AG-UI 1.0 fails a run that ends with reasoning still open,\n * so reasoning is closed too. It also fails a RUN_FINISHED while a subagent\n * is still open, so a stop closes open subagents as well; a RUN_ERROR\n * abandons them, which the protocol allows. Closed lifecycles are forgotten at once and payloads are never kept,\n * so a caller does not have to retain the event array for this purpose.\n */\nexport function createRunEventFinalizer(): RunEventFinalizer {\n const openMessageIds = new Set<string>();\n const openReasoningMessageIds = new Set<string>();\n const openReasoningSpanIds = new Set<string>();\n const openToolCalls = new Map<string, OpenToolCall>();\n // Insertion order is start order, so closing in reverse closes children first.\n const openSubagentRunIds = new Set<string>();\n let runIdentity: { threadId?: string; runId?: string } = {};\n let terminalEventObserved = false;\n\n const clearOpen = () => {\n openMessageIds.clear();\n openReasoningMessageIds.clear();\n openReasoningSpanIds.clear();\n openToolCalls.clear();\n openSubagentRunIds.clear();\n };\n\n const observe = (event: BaseEvent) => {\n if (terminalEventObserved) return;\n\n switch (event.type) {\n case EventType.RUN_STARTED: {\n const { threadId, runId } = event as {\n threadId?: string;\n runId?: string;\n };\n runIdentity = { threadId, runId };\n break;\n }\n case EventType.REASONING_START:\n case EventType.REASONING_END:\n case EventType.REASONING_MESSAGE_START:\n case EventType.REASONING_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId !== \"string\") break;\n const open =\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_END\n ? openReasoningSpanIds\n : openReasoningMessageIds;\n if (\n event.type === EventType.REASONING_START ||\n event.type === EventType.REASONING_MESSAGE_START\n ) {\n open.add(messageId);\n } else {\n open.delete(messageId);\n }\n break;\n }\n case EventType.TEXT_MESSAGE_START: {\n const messageId = (event as { messageId?: string }).messageId;\n if (messageId) openMessageIds.add(messageId);\n break;\n }\n case EventType.TEXT_MESSAGE_END: {\n const messageId = (event as { messageId?: string }).messageId;\n if (typeof messageId === \"string\") openMessageIds.delete(messageId);\n break;\n }\n case EventType.TOOL_CALL_START: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (toolCallId && !openToolCalls.has(toolCallId)) {\n openToolCalls.set(toolCallId, { hasEnd: false, hasResult: false });\n }\n break;\n }\n case EventType.TOOL_CALL_END:\n case EventType.TOOL_CALL_RESULT: {\n const toolCallId = (event as { toolCallId?: string }).toolCallId;\n if (!toolCallId) break;\n const info = openToolCalls.get(toolCallId);\n if (!info) break;\n\n if (event.type === EventType.TOOL_CALL_END) info.hasEnd = true;\n else info.hasResult = true;\n if (info.hasEnd && info.hasResult) openToolCalls.delete(toolCallId);\n break;\n }\n case EventType.SUBAGENT_STARTED:\n case EventType.SUBAGENT_FINISHED:\n case EventType.SUBAGENT_ERROR: {\n const subagentRunId = (event as { subagentRunId?: string })\n .subagentRunId;\n if (!subagentRunId) break;\n if (event.type === EventType.SUBAGENT_STARTED) {\n openSubagentRunIds.add(subagentRunId);\n } else {\n openSubagentRunIds.delete(subagentRunId);\n }\n break;\n }\n case EventType.RUN_FINISHED:\n case EventType.RUN_ERROR:\n terminalEventObserved = true;\n clearOpen();\n break;\n case EventType.TEXT_MESSAGE_CONTENT:\n case EventType.TEXT_MESSAGE_CHUNK:\n case EventType.TOOL_CALL_ARGS:\n case EventType.TOOL_CALL_CHUNK:\n case EventType.STATE_SNAPSHOT:\n case EventType.STATE_DELTA:\n case EventType.MESSAGES_SNAPSHOT:\n case EventType.ACTIVITY_SNAPSHOT:\n case EventType.ACTIVITY_DELTA:\n case EventType.RAW:\n case EventType.CUSTOM:\n case EventType.STEP_STARTED:\n case EventType.STEP_FINISHED:\n case EventType.REASONING_MESSAGE_CONTENT:\n case EventType.REASONING_MESSAGE_CHUNK:\n case EventType.REASONING_ENCRYPTED_VALUE:\n default:\n break;\n }\n };\n\n const finalize = (options: FinalizeRunOptions = {}): BaseEvent[] => {\n if (terminalEventObserved) return [];\n\n const { stopRequested = false, interruptionMessage } = options;\n const resolvedStopMessage = interruptionMessage ?? defaultStopMessage;\n const resolvedAbruptMessage =\n interruptionMessage && interruptionMessage !== defaultStopMessage\n ? interruptionMessage\n : defaultAbruptEndMessage;\n const appended: BaseEvent[] = [];\n\n // A reasoning message closes before the span that holds it.\n for (const messageId of openReasoningMessageIds) {\n appended.push({\n type: EventType.REASONING_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n for (const messageId of openReasoningSpanIds) {\n appended.push({ type: EventType.REASONING_END, messageId } as BaseEvent);\n }\n\n for (const messageId of openMessageIds) {\n appended.push({\n type: EventType.TEXT_MESSAGE_END,\n messageId,\n } as BaseEvent);\n }\n\n for (const [toolCallId, info] of openToolCalls) {\n if (!info.hasEnd) {\n appended.push({\n type: EventType.TOOL_CALL_END,\n toolCallId,\n } as BaseEvent);\n }\n\n if (!info.hasResult) {\n appended.push({\n type: EventType.TOOL_CALL_RESULT,\n toolCallId,\n messageId: `${toolCallId}-result`,\n role: \"tool\",\n content: JSON.stringify(\n stopRequested\n ? {\n status: \"stopped\",\n reason: \"stop_requested\",\n message: resolvedStopMessage,\n }\n : {\n status: \"error\",\n reason: \"missing_terminal_event\",\n message: resolvedAbruptMessage,\n },\n ),\n } as BaseEvent);\n }\n }\n\n if (stopRequested) {\n // Newest first, so a nested subagent closes before its parent. An index\n // loop, because `toReversed` is ES2023 and this package targets older.\n const openIds = [...openSubagentRunIds];\n for (let index = openIds.length - 1; index >= 0; index -= 1) {\n appended.push({\n type: EventType.SUBAGENT_ERROR,\n subagentRunId: openIds[index],\n message: resolvedStopMessage,\n code: \"CANCELLED\",\n } as BaseEvent);\n }\n appended.push({\n type: EventType.RUN_FINISHED,\n ...(runIdentity.threadId !== undefined\n ? { threadId: runIdentity.threadId }\n : {}),\n ...(runIdentity.runId !== undefined\n ? { runId: runIdentity.runId }\n : {}),\n ...(options.protocolVersion !== undefined\n ? { outcome: { type: \"cancelled\" } }\n : {}),\n } as BaseEvent);\n } else {\n const errorEvent: RunErrorEvent = {\n type: EventType.RUN_ERROR,\n message: resolvedAbruptMessage,\n code: \"INCOMPLETE_STREAM\",\n };\n appended.push(errorEvent);\n }\n\n terminalEventObserved = true;\n clearOpen();\n return appended;\n };\n\n return { observe, finalize };\n}\n\n/**\n * Array form of {@link createRunEventFinalizer} for callers that already keep\n * the run's events (runners persist them). Appends the closers to `events` in\n * place and returns them.\n */\nexport function finalizeRunEvents(\n events: BaseEvent[],\n options: FinalizeRunOptions = {},\n): BaseEvent[] {\n const finalizer = createRunEventFinalizer();\n for (const event of events) finalizer.observe(event);\n\n const appended = finalizer.finalize(options);\n events.push(...appended);\n return appended;\n}\n"],"mappings":";;;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;;;;;;;;;;;AAiBhC,SAAgB,0BAA6C;CAC3D,MAAM,iCAAiB,IAAI,KAAa;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AAS,QAAQ;AAC5C,QAAO,KAAK,GAAG,SAAS;AACxB,QAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.d.cts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAGiB,kBAAA;EACf,aAAA;EACA,mBAAA;EAFiC;;;;;;EASjC,eAAA;AAAA;AAAA,UAGe,iBAAA;EAAiB;EAEhC,OAAA,CAAQ,KAAA,EAAO,SAAA;EAAA;EAEf,QAAA,CAAS,OAAA,GAAU,kBAAA,GAAqB,SAAA;AAAA;;;;;;;;;;;iBAqB1B,uBAAA,CAAA,GAA2B,iBAAA;AAA3C;;;;;AAAA,iBAiNgB,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
1
+ {"version":3,"file":"finalize-events.d.cts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAGiB,kBAAA;EACf,aAAA;EACA,mBAAA;EAFiC;;;;;;EASjC,eAAA;AAAA;AAAA,UAGe,iBAAA;EAAiB;EAEhC,OAAA,CAAQ,KAAA,EAAO,SAAA;EAAA;EAEf,QAAA,CAAS,OAAA,GAAU,kBAAA,GAAqB,SAAA;AAAA;;;;;;;;;;;iBAqB1B,uBAAA,CAAA,GAA2B,iBAAA;AAA3C;;;;;AAAA,iBAiOgB,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"finalize-events.d.mts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAGiB,kBAAA;EACf,aAAA;EACA,mBAAA;EAFiC;;;;;;EASjC,eAAA;AAAA;AAAA,UAGe,iBAAA;EAAiB;EAEhC,OAAA,CAAQ,KAAA,EAAO,SAAA;EAAA;EAEf,QAAA,CAAS,OAAA,GAAU,kBAAA,GAAqB,SAAA;AAAA;;;;;;;;;;;iBAqB1B,uBAAA,CAAA,GAA2B,iBAAA;AAA3C;;;;;AAAA,iBAiNgB,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
1
+ {"version":3,"file":"finalize-events.d.mts","names":[],"sources":["../src/finalize-events.ts"],"mappings":";;;UAGiB,kBAAA;EACf,aAAA;EACA,mBAAA;EAFiC;;;;;;EASjC,eAAA;AAAA;AAAA,UAGe,iBAAA;EAAiB;EAEhC,OAAA,CAAQ,KAAA,EAAO,SAAA;EAAA;EAEf,QAAA,CAAS,OAAA,GAAU,kBAAA,GAAqB,SAAA;AAAA;;;;;;;;;;;iBAqB1B,uBAAA,CAAA,GAA2B,iBAAA;AAA3C;;;;;AAAA,iBAiOgB,iBAAA,CACd,MAAA,EAAQ,SAAA,IACR,OAAA,GAAS,kBAAA,GACR,SAAA"}
@@ -93,6 +93,22 @@ function createRunEventFinalizer() {
93
93
  terminalEventObserved = true;
94
94
  clearOpen();
95
95
  break;
96
+ case EventType.TEXT_MESSAGE_CONTENT:
97
+ case EventType.TEXT_MESSAGE_CHUNK:
98
+ case EventType.TOOL_CALL_ARGS:
99
+ case EventType.TOOL_CALL_CHUNK:
100
+ case EventType.STATE_SNAPSHOT:
101
+ case EventType.STATE_DELTA:
102
+ case EventType.MESSAGES_SNAPSHOT:
103
+ case EventType.ACTIVITY_SNAPSHOT:
104
+ case EventType.ACTIVITY_DELTA:
105
+ case EventType.RAW:
106
+ case EventType.CUSTOM:
107
+ case EventType.STEP_STARTED:
108
+ case EventType.STEP_FINISHED:
109
+ case EventType.REASONING_MESSAGE_CONTENT:
110
+ case EventType.REASONING_MESSAGE_CHUNK:
111
+ case EventType.REASONING_ENCRYPTED_VALUE:
96
112
  default: break;
97
113
  }
98
114
  };