@copilotkit/shared 1.84.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.
@@ -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
+ }
package/src/index.ts CHANGED
@@ -182,6 +182,19 @@ export {
182
182
  GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION,
183
183
  } from "./a2ui-prompts";
184
184
  export type { GenerativeUIGuideFeatures } from "./a2ui-prompts";
185
+ export {
186
+ A2UI_BASIC_CATALOG_ID,
187
+ A2UI_SCHEMA_CONTEXT_DESCRIPTION,
188
+ buildA2UICatalogContextValue,
189
+ extractA2UICatalogSchemas,
190
+ serializeA2UISchema,
191
+ } from "./a2ui-catalog-schema";
192
+ export type {
193
+ A2UICatalogSchemaSource,
194
+ A2UICommonTypes,
195
+ A2UIFunctionSchema,
196
+ A2UIInlineCatalogSchema,
197
+ } from "./a2ui-catalog-schema";
185
198
  export {
186
199
  COPILOTKIT_FORWARDED_PROPS_KEY,
187
200
  COPILOTKIT_UI_ENVELOPE_FORMAT,