@copilotkit/shared 2.0.0-rc.2 → 2.0.0-rc.20

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 (272) hide show
  1. package/README.md +3 -14
  2. package/dist/a2ui-envelope.cjs +2 -2
  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 +2 -2
  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/finalize-events.cjs +16 -0
  19. package/dist/finalize-events.cjs.map +1 -1
  20. package/dist/finalize-events.d.cts.map +1 -1
  21. package/dist/finalize-events.d.mts.map +1 -1
  22. package/dist/finalize-events.mjs +16 -0
  23. package/dist/finalize-events.mjs.map +1 -1
  24. package/dist/generative-ui/basic-functions.cjs +1 -1
  25. package/dist/generative-ui/basic-functions.cjs.map +1 -1
  26. package/dist/generative-ui/basic-functions.mjs +1 -1
  27. package/dist/generative-ui/basic-functions.mjs.map +1 -1
  28. package/dist/generative-ui/child-refs.cjs +3 -3
  29. package/dist/generative-ui/child-refs.cjs.map +1 -1
  30. package/dist/generative-ui/child-refs.d.cts.map +1 -1
  31. package/dist/generative-ui/child-refs.d.mts.map +1 -1
  32. package/dist/generative-ui/child-refs.mjs +3 -3
  33. package/dist/generative-ui/child-refs.mjs.map +1 -1
  34. package/dist/generative-ui/compact-schema.cjs +187 -0
  35. package/dist/generative-ui/compact-schema.cjs.map +1 -0
  36. package/dist/generative-ui/compact-schema.d.cts +55 -0
  37. package/dist/generative-ui/compact-schema.d.cts.map +1 -0
  38. package/dist/generative-ui/compact-schema.d.mts +55 -0
  39. package/dist/generative-ui/compact-schema.d.mts.map +1 -0
  40. package/dist/generative-ui/compact-schema.mjs +185 -0
  41. package/dist/generative-ui/compact-schema.mjs.map +1 -0
  42. package/dist/generative-ui/prompt-spec.cjs +225 -0
  43. package/dist/generative-ui/prompt-spec.cjs.map +1 -0
  44. package/dist/generative-ui/prompt-spec.d.cts +94 -0
  45. package/dist/generative-ui/prompt-spec.d.cts.map +1 -0
  46. package/dist/generative-ui/prompt-spec.d.mts +94 -0
  47. package/dist/generative-ui/prompt-spec.d.mts.map +1 -0
  48. package/dist/generative-ui/prompt-spec.mjs +220 -0
  49. package/dist/generative-ui/prompt-spec.mjs.map +1 -0
  50. package/dist/generative-ui/prompt.cjs +10 -36
  51. package/dist/generative-ui/prompt.cjs.map +1 -1
  52. package/dist/generative-ui/prompt.d.cts +2 -1
  53. package/dist/generative-ui/prompt.d.cts.map +1 -1
  54. package/dist/generative-ui/prompt.d.mts +2 -1
  55. package/dist/generative-ui/prompt.d.mts.map +1 -1
  56. package/dist/generative-ui/prompt.mjs +12 -38
  57. package/dist/generative-ui/prompt.mjs.map +1 -1
  58. package/dist/generative-ui/render-ui-args.cjs +1 -0
  59. package/dist/generative-ui/render-ui-args.cjs.map +1 -1
  60. package/dist/generative-ui/render-ui-args.d.cts.map +1 -1
  61. package/dist/generative-ui/render-ui-args.d.mts.map +1 -1
  62. package/dist/generative-ui/render-ui-args.mjs +1 -0
  63. package/dist/generative-ui/render-ui-args.mjs.map +1 -1
  64. package/dist/generative-ui/schema-render.cjs +242 -0
  65. package/dist/generative-ui/schema-render.cjs.map +1 -0
  66. package/dist/generative-ui/schema-render.d.cts +44 -0
  67. package/dist/generative-ui/schema-render.d.cts.map +1 -0
  68. package/dist/generative-ui/schema-render.d.mts +44 -0
  69. package/dist/generative-ui/schema-render.d.mts.map +1 -0
  70. package/dist/generative-ui/schema-render.mjs +239 -0
  71. package/dist/generative-ui/schema-render.mjs.map +1 -0
  72. package/dist/generative-ui/types.cjs +2 -2
  73. package/dist/generative-ui/types.cjs.map +1 -1
  74. package/dist/generative-ui/types.d.cts +7 -7
  75. package/dist/generative-ui/types.d.cts.map +1 -1
  76. package/dist/generative-ui/types.d.mts +7 -7
  77. package/dist/generative-ui/types.d.mts.map +1 -1
  78. package/dist/generative-ui/types.mjs +2 -2
  79. package/dist/generative-ui/types.mjs.map +1 -1
  80. package/dist/generative-ui/validate-operation.cjs +2 -2
  81. package/dist/generative-ui/validate-operation.cjs.map +1 -1
  82. package/dist/generative-ui/validate-operation.mjs +2 -2
  83. package/dist/generative-ui/validate-operation.mjs.map +1 -1
  84. package/dist/index.cjs +17 -15
  85. package/dist/index.cjs.map +1 -1
  86. package/dist/index.d.cts +10 -9
  87. package/dist/index.d.cts.map +1 -1
  88. package/dist/index.d.mts +10 -9
  89. package/dist/index.d.mts.map +1 -1
  90. package/dist/index.mjs +9 -7
  91. package/dist/index.mjs.map +1 -1
  92. package/dist/index.umd.js +839 -447
  93. package/dist/index.umd.js.map +1 -1
  94. package/dist/package.cjs +1 -1
  95. package/dist/package.mjs +1 -1
  96. package/dist/standard-schema.cjs +20 -7
  97. package/dist/standard-schema.cjs.map +1 -1
  98. package/dist/standard-schema.d.cts +15 -16
  99. package/dist/standard-schema.d.cts.map +1 -1
  100. package/dist/standard-schema.d.mts +15 -16
  101. package/dist/standard-schema.d.mts.map +1 -1
  102. package/dist/standard-schema.mjs +20 -8
  103. package/dist/standard-schema.mjs.map +1 -1
  104. package/dist/telemetry/lambda-client.cjs +1 -1
  105. package/dist/telemetry/lambda-client.cjs.map +1 -1
  106. package/dist/telemetry/lambda-client.d.cts.map +1 -1
  107. package/dist/telemetry/lambda-client.d.mts.map +1 -1
  108. package/dist/telemetry/lambda-client.mjs +1 -1
  109. package/dist/telemetry/lambda-client.mjs.map +1 -1
  110. package/dist/telemetry/telemetry-disabled.cjs +3 -6
  111. package/dist/telemetry/telemetry-disabled.cjs.map +1 -1
  112. package/dist/telemetry/telemetry-disabled.d.cts +0 -5
  113. package/dist/telemetry/telemetry-disabled.d.cts.map +1 -1
  114. package/dist/telemetry/telemetry-disabled.d.mts +0 -5
  115. package/dist/telemetry/telemetry-disabled.d.mts.map +1 -1
  116. package/dist/telemetry/telemetry-disabled.mjs +4 -6
  117. package/dist/telemetry/telemetry-disabled.mjs.map +1 -1
  118. package/dist/types/message.d.cts +1 -18
  119. package/dist/types/message.d.cts.map +1 -1
  120. package/dist/types/message.d.mts +1 -18
  121. package/dist/types/message.d.mts.map +1 -1
  122. package/dist/utils/errors.cjs +5 -42
  123. package/dist/utils/errors.cjs.map +1 -1
  124. package/dist/utils/errors.d.cts +16 -34
  125. package/dist/utils/errors.d.cts.map +1 -1
  126. package/dist/utils/errors.d.mts +16 -34
  127. package/dist/utils/errors.d.mts.map +1 -1
  128. package/dist/utils/errors.mjs +6 -41
  129. package/dist/utils/errors.mjs.map +1 -1
  130. package/dist/utils/index.cjs +1 -2
  131. package/dist/utils/index.cjs.map +1 -1
  132. package/dist/utils/index.d.cts +4 -5
  133. package/dist/utils/index.d.cts.map +1 -1
  134. package/dist/utils/index.d.mts +4 -5
  135. package/dist/utils/index.d.mts.map +1 -1
  136. package/dist/utils/index.mjs +4 -5
  137. package/dist/utils/index.mjs.map +1 -1
  138. package/dist/utils/json-schema.cjs +4 -79
  139. package/dist/utils/json-schema.cjs.map +1 -1
  140. package/dist/utils/json-schema.d.cts +1 -4
  141. package/dist/utils/json-schema.d.cts.map +1 -1
  142. package/dist/utils/json-schema.d.mts +1 -4
  143. package/dist/utils/json-schema.d.mts.map +1 -1
  144. package/dist/utils/json-schema.mjs +5 -78
  145. package/dist/utils/json-schema.mjs.map +1 -1
  146. package/dist/utils/process-env.cjs +14 -0
  147. package/dist/utils/process-env.cjs.map +1 -0
  148. package/dist/utils/process-env.d.cts +10 -0
  149. package/dist/utils/process-env.d.cts.map +1 -0
  150. package/dist/utils/process-env.d.mts +10 -0
  151. package/dist/utils/process-env.d.mts.map +1 -0
  152. package/dist/utils/process-env.mjs +13 -0
  153. package/dist/utils/process-env.mjs.map +1 -0
  154. package/dist/utils/random-id.cjs +13 -26
  155. package/dist/utils/random-id.cjs.map +1 -1
  156. package/dist/utils/random-id.d.cts +6 -3
  157. package/dist/utils/random-id.d.cts.map +1 -1
  158. package/dist/utils/random-id.d.mts +6 -3
  159. package/dist/utils/random-id.d.mts.map +1 -1
  160. package/dist/utils/random-id.mjs +14 -25
  161. package/dist/utils/random-id.mjs.map +1 -1
  162. package/package.json +8 -32
  163. package/scripts/verify-cjs-exports.cjs +1 -1
  164. package/src/__tests__/a2ui-envelope.test.ts +18 -13
  165. package/src/__tests__/a2ui-prompts.test.ts +47 -14
  166. package/src/__tests__/fixtures/prompt-goldens.json +354 -0
  167. package/src/__tests__/prompt-spec.test.ts +191 -0
  168. package/src/__tests__/root-entry-browser-safety.test.ts +5 -7
  169. package/src/__tests__/schema-render.test.ts +245 -0
  170. package/src/__tests__/standard-schema.test.ts +61 -101
  171. package/src/a2ui-envelope.ts +7 -6
  172. package/src/a2ui-prompts.ts +47 -96
  173. package/src/finalize-events.ts +16 -0
  174. package/src/generative-ui/__tests__/render-ui-args.test.ts +7 -7
  175. package/src/generative-ui/__tests__/validate-operation.test.ts +19 -13
  176. package/src/generative-ui/basic-functions.ts +1 -1
  177. package/src/generative-ui/child-refs.ts +5 -4
  178. package/src/generative-ui/compact-schema.ts +277 -0
  179. package/src/generative-ui/index.ts +3 -0
  180. package/src/generative-ui/prompt-spec.ts +335 -0
  181. package/src/generative-ui/prompt.ts +25 -75
  182. package/src/generative-ui/render-ui-args.ts +3 -0
  183. package/src/generative-ui/schema-render.ts +377 -0
  184. package/src/generative-ui/types.ts +10 -7
  185. package/src/generative-ui/validate-operation.ts +2 -2
  186. package/src/index.ts +3 -16
  187. package/src/standard-schema.ts +24 -27
  188. package/src/telemetry/lambda-client.ts +8 -3
  189. package/src/telemetry/model-host.test.ts +2 -5
  190. package/src/telemetry/telemetry-disabled.ts +7 -12
  191. package/src/types/message.ts +1 -19
  192. package/src/utils/__tests__/errors.test.ts +44 -0
  193. package/src/utils/__tests__/json-schema.test.ts +3 -479
  194. package/src/utils/__tests__/process-env.test.ts +22 -0
  195. package/src/utils/__tests__/random-id.test.ts +37 -0
  196. package/src/utils/errors.ts +28 -85
  197. package/src/utils/index.ts +1 -2
  198. package/src/utils/json-schema.ts +5 -152
  199. package/src/utils/process-env.ts +14 -0
  200. package/src/utils/random-id.ts +17 -37
  201. package/tsconfig.json +3 -1
  202. package/tsdown.config.ts +2 -19
  203. package/dist/event-transforms/index.cjs +0 -15
  204. package/dist/event-transforms/index.d.cts +0 -4
  205. package/dist/event-transforms/index.d.mts +0 -4
  206. package/dist/event-transforms/index.mjs +0 -5
  207. package/dist/event-transforms/open-generative-ui-middleware.cjs +0 -286
  208. package/dist/event-transforms/open-generative-ui-middleware.cjs.map +0 -1
  209. package/dist/event-transforms/open-generative-ui-middleware.d.cts +0 -60
  210. package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +0 -1
  211. package/dist/event-transforms/open-generative-ui-middleware.d.mts +0 -60
  212. package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +0 -1
  213. package/dist/event-transforms/open-generative-ui-middleware.mjs +0 -283
  214. package/dist/event-transforms/open-generative-ui-middleware.mjs.map +0 -1
  215. package/dist/event-transforms/recorded-events.cjs +0 -59
  216. package/dist/event-transforms/recorded-events.cjs.map +0 -1
  217. package/dist/event-transforms/recorded-events.d.cts +0 -23
  218. package/dist/event-transforms/recorded-events.d.cts.map +0 -1
  219. package/dist/event-transforms/recorded-events.d.mts +0 -23
  220. package/dist/event-transforms/recorded-events.d.mts.map +0 -1
  221. package/dist/event-transforms/recorded-events.mjs +0 -58
  222. package/dist/event-transforms/recorded-events.mjs.map +0 -1
  223. package/dist/telemetry/events.d.cts +0 -72
  224. package/dist/telemetry/events.d.cts.map +0 -1
  225. package/dist/telemetry/events.d.mts +0 -72
  226. package/dist/telemetry/events.d.mts.map +0 -1
  227. package/dist/telemetry/index.cjs +0 -18
  228. package/dist/telemetry/index.d.cts +0 -5
  229. package/dist/telemetry/index.d.mts +0 -5
  230. package/dist/telemetry/index.mjs +0 -6
  231. package/dist/telemetry/telemetry-client.cjs +0 -165
  232. package/dist/telemetry/telemetry-client.cjs.map +0 -1
  233. package/dist/telemetry/telemetry-client.d.cts +0 -87
  234. package/dist/telemetry/telemetry-client.d.cts.map +0 -1
  235. package/dist/telemetry/telemetry-client.d.mts +0 -87
  236. package/dist/telemetry/telemetry-client.d.mts.map +0 -1
  237. package/dist/telemetry/telemetry-client.mjs +0 -164
  238. package/dist/telemetry/telemetry-client.mjs.map +0 -1
  239. package/dist/telemetry/utils.cjs +0 -14
  240. package/dist/telemetry/utils.cjs.map +0 -1
  241. package/dist/telemetry/utils.mjs +0 -13
  242. package/dist/telemetry/utils.mjs.map +0 -1
  243. package/dist/utils/conditions.cjs +0 -32
  244. package/dist/utils/conditions.cjs.map +0 -1
  245. package/dist/utils/conditions.d.cts +0 -31
  246. package/dist/utils/conditions.d.cts.map +0 -1
  247. package/dist/utils/conditions.d.mts +0 -31
  248. package/dist/utils/conditions.d.mts.map +0 -1
  249. package/dist/utils/conditions.mjs +0 -31
  250. package/dist/utils/conditions.mjs.map +0 -1
  251. package/dist/utils/console-styling.cjs +0 -91
  252. package/dist/utils/console-styling.cjs.map +0 -1
  253. package/dist/utils/console-styling.d.cts +0 -65
  254. package/dist/utils/console-styling.d.cts.map +0 -1
  255. package/dist/utils/console-styling.d.mts +0 -65
  256. package/dist/utils/console-styling.d.mts.map +0 -1
  257. package/dist/utils/console-styling.mjs +0 -85
  258. package/dist/utils/console-styling.mjs.map +0 -1
  259. package/src/__tests__/zod-regression.test.ts +0 -319
  260. package/src/event-transforms/index.ts +0 -5
  261. package/src/event-transforms/open-generative-ui-middleware.ts +0 -392
  262. package/src/event-transforms/recorded-events.test.ts +0 -166
  263. package/src/event-transforms/recorded-events.ts +0 -74
  264. package/src/telemetry/events.ts +0 -68
  265. package/src/telemetry/index.ts +0 -9
  266. package/src/telemetry/telemetry-blank-license-identity.test.ts +0 -128
  267. package/src/telemetry/telemetry-client.test.ts +0 -798
  268. package/src/telemetry/telemetry-client.ts +0 -328
  269. package/src/telemetry/utils.ts +0 -15
  270. package/src/utils/__tests__/conditions.test.ts +0 -161
  271. package/src/utils/conditions.ts +0 -116
  272. package/src/utils/console-styling.ts +0 -126
package/dist/index.umd.js CHANGED
@@ -1,8 +1,8 @@
1
1
  (function(global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('graphql'), require('zod'), require('uuid'), require('partial-json'), require('@ag-ui/client')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'graphql', 'zod', 'uuid', 'partial-json', '@ag-ui/client'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitShared = {}), global.GraphQL,global.Zod,global.UUID,global.PartialJSON,global.AgUIClient));
5
- })(this, function(exports, graphql, zod, uuid, partial_json, _ag_ui_client) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('partial-json'), require('@ag-ui/client')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'partial-json', '@ag-ui/client'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitShared = {}), global.PartialJSON,global.AgUIClient));
5
+ })(this, function(exports, partial_json, _ag_ui_client) {
6
6
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
7
7
  //#region \0rolldown/runtime.js
8
8
  var __create = Object.create;
@@ -58,118 +58,6 @@ partial_json = __toESM(partial_json);
58
58
  }
59
59
  }
60
60
 
61
- //#endregion
62
- //#region src/utils/conditions.ts
63
- function executeConditions({ conditions, value }) {
64
- if (!(conditions === null || conditions === void 0 ? void 0 : conditions.length)) return true;
65
- return conditions.every((condition) => executeCondition(condition, value));
66
- }
67
- function executeCondition(condition, value) {
68
- const targetValue = condition.path ? getValueFromPath(value, condition.path) : value;
69
- switch (condition.rule) {
70
- case "AND": return condition.conditions.every((c) => executeCondition(c, value));
71
- case "OR": return condition.conditions.some((c) => executeCondition(c, value));
72
- case "NOT": return !condition.conditions.every((c) => executeCondition(c, value));
73
- case "EQUALS": return targetValue === condition.value;
74
- case "NOT_EQUALS": return targetValue !== condition.value;
75
- case "GREATER_THAN": return targetValue > condition.value;
76
- case "LESS_THAN": return targetValue < condition.value;
77
- case "CONTAINS": return Array.isArray(targetValue) && targetValue.includes(condition.value);
78
- case "NOT_CONTAINS": return Array.isArray(targetValue) && !targetValue.includes(condition.value);
79
- case "MATCHES": return new RegExp(condition.value).test(String(targetValue));
80
- case "STARTS_WITH": return String(targetValue).startsWith(condition.value);
81
- case "ENDS_WITH": return String(targetValue).endsWith(condition.value);
82
- case "EXISTS": return targetValue !== void 0 && targetValue !== null;
83
- case "NOT_EXISTS": return targetValue === void 0 || targetValue === null;
84
- }
85
- }
86
- function getValueFromPath(obj, path) {
87
- return path.split(".").reduce((acc, part) => acc === null || acc === void 0 ? void 0 : acc[part], obj);
88
- }
89
-
90
- //#endregion
91
- //#region src/utils/console-styling.ts
92
- /**
93
- * Console styling utilities for CopilotKit branded messages
94
- * Provides consistent, readable colors across light and dark console themes
95
- */
96
- /**
97
- * Color palette optimized for console readability
98
- */
99
- const ConsoleColors = {
100
- primary: "#007acc",
101
- success: "#22c55e",
102
- feature: "#a855f7",
103
- cta: "#ef4444",
104
- info: "#06b6d4",
105
- inherit: "inherit",
106
- warning: "#f59e0b"
107
- };
108
- /**
109
- * Console style templates for common patterns
110
- */
111
- const ConsoleStyles = {
112
- header: `color: ${ConsoleColors.warning}; font-weight: bold; font-size: 16px;`,
113
- section: `color: ${ConsoleColors.success}; font-weight: bold;`,
114
- highlight: `color: ${ConsoleColors.feature}; font-weight: bold;`,
115
- cta: `color: ${ConsoleColors.success}; font-weight: bold;`,
116
- info: `color: ${ConsoleColors.info}; font-weight: bold;`,
117
- link: `color: ${ConsoleColors.primary}; text-decoration: underline;`,
118
- body: `color: ${ConsoleColors.inherit};`,
119
- warning: `color: ${ConsoleColors.cta}; font-weight: bold;`
120
- };
121
- /**
122
- * Styled console message for CopilotKit Platform promotion
123
- * Displays a beautiful, branded advertisement in the console
124
- */
125
- function logCopilotKitPlatformMessage() {
126
- console.log(`%cCopilotKit Warning%c
127
-
128
- useCopilotChatHeadless_c provides full compatibility with CopilotKit's newly released Headless UI feature set. Headless UI requires a CopilotKit Intelligence license key, available for free at:
129
-
130
- %chttps://dashboard.operations.copilotkit.ai%c
131
-
132
- Alternatively, useCopilotChat is available for basic programmatic control, and does not require a license key.
133
-
134
- To learn more about CopilotKit Intelligence, read the documentation here:
135
-
136
- %chttps://docs.copilotkit.ai/intelligence/overview%c`, ConsoleStyles.header, ConsoleStyles.body, ConsoleStyles.cta, ConsoleStyles.body, ConsoleStyles.link, ConsoleStyles.body);
137
- }
138
- function publicApiKeyRequired(feature) {
139
- console.log(`
140
- %cCopilotKit Warning%c \n
141
- In order to use ${feature}, you need to add your CopilotKit license key, available for free at https://dashboard.operations.copilotkit.ai.
142
- `.trim(), ConsoleStyles.header, ConsoleStyles.body);
143
- }
144
- /**
145
- * Create a styled console message with custom content
146
- *
147
- * @param template - Template string with %c placeholders
148
- * @param styles - Array of style strings matching the %c placeholders
149
- *
150
- * @example
151
- * ```typescript
152
- * logStyled(
153
- * '%cCopilotKit%c Welcome to the platform!',
154
- * [ConsoleStyles.header, ConsoleStyles.body]
155
- * );
156
- * ```
157
- */
158
- function logStyled(template, styles) {
159
- console.log(template, ...styles);
160
- }
161
- /**
162
- * Quick styled console methods for common use cases
163
- */
164
- const styledConsole = {
165
- success: (message) => logStyled(`%c✅ ${message}`, [ConsoleStyles.section]),
166
- info: (message) => logStyled(`%cℹ️ ${message}`, [ConsoleStyles.info]),
167
- feature: (message) => logStyled(`%c✨ ${message}`, [ConsoleStyles.highlight]),
168
- cta: (message) => logStyled(`%c🚀 ${message}`, [ConsoleStyles.cta]),
169
- logCopilotKitPlatformMessage,
170
- publicApiKeyRequired
171
- };
172
-
173
61
  //#endregion
174
62
  //#region src/utils/errors.ts
175
63
  let Severity = /* @__PURE__ */ function(Severity) {
@@ -191,7 +79,6 @@ In order to use ${feature}, you need to add your CopilotKit license key, availab
191
79
  COPILOT_REMOTE_ENDPOINT_DISCOVERY_ERROR: "CopilotKitRemoteEndpointDiscoveryError",
192
80
  COPILOT_KIT_AGENT_DISCOVERY_ERROR: "CopilotKitAgentDiscoveryError",
193
81
  COPILOT_KIT_LOW_LEVEL_ERROR: "CopilotKitLowLevelError",
194
- COPILOT_KIT_VERSION_MISMATCH_ERROR: "CopilotKitVersionMismatchError",
195
82
  RESOLVED_COPILOT_KIT_ERROR: "ResolvedCopilotKitError",
196
83
  CONFIGURATION_ERROR: "ConfigurationError",
197
84
  MISSING_PUBLIC_API_KEY_ERROR: "MissingPublicApiKeyError",
@@ -296,7 +183,7 @@ In order to use ${feature}, you need to add your CopilotKit license key, availab
296
183
  severity: Severity.INFO
297
184
  }
298
185
  };
299
- var CopilotKitError = class extends graphql.GraphQLError {
186
+ var CopilotKitError = class extends Error {
300
187
  constructor({ message = "Unknown error occurred", code, severity, visibility }) {
301
188
  var _ref;
302
189
  const name = ERROR_NAMES.COPILOT_ERROR;
@@ -304,7 +191,8 @@ In order to use ${feature}, you need to add your CopilotKit license key, availab
304
191
  const { statusCode } = config;
305
192
  const resolvedVisibility = (_ref = visibility !== null && visibility !== void 0 ? visibility : config.visibility) !== null && _ref !== void 0 ? _ref : ErrorVisibility.TOAST;
306
193
  const resolvedSeverity = severity !== null && severity !== void 0 ? severity : "severity" in config ? config.severity : void 0;
307
- super(message, { extensions: {
194
+ super(message);
195
+ this.extensions = {
308
196
  name,
309
197
  statusCode,
310
198
  code,
@@ -315,7 +203,7 @@ In order to use ${feature}, you need to add your CopilotKit license key, availab
315
203
  message,
316
204
  stack: (/* @__PURE__ */ new Error()).stack
317
205
  }
318
- } });
206
+ };
319
207
  this.code = code;
320
208
  this.name = name;
321
209
  this.statusCode = statusCode;
@@ -340,26 +228,6 @@ In order to use ${feature}, you need to add your CopilotKit license key, availab
340
228
  this.name = ERROR_NAMES.COPILOT_API_DISCOVERY_ERROR;
341
229
  }
342
230
  };
343
- const getVersionMismatchErrorMessage = ({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) => `Version mismatch detected: @copilotkit/runtime@${runtimeVersion !== null && runtimeVersion !== void 0 ? runtimeVersion : ""} is not compatible with @copilotkit/react-core@${reactCoreVersion} and @copilotkit/runtime-client-gql@${runtimeClientGqlVersion}. Please ensure all installed copilotkit packages are on the same version.`;
344
- /**
345
- * Error thrown when CPK versions does not match
346
- *
347
- * @extends CopilotKitError
348
- */
349
- var CopilotKitVersionMismatchError = class extends CopilotKitError {
350
- constructor({ reactCoreVersion, runtimeVersion, runtimeClientGqlVersion }) {
351
- const code = CopilotKitErrorCode.VERSION_MISMATCH;
352
- super({
353
- message: getVersionMismatchErrorMessage({
354
- reactCoreVersion,
355
- runtimeVersion,
356
- runtimeClientGqlVersion
357
- }),
358
- code
359
- });
360
- this.name = ERROR_NAMES.COPILOT_KIT_VERSION_MISMATCH_ERROR;
361
- }
362
- };
363
231
  /**
364
232
  * Error thrown when the CopilotKit API endpoint cannot be discovered or accessed.
365
233
  * This typically occurs when:
@@ -550,19 +418,6 @@ In order to use ${feature}, you need to add your CopilotKit license key, availab
550
418
  function ensureStructuredError(error, converter) {
551
419
  return isStructuredCopilotKitError(error) ? error : converter(error);
552
420
  }
553
- async function getPossibleVersionMismatch({ runtimeVersion, runtimeClientGqlVersion }) {
554
- if (!runtimeVersion || runtimeVersion === "" || !runtimeClientGqlVersion) return;
555
- if (COPILOTKIT_VERSION !== runtimeVersion || COPILOTKIT_VERSION !== runtimeClientGqlVersion || runtimeVersion !== runtimeClientGqlVersion) return {
556
- runtimeVersion,
557
- runtimeClientGqlVersion,
558
- reactCoreVersion: COPILOTKIT_VERSION,
559
- message: getVersionMismatchErrorMessage({
560
- runtimeVersion,
561
- runtimeClientGqlVersion,
562
- reactCoreVersion: COPILOTKIT_VERSION
563
- })
564
- };
565
- }
566
421
  const resolveLowLevelErrorMessage = ({ errorCode, url }) => {
567
422
  const troubleshootingLink = ERROR_CONFIG[CopilotKitErrorCode.NETWORK_ERROR].troubleshootingUrl;
568
423
  const genericMessage = (description = `Failed to fetch from url ${url}.`) => `${description}.
@@ -583,6 +438,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
583
438
  case "ECONNREFUSED": return `Connection to ${url} was refused. Ensure the server is running and accessible.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
584
439
  case "ENOTFOUND": return `The server on ${url} could not be found. Check the URL or your network configuration.\n\n${getSeeMoreMarkdown(ERROR_CONFIG[CopilotKitErrorCode.NOT_FOUND].troubleshootingUrl)}`;
585
440
  case "ETIMEDOUT": return `The connection to ${url} timed out. The server might be overloaded or taking too long to respond.\n\n${getSeeMoreMarkdown(troubleshootingLink)}`;
441
+ case void 0:
586
442
  default: return;
587
443
  }
588
444
  };
@@ -707,6 +563,10 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
707
563
  ...properties && { properties },
708
564
  ...required && required.length > 0 && { required }
709
565
  };
566
+ case "string[]":
567
+ case "number[]":
568
+ case "boolean[]":
569
+ case void 0:
710
570
  default:
711
571
  var _attribute$type;
712
572
  if ((_attribute$type = attribute.type) === null || _attribute$type === void 0 ? void 0 : _attribute$type.endsWith("[]")) return {
@@ -720,82 +580,6 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
720
580
  };
721
581
  }
722
582
  }
723
- function convertJsonSchemaToZodSchema(jsonSchema, required, definitions, visitedRefs) {
724
- var _ref, _jsonSchema$anyOf, _jsonSchema$type;
725
- if (jsonSchema.$ref && definitions) {
726
- const refPath = jsonSchema.$ref.replace(/^#\/\$defs\/|^#\/definitions\//, "");
727
- const refs = visitedRefs !== null && visitedRefs !== void 0 ? visitedRefs : /* @__PURE__ */ new Set();
728
- if (refs.has(refPath)) {
729
- console.warn(`[CopilotKit] Circular $ref detected for "${refPath}" — falling back to z.any()`);
730
- let schema = zod.z.any();
731
- if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
732
- return required ? schema : schema.optional();
733
- }
734
- const resolved = definitions[refPath];
735
- if (resolved) {
736
- const nextRefs = new Set(refs);
737
- nextRefs.add(refPath);
738
- return convertJsonSchemaToZodSchema(resolved, required, definitions, nextRefs);
739
- }
740
- }
741
- const defs = (_ref = definitions !== null && definitions !== void 0 ? definitions : jsonSchema.$defs) !== null && _ref !== void 0 ? _ref : jsonSchema.definitions;
742
- if (Array.isArray(jsonSchema.type)) {
743
- const types = jsonSchema.type;
744
- const hasNull = types.includes("null");
745
- const nonNullTypes = types.filter((t) => t !== "null");
746
- const resolvedType = nonNullTypes.length > 0 ? nonNullTypes[0] : "string";
747
- const innerSchema = convertJsonSchemaToZodSchema({
748
- ...jsonSchema,
749
- type: resolvedType
750
- }, true, defs, visitedRefs);
751
- let schema = hasNull ? zod.z.union([innerSchema, zod.z.null()]) : innerSchema;
752
- if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
753
- return required ? schema : schema.optional();
754
- }
755
- const unionVariants = (_jsonSchema$anyOf = jsonSchema.anyOf) !== null && _jsonSchema$anyOf !== void 0 ? _jsonSchema$anyOf : jsonSchema.oneOf;
756
- if (Array.isArray(unionVariants) && unionVariants.length > 0) {
757
- if (unionVariants.length === 1) return convertJsonSchemaToZodSchema(unionVariants[0], required, defs, visitedRefs);
758
- const schemas = unionVariants.map((v) => convertJsonSchemaToZodSchema(v, true, defs, visitedRefs));
759
- let schema = zod.z.union(schemas);
760
- if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
761
- return required ? schema : schema.optional();
762
- }
763
- if (jsonSchema.type === "object") {
764
- const spec = {};
765
- if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) return !required ? zod.z.object(spec).optional() : zod.z.object(spec);
766
- for (const [key, value] of Object.entries(jsonSchema.properties)) spec[key] = convertJsonSchemaToZodSchema(value, jsonSchema.required ? jsonSchema.required.includes(key) : false, defs, visitedRefs);
767
- let schema = zod.z.object(spec).describe(jsonSchema.description);
768
- return required ? schema : schema.optional();
769
- } else if (jsonSchema.type === "string") {
770
- if (jsonSchema.enum && jsonSchema.enum.length > 0) {
771
- let schema = zod.z.enum(jsonSchema.enum).describe(jsonSchema.description);
772
- return required ? schema : schema.optional();
773
- }
774
- let schema = zod.z.string().describe(jsonSchema.description);
775
- return required ? schema : schema.optional();
776
- } else if (jsonSchema.type === "number" || jsonSchema.type === "integer") {
777
- let schema = zod.z.number().describe(jsonSchema.description);
778
- return required ? schema : schema.optional();
779
- } else if (jsonSchema.type === "boolean") {
780
- let schema = zod.z.boolean().describe(jsonSchema.description);
781
- return required ? schema : schema.optional();
782
- } else if (jsonSchema.type === "array") {
783
- let itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true, defs, visitedRefs);
784
- let schema = zod.z.array(itemSchema).describe(jsonSchema.description);
785
- return required ? schema : schema.optional();
786
- } else if (jsonSchema.type === "null") {
787
- let schema = zod.z.null().describe(jsonSchema.description);
788
- return required ? schema : schema.optional();
789
- }
790
- console.warn(`[CopilotKit] Unsupported JSON schema type "${(_jsonSchema$type = jsonSchema.type) !== null && _jsonSchema$type !== void 0 ? _jsonSchema$type : "unknown"}" — falling back to z.any()`);
791
- let schema = zod.z.any();
792
- if (jsonSchema.description) schema = schema.describe(jsonSchema.description);
793
- return required ? schema : schema.optional();
794
- }
795
- function getZodParameters(parameters) {
796
- if (!parameters) return zod.z.object({});
797
- return convertJsonSchemaToZodSchema(actionParametersToJsonSchema(parameters), true);
798
- }
799
583
 
800
584
  //#endregion
801
585
  //#region src/utils/dashboard-url.ts
@@ -815,7 +599,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
815
599
 
816
600
  //#endregion
817
601
  //#region src/utils/inspector-metadata.ts
818
- function isRecord$1(value) {
602
+ function isRecord$3(value) {
819
603
  if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
820
604
  try {
821
605
  const prototype = Object.getPrototypeOf(value);
@@ -838,7 +622,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
838
622
  return parsed.length > 0 ? parsed : void 0;
839
623
  }
840
624
  function parseIdentity(value) {
841
- if (!isRecord$1(value)) return;
625
+ if (!isRecord$3(value)) return;
842
626
  const organizationName = parseNonBlankString(value.organizationName);
843
627
  const projectName = parseNonBlankString(value.projectName);
844
628
  if (organizationName === void 0 || projectName === void 0) return;
@@ -848,7 +632,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
848
632
  };
849
633
  }
850
634
  function parsePlan(value) {
851
- if (!isRecord$1(value)) return;
635
+ if (!isRecord$3(value)) return;
852
636
  const code = parseNonBlankString(value.code);
853
637
  const label = parseNonBlankString(value.label);
854
638
  if (code === void 0 || label === void 0) return;
@@ -858,7 +642,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
858
642
  };
859
643
  }
860
644
  function parseLicense(value) {
861
- if (!isRecord$1(value)) return;
645
+ if (!isRecord$3(value)) return;
862
646
  switch (value.state) {
863
647
  case "valid":
864
648
  case "none":
@@ -893,7 +677,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
893
677
  return isSafeDashboardUrl(parsed) ? url : void 0;
894
678
  }
895
679
  function parseAction(value) {
896
- if (!isRecord$1(value)) return;
680
+ if (!isRecord$3(value)) return;
897
681
  const kind = parseActionKind(value.kind);
898
682
  const url = parseSafeActionUrl(value.url);
899
683
  if (kind === void 0 || url === void 0) return;
@@ -906,7 +690,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
906
690
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
907
691
  }
908
692
  function parseUsageLimit(value) {
909
- if (!isRecord$1(value)) return;
693
+ if (!isRecord$3(value)) return;
910
694
  if (value.kind === "finite") {
911
695
  if (typeof value.value !== "number" || !Number.isSafeInteger(value.value) || value.value < 1) return;
912
696
  return {
@@ -918,7 +702,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
918
702
  if (value.kind === "unknown") return { kind: "unknown" };
919
703
  }
920
704
  function parseUsage(value) {
921
- if (!isRecord$1(value)) return;
705
+ if (!isRecord$3(value)) return;
922
706
  const limit = parseUsageLimit(value.limit);
923
707
  const used = value.used;
924
708
  if (!isFiniteNonnegativeInteger(used) || limit === void 0) return;
@@ -939,7 +723,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
939
723
  * top-level payload.
940
724
  */
941
725
  function parseInspectorMetadataV1(value) {
942
- if (!isRecord$1(value) || value.schemaVersion !== 1) return;
726
+ if (!isRecord$3(value) || value.schemaVersion !== 1) return;
943
727
  const identity = parseIdentity(value.identity);
944
728
  const plan = parsePlan(value.plan);
945
729
  const license = parseLicense(value.license);
@@ -1184,31 +968,34 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
1184
968
  //#endregion
1185
969
  //#region src/utils/random-id.ts
1186
970
  function randomId() {
1187
- return "ck-" + (0, uuid.v4)();
1188
- }
1189
- function randomUUID() {
1190
- return (0, uuid.v4)();
971
+ return "ck-" + randomUUID();
1191
972
  }
1192
973
  /**
1193
- * Recursively converts an object to a serializable form by converting functions to their string representation.
974
+ * Returns an RFC 4122 version 4 UUID. Uses `crypto.randomUUID()` when it
975
+ * exists, and builds the UUID from `crypto.getRandomValues()` when it does not
976
+ * (React Native's Hermes has no `randomUUID`).
1194
977
  */
1195
- function toSerializable(value) {
1196
- if (typeof value === "function") return value.toString();
1197
- if (Array.isArray(value)) return value.map(toSerializable);
1198
- if (value !== null && typeof value === "object") {
1199
- const result = {};
1200
- for (const key of Object.keys(value)) result[key] = toSerializable(value[key]);
1201
- return result;
1202
- }
1203
- return value;
1204
- }
1205
- function dataToUUID(input, namespace) {
1206
- const BASE_NAMESPACE = "e4b01160-ff74-4c6e-9b27-d53cd930fe8e";
1207
- const boundNamespace = namespace ? (0, uuid.v5)(namespace, BASE_NAMESPACE) : BASE_NAMESPACE;
1208
- return (0, uuid.v5)(typeof input === "string" ? input : JSON.stringify(toSerializable(input)), boundNamespace);
978
+ function randomUUID() {
979
+ const crypto = globalThis.crypto;
980
+ if (typeof (crypto === null || crypto === void 0 ? void 0 : crypto.randomUUID) === "function") return crypto.randomUUID();
981
+ if (typeof (crypto === null || crypto === void 0 ? void 0 : crypto.getRandomValues) !== "function") throw new Error("crypto.getRandomValues() is not available. In React Native, install a polyfill such as react-native-get-random-values.");
982
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
983
+ bytes[6] = bytes[6] & 15 | 64;
984
+ bytes[8] = bytes[8] & 63 | 128;
985
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
986
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
1209
987
  }
1210
- function isValidUUID(uuid$1) {
1211
- return (0, uuid.validate)(uuid$1);
988
+
989
+ //#endregion
990
+ //#region src/utils/process-env.ts
991
+ /**
992
+ * The process environment, or an empty object where there is no `process`
993
+ * (Cloudflare Workers without `nodejs_compat`, browsers). Read it on each use
994
+ * rather than caching it, so later changes to `process.env` are seen.
995
+ */
996
+ function processEnv() {
997
+ var _process$env, _process;
998
+ return (_process$env = (_process = globalThis.process) === null || _process === void 0 ? void 0 : _process.env) !== null && _process$env !== void 0 ? _process$env : {};
1212
999
  }
1213
1000
 
1214
1001
  //#endregion
@@ -1575,14 +1362,10 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
1575
1362
  * Users can opt out by setting:
1576
1363
  * - COPILOTKIT_TELEMETRY_DISABLED=true or COPILOTKIT_TELEMETRY_DISABLED=1
1577
1364
  * - DO_NOT_TRACK=true or DO_NOT_TRACK=1
1578
- *
1579
- * Lives in its own module so that the browser-facing root entry can
1580
- * re-export it without pulling in `telemetry-client.ts`, whose
1581
- * `@segment/analytics-node` import drags Node built-ins into browser
1582
- * bundler module graphs. See the note in `../index.ts`.
1583
1365
  */
1584
1366
  function isTelemetryDisabled() {
1585
- return process.env.COPILOTKIT_TELEMETRY_DISABLED === "true" || process.env.COPILOTKIT_TELEMETRY_DISABLED === "1" || process.env.DO_NOT_TRACK === "true" || process.env.DO_NOT_TRACK === "1";
1367
+ const env = processEnv();
1368
+ return env.COPILOTKIT_TELEMETRY_DISABLED === "true" || env.COPILOTKIT_TELEMETRY_DISABLED === "1" || env.DO_NOT_TRACK === "true" || env.DO_NOT_TRACK === "1";
1586
1369
  }
1587
1370
 
1588
1371
  //#endregion
@@ -1764,7 +1547,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
1764
1547
  try {
1765
1548
  var _firstNonBlankTelemet;
1766
1549
  const payload = parts[1];
1767
- if (!/^[A-Za-z0-9_-]+$/.test(payload) || payload.length % 4 === 1) return null;
1550
+ if (payload === void 0 || !/^[A-Za-z0-9_-]+$/.test(payload) || payload.length % 4 === 1) return null;
1768
1551
  let b64 = payload.replace(/-/g, "+").replace(/_/g, "/");
1769
1552
  const padding = (4 - b64.length % 4) % 4;
1770
1553
  b64 += "=".repeat(padding);
@@ -1854,6 +1637,18 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
1854
1637
  //#endregion
1855
1638
  //#region src/standard-schema.ts
1856
1639
  /**
1640
+ * A Standard Schema that accepts any value and returns it unchanged.
1641
+ *
1642
+ * Wildcard tool call renderers use it when they declare no `args` schema.
1643
+ *
1644
+ * @internal Application authors must not depend on this contract.
1645
+ */
1646
+ const ɵanySchema = { "~standard": {
1647
+ version: 1,
1648
+ vendor: "copilotkit",
1649
+ validate: (value) => ({ value })
1650
+ } };
1651
+ /**
1857
1652
  * Check whether a schema implements the Standard JSON Schema V1 protocol.
1858
1653
  */
1859
1654
  function hasStandardJsonSchema(schema) {
@@ -1866,17 +1661,17 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
1866
1661
  * Strategy:
1867
1662
  * 1. If the schema implements Standard JSON Schema V1 (`~standard.jsonSchema`),
1868
1663
  * call `schema['~standard'].jsonSchema.input({ target: 'draft-07' })`.
1869
- * 2. If the schema exposes a `toJSONSchema()` method (Zod v4), call it directly.
1870
- * 3. If the schema is a Zod v3 schema (`~standard.vendor === 'zod'`), use the
1871
- * injected `zodToJsonSchema()` function.
1872
- * 4. Otherwise throw a descriptive error.
1664
+ * Zod 4.2+, ArkType 2.1.28+ and Valibot (via `toStandardJsonSchema`) do.
1665
+ * 2. If the schema exposes a `toJSONSchema()` method, call it directly.
1666
+ * 3. Otherwise throw a descriptive error. Zod 3 schemas land here: they
1667
+ * implement Standard Schema validation but cannot describe themselves as
1668
+ * JSON Schema.
1873
1669
  */
1874
- function schemaToJsonSchema(schema, options) {
1670
+ function schemaToJsonSchema(schema) {
1875
1671
  if (hasStandardJsonSchema(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-07" });
1876
1672
  if (typeof schema.toJSONSchema === "function") return schema.toJSONSchema();
1877
1673
  const vendor = schema["~standard"].vendor;
1878
- if (vendor === "zod" && (options === null || options === void 0 ? void 0 : options.zodToJsonSchema)) return options.zodToJsonSchema(schema, { $refStrategy: "none" });
1879
- throw new Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${vendor}") does not implement Standard JSON Schema V1 and no zodToJsonSchema fallback is available. Use a library that supports Standard JSON Schema (e.g., Zod 3.24+, Valibot v1+, ArkType v2+) or pass a zodToJsonSchema function in options.`);
1674
+ throw new Error(`Cannot convert schema to JSON Schema. The schema (vendor: "${vendor}") does not implement Standard JSON Schema V1. Use a library that does: Zod 4.2+ (Zod 3 is not supported), Valibot v1+ wrapped with toStandardJsonSchema() from @valibot/to-json-schema, or ArkType v2.1.28+.`);
1880
1675
  }
1881
1676
 
1882
1677
  //#endregion
@@ -2123,6 +1918,22 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2123
1918
  terminalEventObserved = true;
2124
1919
  clearOpen();
2125
1920
  break;
1921
+ case _ag_ui_client.EventType.TEXT_MESSAGE_CONTENT:
1922
+ case _ag_ui_client.EventType.TEXT_MESSAGE_CHUNK:
1923
+ case _ag_ui_client.EventType.TOOL_CALL_ARGS:
1924
+ case _ag_ui_client.EventType.TOOL_CALL_CHUNK:
1925
+ case _ag_ui_client.EventType.STATE_SNAPSHOT:
1926
+ case _ag_ui_client.EventType.STATE_DELTA:
1927
+ case _ag_ui_client.EventType.MESSAGES_SNAPSHOT:
1928
+ case _ag_ui_client.EventType.ACTIVITY_SNAPSHOT:
1929
+ case _ag_ui_client.EventType.ACTIVITY_DELTA:
1930
+ case _ag_ui_client.EventType.RAW:
1931
+ case _ag_ui_client.EventType.CUSTOM:
1932
+ case _ag_ui_client.EventType.STEP_STARTED:
1933
+ case _ag_ui_client.EventType.STEP_FINISHED:
1934
+ case _ag_ui_client.EventType.REASONING_MESSAGE_CONTENT:
1935
+ case _ag_ui_client.EventType.REASONING_MESSAGE_CHUNK:
1936
+ case _ag_ui_client.EventType.REASONING_ENCRYPTED_VALUE:
2126
1937
  default: break;
2127
1938
  }
2128
1939
  };
@@ -2323,7 +2134,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2323
2134
 
2324
2135
  //#endregion
2325
2136
  //#region package.json
2326
- var version = "2.0.0-rc.2";
2137
+ var version = "2.0.0-rc.20";
2327
2138
 
2328
2139
  //#endregion
2329
2140
  //#region src/generative-ui/basic-functions.ts
@@ -2451,7 +2262,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2451
2262
  */
2452
2263
  const COPILOTKIT_FUNCTIONS = rendererOnly({
2453
2264
  calc: {
2454
- description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name",
2265
+ description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), x ^ y (power), comparisons, && || !, cond ? a : b, min max round floor ceil abs pow sqrt exp ln log10, the constants pi and e, 'text' + name",
2455
2266
  parameters: "{ expression: string; [name: string]: number | string | boolean }",
2456
2267
  returnType: "any",
2457
2268
  extension: true
@@ -2494,7 +2305,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2494
2305
  //#endregion
2495
2306
  //#region src/generative-ui/is-record.ts
2496
2307
  /** True for a plain object: not null, not an array. Internal, not exported. */
2497
- function isRecord(value) {
2308
+ function isRecord$2(value) {
2498
2309
  return typeof value === "object" && value !== null && !Array.isArray(value);
2499
2310
  }
2500
2311
 
@@ -2540,7 +2351,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2540
2351
  const visit = (node) => {
2541
2352
  var _marked;
2542
2353
  if (Array.isArray(node)) return node.map(visit);
2543
- if (!isRecord(node)) return node;
2354
+ if (!isRecord$2(node)) return node;
2544
2355
  const reference = (_marked = marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF)) !== null && _marked !== void 0 ? _marked : marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);
2545
2356
  if (reference) return reference;
2546
2357
  return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, visit(value)]));
@@ -2567,12 +2378,12 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2567
2378
  });
2568
2379
  };
2569
2380
  const visit = (node, path) => {
2570
- if (!isRecord(node)) return;
2381
+ if (!isRecord$2(node)) return;
2571
2382
  const kind = childRefKind(node);
2572
2383
  if (kind) return add(path, kind);
2573
2384
  for (const list of [node.anyOf, node.oneOf]) {
2574
2385
  if (!Array.isArray(list) || list.length === 0) continue;
2575
- const kinds = list.map((variant) => isRecord(variant) ? childRefKind(variant) : void 0);
2386
+ const kinds = list.map((variant) => isRecord$2(variant) ? childRefKind(variant) : void 0);
2576
2387
  const [first] = kinds;
2577
2388
  if (first && kinds.every((k) => k === first)) add(path, first);
2578
2389
  else if (kinds.every((k) => k === void 0)) {
@@ -2582,8 +2393,8 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2582
2393
  }
2583
2394
  }
2584
2395
  if (Array.isArray(node.allOf)) node.allOf.forEach((variant) => visit(variant, path));
2585
- if (isRecord(node.properties)) for (const [key, value] of Object.entries(node.properties)) visit(value, [...path, key]);
2586
- if (isRecord(node.items)) visit(node.items, [...path, "*"]);
2396
+ if (isRecord$2(node.properties)) for (const [key, value] of Object.entries(node.properties)) visit(value, [...path, key]);
2397
+ if (isRecord$2(node.items)) visit(node.items, [...path, "*"]);
2587
2398
  };
2588
2399
  visit(schema, []);
2589
2400
  return refs;
@@ -2598,16 +2409,16 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2598
2409
  const collect = (value) => {
2599
2410
  if (typeof value === "string") ids.push(value);
2600
2411
  else if (Array.isArray(value)) value.forEach((id) => typeof id === "string" && ids.push(id));
2601
- else if (isRecord(value) && typeof value.componentId === "string") ids.push(value.componentId);
2412
+ else if (isRecord$2(value) && typeof value.componentId === "string") ids.push(value.componentId);
2602
2413
  };
2603
2414
  const visit = (value, path) => {
2604
- if (path.length === 0) return collect(value);
2605
2415
  const [head, ...rest] = path;
2416
+ if (head === void 0) return collect(value);
2606
2417
  if (head === "*") {
2607
2418
  if (Array.isArray(value)) value.forEach((item) => visit(item, rest));
2608
2419
  return;
2609
2420
  }
2610
- if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) visit(value[head], rest);
2421
+ if (isRecord$2(value) && Object.prototype.hasOwnProperty.call(value, head)) visit(value[head], rest);
2611
2422
  };
2612
2423
  for (const ref of refs) visit(component, ref.path);
2613
2424
  return ids;
@@ -2618,13 +2429,13 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2618
2429
  * at render time.
2619
2430
  */
2620
2431
  function hasBoundChildRef(component, refs) {
2621
- const isDynamic = (value) => isRecord(value) && ("@path" in value || "@call" in value);
2432
+ const isDynamic = (value) => isRecord$2(value) && ("@path" in value || "@call" in value);
2622
2433
  const visit = (value, path) => {
2623
2434
  if (isDynamic(value)) return true;
2624
- if (path.length === 0) return false;
2625
2435
  const [head, ...rest] = path;
2436
+ if (head === void 0) return false;
2626
2437
  if (head === "*") return Array.isArray(value) && value.some((item) => visit(item, rest));
2627
- return isRecord(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
2438
+ return isRecord$2(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
2628
2439
  };
2629
2440
  return refs.some((ref) => visit(component, ref.path));
2630
2441
  }
@@ -2634,13 +2445,13 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2634
2445
  * else keeps its identity. Missing keys are left alone.
2635
2446
  */
2636
2447
  function mapAtChildRef(value, path, replace) {
2637
- if (path.length === 0) return replace(value);
2638
2448
  const [head, ...rest] = path;
2449
+ if (head === void 0) return replace(value);
2639
2450
  if (head === "*") {
2640
2451
  if (!Array.isArray(value)) return value;
2641
2452
  return value.map((item) => mapAtChildRef(item, rest, replace));
2642
2453
  }
2643
- if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) return value;
2454
+ if (!isRecord$2(value) || !Object.prototype.hasOwnProperty.call(value, head)) return value;
2644
2455
  return {
2645
2456
  ...value,
2646
2457
  [head]: mapAtChildRef(value[head], rest, replace)
@@ -2650,7 +2461,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2650
2461
  //#endregion
2651
2462
  //#region src/generative-ui/types.ts
2652
2463
  /** A2UI protocol version used on the wire. */
2653
- const A2UI_VERSION = "v1.0";
2464
+ const A2UI_VERSION = "1.0";
2654
2465
  /** Activity type of a generated surface message. */
2655
2466
  const GENERATIVE_UI_ACTIVITY_TYPE = "generative-ui-surface";
2656
2467
  /** Activity type of a function call that the agent asks the client to run. */
@@ -2714,7 +2525,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2714
2525
  * @example
2715
2526
  * ```ts
2716
2527
  * toA2UIActionMessage({ name: "buy", surfaceId: "s1", componentId: "b", context: { sku: "a" } });
2717
- * // { version: "v1.0", action: { name: "buy", surfaceId: "s1", sourceComponentId: "b", timestamp: "2026-…", context: { sku: "a" } } }
2528
+ * // { version: "1.0", action: { name: "buy", surfaceId: "s1", sourceComponentId: "b", timestamp: "2026-…", context: { sku: "a" } } }
2718
2529
  * ```
2719
2530
  */
2720
2531
  function toA2UIActionMessage(event) {
@@ -2732,6 +2543,222 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
2732
2543
  };
2733
2544
  }
2734
2545
 
2546
+ //#endregion
2547
+ //#region src/generative-ui/prompt-spec.ts
2548
+ /**
2549
+ * When UI helps the user, for both transports: a light nudge to reach for UI
2550
+ * where it conveys the answer better than prose, and to stay in prose
2551
+ * otherwise.
2552
+ */
2553
+ 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.";
2554
+ /**
2555
+ * When and how to show UI in the markdown transport: the answer first, a
2556
+ * map from tasks to components, real interactivity, honest data and
2557
+ * restraint. Measured with tools/genui-eval against the earlier text.
2558
+ */
2559
+ const GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW = "Answer first: lead with the result or the recommendation in a sentence or two, then show the UI that supports it.\n\nShow UI whenever it makes the answer easier to use, and do not wait for the user to ask for a chart, a calculator or a form. A markdown table or list is not enough when the user would want to change a value, see a shape or a trend, or pick between options. Reply in prose alone only for a greeting or thanks, a one-line fact, a definition, code, or a text the user asked you to write (an email, a message, an update).\n\nMatch the UI to the task:\n- A number that depends on inputs (a price, a loan or mortgage, savings, a conversion, a recipe for N people): a calculator, always. Bind a Slider, TextField or SegmentedControl to the data model and compute the results with calc, so they follow the input. calc has powers, roots and logs, so every input can be a control, also a rate or a term: a monthly payment is rate == 0 ? loan / (years * 12) : loan * (rate / 1200) / (1 - (1 + rate / 1200) ^ -(years * 12)).\n- Choosing between options that share attributes: a Table, or a Grid of EntityCards when each option has a photo, a price or a rating. Plans or offers to pick from: one card each, ending with a Button to choose it.\n- Items with a status, a category or a level: a Badge on each item.\n- Shares, patterns, trends, change over time: a Chart.\n- Places, routes, what is nearby: a Map with the places as markers, next to cards or a List with their details.\n- A sequence or a history: a timeline surface, a List of dated items with a Badge for each era, not a markdown list.\n- How something works, a process, a structure: a diagram drawn with Svg. Draw the real objects as shapes (a cylinder and its piston, a leaf, a server), with arrows for movement or flow and short labels. Labelled boxes of text are not a diagram.\n- A formula or an equation: Math. Solving a math problem: the steps in prose with Math, plus a Chart of the function and a Slider to try values of x.\n- A broad topic (\"tell me about X\"): an overview surface with the key facts, an Image, and a Table or Chart that compares the parts, ending with FollowUp suggestions for what to ask next.\n- Options to choose from (algorithms, products, plans): a Table, plus a SegmentedControl or Select that shows the best option for the user's situation.\n- Research or evidence: a Table of the studies, with a Citation for each source.\n- Things whose look matters (places, products, food): an Image, or the image of an EntityCard.\n- Several inputs, or an action with a side effect (sign-up, booking, contact, scheduling): a Form with fields, checks and a Button. A field with a fixed list of answers (a team size, a topic, a country) is a Select.\n- Practice and learning: a quiz with RadioGroup or ChoicePicker that gives feedback as soon as the user answers, or FlashcardFlip cards. Ask in one language and offer the answers in the other.\n- A plan to follow or tick off: CheckBox items with a progress count that updates as items are ticked.\n- Parallel views (the days of a trip, alternatives): Tabs.\n\nMake interactivity real:\n- Expose the few inputs that change the outcome, with sensible defaults from what the user said.\n- Bind every control to the data model and derive what depends on it with calc or formatString. Controls about the same scenario share the same paths.\n- Every Button does what its label says, and a Link takes \"href\".\n- Never pretend an action happened. For booking, sending or subscribing, show the form and let the user confirm, and say that nothing is sent until they do.\n\nKeep the data honest:\n- Use the facts, places, photos and numbers of the app context when it has them. Never invent prices, availability, ratings, sources or image URLs.\n- Label estimates and assumptions, keep units and currencies consistent, and cite the sources you rely on with Citation.\n\nDesign with restraint:\n- One clear surface beats several. Put the most important result first and make it stand out with a Title, or a Text with size \"lg\". Text sizes go from \"3xs\" to \"lg\"; there is no \"xl\" or \"2xl\".\n- Keep explanations in prose around the surface, not inside it. No decoration, and no surface that only holds text.\n\nBefore you reply, check: does the UI answer the actual question, does every control do something, are the numbers right?";
2560
+ /** The prompts that ship, as a spec. A new object on each call. */
2561
+ /**
2562
+ * The standard components that the default markdown guide names. A guide
2563
+ * line that names one the catalog lacks is left out of the prompt.
2564
+ */
2565
+ const GUIDE_COMPONENTS = new Set([
2566
+ "Grid",
2567
+ "Card",
2568
+ "Tabs",
2569
+ "Title",
2570
+ "Text",
2571
+ "Label",
2572
+ "Badge",
2573
+ "Math",
2574
+ "Link",
2575
+ "Button",
2576
+ "Form",
2577
+ "TextField",
2578
+ "Select",
2579
+ "CheckBox",
2580
+ "RadioGroup",
2581
+ "Slider",
2582
+ "SegmentedControl",
2583
+ "ChoicePicker",
2584
+ "FlashcardFlip",
2585
+ "Table",
2586
+ "List",
2587
+ "Chart",
2588
+ "Map",
2589
+ "Image",
2590
+ "Svg",
2591
+ "Citation",
2592
+ "FollowUp",
2593
+ "EntityCard"
2594
+ ]);
2595
+ function defaultGenerativeUIPromptSpec() {
2596
+ return {
2597
+ markdown: {
2598
+ intro: "You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.",
2599
+ whenToShow: GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW,
2600
+ rules: [
2601
+ "Write explanations as normal markdown prose outside the fences.",
2602
+ "Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
2603
+ "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 limits its components, its surfaces can use only those components.",
2604
+ "Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
2605
+ "Keep each operation whole on its line.",
2606
+ "Give every operation \"version\":\"1.0\".",
2607
+ "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\":\"1.0\",\"createSurface\":{\"surfaceId\":\"plan-picker\",\"dataModel\":{ ...initial data... },\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"seats\",\"pick\"]}]}}\n {\"version\":\"1.0\",\"updateComponents\":{\"surfaceId\":\"plan-picker\",\"components\":[ ...the children... ]}}\n ```",
2608
+ "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.",
2609
+ "Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.",
2610
+ "Send every component you reference in the same reply. If a surface gets long, make it smaller rather than leave components out.",
2611
+ "Use unique ids. Do not make cycles. A component cannot be its own child.",
2612
+ "Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
2613
+ "Close each component with exactly one }, also when its last prop is a list: {\"id\":\"map\",\"component\":\"Map\",\"markers\":[{\"label\":\"A\",\"lat\":48.2,\"lng\":16.4}]}. A createSurface or updateComponents line ends with }]}} : the last component, the \"components\" list, the operation, the line.",
2614
+ "A prop that holds a call closes with }} : its \"args\", then the call. The component closes with its own single } after its last prop. With a prop after the call: {\"id\":\"count\",\"component\":\"Text\",\"text\":{\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} items\"}},\"size\":\"lg\"}. With the call last: {\"id\":\"count\",\"component\":\"Text\",\"size\":\"lg\",\"text\":{\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} items\"}}}.",
2615
+ "Deep props close every level they open, then the component closes with its own }. An event with a context: \"onSubmit\":{\"event\":{\"name\":\"send\",\"context\":{\"email\":{\"@path\":\"/email\"}}}}} ends with }}}}} : the path, \"context\", \"event\", the prop, the component. A Table: \"rows\":[[\"Mon\",\"9°C\"],[\"Tue\",\"7°C\"]]} ends with ]]} : the last row, \"rows\", the component, and nothing more. A list item with a call: \"items\":[{\"label\":{\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} cups\"}}}]} ends with }}}]} : \"args\", the call, the item, the list, the component.",
2616
+ "Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
2617
+ "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. \"live\":\"polite\" goes only inside \"accessibility\" ({\"accessibility\":{\"live\":\"polite\"}}), only on text that changes by itself, never as a prop of the component.",
2618
+ "Use only the components, props, events, and slots in the schema. A component marked +common also takes every common prop. A component with a prop that is not in its schema, or a value outside its enum, is dropped with everything inside it, so check each prop against the schema.",
2619
+ "Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
2620
+ "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 in the schema. Write a literal when the value never changes.",
2621
+ "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.",
2622
+ "${...} 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.",
2623
+ "Inside ${...}, close every ( you open, and write no operators and no ?: : compute with calc. To round a computed number, round inside calc instead of wrapping it in formatNumber: ${calc(expression: 'round(servings * 0.5 * 10) / 10', servings: /servings)} cups. calc has ^ (power), sqrt, exp and ln.",
2624
+ "To show one of two texts, let calc choose: \"text\":{\"@call\":\"calc\",\"args\":{\"expression\":\"billing == 'yearly' ? 'per year' : 'per month'\",\"billing\":{\"@path\":\"/billing\"}}}.",
2625
+ "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.",
2626
+ "Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
2627
+ "The value of a ChoicePicker is a list of strings, also for one choice. SegmentedControl, RadioGroup and Select take one string. Option values are always strings: for a yes/no choice use \"yes\" and \"no\", not true and false.",
2628
+ "To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".",
2629
+ "Set \"value\":null to delete the key at \"path\".",
2630
+ {
2631
+ when: ["events"],
2632
+ items: ["Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.", "Put the action of a Button in its \"onClick\": {\"event\":{...}} to send it back to you, or {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"...\"}}}. Never write \"event\" or \"functionCall\" as a prop of its own."]
2633
+ },
2634
+ {
2635
+ when: ["events", "functions"],
2636
+ items: ["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."]
2637
+ },
2638
+ {
2639
+ when: ["events", "noFunctions"],
2640
+ items: ["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."]
2641
+ },
2642
+ {
2643
+ when: ["events"],
2644
+ items: [
2645
+ "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\".",
2646
+ "To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.",
2647
+ "A button or other event prop without an event or functionCall does nothing."
2648
+ ]
2649
+ },
2650
+ {
2651
+ when: ["checks"],
2652
+ items: ["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."]
2653
+ },
2654
+ "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\"}].",
2655
+ {
2656
+ when: ["templates"],
2657
+ items: [
2658
+ "To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.",
2659
+ "Inside a template, paths are relative to the item (\"name\", not \"/name\").",
2660
+ "Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}."
2661
+ ]
2662
+ },
2663
+ "Updating a component replaces all of its props. Send every prop again.",
2664
+ "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.",
2665
+ "Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.",
2666
+ {
2667
+ when: ["agentCalls"],
2668
+ items: [
2669
+ "To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.",
2670
+ "Give every callRendererFunction a new functionCallId. Call only a function that the schema marks UI or agent, or agent only; a function with no mark is for the UI only. A function marked agent only is only for callRendererFunction: do not bind an event to it.",
2671
+ "The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.",
2672
+ "Do not guess the result of a callRendererFunction. Wait for the developer message."
2673
+ ]
2674
+ },
2675
+ "The schema lists the surfaces that already exist. \"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.",
2676
+ "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.",
2677
+ "Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
2678
+ "Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
2679
+ "Never wrap the whole reply in a fence."
2680
+ ]
2681
+ },
2682
+ tool: {
2683
+ intro: `Call \`${GENERATIVE_UI_RENDER_TOOL}\` to show UI. Arguments: \`target\` first, then \`operations\` (A2UI v1.0 operations, applied in order).`,
2684
+ whenToShow: GENERATIVE_UI_WHEN_TO_SHOW,
2685
+ operations: [
2686
+ "{\"version\":\"1.0\",\"createSurface\":{\"surfaceId\":\"<new id>\",\"dataModel\":{...},\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"<child id>\"]}]}}: the first operation of a new surface. \"dataModel\" and \"components\" are optional.",
2687
+ "{\"version\":\"1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
2688
+ "{\"version\":\"1.0\",\"updateDataModel\":{\"surfaceId\":\"<id>\",\"path\":\"/some/path\",\"value\":<json>}}: set the value at \"path\". Always give \"value\". \"value\":null deletes the key at \"path\".",
2689
+ "{\"version\":\"1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
2690
+ {
2691
+ when: ["agentCalls"],
2692
+ items: ["{\"version\":\"1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."]
2693
+ }
2694
+ ],
2695
+ rules: [
2696
+ "Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
2697
+ "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.",
2698
+ "Stream progressively: put the initial data in \"dataModel\" and the root in \"components\" of the createSurface operation, then send one updateComponents operation per child, so the UI appears while you are still writing. The root must already list the ids of its children in its slot props (for example \"children\":[\"card-1\",\"card-2\"]), even though the children come later. A component that no slot references is never shown.",
2699
+ "Updating a component replaces all of its props, so resend every prop.",
2700
+ "Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
2701
+ {
2702
+ when: ["events", "functions"],
2703
+ items: ["Event props take an action. {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}} runs an app function in the browser immediately, and you are not told about it. {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\". Only call functions listed below."]
2704
+ },
2705
+ {
2706
+ when: ["events", "noFunctions"],
2707
+ items: ["Event props take an action: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\"."]
2708
+ },
2709
+ "To show a different view, create a new surface with a new surfaceId (for example, a checkout form after a cart summary). Update an existing surface only when the user asks to change that same view: then do not send createSurface, use its surfaceId, and pass its existing target. Never reuse an earlier chat surface for a different view, because that replaces the earlier UI and anything the user typed into it.",
2710
+ "Never use a surfaceId again, also after deleteSurface.",
2711
+ "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Only call functions listed below. formatString interpolates ${/path} and ${fn(arg: value)} in its value.",
2712
+ "${...} 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\"}}}.",
2713
+ "For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
2714
+ {
2715
+ when: ["checks"],
2716
+ items: ["Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks."]
2717
+ },
2718
+ {
2719
+ when: ["templates"],
2720
+ items: ["To repeat a component for each item of a list, give a multiple slot a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}. Inside the template, paths are relative to the item (\"name\", not \"/name\"). {\"@call\":\"@index\"} gives the position of the item, from 0; {\"@call\":\"@index\",\"args\":{\"offset\":1}} counts from 1."]
2721
+ },
2722
+ {
2723
+ when: ["agentCalls"],
2724
+ items: ["Give every callRendererFunction a new functionCallId. Call only a function marked (UI or agent) or (agent only); a function with no mark is for the UI only. A function marked (agent only) is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you in a new turn, as a developer message: {\"version\":\"1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Do not wait for the result in this reply, and do not guess it."]
2725
+ }
2726
+ ]
2727
+ },
2728
+ schema: {
2729
+ markdown: {
2730
+ notation: "lines",
2731
+ propDescriptions: true,
2732
+ commonProps: true
2733
+ },
2734
+ tool: {
2735
+ notation: "json-schema",
2736
+ propDescriptions: true,
2737
+ commonProps: false
2738
+ }
2739
+ },
2740
+ descriptions: {}
2741
+ };
2742
+ }
2743
+ /** The rules of `items` whose block conditions hold, in order. */
2744
+ function selectPromptItems(items, features) {
2745
+ return items.flatMap((item) => typeof item === "string" ? [item] : item.when.every((feature) => features[feature]) ? item.items : []);
2746
+ }
2747
+ /**
2748
+ * The prompt features of a run, from the guide features of its manifest
2749
+ * (`generativeUIGuideFeatures`).
2750
+ */
2751
+ function generativeUIPromptFeatures(guide) {
2752
+ return {
2753
+ functions: guide.functions,
2754
+ noFunctions: !guide.functions,
2755
+ events: guide.events,
2756
+ templates: guide.templates,
2757
+ checks: guide.checks,
2758
+ agentCalls: guide.functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS
2759
+ };
2760
+ }
2761
+
2735
2762
  //#endregion
2736
2763
  //#region src/a2ui-prompts.ts
2737
2764
  /**
@@ -2847,12 +2874,6 @@ Design principles:
2847
2874
  action context should reference the same paths to capture user input.
2848
2875
 
2849
2876
  Use the SAME surfaceId as the main surface. Match action names to button action event names.`;
2850
- /**
2851
- * When UI helps the user, for both transports: a light nudge to reach for UI
2852
- * where it conveys the answer better than prose, and to stay in prose
2853
- * otherwise.
2854
- */
2855
- const GENERATIVE_UI_WHEN_TO_SHOW = "Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.";
2856
2877
  /** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */
2857
2878
  const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = "Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.";
2858
2879
  /**
@@ -2898,6 +2919,7 @@ Use the SAME surfaceId as the main surface. Match action names to button action
2898
2919
  return Object.values(node).some(hasChildList);
2899
2920
  };
2900
2921
  return {
2922
+ components: Object.keys(manifest.components),
2901
2923
  functions: Object.keys(manifest.functions).some((name) => !isA2UIBasicFunction(name)),
2902
2924
  events: components.some((c) => {
2903
2925
  var _c$events;
@@ -2913,43 +2935,21 @@ Use the SAME surfaceId as the main surface. Match action names to button action
2913
2935
  })
2914
2936
  };
2915
2937
  }
2916
- /** The first rules of every markdown guideline, before the optional groups. */
2917
- const MARKDOWN_BASE_RULES = [
2918
- "Write explanations as normal markdown prose outside the fences.",
2919
- "Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
2920
- "Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target has \"components\", its surfaces can use only those components.",
2921
- "Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
2922
- "Keep each operation whole on its line.",
2923
- "Give every operation \"version\":\"v1.0\".",
2924
- `Start a surface with one createSurface. Put all the initial data in "dataModel" and the "root" component in "components". Then write the children in updateComponents lines, so that they show while you write:
2925
- \`\`\`a2ui
2926
- {"version":"v1.0","createSurface":{"surfaceId":"plan-picker","dataModel":{ ...initial data... },"components":[{"id":"root","component":"<Name>","children":["seats","pick"]}]}}
2927
- {"version":"v1.0","updateComponents":{"surfaceId":"plan-picker","components":[ ...the children... ]}}
2928
- \`\`\``,
2929
- "Keep \"dataModel\" flat: top-level keys such as \"seats\" or \"form\", never one wrapper object around everything. Check that every { and [ you open in a line is closed.",
2930
- "Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.",
2931
- "Use unique ids. Do not make cycles. A component cannot be its own child.",
2932
- "Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
2933
- "Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
2934
- "A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
2935
- "Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".",
2936
- "Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
2937
- "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions under \"functions\" in the schema. Write a literal when the value never changes.",
2938
- "formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: 'EUR')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.",
2939
- "${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: 'seats * 29', seats: /seats), currency: 'USD')}. The UI then follows the user's input with no round trip.",
2940
- "For a computed list (chart data, template items) use series. Its description under \"functions\" in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.",
2941
- "Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
2942
- "To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".",
2943
- "Set \"value\":null to delete the key at \"path\"."
2944
- ];
2945
- /** The last rules of every markdown guideline, after the optional groups. */
2946
- const MARKDOWN_CLOSING_RULES = [
2947
- "The schema lists the surfaces that already exist under \"surfaces\". \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.",
2948
- "Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.",
2949
- "Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
2950
- "Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
2951
- "Never wrap the whole reply in a fence."
2952
- ];
2938
+ /**
2939
+ * Whether a guide line names only standard components (`GUIDE_COMPONENTS`,
2940
+ * also in the plural) that the catalog has. With no catalog, every line fits.
2941
+ */
2942
+ function namesOnlyCatalogComponents(catalog) {
2943
+ if (!catalog) return () => true;
2944
+ const has = new Set(catalog);
2945
+ return (line) => {
2946
+ var _line$match;
2947
+ return ((_line$match = line.match(/\b[A-Z][A-Za-z0-9]*\b/g)) !== null && _line$match !== void 0 ? _line$match : []).every((word) => {
2948
+ const name = !GUIDE_COMPONENTS.has(word) && word.endsWith("s") ? word.slice(0, -1) : word;
2949
+ return !GUIDE_COMPONENTS.has(name) || has.has(name);
2950
+ });
2951
+ };
2952
+ }
2953
2953
  /**
2954
2954
  * Builds the markdown-transport guideline. The model writes A2UI v1.0
2955
2955
  * operations inside ```a2ui fences between normal markdown prose. The rules
@@ -2957,25 +2957,15 @@ Use the SAME surfaceId as the main surface. Match action names to button action
2957
2957
  * none of them, so the guideline stays small.
2958
2958
  *
2959
2959
  * @param features - The optional rule groups to include. Defaults to all.
2960
+ * @param spec - The wording. Defaults to the prompts that ship.
2960
2961
  * @returns The guideline text, one rule per line.
2961
2962
  */
2962
- function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES) {
2963
- const { functions, events, templates, checks } = features;
2964
- const rules = [...MARKDOWN_BASE_RULES];
2965
- if (events) rules.push("Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.", functions ? "Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call." : "Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.", "Use {\"event\": ...} to send the interaction back to you as a user message. Put the text of that message in \"userMessage\": {\"event\":{\"name\":\"choose\",\"userMessage\":\"Show me the Team plan\"}}. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".", "To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.", "A button or other event prop without an event or functionCall does nothing.");
2966
- if (checks) rules.push("Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks.");
2967
- rules.push("A prop typed componentId takes the id of another component, and a childList takes ids [\"a\",\"b\"]: \"child\":\"card\", \"children\":[\"a\",\"b\"], \"tabs\":[{\"title\":\"Specs\",\"child\":\"specs\"}].");
2968
- if (templates) rules.push("To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.", "Inside a template, paths are relative to the item (\"name\", not \"/name\").", "Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.");
2969
- rules.push("Updating a component replaces all of its props. Send every prop again.", "To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.", "Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.");
2970
- if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) rules.push("To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.", "Give every callRendererFunction a new functionCallId. Call only a function from the schema with \"callers\": \"UI or agent\" or \"agent only\"; a function without \"callers\" is for the UI only. A function with \"callers\": \"agent only\" is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.", "Do not guess the result of a callRendererFunction. Wait for the developer message.");
2971
- rules.push(...MARKDOWN_CLOSING_RULES);
2972
- return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.
2973
-
2974
- ${GENERATIVE_UI_WHEN_TO_SHOW}
2975
-
2976
- RULES
2977
- ${rules.map((rule) => `- ${rule}`).join("\n")}
2978
- `;
2963
+ function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES, spec = defaultGenerativeUIPromptSpec()) {
2964
+ const { intro, rules } = spec.markdown;
2965
+ const fits = namesOnlyCatalogComponents(features.components);
2966
+ const selected = selectPromptItems(rules, generativeUIPromptFeatures(features)).filter(fits);
2967
+ const whenToShow = spec.markdown.whenToShow.split("\n").filter(fits).join("\n");
2968
+ return `${intro}\n\n${whenToShow ? `${whenToShow}\n\n` : ""}RULES\n${selected.map((rule) => `- ${rule}`).join("\n")}\n`;
2979
2969
  }
2980
2970
  /**
2981
2971
  * The markdown-transport guideline with every rule group. A run sends
@@ -3003,11 +2993,11 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3003
2993
  return typeof value === "string" && value !== "";
3004
2994
  }
3005
2995
  function isRecordOf(value, isEntry) {
3006
- return isRecord(value) && Object.values(value).every(isEntry);
2996
+ return isRecord$2(value) && Object.values(value).every(isEntry);
3007
2997
  }
3008
2998
  /** A function, or an event of a component: a description and a parameter schema. */
3009
2999
  function isSchemaEntry(value) {
3010
- return isRecord(value) && isRecord(value.parameters) && isOptionalString(value.description);
3000
+ return isRecord$2(value) && isRecord$2(value.parameters) && isOptionalString(value.description);
3011
3001
  }
3012
3002
  function isSlotKind(value) {
3013
3003
  return value === "single" || value === "multiple";
@@ -3017,11 +3007,11 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3017
3007
  * so those two must have the right shape when they are there.
3018
3008
  */
3019
3009
  function isPropsSchema(value) {
3020
- return isRecord(value) && (value.properties === void 0 || isRecord(value.properties)) && (value.required === void 0 || Array.isArray(value.required) && value.required.every((name) => typeof name === "string"));
3010
+ return isRecord$2(value) && (value.properties === void 0 || isRecord$2(value.properties)) && (value.required === void 0 || Array.isArray(value.required) && value.required.every((name) => typeof name === "string"));
3021
3011
  }
3022
3012
  function isComponentManifest(value) {
3023
3013
  var _value$props$properti, _value$slots, _value$events;
3024
- if (!isRecord(value) || !isPropsSchema(value.props) || !isOptionalString(value.description) || value.events !== void 0 && !isRecordOf(value.events, isSchemaEntry) || value.slots !== void 0 && !isRecordOf(value.slots, isSlotKind)) return false;
3014
+ if (!isRecord$2(value) || !isPropsSchema(value.props) || !isOptionalString(value.description) || value.events !== void 0 && !isRecordOf(value.events, isSchemaEntry) || value.slots !== void 0 && !isRecordOf(value.slots, isSlotKind)) return false;
3025
3015
  const order = value.parameterOrder;
3026
3016
  if (order === void 0) return true;
3027
3017
  const keys = new Set([
@@ -3032,31 +3022,31 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3032
3022
  return Array.isArray(order) && new Set(order).size === order.length && order.every((key) => typeof key === "string" && keys.has(key));
3033
3023
  }
3034
3024
  function isInlineCatalog(value) {
3035
- return isRecord(value) && isNonEmptyString(value.catalogId) && value.protocolVersion === "1.0" && (value.components === void 0 || isRecordOf(value.components, isComponentManifest)) && isRecordOf(value.functions, isSchemaEntry) && isOptionalString(value.instructions);
3025
+ return isRecord$2(value) && isNonEmptyString(value.catalogId) && value.protocolVersion === "1.0" && (value.components === void 0 || isRecordOf(value.components, isComponentManifest)) && isRecordOf(value.functions, isSchemaEntry) && isOptionalString(value.instructions);
3036
3026
  }
3037
3027
  function isCapabilities(value) {
3038
- return isRecord(value) && Array.isArray(value.supportedCatalogIds) && value.supportedCatalogIds.length > 0 && value.supportedCatalogIds.every(isNonEmptyString) && (value.inlineCatalogs === void 0 || Array.isArray(value.inlineCatalogs) && value.inlineCatalogs.every(isInlineCatalog));
3028
+ return isRecord$2(value) && Array.isArray(value.supportedCatalogIds) && value.supportedCatalogIds.length > 0 && value.supportedCatalogIds.every(isNonEmptyString) && (value.inlineCatalogs === void 0 || Array.isArray(value.inlineCatalogs) && value.inlineCatalogs.every(isInlineCatalog));
3039
3029
  }
3040
3030
  /** A short list of component names. */
3041
3031
  function isComponentNameList(value) {
3042
3032
  return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_TARGET_COMPONENTS && value.every(isNonEmptyString);
3043
3033
  }
3044
3034
  function isTarget(value) {
3045
- return isRecord(value) && isNonEmptyString(value.id) && (value.kind === "chat" || value.kind === "inline") && isOptionalString(value.description) && (value.components === void 0 || isComponentNameList(value.components));
3035
+ return isRecord$2(value) && isNonEmptyString(value.id) && (value.kind === "chat" || value.kind === "inline") && isOptionalString(value.description) && (value.components === void 0 || isComponentNameList(value.components));
3046
3036
  }
3047
3037
  /** A short list of short strings. The summary limits keep the guide small. */
3048
3038
  function isRejectionList(value) {
3049
3039
  return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_SUMMARY_REJECTIONS && value.every((entry) => typeof entry === "string" && entry.length <= GENERATIVE_UI_MAX_REJECTION_LENGTH);
3050
3040
  }
3051
3041
  function isSurfaceEntry(value) {
3052
- return isRecord(value) && isNonEmptyString(value.target) && (value.dataModel === void 0 || isRecord(value.dataModel)) && (value.rejected === void 0 || isRejectionList(value.rejected)) && (value.status === void 0 || value.status === "deleted" || value.status === "failed");
3042
+ return isRecord$2(value) && isNonEmptyString(value.target) && (value.dataModel === void 0 || isRecord$2(value.dataModel)) && (value.rejected === void 0 || isRejectionList(value.rejected)) && (value.status === void 0 || value.status === "deleted" || value.status === "failed");
3053
3043
  }
3054
3044
  /** Checks the `copilotkit_` keys only. Other extensions can be there too. */
3055
3045
  function isExtensions(value) {
3056
- return isRecord(value) && value.copilotkit_format === COPILOTKIT_UI_ENVELOPE_FORMAT && (value.copilotkit_transport === "tool" || value.copilotkit_transport === "markdown") && Array.isArray(value.copilotkit_targets) && value.copilotkit_targets.every(isTarget) && isRecordOf(value.copilotkit_surfaces, isSurfaceEntry) && typeof value.copilotkit_contextSent === "boolean";
3046
+ return isRecord$2(value) && value.copilotkit_format === COPILOTKIT_UI_ENVELOPE_FORMAT && (value.copilotkit_transport === "tool" || value.copilotkit_transport === "markdown") && Array.isArray(value.copilotkit_targets) && value.copilotkit_targets.every(isTarget) && isRecordOf(value.copilotkit_surfaces, isSurfaceEntry) && typeof value.copilotkit_contextSent === "boolean";
3057
3047
  }
3058
3048
  function isEnvelope(value) {
3059
- return isRecord(value) && isCapabilities(value["v1.0"]) && isRecord(value.metadata) && isExtensions(value.metadata.extensions);
3049
+ return isRecord$2(value) && isCapabilities(value["1.0"]) && isRecord$2(value.metadata) && isExtensions(value.metadata.extensions);
3060
3050
  }
3061
3051
  /**
3062
3052
  * Reads the generative UI envelope from the `forwardedProps` of a run.
@@ -3077,9 +3067,9 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3077
3067
  * ```
3078
3068
  */
3079
3069
  function readCopilotKitUIEnvelope(forwardedProps) {
3080
- if (!isRecord(forwardedProps)) return void 0;
3070
+ if (!isRecord$2(forwardedProps)) return void 0;
3081
3071
  const namespace = forwardedProps[COPILOTKIT_FORWARDED_PROPS_KEY];
3082
- if (!isRecord(namespace)) return void 0;
3072
+ if (!isRecord$2(namespace)) return void 0;
3083
3073
  const envelope = namespace.ui;
3084
3074
  return isEnvelope(envelope) ? envelope : void 0;
3085
3075
  }
@@ -3112,7 +3102,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3112
3102
  */
3113
3103
  function envelopeToManifest(envelope) {
3114
3104
  var _catalog$components, _catalog$functions;
3115
- const { supportedCatalogIds, inlineCatalogs } = envelope["v1.0"];
3105
+ const { supportedCatalogIds, inlineCatalogs } = envelope["1.0"];
3116
3106
  const catalogId = supportedCatalogIds[0];
3117
3107
  const catalog = inlineCatalogs === null || inlineCatalogs === void 0 ? void 0 : inlineCatalogs.find((entry) => entry.catalogId === catalogId);
3118
3108
  const extensions = envelope.metadata.extensions;
@@ -3152,7 +3142,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3152
3142
  });
3153
3143
  /** Models write the v0.9 binding from habit. The reason names the v1.0 form. */
3154
3144
  const V09_PATH_REASON = "bind data with {\"@path\": \"/x\"}, not {\"path\": \"/x\"}";
3155
- function hasOwn(record, key) {
3145
+ function hasOwn$1(record, key) {
3156
3146
  return Object.prototype.hasOwnProperty.call(record, key);
3157
3147
  }
3158
3148
  /**
@@ -3160,42 +3150,42 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3160
3150
  * "toString" must not resolve to Object.prototype members.
3161
3151
  */
3162
3152
  function ownValue(record, key) {
3163
- return record && hasOwn(record, key) ? record[key] : void 0;
3153
+ return record && hasOwn$1(record, key) ? record[key] : void 0;
3164
3154
  }
3165
3155
  function getOperationKind(op) {
3166
- if (!isRecord(op)) return void 0;
3156
+ if (!isRecord$2(op)) return void 0;
3167
3157
  const kinds = OPERATION_KINDS.filter((kind) => kind in op);
3168
3158
  return kinds.length === 1 ? kinds[0] : void 0;
3169
3159
  }
3170
3160
  /** The `surfaceId` of a surface operation. `callRendererFunction` has none. */
3171
3161
  function getOperationSurfaceId(op) {
3172
- if (!isRecord(op)) return void 0;
3162
+ if (!isRecord$2(op)) return void 0;
3173
3163
  const kind = getOperationKind(op);
3174
3164
  if (!kind) return void 0;
3175
3165
  const payload = op[kind];
3176
- return isRecord(payload) && typeof payload.surfaceId === "string" ? payload.surfaceId : void 0;
3166
+ return isRecord$2(payload) && typeof payload.surfaceId === "string" ? payload.surfaceId : void 0;
3177
3167
  }
3178
3168
  /** `{ "@path": "/x" }`: a data-model binding. */
3179
3169
  function isPathBinding(value) {
3180
- return isRecord(value) && typeof value["@path"] === "string" && Object.keys(value).length === 1;
3170
+ return isRecord$2(value) && typeof value["@path"] === "string" && Object.keys(value).length === 1;
3181
3171
  }
3182
3172
  /** `{ "path": "/x" }`: the v0.9 binding, which v1.0 does not accept. */
3183
3173
  function isV09PathBinding(value) {
3184
- return isRecord(value) && typeof value.path === "string" && Object.keys(value).length === 1;
3174
+ return isRecord$2(value) && typeof value.path === "string" && Object.keys(value).length === 1;
3185
3175
  }
3186
3176
  /**
3187
3177
  * `{ "@call": "@index" }` or `{ "@call": "@index", "args": { "offset": 1 } }`:
3188
3178
  * the 0-based position of the item in a template, plus `offset`.
3189
3179
  */
3190
3180
  function isIndexCall(value) {
3191
- if (!isRecord(value) || value["@call"] !== "@index") return false;
3181
+ if (!isRecord$2(value) || value["@call"] !== "@index") return false;
3192
3182
  if (!Object.keys(value).every((key) => key === "@call" || key === "args")) return false;
3193
3183
  const { args } = value;
3194
3184
  if (args === void 0) return true;
3195
- return isRecord(args) && Object.keys(args).every((key) => key === "offset") && (args.offset === void 0 || Number.isFinite(args.offset));
3185
+ return isRecord$2(args) && Object.keys(args).every((key) => key === "offset") && (args.offset === void 0 || Number.isFinite(args.offset));
3196
3186
  }
3197
3187
  function isActionBinding(value) {
3198
- return isRecord(value) && Object.keys(value).length === 1 && (isRecord(value.functionCall) || isRecord(value.event));
3188
+ return isRecord$2(value) && Object.keys(value).length === 1 && (isRecord$2(value.functionCall) || isRecord$2(value.event));
3199
3189
  }
3200
3190
  /**
3201
3191
  * Checks one A2UI v1.0 operation against the catalog and the surfaces that
@@ -3213,7 +3203,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3213
3203
  * ```
3214
3204
  */
3215
3205
  function validateOperation(op, options) {
3216
- if (!isRecord(op)) return fail("operation must be a JSON object");
3206
+ if (!isRecord$2(op)) return fail("operation must be a JSON object");
3217
3207
  if (op.version !== A2UI_VERSION) return fail(versionProblem(op.version));
3218
3208
  const kind = getOperationKind(op);
3219
3209
  if (!kind) return fail(`operation must contain exactly one of ${OPERATION_KINDS.join(", ")}`);
@@ -3222,7 +3212,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3222
3212
  if (!GENERATIVE_UI_AGENT_FUNCTION_CALLS) return fail(GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
3223
3213
  return validateRendererFunctionCall(payload, options);
3224
3214
  }
3225
- if (!isRecord(payload) || typeof payload.surfaceId !== "string" || !payload.surfaceId) return fail(`${kind}.surfaceId is required`);
3215
+ if (!isRecord$2(payload) || typeof payload.surfaceId !== "string" || !payload.surfaceId) return fail(`${kind}.surfaceId is required`);
3226
3216
  const surfaceId = payload.surfaceId;
3227
3217
  if (kind === "createSurface") return validateCreateSurface(payload, surfaceId, options);
3228
3218
  if (!options.knownSurfaces.has(surfaceId)) return fail(`surface "${surfaceId}" does not exist; send createSurface first`);
@@ -3251,12 +3241,12 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3251
3241
  const catalogReason = catalogProblem(payload.catalogId, options.manifest);
3252
3242
  if (catalogReason) return fail(catalogReason);
3253
3243
  const { dataModel, components } = payload;
3254
- if (dataModel !== void 0 && !isRecord(dataModel)) return fail("createSurface.dataModel must be a JSON object");
3244
+ if (dataModel !== void 0 && !isRecord$2(dataModel)) return fail("createSurface.dataModel must be a JSON object");
3255
3245
  if (components === void 0) return OK;
3256
3246
  return validateComponents(components, "createSurface.components", options);
3257
3247
  }
3258
3248
  function validateRendererFunctionCall(payload, options) {
3259
- if (!(isRecord(payload) && typeof payload.functionCallId === "string" && payload.functionCallId !== "")) return fail("callRendererFunction.functionCallId must be a non-empty string");
3249
+ if (!(isRecord$2(payload) && typeof payload.functionCallId === "string" && payload.functionCallId !== "")) return fail("callRendererFunction.functionCallId must be a non-empty string");
3260
3250
  const reason = functionCallProblem(payload.callFunction, "callRendererFunction.callFunction", options);
3261
3251
  return reason ? fail(reason) : OK;
3262
3252
  }
@@ -3274,7 +3264,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3274
3264
  const path = (_payload$path = payload.path) !== null && _payload$path !== void 0 ? _payload$path : "/";
3275
3265
  if (typeof path !== "string" || !path.startsWith("/")) return fail("updateDataModel.path must be an absolute JSON pointer");
3276
3266
  if (path === "/") {
3277
- if (!isRecord(payload.value)) return fail("a root updateDataModel value must be a JSON object");
3267
+ if (!isRecord$2(payload.value)) return fail("a root updateDataModel value must be a JSON object");
3278
3268
  return OK;
3279
3269
  }
3280
3270
  const reason = pathProblem(path, "updateDataModel.path");
@@ -3294,7 +3284,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3294
3284
  if (!Array.isArray(components) || components.length === 0) return fail(`${label} must be a non-empty array`);
3295
3285
  const ids = /* @__PURE__ */ new Set();
3296
3286
  for (const node of components) {
3297
- if (!isRecord(node)) return fail("component must be a JSON object");
3287
+ if (!isRecord$2(node)) return fail("component must be a JSON object");
3298
3288
  const { id } = node;
3299
3289
  if (typeof id !== "string" || !id) return fail("id is required");
3300
3290
  const reason = nodeProblem(node, id, options);
@@ -3314,7 +3304,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3314
3304
  return `"${node.component}" is not allowed in target "${allowedComponents.target}"; use one of: ${names}`;
3315
3305
  }
3316
3306
  const { properties, required } = entry.props;
3317
- const propNames = isRecord(properties) ? Object.keys(properties) : [];
3307
+ const propNames = isRecord$2(properties) ? Object.keys(properties) : [];
3318
3308
  const props = Object.entries(node);
3319
3309
  for (const [key, value] of props) {
3320
3310
  if (key === "id" || key === "component") continue;
@@ -3324,7 +3314,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3324
3314
  continue;
3325
3315
  }
3326
3316
  if (key === "metadata") {
3327
- if (!(isRecord(value) && (value.extensions === void 0 || isRecord(value.extensions)))) return "metadata must be { \"extensions\": { ... } }";
3317
+ if (!(isRecord$2(value) && (value.extensions === void 0 || isRecord$2(value.extensions)))) return "metadata must be { \"extensions\": { ... } }";
3328
3318
  continue;
3329
3319
  }
3330
3320
  if (key === "accessibility") {
@@ -3372,7 +3362,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3372
3362
  * values, `hidden` is a boolean or a dynamic value.
3373
3363
  */
3374
3364
  function accessibilityProblem(value) {
3375
- if (!isRecord(value)) return "must be { \"label\": \"...\", \"description\": \"...\", \"live\": \"polite\", \"hidden\": false }";
3365
+ if (!isRecord$2(value)) return "must be { \"label\": \"...\", \"description\": \"...\", \"live\": \"polite\", \"hidden\": false }";
3376
3366
  const isDynamic = (field) => isPathBinding(field) || isCallBinding(field);
3377
3367
  for (const [key, field] of Object.entries(value)) {
3378
3368
  if (!ACCESSIBILITY_KEYS.includes(key)) return `unknown key "${key}"`;
@@ -3390,7 +3380,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3390
3380
  }
3391
3381
  }
3392
3382
  function actionBindingProblem(value, options) {
3393
- if (!isRecord(value)) return "must be an action object";
3383
+ if (!isRecord$2(value)) return "must be an action object";
3394
3384
  const keys = Object.keys(value);
3395
3385
  if (!(keys.length === 1 && (keys[0] === "functionCall" || keys[0] === "event"))) return "must be { \"event\": ... } or { \"functionCall\": ... }";
3396
3386
  if (keys[0] === "functionCall") return functionCallProblem(value.functionCall, "functionCall", options);
@@ -3401,18 +3391,18 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3401
3391
  * field in the reason.
3402
3392
  */
3403
3393
  function functionCallProblem(call, label, options) {
3404
- if (!isRecord(call)) return `${label} must be { "@call": "<function>", "args": { ... } }`;
3394
+ if (!isRecord$2(call)) return `${label} must be { "@call": "<function>", "args": { ... } }`;
3405
3395
  const name = call["@call"];
3406
3396
  if (typeof name !== "string" || !name) return typeof call.call === "string" ? `${label} names the function with "@call", not "call"` : `${label}["@call"] must be a function name`;
3407
3397
  const { args } = call;
3408
- if (args !== void 0 && !isRecord(args)) return `${label}.args must be an object`;
3398
+ if (args !== void 0 && !isRecord$2(args)) return `${label}.args must be an object`;
3409
3399
  const catalogReason = catalogProblem(call.catalogId, options.manifest);
3410
3400
  if (catalogReason) return `${label}: ${catalogReason}`;
3411
3401
  const argEntries = Object.entries(args !== null && args !== void 0 ? args : {});
3412
3402
  for (const [key, arg] of argEntries) if (isV09PathBinding(arg)) return `${label}.args.${key}: ${V09_PATH_REASON}`;
3413
3403
  const appFunctions = options.functions;
3414
- const declared = appFunctions !== void 0 && hasOwn(appFunctions, name) ? appFunctions[name] : void 0;
3415
- const builtIn = declared === void 0 && hasOwn(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
3404
+ const declared = appFunctions !== void 0 && hasOwn$1(appFunctions, name) ? appFunctions[name] : void 0;
3405
+ const builtIn = declared === void 0 && hasOwn$1(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
3416
3406
  if (declared === void 0 && builtIn === void 0) return appFunctions === void 0 ? void 0 : `function "${name}" is not exposed to generative UI`;
3417
3407
  if (declared === void 0 && appFunctions === void 0) return void 0;
3418
3408
  return callerProblem(name, declared !== null && declared !== void 0 ? declared : builtIn, label.startsWith("callRendererFunction") ? "agent" : "renderer");
@@ -3428,11 +3418,11 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3428
3418
  if (caller === "renderer" && !callers.renderer) return `function "${name}" runs only for the agent (allowedCallers "agentOnly"); the UI cannot call it`;
3429
3419
  }
3430
3420
  function eventProblem(event) {
3431
- if (!isRecord(event) || typeof event.name !== "string" || !event.name) return "event.name is required";
3421
+ if (!isRecord$2(event) || typeof event.name !== "string" || !event.name) return "event.name is required";
3432
3422
  const { userMessage, context } = event;
3433
- if (!(userMessage === void 0 || typeof userMessage === "string" || isPathBinding(userMessage) || isRecord(userMessage) && typeof userMessage["@call"] === "string" && findForbiddenCall(userMessage, { allowValueFunctions: true }) === void 0)) return isV09PathBinding(userMessage) ? `event.userMessage: ${V09_PATH_REASON}` : "event.userMessage must be a string, {\"@path\": \"/x\"} or a function value";
3423
+ if (!(userMessage === void 0 || typeof userMessage === "string" || isPathBinding(userMessage) || isRecord$2(userMessage) && typeof userMessage["@call"] === "string" && findForbiddenCall(userMessage, { allowValueFunctions: true }) === void 0)) return isV09PathBinding(userMessage) ? `event.userMessage: ${V09_PATH_REASON}` : "event.userMessage must be a string, {\"@path\": \"/x\"} or a function value";
3434
3424
  if (context === void 0) return void 0;
3435
- if (!isRecord(context)) return "event.context must be an object";
3425
+ if (!isRecord$2(context)) return "event.context must be an object";
3436
3426
  const entries = Object.entries(context);
3437
3427
  for (const [key, entry] of entries) {
3438
3428
  if (isV09PathBinding(entry)) return `event.context.${key}: ${V09_PATH_REASON}`;
@@ -3441,7 +3431,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3441
3431
  }
3442
3432
  }
3443
3433
  function slotProblem(value, kind, ownId) {
3444
- const isTemplate = isRecord(value) && "componentId" in value;
3434
+ const isTemplate = isRecord$2(value) && "componentId" in value;
3445
3435
  if (kind === "single" && isTemplate) return "a template { \"componentId\", \"path\" } is only allowed in a \"multiple\" slot";
3446
3436
  if (kind === "multiple" && isTemplate) return templateProblem(value, ownId);
3447
3437
  if (kind === "multiple" && !Array.isArray(value)) return "must be an array of component ids or a template { \"componentId\", \"path\" }";
@@ -3475,7 +3465,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3475
3465
  }
3476
3466
  return;
3477
3467
  }
3478
- if (!isRecord(value)) return void 0;
3468
+ if (!isRecord$2(value)) return void 0;
3479
3469
  if (isIndexCall(value)) return void 0;
3480
3470
  if (value["@call"] === "@index") return "@index takes only an offset";
3481
3471
  if (typeof value.call === "string") return "name the function with \"@call\", not \"call\"";
@@ -3484,7 +3474,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3484
3474
  if (typeof name === "string") {
3485
3475
  if (!options.allowValueFunctions || !isA2UIValueFunction(name)) return isA2UIBasicFunction(name) ? `"${name}" runs only from an event` : `"${name}" is not a basic function`;
3486
3476
  const args = value.args;
3487
- if (args !== void 0 && !isRecord(args)) return `the args of "${name}" must be an object`;
3477
+ if (args !== void 0 && !isRecord$2(args)) return `the args of "${name}" must be an object`;
3488
3478
  return args === void 0 ? void 0 : findForbiddenCall(args, options);
3489
3479
  }
3490
3480
  for (const item of Object.values(value)) {
@@ -3509,14 +3499,14 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3509
3499
  */
3510
3500
  function childRefProblem(node, ref, ownId) {
3511
3501
  const label = ref.path.filter((step) => step !== "*").join(".");
3512
- const isDynamic = (value) => isPathBinding(value) || isRecord(value) && "@call" in value;
3502
+ const isDynamic = (value) => isPathBinding(value) || isRecord$2(value) && "@call" in value;
3513
3503
  const visit = (value, steps) => {
3514
3504
  if (isDynamic(value)) return void 0;
3515
- if (steps.length === 0) {
3505
+ const [head, ...rest] = steps;
3506
+ if (head === void 0) {
3516
3507
  const reason = slotProblem(value, ref.kind, ownId);
3517
3508
  return reason ? `${label}: ${reason}` : void 0;
3518
3509
  }
3519
- const [head, ...rest] = steps;
3520
3510
  if (head === "*") {
3521
3511
  if (!Array.isArray(value)) return void 0;
3522
3512
  for (const item of value) {
@@ -3525,7 +3515,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3525
3515
  }
3526
3516
  return;
3527
3517
  }
3528
- if (!isRecord(value) || !hasOwn(value, head)) return void 0;
3518
+ if (!isRecord$2(value) || !hasOwn$1(value, head)) return void 0;
3529
3519
  return visit(value[head], rest);
3530
3520
  };
3531
3521
  return visit(node, ref.path);
@@ -3630,6 +3620,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3630
3620
  expectingValue = false;
3631
3621
  }
3632
3622
  break;
3623
+ case void 0: break;
3633
3624
  }
3634
3625
  }
3635
3626
  this.inString = inString;
@@ -3649,7 +3640,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3649
3640
  function parseObject(raw) {
3650
3641
  try {
3651
3642
  const value = JSON.parse(raw);
3652
- return isRecord(value) ? value : null;
3643
+ return isRecord$2(value) ? value : null;
3653
3644
  } catch (_unused3) {
3654
3645
  return null;
3655
3646
  }
@@ -3686,6 +3677,434 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3686
3677
  }
3687
3678
  };
3688
3679
 
3680
+ //#endregion
3681
+ //#region src/generative-ui/compact-schema.ts
3682
+ /** Objects nested deeper than this show as `object`. */
3683
+ const MAX_OBJECT_DEPTH = 2;
3684
+ /** A prop must appear verbatim in at least this many components to be hoisted. */
3685
+ const COMMON_PROP_MIN_COMPONENTS = 8;
3686
+ function isRecord$1(value) {
3687
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3688
+ }
3689
+ /** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
3690
+ function schemaList(value) {
3691
+ return Array.isArray(value) ? value.filter(isRecord$1) : [];
3692
+ }
3693
+ /**
3694
+ * Puts a top-level union in parentheses, so that `[]` applies to all of
3695
+ * it. A union inside braces needs none.
3696
+ */
3697
+ function asArrayItem(type) {
3698
+ let outside = type;
3699
+ for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside;) {
3700
+ outside = inner;
3701
+ inner = outside.replace(/\{[^{}]*\}/g, "");
3702
+ }
3703
+ return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
3704
+ }
3705
+ /**
3706
+ * A JSON Schema as a short TypeScript-like type, for example
3707
+ * `{ label: string; size?: "sm" | "md" }`.
3708
+ */
3709
+ function compactType(schema, depth) {
3710
+ const ref = childRefKind(schema);
3711
+ if (ref === "single") return "componentId";
3712
+ if (ref === "multiple") return "componentId[] | { componentId: string; path: string }";
3713
+ if ("const" in schema) return JSON.stringify(schema.const);
3714
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
3715
+ const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
3716
+ if (variants.length > 0) return variants.map((variant) => compactType(variant, depth)).join(" | ");
3717
+ return (Array.isArray(schema.type) ? schema.type : [schema.type]).map((type) => {
3718
+ switch (type) {
3719
+ case "string":
3720
+ case "boolean":
3721
+ case "null": return type;
3722
+ case "number":
3723
+ case "integer": return "number";
3724
+ case "array": return isRecord$1(schema.items) ? asArrayItem(compactType(schema.items, depth)) : "unknown[]";
3725
+ case "object": return compactObject(schema, depth);
3726
+ default: return "unknown";
3727
+ }
3728
+ }).join(" | ");
3729
+ }
3730
+ /** An object schema as `{ key: type; other?: type }`. */
3731
+ function compactObject(schema, depth) {
3732
+ const properties = isRecord$1(schema.properties) ? schema.properties : {};
3733
+ const entries = Object.entries(properties);
3734
+ if (entries.length === 0) return isRecord$1(schema.additionalProperties) ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>` : "object";
3735
+ if (depth >= MAX_OBJECT_DEPTH) return "object";
3736
+ const required = Array.isArray(schema.required) ? schema.required : [];
3737
+ return `{ ${entries.map(([key, value]) => {
3738
+ const type = isRecord$1(value) ? compactType(value, depth + 1) : "unknown";
3739
+ return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
3740
+ }).join("; ")} }`;
3741
+ }
3742
+ /** A schema as its type, with its description after `//`. */
3743
+ function describedType(schema, depth) {
3744
+ const type = compactType(schema, depth);
3745
+ return typeof schema.description === "string" ? `${type} // ${schema.description}` : type;
3746
+ }
3747
+ /**
3748
+ * The props of a component: `{ "label": "string", "size?": "..." }`. With
3749
+ * `descriptions`, each type carries its description after `//`.
3750
+ */
3751
+ function compactProps(schema, descriptions = true) {
3752
+ const properties = isRecord$1(schema.properties) ? schema.properties : {};
3753
+ const required = Array.isArray(schema.required) ? schema.required : [];
3754
+ const props = {};
3755
+ for (const [key, value] of Object.entries(properties)) {
3756
+ if (!isRecord$1(value)) continue;
3757
+ const name = required.includes(key) ? key : `${key}?`;
3758
+ props[name] = descriptions ? describedType(value, 1) : compactType(value, 1);
3759
+ }
3760
+ return props;
3761
+ }
3762
+ /**
3763
+ * The prop set worth listing once. Candidates are (key, type) pairs that at
3764
+ * least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
3765
+ * candidate subset of each component is a possible common set, scored by
3766
+ * the characters it saves (set size times the components that contain all
3767
+ * of it). `undefined` when no set is shared by enough components.
3768
+ */
3769
+ function findCommonProps(propsList) {
3770
+ const pairKey = (key, type) => `${key}\u0000${type}`;
3771
+ const counts = /* @__PURE__ */ new Map();
3772
+ for (const props of propsList) for (const [key, type] of Object.entries(props)) {
3773
+ var _counts$get;
3774
+ const id = pairKey(key, type);
3775
+ counts.set(id, ((_counts$get = counts.get(id)) !== null && _counts$get !== void 0 ? _counts$get : 0) + 1);
3776
+ }
3777
+ let best;
3778
+ let bestScore = 0;
3779
+ const seen = /* @__PURE__ */ new Set();
3780
+ for (const props of propsList) {
3781
+ const subset = Object.entries(props).filter(([key, type]) => {
3782
+ var _counts$get2;
3783
+ return ((_counts$get2 = counts.get(pairKey(key, type))) !== null && _counts$get2 !== void 0 ? _counts$get2 : 0) >= COMMON_PROP_MIN_COMPONENTS;
3784
+ });
3785
+ if (subset.length < 2) continue;
3786
+ const signature = subset.map(([key, type]) => pairKey(key, type)).join("\n");
3787
+ if (seen.has(signature)) continue;
3788
+ seen.add(signature);
3789
+ const members = propsList.filter((other) => subset.every(([key, type]) => other[key] === type)).length;
3790
+ if (members < COMMON_PROP_MIN_COMPONENTS) continue;
3791
+ const score = subset.reduce((total, [key, type]) => total + key.length + type.length, 0) * (members - 1);
3792
+ if (score > bestScore) {
3793
+ bestScore = score;
3794
+ best = Object.fromEntries(subset);
3795
+ }
3796
+ }
3797
+ return best;
3798
+ }
3799
+ /**
3800
+ * The component schema of the markdown transport, from the per-run
3801
+ * manifest. It is smaller than the manifest: each prop is one short type,
3802
+ * and the props that many components share verbatim (the layout props of
3803
+ * the containers) are listed once in `commonProps`; a component that takes
3804
+ * them is flagged `includesCommonProps`.
3805
+ * It has the catalog id, the targets with their descriptions and their
3806
+ * component lists, the functions with their parameters, the components
3807
+ * with their props, events and slots, and the surfaces of the thread. A surface lists the
3808
+ * values that the user set and the operations that the client dropped.
3809
+ *
3810
+ * @param manifest - The manifest from `buildGenerativeUIManifest`.
3811
+ * @param options - `propDescriptions` (default true) writes each prop's
3812
+ * description; `commonProps` (default true) lists shared props once.
3813
+ * @returns A JSON-ready object.
3814
+ *
3815
+ * @example
3816
+ * ```ts
3817
+ * const value = JSON.stringify(
3818
+ * buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
3819
+ * );
3820
+ * ```
3821
+ */
3822
+ function buildCompactGenerativeUISchema(manifest, options = {}) {
3823
+ const { propDescriptions = true, commonProps = true } = options;
3824
+ const components = {};
3825
+ for (const [name, component] of Object.entries(manifest.components)) {
3826
+ var _component$events;
3827
+ const events = Object.entries((_component$events = component.events) !== null && _component$events !== void 0 ? _component$events : {}).map(([event, definition]) => {
3828
+ var _definition$descripti;
3829
+ return [event, (_definition$descripti = definition.description) !== null && _definition$descripti !== void 0 ? _definition$descripti : compactType(definition.parameters, 0)];
3830
+ });
3831
+ components[name] = {
3832
+ ...component.description ? { description: component.description } : {},
3833
+ props: compactProps(component.props, propDescriptions),
3834
+ ...events.length > 0 ? { events: Object.fromEntries(events) } : {},
3835
+ ...component.slots ? { slots: component.slots } : {}
3836
+ };
3837
+ }
3838
+ const common = commonProps ? findCommonProps(Object.values(components).map((component) => component.props)) : void 0;
3839
+ if (common) {
3840
+ const commonKeys = Object.keys(common);
3841
+ for (const component of Object.values(components)) {
3842
+ if (!commonKeys.every((key) => component.props[key] === common[key])) continue;
3843
+ component.includesCommonProps = true;
3844
+ component.props = Object.fromEntries(Object.entries(component.props).filter(([key]) => !(key in common)));
3845
+ }
3846
+ }
3847
+ const functions = Object.fromEntries(Object.entries(manifest.functions).map(([name, fn]) => {
3848
+ const signature = fn.parameters.description;
3849
+ const hasSignature = typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2;
3850
+ const callers = functionCallers(fn);
3851
+ return [name, {
3852
+ ...fn.description ? { description: fn.description } : {},
3853
+ parameters: hasSignature ? signature : compactType(fn.parameters, 0),
3854
+ ...callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? { callers: callers.renderer ? "UI or agent" : "agent only" } : {}
3855
+ }];
3856
+ }));
3857
+ return {
3858
+ catalogId: manifest.catalogId,
3859
+ targets: manifest.targets,
3860
+ functions,
3861
+ ...common ? { commonProps: common } : {},
3862
+ components,
3863
+ surfaces: manifest.surfaces
3864
+ };
3865
+ }
3866
+
3867
+ //#endregion
3868
+ //#region src/generative-ui/schema-render.ts
3869
+ /** An own key (shared compiles to ES2017, which has no Object.hasOwn). */
3870
+ const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
3871
+ function isRecord(value) {
3872
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3873
+ }
3874
+ /** The props schema without the description of each prop. */
3875
+ function withoutPropDescriptions(schema) {
3876
+ if (!isRecord(schema.properties)) return schema;
3877
+ return {
3878
+ ...schema,
3879
+ properties: Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => {
3880
+ if (!isRecord(value)) return [key, value];
3881
+ const { description: _description, ...rest } = value;
3882
+ return [key, rest];
3883
+ }))
3884
+ };
3885
+ }
3886
+ /** The short signature of a function: its built-in signature, or its schema made short. */
3887
+ function functionSignature(fn) {
3888
+ const signature = fn.parameters.description;
3889
+ return typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2 ? signature : compactType(fn.parameters, 0);
3890
+ }
3891
+ /**
3892
+ * A function name with its parameters: `pick{ id: string }`, `clearCart{}`
3893
+ * for no arguments, `setVolume(number)` for a parameter that is not an object.
3894
+ */
3895
+ function nameWithParameters(name, parameters) {
3896
+ if (parameters.startsWith("{")) return `${name}${parameters}`;
3897
+ if (parameters === "object") return `${name}{}`;
3898
+ return `${name}(${parameters})`;
3899
+ }
3900
+ /**
3901
+ * One component as a TypeScript-like signature line, with its events and
3902
+ * slots on the lines below:
3903
+ * `- Text(text?: string // The text): Shows text`.
3904
+ */
3905
+ function signatureLines(name, component, settings) {
3906
+ var _component$events, _component$slots;
3907
+ const lines = [`- ${name}(${Object.entries(compactProps(component.props, settings.propDescriptions)).map(([key, type]) => `${key}: ${type}`).join(", ")})${component.description ? `: ${oneLine(component.description)}` : ""}`];
3908
+ const events = Object.entries((_component$events = component.events) !== null && _component$events !== void 0 ? _component$events : {}).map(([event, definition]) => `${event}(${definition.description ? oneLine(definition.description) : compactType(definition.parameters, 0)})`);
3909
+ if (events.length > 0) lines.push(` events: ${events.join(", ")}`);
3910
+ const slots = Object.entries((_component$slots = component.slots) !== null && _component$slots !== void 0 ? _component$slots : {}).map(([slot, kind]) => `${slot} (${kind})`);
3911
+ if (slots.length > 0) lines.push(` slots: ${slots.join(", ")}`);
3912
+ return lines;
3913
+ }
3914
+ /** The whole schema as signature text: targets, functions, components, surfaces. */
3915
+ function signatureSchema(manifest, settings) {
3916
+ const targets = manifest.targets.map((t) => {
3917
+ const limit = t.components ? `; only ${t.components.join(", ")}` : "";
3918
+ return `- ${t.id} (${t.kind}${limit})${t.description ? `: ${oneLine(t.description)}` : ""}`;
3919
+ });
3920
+ const functions = Object.entries(manifest.functions).map(([name, fn]) => {
3921
+ const callers = functionCallers(fn);
3922
+ const who = callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? callers.renderer ? " (UI or agent)" : " (agent only)" : "";
3923
+ return `- ${nameWithParameters(name, functionSignature(fn))}${who}${fn.description ? `: ${oneLine(fn.description)}` : ""}`;
3924
+ });
3925
+ const components = Object.entries(manifest.components).flatMap(([name, component]) => signatureLines(name, component, settings));
3926
+ const surfaces = Object.entries(manifest.surfaces).map(([id, s]) => {
3927
+ var _s$rejected;
3928
+ return `- ${id} (target ${s.target})${s.status ? ` status: ${s.status}` : ""}${s.dataModel ? ` user values: ${JSON.stringify(s.dataModel)}` : ""}${((_s$rejected = s.rejected) !== null && _s$rejected !== void 0 ? _s$rejected : []).map((r) => ` rejected: ${r}`).join("")}`;
3929
+ });
3930
+ return [
3931
+ `Catalog: ${manifest.catalogId}`,
3932
+ `Targets:\n${targets.join("\n") || "- none"}`,
3933
+ `Functions:\n${functions.join("\n") || "- none"}`,
3934
+ `Components:\n${components.join("\n") || "- none"}`,
3935
+ `Surfaces:\n${surfaces.join("\n") || "- none"}`
3936
+ ].join("\n\n");
3937
+ }
3938
+ /** A description on one line, so its lines cannot read as new entries. */
3939
+ function oneLine(text) {
3940
+ return text.replace(/\s*\n\s*/g, " ");
3941
+ }
3942
+ /** Values that would read as a type or a number once their quotes are gone. */
3943
+ const AMBIGUOUS_VALUE = /^(?:string|number|integer|boolean|true|false|null|object|array|unknown|any|-?\d[\d.]*)$/;
3944
+ /**
3945
+ * A compact type with bare enum values and tight unions:
3946
+ * `"sm" | "md" | "lg"` becomes `sm|md|lg`. A union keeps its quotes when it
3947
+ * also holds a type (`"sm" | number`) or a value that reads as a type or a
3948
+ * number (`"number" | "currency"`, `"1" | "2"`), and so do values that are
3949
+ * not plain words.
3950
+ */
3951
+ function bareType(type) {
3952
+ return type.replace(/"[A-Za-z0-9_#%.-]+"(?: \| "[A-Za-z0-9_#%.-]+")*(?! \|)/g, (union, offset, whole) => {
3953
+ if (whole.slice(offset - 2, offset) === "| ") return union;
3954
+ const values = union.split(" | ").map((v) => v.slice(1, -1));
3955
+ if (values.some((v) => AMBIGUOUS_VALUE.test(v))) return union;
3956
+ return values.join("|");
3957
+ }).replace(/ \| /g, "|");
3958
+ }
3959
+ /** A compact prop (`type // description`) as `name: type - description`. */
3960
+ function propLine(key, value) {
3961
+ const name = key.endsWith("?") ? key.slice(0, -1) : `${key}*`;
3962
+ const cut = value.indexOf(" // ");
3963
+ const type = bareType(cut < 0 ? value : value.slice(0, cut));
3964
+ const text = cut < 0 ? "" : value.slice(cut + 4).trim();
3965
+ return ` ${name}: ${type}${text ? ` - ${oneLine(text)}` : ""}`;
3966
+ }
3967
+ /**
3968
+ * The whole schema as plain lines: a header line per component and one
3969
+ * indented line per prop: events are `action` props and slots `componentId`
3970
+ * or `childList` props. Props are optional unless marked `*`, enum values
3971
+ * are bare, and the common props are listed once. It carries the same names, types and descriptions as
3972
+ * `compact`, in fewer tokens.
3973
+ */
3974
+ function linesSchema(manifest, settings) {
3975
+ const compact = buildCompactGenerativeUISchema(manifest, {
3976
+ propDescriptions: settings.propDescriptions,
3977
+ commonProps: settings.commonProps
3978
+ });
3979
+ const targets = compact.targets.map((t) => {
3980
+ const limit = t.components ? `, only ${t.components.join(", ")}` : "";
3981
+ return `${t.id} (${t.kind}${limit})${t.description ? `: ${oneLine(t.description)}` : ""}`;
3982
+ }).join("; ");
3983
+ const functions = Object.entries(compact.functions).map(([name, fn]) => `${nameWithParameters(name, fn.parameters)}${"callers" in fn ? ` (${fn.callers})` : ""}${fn.description ? `: ${oneLine(fn.description)}` : ""}`);
3984
+ const common = compact.commonProps ? Object.entries(compact.commonProps).map(([k, v]) => propLine(k, v)) : [];
3985
+ const components = Object.entries(compact.components).map(([name, c]) => {
3986
+ var _c$events;
3987
+ return {
3988
+ name,
3989
+ c,
3990
+ own: [...Object.entries(c.props).map(([k, v]) => propLine(k, v)), ...Object.entries((_c$events = c.events) !== null && _c$events !== void 0 ? _c$events : {}).map(([e, d]) => ` ${e}: action - ${oneLine(d)}`)]
3991
+ };
3992
+ }).flatMap(({ name, c, own }) => {
3993
+ var _c$slots;
3994
+ const lines = [`${name}${c.includesCommonProps ? " +common" : ""}${c.description ? `: ${oneLine(c.description)}` : ""}`, ...own];
3995
+ for (const [slot, kind] of Object.entries((_c$slots = c.slots) !== null && _c$slots !== void 0 ? _c$slots : {})) lines.push(` ${slot}: ${kind === "single" ? "componentId" : "childList"}`);
3996
+ return lines;
3997
+ });
3998
+ const surfaces = Object.keys(compact.surfaces).length ? JSON.stringify(compact.surfaces) : "none";
3999
+ return [
4000
+ `Catalog ${compact.catalogId}. Targets: ${targets || "none"}`,
4001
+ "Props are optional unless marked *. a|b|c is one of those strings, quoted when one reads as a type or a number. A component marked +common also takes every common prop. A prop of type action is an event prop: give it {\"event\":{...}} or {\"functionCall\":{...}}. A componentId prop takes one component id; a childList prop takes a list of ids or a template.",
4002
+ `Functions:\n${functions.join("\n")}`,
4003
+ ...common.length ? [`Common props:\n${common.join("\n")}`] : [],
4004
+ `Components:\n${components.join("\n")}`,
4005
+ `Surfaces: ${surfaces}`
4006
+ ].join("\n\n");
4007
+ }
4008
+ /**
4009
+ * The component schema of the markdown transport, as the text of its
4010
+ * context entry, in the notation of `settings`. `compact` is the schema that
4011
+ * ships (`buildCompactGenerativeUISchema`), `json-schema` the manifest parts
4012
+ * as JSON, `ts-signature` one line per component, `lines` one line per
4013
+ * prop with bare enums (the fewest tokens).
4014
+ *
4015
+ * @example
4016
+ * ```ts
4017
+ * const value = renderGenerativeUISchema(manifest, spec.schema.markdown);
4018
+ * ```
4019
+ */
4020
+ function renderGenerativeUISchema(manifest, settings) {
4021
+ switch (settings.notation) {
4022
+ case "compact": return JSON.stringify(buildCompactGenerativeUISchema(manifest, {
4023
+ propDescriptions: settings.propDescriptions,
4024
+ commonProps: settings.commonProps
4025
+ }));
4026
+ case "json-schema": {
4027
+ const components = Object.fromEntries(Object.entries(manifest.components).map(([name, c]) => [name, settings.propDescriptions ? c : {
4028
+ ...c,
4029
+ props: withoutPropDescriptions(c.props)
4030
+ }]));
4031
+ return JSON.stringify({
4032
+ catalogId: manifest.catalogId,
4033
+ targets: manifest.targets,
4034
+ functions: manifest.functions,
4035
+ components,
4036
+ surfaces: manifest.surfaces
4037
+ });
4038
+ }
4039
+ case "ts-signature": return signatureSchema(manifest, settings);
4040
+ case "lines": return linesSchema(manifest, settings);
4041
+ }
4042
+ }
4043
+ /**
4044
+ * The component list of the tool guide, one entry per component, in the
4045
+ * notation of `settings`. `json-schema` is the list that ships.
4046
+ */
4047
+ function renderGenerativeUIComponentList(components, settings) {
4048
+ return Object.entries(components).map(([name, c]) => {
4049
+ if (settings.notation === "ts-signature" || settings.notation === "lines") return signatureLines(name, c, settings).join("\n");
4050
+ const props = settings.notation === "compact" ? compactProps(c.props, settings.propDescriptions) : settings.propDescriptions ? c.props : withoutPropDescriptions(c.props);
4051
+ const lines = [`- **${name}**${c.description ? `: ${oneLine(c.description)}` : ""}`, ` props: ${JSON.stringify(props)}`];
4052
+ if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
4053
+ if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
4054
+ return lines.join("\n");
4055
+ }).join("\n");
4056
+ }
4057
+ /**
4058
+ * The manifest with replaced descriptions: `"Name"` replaces the
4059
+ * description of a component, `"Name.prop"` the description of one of its
4060
+ * props. Keys that name no component or prop are left out of the result
4061
+ * and listed in `unknown`. The manifest is not changed.
4062
+ */
4063
+ function applyDescriptionOverrides(manifest, overrides) {
4064
+ const components = structuredClone(manifest.components);
4065
+ const unknown = [];
4066
+ for (const [key, description] of Object.entries(overrides)) {
4067
+ const [name, prop, ...rest] = key.split(".");
4068
+ const component = name !== void 0 && hasOwn(components, name) ? components[name] : void 0;
4069
+ if (!component || rest.length > 0) {
4070
+ unknown.push(key);
4071
+ continue;
4072
+ }
4073
+ if (prop === void 0) {
4074
+ component.description = description;
4075
+ continue;
4076
+ }
4077
+ const properties = component.props.properties;
4078
+ const property = isRecord(properties) && hasOwn(properties, prop) ? properties[prop] : void 0;
4079
+ if (!isRecord(property)) {
4080
+ unknown.push(key);
4081
+ continue;
4082
+ }
4083
+ property.description = description;
4084
+ }
4085
+ return {
4086
+ manifest: {
4087
+ ...manifest,
4088
+ components
4089
+ },
4090
+ unknown
4091
+ };
4092
+ }
4093
+ /**
4094
+ * The components and props of `manifest` whose names do not appear in
4095
+ * `rendered`. A schema notation that leaves one out would hide part of the
4096
+ * catalog from the model.
4097
+ */
4098
+ function schemaCoverage(manifest, rendered) {
4099
+ const missing = [];
4100
+ for (const [name, component] of Object.entries(manifest.components)) {
4101
+ if (!rendered.includes(name)) missing.push(name);
4102
+ const properties = isRecord(component.props.properties) ? component.props.properties : {};
4103
+ for (const prop of Object.keys(properties)) if (!rendered.includes(prop)) missing.push(`${name}.${prop}`);
4104
+ }
4105
+ return { missing };
4106
+ }
4107
+
3689
4108
  //#endregion
3690
4109
  //#region src/generative-ui/prompt.ts
3691
4110
  const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
@@ -3700,19 +4119,15 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3700
4119
  * the `render_ui` rules, the targets, components, functions, and surfaces of
3701
4120
  * the manifest. It is in shared so that the inspector shows the same text.
3702
4121
  */
3703
- function buildGenerativeUIPrompt(manifest) {
4122
+ function buildGenerativeUIPrompt(manifest, spec = defaultGenerativeUIPromptSpec()) {
4123
+ var _spec$tool$operations;
3704
4124
  const targets = manifest.targets.map((t) => {
3705
4125
  const place = t.kind === "chat" ? "inside the chat transcript" : "a named area of the app";
3706
4126
  const limit = t.components ? `; only ${t.components.join(", ") || "no components"}` : "";
3707
4127
  const description = t.description ? `: ${t.description}` : "";
3708
4128
  return `- "${t.id}" (${place}${limit})${description}`;
3709
4129
  }).join("\n");
3710
- const components = Object.entries(manifest.components).map(([name, c]) => {
3711
- const lines = [`- **${name}**${c.description ? `: ${c.description}` : ""}`, ` props: ${JSON.stringify(c.props)}`];
3712
- if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
3713
- if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
3714
- return lines.join("\n");
3715
- }).join("\n");
4130
+ const components = renderGenerativeUIComponentList(manifest.components, spec.schema.tool);
3716
4131
  const functions = Object.entries(manifest.functions).map(([name, f]) => {
3717
4132
  const signature = f.parameters.description;
3718
4133
  const args = typeof signature === "string" && signature.startsWith("{") && Object.keys(f.parameters).length === 2 ? signature : JSON.stringify(f.parameters);
@@ -3731,38 +4146,15 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
3731
4146
  var _s$rejected$length, _s$rejected2;
3732
4147
  return s.dataModel !== void 0 || ((_s$rejected$length = (_s$rejected2 = s.rejected) === null || _s$rejected2 === void 0 ? void 0 : _s$rejected2.length) !== null && _s$rejected$length !== void 0 ? _s$rejected$length : 0) > 0;
3733
4148
  }) ? "User values are what the user entered, by path. Your writes to those paths are ignored. Rejected operations were dropped: send them again with the problem fixed.\n" : "";
3734
- const { functions: hasFunctions, events, templates, checks } = generativeUIGuideFeatures(manifest);
3735
- const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;
3736
- const operations = [
3737
- "{\"version\":\"v1.0\",\"createSurface\":{\"surfaceId\":\"<new id>\",\"dataModel\":{...},\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"<child id>\"]}]}}: the first operation of a new surface. \"dataModel\" and \"components\" are optional.",
3738
- "{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
3739
- "{\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"<id>\",\"path\":\"/some/path\",\"value\":<json>}}: set the value at \"path\". Always give \"value\". \"value\":null deletes the key at \"path\".",
3740
- "{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
3741
- ...agentCalls ? ["{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."] : []
3742
- ];
3743
- const rules = [
3744
- "Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
3745
- "A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
3746
- "Stream progressively: put the initial data in \"dataModel\" and the root in \"components\" of the createSurface operation, then send one updateComponents operation per child, so the UI appears while you are still writing. The root must already list the ids of its children in its slot props (for example \"children\":[\"card-1\",\"card-2\"]), even though the children come later. A component that no slot references is never shown.",
3747
- "Updating a component replaces all of its props, so resend every prop.",
3748
- "Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
3749
- ...events ? [hasFunctions ? "Event props take an action. {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}} runs an app function in the browser immediately, and you are not told about it. {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\". Only call functions listed below." : "Event props take an action: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\"."] : [],
3750
- "To show a different view, create a new surface with a new surfaceId (for example, a checkout form after a cart summary). Update an existing surface only when the user asks to change that same view: then do not send createSurface, use its surfaceId, and pass its existing target. Never reuse an earlier chat surface for a different view, because that replaces the earlier UI and anything the user typed into it.",
3751
- "Never use a surfaceId again, also after deleteSurface.",
3752
- "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Only call functions listed below. formatString interpolates ${/path} and ${fn(arg: value)} in its value.",
3753
- "${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}.",
3754
- "For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
3755
- ...checks ? ["Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks."] : [],
3756
- ...templates ? ["To repeat a component for each item of a list, give a multiple slot a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}. Inside the template, paths are relative to the item (\"name\", not \"/name\"). {\"@call\":\"@index\"} gives the position of the item, from 0; {\"@call\":\"@index\",\"args\":{\"offset\":1}} counts from 1."] : [],
3757
- ...agentCalls ? ["Give every callRendererFunction a new functionCallId. Call only a function marked (UI or agent) or (agent only); a function with no mark is for the UI only. A function marked (agent only) is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you in a new turn, as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Do not wait for the result in this reply, and do not guess it."] : []
3758
- ];
4149
+ const features = generativeUIPromptFeatures(generativeUIGuideFeatures(manifest));
4150
+ const { intro, whenToShow } = spec.tool;
4151
+ const operations = selectPromptItems((_spec$tool$operations = spec.tool.operations) !== null && _spec$tool$operations !== void 0 ? _spec$tool$operations : [], features);
4152
+ const rules = selectPromptItems(spec.tool.rules, features);
3759
4153
  return [
3760
4154
  `## Generative UI
3761
- Call \`${GENERATIVE_UI_RENDER_TOOL}\` to show UI. Arguments: \`target\` first, then \`operations\` (A2UI v1.0 operations, applied in order).
3762
-
3763
- ${GENERATIVE_UI_WHEN_TO_SHOW}
4155
+ ${intro}
3764
4156
 
3765
- Every operation has "version":"v1.0" and exactly one of:
4157
+ ${whenToShow ? `${whenToShow}\n\n` : ""}Every operation has "version":"1.0" and exactly one of:
3766
4158
  ${operations.map((op) => `- ${op}`).join("\n")}
3767
4159
 
3768
4160
  Rules:
@@ -3844,8 +4236,6 @@ exports.COPILOT_CLOUD_ERROR_NAMES = COPILOT_CLOUD_ERROR_NAMES;
3844
4236
  exports.COPILOT_CLOUD_PUBLIC_API_KEY_HEADER = COPILOT_CLOUD_PUBLIC_API_KEY_HEADER;
3845
4237
  exports.COPILOT_CLOUD_VERSION = COPILOT_CLOUD_VERSION;
3846
4238
  exports.ConfigurationError = ConfigurationError;
3847
- exports.ConsoleColors = ConsoleColors;
3848
- exports.ConsoleStyles = ConsoleStyles;
3849
4239
  exports.CopilotKitAgentDiscoveryError = CopilotKitAgentDiscoveryError;
3850
4240
  exports.CopilotKitApiDiscoveryError = CopilotKitApiDiscoveryError;
3851
4241
  exports.CopilotKitError = CopilotKitError;
@@ -3853,7 +4243,6 @@ exports.CopilotKitErrorCode = CopilotKitErrorCode;
3853
4243
  exports.CopilotKitLowLevelError = CopilotKitLowLevelError;
3854
4244
  exports.CopilotKitMisuseError = CopilotKitMisuseError;
3855
4245
  exports.CopilotKitRemoteEndpointDiscoveryError = CopilotKitRemoteEndpointDiscoveryError;
3856
- exports.CopilotKitVersionMismatchError = CopilotKitVersionMismatchError;
3857
4246
  exports.DEFAULT_AGENT_ID = DEFAULT_AGENT_ID;
3858
4247
  exports.ERROR_CONFIG = ERROR_CONFIG;
3859
4248
  exports.ERROR_NAMES = ERROR_NAMES;
@@ -3870,11 +4259,14 @@ exports.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE = GENERATIVE_UI_FUNCTION_CALL_
3870
4259
  exports.GENERATIVE_UI_MARKDOWN_GUIDELINES = GENERATIVE_UI_MARKDOWN_GUIDELINES;
3871
4260
  exports.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION;
3872
4261
  exports.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION = GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION;
4262
+ exports.GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW = GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW;
3873
4263
  exports.GENERATIVE_UI_MAX_REJECTION_LENGTH = GENERATIVE_UI_MAX_REJECTION_LENGTH;
3874
4264
  exports.GENERATIVE_UI_MAX_SUMMARY_REJECTIONS = GENERATIVE_UI_MAX_SUMMARY_REJECTIONS;
3875
4265
  exports.GENERATIVE_UI_MAX_TARGET_COMPONENTS = GENERATIVE_UI_MAX_TARGET_COMPONENTS;
3876
4266
  exports.GENERATIVE_UI_RENDER_TOOL = GENERATIVE_UI_RENDER_TOOL;
3877
4267
  exports.GENERATIVE_UI_ROOT_ID = GENERATIVE_UI_ROOT_ID;
4268
+ exports.GENERATIVE_UI_WHEN_TO_SHOW = GENERATIVE_UI_WHEN_TO_SHOW;
4269
+ exports.GUIDE_COMPONENTS = GUIDE_COMPONENTS;
3878
4270
  exports.MODEL_HOST_CLASSES = MODEL_HOST_CLASSES;
3879
4271
  exports.MissingPublicApiKeyError = MissingPublicApiKeyError;
3880
4272
  exports.RUNTIME_MODE_INTELLIGENCE = RUNTIME_MODE_INTELLIGENCE;
@@ -3893,6 +4285,8 @@ exports.UNSAMPLED_RATE = UNSAMPLED_RATE;
3893
4285
  exports.UpgradeRequiredError = UpgradeRequiredError;
3894
4286
  exports.actionParametersToJsonSchema = actionParametersToJsonSchema;
3895
4287
  exports.applyChildRefMarks = applyChildRefMarks;
4288
+ exports.applyDescriptionOverrides = applyDescriptionOverrides;
4289
+ exports.buildCompactGenerativeUISchema = buildCompactGenerativeUISchema;
3896
4290
  exports.buildGenerativeUIMarkdownGuidelines = buildGenerativeUIMarkdownGuidelines;
3897
4291
  exports.buildGenerativeUIPrompt = buildGenerativeUIPrompt;
3898
4292
  exports.callerProblem = callerProblem;
@@ -3902,17 +4296,15 @@ exports.classifyModelHost = classifyModelHost;
3902
4296
  exports.collectChildRefs = collectChildRefs;
3903
4297
  exports.commitRowKeyStore = commitRowKeyStore;
3904
4298
  exports.computeSamplingMeta = computeSamplingMeta;
3905
- exports.convertJsonSchemaToZodSchema = convertJsonSchemaToZodSchema;
3906
4299
  exports.copyToClipboard = copyToClipboard;
3907
4300
  exports.createAttachmentContent = createAttachmentContent;
3908
4301
  exports.createLicenseContextValue = createLicenseContextValue;
3909
4302
  exports.createRowKeyStore = createRowKeyStore;
3910
4303
  exports.createRunEventFinalizer = createRunEventFinalizer;
3911
- exports.dataToUUID = dataToUUID;
4304
+ exports.defaultGenerativeUIPromptSpec = defaultGenerativeUIPromptSpec;
3912
4305
  exports.ensureStructuredError = ensureStructuredError;
3913
4306
  exports.envelopeToManifest = envelopeToManifest;
3914
4307
  exports.exceedsMaxSize = exceedsMaxSize;
3915
- exports.executeConditions = executeConditions;
3916
4308
  exports.extractRenderUIArgs = extractRenderUIArgs;
3917
4309
  exports.finalizeRunEvents = finalizeRunEvents;
3918
4310
  exports.firstNonBlankTelemetryId = firstNonBlankTelemetryId;
@@ -3921,14 +4313,13 @@ exports.functionCallers = functionCallers;
3921
4313
  exports.generateVideoThumbnail = generateVideoThumbnail;
3922
4314
  exports.generativeUIFunctionCallMessageId = generativeUIFunctionCallMessageId;
3923
4315
  exports.generativeUIGuideFeatures = generativeUIGuideFeatures;
4316
+ exports.generativeUIPromptFeatures = generativeUIPromptFeatures;
3924
4317
  exports.generativeUISurfaceMessageId = generativeUISurfaceMessageId;
3925
4318
  exports.getDocumentIcon = getDocumentIcon;
3926
4319
  exports.getModalityFromMimeType = getModalityFromMimeType;
3927
4320
  exports.getOperationKind = getOperationKind;
3928
4321
  exports.getOperationSurfaceId = getOperationSurfaceId;
3929
- exports.getPossibleVersionMismatch = getPossibleVersionMismatch;
3930
4322
  exports.getSourceUrl = getSourceUrl;
3931
- exports.getZodParameters = getZodParameters;
3932
4323
  exports.hasBoundChildRef = hasBoundChildRef;
3933
4324
  exports.isA2UIBasicFunction = isA2UIBasicFunction;
3934
4325
  exports.isA2UIValueFunction = isA2UIValueFunction;
@@ -3939,12 +4330,9 @@ exports.isMacOS = isMacOS;
3939
4330
  exports.isPathBinding = isPathBinding;
3940
4331
  exports.isStructuredCopilotKitError = isStructuredCopilotKitError;
3941
4332
  exports.isTelemetryDisabled = isTelemetryDisabled;
3942
- exports.isValidUUID = isValidUUID;
3943
4333
  exports.isValidationResult = isValidationResult;
3944
4334
  exports.jsonSchemaToActionParameters = jsonSchemaToActionParameters;
3945
4335
  exports.lambdaClient = lambdaClient;
3946
- exports.logCopilotKitPlatformMessage = logCopilotKitPlatformMessage;
3947
- exports.logStyled = logStyled;
3948
4336
  exports.logger = logger;
3949
4337
  exports.mapAtChildRef = mapAtChildRef;
3950
4338
  exports.matchesAcceptFilter = matchesAcceptFilter;
@@ -3957,23 +4345,27 @@ exports.parseJson = parseJson;
3957
4345
  exports.parseTelemetryIdFromLicense = parseTelemetryIdFromLicense;
3958
4346
  exports.partialJSONParse = partialJSONParse;
3959
4347
  exports.phoenixExponentialBackoff = phoenixExponentialBackoff;
4348
+ exports.processEnv = processEnv;
3960
4349
  exports.pruneRowKeyStore = pruneRowKeyStore;
3961
- exports.publicApiKeyRequired = publicApiKeyRequired;
3962
4350
  exports.randomId = randomId;
3963
4351
  exports.randomUUID = randomUUID;
3964
4352
  exports.readBody = readBody;
3965
4353
  exports.readCopilotKitUIEnvelope = readCopilotKitUIEnvelope;
3966
4354
  exports.readFileAsBase64 = readFileAsBase64;
4355
+ exports.renderGenerativeUIComponentList = renderGenerativeUIComponentList;
4356
+ exports.renderGenerativeUISchema = renderGenerativeUISchema;
3967
4357
  exports.resolveDebugConfig = resolveDebugConfig;
3968
4358
  exports.resolveRowRenderKeys = resolveRowRenderKeys;
3969
4359
  exports.resolveRowRenderKeysById = resolveRowRenderKeysById;
3970
4360
  exports.safeParseToolArgs = safeParseToolArgs;
4361
+ exports.schemaCoverage = schemaCoverage;
3971
4362
  exports.schemaToJsonSchema = schemaToJsonSchema;
4363
+ exports.selectPromptItems = selectPromptItems;
3972
4364
  exports.shouldEnableInspector = shouldEnableInspector;
3973
4365
  exports.stripIntelligenceRoutingFields = stripIntelligenceRoutingFields;
3974
- exports.styledConsole = styledConsole;
3975
4366
  exports.toA2UIActionMessage = toA2UIActionMessage;
3976
4367
  exports.tryMap = tryMap;
3977
4368
  exports.validateOperation = validateOperation;
4369
+ exports.ɵanySchema = ɵanySchema;
3978
4370
  });
3979
4371
  //# sourceMappingURL=index.umd.js.map