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

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 (220) hide show
  1. package/README.md +3 -14
  2. package/dist/a2ui-prompts.cjs +21 -62
  3. package/dist/a2ui-prompts.cjs.map +1 -1
  4. package/dist/a2ui-prompts.d.cts +8 -1
  5. package/dist/a2ui-prompts.d.cts.map +1 -1
  6. package/dist/a2ui-prompts.d.mts +8 -1
  7. package/dist/a2ui-prompts.d.mts.map +1 -1
  8. package/dist/a2ui-prompts.mjs +22 -62
  9. package/dist/a2ui-prompts.mjs.map +1 -1
  10. package/dist/generative-ui/basic-functions.cjs +1 -1
  11. package/dist/generative-ui/basic-functions.cjs.map +1 -1
  12. package/dist/generative-ui/basic-functions.mjs +1 -1
  13. package/dist/generative-ui/basic-functions.mjs.map +1 -1
  14. package/dist/generative-ui/compact-schema.cjs +187 -0
  15. package/dist/generative-ui/compact-schema.cjs.map +1 -0
  16. package/dist/generative-ui/compact-schema.d.cts +55 -0
  17. package/dist/generative-ui/compact-schema.d.cts.map +1 -0
  18. package/dist/generative-ui/compact-schema.d.mts +55 -0
  19. package/dist/generative-ui/compact-schema.d.mts.map +1 -0
  20. package/dist/generative-ui/compact-schema.mjs +185 -0
  21. package/dist/generative-ui/compact-schema.mjs.map +1 -0
  22. package/dist/generative-ui/prompt-spec.cjs +225 -0
  23. package/dist/generative-ui/prompt-spec.cjs.map +1 -0
  24. package/dist/generative-ui/prompt-spec.d.cts +94 -0
  25. package/dist/generative-ui/prompt-spec.d.cts.map +1 -0
  26. package/dist/generative-ui/prompt-spec.d.mts +94 -0
  27. package/dist/generative-ui/prompt-spec.d.mts.map +1 -0
  28. package/dist/generative-ui/prompt-spec.mjs +220 -0
  29. package/dist/generative-ui/prompt-spec.mjs.map +1 -0
  30. package/dist/generative-ui/prompt.cjs +10 -36
  31. package/dist/generative-ui/prompt.cjs.map +1 -1
  32. package/dist/generative-ui/prompt.d.cts +2 -1
  33. package/dist/generative-ui/prompt.d.cts.map +1 -1
  34. package/dist/generative-ui/prompt.d.mts +2 -1
  35. package/dist/generative-ui/prompt.d.mts.map +1 -1
  36. package/dist/generative-ui/prompt.mjs +12 -38
  37. package/dist/generative-ui/prompt.mjs.map +1 -1
  38. package/dist/generative-ui/schema-render.cjs +242 -0
  39. package/dist/generative-ui/schema-render.cjs.map +1 -0
  40. package/dist/generative-ui/schema-render.d.cts +44 -0
  41. package/dist/generative-ui/schema-render.d.cts.map +1 -0
  42. package/dist/generative-ui/schema-render.d.mts +44 -0
  43. package/dist/generative-ui/schema-render.d.mts.map +1 -0
  44. package/dist/generative-ui/schema-render.mjs +239 -0
  45. package/dist/generative-ui/schema-render.mjs.map +1 -0
  46. package/dist/index.cjs +17 -15
  47. package/dist/index.cjs.map +1 -1
  48. package/dist/index.d.cts +10 -9
  49. package/dist/index.d.cts.map +1 -1
  50. package/dist/index.d.mts +10 -9
  51. package/dist/index.d.mts.map +1 -1
  52. package/dist/index.mjs +9 -7
  53. package/dist/index.mjs.map +1 -1
  54. package/dist/index.umd.js +808 -438
  55. package/dist/index.umd.js.map +1 -1
  56. package/dist/package.cjs +1 -1
  57. package/dist/package.mjs +1 -1
  58. package/dist/standard-schema.cjs +20 -7
  59. package/dist/standard-schema.cjs.map +1 -1
  60. package/dist/standard-schema.d.cts +15 -16
  61. package/dist/standard-schema.d.cts.map +1 -1
  62. package/dist/standard-schema.d.mts +15 -16
  63. package/dist/standard-schema.d.mts.map +1 -1
  64. package/dist/standard-schema.mjs +20 -8
  65. package/dist/standard-schema.mjs.map +1 -1
  66. package/dist/telemetry/lambda-client.cjs.map +1 -1
  67. package/dist/telemetry/lambda-client.d.cts.map +1 -1
  68. package/dist/telemetry/lambda-client.d.mts.map +1 -1
  69. package/dist/telemetry/lambda-client.mjs.map +1 -1
  70. package/dist/telemetry/telemetry-disabled.cjs +3 -6
  71. package/dist/telemetry/telemetry-disabled.cjs.map +1 -1
  72. package/dist/telemetry/telemetry-disabled.d.cts +0 -5
  73. package/dist/telemetry/telemetry-disabled.d.cts.map +1 -1
  74. package/dist/telemetry/telemetry-disabled.d.mts +0 -5
  75. package/dist/telemetry/telemetry-disabled.d.mts.map +1 -1
  76. package/dist/telemetry/telemetry-disabled.mjs +4 -6
  77. package/dist/telemetry/telemetry-disabled.mjs.map +1 -1
  78. package/dist/types/message.d.cts +1 -18
  79. package/dist/types/message.d.cts.map +1 -1
  80. package/dist/types/message.d.mts +1 -18
  81. package/dist/types/message.d.mts.map +1 -1
  82. package/dist/utils/errors.cjs +4 -42
  83. package/dist/utils/errors.cjs.map +1 -1
  84. package/dist/utils/errors.d.cts +16 -34
  85. package/dist/utils/errors.d.cts.map +1 -1
  86. package/dist/utils/errors.d.mts +16 -34
  87. package/dist/utils/errors.d.mts.map +1 -1
  88. package/dist/utils/errors.mjs +5 -41
  89. package/dist/utils/errors.mjs.map +1 -1
  90. package/dist/utils/index.cjs +1 -2
  91. package/dist/utils/index.cjs.map +1 -1
  92. package/dist/utils/index.d.cts +4 -5
  93. package/dist/utils/index.d.cts.map +1 -1
  94. package/dist/utils/index.d.mts +4 -5
  95. package/dist/utils/index.d.mts.map +1 -1
  96. package/dist/utils/index.mjs +4 -5
  97. package/dist/utils/index.mjs.map +1 -1
  98. package/dist/utils/json-schema.cjs +0 -79
  99. package/dist/utils/json-schema.cjs.map +1 -1
  100. package/dist/utils/json-schema.d.cts +1 -4
  101. package/dist/utils/json-schema.d.cts.map +1 -1
  102. package/dist/utils/json-schema.d.mts +1 -4
  103. package/dist/utils/json-schema.d.mts.map +1 -1
  104. package/dist/utils/json-schema.mjs +1 -78
  105. package/dist/utils/json-schema.mjs.map +1 -1
  106. package/dist/utils/process-env.cjs +14 -0
  107. package/dist/utils/process-env.cjs.map +1 -0
  108. package/dist/utils/process-env.d.cts +10 -0
  109. package/dist/utils/process-env.d.cts.map +1 -0
  110. package/dist/utils/process-env.d.mts +10 -0
  111. package/dist/utils/process-env.d.mts.map +1 -0
  112. package/dist/utils/process-env.mjs +13 -0
  113. package/dist/utils/process-env.mjs.map +1 -0
  114. package/dist/utils/random-id.cjs +13 -26
  115. package/dist/utils/random-id.cjs.map +1 -1
  116. package/dist/utils/random-id.d.cts +6 -3
  117. package/dist/utils/random-id.d.cts.map +1 -1
  118. package/dist/utils/random-id.d.mts +6 -3
  119. package/dist/utils/random-id.d.mts.map +1 -1
  120. package/dist/utils/random-id.mjs +14 -25
  121. package/dist/utils/random-id.mjs.map +1 -1
  122. package/package.json +7 -31
  123. package/src/__tests__/a2ui-prompts.test.ts +42 -9
  124. package/src/__tests__/fixtures/prompt-goldens.json +354 -0
  125. package/src/__tests__/prompt-spec.test.ts +191 -0
  126. package/src/__tests__/root-entry-browser-safety.test.ts +5 -7
  127. package/src/__tests__/schema-render.test.ts +245 -0
  128. package/src/__tests__/standard-schema.test.ts +61 -101
  129. package/src/a2ui-prompts.ts +47 -96
  130. package/src/generative-ui/basic-functions.ts +1 -1
  131. package/src/generative-ui/compact-schema.ts +277 -0
  132. package/src/generative-ui/index.ts +3 -0
  133. package/src/generative-ui/prompt-spec.ts +335 -0
  134. package/src/generative-ui/prompt.ts +25 -75
  135. package/src/generative-ui/schema-render.ts +374 -0
  136. package/src/index.ts +3 -16
  137. package/src/standard-schema.ts +24 -27
  138. package/src/telemetry/lambda-client.ts +3 -2
  139. package/src/telemetry/telemetry-disabled.ts +7 -12
  140. package/src/types/message.ts +1 -19
  141. package/src/utils/__tests__/errors.test.ts +44 -0
  142. package/src/utils/__tests__/json-schema.test.ts +3 -479
  143. package/src/utils/__tests__/process-env.test.ts +22 -0
  144. package/src/utils/__tests__/random-id.test.ts +37 -0
  145. package/src/utils/errors.ts +27 -85
  146. package/src/utils/index.ts +1 -2
  147. package/src/utils/json-schema.ts +1 -152
  148. package/src/utils/process-env.ts +14 -0
  149. package/src/utils/random-id.ts +17 -37
  150. package/tsdown.config.ts +2 -19
  151. package/dist/event-transforms/index.cjs +0 -15
  152. package/dist/event-transforms/index.d.cts +0 -4
  153. package/dist/event-transforms/index.d.mts +0 -4
  154. package/dist/event-transforms/index.mjs +0 -5
  155. package/dist/event-transforms/open-generative-ui-middleware.cjs +0 -286
  156. package/dist/event-transforms/open-generative-ui-middleware.cjs.map +0 -1
  157. package/dist/event-transforms/open-generative-ui-middleware.d.cts +0 -60
  158. package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +0 -1
  159. package/dist/event-transforms/open-generative-ui-middleware.d.mts +0 -60
  160. package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +0 -1
  161. package/dist/event-transforms/open-generative-ui-middleware.mjs +0 -283
  162. package/dist/event-transforms/open-generative-ui-middleware.mjs.map +0 -1
  163. package/dist/event-transforms/recorded-events.cjs +0 -59
  164. package/dist/event-transforms/recorded-events.cjs.map +0 -1
  165. package/dist/event-transforms/recorded-events.d.cts +0 -23
  166. package/dist/event-transforms/recorded-events.d.cts.map +0 -1
  167. package/dist/event-transforms/recorded-events.d.mts +0 -23
  168. package/dist/event-transforms/recorded-events.d.mts.map +0 -1
  169. package/dist/event-transforms/recorded-events.mjs +0 -58
  170. package/dist/event-transforms/recorded-events.mjs.map +0 -1
  171. package/dist/telemetry/events.d.cts +0 -72
  172. package/dist/telemetry/events.d.cts.map +0 -1
  173. package/dist/telemetry/events.d.mts +0 -72
  174. package/dist/telemetry/events.d.mts.map +0 -1
  175. package/dist/telemetry/index.cjs +0 -18
  176. package/dist/telemetry/index.d.cts +0 -5
  177. package/dist/telemetry/index.d.mts +0 -5
  178. package/dist/telemetry/index.mjs +0 -6
  179. package/dist/telemetry/telemetry-client.cjs +0 -165
  180. package/dist/telemetry/telemetry-client.cjs.map +0 -1
  181. package/dist/telemetry/telemetry-client.d.cts +0 -87
  182. package/dist/telemetry/telemetry-client.d.cts.map +0 -1
  183. package/dist/telemetry/telemetry-client.d.mts +0 -87
  184. package/dist/telemetry/telemetry-client.d.mts.map +0 -1
  185. package/dist/telemetry/telemetry-client.mjs +0 -164
  186. package/dist/telemetry/telemetry-client.mjs.map +0 -1
  187. package/dist/telemetry/utils.cjs +0 -14
  188. package/dist/telemetry/utils.cjs.map +0 -1
  189. package/dist/telemetry/utils.mjs +0 -13
  190. package/dist/telemetry/utils.mjs.map +0 -1
  191. package/dist/utils/conditions.cjs +0 -32
  192. package/dist/utils/conditions.cjs.map +0 -1
  193. package/dist/utils/conditions.d.cts +0 -31
  194. package/dist/utils/conditions.d.cts.map +0 -1
  195. package/dist/utils/conditions.d.mts +0 -31
  196. package/dist/utils/conditions.d.mts.map +0 -1
  197. package/dist/utils/conditions.mjs +0 -31
  198. package/dist/utils/conditions.mjs.map +0 -1
  199. package/dist/utils/console-styling.cjs +0 -91
  200. package/dist/utils/console-styling.cjs.map +0 -1
  201. package/dist/utils/console-styling.d.cts +0 -65
  202. package/dist/utils/console-styling.d.cts.map +0 -1
  203. package/dist/utils/console-styling.d.mts +0 -65
  204. package/dist/utils/console-styling.d.mts.map +0 -1
  205. package/dist/utils/console-styling.mjs +0 -85
  206. package/dist/utils/console-styling.mjs.map +0 -1
  207. package/src/__tests__/zod-regression.test.ts +0 -319
  208. package/src/event-transforms/index.ts +0 -5
  209. package/src/event-transforms/open-generative-ui-middleware.ts +0 -392
  210. package/src/event-transforms/recorded-events.test.ts +0 -166
  211. package/src/event-transforms/recorded-events.ts +0 -74
  212. package/src/telemetry/events.ts +0 -68
  213. package/src/telemetry/index.ts +0 -9
  214. package/src/telemetry/telemetry-blank-license-identity.test.ts +0 -128
  215. package/src/telemetry/telemetry-client.test.ts +0 -798
  216. package/src/telemetry/telemetry-client.ts +0 -328
  217. package/src/telemetry/utils.ts +0 -15
  218. package/src/utils/__tests__/conditions.test.ts +0 -161
  219. package/src/utils/conditions.ts +0 -116
  220. package/src/utils/console-styling.ts +0 -126
@@ -1,7 +1,17 @@
1
1
  import { isA2UIBasicFunction } from "./generative-ui/basic-functions";
2
2
  import { A2UI_CHILD_LIST_REF } from "./generative-ui/child-refs";
3
- import { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from "./generative-ui/types";
4
3
  import type { GenerativeUIManifest } from "./generative-ui/types";
4
+ import {
5
+ defaultGenerativeUIPromptSpec,
6
+ GUIDE_COMPONENTS,
7
+ generativeUIPromptFeatures,
8
+ selectPromptItems,
9
+ } from "./generative-ui/prompt-spec";
10
+ import type { GenerativeUIPromptSpec } from "./generative-ui/prompt-spec";
11
+ export {
12
+ GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW,
13
+ GENERATIVE_UI_WHEN_TO_SHOW,
14
+ } from "./generative-ui/prompt-spec";
5
15
  /**
6
16
  * Default A2UI generation and design guideline prompts.
7
17
  *
@@ -118,14 +128,6 @@ Design principles:
118
128
 
119
129
  Use the SAME surfaceId as the main surface. Match action names to button action event names.`;
120
130
 
121
- /**
122
- * When UI helps the user, for both transports: a light nudge to reach for UI
123
- * where it conveys the answer better than prose, and to stay in prose
124
- * otherwise.
125
- */
126
- export const GENERATIVE_UI_WHEN_TO_SHOW =
127
- "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.";
128
-
129
131
  /** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */
130
132
  export const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION =
131
133
  "Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.";
@@ -154,6 +156,11 @@ export interface GenerativeUIGuideFeatures {
154
156
  templates: boolean;
155
157
  /** A component has a "checks" prop: validation rules on inputs. */
156
158
  checks: boolean;
159
+ /**
160
+ * The component names of the catalog. A guide line that names a standard
161
+ * component missing from it is left out. Unset keeps every line.
162
+ */
163
+ components?: readonly string[];
157
164
  }
158
165
 
159
166
  /** Every optional rule group. Use it when the manifest is not known. */
@@ -190,6 +197,7 @@ export function generativeUIGuideFeatures(
190
197
  return Object.values(node).some(hasChildList);
191
198
  };
192
199
  return {
200
+ components: Object.keys(manifest.components),
193
201
  // App functions only: the built-in ones are always there and have
194
202
  // their own rules.
195
203
  functions: Object.keys(manifest.functions).some(
@@ -212,44 +220,22 @@ export function generativeUIGuideFeatures(
212
220
  };
213
221
  }
214
222
 
215
- /** The first rules of every markdown guideline, before the optional groups. */
216
- const MARKDOWN_BASE_RULES = [
217
- "Write explanations as normal markdown prose outside the fences.",
218
- "Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
219
- '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.',
220
- "Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
221
- "Keep each operation whole on its line.",
222
- 'Give every operation "version":"v1.0".',
223
- `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:
224
- \`\`\`a2ui
225
- {"version":"v1.0","createSurface":{"surfaceId":"plan-picker","dataModel":{ ...initial data... },"components":[{"id":"root","component":"<Name>","children":["seats","pick"]}]}}
226
- {"version":"v1.0","updateComponents":{"surfaceId":"plan-picker","components":[ ...the children... ]}}
227
- \`\`\``,
228
- '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.',
229
- 'Every surface renders from the component with id "root". Make every other component reachable from "root" through slots.',
230
- "Use unique ids. Do not make cycles. A component cannot be its own child.",
231
- 'Write a component as one flat object: {"id":"title","component":"<Name>","text":"Hello"}.',
232
- 'Put the component name in "component" (never "type"). Put props next to it, never inside a "props" object.',
233
- '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.',
234
- 'Use only the components, props, events, and slots in the schema. A component with "includesCommonProps" also takes every prop in "commonProps".',
235
- 'Give a prop a literal value, or bind it to the data model with {"@path":"/x"}. Never write {"path":"/x"} as a binding.',
236
- '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.',
237
- '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.',
238
- '${...} 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.',
239
- '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.',
240
- 'Bind a writable prop to let the user edit it: "value":{"@path":"/form/email"}. The user\'s input goes to that path.',
241
- '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".',
242
- 'Set "value":null to delete the key at "path".',
243
- ];
244
-
245
- /** The last rules of every markdown guideline, after the optional groups. */
246
- const MARKDOWN_CLOSING_RULES = [
247
- '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.',
248
- "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.",
249
- "Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
250
- "Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
251
- "Never wrap the whole reply in a fence.",
252
- ];
223
+ /**
224
+ * Whether a guide line names only standard components (`GUIDE_COMPONENTS`,
225
+ * also in the plural) that the catalog has. With no catalog, every line fits.
226
+ */
227
+ function namesOnlyCatalogComponents(catalog: readonly string[] | undefined) {
228
+ if (!catalog) return () => true;
229
+ const has = new Set(catalog);
230
+ return (line: string) =>
231
+ (line.match(/\b[A-Z][A-Za-z0-9]*\b/g) ?? []).every((word) => {
232
+ const name =
233
+ !GUIDE_COMPONENTS.has(word) && word.endsWith("s")
234
+ ? word.slice(0, -1)
235
+ : word;
236
+ return !GUIDE_COMPONENTS.has(name) || has.has(name);
237
+ });
238
+ }
253
239
 
254
240
  /**
255
241
  * Builds the markdown-transport guideline. The model writes A2UI v1.0
@@ -258,60 +244,25 @@ const MARKDOWN_CLOSING_RULES = [
258
244
  * none of them, so the guideline stays small.
259
245
  *
260
246
  * @param features - The optional rule groups to include. Defaults to all.
247
+ * @param spec - The wording. Defaults to the prompts that ship.
261
248
  * @returns The guideline text, one rule per line.
262
249
  */
263
250
  export function buildGenerativeUIMarkdownGuidelines(
264
251
  features: GenerativeUIGuideFeatures = ALL_GENERATIVE_UI_GUIDE_FEATURES,
252
+ spec: GenerativeUIPromptSpec = defaultGenerativeUIPromptSpec(),
265
253
  ) {
266
- const { functions, events, templates, checks } = features;
267
- const rules = [...MARKDOWN_BASE_RULES];
268
- if (events) {
269
- rules.push(
270
- 'Give an event prop an object: {"event":{"name":"<name>","userMessage":"<text>","context":{...}}} or {"functionCall":{"@call":"<function>","args":{...}}}. Never a flat {"event":"<name>"}.',
271
- functions
272
- ? '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.'
273
- : '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.',
274
- '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".',
275
- 'To send input values with an event, bind them in the context: "context":{"email":{"@path":"/form/email"}}.',
276
- "A button or other event prop without an event or functionCall does nothing.",
277
- );
278
- }
279
- if (checks) {
280
- rules.push(
281
- '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.',
282
- );
283
- }
284
- rules.push(
285
- '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"}].',
286
- );
287
- if (templates) {
288
- rules.push(
289
- 'To repeat a component for each item of a list, give a childList a template: "children":{"componentId":"row","path":"/items"}.',
290
- 'Inside a template, paths are relative to the item ("name", not "/name").',
291
- 'Inside a template, {"@call":"@index"} gives the position of the item, from 0. To count from 1, write {"@call":"@index","args":{"offset":1}}.',
292
- );
293
- }
294
- rules.push(
295
- "Updating a component replaces all of its props. Send every prop again.",
296
- "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.",
297
- "Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.",
298
- );
299
- if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) {
300
- rules.push(
301
- '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.',
302
- '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.',
303
- '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.',
304
- "Do not guess the result of a callRendererFunction. Wait for the developer message.",
305
- );
306
- }
307
- rules.push(...MARKDOWN_CLOSING_RULES);
308
- return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.
309
-
310
- ${GENERATIVE_UI_WHEN_TO_SHOW}
311
-
312
- RULES
313
- ${rules.map((rule) => `- ${rule}`).join("\n")}
314
- `;
254
+ const { intro, rules } = spec.markdown;
255
+ const fits = namesOnlyCatalogComponents(features.components);
256
+ const selected = selectPromptItems(
257
+ rules,
258
+ generativeUIPromptFeatures(features),
259
+ ).filter(fits);
260
+ const whenToShow = spec.markdown.whenToShow
261
+ .split("\n")
262
+ .filter(fits)
263
+ .join("\n");
264
+ const when = whenToShow ? `${whenToShow}\n\n` : "";
265
+ return `${intro}\n\n${when}RULES\n${selected.map((rule) => `- ${rule}`).join("\n")}\n`;
315
266
  }
316
267
 
317
268
  /**
@@ -189,7 +189,7 @@ export const COPILOTKIT_FUNCTIONS: Readonly<
189
189
  > = rendererOnly({
190
190
  calc: {
191
191
  description:
192
- "The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name",
192
+ "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",
193
193
  parameters:
194
194
  "{ expression: string; [name: string]: number | string | boolean }",
195
195
  returnType: "any",
@@ -0,0 +1,277 @@
1
+ import { childRefKind } from "./child-refs";
2
+ import { functionCallers } from "./basic-functions";
3
+ import { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from "./types";
4
+ import type { GenerativeUIJSONSchema, GenerativeUIManifest } from "./types";
5
+
6
+ /** Objects nested deeper than this show as `object`. */
7
+ const MAX_OBJECT_DEPTH = 2;
8
+
9
+ /** A prop must appear verbatim in at least this many components to be hoisted. */
10
+ const COMMON_PROP_MIN_COMPONENTS = 8;
11
+
12
+ function isRecord(value: unknown): value is Record<string, unknown> {
13
+ return typeof value === "object" && value !== null && !Array.isArray(value);
14
+ }
15
+
16
+ /** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
17
+ function schemaList(value: unknown) {
18
+ return Array.isArray(value) ? value.filter(isRecord) : [];
19
+ }
20
+
21
+ /**
22
+ * Puts a top-level union in parentheses, so that `[]` applies to all of
23
+ * it. A union inside braces needs none.
24
+ */
25
+ function asArrayItem(type: string) {
26
+ let outside = type;
27
+ for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside; ) {
28
+ outside = inner;
29
+ inner = outside.replace(/\{[^{}]*\}/g, "");
30
+ }
31
+ return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
32
+ }
33
+
34
+ /**
35
+ * A JSON Schema as a short TypeScript-like type, for example
36
+ * `{ label: string; size?: "sm" | "md" }`.
37
+ */
38
+ export function compactType(
39
+ schema: GenerativeUIJSONSchema,
40
+ depth: number,
41
+ ): string {
42
+ const ref = childRefKind(schema);
43
+ if (ref === "single") return "componentId";
44
+ if (ref === "multiple")
45
+ return "componentId[] | { componentId: string; path: string }";
46
+ if ("const" in schema) return JSON.stringify(schema.const);
47
+ if (Array.isArray(schema.enum)) {
48
+ return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
49
+ }
50
+ const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
51
+ if (variants.length > 0) {
52
+ return variants.map((variant) => compactType(variant, depth)).join(" | ");
53
+ }
54
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
55
+ const summaries = types.map((type) => {
56
+ switch (type) {
57
+ case "string":
58
+ case "boolean":
59
+ case "null":
60
+ return type;
61
+ case "number":
62
+ case "integer":
63
+ return "number";
64
+ case "array":
65
+ return isRecord(schema.items)
66
+ ? asArrayItem(compactType(schema.items, depth))
67
+ : "unknown[]";
68
+ case "object":
69
+ return compactObject(schema, depth);
70
+ default:
71
+ return "unknown";
72
+ }
73
+ });
74
+ return summaries.join(" | ");
75
+ }
76
+
77
+ /** An object schema as `{ key: type; other?: type }`. */
78
+ function compactObject(schema: GenerativeUIJSONSchema, depth: number) {
79
+ const properties = isRecord(schema.properties) ? schema.properties : {};
80
+ const entries = Object.entries(properties);
81
+ if (entries.length === 0) {
82
+ return isRecord(schema.additionalProperties)
83
+ ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>`
84
+ : "object";
85
+ }
86
+ if (depth >= MAX_OBJECT_DEPTH) return "object";
87
+ const required = Array.isArray(schema.required) ? schema.required : [];
88
+ const fields = entries.map(([key, value]) => {
89
+ const type = isRecord(value) ? compactType(value, depth + 1) : "unknown";
90
+ return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
91
+ });
92
+ return `{ ${fields.join("; ")} }`;
93
+ }
94
+
95
+ /** A schema as its type, with its description after `//`. */
96
+ function describedType(schema: GenerativeUIJSONSchema, depth: number) {
97
+ const type = compactType(schema, depth);
98
+ return typeof schema.description === "string"
99
+ ? `${type} // ${schema.description}`
100
+ : type;
101
+ }
102
+
103
+ /**
104
+ * The props of a component: `{ "label": "string", "size?": "..." }`. With
105
+ * `descriptions`, each type carries its description after `//`.
106
+ */
107
+ export function compactProps(
108
+ schema: GenerativeUIJSONSchema,
109
+ descriptions = true,
110
+ ) {
111
+ const properties = isRecord(schema.properties) ? schema.properties : {};
112
+ const required = Array.isArray(schema.required) ? schema.required : [];
113
+ const props: Record<string, string> = {};
114
+ for (const [key, value] of Object.entries(properties)) {
115
+ if (!isRecord(value)) continue;
116
+ const name = required.includes(key) ? key : `${key}?`;
117
+ props[name] = descriptions
118
+ ? describedType(value, 1)
119
+ : compactType(value, 1);
120
+ }
121
+ return props;
122
+ }
123
+
124
+ /**
125
+ * The prop set worth listing once. Candidates are (key, type) pairs that at
126
+ * least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
127
+ * candidate subset of each component is a possible common set, scored by
128
+ * the characters it saves (set size times the components that contain all
129
+ * of it). `undefined` when no set is shared by enough components.
130
+ */
131
+ function findCommonProps(propsList: Array<Record<string, string>>) {
132
+ const pairKey = (key: string, type: string) => `${key}\u0000${type}`;
133
+ const counts = new Map<string, number>();
134
+ for (const props of propsList) {
135
+ for (const [key, type] of Object.entries(props)) {
136
+ const id = pairKey(key, type);
137
+ counts.set(id, (counts.get(id) ?? 0) + 1);
138
+ }
139
+ }
140
+ let best: Record<string, string> | undefined;
141
+ let bestScore = 0;
142
+ const seen = new Set<string>();
143
+ for (const props of propsList) {
144
+ const subset = Object.entries(props).filter(
145
+ ([key, type]) =>
146
+ (counts.get(pairKey(key, type)) ?? 0) >= COMMON_PROP_MIN_COMPONENTS,
147
+ );
148
+ if (subset.length < 2) continue;
149
+ const signature = subset
150
+ .map(([key, type]) => pairKey(key, type))
151
+ .join("\n");
152
+ if (seen.has(signature)) continue;
153
+ seen.add(signature);
154
+ const members = propsList.filter((other) =>
155
+ subset.every(([key, type]) => other[key] === type),
156
+ ).length;
157
+ if (members < COMMON_PROP_MIN_COMPONENTS) continue;
158
+ const size = subset.reduce(
159
+ (total, [key, type]) => total + key.length + type.length,
160
+ 0,
161
+ );
162
+ const score = size * (members - 1);
163
+ if (score > bestScore) {
164
+ bestScore = score;
165
+ best = Object.fromEntries(subset);
166
+ }
167
+ }
168
+ return best;
169
+ }
170
+
171
+ /** One component of the compact schema. */
172
+ interface CompactComponent {
173
+ description?: string;
174
+ /** True when the component also takes every prop in `commonProps`. */
175
+ includesCommonProps?: true;
176
+ props: Record<string, string>;
177
+ events?: Record<string, string>;
178
+ slots?: Record<string, "single" | "multiple">;
179
+ }
180
+
181
+ /**
182
+ * The component schema of the markdown transport, from the per-run
183
+ * manifest. It is smaller than the manifest: each prop is one short type,
184
+ * and the props that many components share verbatim (the layout props of
185
+ * the containers) are listed once in `commonProps`; a component that takes
186
+ * them is flagged `includesCommonProps`.
187
+ * It has the catalog id, the targets with their descriptions and their
188
+ * component lists, the functions with their parameters, the components
189
+ * with their props, events and slots, and the surfaces of the thread. A surface lists the
190
+ * values that the user set and the operations that the client dropped.
191
+ *
192
+ * @param manifest - The manifest from `buildGenerativeUIManifest`.
193
+ * @param options - `propDescriptions` (default true) writes each prop's
194
+ * description; `commonProps` (default true) lists shared props once.
195
+ * @returns A JSON-ready object.
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * const value = JSON.stringify(
200
+ * buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
201
+ * );
202
+ * ```
203
+ */
204
+ export function buildCompactGenerativeUISchema(
205
+ manifest: Pick<
206
+ GenerativeUIManifest,
207
+ "catalogId" | "components" | "functions" | "targets" | "surfaces"
208
+ >,
209
+ options: { propDescriptions?: boolean; commonProps?: boolean } = {},
210
+ ) {
211
+ const { propDescriptions = true, commonProps = true } = options;
212
+ const components: Record<string, CompactComponent> = {};
213
+ for (const [name, component] of Object.entries(manifest.components)) {
214
+ const events = Object.entries(component.events ?? {}).map(
215
+ ([event, definition]) => [
216
+ event,
217
+ definition.description ?? compactType(definition.parameters, 0),
218
+ ],
219
+ );
220
+ components[name] = {
221
+ ...(component.description ? { description: component.description } : {}),
222
+ props: compactProps(component.props, propDescriptions),
223
+ ...(events.length > 0 ? { events: Object.fromEntries(events) } : {}),
224
+ ...(component.slots ? { slots: component.slots } : {}),
225
+ };
226
+ }
227
+ const common = commonProps
228
+ ? findCommonProps(
229
+ Object.values(components).map((component) => component.props),
230
+ )
231
+ : undefined;
232
+ if (common) {
233
+ const commonKeys = Object.keys(common);
234
+ for (const component of Object.values(components)) {
235
+ const includesCommon = commonKeys.every(
236
+ (key) => component.props[key] === common[key],
237
+ );
238
+ if (!includesCommon) continue;
239
+ component.includesCommonProps = true;
240
+ component.props = Object.fromEntries(
241
+ Object.entries(component.props).filter(([key]) => !(key in common)),
242
+ );
243
+ }
244
+ }
245
+ // A built-in function carries its short signature in the description of
246
+ // its parameters (see `builtInFunctionManifests`); an app function gets
247
+ // its JSON Schema made short. A function is for the UI unless it says
248
+ // that the agent may call it too, or only the agent.
249
+ const functions = Object.fromEntries(
250
+ Object.entries(manifest.functions).map(([name, fn]) => {
251
+ const signature = fn.parameters.description;
252
+ const hasSignature =
253
+ typeof signature === "string" &&
254
+ signature.startsWith("{") &&
255
+ Object.keys(fn.parameters).length === 2;
256
+ const callers = functionCallers(fn);
257
+ return [
258
+ name,
259
+ {
260
+ ...(fn.description ? { description: fn.description } : {}),
261
+ parameters: hasSignature ? signature : compactType(fn.parameters, 0),
262
+ ...(callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS
263
+ ? { callers: callers.renderer ? "UI or agent" : "agent only" }
264
+ : {}),
265
+ },
266
+ ];
267
+ }),
268
+ );
269
+ return {
270
+ catalogId: manifest.catalogId,
271
+ targets: manifest.targets,
272
+ functions,
273
+ ...(common ? { commonProps: common } : {}),
274
+ components,
275
+ surfaces: manifest.surfaces,
276
+ };
277
+ }
@@ -4,3 +4,6 @@ export * from "./render-ui-args";
4
4
  export * from "./basic-functions";
5
5
  export * from "./child-refs";
6
6
  export * from "./prompt";
7
+ export { buildCompactGenerativeUISchema } from "./compact-schema";
8
+ export * from "./prompt-spec";
9
+ export * from "./schema-render";