@copilotkit/shared 1.83.0 → 1.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/a2ui-envelope.cjs +2 -2
  2. package/dist/a2ui-envelope.cjs.map +1 -1
  3. package/dist/a2ui-envelope.d.cts +1 -1
  4. package/dist/a2ui-envelope.d.cts.map +1 -1
  5. package/dist/a2ui-envelope.d.mts +1 -1
  6. package/dist/a2ui-envelope.d.mts.map +1 -1
  7. package/dist/a2ui-envelope.mjs +2 -2
  8. package/dist/a2ui-envelope.mjs.map +1 -1
  9. package/dist/a2ui-prompts.cjs +21 -62
  10. package/dist/a2ui-prompts.cjs.map +1 -1
  11. package/dist/a2ui-prompts.d.cts +8 -1
  12. package/dist/a2ui-prompts.d.cts.map +1 -1
  13. package/dist/a2ui-prompts.d.mts +8 -1
  14. package/dist/a2ui-prompts.d.mts.map +1 -1
  15. package/dist/a2ui-prompts.mjs +22 -62
  16. package/dist/a2ui-prompts.mjs.map +1 -1
  17. package/dist/generative-ui/basic-functions.cjs +1 -1
  18. package/dist/generative-ui/basic-functions.cjs.map +1 -1
  19. package/dist/generative-ui/basic-functions.mjs +1 -1
  20. package/dist/generative-ui/basic-functions.mjs.map +1 -1
  21. package/dist/generative-ui/compact-schema.cjs +187 -0
  22. package/dist/generative-ui/compact-schema.cjs.map +1 -0
  23. package/dist/generative-ui/compact-schema.d.cts +55 -0
  24. package/dist/generative-ui/compact-schema.d.cts.map +1 -0
  25. package/dist/generative-ui/compact-schema.d.mts +55 -0
  26. package/dist/generative-ui/compact-schema.d.mts.map +1 -0
  27. package/dist/generative-ui/compact-schema.mjs +185 -0
  28. package/dist/generative-ui/compact-schema.mjs.map +1 -0
  29. package/dist/generative-ui/prompt-spec.cjs +225 -0
  30. package/dist/generative-ui/prompt-spec.cjs.map +1 -0
  31. package/dist/generative-ui/prompt-spec.d.cts +94 -0
  32. package/dist/generative-ui/prompt-spec.d.cts.map +1 -0
  33. package/dist/generative-ui/prompt-spec.d.mts +94 -0
  34. package/dist/generative-ui/prompt-spec.d.mts.map +1 -0
  35. package/dist/generative-ui/prompt-spec.mjs +220 -0
  36. package/dist/generative-ui/prompt-spec.mjs.map +1 -0
  37. package/dist/generative-ui/prompt.cjs +10 -36
  38. package/dist/generative-ui/prompt.cjs.map +1 -1
  39. package/dist/generative-ui/prompt.d.cts +2 -1
  40. package/dist/generative-ui/prompt.d.cts.map +1 -1
  41. package/dist/generative-ui/prompt.d.mts +2 -1
  42. package/dist/generative-ui/prompt.d.mts.map +1 -1
  43. package/dist/generative-ui/prompt.mjs +12 -38
  44. package/dist/generative-ui/prompt.mjs.map +1 -1
  45. package/dist/generative-ui/schema-render.cjs +242 -0
  46. package/dist/generative-ui/schema-render.cjs.map +1 -0
  47. package/dist/generative-ui/schema-render.d.cts +44 -0
  48. package/dist/generative-ui/schema-render.d.cts.map +1 -0
  49. package/dist/generative-ui/schema-render.d.mts +44 -0
  50. package/dist/generative-ui/schema-render.d.mts.map +1 -0
  51. package/dist/generative-ui/schema-render.mjs +239 -0
  52. package/dist/generative-ui/schema-render.mjs.map +1 -0
  53. package/dist/generative-ui/types.cjs +2 -2
  54. package/dist/generative-ui/types.cjs.map +1 -1
  55. package/dist/generative-ui/types.d.cts +7 -7
  56. package/dist/generative-ui/types.d.cts.map +1 -1
  57. package/dist/generative-ui/types.d.mts +7 -7
  58. package/dist/generative-ui/types.d.mts.map +1 -1
  59. package/dist/generative-ui/types.mjs +2 -2
  60. package/dist/generative-ui/types.mjs.map +1 -1
  61. package/dist/index.cjs +14 -0
  62. package/dist/index.cjs.map +1 -1
  63. package/dist/index.d.cts +4 -1
  64. package/dist/index.d.cts.map +1 -1
  65. package/dist/index.d.mts +4 -1
  66. package/dist/index.d.mts.map +1 -1
  67. package/dist/index.mjs +4 -1
  68. package/dist/index.mjs.map +1 -1
  69. package/dist/index.umd.js +756 -165
  70. package/dist/index.umd.js.map +1 -1
  71. package/dist/package.cjs +1 -1
  72. package/dist/package.mjs +1 -1
  73. package/package.json +1 -1
  74. package/src/__tests__/a2ui-envelope.test.ts +18 -13
  75. package/src/__tests__/a2ui-prompts.test.ts +47 -14
  76. package/src/__tests__/fixtures/prompt-goldens.json +354 -0
  77. package/src/__tests__/prompt-spec.test.ts +191 -0
  78. package/src/__tests__/schema-render.test.ts +245 -0
  79. package/src/a2ui-envelope.ts +5 -5
  80. package/src/a2ui-prompts.ts +47 -96
  81. package/src/generative-ui/__tests__/render-ui-args.test.ts +7 -7
  82. package/src/generative-ui/__tests__/validate-operation.test.ts +19 -13
  83. package/src/generative-ui/basic-functions.ts +1 -1
  84. package/src/generative-ui/compact-schema.ts +277 -0
  85. package/src/generative-ui/index.ts +3 -0
  86. package/src/generative-ui/prompt-spec.ts +335 -0
  87. package/src/generative-ui/prompt.ts +25 -75
  88. package/src/generative-ui/schema-render.ts +374 -0
  89. package/src/generative-ui/types.ts +10 -7
  90. package/src/utils/__tests__/conditions.test.ts +153 -43
@@ -1,6 +1,6 @@
1
1
  import { isA2UIBasicFunction } from "./generative-ui/basic-functions.mjs";
2
2
  import { A2UI_CHILD_LIST_REF } from "./generative-ui/child-refs.mjs";
3
- import { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from "./generative-ui/types.mjs";
3
+ import { GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW, GENERATIVE_UI_WHEN_TO_SHOW, GUIDE_COMPONENTS, defaultGenerativeUIPromptSpec, generativeUIPromptFeatures, selectPromptItems } from "./generative-ui/prompt-spec.mjs";
4
4
 
5
5
  //#region src/a2ui-prompts.ts
6
6
  /**
@@ -116,12 +116,6 @@ Design principles:
116
116
  action context should reference the same paths to capture user input.
117
117
 
118
118
  Use the SAME surfaceId as the main surface. Match action names to button action event names.`;
119
- /**
120
- * When UI helps the user, for both transports: a light nudge to reach for UI
121
- * where it conveys the answer better than prose, and to stay in prose
122
- * otherwise.
123
- */
124
- const GENERATIVE_UI_WHEN_TO_SHOW = "Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.";
125
119
  /** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */
126
120
  const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = "Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.";
127
121
  /**
@@ -167,6 +161,7 @@ function generativeUIGuideFeatures(manifest) {
167
161
  return Object.values(node).some(hasChildList);
168
162
  };
169
163
  return {
164
+ components: Object.keys(manifest.components),
170
165
  functions: Object.keys(manifest.functions).some((name) => !isA2UIBasicFunction(name)),
171
166
  events: components.some((c) => Object.keys(c.events ?? {}).length > 0),
172
167
  templates: components.some((c) => Object.values(c.slots ?? {}).includes("multiple") || hasChildList(c.props)),
@@ -176,43 +171,18 @@ function generativeUIGuideFeatures(manifest) {
176
171
  })
177
172
  };
178
173
  }
179
- /** The first rules of every markdown guideline, before the optional groups. */
180
- const MARKDOWN_BASE_RULES = [
181
- "Write explanations as normal markdown prose outside the fences.",
182
- "Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
183
- "Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target has \"components\", its surfaces can use only those components.",
184
- "Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
185
- "Keep each operation whole on its line.",
186
- "Give every operation \"version\":\"v1.0\".",
187
- `Start a surface with one createSurface. Put all the initial data in "dataModel" and the "root" component in "components". Then write the children in updateComponents lines, so that they show while you write:
188
- \`\`\`a2ui
189
- {"version":"v1.0","createSurface":{"surfaceId":"plan-picker","dataModel":{ ...initial data... },"components":[{"id":"root","component":"<Name>","children":["seats","pick"]}]}}
190
- {"version":"v1.0","updateComponents":{"surfaceId":"plan-picker","components":[ ...the children... ]}}
191
- \`\`\``,
192
- "Keep \"dataModel\" flat: top-level keys such as \"seats\" or \"form\", never one wrapper object around everything. Check that every { and [ you open in a line is closed.",
193
- "Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.",
194
- "Use unique ids. Do not make cycles. A component cannot be its own child.",
195
- "Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
196
- "Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
197
- "A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
198
- "Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".",
199
- "Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
200
- "A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions under \"functions\" in the schema. Write a literal when the value never changes.",
201
- "formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: 'EUR')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.",
202
- "${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: 'seats * 29', seats: /seats), currency: 'USD')}. The UI then follows the user's input with no round trip.",
203
- "For a computed list (chart data, template items) use series. Its description under \"functions\" in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.",
204
- "Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
205
- "To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".",
206
- "Set \"value\":null to delete the key at \"path\"."
207
- ];
208
- /** The last rules of every markdown guideline, after the optional groups. */
209
- const MARKDOWN_CLOSING_RULES = [
210
- "The schema lists the surfaces that already exist under \"surfaces\". \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.",
211
- "Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.",
212
- "Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
213
- "Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
214
- "Never wrap the whole reply in a fence."
215
- ];
174
+ /**
175
+ * Whether a guide line names only standard components (`GUIDE_COMPONENTS`,
176
+ * also in the plural) that the catalog has. With no catalog, every line fits.
177
+ */
178
+ function namesOnlyCatalogComponents(catalog) {
179
+ if (!catalog) return () => true;
180
+ const has = new Set(catalog);
181
+ return (line) => (line.match(/\b[A-Z][A-Za-z0-9]*\b/g) ?? []).every((word) => {
182
+ const name = !GUIDE_COMPONENTS.has(word) && word.endsWith("s") ? word.slice(0, -1) : word;
183
+ return !GUIDE_COMPONENTS.has(name) || has.has(name);
184
+ });
185
+ }
216
186
  /**
217
187
  * Builds the markdown-transport guideline. The model writes A2UI v1.0
218
188
  * operations inside ```a2ui fences between normal markdown prose. The rules
@@ -220,25 +190,15 @@ const MARKDOWN_CLOSING_RULES = [
220
190
  * none of them, so the guideline stays small.
221
191
  *
222
192
  * @param features - The optional rule groups to include. Defaults to all.
193
+ * @param spec - The wording. Defaults to the prompts that ship.
223
194
  * @returns The guideline text, one rule per line.
224
195
  */
225
- function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES) {
226
- const { functions, events, templates, checks } = features;
227
- const rules = [...MARKDOWN_BASE_RULES];
228
- if (events) rules.push("Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.", functions ? "Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call." : "Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.", "Use {\"event\": ...} to send the interaction back to you as a user message. Put the text of that message in \"userMessage\": {\"event\":{\"name\":\"choose\",\"userMessage\":\"Show me the Team plan\"}}. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".", "To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.", "A button or other event prop without an event or functionCall does nothing.");
229
- if (checks) rules.push("Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks.");
230
- rules.push("A prop typed componentId takes the id of another component, and a childList takes ids [\"a\",\"b\"]: \"child\":\"card\", \"children\":[\"a\",\"b\"], \"tabs\":[{\"title\":\"Specs\",\"child\":\"specs\"}].");
231
- if (templates) rules.push("To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.", "Inside a template, paths are relative to the item (\"name\", not \"/name\").", "Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.");
232
- rules.push("Updating a component replaces all of its props. Send every prop again.", "To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.", "Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.");
233
- if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) rules.push("To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.", "Give every callRendererFunction a new functionCallId. Call only a function from the schema with \"callers\": \"UI or agent\" or \"agent only\"; a function without \"callers\" is for the UI only. A function with \"callers\": \"agent only\" is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.", "Do not guess the result of a callRendererFunction. Wait for the developer message.");
234
- rules.push(...MARKDOWN_CLOSING_RULES);
235
- return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.
236
-
237
- ${GENERATIVE_UI_WHEN_TO_SHOW}
238
-
239
- RULES
240
- ${rules.map((rule) => `- ${rule}`).join("\n")}
241
- `;
196
+ function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES, spec = defaultGenerativeUIPromptSpec()) {
197
+ const { intro, rules } = spec.markdown;
198
+ const fits = namesOnlyCatalogComponents(features.components);
199
+ const selected = selectPromptItems(rules, generativeUIPromptFeatures(features)).filter(fits);
200
+ const whenToShow = spec.markdown.whenToShow.split("\n").filter(fits).join("\n");
201
+ return `${intro}\n\n${whenToShow ? `${whenToShow}\n\n` : ""}RULES\n${selected.map((rule) => `- ${rule}`).join("\n")}\n`;
242
202
  }
243
203
  /**
244
204
  * The markdown-transport guideline with every rule group. A run sends
@@ -247,5 +207,5 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
247
207
  const GENERATIVE_UI_MARKDOWN_GUIDELINES = buildGenerativeUIMarkdownGuidelines();
248
208
 
249
209
  //#endregion
250
- export { A2UI_DEFAULT_DESIGN_GUIDELINES, A2UI_DEFAULT_GENERATION_GUIDELINES, ALL_GENERATIVE_UI_GUIDE_FEATURES, GENERATIVE_UI_MARKDOWN_GUIDELINES, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, GENERATIVE_UI_WHEN_TO_SHOW, buildGenerativeUIMarkdownGuidelines, generativeUIGuideFeatures };
210
+ export { A2UI_DEFAULT_DESIGN_GUIDELINES, A2UI_DEFAULT_GENERATION_GUIDELINES, ALL_GENERATIVE_UI_GUIDE_FEATURES, GENERATIVE_UI_MARKDOWN_GUIDELINES, GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION, GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION, buildGenerativeUIMarkdownGuidelines, generativeUIGuideFeatures };
251
211
  //# sourceMappingURL=a2ui-prompts.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"a2ui-prompts.mjs","names":[],"sources":["../src/a2ui-prompts.ts"],"sourcesContent":["import { isA2UIBasicFunction } from \"./generative-ui/basic-functions\";\nimport { A2UI_CHILD_LIST_REF } from \"./generative-ui/child-refs\";\nimport { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from \"./generative-ui/types\";\nimport type { GenerativeUIManifest } from \"./generative-ui/types\";\n/**\n * Default A2UI generation and design guideline prompts.\n *\n * These are the canonical prompt fragments that instruct an LLM how to call\n * the render_a2ui tool, how to bind data, and how to style surfaces.\n */\n\n/**\n * Generation guidelines — protocol rules, tool arguments, path rules,\n * data model format, and form/two-way-binding instructions.\n */\nexport const A2UI_DEFAULT_GENERATION_GUIDELINES = `\\\nGenerate A2UI v0.9 JSON.\n\n## A2UI Protocol Instructions\n\nA2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.\n\nCRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:\n- surfaceId: A unique ID for the surface (e.g. \"product-comparison\")\n- components: REQUIRED — the A2UI component array. NEVER omit this. Only use\n components listed in the Available Components schema provided as context.\n- data: OPTIONAL — a JSON object written to the root of the surface data model.\n Use for pre-filling form values or providing data for path-bound components.\n- every component must have the \"component\" field specifying the component type.\n ONLY use component names from the Available Components schema — do NOT invent\n component names or use names not in the schema.\n\nCOMPONENT ID RULES:\n- Exactly one component MUST have id=\"root\". This is the surface's entry\n point — the renderer begins at \"root\" and walks the child/children tree\n from there. Every other component must be reachable from \"root\". If no\n component has id=\"root\", the surface renders an empty loading placeholder\n and none of your components will be shown.\n- Every component ID must be unique within the surface.\n- A component MUST NOT reference itself as child/children. This causes a\n circular dependency error. For example, if a component has id=\"avatar\",\n its child must be a DIFFERENT id (e.g. \"avatar-img\"), never \"avatar\".\n- The child/children tree must be a DAG — no cycles allowed.\n\nREPEATING CONTENT (TEMPLATES):\nTo repeat a component for each item in an array, use the structural children format:\n children: { componentId: \"card-id\", path: \"/items\" }\nThis tells the renderer to create one instance of \"card-id\" per item in the \"/items\" array.\n\nPATH RULES FOR TEMPLATES:\nComponents inside a repeating template use RELATIVE paths (no leading slash).\nThe path is resolved relative to each array item automatically.\nIf a container has children: { componentId: \"card\", path: \"/items\" } and each item\nhas a key \"name\", use { \"path\": \"name\" } (NO leading slash — relative to item).\nCRITICAL: Do NOT use \"/name\" (absolute) inside templates — use \"name\" (relative).\nThe container's path (\"/items\") uses a leading slash (absolute), but all\ncomponents INSIDE the template use paths WITHOUT leading slash.\n\nCOMPONENT VALUES — DEFAULT RULE:\nUse inline literal values for ALL component properties. Pass strings, numbers,\narrays, and objects directly on the component. Do NOT use { \"path\": \"...\" }\nobjects unless the property's schema explicitly allows it (see exception below).\nCRITICAL: USING { \"path\": \"...\" } ON A PROPERTY THAT DOES NOT DECLARE PATH\nSUPPORT IN ITS SCHEMA WILL CAUSE A RUNTIME CRASH AND BREAK THE ENTIRE UI.\nALWAYS CHECK THE COMPONENT SCHEMA FIRST — IF THE PROPERTY ONLY ACCEPTS A\nPLAIN TYPE, YOU MUST USE A LITERAL VALUE.\nVERY IMPORTANT: THE APPLICATION WILL BREAK IF YOU DO NOT FOLLOW THIS RULE!\n\nFor example, a chart's \"data\" must always be an inline array:\n \"data\": [{\"label\": \"Jan\", \"value\": 100}, {\"label\": \"Feb\", \"value\": 200}]\nA metric's \"value\" must always be an inline string:\n \"value\": \"$1,200\"\n\nPATH BINDING EXCEPTION — SCHEMA-DRIVEN:\nA few properties accept { \"path\": \"/some/path\" } as an alternative to a literal\nvalue. You can identify these in the Available Components schema: the property\nwill list BOTH a literal type AND an object-with-path option. If a property only\nshows a single type (string, number, array, etc.), it does NOT support path\nbinding — use a literal value only.\n\nPath binding is typically used for editable form inputs so the client can write\nuser input back to the data model. When building forms:\n- Bind input \"value\" to a data model path: \"value\": { \"path\": \"/form/name\" }\n- Pre-fill via the \"data\" tool argument: \"data\": { \"form\": { \"name\": \"Alice\" } }\n- Capture values on submit via button action context:\n \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"name\": { \"path\": \"/form/name\" } } } }\n\nREPEATING CONTENT uses a structural children format (not the same as value binding):\n children: { componentId: \"card-id\", path: \"/items\" }\nComponents inside templates use RELATIVE paths (no leading slash): { \"path\": \"name\" }.`;\n\n/**\n * Design guidelines — visual design rules, component hierarchy tips,\n * and action handler patterns.\n */\nexport const A2UI_DEFAULT_DESIGN_GUIDELINES = `\\\nCreate polished, visually appealing interfaces. ONLY use components listed in the\nAvailable Components schema — do NOT use component names that are not in the schema.\n\nDesign principles:\n- Create clear visual hierarchy within cards and layouts.\n- Keep cards clean — avoid clutter. Whitespace is good.\n- Use consistent surfaceIds (lowercase, hyphenated).\n- NEVER use the same ID for a component and its child — this creates a\n circular dependency. E.g. if id=\"avatar\", child must NOT be \"avatar\".\n- For side-by-side comparisons, use a container with structural children\n (children: { componentId, path }) to repeat a card template per data item.\n- Include images when relevant (logos, icons, product photos):\n - Prefer company logos via Google favicons: https://www.google.com/s2/favicons?domain=example.com&sz=128\n - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.\n- For buttons: action MUST use this exact nested format:\n \"action\": { \"event\": { \"name\": \"myAction\", \"context\": { \"key\": \"value\" } } }\n The \"event\" key holds an OBJECT with \"name\" (required) and \"context\" (optional).\n Do NOT use a flat format like {\"event\": \"name\"} — \"event\" must be an object.\n- For forms: check the component schema — if an input's \"value\" property\n supports path binding, use it for editable fields. The submit button's\n action context should reference the same paths to capture user input.\n\nUse the SAME surfaceId as the main surface. Match action names to button action event names.`;\n\n/**\n * When UI helps the user, for both transports: a light nudge to reach for UI\n * where it conveys the answer better than prose, and to stay in prose\n * otherwise.\n */\nexport const GENERATIVE_UI_WHEN_TO_SHOW =\n \"Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.\";\n\n/** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION =\n \"Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.\";\n\n/**\n * Description of the context entry that carries the compact component schema\n * in the markdown transport.\n *\n * It must not equal `A2UI_SCHEMA_CONTEXT_DESCRIPTION` (the key that\n * `@ag-ui/a2ui-middleware` stamps for tool mode). The LangGraph and Strands\n * adapters find that exact string and move the entry into\n * `state[\"ag-ui\"][\"a2ui_schema\"]` for the `render_a2ui` tool, so it never\n * gets to the system prompt. The markdown transport has no tool, so the\n * schema must stay ordinary context that the model reads as App Context.\n */\nexport const GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION =\n \"Generative UI component schema: the components, props, events, slots, functions, and targets that ```a2ui code fences can use, and the surfaces that already exist.\";\n\n/** Which optional parts of A2UI a manifest uses. The guides leave out the rules for the others. */\nexport interface GenerativeUIGuideFeatures {\n /** A function is mounted: function calls and callRendererFunction. */\n functions: boolean;\n /** A component has an event prop. */\n events: boolean;\n /** A component has a \"multiple\" slot, which takes templates and @index. */\n templates: boolean;\n /** A component has a \"checks\" prop: validation rules on inputs. */\n checks: boolean;\n}\n\n/** Every optional rule group. Use it when the manifest is not known. */\nexport const ALL_GENERATIVE_UI_GUIDE_FEATURES: GenerativeUIGuideFeatures = {\n functions: true,\n events: true,\n templates: true,\n checks: true,\n};\n\n/**\n * The optional parts of A2UI that a manifest uses, so that a guide sends only\n * the rules that the model can apply.\n *\n * @param manifest - The components and the mounted functions of a run.\n * @returns Which optional rule groups the guides include.\n *\n * @example\n * ```ts\n * const guide = buildGenerativeUIMarkdownGuidelines(\n * generativeUIGuideFeatures(manifest),\n * );\n * ```\n */\nexport function generativeUIGuideFeatures(\n manifest: Pick<GenerativeUIManifest, \"components\" | \"functions\">,\n): GenerativeUIGuideFeatures {\n const components = Object.values(manifest.components);\n const hasChildList = (schema: unknown): boolean => {\n if (Array.isArray(schema)) return schema.some(hasChildList);\n if (typeof schema !== \"object\" || schema === null) return false;\n const node = schema as Record<string, unknown>;\n if (node.$ref === A2UI_CHILD_LIST_REF) return true;\n return Object.values(node).some(hasChildList);\n };\n return {\n // App functions only: the built-in ones are always there and have\n // their own rules.\n functions: Object.keys(manifest.functions).some(\n (name) => !isA2UIBasicFunction(name),\n ),\n events: components.some((c) => Object.keys(c.events ?? {}).length > 0),\n templates: components.some(\n (c) =>\n Object.values(c.slots ?? {}).includes(\"multiple\") ||\n hasChildList(c.props),\n ),\n checks: components.some((c) => {\n const properties = c.props.properties;\n return (\n typeof properties === \"object\" &&\n properties !== null &&\n Object.prototype.hasOwnProperty.call(properties, \"checks\")\n );\n }),\n };\n}\n\n/** The first rules of every markdown guideline, before the optional groups. */\nconst MARKDOWN_BASE_RULES = [\n \"Write explanations as normal markdown prose outside the fences.\",\n \"Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.\",\n 'Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target has \"components\", its surfaces can use only those components.',\n \"Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.\",\n \"Keep each operation whole on its line.\",\n 'Give every operation \"version\":\"v1.0\".',\n `Start a surface with one createSurface. Put all the initial data in \"dataModel\" and the \"root\" component in \"components\". Then write the children in updateComponents lines, so that they show while you write:\n \\`\\`\\`a2ui\n {\"version\":\"v1.0\",\"createSurface\":{\"surfaceId\":\"plan-picker\",\"dataModel\":{ ...initial data... },\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"seats\",\"pick\"]}]}}\n {\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"plan-picker\",\"components\":[ ...the children... ]}}\n \\`\\`\\``,\n 'Keep \"dataModel\" flat: top-level keys such as \"seats\" or \"form\", never one wrapper object around everything. Check that every { and [ you open in a line is closed.',\n 'Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.',\n \"Use unique ids. Do not make cycles. A component cannot be its own child.\",\n 'Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.',\n 'Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.',\n 'A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.',\n 'Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".',\n 'Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.',\n 'A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions under \"functions\" in the schema. Write a literal when the value never changes.',\n 'formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: \\'EUR\\')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.',\n '${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: \\'seats * 29\\', seats: /seats), currency: \\'USD\\')}. The UI then follows the user\\'s input with no round trip.',\n 'For a computed list (chart data, template items) use series. Its description under \"functions\" in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.',\n 'Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user\\'s input goes to that path.',\n 'To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".',\n 'Set \"value\":null to delete the key at \"path\".',\n];\n\n/** The last rules of every markdown guideline, after the optional groups. */\nconst MARKDOWN_CLOSING_RULES = [\n 'The schema lists the surfaces that already exist under \"surfaces\". \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.',\n \"Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.\",\n \"Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.\",\n \"Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.\",\n \"Never wrap the whole reply in a fence.\",\n];\n\n/**\n * Builds the markdown-transport guideline. The model writes A2UI v1.0\n * operations inside ```a2ui fences between normal markdown prose. The rules\n * for functions, events, and templates are left out when the manifest has\n * none of them, so the guideline stays small.\n *\n * @param features - The optional rule groups to include. Defaults to all.\n * @returns The guideline text, one rule per line.\n */\nexport function buildGenerativeUIMarkdownGuidelines(\n features: GenerativeUIGuideFeatures = ALL_GENERATIVE_UI_GUIDE_FEATURES,\n) {\n const { functions, events, templates, checks } = features;\n const rules = [...MARKDOWN_BASE_RULES];\n if (events) {\n rules.push(\n 'Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.',\n functions\n ? 'Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.'\n : 'Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.',\n 'Use {\"event\": ...} to send the interaction back to you as a user message. Put the text of that message in \"userMessage\": {\"event\":{\"name\":\"choose\",\"userMessage\":\"Show me the Team plan\"}}. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".',\n 'To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.',\n \"A button or other event prop without an event or functionCall does nothing.\",\n );\n }\n if (checks) {\n rules.push(\n 'Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks.',\n );\n }\n rules.push(\n 'A prop typed componentId takes the id of another component, and a childList takes ids [\"a\",\"b\"]: \"child\":\"card\", \"children\":[\"a\",\"b\"], \"tabs\":[{\"title\":\"Specs\",\"child\":\"specs\"}].',\n );\n if (templates) {\n rules.push(\n 'To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.',\n 'Inside a template, paths are relative to the item (\"name\", not \"/name\").',\n 'Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.',\n );\n }\n rules.push(\n \"Updating a component replaces all of its props. Send every prop again.\",\n \"To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.\",\n \"Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.\",\n );\n if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) {\n rules.push(\n 'To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.',\n 'Give every callRendererFunction a new functionCallId. Call only a function from the schema with \"callers\": \"UI or agent\" or \"agent only\"; a function without \"callers\" is for the UI only. A function with \"callers\": \"agent only\" is only for callRendererFunction: do not bind an event to it.',\n 'The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.',\n \"Do not guess the result of a callRendererFunction. Wait for the developer message.\",\n );\n }\n rules.push(...MARKDOWN_CLOSING_RULES);\n return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nRULES\n${rules.map((rule) => `- ${rule}`).join(\"\\n\")}\n`;\n}\n\n/**\n * The markdown-transport guideline with every rule group. A run sends\n * `buildGenerativeUIMarkdownGuidelines` for its own manifest instead.\n */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES =\n buildGenerativeUIMarkdownGuidelines();\n"],"mappings":";;;;;;;;;;;;;;;AAeA,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFlD,MAAa,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8B9C,MAAa,6BACX;;AAGF,MAAa,gDACX;;;;;;;;;;;;AAaF,MAAa,oDACX;;AAeF,MAAa,mCAA8D;CACzE,WAAW;CACX,QAAQ;CACR,WAAW;CACX,QAAQ;CACT;;;;;;;;;;;;;;;AAgBD,SAAgB,0BACd,UAC2B;CAC3B,MAAM,aAAa,OAAO,OAAO,SAAS,WAAW;CACrD,MAAM,gBAAgB,WAA6B;AACjD,MAAI,MAAM,QAAQ,OAAO,CAAE,QAAO,OAAO,KAAK,aAAa;AAC3D,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;EAC1D,MAAM,OAAO;AACb,MAAI,KAAK,SAAS,oBAAqB,QAAO;AAC9C,SAAO,OAAO,OAAO,KAAK,CAAC,KAAK,aAAa;;AAE/C,QAAO;EAGL,WAAW,OAAO,KAAK,SAAS,UAAU,CAAC,MACxC,SAAS,CAAC,oBAAoB,KAAK,CACrC;EACD,QAAQ,WAAW,MAAM,MAAM,OAAO,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC,SAAS,EAAE;EACtE,WAAW,WAAW,MACnB,MACC,OAAO,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,WAAW,IACjD,aAAa,EAAE,MAAM,CACxB;EACD,QAAQ,WAAW,MAAM,MAAM;GAC7B,MAAM,aAAa,EAAE,MAAM;AAC3B,UACE,OAAO,eAAe,YACtB,eAAe,QACf,OAAO,UAAU,eAAe,KAAK,YAAY,SAAS;IAE5D;EACH;;;AAIH,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;;;;;CAKA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;AAGD,MAAM,yBAAyB;CAC7B;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,SAAgB,oCACd,WAAsC,kCACtC;CACA,MAAM,EAAE,WAAW,QAAQ,WAAW,WAAW;CACjD,MAAM,QAAQ,CAAC,GAAG,oBAAoB;AACtC,KAAI,OACF,OAAM,KACJ,sNACA,YACI,4PACA,2LACJ,ySACA,sHACA,8EACD;AAEH,KAAI,OACF,OAAM,KACJ,uXACD;AAEH,OAAM,KACJ,6MACD;AACD,KAAI,UACF,OAAM,KACJ,2IACA,gFACA,2JACD;AAEH,OAAM,KACJ,0EACA,+UACA,4GACD;AACD,KAAI,aAAa,mCACf,OAAM,KACJ,kQACA,gTACA,wQACA,qFACD;AAEH,OAAM,KAAK,GAAG,uBAAuB;AACrC,QAAO;;EAEP,2BAA2B;;;EAG3B,MAAM,KAAK,SAAS,KAAK,OAAO,CAAC,KAAK,KAAK,CAAC;;;;;;;AAQ9C,MAAa,oCACX,qCAAqC"}
1
+ {"version":3,"file":"a2ui-prompts.mjs","names":[],"sources":["../src/a2ui-prompts.ts"],"sourcesContent":["import { isA2UIBasicFunction } from \"./generative-ui/basic-functions\";\nimport { A2UI_CHILD_LIST_REF } from \"./generative-ui/child-refs\";\nimport type { GenerativeUIManifest } from \"./generative-ui/types\";\nimport {\n defaultGenerativeUIPromptSpec,\n GUIDE_COMPONENTS,\n generativeUIPromptFeatures,\n selectPromptItems,\n} from \"./generative-ui/prompt-spec\";\nimport type { GenerativeUIPromptSpec } from \"./generative-ui/prompt-spec\";\nexport {\n GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW,\n GENERATIVE_UI_WHEN_TO_SHOW,\n} from \"./generative-ui/prompt-spec\";\n/**\n * Default A2UI generation and design guideline prompts.\n *\n * These are the canonical prompt fragments that instruct an LLM how to call\n * the render_a2ui tool, how to bind data, and how to style surfaces.\n */\n\n/**\n * Generation guidelines — protocol rules, tool arguments, path rules,\n * data model format, and form/two-way-binding instructions.\n */\nexport const A2UI_DEFAULT_GENERATION_GUIDELINES = `\\\nGenerate A2UI v0.9 JSON.\n\n## A2UI Protocol Instructions\n\nA2UI (Agent to UI) is a protocol for rendering rich UI surfaces from agent responses.\n\nCRITICAL: You MUST call the render_a2ui tool with ALL of these arguments:\n- surfaceId: A unique ID for the surface (e.g. \"product-comparison\")\n- components: REQUIRED — the A2UI component array. NEVER omit this. Only use\n components listed in the Available Components schema provided as context.\n- data: OPTIONAL — a JSON object written to the root of the surface data model.\n Use for pre-filling form values or providing data for path-bound components.\n- every component must have the \"component\" field specifying the component type.\n ONLY use component names from the Available Components schema — do NOT invent\n component names or use names not in the schema.\n\nCOMPONENT ID RULES:\n- Exactly one component MUST have id=\"root\". This is the surface's entry\n point — the renderer begins at \"root\" and walks the child/children tree\n from there. Every other component must be reachable from \"root\". If no\n component has id=\"root\", the surface renders an empty loading placeholder\n and none of your components will be shown.\n- Every component ID must be unique within the surface.\n- A component MUST NOT reference itself as child/children. This causes a\n circular dependency error. For example, if a component has id=\"avatar\",\n its child must be a DIFFERENT id (e.g. \"avatar-img\"), never \"avatar\".\n- The child/children tree must be a DAG — no cycles allowed.\n\nREPEATING CONTENT (TEMPLATES):\nTo repeat a component for each item in an array, use the structural children format:\n children: { componentId: \"card-id\", path: \"/items\" }\nThis tells the renderer to create one instance of \"card-id\" per item in the \"/items\" array.\n\nPATH RULES FOR TEMPLATES:\nComponents inside a repeating template use RELATIVE paths (no leading slash).\nThe path is resolved relative to each array item automatically.\nIf a container has children: { componentId: \"card\", path: \"/items\" } and each item\nhas a key \"name\", use { \"path\": \"name\" } (NO leading slash — relative to item).\nCRITICAL: Do NOT use \"/name\" (absolute) inside templates — use \"name\" (relative).\nThe container's path (\"/items\") uses a leading slash (absolute), but all\ncomponents INSIDE the template use paths WITHOUT leading slash.\n\nCOMPONENT VALUES — DEFAULT RULE:\nUse inline literal values for ALL component properties. Pass strings, numbers,\narrays, and objects directly on the component. Do NOT use { \"path\": \"...\" }\nobjects unless the property's schema explicitly allows it (see exception below).\nCRITICAL: USING { \"path\": \"...\" } ON A PROPERTY THAT DOES NOT DECLARE PATH\nSUPPORT IN ITS SCHEMA WILL CAUSE A RUNTIME CRASH AND BREAK THE ENTIRE UI.\nALWAYS CHECK THE COMPONENT SCHEMA FIRST — IF THE PROPERTY ONLY ACCEPTS A\nPLAIN TYPE, YOU MUST USE A LITERAL VALUE.\nVERY IMPORTANT: THE APPLICATION WILL BREAK IF YOU DO NOT FOLLOW THIS RULE!\n\nFor example, a chart's \"data\" must always be an inline array:\n \"data\": [{\"label\": \"Jan\", \"value\": 100}, {\"label\": \"Feb\", \"value\": 200}]\nA metric's \"value\" must always be an inline string:\n \"value\": \"$1,200\"\n\nPATH BINDING EXCEPTION — SCHEMA-DRIVEN:\nA few properties accept { \"path\": \"/some/path\" } as an alternative to a literal\nvalue. You can identify these in the Available Components schema: the property\nwill list BOTH a literal type AND an object-with-path option. If a property only\nshows a single type (string, number, array, etc.), it does NOT support path\nbinding — use a literal value only.\n\nPath binding is typically used for editable form inputs so the client can write\nuser input back to the data model. When building forms:\n- Bind input \"value\" to a data model path: \"value\": { \"path\": \"/form/name\" }\n- Pre-fill via the \"data\" tool argument: \"data\": { \"form\": { \"name\": \"Alice\" } }\n- Capture values on submit via button action context:\n \"action\": { \"event\": { \"name\": \"submit\", \"context\": { \"name\": { \"path\": \"/form/name\" } } } }\n\nREPEATING CONTENT uses a structural children format (not the same as value binding):\n children: { componentId: \"card-id\", path: \"/items\" }\nComponents inside templates use RELATIVE paths (no leading slash): { \"path\": \"name\" }.`;\n\n/**\n * Design guidelines — visual design rules, component hierarchy tips,\n * and action handler patterns.\n */\nexport const A2UI_DEFAULT_DESIGN_GUIDELINES = `\\\nCreate polished, visually appealing interfaces. ONLY use components listed in the\nAvailable Components schema — do NOT use component names that are not in the schema.\n\nDesign principles:\n- Create clear visual hierarchy within cards and layouts.\n- Keep cards clean — avoid clutter. Whitespace is good.\n- Use consistent surfaceIds (lowercase, hyphenated).\n- NEVER use the same ID for a component and its child — this creates a\n circular dependency. E.g. if id=\"avatar\", child must NOT be \"avatar\".\n- For side-by-side comparisons, use a container with structural children\n (children: { componentId, path }) to repeat a card template per data item.\n- Include images when relevant (logos, icons, product photos):\n - Prefer company logos via Google favicons: https://www.google.com/s2/favicons?domain=example.com&sz=128\n - Do NOT invent Unsplash photo-IDs — they will 404. Only use real, known URLs.\n- For buttons: action MUST use this exact nested format:\n \"action\": { \"event\": { \"name\": \"myAction\", \"context\": { \"key\": \"value\" } } }\n The \"event\" key holds an OBJECT with \"name\" (required) and \"context\" (optional).\n Do NOT use a flat format like {\"event\": \"name\"} — \"event\" must be an object.\n- For forms: check the component schema — if an input's \"value\" property\n supports path binding, use it for editable fields. The submit button's\n action context should reference the same paths to capture user input.\n\nUse the SAME surfaceId as the main surface. Match action names to button action event names.`;\n\n/** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION =\n \"Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.\";\n\n/**\n * Description of the context entry that carries the compact component schema\n * in the markdown transport.\n *\n * It must not equal `A2UI_SCHEMA_CONTEXT_DESCRIPTION` (the key that\n * `@ag-ui/a2ui-middleware` stamps for tool mode). The LangGraph and Strands\n * adapters find that exact string and move the entry into\n * `state[\"ag-ui\"][\"a2ui_schema\"]` for the `render_a2ui` tool, so it never\n * gets to the system prompt. The markdown transport has no tool, so the\n * schema must stay ordinary context that the model reads as App Context.\n */\nexport const GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION =\n \"Generative UI component schema: the components, props, events, slots, functions, and targets that ```a2ui code fences can use, and the surfaces that already exist.\";\n\n/** Which optional parts of A2UI a manifest uses. The guides leave out the rules for the others. */\nexport interface GenerativeUIGuideFeatures {\n /** A function is mounted: function calls and callRendererFunction. */\n functions: boolean;\n /** A component has an event prop. */\n events: boolean;\n /** A component has a \"multiple\" slot, which takes templates and @index. */\n templates: boolean;\n /** A component has a \"checks\" prop: validation rules on inputs. */\n checks: boolean;\n /**\n * The component names of the catalog. A guide line that names a standard\n * component missing from it is left out. Unset keeps every line.\n */\n components?: readonly string[];\n}\n\n/** Every optional rule group. Use it when the manifest is not known. */\nexport const ALL_GENERATIVE_UI_GUIDE_FEATURES: GenerativeUIGuideFeatures = {\n functions: true,\n events: true,\n templates: true,\n checks: true,\n};\n\n/**\n * The optional parts of A2UI that a manifest uses, so that a guide sends only\n * the rules that the model can apply.\n *\n * @param manifest - The components and the mounted functions of a run.\n * @returns Which optional rule groups the guides include.\n *\n * @example\n * ```ts\n * const guide = buildGenerativeUIMarkdownGuidelines(\n * generativeUIGuideFeatures(manifest),\n * );\n * ```\n */\nexport function generativeUIGuideFeatures(\n manifest: Pick<GenerativeUIManifest, \"components\" | \"functions\">,\n): GenerativeUIGuideFeatures {\n const components = Object.values(manifest.components);\n const hasChildList = (schema: unknown): boolean => {\n if (Array.isArray(schema)) return schema.some(hasChildList);\n if (typeof schema !== \"object\" || schema === null) return false;\n const node = schema as Record<string, unknown>;\n if (node.$ref === A2UI_CHILD_LIST_REF) return true;\n return Object.values(node).some(hasChildList);\n };\n return {\n components: Object.keys(manifest.components),\n // App functions only: the built-in ones are always there and have\n // their own rules.\n functions: Object.keys(manifest.functions).some(\n (name) => !isA2UIBasicFunction(name),\n ),\n events: components.some((c) => Object.keys(c.events ?? {}).length > 0),\n templates: components.some(\n (c) =>\n Object.values(c.slots ?? {}).includes(\"multiple\") ||\n hasChildList(c.props),\n ),\n checks: components.some((c) => {\n const properties = c.props.properties;\n return (\n typeof properties === \"object\" &&\n properties !== null &&\n Object.prototype.hasOwnProperty.call(properties, \"checks\")\n );\n }),\n };\n}\n\n/**\n * Whether a guide line names only standard components (`GUIDE_COMPONENTS`,\n * also in the plural) that the catalog has. With no catalog, every line fits.\n */\nfunction namesOnlyCatalogComponents(catalog: readonly string[] | undefined) {\n if (!catalog) return () => true;\n const has = new Set(catalog);\n return (line: string) =>\n (line.match(/\\b[A-Z][A-Za-z0-9]*\\b/g) ?? []).every((word) => {\n const name =\n !GUIDE_COMPONENTS.has(word) && word.endsWith(\"s\")\n ? word.slice(0, -1)\n : word;\n return !GUIDE_COMPONENTS.has(name) || has.has(name);\n });\n}\n\n/**\n * Builds the markdown-transport guideline. The model writes A2UI v1.0\n * operations inside ```a2ui fences between normal markdown prose. The rules\n * for functions, events, and templates are left out when the manifest has\n * none of them, so the guideline stays small.\n *\n * @param features - The optional rule groups to include. Defaults to all.\n * @param spec - The wording. Defaults to the prompts that ship.\n * @returns The guideline text, one rule per line.\n */\nexport function buildGenerativeUIMarkdownGuidelines(\n features: GenerativeUIGuideFeatures = ALL_GENERATIVE_UI_GUIDE_FEATURES,\n spec: GenerativeUIPromptSpec = defaultGenerativeUIPromptSpec(),\n) {\n const { intro, rules } = spec.markdown;\n const fits = namesOnlyCatalogComponents(features.components);\n const selected = selectPromptItems(\n rules,\n generativeUIPromptFeatures(features),\n ).filter(fits);\n const whenToShow = spec.markdown.whenToShow\n .split(\"\\n\")\n .filter(fits)\n .join(\"\\n\");\n const when = whenToShow ? `${whenToShow}\\n\\n` : \"\";\n return `${intro}\\n\\n${when}RULES\\n${selected.map((rule) => `- ${rule}`).join(\"\\n\")}\\n`;\n}\n\n/**\n * The markdown-transport guideline with every rule group. A run sends\n * `buildGenerativeUIMarkdownGuidelines` for its own manifest instead.\n */\nexport const GENERATIVE_UI_MARKDOWN_GUIDELINES =\n buildGenerativeUIMarkdownGuidelines();\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,MAAa,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgFlD,MAAa,iCAAiC;;;;;;;;;;;;;;;;;;;;;;;;;AA0B9C,MAAa,gDACX;;;;;;;;;;;;AAaF,MAAa,oDACX;;AAoBF,MAAa,mCAA8D;CACzE,WAAW;CACX,QAAQ;CACR,WAAW;CACX,QAAQ;CACT;;;;;;;;;;;;;;;AAgBD,SAAgB,0BACd,UAC2B;CAC3B,MAAM,aAAa,OAAO,OAAO,SAAS,WAAW;CACrD,MAAM,gBAAgB,WAA6B;AACjD,MAAI,MAAM,QAAQ,OAAO,CAAE,QAAO,OAAO,KAAK,aAAa;AAC3D,MAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;EAC1D,MAAM,OAAO;AACb,MAAI,KAAK,SAAS,oBAAqB,QAAO;AAC9C,SAAO,OAAO,OAAO,KAAK,CAAC,KAAK,aAAa;;AAE/C,QAAO;EACL,YAAY,OAAO,KAAK,SAAS,WAAW;EAG5C,WAAW,OAAO,KAAK,SAAS,UAAU,CAAC,MACxC,SAAS,CAAC,oBAAoB,KAAK,CACrC;EACD,QAAQ,WAAW,MAAM,MAAM,OAAO,KAAK,EAAE,UAAU,EAAE,CAAC,CAAC,SAAS,EAAE;EACtE,WAAW,WAAW,MACnB,MACC,OAAO,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,SAAS,WAAW,IACjD,aAAa,EAAE,MAAM,CACxB;EACD,QAAQ,WAAW,MAAM,MAAM;GAC7B,MAAM,aAAa,EAAE,MAAM;AAC3B,UACE,OAAO,eAAe,YACtB,eAAe,QACf,OAAO,UAAU,eAAe,KAAK,YAAY,SAAS;IAE5D;EACH;;;;;;AAOH,SAAS,2BAA2B,SAAwC;AAC1E,KAAI,CAAC,QAAS,cAAa;CAC3B,MAAM,MAAM,IAAI,IAAI,QAAQ;AAC5B,SAAQ,UACL,KAAK,MAAM,yBAAyB,IAAI,EAAE,EAAE,OAAO,SAAS;EAC3D,MAAM,OACJ,CAAC,iBAAiB,IAAI,KAAK,IAAI,KAAK,SAAS,IAAI,GAC7C,KAAK,MAAM,GAAG,GAAG,GACjB;AACN,SAAO,CAAC,iBAAiB,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK;GACnD;;;;;;;;;;;;AAaN,SAAgB,oCACd,WAAsC,kCACtC,OAA+B,+BAA+B,EAC9D;CACA,MAAM,EAAE,OAAO,UAAU,KAAK;CAC9B,MAAM,OAAO,2BAA2B,SAAS,WAAW;CAC5D,MAAM,WAAW,kBACf,OACA,2BAA2B,SAAS,CACrC,CAAC,OAAO,KAAK;CACd,MAAM,aAAa,KAAK,SAAS,WAC9B,MAAM,KAAK,CACX,OAAO,KAAK,CACZ,KAAK,KAAK;AAEb,QAAO,GAAG,MAAM,MADH,aAAa,GAAG,WAAW,QAAQ,GACrB,SAAS,SAAS,KAAK,SAAS,KAAK,OAAO,CAAC,KAAK,KAAK,CAAC;;;;;;AAOrF,MAAa,oCACX,qCAAqC"}
@@ -123,7 +123,7 @@ const A2UI_BASIC_FUNCTIONS = rendererOnly({
123
123
  */
124
124
  const COPILOTKIT_FUNCTIONS = rendererOnly({
125
125
  calc: {
126
- 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",
126
+ 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",
127
127
  parameters: "{ expression: string; [name: string]: number | string | boolean }",
128
128
  returnType: "any",
129
129
  extension: true
@@ -1 +1 @@
1
- {"version":3,"file":"basic-functions.cjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;;;AAwBF,SAAgB,gBAAgB,IAA6B;AAC3D,KAAI,GAAG,uBAAwB,QAAO;EAAE,UAAU;EAAM,OAAO;EAAO;CACtE,MAAM,UAAU,GAAG,kBAAkB;AACrC,QAAO;EACL,UAAU,YAAY;EACtB,OAAO,YAAY;EACpB;;;AAgBH,SAAS,aACP,WAC+C;AAC/C,QAAO,OAAO,YACZ,OAAO,QACL,UACD,CAAC,KAAK,CAAC,MAAM,UAAU,CACtB,MACA;EAAE,GAAG;EAAM,gBAAgB;EAAgB,CAC5C,CAAC,CACH;;;;;;;AAQH,MAAa,uBAET,aAAa;CACf,UAAU;EACR,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,QAAQ;EACN,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,gBAAgB;EACd,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,YAAY;EACV,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,WAAW;EACT,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACZ,wBAAwB;EACzB;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,IAAI;EACF,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACF,CAAC;;;;;;;;AASF,MAAa,uBAET,aAAa;CACf,MAAM;EACJ,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CAKD,QAAQ;EACN,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CACF,CAAC;;AAGF,MAAa,0BAET;CAAE,GAAG;CAAsB,GAAG;CAAsB;;AAGxD,MAAa,sBAAsB;;AAGnC,SAAgB,oBAAoB,MAAc;AAChD,QACE,SAAS,uBACT,OAAO,UAAU,eAAe,KAAK,yBAAyB,KAAK;;;;;;AAQvE,SAAgB,oBAAoB,MAAc;AAChD,KAAI,SAAS,oBAAqB,QAAO;CACzC,MAAM,OAAO,OAAO,UAAU,eAAe,KAC3C,yBACA,KACD,GACG,wBAAwB,QACxB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
1
+ {"version":3,"file":"basic-functions.cjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"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\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;;;AAwBF,SAAgB,gBAAgB,IAA6B;AAC3D,KAAI,GAAG,uBAAwB,QAAO;EAAE,UAAU;EAAM,OAAO;EAAO;CACtE,MAAM,UAAU,GAAG,kBAAkB;AACrC,QAAO;EACL,UAAU,YAAY;EACtB,OAAO,YAAY;EACpB;;;AAgBH,SAAS,aACP,WAC+C;AAC/C,QAAO,OAAO,YACZ,OAAO,QACL,UACD,CAAC,KAAK,CAAC,MAAM,UAAU,CACtB,MACA;EAAE,GAAG;EAAM,gBAAgB;EAAgB,CAC5C,CAAC,CACH;;;;;;;AAQH,MAAa,uBAET,aAAa;CACf,UAAU;EACR,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,QAAQ;EACN,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,gBAAgB;EACd,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,YAAY;EACV,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,WAAW;EACT,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACZ,wBAAwB;EACzB;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,IAAI;EACF,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACF,CAAC;;;;;;;;AASF,MAAa,uBAET,aAAa;CACf,MAAM;EACJ,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CAKD,QAAQ;EACN,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CACF,CAAC;;AAGF,MAAa,0BAET;CAAE,GAAG;CAAsB,GAAG;CAAsB;;AAGxD,MAAa,sBAAsB;;AAGnC,SAAgB,oBAAoB,MAAc;AAChD,QACE,SAAS,uBACT,OAAO,UAAU,eAAe,KAAK,yBAAyB,KAAK;;;;;;AAQvE,SAAgB,oBAAoB,MAAc;AAChD,KAAI,SAAS,oBAAqB,QAAO;CACzC,MAAM,OAAO,OAAO,UAAU,eAAe,KAC3C,yBACA,KACD,GACG,wBAAwB,QACxB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
@@ -122,7 +122,7 @@ const A2UI_BASIC_FUNCTIONS = rendererOnly({
122
122
  */
123
123
  const COPILOTKIT_FUNCTIONS = rendererOnly({
124
124
  calc: {
125
- 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",
125
+ 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",
126
126
  parameters: "{ expression: string; [name: string]: number | string | boolean }",
127
127
  returnType: "any",
128
128
  extension: true
@@ -1 +1 @@
1
- {"version":3,"file":"basic-functions.mjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;;;AAwBF,SAAgB,gBAAgB,IAA6B;AAC3D,KAAI,GAAG,uBAAwB,QAAO;EAAE,UAAU;EAAM,OAAO;EAAO;CACtE,MAAM,UAAU,GAAG,kBAAkB;AACrC,QAAO;EACL,UAAU,YAAY;EACtB,OAAO,YAAY;EACpB;;;AAgBH,SAAS,aACP,WAC+C;AAC/C,QAAO,OAAO,YACZ,OAAO,QACL,UACD,CAAC,KAAK,CAAC,MAAM,UAAU,CACtB,MACA;EAAE,GAAG;EAAM,gBAAgB;EAAgB,CAC5C,CAAC,CACH;;;;;;;AAQH,MAAa,uBAET,aAAa;CACf,UAAU;EACR,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,QAAQ;EACN,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,gBAAgB;EACd,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,YAAY;EACV,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,WAAW;EACT,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACZ,wBAAwB;EACzB;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,IAAI;EACF,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACF,CAAC;;;;;;;;AASF,MAAa,uBAET,aAAa;CACf,MAAM;EACJ,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CAKD,QAAQ;EACN,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CACF,CAAC;;AAGF,MAAa,0BAET;CAAE,GAAG;CAAsB,GAAG;CAAsB;;AAGxD,MAAa,sBAAsB;;AAGnC,SAAgB,oBAAoB,MAAc;AAChD,QACE,SAAS,uBACT,OAAO,UAAU,eAAe,KAAK,yBAAyB,KAAK;;;;;;AAQvE,SAAgB,oBAAoB,MAAc;AAChD,KAAI,SAAS,oBAAqB,QAAO;CACzC,MAAM,OAAO,OAAO,UAAU,eAAe,KAC3C,yBACA,KACD,GACG,wBAAwB,QACxB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
1
+ {"version":3,"file":"basic-functions.mjs","names":[],"sources":["../../src/generative-ui/basic-functions.ts"],"sourcesContent":["/**\n * The functions of the A2UI 1.0 basic catalog, as the model and the\n * validator see them. The renderer implements them (react-core\n * `generative-ui/functions.ts`); this file holds only what both sides share:\n * the names, the short signatures for the schema the model reads, and who\n * may call each one.\n */\n\n/** What a function gives back, as A2UI 1.0 names it. */\nexport type A2UIFunctionReturnType =\n | \"string\"\n | \"number\"\n | \"boolean\"\n | \"array\"\n | \"object\"\n | \"validationResult\"\n | \"any\"\n | \"void\";\n\n/**\n * Who may call a function. The renderer calls it from an event binding or\n * as a prop value; the agent calls it with `callRendererFunction`.\n */\nexport type A2UIAllowedCallers =\n | \"rendererOnly\"\n | \"agentOnly\"\n | \"rendererOrAgent\";\n\n/**\n * The callers of an app function that names none: the renderer only, as\n * in A2UI 1.0. The agent calls a function with `callRendererFunction` only\n * when its declaration allows it (`\"rendererOrAgent\"` or `\"agentOnly\"`).\n * The manifests and the exported catalog write the value out.\n */\nexport const GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS: A2UIAllowedCallers =\n \"rendererOnly\";\n\n/** The A2UI 1.0 interface fields of a function: who calls it, and how. */\nexport interface A2UIFunctionPermissions {\n allowedCallers?: A2UIAllowedCallers;\n /**\n * True for a function that only runs from a user gesture (a click, a key\n * press). It is `rendererOnly`: the agent cannot call it, and a prop\n * cannot be bound to it.\n */\n requiresUserActivation?: boolean;\n}\n\n/**\n * Who may call a function, from its permissions. A function that needs a\n * user gesture is for the renderer only, whatever `allowedCallers` says.\n *\n * @example\n * ```ts\n * functionCallers({}); // { renderer: true, agent: true }\n * functionCallers({ allowedCallers: \"rendererOnly\" }); // { renderer: true, agent: false }\n * functionCallers({ requiresUserActivation: true }); // { renderer: true, agent: false }\n * ```\n */\nexport function functionCallers(fn: A2UIFunctionPermissions) {\n if (fn.requiresUserActivation) return { renderer: true, agent: false };\n const callers = fn.allowedCallers ?? GENERATIVE_UI_DEFAULT_ALLOWED_CALLERS;\n return {\n renderer: callers !== \"agentOnly\",\n agent: callers !== \"rendererOnly\",\n };\n}\n\nexport interface A2UIBasicFunctionInfo extends A2UIFunctionPermissions {\n description: string;\n /** The args, as a short TypeScript-like type for the compact schema. */\n parameters: string;\n returnType: A2UIFunctionReturnType;\n /** Built-in functions are value functions of the renderer. */\n allowedCallers: \"rendererOnly\";\n requiresUserActivation?: true;\n /** True for a CopilotKit function that the A2UI basic catalog lacks. */\n extension?: true;\n}\n\n/** Marks a table of built-in functions as callable by the renderer only. */\nfunction rendererOnly<Name extends string>(\n functions: Record<Name, Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>,\n): Readonly<Record<Name, A2UIBasicFunctionInfo>> {\n return Object.fromEntries(\n Object.entries<Omit<A2UIBasicFunctionInfo, \"allowedCallers\">>(\n functions,\n ).map(([name, info]) => [\n name,\n { ...info, allowedCallers: \"rendererOnly\" },\n ]),\n ) as Record<Name, A2UIBasicFunctionInfo>;\n}\n\n/**\n * The basic functions by name. A `{\"@call\"}` in a prop, in an event\n * binding, or in a `callRendererFunction` may name any of them without a\n * declaration in `createGenerativeUI({ functions })`.\n */\nexport const A2UI_BASIC_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n required: {\n description: \"Valid when the value is not empty\",\n parameters: \"{ value: unknown }\",\n returnType: \"validationResult\",\n },\n regex: {\n description: \"Valid when the value matches the pattern\",\n parameters: \"{ value: string; pattern: string }\",\n returnType: \"validationResult\",\n },\n length: {\n description: \"Valid when the length of the value is within min and max\",\n parameters: \"{ value: string; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n numeric: {\n description: \"Valid when the value is a number within min and max\",\n parameters: \"{ value: number; min?: number; max?: number }\",\n returnType: \"validationResult\",\n },\n email: {\n description: \"Valid when the value is an email address\",\n parameters: \"{ value: string }\",\n returnType: \"validationResult\",\n },\n formatString: {\n description:\n \"Interpolates ${/path}, ${relative/path} and ${fn(arg: value)} in the value; \\\\${ is a literal\",\n parameters: \"{ value: string }\",\n returnType: \"string\",\n },\n formatNumber: {\n description: \"The number in the locale of the user\",\n parameters: \"{ value: number; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatCurrency: {\n description: \"The amount as money, with an ISO 4217 currency code\",\n parameters:\n \"{ value: number; currency: string; decimals?: number; grouping?: boolean }\",\n returnType: \"string\",\n },\n formatDate: {\n description:\n 'A date or ISO string in a TR35 pattern, for example \"MMM d, yyyy\" or \"HH:mm\"',\n parameters: \"{ value: string | number; format: string }\",\n returnType: \"string\",\n },\n pluralize: {\n description: \"The string of the plural category of the value\",\n parameters:\n \"{ value: number; zero?: string; one?: string; two?: string; few?: string; many?: string; other: string }\",\n returnType: \"string\",\n },\n openUrl: {\n description: \"Opens an http(s) URL in a new tab. Only from an event\",\n parameters: \"{ url: string }\",\n returnType: \"void\",\n requiresUserActivation: true,\n },\n and: {\n description: \"True when every value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n or: {\n description: \"True when any value is true\",\n parameters: \"{ values: boolean[] }\",\n returnType: \"boolean\",\n },\n not: {\n description: \"The negated value\",\n parameters: \"{ value: boolean }\",\n returnType: \"boolean\",\n },\n});\n\n/**\n * The value functions that CopilotKit adds to the basic catalog, because\n * A2UI 1.0 has no arithmetic: `calc` evaluates an expression over named\n * args, and `series` builds a computed list. A catalog may declare its own\n * functions in A2UI, so these are regular catalog functions to the model;\n * a renderer without them rejects the call instead of misrendering.\n */\nexport const COPILOTKIT_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = rendererOnly({\n calc: {\n description:\n \"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\",\n parameters:\n \"{ expression: string; [name: string]: number | string | boolean }\",\n returnType: \"any\",\n extension: true,\n },\n // WORKAROUND(a2ui-agent-sdk 0.9.0): examples omit `variable` and use default i\n // because the Express compiler mistakes a literal `variable` key for its AST.\n // Runtime support for custom variable names is unchanged.\n // https://github.com/a2ui-project/a2ui/issues/3410\n series: {\n description:\n 'A list of count copies of item, for chart data and template lists. Put arithmetic in ${expression} strings in item, using the loop variable (default i, counting from start, default 1) and other named args. A whole-expression string retains the result type, so \"${i * monthlyCost}\" yields a number. Arguments, including nested calc or formatString calls in item, resolve before the series loop; those calls cannot use the loop variable. Example: {\"@call\":\"series\",\"args\":{\"count\":6,\"item\":{\"month\":\"${i}\",\"cost\":\"${i * monthlyCost}\"},\"monthlyCost\":{\"@path\":\"/monthlyCost\"}}}. Omit variable to use i.',\n parameters:\n \"{ count: number; item: unknown; variable?: string; start?: number; [name: string]: unknown }\",\n returnType: \"array\",\n extension: true,\n },\n});\n\n/** Every function a `{\"@call\"}` may name without a declaration: basic and CopilotKit. */\nexport const GENERATIVE_UI_FUNCTIONS: Readonly<\n Record<string, A2UIBasicFunctionInfo>\n> = { ...A2UI_BASIC_FUNCTIONS, ...COPILOTKIT_FUNCTIONS };\n\n/** The name of the system function that gives the index of a template item. */\nexport const A2UI_INDEX_FUNCTION = \"@index\";\n\n/** True for a built-in function name: basic, CopilotKit, or `@index`. */\nexport function isA2UIBasicFunction(name: string) {\n return (\n name === A2UI_INDEX_FUNCTION ||\n Object.prototype.hasOwnProperty.call(GENERATIVE_UI_FUNCTIONS, name)\n );\n}\n\n/**\n * True for a built-in function that a prop or a check may call: every one\n * except the functions that need a user gesture.\n */\nexport function isA2UIValueFunction(name: string) {\n if (name === A2UI_INDEX_FUNCTION) return true;\n const info = Object.prototype.hasOwnProperty.call(\n GENERATIVE_UI_FUNCTIONS,\n name,\n )\n ? GENERATIVE_UI_FUNCTIONS[name]\n : undefined;\n return info !== undefined && !info.requiresUserActivation;\n}\n\n/** `{ \"@call\": \"<name>\", \"args\"?: {...} }`: a function call value. */\nexport function isCallBinding(\n value: unknown,\n): value is { \"@call\": string; args?: Record<string, unknown> } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>)[\"@call\"] === \"string\"\n );\n}\n\n/** How bad a failed check is. `error` is the default; only an error blocks. */\nexport type A2UIValidationSeverity = \"error\" | \"warning\" | \"info\";\n\n/**\n * A2UI's `ValidationResult`: what a check gives. A validator function gives\n * one; a check may also bind a boolean, which the renderer coerces to one.\n * `code` names the failure for programs; `severity` says how bad it is,\n * `\"error\"` when left out. Other keys are allowed, for app validators that\n * carry more (a suggested value, a field path).\n */\nexport interface A2UIValidationResult {\n valid: boolean;\n message?: string;\n code?: string;\n severity?: A2UIValidationSeverity;\n [extra: string]: unknown;\n}\n\nexport function isValidationResult(\n value: unknown,\n): value is A2UIValidationResult {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n typeof (value as Record<string, unknown>).valid === \"boolean\"\n );\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,wCACX;;;;;;;;;;;;AAwBF,SAAgB,gBAAgB,IAA6B;AAC3D,KAAI,GAAG,uBAAwB,QAAO;EAAE,UAAU;EAAM,OAAO;EAAO;CACtE,MAAM,UAAU,GAAG,kBAAkB;AACrC,QAAO;EACL,UAAU,YAAY;EACtB,OAAO,YAAY;EACpB;;;AAgBH,SAAS,aACP,WAC+C;AAC/C,QAAO,OAAO,YACZ,OAAO,QACL,UACD,CAAC,KAAK,CAAC,MAAM,UAAU,CACtB,MACA;EAAE,GAAG;EAAM,gBAAgB;EAAgB,CAC5C,CAAC,CACH;;;;;;;AAQH,MAAa,uBAET,aAAa;CACf,UAAU;EACR,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,QAAQ;EACN,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,OAAO;EACL,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,cAAc;EACZ,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,gBAAgB;EACd,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,YAAY;EACV,aACE;EACF,YAAY;EACZ,YAAY;EACb;CACD,WAAW;EACT,aAAa;EACb,YACE;EACF,YAAY;EACb;CACD,SAAS;EACP,aAAa;EACb,YAAY;EACZ,YAAY;EACZ,wBAAwB;EACzB;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,IAAI;EACF,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACD,KAAK;EACH,aAAa;EACb,YAAY;EACZ,YAAY;EACb;CACF,CAAC;;;;;;;;AASF,MAAa,uBAET,aAAa;CACf,MAAM;EACJ,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CAKD,QAAQ;EACN,aACE;EACF,YACE;EACF,YAAY;EACZ,WAAW;EACZ;CACF,CAAC;;AAGF,MAAa,0BAET;CAAE,GAAG;CAAsB,GAAG;CAAsB;;AAGxD,MAAa,sBAAsB;;AAGnC,SAAgB,oBAAoB,MAAc;AAChD,QACE,SAAS,uBACT,OAAO,UAAU,eAAe,KAAK,yBAAyB,KAAK;;;;;;AAQvE,SAAgB,oBAAoB,MAAc;AAChD,KAAI,SAAS,oBAAqB,QAAO;CACzC,MAAM,OAAO,OAAO,UAAU,eAAe,KAC3C,yBACA,KACD,GACG,wBAAwB,QACxB;AACJ,QAAO,SAAS,UAAa,CAAC,KAAK;;;AAIrC,SAAgB,cACd,OAC8D;AAC9D,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,aAAa;;AAsB3D,SAAgB,mBACd,OAC+B;AAC/B,QACE,OAAO,UAAU,YACjB,UAAU,QACV,CAAC,MAAM,QAAQ,MAAM,IACrB,OAAQ,MAAkC,UAAU"}
@@ -0,0 +1,187 @@
1
+ const require_basic_functions = require('./basic-functions.cjs');
2
+ const require_child_refs = require('./child-refs.cjs');
3
+ const require_types = require('./types.cjs');
4
+
5
+ //#region src/generative-ui/compact-schema.ts
6
+ /** Objects nested deeper than this show as `object`. */
7
+ const MAX_OBJECT_DEPTH = 2;
8
+ /** A prop must appear verbatim in at least this many components to be hoisted. */
9
+ const COMMON_PROP_MIN_COMPONENTS = 8;
10
+ function isRecord(value) {
11
+ return typeof value === "object" && value !== null && !Array.isArray(value);
12
+ }
13
+ /** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
14
+ function schemaList(value) {
15
+ return Array.isArray(value) ? value.filter(isRecord) : [];
16
+ }
17
+ /**
18
+ * Puts a top-level union in parentheses, so that `[]` applies to all of
19
+ * it. A union inside braces needs none.
20
+ */
21
+ function asArrayItem(type) {
22
+ let outside = type;
23
+ for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside;) {
24
+ outside = inner;
25
+ inner = outside.replace(/\{[^{}]*\}/g, "");
26
+ }
27
+ return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
28
+ }
29
+ /**
30
+ * A JSON Schema as a short TypeScript-like type, for example
31
+ * `{ label: string; size?: "sm" | "md" }`.
32
+ */
33
+ function compactType(schema, depth) {
34
+ const ref = require_child_refs.childRefKind(schema);
35
+ if (ref === "single") return "componentId";
36
+ if (ref === "multiple") return "componentId[] | { componentId: string; path: string }";
37
+ if ("const" in schema) return JSON.stringify(schema.const);
38
+ if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
39
+ const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
40
+ if (variants.length > 0) return variants.map((variant) => compactType(variant, depth)).join(" | ");
41
+ return (Array.isArray(schema.type) ? schema.type : [schema.type]).map((type) => {
42
+ switch (type) {
43
+ case "string":
44
+ case "boolean":
45
+ case "null": return type;
46
+ case "number":
47
+ case "integer": return "number";
48
+ case "array": return isRecord(schema.items) ? asArrayItem(compactType(schema.items, depth)) : "unknown[]";
49
+ case "object": return compactObject(schema, depth);
50
+ default: return "unknown";
51
+ }
52
+ }).join(" | ");
53
+ }
54
+ /** An object schema as `{ key: type; other?: type }`. */
55
+ function compactObject(schema, depth) {
56
+ const properties = isRecord(schema.properties) ? schema.properties : {};
57
+ const entries = Object.entries(properties);
58
+ if (entries.length === 0) return isRecord(schema.additionalProperties) ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>` : "object";
59
+ if (depth >= MAX_OBJECT_DEPTH) return "object";
60
+ const required = Array.isArray(schema.required) ? schema.required : [];
61
+ return `{ ${entries.map(([key, value]) => {
62
+ const type = isRecord(value) ? compactType(value, depth + 1) : "unknown";
63
+ return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
64
+ }).join("; ")} }`;
65
+ }
66
+ /** A schema as its type, with its description after `//`. */
67
+ function describedType(schema, depth) {
68
+ const type = compactType(schema, depth);
69
+ return typeof schema.description === "string" ? `${type} // ${schema.description}` : type;
70
+ }
71
+ /**
72
+ * The props of a component: `{ "label": "string", "size?": "..." }`. With
73
+ * `descriptions`, each type carries its description after `//`.
74
+ */
75
+ function compactProps(schema, descriptions = true) {
76
+ const properties = isRecord(schema.properties) ? schema.properties : {};
77
+ const required = Array.isArray(schema.required) ? schema.required : [];
78
+ const props = {};
79
+ for (const [key, value] of Object.entries(properties)) {
80
+ if (!isRecord(value)) continue;
81
+ const name = required.includes(key) ? key : `${key}?`;
82
+ props[name] = descriptions ? describedType(value, 1) : compactType(value, 1);
83
+ }
84
+ return props;
85
+ }
86
+ /**
87
+ * The prop set worth listing once. Candidates are (key, type) pairs that at
88
+ * least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
89
+ * candidate subset of each component is a possible common set, scored by
90
+ * the characters it saves (set size times the components that contain all
91
+ * of it). `undefined` when no set is shared by enough components.
92
+ */
93
+ function findCommonProps(propsList) {
94
+ const pairKey = (key, type) => `${key}\u0000${type}`;
95
+ const counts = /* @__PURE__ */ new Map();
96
+ for (const props of propsList) for (const [key, type] of Object.entries(props)) {
97
+ const id = pairKey(key, type);
98
+ counts.set(id, (counts.get(id) ?? 0) + 1);
99
+ }
100
+ let best;
101
+ let bestScore = 0;
102
+ const seen = /* @__PURE__ */ new Set();
103
+ for (const props of propsList) {
104
+ const subset = Object.entries(props).filter(([key, type]) => (counts.get(pairKey(key, type)) ?? 0) >= COMMON_PROP_MIN_COMPONENTS);
105
+ if (subset.length < 2) continue;
106
+ const signature = subset.map(([key, type]) => pairKey(key, type)).join("\n");
107
+ if (seen.has(signature)) continue;
108
+ seen.add(signature);
109
+ const members = propsList.filter((other) => subset.every(([key, type]) => other[key] === type)).length;
110
+ if (members < COMMON_PROP_MIN_COMPONENTS) continue;
111
+ const score = subset.reduce((total, [key, type]) => total + key.length + type.length, 0) * (members - 1);
112
+ if (score > bestScore) {
113
+ bestScore = score;
114
+ best = Object.fromEntries(subset);
115
+ }
116
+ }
117
+ return best;
118
+ }
119
+ /**
120
+ * The component schema of the markdown transport, from the per-run
121
+ * manifest. It is smaller than the manifest: each prop is one short type,
122
+ * and the props that many components share verbatim (the layout props of
123
+ * the containers) are listed once in `commonProps`; a component that takes
124
+ * them is flagged `includesCommonProps`.
125
+ * It has the catalog id, the targets with their descriptions and their
126
+ * component lists, the functions with their parameters, the components
127
+ * with their props, events and slots, and the surfaces of the thread. A surface lists the
128
+ * values that the user set and the operations that the client dropped.
129
+ *
130
+ * @param manifest - The manifest from `buildGenerativeUIManifest`.
131
+ * @param options - `propDescriptions` (default true) writes each prop's
132
+ * description; `commonProps` (default true) lists shared props once.
133
+ * @returns A JSON-ready object.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * const value = JSON.stringify(
138
+ * buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
139
+ * );
140
+ * ```
141
+ */
142
+ function buildCompactGenerativeUISchema(manifest, options = {}) {
143
+ const { propDescriptions = true, commonProps = true } = options;
144
+ const components = {};
145
+ for (const [name, component] of Object.entries(manifest.components)) {
146
+ const events = Object.entries(component.events ?? {}).map(([event, definition]) => [event, definition.description ?? compactType(definition.parameters, 0)]);
147
+ components[name] = {
148
+ ...component.description ? { description: component.description } : {},
149
+ props: compactProps(component.props, propDescriptions),
150
+ ...events.length > 0 ? { events: Object.fromEntries(events) } : {},
151
+ ...component.slots ? { slots: component.slots } : {}
152
+ };
153
+ }
154
+ const common = commonProps ? findCommonProps(Object.values(components).map((component) => component.props)) : void 0;
155
+ if (common) {
156
+ const commonKeys = Object.keys(common);
157
+ for (const component of Object.values(components)) {
158
+ if (!commonKeys.every((key) => component.props[key] === common[key])) continue;
159
+ component.includesCommonProps = true;
160
+ component.props = Object.fromEntries(Object.entries(component.props).filter(([key]) => !(key in common)));
161
+ }
162
+ }
163
+ const functions = Object.fromEntries(Object.entries(manifest.functions).map(([name, fn]) => {
164
+ const signature = fn.parameters.description;
165
+ const hasSignature = typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2;
166
+ const callers = require_basic_functions.functionCallers(fn);
167
+ return [name, {
168
+ ...fn.description ? { description: fn.description } : {},
169
+ parameters: hasSignature ? signature : compactType(fn.parameters, 0),
170
+ ...callers.agent && require_types.GENERATIVE_UI_AGENT_FUNCTION_CALLS ? { callers: callers.renderer ? "UI or agent" : "agent only" } : {}
171
+ }];
172
+ }));
173
+ return {
174
+ catalogId: manifest.catalogId,
175
+ targets: manifest.targets,
176
+ functions,
177
+ ...common ? { commonProps: common } : {},
178
+ components,
179
+ surfaces: manifest.surfaces
180
+ };
181
+ }
182
+
183
+ //#endregion
184
+ exports.buildCompactGenerativeUISchema = buildCompactGenerativeUISchema;
185
+ exports.compactProps = compactProps;
186
+ exports.compactType = compactType;
187
+ //# sourceMappingURL=compact-schema.cjs.map