@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.
- package/dist/a2ui-catalog-schema.cjs +264 -0
- package/dist/a2ui-catalog-schema.cjs.map +1 -0
- package/dist/a2ui-catalog-schema.d.cts +112 -0
- package/dist/a2ui-catalog-schema.d.cts.map +1 -0
- package/dist/a2ui-catalog-schema.d.mts +112 -0
- package/dist/a2ui-catalog-schema.d.mts.map +1 -0
- package/dist/a2ui-catalog-schema.mjs +259 -0
- package/dist/a2ui-catalog-schema.mjs.map +1 -0
- package/dist/a2ui-envelope.cjs +2 -2
- package/dist/a2ui-envelope.cjs.map +1 -1
- package/dist/a2ui-envelope.d.cts +1 -1
- package/dist/a2ui-envelope.d.cts.map +1 -1
- package/dist/a2ui-envelope.d.mts +1 -1
- package/dist/a2ui-envelope.d.mts.map +1 -1
- package/dist/a2ui-envelope.mjs +2 -2
- package/dist/a2ui-envelope.mjs.map +1 -1
- package/dist/a2ui-prompts.cjs +21 -62
- package/dist/a2ui-prompts.cjs.map +1 -1
- package/dist/a2ui-prompts.d.cts +8 -1
- package/dist/a2ui-prompts.d.cts.map +1 -1
- package/dist/a2ui-prompts.d.mts +8 -1
- package/dist/a2ui-prompts.d.mts.map +1 -1
- package/dist/a2ui-prompts.mjs +22 -62
- package/dist/a2ui-prompts.mjs.map +1 -1
- package/dist/generative-ui/basic-functions.cjs +1 -1
- package/dist/generative-ui/basic-functions.cjs.map +1 -1
- package/dist/generative-ui/basic-functions.mjs +1 -1
- package/dist/generative-ui/basic-functions.mjs.map +1 -1
- package/dist/generative-ui/compact-schema.cjs +187 -0
- package/dist/generative-ui/compact-schema.cjs.map +1 -0
- package/dist/generative-ui/compact-schema.d.cts +55 -0
- package/dist/generative-ui/compact-schema.d.cts.map +1 -0
- package/dist/generative-ui/compact-schema.d.mts +55 -0
- package/dist/generative-ui/compact-schema.d.mts.map +1 -0
- package/dist/generative-ui/compact-schema.mjs +185 -0
- package/dist/generative-ui/compact-schema.mjs.map +1 -0
- package/dist/generative-ui/prompt-spec.cjs +225 -0
- package/dist/generative-ui/prompt-spec.cjs.map +1 -0
- package/dist/generative-ui/prompt-spec.d.cts +94 -0
- package/dist/generative-ui/prompt-spec.d.cts.map +1 -0
- package/dist/generative-ui/prompt-spec.d.mts +94 -0
- package/dist/generative-ui/prompt-spec.d.mts.map +1 -0
- package/dist/generative-ui/prompt-spec.mjs +220 -0
- package/dist/generative-ui/prompt-spec.mjs.map +1 -0
- package/dist/generative-ui/prompt.cjs +10 -36
- package/dist/generative-ui/prompt.cjs.map +1 -1
- package/dist/generative-ui/prompt.d.cts +2 -1
- package/dist/generative-ui/prompt.d.cts.map +1 -1
- package/dist/generative-ui/prompt.d.mts +2 -1
- package/dist/generative-ui/prompt.d.mts.map +1 -1
- package/dist/generative-ui/prompt.mjs +12 -38
- package/dist/generative-ui/prompt.mjs.map +1 -1
- package/dist/generative-ui/schema-render.cjs +242 -0
- package/dist/generative-ui/schema-render.cjs.map +1 -0
- package/dist/generative-ui/schema-render.d.cts +44 -0
- package/dist/generative-ui/schema-render.d.cts.map +1 -0
- package/dist/generative-ui/schema-render.d.mts +44 -0
- package/dist/generative-ui/schema-render.d.mts.map +1 -0
- package/dist/generative-ui/schema-render.mjs +239 -0
- package/dist/generative-ui/schema-render.mjs.map +1 -0
- package/dist/generative-ui/types.cjs +2 -2
- package/dist/generative-ui/types.cjs.map +1 -1
- package/dist/generative-ui/types.d.cts +7 -7
- package/dist/generative-ui/types.d.cts.map +1 -1
- package/dist/generative-ui/types.d.mts +7 -7
- package/dist/generative-ui/types.d.mts.map +1 -1
- package/dist/generative-ui/types.mjs +2 -2
- package/dist/generative-ui/types.mjs.map +1 -1
- package/dist/index.cjs +20 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +5 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +5 -1
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +1023 -169
- package/dist/index.umd.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/package.json +1 -1
- package/src/__tests__/a2ui-catalog-schema.test.ts +403 -0
- package/src/__tests__/a2ui-envelope.test.ts +18 -13
- package/src/__tests__/a2ui-prompts.test.ts +47 -14
- package/src/__tests__/fixtures/prompt-goldens.json +354 -0
- package/src/__tests__/prompt-spec.test.ts +191 -0
- package/src/__tests__/schema-render.test.ts +245 -0
- package/src/a2ui-catalog-schema.ts +404 -0
- package/src/a2ui-envelope.ts +5 -5
- package/src/a2ui-prompts.ts +47 -96
- package/src/generative-ui/__tests__/render-ui-args.test.ts +7 -7
- package/src/generative-ui/__tests__/validate-operation.test.ts +19 -13
- package/src/generative-ui/basic-functions.ts +1 -1
- package/src/generative-ui/compact-schema.ts +277 -0
- package/src/generative-ui/index.ts +3 -0
- package/src/generative-ui/prompt-spec.ts +335 -0
- package/src/generative-ui/prompt.ts +25 -75
- package/src/generative-ui/schema-render.ts +374 -0
- package/src/generative-ui/types.ts +10 -7
- package/src/index.ts +13 -0
- package/src/utils/__tests__/conditions.test.ts +153 -43
package/dist/index.umd.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
(function(global, factory) {
|
|
2
|
-
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('graphql'), require('zod'), require('uuid'), require('partial-json'), require('@ag-ui/client')) :
|
|
3
|
-
typeof define === 'function' && define.amd ? define(['exports', 'graphql', 'zod', 'uuid', 'partial-json', '@ag-ui/client'], factory) :
|
|
4
|
-
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitShared = {}), global.GraphQL,global.Zod,global.UUID,global.PartialJSON,global.AgUIClient));
|
|
5
|
-
})(this, function(exports, graphql, zod, uuid, partial_json, _ag_ui_client) {
|
|
2
|
+
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('graphql'), require('zod'), require('uuid'), require('partial-json'), require('@ag-ui/client'), require('zod-to-json-schema')) :
|
|
3
|
+
typeof define === 'function' && define.amd ? define(['exports', 'graphql', 'zod', 'uuid', 'partial-json', '@ag-ui/client', 'zod-to-json-schema'], factory) :
|
|
4
|
+
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.CopilotKitShared = {}), global.GraphQL,global.Zod,global.UUID,global.PartialJSON,global.AgUIClient,global.zod_to_json_schema));
|
|
5
|
+
})(this, function(exports, graphql, zod, uuid, partial_json, _ag_ui_client, zod_to_json_schema) {
|
|
6
6
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
7
7
|
//#region \0rolldown/runtime.js
|
|
8
8
|
var __create = Object.create;
|
|
@@ -815,7 +815,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
815
815
|
|
|
816
816
|
//#endregion
|
|
817
817
|
//#region src/utils/inspector-metadata.ts
|
|
818
|
-
function isRecord$
|
|
818
|
+
function isRecord$3(value) {
|
|
819
819
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
820
820
|
try {
|
|
821
821
|
const prototype = Object.getPrototypeOf(value);
|
|
@@ -838,7 +838,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
838
838
|
return parsed.length > 0 ? parsed : void 0;
|
|
839
839
|
}
|
|
840
840
|
function parseIdentity(value) {
|
|
841
|
-
if (!isRecord$
|
|
841
|
+
if (!isRecord$3(value)) return;
|
|
842
842
|
const organizationName = parseNonBlankString(value.organizationName);
|
|
843
843
|
const projectName = parseNonBlankString(value.projectName);
|
|
844
844
|
if (organizationName === void 0 || projectName === void 0) return;
|
|
@@ -848,7 +848,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
848
848
|
};
|
|
849
849
|
}
|
|
850
850
|
function parsePlan(value) {
|
|
851
|
-
if (!isRecord$
|
|
851
|
+
if (!isRecord$3(value)) return;
|
|
852
852
|
const code = parseNonBlankString(value.code);
|
|
853
853
|
const label = parseNonBlankString(value.label);
|
|
854
854
|
if (code === void 0 || label === void 0) return;
|
|
@@ -858,7 +858,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
858
858
|
};
|
|
859
859
|
}
|
|
860
860
|
function parseLicense(value) {
|
|
861
|
-
if (!isRecord$
|
|
861
|
+
if (!isRecord$3(value)) return;
|
|
862
862
|
switch (value.state) {
|
|
863
863
|
case "valid":
|
|
864
864
|
case "none":
|
|
@@ -893,7 +893,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
893
893
|
return isSafeDashboardUrl(parsed) ? url : void 0;
|
|
894
894
|
}
|
|
895
895
|
function parseAction(value) {
|
|
896
|
-
if (!isRecord$
|
|
896
|
+
if (!isRecord$3(value)) return;
|
|
897
897
|
const kind = parseActionKind(value.kind);
|
|
898
898
|
const url = parseSafeActionUrl(value.url);
|
|
899
899
|
if (kind === void 0 || url === void 0) return;
|
|
@@ -906,7 +906,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
906
906
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
907
907
|
}
|
|
908
908
|
function parseUsageLimit(value) {
|
|
909
|
-
if (!isRecord$
|
|
909
|
+
if (!isRecord$3(value)) return;
|
|
910
910
|
if (value.kind === "finite") {
|
|
911
911
|
if (typeof value.value !== "number" || !Number.isSafeInteger(value.value) || value.value < 1) return;
|
|
912
912
|
return {
|
|
@@ -918,7 +918,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
918
918
|
if (value.kind === "unknown") return { kind: "unknown" };
|
|
919
919
|
}
|
|
920
920
|
function parseUsage(value) {
|
|
921
|
-
if (!isRecord$
|
|
921
|
+
if (!isRecord$3(value)) return;
|
|
922
922
|
const limit = parseUsageLimit(value.limit);
|
|
923
923
|
const used = value.used;
|
|
924
924
|
if (!isFiniteNonnegativeInteger(used) || limit === void 0) return;
|
|
@@ -939,7 +939,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
939
939
|
* top-level payload.
|
|
940
940
|
*/
|
|
941
941
|
function parseInspectorMetadataV1(value) {
|
|
942
|
-
if (!isRecord$
|
|
942
|
+
if (!isRecord$3(value) || value.schemaVersion !== 1) return;
|
|
943
943
|
const identity = parseIdentity(value.identity);
|
|
944
944
|
const plan = parsePlan(value.plan);
|
|
945
945
|
const license = parseLicense(value.license);
|
|
@@ -2323,7 +2323,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2323
2323
|
|
|
2324
2324
|
//#endregion
|
|
2325
2325
|
//#region package.json
|
|
2326
|
-
var version = "1.
|
|
2326
|
+
var version = "1.84.1";
|
|
2327
2327
|
|
|
2328
2328
|
//#endregion
|
|
2329
2329
|
//#region src/generative-ui/basic-functions.ts
|
|
@@ -2451,7 +2451,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2451
2451
|
*/
|
|
2452
2452
|
const COPILOTKIT_FUNCTIONS = rendererOnly({
|
|
2453
2453
|
calc: {
|
|
2454
|
-
description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), comparisons, && || !, cond ? a : b, min max round floor ceil abs, 'text' + name",
|
|
2454
|
+
description: "The value of an arithmetic expression over the other args, by name: + - * / % ( ), x ^ y (power), comparisons, && || !, cond ? a : b, min max round floor ceil abs pow sqrt exp ln log10, the constants pi and e, 'text' + name",
|
|
2455
2455
|
parameters: "{ expression: string; [name: string]: number | string | boolean }",
|
|
2456
2456
|
returnType: "any",
|
|
2457
2457
|
extension: true
|
|
@@ -2494,7 +2494,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2494
2494
|
//#endregion
|
|
2495
2495
|
//#region src/generative-ui/is-record.ts
|
|
2496
2496
|
/** True for a plain object: not null, not an array. Internal, not exported. */
|
|
2497
|
-
function isRecord(value) {
|
|
2497
|
+
function isRecord$2(value) {
|
|
2498
2498
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2499
2499
|
}
|
|
2500
2500
|
|
|
@@ -2540,7 +2540,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2540
2540
|
const visit = (node) => {
|
|
2541
2541
|
var _marked;
|
|
2542
2542
|
if (Array.isArray(node)) return node.map(visit);
|
|
2543
|
-
if (!isRecord(node)) return node;
|
|
2543
|
+
if (!isRecord$2(node)) return node;
|
|
2544
2544
|
const reference = (_marked = marked(node.description, A2UI_COMPONENT_ID_MARK, A2UI_COMPONENT_ID_REF)) !== null && _marked !== void 0 ? _marked : marked(node.description, A2UI_CHILD_LIST_MARK, A2UI_CHILD_LIST_REF);
|
|
2545
2545
|
if (reference) return reference;
|
|
2546
2546
|
return Object.fromEntries(Object.entries(node).map(([key, value]) => [key, visit(value)]));
|
|
@@ -2567,12 +2567,12 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2567
2567
|
});
|
|
2568
2568
|
};
|
|
2569
2569
|
const visit = (node, path) => {
|
|
2570
|
-
if (!isRecord(node)) return;
|
|
2570
|
+
if (!isRecord$2(node)) return;
|
|
2571
2571
|
const kind = childRefKind(node);
|
|
2572
2572
|
if (kind) return add(path, kind);
|
|
2573
2573
|
for (const list of [node.anyOf, node.oneOf]) {
|
|
2574
2574
|
if (!Array.isArray(list) || list.length === 0) continue;
|
|
2575
|
-
const kinds = list.map((variant) => isRecord(variant) ? childRefKind(variant) : void 0);
|
|
2575
|
+
const kinds = list.map((variant) => isRecord$2(variant) ? childRefKind(variant) : void 0);
|
|
2576
2576
|
const [first] = kinds;
|
|
2577
2577
|
if (first && kinds.every((k) => k === first)) add(path, first);
|
|
2578
2578
|
else if (kinds.every((k) => k === void 0)) {
|
|
@@ -2582,8 +2582,8 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2582
2582
|
}
|
|
2583
2583
|
}
|
|
2584
2584
|
if (Array.isArray(node.allOf)) node.allOf.forEach((variant) => visit(variant, path));
|
|
2585
|
-
if (isRecord(node.properties)) for (const [key, value] of Object.entries(node.properties)) visit(value, [...path, key]);
|
|
2586
|
-
if (isRecord(node.items)) visit(node.items, [...path, "*"]);
|
|
2585
|
+
if (isRecord$2(node.properties)) for (const [key, value] of Object.entries(node.properties)) visit(value, [...path, key]);
|
|
2586
|
+
if (isRecord$2(node.items)) visit(node.items, [...path, "*"]);
|
|
2587
2587
|
};
|
|
2588
2588
|
visit(schema, []);
|
|
2589
2589
|
return refs;
|
|
@@ -2598,7 +2598,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2598
2598
|
const collect = (value) => {
|
|
2599
2599
|
if (typeof value === "string") ids.push(value);
|
|
2600
2600
|
else if (Array.isArray(value)) value.forEach((id) => typeof id === "string" && ids.push(id));
|
|
2601
|
-
else if (isRecord(value) && typeof value.componentId === "string") ids.push(value.componentId);
|
|
2601
|
+
else if (isRecord$2(value) && typeof value.componentId === "string") ids.push(value.componentId);
|
|
2602
2602
|
};
|
|
2603
2603
|
const visit = (value, path) => {
|
|
2604
2604
|
if (path.length === 0) return collect(value);
|
|
@@ -2607,7 +2607,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2607
2607
|
if (Array.isArray(value)) value.forEach((item) => visit(item, rest));
|
|
2608
2608
|
return;
|
|
2609
2609
|
}
|
|
2610
|
-
if (isRecord(value) && Object.prototype.hasOwnProperty.call(value, head)) visit(value[head], rest);
|
|
2610
|
+
if (isRecord$2(value) && Object.prototype.hasOwnProperty.call(value, head)) visit(value[head], rest);
|
|
2611
2611
|
};
|
|
2612
2612
|
for (const ref of refs) visit(component, ref.path);
|
|
2613
2613
|
return ids;
|
|
@@ -2618,13 +2618,13 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2618
2618
|
* at render time.
|
|
2619
2619
|
*/
|
|
2620
2620
|
function hasBoundChildRef(component, refs) {
|
|
2621
|
-
const isDynamic = (value) => isRecord(value) && ("@path" in value || "@call" in value);
|
|
2621
|
+
const isDynamic = (value) => isRecord$2(value) && ("@path" in value || "@call" in value);
|
|
2622
2622
|
const visit = (value, path) => {
|
|
2623
2623
|
if (isDynamic(value)) return true;
|
|
2624
2624
|
if (path.length === 0) return false;
|
|
2625
2625
|
const [head, ...rest] = path;
|
|
2626
2626
|
if (head === "*") return Array.isArray(value) && value.some((item) => visit(item, rest));
|
|
2627
|
-
return isRecord(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
|
|
2627
|
+
return isRecord$2(value) && Object.prototype.hasOwnProperty.call(value, head) && visit(value[head], rest);
|
|
2628
2628
|
};
|
|
2629
2629
|
return refs.some((ref) => visit(component, ref.path));
|
|
2630
2630
|
}
|
|
@@ -2640,7 +2640,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2640
2640
|
if (!Array.isArray(value)) return value;
|
|
2641
2641
|
return value.map((item) => mapAtChildRef(item, rest, replace));
|
|
2642
2642
|
}
|
|
2643
|
-
if (!isRecord(value) || !Object.prototype.hasOwnProperty.call(value, head)) return value;
|
|
2643
|
+
if (!isRecord$2(value) || !Object.prototype.hasOwnProperty.call(value, head)) return value;
|
|
2644
2644
|
return {
|
|
2645
2645
|
...value,
|
|
2646
2646
|
[head]: mapAtChildRef(value[head], rest, replace)
|
|
@@ -2650,7 +2650,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2650
2650
|
//#endregion
|
|
2651
2651
|
//#region src/generative-ui/types.ts
|
|
2652
2652
|
/** A2UI protocol version used on the wire. */
|
|
2653
|
-
const A2UI_VERSION = "
|
|
2653
|
+
const A2UI_VERSION = "1.0";
|
|
2654
2654
|
/** Activity type of a generated surface message. */
|
|
2655
2655
|
const GENERATIVE_UI_ACTIVITY_TYPE = "generative-ui-surface";
|
|
2656
2656
|
/** Activity type of a function call that the agent asks the client to run. */
|
|
@@ -2714,7 +2714,7 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2714
2714
|
* @example
|
|
2715
2715
|
* ```ts
|
|
2716
2716
|
* toA2UIActionMessage({ name: "buy", surfaceId: "s1", componentId: "b", context: { sku: "a" } });
|
|
2717
|
-
* // { version: "
|
|
2717
|
+
* // { version: "1.0", action: { name: "buy", surfaceId: "s1", sourceComponentId: "b", timestamp: "2026-…", context: { sku: "a" } } }
|
|
2718
2718
|
* ```
|
|
2719
2719
|
*/
|
|
2720
2720
|
function toA2UIActionMessage(event) {
|
|
@@ -2732,6 +2732,222 @@ ${getSeeMoreMarkdown(troubleshootingLink)}`;
|
|
|
2732
2732
|
};
|
|
2733
2733
|
}
|
|
2734
2734
|
|
|
2735
|
+
//#endregion
|
|
2736
|
+
//#region src/generative-ui/prompt-spec.ts
|
|
2737
|
+
/**
|
|
2738
|
+
* When UI helps the user, for both transports: a light nudge to reach for UI
|
|
2739
|
+
* where it conveys the answer better than prose, and to stay in prose
|
|
2740
|
+
* otherwise.
|
|
2741
|
+
*/
|
|
2742
|
+
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.";
|
|
2743
|
+
/**
|
|
2744
|
+
* When and how to show UI in the markdown transport: the answer first, a
|
|
2745
|
+
* map from tasks to components, real interactivity, honest data and
|
|
2746
|
+
* restraint. Measured with tools/genui-eval against the earlier text.
|
|
2747
|
+
*/
|
|
2748
|
+
const GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW = "Answer first: lead with the result or the recommendation in a sentence or two, then show the UI that supports it.\n\nShow UI whenever it makes the answer easier to use, and do not wait for the user to ask for a chart, a calculator or a form. A markdown table or list is not enough when the user would want to change a value, see a shape or a trend, or pick between options. Reply in prose alone only for a greeting or thanks, a one-line fact, a definition, code, or a text the user asked you to write (an email, a message, an update).\n\nMatch the UI to the task:\n- A number that depends on inputs (a price, a loan or mortgage, savings, a conversion, a recipe for N people): a calculator, always. Bind a Slider, TextField or SegmentedControl to the data model and compute the results with calc, so they follow the input. calc has powers, roots and logs, so every input can be a control, also a rate or a term: a monthly payment is rate == 0 ? loan / (years * 12) : loan * (rate / 1200) / (1 - (1 + rate / 1200) ^ -(years * 12)).\n- Choosing between options that share attributes: a Table, or a Grid of EntityCards when each option has a photo, a price or a rating. Plans or offers to pick from: one card each, ending with a Button to choose it.\n- Items with a status, a category or a level: a Badge on each item.\n- Shares, patterns, trends, change over time: a Chart.\n- Places, routes, what is nearby: a Map with the places as markers, next to cards or a List with their details.\n- A sequence or a history: a timeline surface, a List of dated items with a Badge for each era, not a markdown list.\n- How something works, a process, a structure: a diagram drawn with Svg. Draw the real objects as shapes (a cylinder and its piston, a leaf, a server), with arrows for movement or flow and short labels. Labelled boxes of text are not a diagram.\n- A formula or an equation: Math. Solving a math problem: the steps in prose with Math, plus a Chart of the function and a Slider to try values of x.\n- A broad topic (\"tell me about X\"): an overview surface with the key facts, an Image, and a Table or Chart that compares the parts, ending with FollowUp suggestions for what to ask next.\n- Options to choose from (algorithms, products, plans): a Table, plus a SegmentedControl or Select that shows the best option for the user's situation.\n- Research or evidence: a Table of the studies, with a Citation for each source.\n- Things whose look matters (places, products, food): an Image, or the image of an EntityCard.\n- Several inputs, or an action with a side effect (sign-up, booking, contact, scheduling): a Form with fields, checks and a Button. A field with a fixed list of answers (a team size, a topic, a country) is a Select.\n- Practice and learning: a quiz with RadioGroup or ChoicePicker that gives feedback as soon as the user answers, or FlashcardFlip cards. Ask in one language and offer the answers in the other.\n- A plan to follow or tick off: CheckBox items with a progress count that updates as items are ticked.\n- Parallel views (the days of a trip, alternatives): Tabs.\n\nMake interactivity real:\n- Expose the few inputs that change the outcome, with sensible defaults from what the user said.\n- Bind every control to the data model and derive what depends on it with calc or formatString. Controls about the same scenario share the same paths.\n- Every Button does what its label says, and a Link takes \"href\".\n- Never pretend an action happened. For booking, sending or subscribing, show the form and let the user confirm, and say that nothing is sent until they do.\n\nKeep the data honest:\n- Use the facts, places, photos and numbers of the app context when it has them. Never invent prices, availability, ratings, sources or image URLs.\n- Label estimates and assumptions, keep units and currencies consistent, and cite the sources you rely on with Citation.\n\nDesign with restraint:\n- One clear surface beats several. Put the most important result first and make it stand out with a Title, or a Text with size \"lg\". Text sizes go from \"3xs\" to \"lg\"; there is no \"xl\" or \"2xl\".\n- Keep explanations in prose around the surface, not inside it. No decoration, and no surface that only holds text.\n\nBefore you reply, check: does the UI answer the actual question, does every control do something, are the numbers right?";
|
|
2749
|
+
/** The prompts that ship, as a spec. A new object on each call. */
|
|
2750
|
+
/**
|
|
2751
|
+
* The standard components that the default markdown guide names. A guide
|
|
2752
|
+
* line that names one the catalog lacks is left out of the prompt.
|
|
2753
|
+
*/
|
|
2754
|
+
const GUIDE_COMPONENTS = new Set([
|
|
2755
|
+
"Grid",
|
|
2756
|
+
"Card",
|
|
2757
|
+
"Tabs",
|
|
2758
|
+
"Title",
|
|
2759
|
+
"Text",
|
|
2760
|
+
"Label",
|
|
2761
|
+
"Badge",
|
|
2762
|
+
"Math",
|
|
2763
|
+
"Link",
|
|
2764
|
+
"Button",
|
|
2765
|
+
"Form",
|
|
2766
|
+
"TextField",
|
|
2767
|
+
"Select",
|
|
2768
|
+
"CheckBox",
|
|
2769
|
+
"RadioGroup",
|
|
2770
|
+
"Slider",
|
|
2771
|
+
"SegmentedControl",
|
|
2772
|
+
"ChoicePicker",
|
|
2773
|
+
"FlashcardFlip",
|
|
2774
|
+
"Table",
|
|
2775
|
+
"List",
|
|
2776
|
+
"Chart",
|
|
2777
|
+
"Map",
|
|
2778
|
+
"Image",
|
|
2779
|
+
"Svg",
|
|
2780
|
+
"Citation",
|
|
2781
|
+
"FollowUp",
|
|
2782
|
+
"EntityCard"
|
|
2783
|
+
]);
|
|
2784
|
+
function defaultGenerativeUIPromptSpec() {
|
|
2785
|
+
return {
|
|
2786
|
+
markdown: {
|
|
2787
|
+
intro: "You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.",
|
|
2788
|
+
whenToShow: GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW,
|
|
2789
|
+
rules: [
|
|
2790
|
+
"Write explanations as normal markdown prose outside the fences.",
|
|
2791
|
+
"Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.",
|
|
2792
|
+
"Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target limits its components, its surfaces can use only those components.",
|
|
2793
|
+
"Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.",
|
|
2794
|
+
"Keep each operation whole on its line.",
|
|
2795
|
+
"Give every operation \"version\":\"1.0\".",
|
|
2796
|
+
"Start a surface with one createSurface. Put all the initial data in \"dataModel\" and the \"root\" component in \"components\". Then write the children in updateComponents lines, so that they show while you write:\n ```a2ui\n {\"version\":\"1.0\",\"createSurface\":{\"surfaceId\":\"plan-picker\",\"dataModel\":{ ...initial data... },\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"seats\",\"pick\"]}]}}\n {\"version\":\"1.0\",\"updateComponents\":{\"surfaceId\":\"plan-picker\",\"components\":[ ...the children... ]}}\n ```",
|
|
2797
|
+
"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.",
|
|
2798
|
+
"Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.",
|
|
2799
|
+
"Send every component you reference in the same reply. If a surface gets long, make it smaller rather than leave components out.",
|
|
2800
|
+
"Use unique ids. Do not make cycles. A component cannot be its own child.",
|
|
2801
|
+
"Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
|
|
2802
|
+
"Close each component with exactly one }, also when its last prop is a list: {\"id\":\"map\",\"component\":\"Map\",\"markers\":[{\"label\":\"A\",\"lat\":48.2,\"lng\":16.4}]}. A createSurface or updateComponents line ends with }]}} : the last component, the \"components\" list, the operation, the line.",
|
|
2803
|
+
"A prop that holds a call closes with }} : its \"args\", then the call. The component closes with its own single } after its last prop. With a prop after the call: {\"id\":\"count\",\"component\":\"Text\",\"text\":{\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} items\"}},\"size\":\"lg\"}. With the call last: {\"id\":\"count\",\"component\":\"Text\",\"size\":\"lg\",\"text\":{\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} items\"}}}.",
|
|
2804
|
+
"Deep props close every level they open, then the component closes with its own }. An event with a context: \"onSubmit\":{\"event\":{\"name\":\"send\",\"context\":{\"email\":{\"@path\":\"/email\"}}}}} ends with }}}}} : the path, \"context\", \"event\", the prop, the component. A Table: \"rows\":[[\"Mon\",\"9°C\"],[\"Tue\",\"7°C\"]]} ends with ]]} : the last row, \"rows\", the component, and nothing more. A list item with a call: \"items\":[{\"label\":{\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} cups\"}}}]} ends with }}}]} : \"args\", the call, the item, the list, the component.",
|
|
2805
|
+
"Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
|
|
2806
|
+
"A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component. \"live\":\"polite\" goes only inside \"accessibility\" ({\"accessibility\":{\"live\":\"polite\"}}), only on text that changes by itself, never as a prop of the component.",
|
|
2807
|
+
"Use only the components, props, events, and slots in the schema. A component marked +common also takes every common prop. A component with a prop that is not in its schema, or a value outside its enum, is dropped with everything inside it, so check each prop against the schema.",
|
|
2808
|
+
"Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
|
|
2809
|
+
"A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions in the schema. Write a literal when the value never changes.",
|
|
2810
|
+
"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.",
|
|
2811
|
+
"${...} 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.",
|
|
2812
|
+
"Inside ${...}, close every ( you open, and write no operators and no ?: : compute with calc. To round a computed number, round inside calc instead of wrapping it in formatNumber: ${calc(expression: 'round(servings * 0.5 * 10) / 10', servings: /servings)} cups. calc has ^ (power), sqrt, exp and ln.",
|
|
2813
|
+
"To show one of two texts, let calc choose: \"text\":{\"@call\":\"calc\",\"args\":{\"expression\":\"billing == 'yearly' ? 'per year' : 'per month'\",\"billing\":{\"@path\":\"/billing\"}}}.",
|
|
2814
|
+
"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.",
|
|
2815
|
+
"Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
|
|
2816
|
+
"The value of a ChoicePicker is a list of strings, also for one choice. SegmentedControl, RadioGroup and Select take one string. Option values are always strings: for a yes/no choice use \"yes\" and \"no\", not true and false.",
|
|
2817
|
+
"To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".",
|
|
2818
|
+
"Set \"value\":null to delete the key at \"path\".",
|
|
2819
|
+
{
|
|
2820
|
+
when: ["events"],
|
|
2821
|
+
items: ["Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.", "Put the action of a Button in its \"onClick\": {\"event\":{...}} to send it back to you, or {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"...\"}}}. Never write \"event\" or \"functionCall\" as a prop of its own."]
|
|
2822
|
+
},
|
|
2823
|
+
{
|
|
2824
|
+
when: ["events", "functions"],
|
|
2825
|
+
items: ["Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call."]
|
|
2826
|
+
},
|
|
2827
|
+
{
|
|
2828
|
+
when: ["events", "noFunctions"],
|
|
2829
|
+
items: ["Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call."]
|
|
2830
|
+
},
|
|
2831
|
+
{
|
|
2832
|
+
when: ["events"],
|
|
2833
|
+
items: [
|
|
2834
|
+
"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\".",
|
|
2835
|
+
"To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.",
|
|
2836
|
+
"A button or other event prop without an event or functionCall does nothing."
|
|
2837
|
+
]
|
|
2838
|
+
},
|
|
2839
|
+
{
|
|
2840
|
+
when: ["checks"],
|
|
2841
|
+
items: ["Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks."]
|
|
2842
|
+
},
|
|
2843
|
+
"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\"}].",
|
|
2844
|
+
{
|
|
2845
|
+
when: ["templates"],
|
|
2846
|
+
items: [
|
|
2847
|
+
"To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.",
|
|
2848
|
+
"Inside a template, paths are relative to the item (\"name\", not \"/name\").",
|
|
2849
|
+
"Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}."
|
|
2850
|
+
]
|
|
2851
|
+
},
|
|
2852
|
+
"Updating a component replaces all of its props. Send every prop again.",
|
|
2853
|
+
"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.",
|
|
2854
|
+
"Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.",
|
|
2855
|
+
{
|
|
2856
|
+
when: ["agentCalls"],
|
|
2857
|
+
items: [
|
|
2858
|
+
"To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.",
|
|
2859
|
+
"Give every callRendererFunction a new functionCallId. Call only a function that the schema marks UI or agent, or agent only; a function with no mark is for the UI only. A function marked agent only is only for callRendererFunction: do not bind an event to it.",
|
|
2860
|
+
"The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.",
|
|
2861
|
+
"Do not guess the result of a callRendererFunction. Wait for the developer message."
|
|
2862
|
+
]
|
|
2863
|
+
},
|
|
2864
|
+
"The schema lists the surfaces that already exist. \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.",
|
|
2865
|
+
"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.",
|
|
2866
|
+
"Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
|
|
2867
|
+
"Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
|
|
2868
|
+
"Never wrap the whole reply in a fence."
|
|
2869
|
+
]
|
|
2870
|
+
},
|
|
2871
|
+
tool: {
|
|
2872
|
+
intro: `Call \`${GENERATIVE_UI_RENDER_TOOL}\` to show UI. Arguments: \`target\` first, then \`operations\` (A2UI v1.0 operations, applied in order).`,
|
|
2873
|
+
whenToShow: GENERATIVE_UI_WHEN_TO_SHOW,
|
|
2874
|
+
operations: [
|
|
2875
|
+
"{\"version\":\"1.0\",\"createSurface\":{\"surfaceId\":\"<new id>\",\"dataModel\":{...},\"components\":[{\"id\":\"root\",\"component\":\"<Name>\",\"children\":[\"<child id>\"]}]}}: the first operation of a new surface. \"dataModel\" and \"components\" are optional.",
|
|
2876
|
+
"{\"version\":\"1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
|
|
2877
|
+
"{\"version\":\"1.0\",\"updateDataModel\":{\"surfaceId\":\"<id>\",\"path\":\"/some/path\",\"value\":<json>}}: set the value at \"path\". Always give \"value\". \"value\":null deletes the key at \"path\".",
|
|
2878
|
+
"{\"version\":\"1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
|
|
2879
|
+
{
|
|
2880
|
+
when: ["agentCalls"],
|
|
2881
|
+
items: ["{\"version\":\"1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."]
|
|
2882
|
+
}
|
|
2883
|
+
],
|
|
2884
|
+
rules: [
|
|
2885
|
+
"Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
|
|
2886
|
+
"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.",
|
|
2887
|
+
"Stream progressively: put the initial data in \"dataModel\" and the root in \"components\" of the createSurface operation, then send one updateComponents operation per child, so the UI appears while you are still writing. The root must already list the ids of its children in its slot props (for example \"children\":[\"card-1\",\"card-2\"]), even though the children come later. A component that no slot references is never shown.",
|
|
2888
|
+
"Updating a component replaces all of its props, so resend every prop.",
|
|
2889
|
+
"Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
|
|
2890
|
+
{
|
|
2891
|
+
when: ["events", "functions"],
|
|
2892
|
+
items: ["Event props take an action. {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}} runs an app function in the browser immediately, and you are not told about it. {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\". Only call functions listed below."]
|
|
2893
|
+
},
|
|
2894
|
+
{
|
|
2895
|
+
when: ["events", "noFunctions"],
|
|
2896
|
+
items: ["Event props take an action: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\"."]
|
|
2897
|
+
},
|
|
2898
|
+
"To show a different view, create a new surface with a new surfaceId (for example, a checkout form after a cart summary). Update an existing surface only when the user asks to change that same view: then do not send createSurface, use its surfaceId, and pass its existing target. Never reuse an earlier chat surface for a different view, because that replaces the earlier UI and anything the user typed into it.",
|
|
2899
|
+
"Never use a surfaceId again, also after deleteSurface.",
|
|
2900
|
+
"A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Only call functions listed below. formatString interpolates ${/path} and ${fn(arg: value)} in its value.",
|
|
2901
|
+
"${...} 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\"}}}.",
|
|
2902
|
+
"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
|
|
2903
|
+
{
|
|
2904
|
+
when: ["checks"],
|
|
2905
|
+
items: ["Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks."]
|
|
2906
|
+
},
|
|
2907
|
+
{
|
|
2908
|
+
when: ["templates"],
|
|
2909
|
+
items: ["To repeat a component for each item of a list, give a multiple slot a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}. Inside the template, paths are relative to the item (\"name\", not \"/name\"). {\"@call\":\"@index\"} gives the position of the item, from 0; {\"@call\":\"@index\",\"args\":{\"offset\":1}} counts from 1."]
|
|
2910
|
+
},
|
|
2911
|
+
{
|
|
2912
|
+
when: ["agentCalls"],
|
|
2913
|
+
items: ["Give every callRendererFunction a new functionCallId. Call only a function marked (UI or agent) or (agent only); a function with no mark is for the UI only. A function marked (agent only) is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you in a new turn, as a developer message: {\"version\":\"1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Do not wait for the result in this reply, and do not guess it."]
|
|
2914
|
+
}
|
|
2915
|
+
]
|
|
2916
|
+
},
|
|
2917
|
+
schema: {
|
|
2918
|
+
markdown: {
|
|
2919
|
+
notation: "lines",
|
|
2920
|
+
propDescriptions: true,
|
|
2921
|
+
commonProps: true
|
|
2922
|
+
},
|
|
2923
|
+
tool: {
|
|
2924
|
+
notation: "json-schema",
|
|
2925
|
+
propDescriptions: true,
|
|
2926
|
+
commonProps: false
|
|
2927
|
+
}
|
|
2928
|
+
},
|
|
2929
|
+
descriptions: {}
|
|
2930
|
+
};
|
|
2931
|
+
}
|
|
2932
|
+
/** The rules of `items` whose block conditions hold, in order. */
|
|
2933
|
+
function selectPromptItems(items, features) {
|
|
2934
|
+
return items.flatMap((item) => typeof item === "string" ? [item] : item.when.every((feature) => features[feature]) ? item.items : []);
|
|
2935
|
+
}
|
|
2936
|
+
/**
|
|
2937
|
+
* The prompt features of a run, from the guide features of its manifest
|
|
2938
|
+
* (`generativeUIGuideFeatures`).
|
|
2939
|
+
*/
|
|
2940
|
+
function generativeUIPromptFeatures(guide) {
|
|
2941
|
+
return {
|
|
2942
|
+
functions: guide.functions,
|
|
2943
|
+
noFunctions: !guide.functions,
|
|
2944
|
+
events: guide.events,
|
|
2945
|
+
templates: guide.templates,
|
|
2946
|
+
checks: guide.checks,
|
|
2947
|
+
agentCalls: guide.functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS
|
|
2948
|
+
};
|
|
2949
|
+
}
|
|
2950
|
+
|
|
2735
2951
|
//#endregion
|
|
2736
2952
|
//#region src/a2ui-prompts.ts
|
|
2737
2953
|
/**
|
|
@@ -2847,12 +3063,6 @@ Design principles:
|
|
|
2847
3063
|
action context should reference the same paths to capture user input.
|
|
2848
3064
|
|
|
2849
3065
|
Use the SAME surfaceId as the main surface. Match action names to button action event names.`;
|
|
2850
|
-
/**
|
|
2851
|
-
* When UI helps the user, for both transports: a light nudge to reach for UI
|
|
2852
|
-
* where it conveys the answer better than prose, and to stay in prose
|
|
2853
|
-
* otherwise.
|
|
2854
|
-
*/
|
|
2855
|
-
const GENERATIVE_UI_WHEN_TO_SHOW = "Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.";
|
|
2856
3066
|
/** Description of the context entry that carries `GENERATIVE_UI_MARKDOWN_GUIDELINES`. */
|
|
2857
3067
|
const GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = "Generative UI markdown guide: how to write UI surfaces inside ```a2ui code fences in a normal markdown reply.";
|
|
2858
3068
|
/**
|
|
@@ -2898,6 +3108,7 @@ Use the SAME surfaceId as the main surface. Match action names to button action
|
|
|
2898
3108
|
return Object.values(node).some(hasChildList);
|
|
2899
3109
|
};
|
|
2900
3110
|
return {
|
|
3111
|
+
components: Object.keys(manifest.components),
|
|
2901
3112
|
functions: Object.keys(manifest.functions).some((name) => !isA2UIBasicFunction(name)),
|
|
2902
3113
|
events: components.some((c) => {
|
|
2903
3114
|
var _c$events;
|
|
@@ -2913,43 +3124,21 @@ Use the SAME surfaceId as the main surface. Match action names to button action
|
|
|
2913
3124
|
})
|
|
2914
3125
|
};
|
|
2915
3126
|
}
|
|
2916
|
-
/**
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
"Use unique ids. Do not make cycles. A component cannot be its own child.",
|
|
2932
|
-
"Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.",
|
|
2933
|
-
"Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.",
|
|
2934
|
-
"A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
|
|
2935
|
-
"Use only the components, props, events, and slots in the schema. A component with \"includesCommonProps\" also takes every prop in \"commonProps\".",
|
|
2936
|
-
"Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.",
|
|
2937
|
-
"A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions under \"functions\" in the schema. Write a literal when the value never changes.",
|
|
2938
|
-
"formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: 'EUR')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.",
|
|
2939
|
-
"${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: 'seats * 29', seats: /seats), currency: 'USD')}. The UI then follows the user's input with no round trip.",
|
|
2940
|
-
"For a computed list (chart data, template items) use series. Its description under \"functions\" in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.",
|
|
2941
|
-
"Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user's input goes to that path.",
|
|
2942
|
-
"To change data, write updateDataModel with a \"path\" and a \"value\": {\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"plan-picker\",\"path\":\"/seats\",\"value\":12}}. Always give \"value\".",
|
|
2943
|
-
"Set \"value\":null to delete the key at \"path\"."
|
|
2944
|
-
];
|
|
2945
|
-
/** The last rules of every markdown guideline, after the optional groups. */
|
|
2946
|
-
const MARKDOWN_CLOSING_RULES = [
|
|
2947
|
-
"The schema lists the surfaces that already exist under \"surfaces\". \"dataModel\" holds the values that the user entered: read them, and do not write those paths. \"rejected\" lists operations that the client dropped: send corrected operations in a new fence for that surfaceId. \"status\":\"deleted\" means the surface is gone: never use its id again. \"status\":\"failed\" means its createSurface was rejected: send a corrected createSurface with that id.",
|
|
2948
|
-
"Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.",
|
|
2949
|
-
"Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.",
|
|
2950
|
-
"Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.",
|
|
2951
|
-
"Never wrap the whole reply in a fence."
|
|
2952
|
-
];
|
|
3127
|
+
/**
|
|
3128
|
+
* Whether a guide line names only standard components (`GUIDE_COMPONENTS`,
|
|
3129
|
+
* also in the plural) that the catalog has. With no catalog, every line fits.
|
|
3130
|
+
*/
|
|
3131
|
+
function namesOnlyCatalogComponents(catalog) {
|
|
3132
|
+
if (!catalog) return () => true;
|
|
3133
|
+
const has = new Set(catalog);
|
|
3134
|
+
return (line) => {
|
|
3135
|
+
var _line$match;
|
|
3136
|
+
return ((_line$match = line.match(/\b[A-Z][A-Za-z0-9]*\b/g)) !== null && _line$match !== void 0 ? _line$match : []).every((word) => {
|
|
3137
|
+
const name = !GUIDE_COMPONENTS.has(word) && word.endsWith("s") ? word.slice(0, -1) : word;
|
|
3138
|
+
return !GUIDE_COMPONENTS.has(name) || has.has(name);
|
|
3139
|
+
});
|
|
3140
|
+
};
|
|
3141
|
+
}
|
|
2953
3142
|
/**
|
|
2954
3143
|
* Builds the markdown-transport guideline. The model writes A2UI v1.0
|
|
2955
3144
|
* operations inside ```a2ui fences between normal markdown prose. The rules
|
|
@@ -2957,25 +3146,15 @@ Use the SAME surfaceId as the main surface. Match action names to button action
|
|
|
2957
3146
|
* none of them, so the guideline stays small.
|
|
2958
3147
|
*
|
|
2959
3148
|
* @param features - The optional rule groups to include. Defaults to all.
|
|
3149
|
+
* @param spec - The wording. Defaults to the prompts that ship.
|
|
2960
3150
|
* @returns The guideline text, one rule per line.
|
|
2961
3151
|
*/
|
|
2962
|
-
function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES) {
|
|
2963
|
-
const {
|
|
2964
|
-
const
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
if (templates) rules.push("To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.", "Inside a template, paths are relative to the item (\"name\", not \"/name\").", "Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.");
|
|
2969
|
-
rules.push("Updating a component replaces all of its props. Send every prop again.", "To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.", "Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.");
|
|
2970
|
-
if (functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS) rules.push("To run an app function now, with no click, write a callRendererFunction line in a fence: {\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}. It needs no surface.", "Give every callRendererFunction a new functionCallId. Call only a function from the schema with \"callers\": \"UI or agent\" or \"agent only\"; a function without \"callers\" is for the UI only. A function with \"callers\": \"agent only\" is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Then you get a new turn.", "Do not guess the result of a callRendererFunction. Wait for the developer message.");
|
|
2971
|
-
rules.push(...MARKDOWN_CLOSING_RULES);
|
|
2972
|
-
return `You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.
|
|
2973
|
-
|
|
2974
|
-
${GENERATIVE_UI_WHEN_TO_SHOW}
|
|
2975
|
-
|
|
2976
|
-
RULES
|
|
2977
|
-
${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
2978
|
-
`;
|
|
3152
|
+
function buildGenerativeUIMarkdownGuidelines(features = ALL_GENERATIVE_UI_GUIDE_FEATURES, spec = defaultGenerativeUIPromptSpec()) {
|
|
3153
|
+
const { intro, rules } = spec.markdown;
|
|
3154
|
+
const fits = namesOnlyCatalogComponents(features.components);
|
|
3155
|
+
const selected = selectPromptItems(rules, generativeUIPromptFeatures(features)).filter(fits);
|
|
3156
|
+
const whenToShow = spec.markdown.whenToShow.split("\n").filter(fits).join("\n");
|
|
3157
|
+
return `${intro}\n\n${whenToShow ? `${whenToShow}\n\n` : ""}RULES\n${selected.map((rule) => `- ${rule}`).join("\n")}\n`;
|
|
2979
3158
|
}
|
|
2980
3159
|
/**
|
|
2981
3160
|
* The markdown-transport guideline with every rule group. A run sends
|
|
@@ -2983,6 +3162,264 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
2983
3162
|
*/
|
|
2984
3163
|
const GENERATIVE_UI_MARKDOWN_GUIDELINES = buildGenerativeUIMarkdownGuidelines();
|
|
2985
3164
|
|
|
3165
|
+
//#endregion
|
|
3166
|
+
//#region src/a2ui-catalog-schema.ts
|
|
3167
|
+
/**
|
|
3168
|
+
* Context description used to identify the A2UI component schema in
|
|
3169
|
+
* RunAgentInput.context. Must match the constant in @ag-ui/a2ui-middleware so
|
|
3170
|
+
* the middleware can overwrite a frontend-provided schema with a server-side one.
|
|
3171
|
+
*/
|
|
3172
|
+
const A2UI_SCHEMA_CONTEXT_DESCRIPTION = "A2UI Component Schema — available components for generating UI surfaces. Use these component names and properties when creating A2UI operations.";
|
|
3173
|
+
/** Id of the A2UI v0.9 basic catalog. */
|
|
3174
|
+
const A2UI_BASIC_CATALOG_ID = "https://a2ui.org/specification/v0_9/basic_catalog.json";
|
|
3175
|
+
/**
|
|
3176
|
+
* Serialize a catalog's Zod schemas in the A2UI v0.9 inline catalog format.
|
|
3177
|
+
*
|
|
3178
|
+
* Each component composes `ComponentCommon` with its own properties, matching
|
|
3179
|
+
* the flat wire format the agent must produce:
|
|
3180
|
+
*
|
|
3181
|
+
* { "Column": { "allOf": [
|
|
3182
|
+
* { "$ref": "common_types.json#/$defs/ComponentCommon" },
|
|
3183
|
+
* { "properties": { "component": {"const":"Column"}, "gap": ..., "children": ... },
|
|
3184
|
+
* "required": ["component"] }
|
|
3185
|
+
* ]}}
|
|
3186
|
+
*
|
|
3187
|
+
* This follows `getClientCapabilities` in `@a2ui/web_core` with these
|
|
3188
|
+
* deliberate differences:
|
|
3189
|
+
*
|
|
3190
|
+
* - Reused Zod schemas are inlined rather than emitted as local `$ref`s, which
|
|
3191
|
+
* would dangle once properties move under `allOf[1]`.
|
|
3192
|
+
* - A `REF:<ref>|<description>` marker becomes a bare `$ref`, as upstream, but
|
|
3193
|
+
* the shape it replaced is kept once under
|
|
3194
|
+
* `"common_types.json": { "$defs": { <Name>: ... } }`. Every
|
|
3195
|
+
* `common_types.json#/$defs/<Name>` ref therefore resolves within the
|
|
3196
|
+
* payload, both for agents that only see it as prompt text and for SDKs
|
|
3197
|
+
* (such as Google's A2UI SDK used by ADK) that read the `$ref`. Each type is
|
|
3198
|
+
* stated once rather than at every use site, which keeps the payload small.
|
|
3199
|
+
* A use whose shape differs from the stored one keeps its shape inline next
|
|
3200
|
+
* to the `$ref`, so the agent never sees a looser type than the client
|
|
3201
|
+
* accepts.
|
|
3202
|
+
* - A `REF:` marker on a schema's root only sets its description; replacing
|
|
3203
|
+
* the root would drop every property.
|
|
3204
|
+
* - A component's root `.describe()` is kept as the component `description`.
|
|
3205
|
+
* - Function parameters drop `$schema` and the description already given on
|
|
3206
|
+
* the function itself, to keep the prompt small.
|
|
3207
|
+
*/
|
|
3208
|
+
function extractA2UICatalogSchemas(catalog) {
|
|
3209
|
+
const components = Object.create(null);
|
|
3210
|
+
const commonTypes = Object.create(null);
|
|
3211
|
+
for (const [name, component] of catalog.components) {
|
|
3212
|
+
var _schema$properties, _schema$required;
|
|
3213
|
+
const schema = serializeA2UISchema(component.schema, commonTypes);
|
|
3214
|
+
const properties = (_schema$properties = schema.properties) !== null && _schema$properties !== void 0 ? _schema$properties : {};
|
|
3215
|
+
const required = (_schema$required = schema.required) !== null && _schema$required !== void 0 ? _schema$required : [];
|
|
3216
|
+
components[name] = {
|
|
3217
|
+
...typeof schema.description === "string" ? { description: schema.description } : {},
|
|
3218
|
+
allOf: [{ $ref: "common_types.json#/$defs/ComponentCommon" }, {
|
|
3219
|
+
properties: {
|
|
3220
|
+
component: { const: name },
|
|
3221
|
+
...properties
|
|
3222
|
+
},
|
|
3223
|
+
required: ["component", ...required]
|
|
3224
|
+
}]
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
const functions = catalogFunctions(catalog.functions).map((fn) => {
|
|
3228
|
+
var _fn$returnType;
|
|
3229
|
+
const { description, ...parameters } = serializeA2UISchema(fn.schema, commonTypes);
|
|
3230
|
+
return {
|
|
3231
|
+
name: fn.name,
|
|
3232
|
+
...typeof description === "string" ? { description } : {},
|
|
3233
|
+
returnType: (_fn$returnType = fn.returnType) !== null && _fn$returnType !== void 0 ? _fn$returnType : "any",
|
|
3234
|
+
parameters
|
|
3235
|
+
};
|
|
3236
|
+
});
|
|
3237
|
+
const theme = catalog.themeSchema ? serializeA2UISchema(catalog.themeSchema, commonTypes).properties : void 0;
|
|
3238
|
+
return {
|
|
3239
|
+
catalogId: catalog.id,
|
|
3240
|
+
components,
|
|
3241
|
+
...functions.length > 0 ? { functions } : {},
|
|
3242
|
+
...theme ? { theme } : {},
|
|
3243
|
+
...Object.keys(commonTypes).length > 0 ? { "common_types.json": { $defs: commonTypes } } : {}
|
|
3244
|
+
};
|
|
3245
|
+
}
|
|
3246
|
+
/**
|
|
3247
|
+
* Build a context string describing the catalog's id and the components it
|
|
3248
|
+
* adds beyond the basic catalog.
|
|
3249
|
+
*
|
|
3250
|
+
* Schemas are serialized as in {@link extractA2UICatalogSchemas}, with the
|
|
3251
|
+
* common types they reference listed once after the components.
|
|
3252
|
+
*
|
|
3253
|
+
* When `options.includeSchema` is `false`, custom components are listed by name
|
|
3254
|
+
* only and their JSON schemas are omitted.
|
|
3255
|
+
*/
|
|
3256
|
+
function buildA2UICatalogContextValue(catalog, basicComponentNames, options) {
|
|
3257
|
+
const lines = ["Available A2UI catalog:"];
|
|
3258
|
+
if (catalog.id === A2UI_BASIC_CATALOG_ID) {
|
|
3259
|
+
lines.push(`- ${catalog.id} (basic catalog)`);
|
|
3260
|
+
return lines.join("\n");
|
|
3261
|
+
}
|
|
3262
|
+
const isSuperset = [...basicComponentNames].every((name) => catalog.components.has(name));
|
|
3263
|
+
lines.push(`- ${catalog.id}`);
|
|
3264
|
+
if (isSuperset) lines.push(" Extends the basic catalog with all standard components plus:");
|
|
3265
|
+
else {
|
|
3266
|
+
lines.push(" Custom catalog (does NOT include all basic components).");
|
|
3267
|
+
lines.push(" Custom components:");
|
|
3268
|
+
}
|
|
3269
|
+
const commonTypes = Object.create(null);
|
|
3270
|
+
for (const [name, component] of catalog.components) {
|
|
3271
|
+
if (basicComponentNames.has(name)) continue;
|
|
3272
|
+
if ((options === null || options === void 0 ? void 0 : options.includeSchema) === false) {
|
|
3273
|
+
lines.push(` - ${name}`);
|
|
3274
|
+
continue;
|
|
3275
|
+
}
|
|
3276
|
+
lines.push(` - ${name}:`);
|
|
3277
|
+
lines.push(indented(serializeA2UISchema(component.schema, commonTypes)));
|
|
3278
|
+
}
|
|
3279
|
+
if (Object.keys(commonTypes).length > 0) {
|
|
3280
|
+
lines.push(" Common types referenced above (common_types.json#/$defs):");
|
|
3281
|
+
lines.push(indented(commonTypes));
|
|
3282
|
+
}
|
|
3283
|
+
return lines.join("\n");
|
|
3284
|
+
}
|
|
3285
|
+
/** JSON for the catalog context value, indented under a list item. */
|
|
3286
|
+
function indented(value) {
|
|
3287
|
+
return ` ${JSON.stringify(value, null, 2).split("\n").join("\n ")}`;
|
|
3288
|
+
}
|
|
3289
|
+
/** Raw zod-to-json-schema output per Zod schema, stored as JSON text. */
|
|
3290
|
+
const serializedSchemas = /* @__PURE__ */ new WeakMap();
|
|
3291
|
+
/**
|
|
3292
|
+
* Convert one A2UI Zod schema to JSON Schema 2019-09, inlining reused schemas
|
|
3293
|
+
* and resolving `REF:` markers (see {@link extractA2UICatalogSchemas}). The
|
|
3294
|
+
* shapes behind `common_types.json` refs are recorded in `commonTypes`; pass
|
|
3295
|
+
* the same map for every schema of one payload.
|
|
3296
|
+
*
|
|
3297
|
+
* The raw conversion is cached per schema object as JSON text, and every call
|
|
3298
|
+
* parses a fresh copy. The JSON round-trip, unlike structuredClone, never
|
|
3299
|
+
* throws on values such as a function or a Vue reactive proxy in a
|
|
3300
|
+
* `.default()`, and yields exactly what the agent receives.
|
|
3301
|
+
*/
|
|
3302
|
+
function serializeA2UISchema(schema, commonTypes = Object.create(null)) {
|
|
3303
|
+
const key = typeof schema === "object" && schema !== null ? schema : null;
|
|
3304
|
+
let serialized = key ? serializedSchemas.get(key) : void 0;
|
|
3305
|
+
if (serialized === void 0) {
|
|
3306
|
+
const jsonSchema = (0, zod_to_json_schema.zodToJsonSchema)(schema, {
|
|
3307
|
+
target: "jsonSchema2019-09",
|
|
3308
|
+
$refStrategy: "none",
|
|
3309
|
+
override: (_def, refs, seen, forceResolution) => seen && !forceResolution && seen.path.length < refs.currentPath.length && seen.path.every((part, i) => refs.currentPath[i] === part) ? {} : zod_to_json_schema.ignoreOverride
|
|
3310
|
+
});
|
|
3311
|
+
delete jsonSchema.$schema;
|
|
3312
|
+
serialized = JSON.stringify(jsonSchema);
|
|
3313
|
+
if (key) serializedSchemas.set(key, serialized);
|
|
3314
|
+
}
|
|
3315
|
+
const root = JSON.parse(serialized);
|
|
3316
|
+
const marker = parseRefMarker(root.description);
|
|
3317
|
+
if (marker) {
|
|
3318
|
+
delete root.description;
|
|
3319
|
+
if (marker.description) root.description = marker.description;
|
|
3320
|
+
}
|
|
3321
|
+
return resolveSubschemas(root, commonTypes);
|
|
3322
|
+
}
|
|
3323
|
+
/** Keywords whose value is a subschema, or an array of subschemas. */
|
|
3324
|
+
const SUBSCHEMA_KEYWORDS = [
|
|
3325
|
+
"items",
|
|
3326
|
+
"additionalItems",
|
|
3327
|
+
"additionalProperties",
|
|
3328
|
+
"unevaluatedItems",
|
|
3329
|
+
"unevaluatedProperties",
|
|
3330
|
+
"contains",
|
|
3331
|
+
"propertyNames",
|
|
3332
|
+
"not",
|
|
3333
|
+
"if",
|
|
3334
|
+
"then",
|
|
3335
|
+
"else",
|
|
3336
|
+
"allOf",
|
|
3337
|
+
"anyOf",
|
|
3338
|
+
"oneOf",
|
|
3339
|
+
"prefixItems"
|
|
3340
|
+
];
|
|
3341
|
+
/** Keywords whose value maps names to subschemas. */
|
|
3342
|
+
const SUBSCHEMA_MAP_KEYWORDS = [
|
|
3343
|
+
"properties",
|
|
3344
|
+
"patternProperties",
|
|
3345
|
+
"dependentSchemas",
|
|
3346
|
+
"$defs",
|
|
3347
|
+
"definitions"
|
|
3348
|
+
];
|
|
3349
|
+
const COMMON_TYPE_REF = /^common_types\.json#\/\$defs\/([^/]+)$/;
|
|
3350
|
+
function isObject(value) {
|
|
3351
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
3352
|
+
}
|
|
3353
|
+
/**
|
|
3354
|
+
* Split a `REF:<ref>|<description>` marker at its first `|`, so a description
|
|
3355
|
+
* containing `|` is kept whole. The convention comes from
|
|
3356
|
+
* `MessageProcessor.processRefs` in `@a2ui/web_core`.
|
|
3357
|
+
*/
|
|
3358
|
+
function parseRefMarker(description) {
|
|
3359
|
+
if (typeof description !== "string" || !description.startsWith("REF:")) return;
|
|
3360
|
+
const body = description.slice(4);
|
|
3361
|
+
const separator = body.indexOf("|");
|
|
3362
|
+
return separator === -1 ? { ref: body } : {
|
|
3363
|
+
ref: body.slice(0, separator),
|
|
3364
|
+
description: body.slice(separator + 1)
|
|
3365
|
+
};
|
|
3366
|
+
}
|
|
3367
|
+
/**
|
|
3368
|
+
* Resolve `REF:` markers in a schema's subschemas, innermost first, so a
|
|
3369
|
+
* stored common type refers to the types it contains by bare `$ref` too.
|
|
3370
|
+
*
|
|
3371
|
+
* Only schema-valued keywords are traversed, so literal values under
|
|
3372
|
+
* `default`, `const`, `enum` or `examples` are never rewritten.
|
|
3373
|
+
*/
|
|
3374
|
+
function resolveSubschemas(node, commonTypes) {
|
|
3375
|
+
const resolve = (value) => Array.isArray(value) ? value.map(resolve) : isObject(value) ? resolveRefMarker(resolveSubschemas(value, commonTypes), commonTypes) : value;
|
|
3376
|
+
const out = { ...node };
|
|
3377
|
+
for (const keyword of SUBSCHEMA_KEYWORDS) if (keyword in out) out[keyword] = resolve(out[keyword]);
|
|
3378
|
+
for (const keyword of SUBSCHEMA_MAP_KEYWORDS) {
|
|
3379
|
+
const map = out[keyword];
|
|
3380
|
+
if (isObject(map)) out[keyword] = Object.fromEntries(Object.entries(map).map(([name, child]) => [name, resolve(child)]));
|
|
3381
|
+
}
|
|
3382
|
+
return out;
|
|
3383
|
+
}
|
|
3384
|
+
/**
|
|
3385
|
+
* Turn a node carrying a `REF:` marker into a bare `$ref`, recording the
|
|
3386
|
+
* shape it replaced under its `common_types.json` name. A shape that differs
|
|
3387
|
+
* from the one already recorded, or a ref outside `common_types.json`, stays
|
|
3388
|
+
* inline next to the `$ref`.
|
|
3389
|
+
*/
|
|
3390
|
+
function resolveRefMarker(node, commonTypes) {
|
|
3391
|
+
var _COMMON_TYPE_REF$exec;
|
|
3392
|
+
const marker = parseRefMarker(node.description);
|
|
3393
|
+
if (!marker) return node;
|
|
3394
|
+
const { description: _marker, ...shape } = node;
|
|
3395
|
+
const ref = {
|
|
3396
|
+
$ref: marker.ref,
|
|
3397
|
+
...marker.description ? { description: marker.description } : {}
|
|
3398
|
+
};
|
|
3399
|
+
const name = (_COMMON_TYPE_REF$exec = COMMON_TYPE_REF.exec(marker.ref)) === null || _COMMON_TYPE_REF$exec === void 0 ? void 0 : _COMMON_TYPE_REF$exec[1];
|
|
3400
|
+
if (name !== void 0) {
|
|
3401
|
+
const known = commonTypes[name];
|
|
3402
|
+
if (known === void 0) {
|
|
3403
|
+
commonTypes[name] = shape;
|
|
3404
|
+
return ref;
|
|
3405
|
+
}
|
|
3406
|
+
if (JSON.stringify(known) === JSON.stringify(shape)) return ref;
|
|
3407
|
+
}
|
|
3408
|
+
return {
|
|
3409
|
+
...ref,
|
|
3410
|
+
...shape
|
|
3411
|
+
};
|
|
3412
|
+
}
|
|
3413
|
+
/**
|
|
3414
|
+
* Read a catalog's functions, tolerating catalog-shaped objects whose
|
|
3415
|
+
* `functions` is missing, a plain object or an array, and skipping entries
|
|
3416
|
+
* without a name or schema.
|
|
3417
|
+
*/
|
|
3418
|
+
function catalogFunctions(functions) {
|
|
3419
|
+
if (typeof functions !== "object" || functions === null) return [];
|
|
3420
|
+
return (functions instanceof Map ? [...functions.values()] : Array.isArray(functions) ? functions : Object.values(functions)).filter((fn) => typeof fn === "object" && fn !== null && typeof fn.name === "string" && typeof fn.schema === "object" && fn.schema !== null);
|
|
3421
|
+
}
|
|
3422
|
+
|
|
2986
3423
|
//#endregion
|
|
2987
3424
|
//#region src/a2ui-envelope.ts
|
|
2988
3425
|
/**
|
|
@@ -3003,11 +3440,11 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3003
3440
|
return typeof value === "string" && value !== "";
|
|
3004
3441
|
}
|
|
3005
3442
|
function isRecordOf(value, isEntry) {
|
|
3006
|
-
return isRecord(value) && Object.values(value).every(isEntry);
|
|
3443
|
+
return isRecord$2(value) && Object.values(value).every(isEntry);
|
|
3007
3444
|
}
|
|
3008
3445
|
/** A function, or an event of a component: a description and a parameter schema. */
|
|
3009
3446
|
function isSchemaEntry(value) {
|
|
3010
|
-
return isRecord(value) && isRecord(value.parameters) && isOptionalString(value.description);
|
|
3447
|
+
return isRecord$2(value) && isRecord$2(value.parameters) && isOptionalString(value.description);
|
|
3011
3448
|
}
|
|
3012
3449
|
function isSlotKind(value) {
|
|
3013
3450
|
return value === "single" || value === "multiple";
|
|
@@ -3017,11 +3454,11 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3017
3454
|
* so those two must have the right shape when they are there.
|
|
3018
3455
|
*/
|
|
3019
3456
|
function isPropsSchema(value) {
|
|
3020
|
-
return isRecord(value) && (value.properties === void 0 || isRecord(value.properties)) && (value.required === void 0 || Array.isArray(value.required) && value.required.every((name) => typeof name === "string"));
|
|
3457
|
+
return isRecord$2(value) && (value.properties === void 0 || isRecord$2(value.properties)) && (value.required === void 0 || Array.isArray(value.required) && value.required.every((name) => typeof name === "string"));
|
|
3021
3458
|
}
|
|
3022
3459
|
function isComponentManifest(value) {
|
|
3023
3460
|
var _value$props$properti, _value$slots, _value$events;
|
|
3024
|
-
if (!isRecord(value) || !isPropsSchema(value.props) || !isOptionalString(value.description) || value.events !== void 0 && !isRecordOf(value.events, isSchemaEntry) || value.slots !== void 0 && !isRecordOf(value.slots, isSlotKind)) return false;
|
|
3461
|
+
if (!isRecord$2(value) || !isPropsSchema(value.props) || !isOptionalString(value.description) || value.events !== void 0 && !isRecordOf(value.events, isSchemaEntry) || value.slots !== void 0 && !isRecordOf(value.slots, isSlotKind)) return false;
|
|
3025
3462
|
const order = value.parameterOrder;
|
|
3026
3463
|
if (order === void 0) return true;
|
|
3027
3464
|
const keys = new Set([
|
|
@@ -3032,31 +3469,31 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3032
3469
|
return Array.isArray(order) && new Set(order).size === order.length && order.every((key) => typeof key === "string" && keys.has(key));
|
|
3033
3470
|
}
|
|
3034
3471
|
function isInlineCatalog(value) {
|
|
3035
|
-
return isRecord(value) && isNonEmptyString(value.catalogId) && value.protocolVersion === "1.0" && (value.components === void 0 || isRecordOf(value.components, isComponentManifest)) && isRecordOf(value.functions, isSchemaEntry) && isOptionalString(value.instructions);
|
|
3472
|
+
return isRecord$2(value) && isNonEmptyString(value.catalogId) && value.protocolVersion === "1.0" && (value.components === void 0 || isRecordOf(value.components, isComponentManifest)) && isRecordOf(value.functions, isSchemaEntry) && isOptionalString(value.instructions);
|
|
3036
3473
|
}
|
|
3037
3474
|
function isCapabilities(value) {
|
|
3038
|
-
return isRecord(value) && Array.isArray(value.supportedCatalogIds) && value.supportedCatalogIds.length > 0 && value.supportedCatalogIds.every(isNonEmptyString) && (value.inlineCatalogs === void 0 || Array.isArray(value.inlineCatalogs) && value.inlineCatalogs.every(isInlineCatalog));
|
|
3475
|
+
return isRecord$2(value) && Array.isArray(value.supportedCatalogIds) && value.supportedCatalogIds.length > 0 && value.supportedCatalogIds.every(isNonEmptyString) && (value.inlineCatalogs === void 0 || Array.isArray(value.inlineCatalogs) && value.inlineCatalogs.every(isInlineCatalog));
|
|
3039
3476
|
}
|
|
3040
3477
|
/** A short list of component names. */
|
|
3041
3478
|
function isComponentNameList(value) {
|
|
3042
3479
|
return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_TARGET_COMPONENTS && value.every(isNonEmptyString);
|
|
3043
3480
|
}
|
|
3044
3481
|
function isTarget(value) {
|
|
3045
|
-
return isRecord(value) && isNonEmptyString(value.id) && (value.kind === "chat" || value.kind === "inline") && isOptionalString(value.description) && (value.components === void 0 || isComponentNameList(value.components));
|
|
3482
|
+
return isRecord$2(value) && isNonEmptyString(value.id) && (value.kind === "chat" || value.kind === "inline") && isOptionalString(value.description) && (value.components === void 0 || isComponentNameList(value.components));
|
|
3046
3483
|
}
|
|
3047
3484
|
/** A short list of short strings. The summary limits keep the guide small. */
|
|
3048
3485
|
function isRejectionList(value) {
|
|
3049
3486
|
return Array.isArray(value) && value.length <= GENERATIVE_UI_MAX_SUMMARY_REJECTIONS && value.every((entry) => typeof entry === "string" && entry.length <= GENERATIVE_UI_MAX_REJECTION_LENGTH);
|
|
3050
3487
|
}
|
|
3051
3488
|
function isSurfaceEntry(value) {
|
|
3052
|
-
return isRecord(value) && isNonEmptyString(value.target) && (value.dataModel === void 0 || isRecord(value.dataModel)) && (value.rejected === void 0 || isRejectionList(value.rejected)) && (value.status === void 0 || value.status === "deleted" || value.status === "failed");
|
|
3489
|
+
return isRecord$2(value) && isNonEmptyString(value.target) && (value.dataModel === void 0 || isRecord$2(value.dataModel)) && (value.rejected === void 0 || isRejectionList(value.rejected)) && (value.status === void 0 || value.status === "deleted" || value.status === "failed");
|
|
3053
3490
|
}
|
|
3054
3491
|
/** Checks the `copilotkit_` keys only. Other extensions can be there too. */
|
|
3055
3492
|
function isExtensions(value) {
|
|
3056
|
-
return isRecord(value) && value.copilotkit_format === COPILOTKIT_UI_ENVELOPE_FORMAT && (value.copilotkit_transport === "tool" || value.copilotkit_transport === "markdown") && Array.isArray(value.copilotkit_targets) && value.copilotkit_targets.every(isTarget) && isRecordOf(value.copilotkit_surfaces, isSurfaceEntry) && typeof value.copilotkit_contextSent === "boolean";
|
|
3493
|
+
return isRecord$2(value) && value.copilotkit_format === COPILOTKIT_UI_ENVELOPE_FORMAT && (value.copilotkit_transport === "tool" || value.copilotkit_transport === "markdown") && Array.isArray(value.copilotkit_targets) && value.copilotkit_targets.every(isTarget) && isRecordOf(value.copilotkit_surfaces, isSurfaceEntry) && typeof value.copilotkit_contextSent === "boolean";
|
|
3057
3494
|
}
|
|
3058
3495
|
function isEnvelope(value) {
|
|
3059
|
-
return isRecord(value) && isCapabilities(value["
|
|
3496
|
+
return isRecord$2(value) && isCapabilities(value["1.0"]) && isRecord$2(value.metadata) && isExtensions(value.metadata.extensions);
|
|
3060
3497
|
}
|
|
3061
3498
|
/**
|
|
3062
3499
|
* Reads the generative UI envelope from the `forwardedProps` of a run.
|
|
@@ -3077,9 +3514,9 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3077
3514
|
* ```
|
|
3078
3515
|
*/
|
|
3079
3516
|
function readCopilotKitUIEnvelope(forwardedProps) {
|
|
3080
|
-
if (!isRecord(forwardedProps)) return void 0;
|
|
3517
|
+
if (!isRecord$2(forwardedProps)) return void 0;
|
|
3081
3518
|
const namespace = forwardedProps[COPILOTKIT_FORWARDED_PROPS_KEY];
|
|
3082
|
-
if (!isRecord(namespace)) return void 0;
|
|
3519
|
+
if (!isRecord$2(namespace)) return void 0;
|
|
3083
3520
|
const envelope = namespace.ui;
|
|
3084
3521
|
return isEnvelope(envelope) ? envelope : void 0;
|
|
3085
3522
|
}
|
|
@@ -3112,7 +3549,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3112
3549
|
*/
|
|
3113
3550
|
function envelopeToManifest(envelope) {
|
|
3114
3551
|
var _catalog$components, _catalog$functions;
|
|
3115
|
-
const { supportedCatalogIds, inlineCatalogs } = envelope["
|
|
3552
|
+
const { supportedCatalogIds, inlineCatalogs } = envelope["1.0"];
|
|
3116
3553
|
const catalogId = supportedCatalogIds[0];
|
|
3117
3554
|
const catalog = inlineCatalogs === null || inlineCatalogs === void 0 ? void 0 : inlineCatalogs.find((entry) => entry.catalogId === catalogId);
|
|
3118
3555
|
const extensions = envelope.metadata.extensions;
|
|
@@ -3152,7 +3589,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3152
3589
|
});
|
|
3153
3590
|
/** Models write the v0.9 binding from habit. The reason names the v1.0 form. */
|
|
3154
3591
|
const V09_PATH_REASON = "bind data with {\"@path\": \"/x\"}, not {\"path\": \"/x\"}";
|
|
3155
|
-
function hasOwn(record, key) {
|
|
3592
|
+
function hasOwn$1(record, key) {
|
|
3156
3593
|
return Object.prototype.hasOwnProperty.call(record, key);
|
|
3157
3594
|
}
|
|
3158
3595
|
/**
|
|
@@ -3160,42 +3597,42 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3160
3597
|
* "toString" must not resolve to Object.prototype members.
|
|
3161
3598
|
*/
|
|
3162
3599
|
function ownValue(record, key) {
|
|
3163
|
-
return record && hasOwn(record, key) ? record[key] : void 0;
|
|
3600
|
+
return record && hasOwn$1(record, key) ? record[key] : void 0;
|
|
3164
3601
|
}
|
|
3165
3602
|
function getOperationKind(op) {
|
|
3166
|
-
if (!isRecord(op)) return void 0;
|
|
3603
|
+
if (!isRecord$2(op)) return void 0;
|
|
3167
3604
|
const kinds = OPERATION_KINDS.filter((kind) => kind in op);
|
|
3168
3605
|
return kinds.length === 1 ? kinds[0] : void 0;
|
|
3169
3606
|
}
|
|
3170
3607
|
/** The `surfaceId` of a surface operation. `callRendererFunction` has none. */
|
|
3171
3608
|
function getOperationSurfaceId(op) {
|
|
3172
|
-
if (!isRecord(op)) return void 0;
|
|
3609
|
+
if (!isRecord$2(op)) return void 0;
|
|
3173
3610
|
const kind = getOperationKind(op);
|
|
3174
3611
|
if (!kind) return void 0;
|
|
3175
3612
|
const payload = op[kind];
|
|
3176
|
-
return isRecord(payload) && typeof payload.surfaceId === "string" ? payload.surfaceId : void 0;
|
|
3613
|
+
return isRecord$2(payload) && typeof payload.surfaceId === "string" ? payload.surfaceId : void 0;
|
|
3177
3614
|
}
|
|
3178
3615
|
/** `{ "@path": "/x" }`: a data-model binding. */
|
|
3179
3616
|
function isPathBinding(value) {
|
|
3180
|
-
return isRecord(value) && typeof value["@path"] === "string" && Object.keys(value).length === 1;
|
|
3617
|
+
return isRecord$2(value) && typeof value["@path"] === "string" && Object.keys(value).length === 1;
|
|
3181
3618
|
}
|
|
3182
3619
|
/** `{ "path": "/x" }`: the v0.9 binding, which v1.0 does not accept. */
|
|
3183
3620
|
function isV09PathBinding(value) {
|
|
3184
|
-
return isRecord(value) && typeof value.path === "string" && Object.keys(value).length === 1;
|
|
3621
|
+
return isRecord$2(value) && typeof value.path === "string" && Object.keys(value).length === 1;
|
|
3185
3622
|
}
|
|
3186
3623
|
/**
|
|
3187
3624
|
* `{ "@call": "@index" }` or `{ "@call": "@index", "args": { "offset": 1 } }`:
|
|
3188
3625
|
* the 0-based position of the item in a template, plus `offset`.
|
|
3189
3626
|
*/
|
|
3190
3627
|
function isIndexCall(value) {
|
|
3191
|
-
if (!isRecord(value) || value["@call"] !== "@index") return false;
|
|
3628
|
+
if (!isRecord$2(value) || value["@call"] !== "@index") return false;
|
|
3192
3629
|
if (!Object.keys(value).every((key) => key === "@call" || key === "args")) return false;
|
|
3193
3630
|
const { args } = value;
|
|
3194
3631
|
if (args === void 0) return true;
|
|
3195
|
-
return isRecord(args) && Object.keys(args).every((key) => key === "offset") && (args.offset === void 0 || Number.isFinite(args.offset));
|
|
3632
|
+
return isRecord$2(args) && Object.keys(args).every((key) => key === "offset") && (args.offset === void 0 || Number.isFinite(args.offset));
|
|
3196
3633
|
}
|
|
3197
3634
|
function isActionBinding(value) {
|
|
3198
|
-
return isRecord(value) && Object.keys(value).length === 1 && (isRecord(value.functionCall) || isRecord(value.event));
|
|
3635
|
+
return isRecord$2(value) && Object.keys(value).length === 1 && (isRecord$2(value.functionCall) || isRecord$2(value.event));
|
|
3199
3636
|
}
|
|
3200
3637
|
/**
|
|
3201
3638
|
* Checks one A2UI v1.0 operation against the catalog and the surfaces that
|
|
@@ -3213,7 +3650,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3213
3650
|
* ```
|
|
3214
3651
|
*/
|
|
3215
3652
|
function validateOperation(op, options) {
|
|
3216
|
-
if (!isRecord(op)) return fail("operation must be a JSON object");
|
|
3653
|
+
if (!isRecord$2(op)) return fail("operation must be a JSON object");
|
|
3217
3654
|
if (op.version !== A2UI_VERSION) return fail(versionProblem(op.version));
|
|
3218
3655
|
const kind = getOperationKind(op);
|
|
3219
3656
|
if (!kind) return fail(`operation must contain exactly one of ${OPERATION_KINDS.join(", ")}`);
|
|
@@ -3222,7 +3659,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3222
3659
|
if (!GENERATIVE_UI_AGENT_FUNCTION_CALLS) return fail(GENERATIVE_UI_AGENT_FUNCTION_CALLS_OFF_REASON);
|
|
3223
3660
|
return validateRendererFunctionCall(payload, options);
|
|
3224
3661
|
}
|
|
3225
|
-
if (!isRecord(payload) || typeof payload.surfaceId !== "string" || !payload.surfaceId) return fail(`${kind}.surfaceId is required`);
|
|
3662
|
+
if (!isRecord$2(payload) || typeof payload.surfaceId !== "string" || !payload.surfaceId) return fail(`${kind}.surfaceId is required`);
|
|
3226
3663
|
const surfaceId = payload.surfaceId;
|
|
3227
3664
|
if (kind === "createSurface") return validateCreateSurface(payload, surfaceId, options);
|
|
3228
3665
|
if (!options.knownSurfaces.has(surfaceId)) return fail(`surface "${surfaceId}" does not exist; send createSurface first`);
|
|
@@ -3251,12 +3688,12 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3251
3688
|
const catalogReason = catalogProblem(payload.catalogId, options.manifest);
|
|
3252
3689
|
if (catalogReason) return fail(catalogReason);
|
|
3253
3690
|
const { dataModel, components } = payload;
|
|
3254
|
-
if (dataModel !== void 0 && !isRecord(dataModel)) return fail("createSurface.dataModel must be a JSON object");
|
|
3691
|
+
if (dataModel !== void 0 && !isRecord$2(dataModel)) return fail("createSurface.dataModel must be a JSON object");
|
|
3255
3692
|
if (components === void 0) return OK;
|
|
3256
3693
|
return validateComponents(components, "createSurface.components", options);
|
|
3257
3694
|
}
|
|
3258
3695
|
function validateRendererFunctionCall(payload, options) {
|
|
3259
|
-
if (!(isRecord(payload) && typeof payload.functionCallId === "string" && payload.functionCallId !== "")) return fail("callRendererFunction.functionCallId must be a non-empty string");
|
|
3696
|
+
if (!(isRecord$2(payload) && typeof payload.functionCallId === "string" && payload.functionCallId !== "")) return fail("callRendererFunction.functionCallId must be a non-empty string");
|
|
3260
3697
|
const reason = functionCallProblem(payload.callFunction, "callRendererFunction.callFunction", options);
|
|
3261
3698
|
return reason ? fail(reason) : OK;
|
|
3262
3699
|
}
|
|
@@ -3274,7 +3711,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3274
3711
|
const path = (_payload$path = payload.path) !== null && _payload$path !== void 0 ? _payload$path : "/";
|
|
3275
3712
|
if (typeof path !== "string" || !path.startsWith("/")) return fail("updateDataModel.path must be an absolute JSON pointer");
|
|
3276
3713
|
if (path === "/") {
|
|
3277
|
-
if (!isRecord(payload.value)) return fail("a root updateDataModel value must be a JSON object");
|
|
3714
|
+
if (!isRecord$2(payload.value)) return fail("a root updateDataModel value must be a JSON object");
|
|
3278
3715
|
return OK;
|
|
3279
3716
|
}
|
|
3280
3717
|
const reason = pathProblem(path, "updateDataModel.path");
|
|
@@ -3294,7 +3731,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3294
3731
|
if (!Array.isArray(components) || components.length === 0) return fail(`${label} must be a non-empty array`);
|
|
3295
3732
|
const ids = /* @__PURE__ */ new Set();
|
|
3296
3733
|
for (const node of components) {
|
|
3297
|
-
if (!isRecord(node)) return fail("component must be a JSON object");
|
|
3734
|
+
if (!isRecord$2(node)) return fail("component must be a JSON object");
|
|
3298
3735
|
const { id } = node;
|
|
3299
3736
|
if (typeof id !== "string" || !id) return fail("id is required");
|
|
3300
3737
|
const reason = nodeProblem(node, id, options);
|
|
@@ -3314,7 +3751,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3314
3751
|
return `"${node.component}" is not allowed in target "${allowedComponents.target}"; use one of: ${names}`;
|
|
3315
3752
|
}
|
|
3316
3753
|
const { properties, required } = entry.props;
|
|
3317
|
-
const propNames = isRecord(properties) ? Object.keys(properties) : [];
|
|
3754
|
+
const propNames = isRecord$2(properties) ? Object.keys(properties) : [];
|
|
3318
3755
|
const props = Object.entries(node);
|
|
3319
3756
|
for (const [key, value] of props) {
|
|
3320
3757
|
if (key === "id" || key === "component") continue;
|
|
@@ -3324,7 +3761,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3324
3761
|
continue;
|
|
3325
3762
|
}
|
|
3326
3763
|
if (key === "metadata") {
|
|
3327
|
-
if (!(isRecord(value) && (value.extensions === void 0 || isRecord(value.extensions)))) return "metadata must be { \"extensions\": { ... } }";
|
|
3764
|
+
if (!(isRecord$2(value) && (value.extensions === void 0 || isRecord$2(value.extensions)))) return "metadata must be { \"extensions\": { ... } }";
|
|
3328
3765
|
continue;
|
|
3329
3766
|
}
|
|
3330
3767
|
if (key === "accessibility") {
|
|
@@ -3372,7 +3809,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3372
3809
|
* values, `hidden` is a boolean or a dynamic value.
|
|
3373
3810
|
*/
|
|
3374
3811
|
function accessibilityProblem(value) {
|
|
3375
|
-
if (!isRecord(value)) return "must be { \"label\": \"...\", \"description\": \"...\", \"live\": \"polite\", \"hidden\": false }";
|
|
3812
|
+
if (!isRecord$2(value)) return "must be { \"label\": \"...\", \"description\": \"...\", \"live\": \"polite\", \"hidden\": false }";
|
|
3376
3813
|
const isDynamic = (field) => isPathBinding(field) || isCallBinding(field);
|
|
3377
3814
|
for (const [key, field] of Object.entries(value)) {
|
|
3378
3815
|
if (!ACCESSIBILITY_KEYS.includes(key)) return `unknown key "${key}"`;
|
|
@@ -3390,7 +3827,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3390
3827
|
}
|
|
3391
3828
|
}
|
|
3392
3829
|
function actionBindingProblem(value, options) {
|
|
3393
|
-
if (!isRecord(value)) return "must be an action object";
|
|
3830
|
+
if (!isRecord$2(value)) return "must be an action object";
|
|
3394
3831
|
const keys = Object.keys(value);
|
|
3395
3832
|
if (!(keys.length === 1 && (keys[0] === "functionCall" || keys[0] === "event"))) return "must be { \"event\": ... } or { \"functionCall\": ... }";
|
|
3396
3833
|
if (keys[0] === "functionCall") return functionCallProblem(value.functionCall, "functionCall", options);
|
|
@@ -3401,18 +3838,18 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3401
3838
|
* field in the reason.
|
|
3402
3839
|
*/
|
|
3403
3840
|
function functionCallProblem(call, label, options) {
|
|
3404
|
-
if (!isRecord(call)) return `${label} must be { "@call": "<function>", "args": { ... } }`;
|
|
3841
|
+
if (!isRecord$2(call)) return `${label} must be { "@call": "<function>", "args": { ... } }`;
|
|
3405
3842
|
const name = call["@call"];
|
|
3406
3843
|
if (typeof name !== "string" || !name) return typeof call.call === "string" ? `${label} names the function with "@call", not "call"` : `${label}["@call"] must be a function name`;
|
|
3407
3844
|
const { args } = call;
|
|
3408
|
-
if (args !== void 0 && !isRecord(args)) return `${label}.args must be an object`;
|
|
3845
|
+
if (args !== void 0 && !isRecord$2(args)) return `${label}.args must be an object`;
|
|
3409
3846
|
const catalogReason = catalogProblem(call.catalogId, options.manifest);
|
|
3410
3847
|
if (catalogReason) return `${label}: ${catalogReason}`;
|
|
3411
3848
|
const argEntries = Object.entries(args !== null && args !== void 0 ? args : {});
|
|
3412
3849
|
for (const [key, arg] of argEntries) if (isV09PathBinding(arg)) return `${label}.args.${key}: ${V09_PATH_REASON}`;
|
|
3413
3850
|
const appFunctions = options.functions;
|
|
3414
|
-
const declared = appFunctions !== void 0 && hasOwn(appFunctions, name) ? appFunctions[name] : void 0;
|
|
3415
|
-
const builtIn = declared === void 0 && hasOwn(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
|
|
3851
|
+
const declared = appFunctions !== void 0 && hasOwn$1(appFunctions, name) ? appFunctions[name] : void 0;
|
|
3852
|
+
const builtIn = declared === void 0 && hasOwn$1(GENERATIVE_UI_FUNCTIONS, name) ? GENERATIVE_UI_FUNCTIONS[name] : void 0;
|
|
3416
3853
|
if (declared === void 0 && builtIn === void 0) return appFunctions === void 0 ? void 0 : `function "${name}" is not exposed to generative UI`;
|
|
3417
3854
|
if (declared === void 0 && appFunctions === void 0) return void 0;
|
|
3418
3855
|
return callerProblem(name, declared !== null && declared !== void 0 ? declared : builtIn, label.startsWith("callRendererFunction") ? "agent" : "renderer");
|
|
@@ -3428,11 +3865,11 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3428
3865
|
if (caller === "renderer" && !callers.renderer) return `function "${name}" runs only for the agent (allowedCallers "agentOnly"); the UI cannot call it`;
|
|
3429
3866
|
}
|
|
3430
3867
|
function eventProblem(event) {
|
|
3431
|
-
if (!isRecord(event) || typeof event.name !== "string" || !event.name) return "event.name is required";
|
|
3868
|
+
if (!isRecord$2(event) || typeof event.name !== "string" || !event.name) return "event.name is required";
|
|
3432
3869
|
const { userMessage, context } = event;
|
|
3433
|
-
if (!(userMessage === void 0 || typeof userMessage === "string" || isPathBinding(userMessage) || isRecord(userMessage) && typeof userMessage["@call"] === "string" && findForbiddenCall(userMessage, { allowValueFunctions: true }) === void 0)) return isV09PathBinding(userMessage) ? `event.userMessage: ${V09_PATH_REASON}` : "event.userMessage must be a string, {\"@path\": \"/x\"} or a function value";
|
|
3870
|
+
if (!(userMessage === void 0 || typeof userMessage === "string" || isPathBinding(userMessage) || isRecord$2(userMessage) && typeof userMessage["@call"] === "string" && findForbiddenCall(userMessage, { allowValueFunctions: true }) === void 0)) return isV09PathBinding(userMessage) ? `event.userMessage: ${V09_PATH_REASON}` : "event.userMessage must be a string, {\"@path\": \"/x\"} or a function value";
|
|
3434
3871
|
if (context === void 0) return void 0;
|
|
3435
|
-
if (!isRecord(context)) return "event.context must be an object";
|
|
3872
|
+
if (!isRecord$2(context)) return "event.context must be an object";
|
|
3436
3873
|
const entries = Object.entries(context);
|
|
3437
3874
|
for (const [key, entry] of entries) {
|
|
3438
3875
|
if (isV09PathBinding(entry)) return `event.context.${key}: ${V09_PATH_REASON}`;
|
|
@@ -3441,7 +3878,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3441
3878
|
}
|
|
3442
3879
|
}
|
|
3443
3880
|
function slotProblem(value, kind, ownId) {
|
|
3444
|
-
const isTemplate = isRecord(value) && "componentId" in value;
|
|
3881
|
+
const isTemplate = isRecord$2(value) && "componentId" in value;
|
|
3445
3882
|
if (kind === "single" && isTemplate) return "a template { \"componentId\", \"path\" } is only allowed in a \"multiple\" slot";
|
|
3446
3883
|
if (kind === "multiple" && isTemplate) return templateProblem(value, ownId);
|
|
3447
3884
|
if (kind === "multiple" && !Array.isArray(value)) return "must be an array of component ids or a template { \"componentId\", \"path\" }";
|
|
@@ -3475,7 +3912,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3475
3912
|
}
|
|
3476
3913
|
return;
|
|
3477
3914
|
}
|
|
3478
|
-
if (!isRecord(value)) return void 0;
|
|
3915
|
+
if (!isRecord$2(value)) return void 0;
|
|
3479
3916
|
if (isIndexCall(value)) return void 0;
|
|
3480
3917
|
if (value["@call"] === "@index") return "@index takes only an offset";
|
|
3481
3918
|
if (typeof value.call === "string") return "name the function with \"@call\", not \"call\"";
|
|
@@ -3484,7 +3921,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3484
3921
|
if (typeof name === "string") {
|
|
3485
3922
|
if (!options.allowValueFunctions || !isA2UIValueFunction(name)) return isA2UIBasicFunction(name) ? `"${name}" runs only from an event` : `"${name}" is not a basic function`;
|
|
3486
3923
|
const args = value.args;
|
|
3487
|
-
if (args !== void 0 && !isRecord(args)) return `the args of "${name}" must be an object`;
|
|
3924
|
+
if (args !== void 0 && !isRecord$2(args)) return `the args of "${name}" must be an object`;
|
|
3488
3925
|
return args === void 0 ? void 0 : findForbiddenCall(args, options);
|
|
3489
3926
|
}
|
|
3490
3927
|
for (const item of Object.values(value)) {
|
|
@@ -3509,7 +3946,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3509
3946
|
*/
|
|
3510
3947
|
function childRefProblem(node, ref, ownId) {
|
|
3511
3948
|
const label = ref.path.filter((step) => step !== "*").join(".");
|
|
3512
|
-
const isDynamic = (value) => isPathBinding(value) || isRecord(value) && "@call" in value;
|
|
3949
|
+
const isDynamic = (value) => isPathBinding(value) || isRecord$2(value) && "@call" in value;
|
|
3513
3950
|
const visit = (value, steps) => {
|
|
3514
3951
|
if (isDynamic(value)) return void 0;
|
|
3515
3952
|
if (steps.length === 0) {
|
|
@@ -3525,7 +3962,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3525
3962
|
}
|
|
3526
3963
|
return;
|
|
3527
3964
|
}
|
|
3528
|
-
if (!isRecord(value) || !hasOwn(value, head)) return void 0;
|
|
3965
|
+
if (!isRecord$2(value) || !hasOwn$1(value, head)) return void 0;
|
|
3529
3966
|
return visit(value[head], rest);
|
|
3530
3967
|
};
|
|
3531
3968
|
return visit(node, ref.path);
|
|
@@ -3649,7 +4086,7 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3649
4086
|
function parseObject(raw) {
|
|
3650
4087
|
try {
|
|
3651
4088
|
const value = JSON.parse(raw);
|
|
3652
|
-
return isRecord(value) ? value : null;
|
|
4089
|
+
return isRecord$2(value) ? value : null;
|
|
3653
4090
|
} catch (_unused3) {
|
|
3654
4091
|
return null;
|
|
3655
4092
|
}
|
|
@@ -3686,6 +4123,434 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3686
4123
|
}
|
|
3687
4124
|
};
|
|
3688
4125
|
|
|
4126
|
+
//#endregion
|
|
4127
|
+
//#region src/generative-ui/compact-schema.ts
|
|
4128
|
+
/** Objects nested deeper than this show as `object`. */
|
|
4129
|
+
const MAX_OBJECT_DEPTH = 2;
|
|
4130
|
+
/** A prop must appear verbatim in at least this many components to be hoisted. */
|
|
4131
|
+
const COMMON_PROP_MIN_COMPONENTS = 8;
|
|
4132
|
+
function isRecord$1(value) {
|
|
4133
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4134
|
+
}
|
|
4135
|
+
/** A JSON Schema of a list of schemas (`anyOf`, `oneOf`), else an empty list. */
|
|
4136
|
+
function schemaList(value) {
|
|
4137
|
+
return Array.isArray(value) ? value.filter(isRecord$1) : [];
|
|
4138
|
+
}
|
|
4139
|
+
/**
|
|
4140
|
+
* Puts a top-level union in parentheses, so that `[]` applies to all of
|
|
4141
|
+
* it. A union inside braces needs none.
|
|
4142
|
+
*/
|
|
4143
|
+
function asArrayItem(type) {
|
|
4144
|
+
let outside = type;
|
|
4145
|
+
for (let inner = outside.replace(/\{[^{}]*\}/g, ""); inner !== outside;) {
|
|
4146
|
+
outside = inner;
|
|
4147
|
+
inner = outside.replace(/\{[^{}]*\}/g, "");
|
|
4148
|
+
}
|
|
4149
|
+
return outside.includes(" | ") ? `(${type})[]` : `${type}[]`;
|
|
4150
|
+
}
|
|
4151
|
+
/**
|
|
4152
|
+
* A JSON Schema as a short TypeScript-like type, for example
|
|
4153
|
+
* `{ label: string; size?: "sm" | "md" }`.
|
|
4154
|
+
*/
|
|
4155
|
+
function compactType(schema, depth) {
|
|
4156
|
+
const ref = childRefKind(schema);
|
|
4157
|
+
if (ref === "single") return "componentId";
|
|
4158
|
+
if (ref === "multiple") return "componentId[] | { componentId: string; path: string }";
|
|
4159
|
+
if ("const" in schema) return JSON.stringify(schema.const);
|
|
4160
|
+
if (Array.isArray(schema.enum)) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
|
|
4161
|
+
const variants = [...schemaList(schema.anyOf), ...schemaList(schema.oneOf)];
|
|
4162
|
+
if (variants.length > 0) return variants.map((variant) => compactType(variant, depth)).join(" | ");
|
|
4163
|
+
return (Array.isArray(schema.type) ? schema.type : [schema.type]).map((type) => {
|
|
4164
|
+
switch (type) {
|
|
4165
|
+
case "string":
|
|
4166
|
+
case "boolean":
|
|
4167
|
+
case "null": return type;
|
|
4168
|
+
case "number":
|
|
4169
|
+
case "integer": return "number";
|
|
4170
|
+
case "array": return isRecord$1(schema.items) ? asArrayItem(compactType(schema.items, depth)) : "unknown[]";
|
|
4171
|
+
case "object": return compactObject(schema, depth);
|
|
4172
|
+
default: return "unknown";
|
|
4173
|
+
}
|
|
4174
|
+
}).join(" | ");
|
|
4175
|
+
}
|
|
4176
|
+
/** An object schema as `{ key: type; other?: type }`. */
|
|
4177
|
+
function compactObject(schema, depth) {
|
|
4178
|
+
const properties = isRecord$1(schema.properties) ? schema.properties : {};
|
|
4179
|
+
const entries = Object.entries(properties);
|
|
4180
|
+
if (entries.length === 0) return isRecord$1(schema.additionalProperties) ? `Record<string, ${compactType(schema.additionalProperties, depth + 1)}>` : "object";
|
|
4181
|
+
if (depth >= MAX_OBJECT_DEPTH) return "object";
|
|
4182
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
4183
|
+
return `{ ${entries.map(([key, value]) => {
|
|
4184
|
+
const type = isRecord$1(value) ? compactType(value, depth + 1) : "unknown";
|
|
4185
|
+
return `${key}${required.includes(key) ? "" : "?"}: ${type}`;
|
|
4186
|
+
}).join("; ")} }`;
|
|
4187
|
+
}
|
|
4188
|
+
/** A schema as its type, with its description after `//`. */
|
|
4189
|
+
function describedType(schema, depth) {
|
|
4190
|
+
const type = compactType(schema, depth);
|
|
4191
|
+
return typeof schema.description === "string" ? `${type} // ${schema.description}` : type;
|
|
4192
|
+
}
|
|
4193
|
+
/**
|
|
4194
|
+
* The props of a component: `{ "label": "string", "size?": "..." }`. With
|
|
4195
|
+
* `descriptions`, each type carries its description after `//`.
|
|
4196
|
+
*/
|
|
4197
|
+
function compactProps(schema, descriptions = true) {
|
|
4198
|
+
const properties = isRecord$1(schema.properties) ? schema.properties : {};
|
|
4199
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
4200
|
+
const props = {};
|
|
4201
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
4202
|
+
if (!isRecord$1(value)) continue;
|
|
4203
|
+
const name = required.includes(key) ? key : `${key}?`;
|
|
4204
|
+
props[name] = descriptions ? describedType(value, 1) : compactType(value, 1);
|
|
4205
|
+
}
|
|
4206
|
+
return props;
|
|
4207
|
+
}
|
|
4208
|
+
/**
|
|
4209
|
+
* The prop set worth listing once. Candidates are (key, type) pairs that at
|
|
4210
|
+
* least {@link COMMON_PROP_MIN_COMPONENTS} components carry verbatim. The
|
|
4211
|
+
* candidate subset of each component is a possible common set, scored by
|
|
4212
|
+
* the characters it saves (set size times the components that contain all
|
|
4213
|
+
* of it). `undefined` when no set is shared by enough components.
|
|
4214
|
+
*/
|
|
4215
|
+
function findCommonProps(propsList) {
|
|
4216
|
+
const pairKey = (key, type) => `${key}\u0000${type}`;
|
|
4217
|
+
const counts = /* @__PURE__ */ new Map();
|
|
4218
|
+
for (const props of propsList) for (const [key, type] of Object.entries(props)) {
|
|
4219
|
+
var _counts$get;
|
|
4220
|
+
const id = pairKey(key, type);
|
|
4221
|
+
counts.set(id, ((_counts$get = counts.get(id)) !== null && _counts$get !== void 0 ? _counts$get : 0) + 1);
|
|
4222
|
+
}
|
|
4223
|
+
let best;
|
|
4224
|
+
let bestScore = 0;
|
|
4225
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4226
|
+
for (const props of propsList) {
|
|
4227
|
+
const subset = Object.entries(props).filter(([key, type]) => {
|
|
4228
|
+
var _counts$get2;
|
|
4229
|
+
return ((_counts$get2 = counts.get(pairKey(key, type))) !== null && _counts$get2 !== void 0 ? _counts$get2 : 0) >= COMMON_PROP_MIN_COMPONENTS;
|
|
4230
|
+
});
|
|
4231
|
+
if (subset.length < 2) continue;
|
|
4232
|
+
const signature = subset.map(([key, type]) => pairKey(key, type)).join("\n");
|
|
4233
|
+
if (seen.has(signature)) continue;
|
|
4234
|
+
seen.add(signature);
|
|
4235
|
+
const members = propsList.filter((other) => subset.every(([key, type]) => other[key] === type)).length;
|
|
4236
|
+
if (members < COMMON_PROP_MIN_COMPONENTS) continue;
|
|
4237
|
+
const score = subset.reduce((total, [key, type]) => total + key.length + type.length, 0) * (members - 1);
|
|
4238
|
+
if (score > bestScore) {
|
|
4239
|
+
bestScore = score;
|
|
4240
|
+
best = Object.fromEntries(subset);
|
|
4241
|
+
}
|
|
4242
|
+
}
|
|
4243
|
+
return best;
|
|
4244
|
+
}
|
|
4245
|
+
/**
|
|
4246
|
+
* The component schema of the markdown transport, from the per-run
|
|
4247
|
+
* manifest. It is smaller than the manifest: each prop is one short type,
|
|
4248
|
+
* and the props that many components share verbatim (the layout props of
|
|
4249
|
+
* the containers) are listed once in `commonProps`; a component that takes
|
|
4250
|
+
* them is flagged `includesCommonProps`.
|
|
4251
|
+
* It has the catalog id, the targets with their descriptions and their
|
|
4252
|
+
* component lists, the functions with their parameters, the components
|
|
4253
|
+
* with their props, events and slots, and the surfaces of the thread. A surface lists the
|
|
4254
|
+
* values that the user set and the operations that the client dropped.
|
|
4255
|
+
*
|
|
4256
|
+
* @param manifest - The manifest from `buildGenerativeUIManifest`.
|
|
4257
|
+
* @param options - `propDescriptions` (default true) writes each prop's
|
|
4258
|
+
* description; `commonProps` (default true) lists shared props once.
|
|
4259
|
+
* @returns A JSON-ready object.
|
|
4260
|
+
*
|
|
4261
|
+
* @example
|
|
4262
|
+
* ```ts
|
|
4263
|
+
* const value = JSON.stringify(
|
|
4264
|
+
* buildCompactGenerativeUISchema(buildGenerativeUIManifest(runtime, threadId)),
|
|
4265
|
+
* );
|
|
4266
|
+
* ```
|
|
4267
|
+
*/
|
|
4268
|
+
function buildCompactGenerativeUISchema(manifest, options = {}) {
|
|
4269
|
+
const { propDescriptions = true, commonProps = true } = options;
|
|
4270
|
+
const components = {};
|
|
4271
|
+
for (const [name, component] of Object.entries(manifest.components)) {
|
|
4272
|
+
var _component$events;
|
|
4273
|
+
const events = Object.entries((_component$events = component.events) !== null && _component$events !== void 0 ? _component$events : {}).map(([event, definition]) => {
|
|
4274
|
+
var _definition$descripti;
|
|
4275
|
+
return [event, (_definition$descripti = definition.description) !== null && _definition$descripti !== void 0 ? _definition$descripti : compactType(definition.parameters, 0)];
|
|
4276
|
+
});
|
|
4277
|
+
components[name] = {
|
|
4278
|
+
...component.description ? { description: component.description } : {},
|
|
4279
|
+
props: compactProps(component.props, propDescriptions),
|
|
4280
|
+
...events.length > 0 ? { events: Object.fromEntries(events) } : {},
|
|
4281
|
+
...component.slots ? { slots: component.slots } : {}
|
|
4282
|
+
};
|
|
4283
|
+
}
|
|
4284
|
+
const common = commonProps ? findCommonProps(Object.values(components).map((component) => component.props)) : void 0;
|
|
4285
|
+
if (common) {
|
|
4286
|
+
const commonKeys = Object.keys(common);
|
|
4287
|
+
for (const component of Object.values(components)) {
|
|
4288
|
+
if (!commonKeys.every((key) => component.props[key] === common[key])) continue;
|
|
4289
|
+
component.includesCommonProps = true;
|
|
4290
|
+
component.props = Object.fromEntries(Object.entries(component.props).filter(([key]) => !(key in common)));
|
|
4291
|
+
}
|
|
4292
|
+
}
|
|
4293
|
+
const functions = Object.fromEntries(Object.entries(manifest.functions).map(([name, fn]) => {
|
|
4294
|
+
const signature = fn.parameters.description;
|
|
4295
|
+
const hasSignature = typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2;
|
|
4296
|
+
const callers = functionCallers(fn);
|
|
4297
|
+
return [name, {
|
|
4298
|
+
...fn.description ? { description: fn.description } : {},
|
|
4299
|
+
parameters: hasSignature ? signature : compactType(fn.parameters, 0),
|
|
4300
|
+
...callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? { callers: callers.renderer ? "UI or agent" : "agent only" } : {}
|
|
4301
|
+
}];
|
|
4302
|
+
}));
|
|
4303
|
+
return {
|
|
4304
|
+
catalogId: manifest.catalogId,
|
|
4305
|
+
targets: manifest.targets,
|
|
4306
|
+
functions,
|
|
4307
|
+
...common ? { commonProps: common } : {},
|
|
4308
|
+
components,
|
|
4309
|
+
surfaces: manifest.surfaces
|
|
4310
|
+
};
|
|
4311
|
+
}
|
|
4312
|
+
|
|
4313
|
+
//#endregion
|
|
4314
|
+
//#region src/generative-ui/schema-render.ts
|
|
4315
|
+
/** An own key (shared compiles to ES2017, which has no Object.hasOwn). */
|
|
4316
|
+
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
|
|
4317
|
+
function isRecord(value) {
|
|
4318
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4319
|
+
}
|
|
4320
|
+
/** The props schema without the description of each prop. */
|
|
4321
|
+
function withoutPropDescriptions(schema) {
|
|
4322
|
+
if (!isRecord(schema.properties)) return schema;
|
|
4323
|
+
return {
|
|
4324
|
+
...schema,
|
|
4325
|
+
properties: Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => {
|
|
4326
|
+
if (!isRecord(value)) return [key, value];
|
|
4327
|
+
const { description: _description, ...rest } = value;
|
|
4328
|
+
return [key, rest];
|
|
4329
|
+
}))
|
|
4330
|
+
};
|
|
4331
|
+
}
|
|
4332
|
+
/** The short signature of a function: its built-in signature, or its schema made short. */
|
|
4333
|
+
function functionSignature(fn) {
|
|
4334
|
+
const signature = fn.parameters.description;
|
|
4335
|
+
return typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2 ? signature : compactType(fn.parameters, 0);
|
|
4336
|
+
}
|
|
4337
|
+
/**
|
|
4338
|
+
* A function name with its parameters: `pick{ id: string }`, `clearCart{}`
|
|
4339
|
+
* for no arguments, `setVolume(number)` for a parameter that is not an object.
|
|
4340
|
+
*/
|
|
4341
|
+
function nameWithParameters(name, parameters) {
|
|
4342
|
+
if (parameters.startsWith("{")) return `${name}${parameters}`;
|
|
4343
|
+
if (parameters === "object") return `${name}{}`;
|
|
4344
|
+
return `${name}(${parameters})`;
|
|
4345
|
+
}
|
|
4346
|
+
/**
|
|
4347
|
+
* One component as a TypeScript-like signature line, with its events and
|
|
4348
|
+
* slots on the lines below:
|
|
4349
|
+
* `- Text(text?: string // The text): Shows text`.
|
|
4350
|
+
*/
|
|
4351
|
+
function signatureLines(name, component, settings) {
|
|
4352
|
+
var _component$events, _component$slots;
|
|
4353
|
+
const lines = [`- ${name}(${Object.entries(compactProps(component.props, settings.propDescriptions)).map(([key, type]) => `${key}: ${type}`).join(", ")})${component.description ? `: ${oneLine(component.description)}` : ""}`];
|
|
4354
|
+
const events = Object.entries((_component$events = component.events) !== null && _component$events !== void 0 ? _component$events : {}).map(([event, definition]) => `${event}(${definition.description ? oneLine(definition.description) : compactType(definition.parameters, 0)})`);
|
|
4355
|
+
if (events.length > 0) lines.push(` events: ${events.join(", ")}`);
|
|
4356
|
+
const slots = Object.entries((_component$slots = component.slots) !== null && _component$slots !== void 0 ? _component$slots : {}).map(([slot, kind]) => `${slot} (${kind})`);
|
|
4357
|
+
if (slots.length > 0) lines.push(` slots: ${slots.join(", ")}`);
|
|
4358
|
+
return lines;
|
|
4359
|
+
}
|
|
4360
|
+
/** The whole schema as signature text: targets, functions, components, surfaces. */
|
|
4361
|
+
function signatureSchema(manifest, settings) {
|
|
4362
|
+
const targets = manifest.targets.map((t) => {
|
|
4363
|
+
const limit = t.components ? `; only ${t.components.join(", ")}` : "";
|
|
4364
|
+
return `- ${t.id} (${t.kind}${limit})${t.description ? `: ${oneLine(t.description)}` : ""}`;
|
|
4365
|
+
});
|
|
4366
|
+
const functions = Object.entries(manifest.functions).map(([name, fn]) => {
|
|
4367
|
+
const callers = functionCallers(fn);
|
|
4368
|
+
const who = callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS ? callers.renderer ? " (UI or agent)" : " (agent only)" : "";
|
|
4369
|
+
return `- ${nameWithParameters(name, functionSignature(fn))}${who}${fn.description ? `: ${oneLine(fn.description)}` : ""}`;
|
|
4370
|
+
});
|
|
4371
|
+
const components = Object.entries(manifest.components).flatMap(([name, component]) => signatureLines(name, component, settings));
|
|
4372
|
+
const surfaces = Object.entries(manifest.surfaces).map(([id, s]) => {
|
|
4373
|
+
var _s$rejected;
|
|
4374
|
+
return `- ${id} (target ${s.target})${s.status ? ` status: ${s.status}` : ""}${s.dataModel ? ` user values: ${JSON.stringify(s.dataModel)}` : ""}${((_s$rejected = s.rejected) !== null && _s$rejected !== void 0 ? _s$rejected : []).map((r) => ` rejected: ${r}`).join("")}`;
|
|
4375
|
+
});
|
|
4376
|
+
return [
|
|
4377
|
+
`Catalog: ${manifest.catalogId}`,
|
|
4378
|
+
`Targets:\n${targets.join("\n") || "- none"}`,
|
|
4379
|
+
`Functions:\n${functions.join("\n") || "- none"}`,
|
|
4380
|
+
`Components:\n${components.join("\n") || "- none"}`,
|
|
4381
|
+
`Surfaces:\n${surfaces.join("\n") || "- none"}`
|
|
4382
|
+
].join("\n\n");
|
|
4383
|
+
}
|
|
4384
|
+
/** A description on one line, so its lines cannot read as new entries. */
|
|
4385
|
+
function oneLine(text) {
|
|
4386
|
+
return text.replace(/\s*\n\s*/g, " ");
|
|
4387
|
+
}
|
|
4388
|
+
/** Values that would read as a type or a number once their quotes are gone. */
|
|
4389
|
+
const AMBIGUOUS_VALUE = /^(?:string|number|integer|boolean|true|false|null|object|array|unknown|any|-?\d[\d.]*)$/;
|
|
4390
|
+
/**
|
|
4391
|
+
* A compact type with bare enum values and tight unions:
|
|
4392
|
+
* `"sm" | "md" | "lg"` becomes `sm|md|lg`. A union keeps its quotes when it
|
|
4393
|
+
* also holds a type (`"sm" | number`) or a value that reads as a type or a
|
|
4394
|
+
* number (`"number" | "currency"`, `"1" | "2"`), and so do values that are
|
|
4395
|
+
* not plain words.
|
|
4396
|
+
*/
|
|
4397
|
+
function bareType(type) {
|
|
4398
|
+
return type.replace(/"[A-Za-z0-9_#%.-]+"(?: \| "[A-Za-z0-9_#%.-]+")*(?! \|)/g, (union, offset, whole) => {
|
|
4399
|
+
if (whole.slice(offset - 2, offset) === "| ") return union;
|
|
4400
|
+
const values = union.split(" | ").map((v) => v.slice(1, -1));
|
|
4401
|
+
if (values.some((v) => AMBIGUOUS_VALUE.test(v))) return union;
|
|
4402
|
+
return values.join("|");
|
|
4403
|
+
}).replace(/ \| /g, "|");
|
|
4404
|
+
}
|
|
4405
|
+
/** A compact prop (`type // description`) as `name: type - description`. */
|
|
4406
|
+
function propLine(key, value) {
|
|
4407
|
+
const name = key.endsWith("?") ? key.slice(0, -1) : `${key}*`;
|
|
4408
|
+
const cut = value.indexOf(" // ");
|
|
4409
|
+
const type = bareType(cut < 0 ? value : value.slice(0, cut));
|
|
4410
|
+
const text = cut < 0 ? "" : value.slice(cut + 4).trim();
|
|
4411
|
+
return ` ${name}: ${type}${text ? ` - ${oneLine(text)}` : ""}`;
|
|
4412
|
+
}
|
|
4413
|
+
/**
|
|
4414
|
+
* The whole schema as plain lines: a header line per component and one
|
|
4415
|
+
* indented line per prop: events are `action` props and slots `componentId`
|
|
4416
|
+
* or `childList` props. Props are optional unless marked `*`, enum values
|
|
4417
|
+
* are bare, and the common props are listed once. It carries the same names, types and descriptions as
|
|
4418
|
+
* `compact`, in fewer tokens.
|
|
4419
|
+
*/
|
|
4420
|
+
function linesSchema(manifest, settings) {
|
|
4421
|
+
const compact = buildCompactGenerativeUISchema(manifest, {
|
|
4422
|
+
propDescriptions: settings.propDescriptions,
|
|
4423
|
+
commonProps: settings.commonProps
|
|
4424
|
+
});
|
|
4425
|
+
const targets = compact.targets.map((t) => {
|
|
4426
|
+
const limit = t.components ? `, only ${t.components.join(", ")}` : "";
|
|
4427
|
+
return `${t.id} (${t.kind}${limit})${t.description ? `: ${oneLine(t.description)}` : ""}`;
|
|
4428
|
+
}).join("; ");
|
|
4429
|
+
const functions = Object.entries(compact.functions).map(([name, fn]) => `${nameWithParameters(name, fn.parameters)}${"callers" in fn ? ` (${fn.callers})` : ""}${fn.description ? `: ${oneLine(fn.description)}` : ""}`);
|
|
4430
|
+
const common = compact.commonProps ? Object.entries(compact.commonProps).map(([k, v]) => propLine(k, v)) : [];
|
|
4431
|
+
const components = Object.entries(compact.components).map(([name, c]) => {
|
|
4432
|
+
var _c$events;
|
|
4433
|
+
return {
|
|
4434
|
+
name,
|
|
4435
|
+
c,
|
|
4436
|
+
own: [...Object.entries(c.props).map(([k, v]) => propLine(k, v)), ...Object.entries((_c$events = c.events) !== null && _c$events !== void 0 ? _c$events : {}).map(([e, d]) => ` ${e}: action - ${oneLine(d)}`)]
|
|
4437
|
+
};
|
|
4438
|
+
}).flatMap(({ name, c, own }) => {
|
|
4439
|
+
var _c$slots;
|
|
4440
|
+
const lines = [`${name}${c.includesCommonProps ? " +common" : ""}${c.description ? `: ${oneLine(c.description)}` : ""}`, ...own];
|
|
4441
|
+
for (const [slot, kind] of Object.entries((_c$slots = c.slots) !== null && _c$slots !== void 0 ? _c$slots : {})) lines.push(` ${slot}: ${kind === "single" ? "componentId" : "childList"}`);
|
|
4442
|
+
return lines;
|
|
4443
|
+
});
|
|
4444
|
+
const surfaces = Object.keys(compact.surfaces).length ? JSON.stringify(compact.surfaces) : "none";
|
|
4445
|
+
return [
|
|
4446
|
+
`Catalog ${compact.catalogId}. Targets: ${targets || "none"}`,
|
|
4447
|
+
"Props are optional unless marked *. a|b|c is one of those strings, quoted when one reads as a type or a number. A component marked +common also takes every common prop. A prop of type action is an event prop: give it {\"event\":{...}} or {\"functionCall\":{...}}. A componentId prop takes one component id; a childList prop takes a list of ids or a template.",
|
|
4448
|
+
`Functions:\n${functions.join("\n")}`,
|
|
4449
|
+
...common.length ? [`Common props:\n${common.join("\n")}`] : [],
|
|
4450
|
+
`Components:\n${components.join("\n")}`,
|
|
4451
|
+
`Surfaces: ${surfaces}`
|
|
4452
|
+
].join("\n\n");
|
|
4453
|
+
}
|
|
4454
|
+
/**
|
|
4455
|
+
* The component schema of the markdown transport, as the text of its
|
|
4456
|
+
* context entry, in the notation of `settings`. `compact` is the schema that
|
|
4457
|
+
* ships (`buildCompactGenerativeUISchema`), `json-schema` the manifest parts
|
|
4458
|
+
* as JSON, `ts-signature` one line per component, `lines` one line per
|
|
4459
|
+
* prop with bare enums (the fewest tokens).
|
|
4460
|
+
*
|
|
4461
|
+
* @example
|
|
4462
|
+
* ```ts
|
|
4463
|
+
* const value = renderGenerativeUISchema(manifest, spec.schema.markdown);
|
|
4464
|
+
* ```
|
|
4465
|
+
*/
|
|
4466
|
+
function renderGenerativeUISchema(manifest, settings) {
|
|
4467
|
+
switch (settings.notation) {
|
|
4468
|
+
case "compact": return JSON.stringify(buildCompactGenerativeUISchema(manifest, {
|
|
4469
|
+
propDescriptions: settings.propDescriptions,
|
|
4470
|
+
commonProps: settings.commonProps
|
|
4471
|
+
}));
|
|
4472
|
+
case "json-schema": {
|
|
4473
|
+
const components = Object.fromEntries(Object.entries(manifest.components).map(([name, c]) => [name, settings.propDescriptions ? c : {
|
|
4474
|
+
...c,
|
|
4475
|
+
props: withoutPropDescriptions(c.props)
|
|
4476
|
+
}]));
|
|
4477
|
+
return JSON.stringify({
|
|
4478
|
+
catalogId: manifest.catalogId,
|
|
4479
|
+
targets: manifest.targets,
|
|
4480
|
+
functions: manifest.functions,
|
|
4481
|
+
components,
|
|
4482
|
+
surfaces: manifest.surfaces
|
|
4483
|
+
});
|
|
4484
|
+
}
|
|
4485
|
+
case "ts-signature": return signatureSchema(manifest, settings);
|
|
4486
|
+
case "lines": return linesSchema(manifest, settings);
|
|
4487
|
+
}
|
|
4488
|
+
}
|
|
4489
|
+
/**
|
|
4490
|
+
* The component list of the tool guide, one entry per component, in the
|
|
4491
|
+
* notation of `settings`. `json-schema` is the list that ships.
|
|
4492
|
+
*/
|
|
4493
|
+
function renderGenerativeUIComponentList(components, settings) {
|
|
4494
|
+
return Object.entries(components).map(([name, c]) => {
|
|
4495
|
+
if (settings.notation === "ts-signature" || settings.notation === "lines") return signatureLines(name, c, settings).join("\n");
|
|
4496
|
+
const props = settings.notation === "compact" ? compactProps(c.props, settings.propDescriptions) : settings.propDescriptions ? c.props : withoutPropDescriptions(c.props);
|
|
4497
|
+
const lines = [`- **${name}**${c.description ? `: ${oneLine(c.description)}` : ""}`, ` props: ${JSON.stringify(props)}`];
|
|
4498
|
+
if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
|
|
4499
|
+
if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
|
|
4500
|
+
return lines.join("\n");
|
|
4501
|
+
}).join("\n");
|
|
4502
|
+
}
|
|
4503
|
+
/**
|
|
4504
|
+
* The manifest with replaced descriptions: `"Name"` replaces the
|
|
4505
|
+
* description of a component, `"Name.prop"` the description of one of its
|
|
4506
|
+
* props. Keys that name no component or prop are left out of the result
|
|
4507
|
+
* and listed in `unknown`. The manifest is not changed.
|
|
4508
|
+
*/
|
|
4509
|
+
function applyDescriptionOverrides(manifest, overrides) {
|
|
4510
|
+
const components = structuredClone(manifest.components);
|
|
4511
|
+
const unknown = [];
|
|
4512
|
+
for (const [key, description] of Object.entries(overrides)) {
|
|
4513
|
+
const [name, prop, ...rest] = key.split(".");
|
|
4514
|
+
const component = hasOwn(components, name) ? components[name] : void 0;
|
|
4515
|
+
if (!component || rest.length > 0) {
|
|
4516
|
+
unknown.push(key);
|
|
4517
|
+
continue;
|
|
4518
|
+
}
|
|
4519
|
+
if (prop === void 0) {
|
|
4520
|
+
component.description = description;
|
|
4521
|
+
continue;
|
|
4522
|
+
}
|
|
4523
|
+
const properties = component.props.properties;
|
|
4524
|
+
const property = isRecord(properties) && hasOwn(properties, prop) ? properties[prop] : void 0;
|
|
4525
|
+
if (!isRecord(property)) {
|
|
4526
|
+
unknown.push(key);
|
|
4527
|
+
continue;
|
|
4528
|
+
}
|
|
4529
|
+
property.description = description;
|
|
4530
|
+
}
|
|
4531
|
+
return {
|
|
4532
|
+
manifest: {
|
|
4533
|
+
...manifest,
|
|
4534
|
+
components
|
|
4535
|
+
},
|
|
4536
|
+
unknown
|
|
4537
|
+
};
|
|
4538
|
+
}
|
|
4539
|
+
/**
|
|
4540
|
+
* The components and props of `manifest` whose names do not appear in
|
|
4541
|
+
* `rendered`. A schema notation that leaves one out would hide part of the
|
|
4542
|
+
* catalog from the model.
|
|
4543
|
+
*/
|
|
4544
|
+
function schemaCoverage(manifest, rendered) {
|
|
4545
|
+
const missing = [];
|
|
4546
|
+
for (const [name, component] of Object.entries(manifest.components)) {
|
|
4547
|
+
if (!rendered.includes(name)) missing.push(name);
|
|
4548
|
+
const properties = isRecord(component.props.properties) ? component.props.properties : {};
|
|
4549
|
+
for (const prop of Object.keys(properties)) if (!rendered.includes(prop)) missing.push(`${name}.${prop}`);
|
|
4550
|
+
}
|
|
4551
|
+
return { missing };
|
|
4552
|
+
}
|
|
4553
|
+
|
|
3689
4554
|
//#endregion
|
|
3690
4555
|
//#region src/generative-ui/prompt.ts
|
|
3691
4556
|
const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
|
|
@@ -3700,19 +4565,15 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3700
4565
|
* the `render_ui` rules, the targets, components, functions, and surfaces of
|
|
3701
4566
|
* the manifest. It is in shared so that the inspector shows the same text.
|
|
3702
4567
|
*/
|
|
3703
|
-
function buildGenerativeUIPrompt(manifest) {
|
|
4568
|
+
function buildGenerativeUIPrompt(manifest, spec = defaultGenerativeUIPromptSpec()) {
|
|
4569
|
+
var _spec$tool$operations;
|
|
3704
4570
|
const targets = manifest.targets.map((t) => {
|
|
3705
4571
|
const place = t.kind === "chat" ? "inside the chat transcript" : "a named area of the app";
|
|
3706
4572
|
const limit = t.components ? `; only ${t.components.join(", ") || "no components"}` : "";
|
|
3707
4573
|
const description = t.description ? `: ${t.description}` : "";
|
|
3708
4574
|
return `- "${t.id}" (${place}${limit})${description}`;
|
|
3709
4575
|
}).join("\n");
|
|
3710
|
-
const components =
|
|
3711
|
-
const lines = [`- **${name}**${c.description ? `: ${c.description}` : ""}`, ` props: ${JSON.stringify(c.props)}`];
|
|
3712
|
-
if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
|
|
3713
|
-
if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
|
|
3714
|
-
return lines.join("\n");
|
|
3715
|
-
}).join("\n");
|
|
4576
|
+
const components = renderGenerativeUIComponentList(manifest.components, spec.schema.tool);
|
|
3716
4577
|
const functions = Object.entries(manifest.functions).map(([name, f]) => {
|
|
3717
4578
|
const signature = f.parameters.description;
|
|
3718
4579
|
const args = typeof signature === "string" && signature.startsWith("{") && Object.keys(f.parameters).length === 2 ? signature : JSON.stringify(f.parameters);
|
|
@@ -3731,38 +4592,15 @@ ${rules.map((rule) => `- ${rule}`).join("\n")}
|
|
|
3731
4592
|
var _s$rejected$length, _s$rejected2;
|
|
3732
4593
|
return s.dataModel !== void 0 || ((_s$rejected$length = (_s$rejected2 = s.rejected) === null || _s$rejected2 === void 0 ? void 0 : _s$rejected2.length) !== null && _s$rejected$length !== void 0 ? _s$rejected$length : 0) > 0;
|
|
3733
4594
|
}) ? "User values are what the user entered, by path. Your writes to those paths are ignored. Rejected operations were dropped: send them again with the problem fixed.\n" : "";
|
|
3734
|
-
const
|
|
3735
|
-
const
|
|
3736
|
-
const operations = [
|
|
3737
|
-
|
|
3738
|
-
"{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
|
|
3739
|
-
"{\"version\":\"v1.0\",\"updateDataModel\":{\"surfaceId\":\"<id>\",\"path\":\"/some/path\",\"value\":<json>}}: set the value at \"path\". Always give \"value\". \"value\":null deletes the key at \"path\".",
|
|
3740
|
-
"{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
|
|
3741
|
-
...agentCalls ? ["{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."] : []
|
|
3742
|
-
];
|
|
3743
|
-
const rules = [
|
|
3744
|
-
"Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
|
|
3745
|
-
"A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.",
|
|
3746
|
-
"Stream progressively: put the initial data in \"dataModel\" and the root in \"components\" of the createSurface operation, then send one updateComponents operation per child, so the UI appears while you are still writing. The root must already list the ids of its children in its slot props (for example \"children\":[\"card-1\",\"card-2\"]), even though the children come later. A component that no slot references is never shown.",
|
|
3747
|
-
"Updating a component replaces all of its props, so resend every prop.",
|
|
3748
|
-
"Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
|
|
3749
|
-
...events ? [hasFunctions ? "Event props take an action. {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}} runs an app function in the browser immediately, and you are not told about it. {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\". Only call functions listed below." : "Event props take an action: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} sends the interaction back to you as a user message, with \"userMessage\" as its first line. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\"."] : [],
|
|
3750
|
-
"To show a different view, create a new surface with a new surfaceId (for example, a checkout form after a cart summary). Update an existing surface only when the user asks to change that same view: then do not send createSurface, use its surfaceId, and pass its existing target. Never reuse an earlier chat surface for a different view, because that replaces the earlier UI and anything the user typed into it.",
|
|
3751
|
-
"Never use a surfaceId again, also after deleteSurface.",
|
|
3752
|
-
"A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Only call functions listed below. formatString interpolates ${/path} and ${fn(arg: value)} in its value.",
|
|
3753
|
-
"${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}.",
|
|
3754
|
-
"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
|
|
3755
|
-
...checks ? ["Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks."] : [],
|
|
3756
|
-
...templates ? ["To repeat a component for each item of a list, give a multiple slot a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}. Inside the template, paths are relative to the item (\"name\", not \"/name\"). {\"@call\":\"@index\"} gives the position of the item, from 0; {\"@call\":\"@index\",\"args\":{\"offset\":1}} counts from 1."] : [],
|
|
3757
|
-
...agentCalls ? ["Give every callRendererFunction a new functionCallId. Call only a function marked (UI or agent) or (agent only); a function with no mark is for the UI only. A function marked (agent only) is only for callRendererFunction: do not bind an event to it.", "The result of a callRendererFunction comes back to you in a new turn, as a developer message: {\"version\":\"v1.0\",\"rendererFunctionResponse\":{\"functionCallId\":\"<id>\",\"value\":...}}. If the call failed, it has \"error\" in place of \"value\". Do not wait for the result in this reply, and do not guess it."] : []
|
|
3758
|
-
];
|
|
4595
|
+
const features = generativeUIPromptFeatures(generativeUIGuideFeatures(manifest));
|
|
4596
|
+
const { intro, whenToShow } = spec.tool;
|
|
4597
|
+
const operations = selectPromptItems((_spec$tool$operations = spec.tool.operations) !== null && _spec$tool$operations !== void 0 ? _spec$tool$operations : [], features);
|
|
4598
|
+
const rules = selectPromptItems(spec.tool.rules, features);
|
|
3759
4599
|
return [
|
|
3760
4600
|
`## Generative UI
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
${GENERATIVE_UI_WHEN_TO_SHOW}
|
|
4601
|
+
${intro}
|
|
3764
4602
|
|
|
3765
|
-
Every operation has "version":"
|
|
4603
|
+
${whenToShow ? `${whenToShow}\n\n` : ""}Every operation has "version":"1.0" and exactly one of:
|
|
3766
4604
|
${operations.map((op) => `- ${op}`).join("\n")}
|
|
3767
4605
|
|
|
3768
4606
|
Rules:
|
|
@@ -3821,6 +4659,7 @@ ${rules.map((rule, index) => `${index + 1}. ${rule}`).join("\n")}`,
|
|
|
3821
4659
|
}
|
|
3822
4660
|
|
|
3823
4661
|
//#endregion
|
|
4662
|
+
exports.A2UI_BASIC_CATALOG_ID = A2UI_BASIC_CATALOG_ID;
|
|
3824
4663
|
exports.A2UI_BASIC_FUNCTIONS = A2UI_BASIC_FUNCTIONS;
|
|
3825
4664
|
exports.A2UI_CHILD_LIST_MARK = A2UI_CHILD_LIST_MARK;
|
|
3826
4665
|
exports.A2UI_CHILD_LIST_REF = A2UI_CHILD_LIST_REF;
|
|
@@ -3830,6 +4669,7 @@ exports.A2UI_COMPONENT_ID_REF = A2UI_COMPONENT_ID_REF;
|
|
|
3830
4669
|
exports.A2UI_DEFAULT_DESIGN_GUIDELINES = A2UI_DEFAULT_DESIGN_GUIDELINES;
|
|
3831
4670
|
exports.A2UI_DEFAULT_GENERATION_GUIDELINES = A2UI_DEFAULT_GENERATION_GUIDELINES;
|
|
3832
4671
|
exports.A2UI_INDEX_FUNCTION = A2UI_INDEX_FUNCTION;
|
|
4672
|
+
exports.A2UI_SCHEMA_CONTEXT_DESCRIPTION = A2UI_SCHEMA_CONTEXT_DESCRIPTION;
|
|
3833
4673
|
exports.A2UI_VERSION = A2UI_VERSION;
|
|
3834
4674
|
exports.AG_UI_CHANNEL_EVENT = AG_UI_CHANNEL_EVENT;
|
|
3835
4675
|
exports.ALL_GENERATIVE_UI_GUIDE_FEATURES = ALL_GENERATIVE_UI_GUIDE_FEATURES;
|
|
@@ -3870,11 +4710,14 @@ exports.GENERATIVE_UI_FUNCTION_CALL_ACTIVITY_TYPE = GENERATIVE_UI_FUNCTION_CALL_
|
|
|
3870
4710
|
exports.GENERATIVE_UI_MARKDOWN_GUIDELINES = GENERATIVE_UI_MARKDOWN_GUIDELINES;
|
|
3871
4711
|
exports.GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION = GENERATIVE_UI_MARKDOWN_GUIDELINES_DESCRIPTION;
|
|
3872
4712
|
exports.GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION = GENERATIVE_UI_MARKDOWN_SCHEMA_CONTEXT_DESCRIPTION;
|
|
4713
|
+
exports.GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW = GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW;
|
|
3873
4714
|
exports.GENERATIVE_UI_MAX_REJECTION_LENGTH = GENERATIVE_UI_MAX_REJECTION_LENGTH;
|
|
3874
4715
|
exports.GENERATIVE_UI_MAX_SUMMARY_REJECTIONS = GENERATIVE_UI_MAX_SUMMARY_REJECTIONS;
|
|
3875
4716
|
exports.GENERATIVE_UI_MAX_TARGET_COMPONENTS = GENERATIVE_UI_MAX_TARGET_COMPONENTS;
|
|
3876
4717
|
exports.GENERATIVE_UI_RENDER_TOOL = GENERATIVE_UI_RENDER_TOOL;
|
|
3877
4718
|
exports.GENERATIVE_UI_ROOT_ID = GENERATIVE_UI_ROOT_ID;
|
|
4719
|
+
exports.GENERATIVE_UI_WHEN_TO_SHOW = GENERATIVE_UI_WHEN_TO_SHOW;
|
|
4720
|
+
exports.GUIDE_COMPONENTS = GUIDE_COMPONENTS;
|
|
3878
4721
|
exports.MODEL_HOST_CLASSES = MODEL_HOST_CLASSES;
|
|
3879
4722
|
exports.MissingPublicApiKeyError = MissingPublicApiKeyError;
|
|
3880
4723
|
exports.RUNTIME_MODE_INTELLIGENCE = RUNTIME_MODE_INTELLIGENCE;
|
|
@@ -3893,6 +4736,9 @@ exports.UNSAMPLED_RATE = UNSAMPLED_RATE;
|
|
|
3893
4736
|
exports.UpgradeRequiredError = UpgradeRequiredError;
|
|
3894
4737
|
exports.actionParametersToJsonSchema = actionParametersToJsonSchema;
|
|
3895
4738
|
exports.applyChildRefMarks = applyChildRefMarks;
|
|
4739
|
+
exports.applyDescriptionOverrides = applyDescriptionOverrides;
|
|
4740
|
+
exports.buildA2UICatalogContextValue = buildA2UICatalogContextValue;
|
|
4741
|
+
exports.buildCompactGenerativeUISchema = buildCompactGenerativeUISchema;
|
|
3896
4742
|
exports.buildGenerativeUIMarkdownGuidelines = buildGenerativeUIMarkdownGuidelines;
|
|
3897
4743
|
exports.buildGenerativeUIPrompt = buildGenerativeUIPrompt;
|
|
3898
4744
|
exports.callerProblem = callerProblem;
|
|
@@ -3909,10 +4755,12 @@ exports.createLicenseContextValue = createLicenseContextValue;
|
|
|
3909
4755
|
exports.createRowKeyStore = createRowKeyStore;
|
|
3910
4756
|
exports.createRunEventFinalizer = createRunEventFinalizer;
|
|
3911
4757
|
exports.dataToUUID = dataToUUID;
|
|
4758
|
+
exports.defaultGenerativeUIPromptSpec = defaultGenerativeUIPromptSpec;
|
|
3912
4759
|
exports.ensureStructuredError = ensureStructuredError;
|
|
3913
4760
|
exports.envelopeToManifest = envelopeToManifest;
|
|
3914
4761
|
exports.exceedsMaxSize = exceedsMaxSize;
|
|
3915
4762
|
exports.executeConditions = executeConditions;
|
|
4763
|
+
exports.extractA2UICatalogSchemas = extractA2UICatalogSchemas;
|
|
3916
4764
|
exports.extractRenderUIArgs = extractRenderUIArgs;
|
|
3917
4765
|
exports.finalizeRunEvents = finalizeRunEvents;
|
|
3918
4766
|
exports.firstNonBlankTelemetryId = firstNonBlankTelemetryId;
|
|
@@ -3921,6 +4769,7 @@ exports.functionCallers = functionCallers;
|
|
|
3921
4769
|
exports.generateVideoThumbnail = generateVideoThumbnail;
|
|
3922
4770
|
exports.generativeUIFunctionCallMessageId = generativeUIFunctionCallMessageId;
|
|
3923
4771
|
exports.generativeUIGuideFeatures = generativeUIGuideFeatures;
|
|
4772
|
+
exports.generativeUIPromptFeatures = generativeUIPromptFeatures;
|
|
3924
4773
|
exports.generativeUISurfaceMessageId = generativeUISurfaceMessageId;
|
|
3925
4774
|
exports.getDocumentIcon = getDocumentIcon;
|
|
3926
4775
|
exports.getModalityFromMimeType = getModalityFromMimeType;
|
|
@@ -3964,11 +4813,16 @@ exports.randomUUID = randomUUID;
|
|
|
3964
4813
|
exports.readBody = readBody;
|
|
3965
4814
|
exports.readCopilotKitUIEnvelope = readCopilotKitUIEnvelope;
|
|
3966
4815
|
exports.readFileAsBase64 = readFileAsBase64;
|
|
4816
|
+
exports.renderGenerativeUIComponentList = renderGenerativeUIComponentList;
|
|
4817
|
+
exports.renderGenerativeUISchema = renderGenerativeUISchema;
|
|
3967
4818
|
exports.resolveDebugConfig = resolveDebugConfig;
|
|
3968
4819
|
exports.resolveRowRenderKeys = resolveRowRenderKeys;
|
|
3969
4820
|
exports.resolveRowRenderKeysById = resolveRowRenderKeysById;
|
|
3970
4821
|
exports.safeParseToolArgs = safeParseToolArgs;
|
|
4822
|
+
exports.schemaCoverage = schemaCoverage;
|
|
3971
4823
|
exports.schemaToJsonSchema = schemaToJsonSchema;
|
|
4824
|
+
exports.selectPromptItems = selectPromptItems;
|
|
4825
|
+
exports.serializeA2UISchema = serializeA2UISchema;
|
|
3972
4826
|
exports.shouldEnableInspector = shouldEnableInspector;
|
|
3973
4827
|
exports.stripIntelligenceRoutingFields = stripIntelligenceRoutingFields;
|
|
3974
4828
|
exports.styledConsole = styledConsole;
|