@copilotkit/shared 1.83.0 → 1.84.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/a2ui-catalog-schema.cjs +264 -0
  2. package/dist/a2ui-catalog-schema.cjs.map +1 -0
  3. package/dist/a2ui-catalog-schema.d.cts +112 -0
  4. package/dist/a2ui-catalog-schema.d.cts.map +1 -0
  5. package/dist/a2ui-catalog-schema.d.mts +112 -0
  6. package/dist/a2ui-catalog-schema.d.mts.map +1 -0
  7. package/dist/a2ui-catalog-schema.mjs +259 -0
  8. package/dist/a2ui-catalog-schema.mjs.map +1 -0
  9. package/dist/a2ui-envelope.cjs +2 -2
  10. package/dist/a2ui-envelope.cjs.map +1 -1
  11. package/dist/a2ui-envelope.d.cts +1 -1
  12. package/dist/a2ui-envelope.d.cts.map +1 -1
  13. package/dist/a2ui-envelope.d.mts +1 -1
  14. package/dist/a2ui-envelope.d.mts.map +1 -1
  15. package/dist/a2ui-envelope.mjs +2 -2
  16. package/dist/a2ui-envelope.mjs.map +1 -1
  17. package/dist/a2ui-prompts.cjs +21 -62
  18. package/dist/a2ui-prompts.cjs.map +1 -1
  19. package/dist/a2ui-prompts.d.cts +8 -1
  20. package/dist/a2ui-prompts.d.cts.map +1 -1
  21. package/dist/a2ui-prompts.d.mts +8 -1
  22. package/dist/a2ui-prompts.d.mts.map +1 -1
  23. package/dist/a2ui-prompts.mjs +22 -62
  24. package/dist/a2ui-prompts.mjs.map +1 -1
  25. package/dist/generative-ui/basic-functions.cjs +1 -1
  26. package/dist/generative-ui/basic-functions.cjs.map +1 -1
  27. package/dist/generative-ui/basic-functions.mjs +1 -1
  28. package/dist/generative-ui/basic-functions.mjs.map +1 -1
  29. package/dist/generative-ui/compact-schema.cjs +187 -0
  30. package/dist/generative-ui/compact-schema.cjs.map +1 -0
  31. package/dist/generative-ui/compact-schema.d.cts +55 -0
  32. package/dist/generative-ui/compact-schema.d.cts.map +1 -0
  33. package/dist/generative-ui/compact-schema.d.mts +55 -0
  34. package/dist/generative-ui/compact-schema.d.mts.map +1 -0
  35. package/dist/generative-ui/compact-schema.mjs +185 -0
  36. package/dist/generative-ui/compact-schema.mjs.map +1 -0
  37. package/dist/generative-ui/prompt-spec.cjs +225 -0
  38. package/dist/generative-ui/prompt-spec.cjs.map +1 -0
  39. package/dist/generative-ui/prompt-spec.d.cts +94 -0
  40. package/dist/generative-ui/prompt-spec.d.cts.map +1 -0
  41. package/dist/generative-ui/prompt-spec.d.mts +94 -0
  42. package/dist/generative-ui/prompt-spec.d.mts.map +1 -0
  43. package/dist/generative-ui/prompt-spec.mjs +220 -0
  44. package/dist/generative-ui/prompt-spec.mjs.map +1 -0
  45. package/dist/generative-ui/prompt.cjs +10 -36
  46. package/dist/generative-ui/prompt.cjs.map +1 -1
  47. package/dist/generative-ui/prompt.d.cts +2 -1
  48. package/dist/generative-ui/prompt.d.cts.map +1 -1
  49. package/dist/generative-ui/prompt.d.mts +2 -1
  50. package/dist/generative-ui/prompt.d.mts.map +1 -1
  51. package/dist/generative-ui/prompt.mjs +12 -38
  52. package/dist/generative-ui/prompt.mjs.map +1 -1
  53. package/dist/generative-ui/schema-render.cjs +242 -0
  54. package/dist/generative-ui/schema-render.cjs.map +1 -0
  55. package/dist/generative-ui/schema-render.d.cts +44 -0
  56. package/dist/generative-ui/schema-render.d.cts.map +1 -0
  57. package/dist/generative-ui/schema-render.d.mts +44 -0
  58. package/dist/generative-ui/schema-render.d.mts.map +1 -0
  59. package/dist/generative-ui/schema-render.mjs +239 -0
  60. package/dist/generative-ui/schema-render.mjs.map +1 -0
  61. package/dist/generative-ui/types.cjs +2 -2
  62. package/dist/generative-ui/types.cjs.map +1 -1
  63. package/dist/generative-ui/types.d.cts +7 -7
  64. package/dist/generative-ui/types.d.cts.map +1 -1
  65. package/dist/generative-ui/types.d.mts +7 -7
  66. package/dist/generative-ui/types.d.mts.map +1 -1
  67. package/dist/generative-ui/types.mjs +2 -2
  68. package/dist/generative-ui/types.mjs.map +1 -1
  69. package/dist/index.cjs +20 -0
  70. package/dist/index.cjs.map +1 -1
  71. package/dist/index.d.cts +5 -1
  72. package/dist/index.d.cts.map +1 -1
  73. package/dist/index.d.mts +5 -1
  74. package/dist/index.d.mts.map +1 -1
  75. package/dist/index.mjs +5 -1
  76. package/dist/index.mjs.map +1 -1
  77. package/dist/index.umd.js +1023 -169
  78. package/dist/index.umd.js.map +1 -1
  79. package/dist/package.cjs +1 -1
  80. package/dist/package.mjs +1 -1
  81. package/package.json +1 -1
  82. package/src/__tests__/a2ui-catalog-schema.test.ts +403 -0
  83. package/src/__tests__/a2ui-envelope.test.ts +18 -13
  84. package/src/__tests__/a2ui-prompts.test.ts +47 -14
  85. package/src/__tests__/fixtures/prompt-goldens.json +354 -0
  86. package/src/__tests__/prompt-spec.test.ts +191 -0
  87. package/src/__tests__/schema-render.test.ts +245 -0
  88. package/src/a2ui-catalog-schema.ts +404 -0
  89. package/src/a2ui-envelope.ts +5 -5
  90. package/src/a2ui-prompts.ts +47 -96
  91. package/src/generative-ui/__tests__/render-ui-args.test.ts +7 -7
  92. package/src/generative-ui/__tests__/validate-operation.test.ts +19 -13
  93. package/src/generative-ui/basic-functions.ts +1 -1
  94. package/src/generative-ui/compact-schema.ts +277 -0
  95. package/src/generative-ui/index.ts +3 -0
  96. package/src/generative-ui/prompt-spec.ts +335 -0
  97. package/src/generative-ui/prompt.ts +25 -75
  98. package/src/generative-ui/schema-render.ts +374 -0
  99. package/src/generative-ui/types.ts +10 -7
  100. package/src/index.ts +13 -0
  101. package/src/utils/__tests__/conditions.test.ts +153 -43
@@ -0,0 +1,245 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { defaultGenerativeUIPromptSpec } from "../generative-ui/prompt-spec";
3
+ import type { GenerativeUISchemaSettings } from "../generative-ui/prompt-spec";
4
+ import {
5
+ applyDescriptionOverrides,
6
+ renderGenerativeUIComponentList,
7
+ renderGenerativeUISchema,
8
+ schemaCoverage,
9
+ } from "../generative-ui/schema-render";
10
+ import type { GenerativeUIManifest } from "../generative-ui/types";
11
+
12
+ const manifest: GenerativeUIManifest = {
13
+ catalogId: "test/schema@1",
14
+ components: {
15
+ Text: {
16
+ description: "Shows text",
17
+ props: {
18
+ type: "object",
19
+ properties: {
20
+ text: { type: "string", description: "The text" },
21
+ size: { enum: ["sm", "md"] },
22
+ },
23
+ required: ["text"],
24
+ },
25
+ },
26
+ Button: {
27
+ description: "A button",
28
+ props: { type: "object", properties: { label: { type: "string" } } },
29
+ events: { onClick: { description: "Action" } },
30
+ },
31
+ },
32
+ functions: {
33
+ formatCurrency: {
34
+ description: "Formats money",
35
+ parameters: { type: "object", description: "{value: number}" },
36
+ },
37
+ },
38
+ targets: [{ id: "chat", kind: "chat" }],
39
+ surfaces: {},
40
+ };
41
+
42
+ const settings = (
43
+ notation: GenerativeUISchemaSettings["notation"],
44
+ ): GenerativeUISchemaSettings => ({
45
+ notation,
46
+ propDescriptions: true,
47
+ commonProps: true,
48
+ });
49
+
50
+ describe("renderGenerativeUISchema", () => {
51
+ it("writes the lines schema that ships by default", () => {
52
+ expect(
53
+ renderGenerativeUISchema(
54
+ manifest,
55
+ defaultGenerativeUIPromptSpec().schema.markdown,
56
+ ),
57
+ ).toBe(renderGenerativeUISchema(manifest, settings("lines")));
58
+ });
59
+
60
+ it.each(["compact", "json-schema", "ts-signature", "lines"] as const)(
61
+ "covers every component and prop in %s notation",
62
+ (notation) => {
63
+ const text = renderGenerativeUISchema(manifest, settings(notation));
64
+ expect(schemaCoverage(manifest, text).missing).toEqual([]);
65
+ },
66
+ );
67
+
68
+ it("writes one signature line per component, with events", () => {
69
+ const text = renderGenerativeUISchema(manifest, settings("ts-signature"));
70
+ expect(text).toContain(
71
+ '- Text(text: string // The text, size?: "sm" | "md"): Shows text',
72
+ );
73
+ expect(text).toContain(" events: onClick(Action)");
74
+ expect(text).toContain("- formatCurrency{value: number}: Formats money");
75
+ });
76
+
77
+ it("separates a function name from parameters that are not an object", () => {
78
+ const withCalls: GenerativeUIManifest = {
79
+ ...manifest,
80
+ functions: {
81
+ clearCart: { parameters: { type: "object", properties: {} } },
82
+ setVolume: { parameters: { type: "number" } },
83
+ },
84
+ };
85
+ for (const notation of ["lines", "ts-signature"] as const) {
86
+ const text = renderGenerativeUISchema(withCalls, settings(notation));
87
+ expect(text).toContain("clearCart{}");
88
+ expect(text).toContain("setVolume(number)");
89
+ }
90
+ });
91
+
92
+ it("keeps the quotes of enum values that would read as a type or a number", () => {
93
+ const text = renderGenerativeUISchema(
94
+ {
95
+ ...manifest,
96
+ components: {
97
+ Icon: {
98
+ props: {
99
+ type: "object",
100
+ properties: {
101
+ size: { anyOf: [{ enum: ["sm", "md"] }, { type: "number" }] },
102
+ format: { enum: ["number", "currency"] },
103
+ level: { enum: ["1", "2"] },
104
+ tone: { enum: ["calm", "loud"] },
105
+ stringFlags: { enum: ["true", "false"] },
106
+ booleanFlags: { enum: [true, false] },
107
+ note: {
108
+ type: "string",
109
+ description: "First line\nIcon: not a component",
110
+ },
111
+ },
112
+ },
113
+ },
114
+ },
115
+ },
116
+ settings("lines"),
117
+ );
118
+ expect(text).toContain(' size: "sm"|"md"|number');
119
+ expect(text).toContain(' format: "number"|"currency"');
120
+ expect(text).toContain(' level: "1"|"2"');
121
+ expect(text).toContain(" tone: calm|loud");
122
+ expect(text).toContain(' stringFlags: "true"|"false"');
123
+ expect(text).toContain(" booleanFlags: true|false");
124
+ expect(text).toContain(" note: string - First line Icon: not a component");
125
+ });
126
+
127
+ it("writes the status of a deleted or failed surface in signature notation", () => {
128
+ const text = renderGenerativeUISchema(
129
+ {
130
+ ...manifest,
131
+ surfaces: {
132
+ old: { target: "chat", status: "deleted" },
133
+ bad: { target: "chat", status: "failed" },
134
+ },
135
+ },
136
+ settings("ts-signature"),
137
+ );
138
+ expect(text).toContain("- old (target chat) status: deleted");
139
+ expect(text).toContain("- bad (target chat) status: failed");
140
+ });
141
+
142
+ it("writes lines: one line per prop, bare enums, required marked *, events as action props", () => {
143
+ const text = renderGenerativeUISchema(manifest, settings("lines"));
144
+ expect(text).toContain(
145
+ "Text: Shows text\n text*: string - The text\n size: sm|md",
146
+ );
147
+ expect(text).toContain(
148
+ "Button: A button\n label: string\n onClick: action - Action",
149
+ );
150
+ expect(text).toContain("formatCurrency{value: number}: Formats money");
151
+ expect(text).not.toContain('\\"');
152
+ });
153
+
154
+ it("writes slots as componentId and childList props in lines notation", () => {
155
+ const withSlots: GenerativeUIManifest = {
156
+ ...manifest,
157
+ components: {
158
+ Card: {
159
+ props: { type: "object", properties: {} },
160
+ slots: { child: "single", children: "multiple" },
161
+ },
162
+ },
163
+ };
164
+ const text = renderGenerativeUISchema(withSlots, settings("lines"));
165
+ expect(text).toContain("Card\n child: componentId\n children: childList");
166
+ expect(text).not.toContain("slots");
167
+ });
168
+
169
+ it("leaves the prop descriptions out on request", () => {
170
+ for (const notation of [
171
+ "compact",
172
+ "json-schema",
173
+ "ts-signature",
174
+ "lines",
175
+ ] as const) {
176
+ const text = renderGenerativeUISchema(manifest, {
177
+ ...settings(notation),
178
+ propDescriptions: false,
179
+ });
180
+ expect(text).not.toContain("The text");
181
+ expect(text).toContain("Shows text");
182
+ }
183
+ });
184
+ });
185
+
186
+ describe("renderGenerativeUIComponentList", () => {
187
+ it("writes each notation for the tool guide and covers the catalog", () => {
188
+ for (const notation of [
189
+ "compact",
190
+ "json-schema",
191
+ "ts-signature",
192
+ "lines",
193
+ ] as const) {
194
+ const text = renderGenerativeUIComponentList(
195
+ manifest.components,
196
+ settings(notation),
197
+ );
198
+ expect(schemaCoverage(manifest, text).missing).toEqual([]);
199
+ }
200
+ });
201
+ });
202
+
203
+ describe("applyDescriptionOverrides", () => {
204
+ it("replaces only the named descriptions and reports unknown keys", () => {
205
+ const { manifest: next, unknown } = applyDescriptionOverrides(manifest, {
206
+ Text: "Prose in a surface",
207
+ "Text.size": "How big",
208
+ Nope: "x",
209
+ "Text.nope": "y",
210
+ });
211
+ expect(next.components.Text.description).toBe("Prose in a surface");
212
+ expect(next.components.Text.props.properties).toMatchObject({
213
+ size: { description: "How big" },
214
+ text: { description: "The text" },
215
+ });
216
+ expect(next.components.Button).toEqual(manifest.components.Button);
217
+ expect(unknown).toEqual(["Nope", "Text.nope"]);
218
+ // The input is not changed.
219
+ expect(manifest.components.Text.description).toBe("Shows text");
220
+ });
221
+ });
222
+
223
+ describe("applyDescriptionOverrides with inherited keys", () => {
224
+ it("treats __proto__ as unknown and never touches Object.prototype", () => {
225
+ const { unknown } = applyDescriptionOverrides(manifest, {
226
+ __proto__: "polluted",
227
+ "Text.__proto__": "polluted",
228
+ "Text.constructor": "polluted",
229
+ } as Record<string, string>);
230
+ expect(({} as { description?: string }).description).toBeUndefined();
231
+ expect(unknown).toEqual(
232
+ expect.arrayContaining(["Text.__proto__", "Text.constructor"]),
233
+ );
234
+ });
235
+ });
236
+
237
+ describe("schemaCoverage", () => {
238
+ it("reports a prop that the text leaves out", () => {
239
+ const text = renderGenerativeUISchema(
240
+ manifest,
241
+ settings("ts-signature"),
242
+ ).replace("size", "");
243
+ expect(schemaCoverage(manifest, text).missing).toEqual(["Text.size"]);
244
+ });
245
+ });
@@ -0,0 +1,404 @@
1
+ import { ignoreOverride, zodToJsonSchema } from "zod-to-json-schema";
2
+
3
+ /**
4
+ * Context description used to identify the A2UI component schema in
5
+ * RunAgentInput.context. Must match the constant in @ag-ui/a2ui-middleware so
6
+ * the middleware can overwrite a frontend-provided schema with a server-side one.
7
+ */
8
+ export const A2UI_SCHEMA_CONTEXT_DESCRIPTION =
9
+ "A2UI Component Schema — available components for generating UI surfaces. Use these component names and properties when creating A2UI operations.";
10
+
11
+ /** Id of the A2UI v0.9 basic catalog. */
12
+ export const A2UI_BASIC_CATALOG_ID =
13
+ "https://a2ui.org/specification/v0_9/basic_catalog.json";
14
+
15
+ type JsonSchema = Record<string, unknown>;
16
+
17
+ /**
18
+ * The parts of an `@a2ui/web_core` v0.9 `Catalog` that the serializers read.
19
+ * Typed structurally so this module does not depend on web_core, and so the
20
+ * minimal catalog-shaped objects some apps pass in still work.
21
+ */
22
+ export interface A2UICatalogSchemaSource {
23
+ readonly id: string;
24
+ readonly components: ReadonlyMap<string, { readonly schema: unknown }>;
25
+ /** A `ReadonlyMap` on a real `Catalog`; anything else is tolerated. */
26
+ readonly functions?: unknown;
27
+ readonly themeSchema?: unknown;
28
+ }
29
+
30
+ /** One entry of {@link A2UIInlineCatalogSchema.functions}. */
31
+ export interface A2UIFunctionSchema {
32
+ name: string;
33
+ description?: string;
34
+ returnType: string;
35
+ parameters: JsonSchema;
36
+ }
37
+
38
+ /**
39
+ * A2UI v0.9 inline catalog, the shape of `InlineCatalog` in
40
+ * `@a2ui/web_core/v0_9`, sent to the agent as the component schema.
41
+ */
42
+ export interface A2UIInlineCatalogSchema {
43
+ catalogId: string;
44
+ components: Record<string, JsonSchema>;
45
+ functions?: A2UIFunctionSchema[];
46
+ theme?: Record<string, JsonSchema>;
47
+ /**
48
+ * One copy of each common type the schemas reference, so every
49
+ * `common_types.json#/$defs/<Name>` ref resolves within this payload.
50
+ */
51
+ "common_types.json"?: { $defs: A2UICommonTypes };
52
+ }
53
+
54
+ /** Common type shapes keyed by their `common_types.json` `$defs` name. */
55
+ export type A2UICommonTypes = Record<string, JsonSchema>;
56
+
57
+ /**
58
+ * Serialize a catalog's Zod schemas in the A2UI v0.9 inline catalog format.
59
+ *
60
+ * Each component composes `ComponentCommon` with its own properties, matching
61
+ * the flat wire format the agent must produce:
62
+ *
63
+ * { "Column": { "allOf": [
64
+ * { "$ref": "common_types.json#/$defs/ComponentCommon" },
65
+ * { "properties": { "component": {"const":"Column"}, "gap": ..., "children": ... },
66
+ * "required": ["component"] }
67
+ * ]}}
68
+ *
69
+ * This follows `getClientCapabilities` in `@a2ui/web_core` with these
70
+ * deliberate differences:
71
+ *
72
+ * - Reused Zod schemas are inlined rather than emitted as local `$ref`s, which
73
+ * would dangle once properties move under `allOf[1]`.
74
+ * - A `REF:<ref>|<description>` marker becomes a bare `$ref`, as upstream, but
75
+ * the shape it replaced is kept once under
76
+ * `"common_types.json": { "$defs": { <Name>: ... } }`. Every
77
+ * `common_types.json#/$defs/<Name>` ref therefore resolves within the
78
+ * payload, both for agents that only see it as prompt text and for SDKs
79
+ * (such as Google's A2UI SDK used by ADK) that read the `$ref`. Each type is
80
+ * stated once rather than at every use site, which keeps the payload small.
81
+ * A use whose shape differs from the stored one keeps its shape inline next
82
+ * to the `$ref`, so the agent never sees a looser type than the client
83
+ * accepts.
84
+ * - A `REF:` marker on a schema's root only sets its description; replacing
85
+ * the root would drop every property.
86
+ * - A component's root `.describe()` is kept as the component `description`.
87
+ * - Function parameters drop `$schema` and the description already given on
88
+ * the function itself, to keep the prompt small.
89
+ */
90
+ export function extractA2UICatalogSchemas(
91
+ catalog: A2UICatalogSchemaSource,
92
+ ): A2UIInlineCatalogSchema {
93
+ // Null prototypes, so a component or type named `__proto__` is kept as an
94
+ // entry.
95
+ const components: Record<string, JsonSchema> = Object.create(null);
96
+ const commonTypes: A2UICommonTypes = Object.create(null);
97
+
98
+ for (const [name, component] of catalog.components) {
99
+ const schema = serializeA2UISchema(component.schema, commonTypes);
100
+ const properties = (schema.properties ?? {}) as Record<string, JsonSchema>;
101
+ const required = (schema.required ?? []) as string[];
102
+
103
+ components[name] = {
104
+ ...(typeof schema.description === "string"
105
+ ? { description: schema.description }
106
+ : {}),
107
+ allOf: [
108
+ { $ref: "common_types.json#/$defs/ComponentCommon" },
109
+ {
110
+ properties: { component: { const: name }, ...properties },
111
+ required: ["component", ...required],
112
+ },
113
+ ],
114
+ };
115
+ }
116
+
117
+ const functions = catalogFunctions(catalog.functions).map((fn) => {
118
+ const { description, ...parameters } = serializeA2UISchema(
119
+ fn.schema,
120
+ commonTypes,
121
+ );
122
+ return {
123
+ name: fn.name,
124
+ ...(typeof description === "string" ? { description } : {}),
125
+ returnType: fn.returnType ?? "any",
126
+ parameters,
127
+ };
128
+ });
129
+
130
+ const theme = catalog.themeSchema
131
+ ? (serializeA2UISchema(catalog.themeSchema, commonTypes).properties as
132
+ | Record<string, JsonSchema>
133
+ | undefined)
134
+ : undefined;
135
+
136
+ return {
137
+ catalogId: catalog.id,
138
+ components,
139
+ ...(functions.length > 0 ? { functions } : {}),
140
+ ...(theme ? { theme } : {}),
141
+ ...(Object.keys(commonTypes).length > 0
142
+ ? { "common_types.json": { $defs: commonTypes } }
143
+ : {}),
144
+ };
145
+ }
146
+
147
+ /**
148
+ * Build a context string describing the catalog's id and the components it
149
+ * adds beyond the basic catalog.
150
+ *
151
+ * Schemas are serialized as in {@link extractA2UICatalogSchemas}, with the
152
+ * common types they reference listed once after the components.
153
+ *
154
+ * When `options.includeSchema` is `false`, custom components are listed by name
155
+ * only and their JSON schemas are omitted.
156
+ */
157
+ export function buildA2UICatalogContextValue(
158
+ catalog: A2UICatalogSchemaSource,
159
+ basicComponentNames: ReadonlySet<string>,
160
+ options?: { includeSchema?: boolean },
161
+ ): string {
162
+ const lines: string[] = ["Available A2UI catalog:"];
163
+
164
+ if (catalog.id === A2UI_BASIC_CATALOG_ID) {
165
+ lines.push(`- ${catalog.id} (basic catalog)`);
166
+ return lines.join("\n");
167
+ }
168
+
169
+ const isSuperset = [...basicComponentNames].every((name) =>
170
+ catalog.components.has(name),
171
+ );
172
+
173
+ lines.push(`- ${catalog.id}`);
174
+ if (isSuperset) {
175
+ lines.push(
176
+ " Extends the basic catalog with all standard components plus:",
177
+ );
178
+ } else {
179
+ lines.push(" Custom catalog (does NOT include all basic components).");
180
+ lines.push(" Custom components:");
181
+ }
182
+
183
+ const commonTypes: A2UICommonTypes = Object.create(null);
184
+
185
+ for (const [name, component] of catalog.components) {
186
+ if (basicComponentNames.has(name)) continue;
187
+ if (options?.includeSchema === false) {
188
+ lines.push(` - ${name}`);
189
+ continue;
190
+ }
191
+ lines.push(` - ${name}:`);
192
+ lines.push(indented(serializeA2UISchema(component.schema, commonTypes)));
193
+ }
194
+
195
+ if (Object.keys(commonTypes).length > 0) {
196
+ lines.push(" Common types referenced above (common_types.json#/$defs):");
197
+ lines.push(indented(commonTypes));
198
+ }
199
+
200
+ return lines.join("\n");
201
+ }
202
+
203
+ /** JSON for the catalog context value, indented under a list item. */
204
+ function indented(value: unknown): string {
205
+ return ` ${JSON.stringify(value, null, 2).split("\n").join("\n ")}`;
206
+ }
207
+
208
+ /** Raw zod-to-json-schema output per Zod schema, stored as JSON text. */
209
+ const serializedSchemas = new WeakMap<object, string>();
210
+
211
+ /**
212
+ * zod-to-json-schema's own parameter type. Casting to it (rather than to
213
+ * `ZodTypeAny`) avoids a TS2589 "excessively deep" instantiation.
214
+ */
215
+ type ZodSchemaArg = Parameters<typeof zodToJsonSchema>[0];
216
+
217
+ /**
218
+ * Convert one A2UI Zod schema to JSON Schema 2019-09, inlining reused schemas
219
+ * and resolving `REF:` markers (see {@link extractA2UICatalogSchemas}). The
220
+ * shapes behind `common_types.json` refs are recorded in `commonTypes`; pass
221
+ * the same map for every schema of one payload.
222
+ *
223
+ * The raw conversion is cached per schema object as JSON text, and every call
224
+ * parses a fresh copy. The JSON round-trip, unlike structuredClone, never
225
+ * throws on values such as a function or a Vue reactive proxy in a
226
+ * `.default()`, and yields exactly what the agent receives.
227
+ */
228
+ export function serializeA2UISchema(
229
+ schema: unknown,
230
+ commonTypes: A2UICommonTypes = Object.create(null),
231
+ ): JsonSchema {
232
+ const key = typeof schema === "object" && schema !== null ? schema : null;
233
+ let serialized = key ? serializedSchemas.get(key) : undefined;
234
+ if (serialized === undefined) {
235
+ const jsonSchema = zodToJsonSchema(schema as ZodSchemaArg, {
236
+ target: "jsonSchema2019-09",
237
+ $refStrategy: "none",
238
+ // With "none", zod-to-json-schema already turns a recursive reference
239
+ // into `{}` (any), but logs a warning every time it does. Return `{}`
240
+ // here directly so re-serializing a recursive catalog stays quiet.
241
+ override: (_def, refs, seen, forceResolution) =>
242
+ seen &&
243
+ !forceResolution &&
244
+ seen.path.length < refs.currentPath.length &&
245
+ seen.path.every((part, i) => refs.currentPath[i] === part)
246
+ ? {}
247
+ : ignoreOverride,
248
+ }) as JsonSchema;
249
+ delete jsonSchema.$schema;
250
+ serialized = JSON.stringify(jsonSchema);
251
+ if (key) serializedSchemas.set(key, serialized);
252
+ }
253
+
254
+ const root = JSON.parse(serialized) as JsonSchema;
255
+ const marker = parseRefMarker(root.description);
256
+ if (marker) {
257
+ delete root.description;
258
+ if (marker.description) root.description = marker.description;
259
+ }
260
+ return resolveSubschemas(root, commonTypes);
261
+ }
262
+
263
+ /** Keywords whose value is a subschema, or an array of subschemas. */
264
+ const SUBSCHEMA_KEYWORDS = [
265
+ "items",
266
+ "additionalItems",
267
+ "additionalProperties",
268
+ "unevaluatedItems",
269
+ "unevaluatedProperties",
270
+ "contains",
271
+ "propertyNames",
272
+ "not",
273
+ "if",
274
+ "then",
275
+ "else",
276
+ "allOf",
277
+ "anyOf",
278
+ "oneOf",
279
+ "prefixItems",
280
+ ];
281
+ /** Keywords whose value maps names to subschemas. */
282
+ const SUBSCHEMA_MAP_KEYWORDS = [
283
+ "properties",
284
+ "patternProperties",
285
+ "dependentSchemas",
286
+ "$defs",
287
+ "definitions",
288
+ ];
289
+
290
+ const COMMON_TYPE_REF = /^common_types\.json#\/\$defs\/([^/]+)$/;
291
+
292
+ function isObject(value: unknown): value is JsonSchema {
293
+ return typeof value === "object" && value !== null && !Array.isArray(value);
294
+ }
295
+
296
+ /**
297
+ * Split a `REF:<ref>|<description>` marker at its first `|`, so a description
298
+ * containing `|` is kept whole. The convention comes from
299
+ * `MessageProcessor.processRefs` in `@a2ui/web_core`.
300
+ */
301
+ function parseRefMarker(
302
+ description: unknown,
303
+ ): { ref: string; description?: string } | undefined {
304
+ if (typeof description !== "string" || !description.startsWith("REF:")) {
305
+ return undefined;
306
+ }
307
+ const body = description.slice(4);
308
+ const separator = body.indexOf("|");
309
+ return separator === -1
310
+ ? { ref: body }
311
+ : { ref: body.slice(0, separator), description: body.slice(separator + 1) };
312
+ }
313
+
314
+ /**
315
+ * Resolve `REF:` markers in a schema's subschemas, innermost first, so a
316
+ * stored common type refers to the types it contains by bare `$ref` too.
317
+ *
318
+ * Only schema-valued keywords are traversed, so literal values under
319
+ * `default`, `const`, `enum` or `examples` are never rewritten.
320
+ */
321
+ function resolveSubschemas(
322
+ node: JsonSchema,
323
+ commonTypes: A2UICommonTypes,
324
+ ): JsonSchema {
325
+ const resolve = (value: unknown): unknown =>
326
+ Array.isArray(value)
327
+ ? value.map(resolve)
328
+ : isObject(value)
329
+ ? resolveRefMarker(resolveSubschemas(value, commonTypes), commonTypes)
330
+ : value;
331
+
332
+ const out: JsonSchema = { ...node };
333
+ for (const keyword of SUBSCHEMA_KEYWORDS) {
334
+ if (keyword in out) out[keyword] = resolve(out[keyword]);
335
+ }
336
+ for (const keyword of SUBSCHEMA_MAP_KEYWORDS) {
337
+ const map = out[keyword];
338
+ if (isObject(map)) {
339
+ out[keyword] = Object.fromEntries(
340
+ Object.entries(map).map(([name, child]) => [name, resolve(child)]),
341
+ );
342
+ }
343
+ }
344
+ return out;
345
+ }
346
+
347
+ /**
348
+ * Turn a node carrying a `REF:` marker into a bare `$ref`, recording the
349
+ * shape it replaced under its `common_types.json` name. A shape that differs
350
+ * from the one already recorded, or a ref outside `common_types.json`, stays
351
+ * inline next to the `$ref`.
352
+ */
353
+ function resolveRefMarker(
354
+ node: JsonSchema,
355
+ commonTypes: A2UICommonTypes,
356
+ ): JsonSchema {
357
+ const marker = parseRefMarker(node.description);
358
+ if (!marker) return node;
359
+
360
+ const { description: _marker, ...shape } = node;
361
+ const ref: JsonSchema = {
362
+ $ref: marker.ref,
363
+ ...(marker.description ? { description: marker.description } : {}),
364
+ };
365
+ const name = COMMON_TYPE_REF.exec(marker.ref)?.[1];
366
+ if (name !== undefined) {
367
+ const known = commonTypes[name];
368
+ if (known === undefined) {
369
+ commonTypes[name] = shape;
370
+ return ref;
371
+ }
372
+ if (JSON.stringify(known) === JSON.stringify(shape)) return ref;
373
+ }
374
+ return { ...ref, ...shape };
375
+ }
376
+
377
+ interface CatalogFunction {
378
+ name: string;
379
+ returnType?: string;
380
+ schema: unknown;
381
+ }
382
+
383
+ /**
384
+ * Read a catalog's functions, tolerating catalog-shaped objects whose
385
+ * `functions` is missing, a plain object or an array, and skipping entries
386
+ * without a name or schema.
387
+ */
388
+ function catalogFunctions(functions: unknown): CatalogFunction[] {
389
+ if (typeof functions !== "object" || functions === null) return [];
390
+ const entries =
391
+ functions instanceof Map
392
+ ? [...functions.values()]
393
+ : Array.isArray(functions)
394
+ ? functions
395
+ : Object.values(functions);
396
+ return entries.filter(
397
+ (fn): fn is CatalogFunction =>
398
+ typeof fn === "object" &&
399
+ fn !== null &&
400
+ typeof fn.name === "string" &&
401
+ typeof fn.schema === "object" &&
402
+ fn.schema !== null,
403
+ );
404
+ }
@@ -29,7 +29,7 @@ export const COPILOTKIT_UI_ENVELOPE_FORMAT = 3;
29
29
  /** What the client renders and calls, and how the model must write UI. */
30
30
  export interface CopilotKitUIEnvelope {
31
31
  /** The A2UI v1.0 renderer capabilities. */
32
- "v1.0": {
32
+ "1.0": {
33
33
  /**
34
34
  * The catalog that the client renders comes first, then the catalogs of
35
35
  * its `extends`. An operation can name any of them.
@@ -66,7 +66,7 @@ export interface CopilotKitUIEnvelope {
66
66
  }
67
67
 
68
68
  type InlineCatalog = NonNullable<
69
- CopilotKitUIEnvelope["v1.0"]["inlineCatalogs"]
69
+ CopilotKitUIEnvelope["1.0"]["inlineCatalogs"]
70
70
  >[number];
71
71
  type Extensions = CopilotKitUIEnvelope["metadata"]["extensions"];
72
72
 
@@ -149,7 +149,7 @@ function isInlineCatalog(value: unknown): value is InlineCatalog {
149
149
  );
150
150
  }
151
151
 
152
- function isCapabilities(value: unknown): value is CopilotKitUIEnvelope["v1.0"] {
152
+ function isCapabilities(value: unknown): value is CopilotKitUIEnvelope["1.0"] {
153
153
  return (
154
154
  isRecord(value) &&
155
155
  Array.isArray(value.supportedCatalogIds) &&
@@ -222,7 +222,7 @@ function isExtensions(value: unknown): value is Extensions {
222
222
  function isEnvelope(value: unknown): value is CopilotKitUIEnvelope {
223
223
  return (
224
224
  isRecord(value) &&
225
- isCapabilities(value["v1.0"]) &&
225
+ isCapabilities(value["1.0"]) &&
226
226
  isRecord(value.metadata) &&
227
227
  isExtensions(value.metadata.extensions)
228
228
  );
@@ -282,7 +282,7 @@ export function readCopilotKitUIEnvelope(forwardedProps: unknown) {
282
282
  * ```
283
283
  */
284
284
  export function envelopeToManifest(envelope: CopilotKitUIEnvelope) {
285
- const { supportedCatalogIds, inlineCatalogs } = envelope["v1.0"];
285
+ const { supportedCatalogIds, inlineCatalogs } = envelope["1.0"];
286
286
  const catalogId = supportedCatalogIds[0];
287
287
  const catalog = inlineCatalogs?.find(
288
288
  (entry) => entry.catalogId === catalogId,