@copilotkit/shared 2.0.0-rc.1 → 2.0.0-rc.10
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/README.md +3 -14
- 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/index.cjs +17 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -9
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +10 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -7
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +808 -438
- package/dist/index.umd.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.mjs +1 -1
- package/dist/standard-schema.cjs +20 -7
- package/dist/standard-schema.cjs.map +1 -1
- package/dist/standard-schema.d.cts +15 -16
- package/dist/standard-schema.d.cts.map +1 -1
- package/dist/standard-schema.d.mts +15 -16
- package/dist/standard-schema.d.mts.map +1 -1
- package/dist/standard-schema.mjs +20 -8
- package/dist/standard-schema.mjs.map +1 -1
- package/dist/telemetry/lambda-client.cjs.map +1 -1
- package/dist/telemetry/lambda-client.d.cts.map +1 -1
- package/dist/telemetry/lambda-client.d.mts.map +1 -1
- package/dist/telemetry/lambda-client.mjs.map +1 -1
- package/dist/telemetry/telemetry-disabled.cjs +3 -6
- package/dist/telemetry/telemetry-disabled.cjs.map +1 -1
- package/dist/telemetry/telemetry-disabled.d.cts +0 -5
- package/dist/telemetry/telemetry-disabled.d.cts.map +1 -1
- package/dist/telemetry/telemetry-disabled.d.mts +0 -5
- package/dist/telemetry/telemetry-disabled.d.mts.map +1 -1
- package/dist/telemetry/telemetry-disabled.mjs +4 -6
- package/dist/telemetry/telemetry-disabled.mjs.map +1 -1
- package/dist/types/message.d.cts +1 -18
- package/dist/types/message.d.cts.map +1 -1
- package/dist/types/message.d.mts +1 -18
- package/dist/types/message.d.mts.map +1 -1
- package/dist/utils/errors.cjs +4 -42
- package/dist/utils/errors.cjs.map +1 -1
- package/dist/utils/errors.d.cts +16 -34
- package/dist/utils/errors.d.cts.map +1 -1
- package/dist/utils/errors.d.mts +16 -34
- package/dist/utils/errors.d.mts.map +1 -1
- package/dist/utils/errors.mjs +5 -41
- package/dist/utils/errors.mjs.map +1 -1
- package/dist/utils/index.cjs +1 -2
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +4 -5
- package/dist/utils/index.d.cts.map +1 -1
- package/dist/utils/index.d.mts +4 -5
- package/dist/utils/index.d.mts.map +1 -1
- package/dist/utils/index.mjs +4 -5
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/json-schema.cjs +0 -79
- package/dist/utils/json-schema.cjs.map +1 -1
- package/dist/utils/json-schema.d.cts +1 -4
- package/dist/utils/json-schema.d.cts.map +1 -1
- package/dist/utils/json-schema.d.mts +1 -4
- package/dist/utils/json-schema.d.mts.map +1 -1
- package/dist/utils/json-schema.mjs +1 -78
- package/dist/utils/json-schema.mjs.map +1 -1
- package/dist/utils/process-env.cjs +14 -0
- package/dist/utils/process-env.cjs.map +1 -0
- package/dist/utils/process-env.d.cts +10 -0
- package/dist/utils/process-env.d.cts.map +1 -0
- package/dist/utils/process-env.d.mts +10 -0
- package/dist/utils/process-env.d.mts.map +1 -0
- package/dist/utils/process-env.mjs +13 -0
- package/dist/utils/process-env.mjs.map +1 -0
- package/dist/utils/random-id.cjs +13 -26
- package/dist/utils/random-id.cjs.map +1 -1
- package/dist/utils/random-id.d.cts +6 -3
- package/dist/utils/random-id.d.cts.map +1 -1
- package/dist/utils/random-id.d.mts +6 -3
- package/dist/utils/random-id.d.mts.map +1 -1
- package/dist/utils/random-id.mjs +14 -25
- package/dist/utils/random-id.mjs.map +1 -1
- package/package.json +7 -31
- package/src/__tests__/a2ui-prompts.test.ts +42 -9
- package/src/__tests__/fixtures/prompt-goldens.json +354 -0
- package/src/__tests__/prompt-spec.test.ts +191 -0
- package/src/__tests__/root-entry-browser-safety.test.ts +5 -7
- package/src/__tests__/schema-render.test.ts +245 -0
- package/src/__tests__/standard-schema.test.ts +61 -101
- package/src/a2ui-prompts.ts +47 -96
- 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/index.ts +3 -16
- package/src/standard-schema.ts +24 -27
- package/src/telemetry/lambda-client.ts +3 -2
- package/src/telemetry/telemetry-disabled.ts +7 -12
- package/src/types/message.ts +1 -19
- package/src/utils/__tests__/errors.test.ts +44 -0
- package/src/utils/__tests__/json-schema.test.ts +3 -479
- package/src/utils/__tests__/process-env.test.ts +22 -0
- package/src/utils/__tests__/random-id.test.ts +37 -0
- package/src/utils/errors.ts +27 -85
- package/src/utils/index.ts +1 -2
- package/src/utils/json-schema.ts +1 -152
- package/src/utils/process-env.ts +14 -0
- package/src/utils/random-id.ts +17 -37
- package/tsdown.config.ts +2 -19
- package/dist/event-transforms/index.cjs +0 -15
- package/dist/event-transforms/index.d.cts +0 -4
- package/dist/event-transforms/index.d.mts +0 -4
- package/dist/event-transforms/index.mjs +0 -5
- package/dist/event-transforms/open-generative-ui-middleware.cjs +0 -286
- package/dist/event-transforms/open-generative-ui-middleware.cjs.map +0 -1
- package/dist/event-transforms/open-generative-ui-middleware.d.cts +0 -60
- package/dist/event-transforms/open-generative-ui-middleware.d.cts.map +0 -1
- package/dist/event-transforms/open-generative-ui-middleware.d.mts +0 -60
- package/dist/event-transforms/open-generative-ui-middleware.d.mts.map +0 -1
- package/dist/event-transforms/open-generative-ui-middleware.mjs +0 -283
- package/dist/event-transforms/open-generative-ui-middleware.mjs.map +0 -1
- package/dist/event-transforms/recorded-events.cjs +0 -59
- package/dist/event-transforms/recorded-events.cjs.map +0 -1
- package/dist/event-transforms/recorded-events.d.cts +0 -23
- package/dist/event-transforms/recorded-events.d.cts.map +0 -1
- package/dist/event-transforms/recorded-events.d.mts +0 -23
- package/dist/event-transforms/recorded-events.d.mts.map +0 -1
- package/dist/event-transforms/recorded-events.mjs +0 -58
- package/dist/event-transforms/recorded-events.mjs.map +0 -1
- package/dist/telemetry/events.d.cts +0 -72
- package/dist/telemetry/events.d.cts.map +0 -1
- package/dist/telemetry/events.d.mts +0 -72
- package/dist/telemetry/events.d.mts.map +0 -1
- package/dist/telemetry/index.cjs +0 -18
- package/dist/telemetry/index.d.cts +0 -5
- package/dist/telemetry/index.d.mts +0 -5
- package/dist/telemetry/index.mjs +0 -6
- package/dist/telemetry/telemetry-client.cjs +0 -165
- package/dist/telemetry/telemetry-client.cjs.map +0 -1
- package/dist/telemetry/telemetry-client.d.cts +0 -87
- package/dist/telemetry/telemetry-client.d.cts.map +0 -1
- package/dist/telemetry/telemetry-client.d.mts +0 -87
- package/dist/telemetry/telemetry-client.d.mts.map +0 -1
- package/dist/telemetry/telemetry-client.mjs +0 -164
- package/dist/telemetry/telemetry-client.mjs.map +0 -1
- package/dist/telemetry/utils.cjs +0 -14
- package/dist/telemetry/utils.cjs.map +0 -1
- package/dist/telemetry/utils.mjs +0 -13
- package/dist/telemetry/utils.mjs.map +0 -1
- package/dist/utils/conditions.cjs +0 -32
- package/dist/utils/conditions.cjs.map +0 -1
- package/dist/utils/conditions.d.cts +0 -31
- package/dist/utils/conditions.d.cts.map +0 -1
- package/dist/utils/conditions.d.mts +0 -31
- package/dist/utils/conditions.d.mts.map +0 -1
- package/dist/utils/conditions.mjs +0 -31
- package/dist/utils/conditions.mjs.map +0 -1
- package/dist/utils/console-styling.cjs +0 -91
- package/dist/utils/console-styling.cjs.map +0 -1
- package/dist/utils/console-styling.d.cts +0 -65
- package/dist/utils/console-styling.d.cts.map +0 -1
- package/dist/utils/console-styling.d.mts +0 -65
- package/dist/utils/console-styling.d.mts.map +0 -1
- package/dist/utils/console-styling.mjs +0 -85
- package/dist/utils/console-styling.mjs.map +0 -1
- package/src/__tests__/zod-regression.test.ts +0 -319
- package/src/event-transforms/index.ts +0 -5
- package/src/event-transforms/open-generative-ui-middleware.ts +0 -392
- package/src/event-transforms/recorded-events.test.ts +0 -166
- package/src/event-transforms/recorded-events.ts +0 -74
- package/src/telemetry/events.ts +0 -68
- package/src/telemetry/index.ts +0 -9
- package/src/telemetry/telemetry-blank-license-identity.test.ts +0 -128
- package/src/telemetry/telemetry-client.test.ts +0 -798
- package/src/telemetry/telemetry-client.ts +0 -328
- package/src/telemetry/utils.ts +0 -15
- package/src/utils/__tests__/conditions.test.ts +0 -161
- package/src/utils/conditions.ts +0 -116
- package/src/utils/console-styling.ts +0 -126
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
const require_basic_functions = require('./basic-functions.cjs');
|
|
2
2
|
const require_types = require('./types.cjs');
|
|
3
|
+
const require_prompt_spec = require('./prompt-spec.cjs');
|
|
3
4
|
const require_a2ui_prompts = require('../a2ui-prompts.cjs');
|
|
5
|
+
const require_schema_render = require('./schema-render.cjs');
|
|
4
6
|
|
|
5
7
|
//#region src/generative-ui/prompt.ts
|
|
6
8
|
const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
|
|
@@ -15,19 +17,14 @@ function shorten(text) {
|
|
|
15
17
|
* the `render_ui` rules, the targets, components, functions, and surfaces of
|
|
16
18
|
* the manifest. It is in shared so that the inspector shows the same text.
|
|
17
19
|
*/
|
|
18
|
-
function buildGenerativeUIPrompt(manifest) {
|
|
20
|
+
function buildGenerativeUIPrompt(manifest, spec = require_prompt_spec.defaultGenerativeUIPromptSpec()) {
|
|
19
21
|
const targets = manifest.targets.map((t) => {
|
|
20
22
|
const place = t.kind === "chat" ? "inside the chat transcript" : "a named area of the app";
|
|
21
23
|
const limit = t.components ? `; only ${t.components.join(", ") || "no components"}` : "";
|
|
22
24
|
const description = t.description ? `: ${t.description}` : "";
|
|
23
25
|
return `- "${t.id}" (${place}${limit})${description}`;
|
|
24
26
|
}).join("\n");
|
|
25
|
-
const components =
|
|
26
|
-
const lines = [`- **${name}**${c.description ? `: ${c.description}` : ""}`, ` props: ${JSON.stringify(c.props)}`];
|
|
27
|
-
if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
|
|
28
|
-
if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
|
|
29
|
-
return lines.join("\n");
|
|
30
|
-
}).join("\n");
|
|
27
|
+
const components = require_schema_render.renderGenerativeUIComponentList(manifest.components, spec.schema.tool);
|
|
31
28
|
const functions = Object.entries(manifest.functions).map(([name, f]) => {
|
|
32
29
|
const signature = f.parameters.description;
|
|
33
30
|
const args = typeof signature === "string" && signature.startsWith("{") && Object.keys(f.parameters).length === 2 ? signature : JSON.stringify(f.parameters);
|
|
@@ -42,38 +39,15 @@ function buildGenerativeUIPrompt(manifest) {
|
|
|
42
39
|
return lines.join("\n");
|
|
43
40
|
}).join("\n");
|
|
44
41
|
const surfaceNotes = Object.values(manifest.surfaces).some((s) => s.dataModel !== void 0 || (s.rejected?.length ?? 0) > 0) ? "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" : "";
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
const operations = [
|
|
48
|
-
|
|
49
|
-
"{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
|
|
50
|
-
"{\"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\".",
|
|
51
|
-
"{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
|
|
52
|
-
...agentCalls ? ["{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."] : []
|
|
53
|
-
];
|
|
54
|
-
const rules = [
|
|
55
|
-
"Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
|
|
56
|
-
"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.",
|
|
57
|
-
"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.",
|
|
58
|
-
"Updating a component replaces all of its props, so resend every prop.",
|
|
59
|
-
"Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
|
|
60
|
-
...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\"."] : [],
|
|
61
|
-
"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.",
|
|
62
|
-
"Never use a surfaceId again, also after deleteSurface.",
|
|
63
|
-
"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.",
|
|
64
|
-
"${...} 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\"}}}.",
|
|
65
|
-
"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
|
|
66
|
-
...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."] : [],
|
|
67
|
-
...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."] : [],
|
|
68
|
-
...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."] : []
|
|
69
|
-
];
|
|
42
|
+
const features = require_prompt_spec.generativeUIPromptFeatures(require_a2ui_prompts.generativeUIGuideFeatures(manifest));
|
|
43
|
+
const { intro, whenToShow } = spec.tool;
|
|
44
|
+
const operations = require_prompt_spec.selectPromptItems(spec.tool.operations ?? [], features);
|
|
45
|
+
const rules = require_prompt_spec.selectPromptItems(spec.tool.rules, features);
|
|
70
46
|
return [
|
|
71
47
|
`## Generative UI
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
${require_a2ui_prompts.GENERATIVE_UI_WHEN_TO_SHOW}
|
|
48
|
+
${intro}
|
|
75
49
|
|
|
76
|
-
Every operation has "version":"v1.0" and exactly one of:
|
|
50
|
+
${whenToShow ? `${whenToShow}\n\n` : ""}Every operation has "version":"v1.0" and exactly one of:
|
|
77
51
|
${operations.map((op) => `- ${op}`).join("\n")}
|
|
78
52
|
|
|
79
53
|
Rules:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.cjs","names":["functionCallers","GENERATIVE_UI_AGENT_FUNCTION_CALLS","generativeUIGuideFeatures","GENERATIVE_UI_RENDER_TOOL","GENERATIVE_UI_WHEN_TO_SHOW"],"sources":["../../src/generative-ui/prompt.ts"],"sourcesContent":["import {\n GENERATIVE_UI_WHEN_TO_SHOW,\n generativeUIGuideFeatures,\n} from \"../a2ui-prompts\";\nimport { functionCallers } from \"./basic-functions\";\nimport {\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_RENDER_TOOL,\n} from \"./types\";\nimport type { GenerativeUIManifest } from \"./types\";\n\nexport const GENERATIVE_UI_CONTEXT_DESCRIPTION =\n \"Generative UI guide: available components, functions, targets, and how to call render_ui.\";\n\n/** Most characters of the user values of one surface in the guide. */\nconst MAX_USER_VALUES_LENGTH = 500;\n\n/** Cuts long text and marks the cut with \"...\". */\nfunction shorten(text: string) {\n return text.length > MAX_USER_VALUES_LENGTH\n ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...`\n : text;\n}\n\n/**\n * The guide that the runtime adds as a context entry to a tool-transport run:\n * the `render_ui` rules, the targets, components, functions, and surfaces of\n * the manifest. It is in shared so that the inspector shows the same text.\n */\nexport function buildGenerativeUIPrompt(manifest: GenerativeUIManifest) {\n const targets = manifest.targets\n .map((t) => {\n const place =\n t.kind === \"chat\"\n ? \"inside the chat transcript\"\n : \"a named area of the app\";\n const limit = t.components\n ? `; only ${t.components.join(\", \") || \"no components\"}`\n : \"\";\n const description = t.description ? `: ${t.description}` : \"\";\n return `- \"${t.id}\" (${place}${limit})${description}`;\n })\n .join(\"\\n\");\n const components = Object.entries(manifest.components)\n .map(([name, c]) => {\n const lines = [\n `- **${name}**${c.description ? `: ${c.description}` : \"\"}`,\n ` props: ${JSON.stringify(c.props)}`,\n ];\n if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);\n if (c.slots)\n lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const functions = Object.entries(manifest.functions)\n .map(([name, f]) => {\n // A built-in function carries its short signature in the description\n // of its parameters; an app function has a JSON Schema.\n const signature = f.parameters.description;\n const args =\n typeof signature === \"string\" &&\n signature.startsWith(\"{\") &&\n Object.keys(f.parameters).length === 2\n ? signature\n : JSON.stringify(f.parameters);\n // A function is for the UI unless marked: the agent calls only what\n // the mark allows.\n const callers = functionCallers(f);\n const who =\n callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS\n ? callers.renderer\n ? \" (UI or agent)\"\n : \" (agent only)\"\n : \"\";\n return `- **${name}**${who}${f.description ? `: ${f.description}` : \"\"}\\n args: ${args}`;\n })\n .join(\"\\n\");\n const surfaces = Object.entries(manifest.surfaces)\n .map(([id, s]) => {\n const state =\n s.status === \"deleted\"\n ? \", deleted: never use this id again\"\n : s.status === \"failed\"\n ? \", not created: send a corrected createSurface with this id\"\n : \"\";\n const lines = [`- \"${id}\" (target \"${s.target}\"${state})`];\n if (s.dataModel) {\n lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);\n }\n for (const rejection of s.rejected ?? []) {\n lines.push(` rejected: ${rejection}`);\n }\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const hasSurfaceNotes = Object.values(manifest.surfaces).some(\n (s) => s.dataModel !== undefined || (s.rejected?.length ?? 0) > 0,\n );\n const surfaceNotes = hasSurfaceNotes\n ? \"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\"\n : \"\";\n\n // Rules for functions, events, and templates go only to runs whose manifest\n // has them, so the guide stays small.\n const {\n functions: hasFunctions,\n events,\n templates,\n checks,\n } = generativeUIGuideFeatures(manifest);\n // The agent calls functions only while that path is on.\n const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;\n const operations = [\n '{\"version\":\"v1.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.',\n '{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.',\n '{\"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\".',\n '{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.',\n ...(agentCalls\n ? [\n '{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface.',\n ]\n : []),\n ];\n const eventRule = hasFunctions\n ? '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.'\n : '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\".';\n const rules = [\n 'Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.',\n 'A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.',\n '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.',\n \"Updating a component replaces all of its props, so resend every prop.\",\n 'Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.',\n ...(events ? [eventRule] : []),\n \"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.\",\n \"Never use a surfaceId again, also after deleteSurface.\",\n '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.',\n '${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}.',\n \"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.\",\n ...(checks\n ? [\n 'Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks.',\n ]\n : []),\n ...(templates\n ? [\n '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.',\n ]\n : []),\n ...(agentCalls\n ? [\n \"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.\",\n '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.',\n ]\n : []),\n ];\n\n return [\n `## Generative UI\nCall \\`${GENERATIVE_UI_RENDER_TOOL}\\` to show UI. Arguments: \\`target\\` first, then \\`operations\\` (A2UI v1.0 operations, applied in order).\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nEvery operation has \"version\":\"v1.0\" and exactly one of:\n${operations.map((op) => `- ${op}`).join(\"\\n\")}\n\nRules:\n${rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")}`,\n `### Targets\\n${targets || \"- none\"}`,\n `### Components\\n${components || \"- none\"}`,\n `### Functions\\n${functions || \"- none\"}`,\n `### Existing surfaces\\n${surfaceNotes}${surfaces || \"- none\"}`,\n ].join(\"\\n\\n\");\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"prompt.cjs","names":["defaultGenerativeUIPromptSpec","renderGenerativeUIComponentList","functionCallers","GENERATIVE_UI_AGENT_FUNCTION_CALLS","generativeUIPromptFeatures","generativeUIGuideFeatures","selectPromptItems"],"sources":["../../src/generative-ui/prompt.ts"],"sourcesContent":["import { generativeUIGuideFeatures } from \"../a2ui-prompts\";\nimport { functionCallers } from \"./basic-functions\";\nimport {\n defaultGenerativeUIPromptSpec,\n generativeUIPromptFeatures,\n selectPromptItems,\n} from \"./prompt-spec\";\nimport type { GenerativeUIPromptSpec } from \"./prompt-spec\";\nimport { renderGenerativeUIComponentList } from \"./schema-render\";\nimport { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from \"./types\";\nimport type { GenerativeUIManifest } from \"./types\";\n\nexport const GENERATIVE_UI_CONTEXT_DESCRIPTION =\n \"Generative UI guide: available components, functions, targets, and how to call render_ui.\";\n\n/** Most characters of the user values of one surface in the guide. */\nconst MAX_USER_VALUES_LENGTH = 500;\n\n/** Cuts long text and marks the cut with \"...\". */\nfunction shorten(text: string) {\n return text.length > MAX_USER_VALUES_LENGTH\n ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...`\n : text;\n}\n\n/**\n * The guide that the runtime adds as a context entry to a tool-transport run:\n * the `render_ui` rules, the targets, components, functions, and surfaces of\n * the manifest. It is in shared so that the inspector shows the same text.\n */\nexport function buildGenerativeUIPrompt(\n manifest: GenerativeUIManifest,\n spec: GenerativeUIPromptSpec = defaultGenerativeUIPromptSpec(),\n) {\n const targets = manifest.targets\n .map((t) => {\n const place =\n t.kind === \"chat\"\n ? \"inside the chat transcript\"\n : \"a named area of the app\";\n const limit = t.components\n ? `; only ${t.components.join(\", \") || \"no components\"}`\n : \"\";\n const description = t.description ? `: ${t.description}` : \"\";\n return `- \"${t.id}\" (${place}${limit})${description}`;\n })\n .join(\"\\n\");\n const components = renderGenerativeUIComponentList(\n manifest.components,\n spec.schema.tool,\n );\n const functions = Object.entries(manifest.functions)\n .map(([name, f]) => {\n // A built-in function carries its short signature in the description\n // of its parameters; an app function has a JSON Schema.\n const signature = f.parameters.description;\n const args =\n typeof signature === \"string\" &&\n signature.startsWith(\"{\") &&\n Object.keys(f.parameters).length === 2\n ? signature\n : JSON.stringify(f.parameters);\n // A function is for the UI unless marked: the agent calls only what\n // the mark allows.\n const callers = functionCallers(f);\n const who =\n callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS\n ? callers.renderer\n ? \" (UI or agent)\"\n : \" (agent only)\"\n : \"\";\n return `- **${name}**${who}${f.description ? `: ${f.description}` : \"\"}\\n args: ${args}`;\n })\n .join(\"\\n\");\n const surfaces = Object.entries(manifest.surfaces)\n .map(([id, s]) => {\n const state =\n s.status === \"deleted\"\n ? \", deleted: never use this id again\"\n : s.status === \"failed\"\n ? \", not created: send a corrected createSurface with this id\"\n : \"\";\n const lines = [`- \"${id}\" (target \"${s.target}\"${state})`];\n if (s.dataModel) {\n lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);\n }\n for (const rejection of s.rejected ?? []) {\n lines.push(` rejected: ${rejection}`);\n }\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const hasSurfaceNotes = Object.values(manifest.surfaces).some(\n (s) => s.dataModel !== undefined || (s.rejected?.length ?? 0) > 0,\n );\n const surfaceNotes = hasSurfaceNotes\n ? \"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\"\n : \"\";\n\n // Rules for functions, events, and templates go only to runs whose manifest\n // has them, so the guide stays small.\n const features = generativeUIPromptFeatures(\n generativeUIGuideFeatures(manifest),\n );\n const { intro, whenToShow } = spec.tool;\n const operations = selectPromptItems(spec.tool.operations ?? [], features);\n const rules = selectPromptItems(spec.tool.rules, features);\n const when = whenToShow ? `${whenToShow}\\n\\n` : \"\";\n\n return [\n `## Generative UI\n${intro}\n\n${when}Every operation has \"version\":\"v1.0\" and exactly one of:\n${operations.map((op) => `- ${op}`).join(\"\\n\")}\n\nRules:\n${rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")}`,\n `### Targets\\n${targets || \"- none\"}`,\n `### Components\\n${components || \"- none\"}`,\n `### Functions\\n${functions || \"- none\"}`,\n `### Existing surfaces\\n${surfaceNotes}${surfaces || \"- none\"}`,\n ].join(\"\\n\\n\");\n}\n"],"mappings":";;;;;;;AAYA,MAAa,oCACX;;AAGF,MAAM,yBAAyB;;AAG/B,SAAS,QAAQ,MAAc;AAC7B,QAAO,KAAK,SAAS,yBACjB,GAAG,KAAK,MAAM,GAAG,uBAAuB,CAAC,OACzC;;;;;;;AAQN,SAAgB,wBACd,UACA,OAA+BA,mDAA+B,EAC9D;CACA,MAAM,UAAU,SAAS,QACtB,KAAK,MAAM;EACV,MAAM,QACJ,EAAE,SAAS,SACP,+BACA;EACN,MAAM,QAAQ,EAAE,aACZ,UAAU,EAAE,WAAW,KAAK,KAAK,IAAI,oBACrC;EACJ,MAAM,cAAc,EAAE,cAAc,KAAK,EAAE,gBAAgB;AAC3D,SAAO,MAAM,EAAE,GAAG,KAAK,QAAQ,MAAM,GAAG;GACxC,CACD,KAAK,KAAK;CACb,MAAM,aAAaC,sDACjB,SAAS,YACT,KAAK,OAAO,KACb;CACD,MAAM,YAAY,OAAO,QAAQ,SAAS,UAAU,CACjD,KAAK,CAAC,MAAM,OAAO;EAGlB,MAAM,YAAY,EAAE,WAAW;EAC/B,MAAM,OACJ,OAAO,cAAc,YACrB,UAAU,WAAW,IAAI,IACzB,OAAO,KAAK,EAAE,WAAW,CAAC,WAAW,IACjC,YACA,KAAK,UAAU,EAAE,WAAW;EAGlC,MAAM,UAAUC,wCAAgB,EAAE;AAOlC,SAAO,OAAO,KAAK,IALjB,QAAQ,SAASC,mDACb,QAAQ,WACN,mBACA,kBACF,KACuB,EAAE,cAAc,KAAK,EAAE,gBAAgB,GAAG,YAAY;GACnF,CACD,KAAK,KAAK;CACb,MAAM,WAAW,OAAO,QAAQ,SAAS,SAAS,CAC/C,KAAK,CAAC,IAAI,OAAO;EAChB,MAAM,QACJ,EAAE,WAAW,YACT,uCACA,EAAE,WAAW,WACX,+DACA;EACR,MAAM,QAAQ,CAAC,MAAM,GAAG,aAAa,EAAE,OAAO,GAAG,MAAM,GAAG;AAC1D,MAAI,EAAE,UACJ,OAAM,KAAK,kBAAkB,QAAQ,KAAK,UAAU,EAAE,UAAU,CAAC,GAAG;AAEtE,OAAK,MAAM,aAAa,EAAE,YAAY,EAAE,CACtC,OAAM,KAAK,eAAe,YAAY;AAExC,SAAO,MAAM,KAAK,KAAK;GACvB,CACD,KAAK,KAAK;CAIb,MAAM,eAHkB,OAAO,OAAO,SAAS,SAAS,CAAC,MACtD,MAAM,EAAE,cAAc,WAAc,EAAE,UAAU,UAAU,KAAK,EACjE,GAEG,wKACA;CAIJ,MAAM,WAAWC,+CACfC,+CAA0B,SAAS,CACpC;CACD,MAAM,EAAE,OAAO,eAAe,KAAK;CACnC,MAAM,aAAaC,sCAAkB,KAAK,KAAK,cAAc,EAAE,EAAE,SAAS;CAC1E,MAAM,QAAQA,sCAAkB,KAAK,KAAK,OAAO,SAAS;AAG1D,QAAO;EACL;EACF,MAAM;;EAJO,aAAa,GAAG,WAAW,QAAQ,GAM3C;EACL,WAAW,KAAK,OAAO,KAAK,KAAK,CAAC,KAAK,KAAK,CAAC;;;EAG7C,MAAM,KAAK,MAAM,UAAU,GAAG,QAAQ,EAAE,IAAI,OAAO,CAAC,KAAK,KAAK;EAC5D,gBAAgB,WAAW;EAC3B,mBAAmB,cAAc;EACjC,kBAAkB,aAAa;EAC/B,0BAA0B,eAAe,YAAY;EACtD,CAAC,KAAK,OAAO"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GenerativeUIManifest } from "./types.cjs";
|
|
2
|
+
import { GenerativeUIPromptSpec } from "./prompt-spec.cjs";
|
|
2
3
|
|
|
3
4
|
//#region src/generative-ui/prompt.d.ts
|
|
4
5
|
declare const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
|
|
@@ -7,7 +8,7 @@ declare const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: availabl
|
|
|
7
8
|
* the `render_ui` rules, the targets, components, functions, and surfaces of
|
|
8
9
|
* the manifest. It is in shared so that the inspector shows the same text.
|
|
9
10
|
*/
|
|
10
|
-
declare function buildGenerativeUIPrompt(manifest: GenerativeUIManifest): string;
|
|
11
|
+
declare function buildGenerativeUIPrompt(manifest: GenerativeUIManifest, spec?: GenerativeUIPromptSpec): string;
|
|
11
12
|
//#endregion
|
|
12
13
|
export { GENERATIVE_UI_CONTEXT_DESCRIPTION, buildGenerativeUIPrompt };
|
|
13
14
|
//# sourceMappingURL=prompt.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.d.cts","names":[],"sources":["../../src/generative-ui/prompt.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"prompt.d.cts","names":[],"sources":["../../src/generative-ui/prompt.ts"],"mappings":";;;;cAYa,iCAAA;;AAAb;;;;iBAkBgB,uBAAA,CACd,QAAA,EAAU,oBAAA,EACV,IAAA,GAAM,sBAAA"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { GenerativeUIManifest } from "./types.mjs";
|
|
2
|
+
import { GenerativeUIPromptSpec } from "./prompt-spec.mjs";
|
|
2
3
|
|
|
3
4
|
//#region src/generative-ui/prompt.d.ts
|
|
4
5
|
declare const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
|
|
@@ -7,7 +8,7 @@ declare const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: availabl
|
|
|
7
8
|
* the `render_ui` rules, the targets, components, functions, and surfaces of
|
|
8
9
|
* the manifest. It is in shared so that the inspector shows the same text.
|
|
9
10
|
*/
|
|
10
|
-
declare function buildGenerativeUIPrompt(manifest: GenerativeUIManifest): string;
|
|
11
|
+
declare function buildGenerativeUIPrompt(manifest: GenerativeUIManifest, spec?: GenerativeUIPromptSpec): string;
|
|
11
12
|
//#endregion
|
|
12
13
|
export { GENERATIVE_UI_CONTEXT_DESCRIPTION, buildGenerativeUIPrompt };
|
|
13
14
|
//# sourceMappingURL=prompt.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.d.mts","names":[],"sources":["../../src/generative-ui/prompt.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"prompt.d.mts","names":[],"sources":["../../src/generative-ui/prompt.ts"],"mappings":";;;;cAYa,iCAAA;;AAAb;;;;iBAkBgB,uBAAA,CACd,QAAA,EAAU,oBAAA,EACV,IAAA,GAAM,sBAAA"}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { functionCallers } from "./basic-functions.mjs";
|
|
2
|
-
import { GENERATIVE_UI_AGENT_FUNCTION_CALLS
|
|
3
|
-
import {
|
|
2
|
+
import { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from "./types.mjs";
|
|
3
|
+
import { defaultGenerativeUIPromptSpec, generativeUIPromptFeatures, selectPromptItems } from "./prompt-spec.mjs";
|
|
4
|
+
import { generativeUIGuideFeatures } from "../a2ui-prompts.mjs";
|
|
5
|
+
import { renderGenerativeUIComponentList } from "./schema-render.mjs";
|
|
4
6
|
|
|
5
7
|
//#region src/generative-ui/prompt.ts
|
|
6
8
|
const GENERATIVE_UI_CONTEXT_DESCRIPTION = "Generative UI guide: available components, functions, targets, and how to call render_ui.";
|
|
@@ -15,19 +17,14 @@ function shorten(text) {
|
|
|
15
17
|
* the `render_ui` rules, the targets, components, functions, and surfaces of
|
|
16
18
|
* the manifest. It is in shared so that the inspector shows the same text.
|
|
17
19
|
*/
|
|
18
|
-
function buildGenerativeUIPrompt(manifest) {
|
|
20
|
+
function buildGenerativeUIPrompt(manifest, spec = defaultGenerativeUIPromptSpec()) {
|
|
19
21
|
const targets = manifest.targets.map((t) => {
|
|
20
22
|
const place = t.kind === "chat" ? "inside the chat transcript" : "a named area of the app";
|
|
21
23
|
const limit = t.components ? `; only ${t.components.join(", ") || "no components"}` : "";
|
|
22
24
|
const description = t.description ? `: ${t.description}` : "";
|
|
23
25
|
return `- "${t.id}" (${place}${limit})${description}`;
|
|
24
26
|
}).join("\n");
|
|
25
|
-
const components =
|
|
26
|
-
const lines = [`- **${name}**${c.description ? `: ${c.description}` : ""}`, ` props: ${JSON.stringify(c.props)}`];
|
|
27
|
-
if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
|
|
28
|
-
if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
|
|
29
|
-
return lines.join("\n");
|
|
30
|
-
}).join("\n");
|
|
27
|
+
const components = renderGenerativeUIComponentList(manifest.components, spec.schema.tool);
|
|
31
28
|
const functions = Object.entries(manifest.functions).map(([name, f]) => {
|
|
32
29
|
const signature = f.parameters.description;
|
|
33
30
|
const args = typeof signature === "string" && signature.startsWith("{") && Object.keys(f.parameters).length === 2 ? signature : JSON.stringify(f.parameters);
|
|
@@ -42,38 +39,15 @@ function buildGenerativeUIPrompt(manifest) {
|
|
|
42
39
|
return lines.join("\n");
|
|
43
40
|
}).join("\n");
|
|
44
41
|
const surfaceNotes = Object.values(manifest.surfaces).some((s) => s.dataModel !== void 0 || (s.rejected?.length ?? 0) > 0) ? "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" : "";
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
const operations = [
|
|
48
|
-
|
|
49
|
-
"{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.",
|
|
50
|
-
"{\"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\".",
|
|
51
|
-
"{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.",
|
|
52
|
-
...agentCalls ? ["{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface."] : []
|
|
53
|
-
];
|
|
54
|
-
const rules = [
|
|
55
|
-
"Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.",
|
|
56
|
-
"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.",
|
|
57
|
-
"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.",
|
|
58
|
-
"Updating a component replaces all of its props, so resend every prop.",
|
|
59
|
-
"Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.",
|
|
60
|
-
...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\"."] : [],
|
|
61
|
-
"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.",
|
|
62
|
-
"Never use a surfaceId again, also after deleteSurface.",
|
|
63
|
-
"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.",
|
|
64
|
-
"${...} 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\"}}}.",
|
|
65
|
-
"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.",
|
|
66
|
-
...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."] : [],
|
|
67
|
-
...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."] : [],
|
|
68
|
-
...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."] : []
|
|
69
|
-
];
|
|
42
|
+
const features = generativeUIPromptFeatures(generativeUIGuideFeatures(manifest));
|
|
43
|
+
const { intro, whenToShow } = spec.tool;
|
|
44
|
+
const operations = selectPromptItems(spec.tool.operations ?? [], features);
|
|
45
|
+
const rules = selectPromptItems(spec.tool.rules, features);
|
|
70
46
|
return [
|
|
71
47
|
`## Generative UI
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
${GENERATIVE_UI_WHEN_TO_SHOW}
|
|
48
|
+
${intro}
|
|
75
49
|
|
|
76
|
-
Every operation has "version":"v1.0" and exactly one of:
|
|
50
|
+
${whenToShow ? `${whenToShow}\n\n` : ""}Every operation has "version":"v1.0" and exactly one of:
|
|
77
51
|
${operations.map((op) => `- ${op}`).join("\n")}
|
|
78
52
|
|
|
79
53
|
Rules:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prompt.mjs","names":[],"sources":["../../src/generative-ui/prompt.ts"],"sourcesContent":["import {\n GENERATIVE_UI_WHEN_TO_SHOW,\n generativeUIGuideFeatures,\n} from \"../a2ui-prompts\";\nimport { functionCallers } from \"./basic-functions\";\nimport {\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_RENDER_TOOL,\n} from \"./types\";\nimport type { GenerativeUIManifest } from \"./types\";\n\nexport const GENERATIVE_UI_CONTEXT_DESCRIPTION =\n \"Generative UI guide: available components, functions, targets, and how to call render_ui.\";\n\n/** Most characters of the user values of one surface in the guide. */\nconst MAX_USER_VALUES_LENGTH = 500;\n\n/** Cuts long text and marks the cut with \"...\". */\nfunction shorten(text: string) {\n return text.length > MAX_USER_VALUES_LENGTH\n ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...`\n : text;\n}\n\n/**\n * The guide that the runtime adds as a context entry to a tool-transport run:\n * the `render_ui` rules, the targets, components, functions, and surfaces of\n * the manifest. It is in shared so that the inspector shows the same text.\n */\nexport function buildGenerativeUIPrompt(manifest: GenerativeUIManifest) {\n const targets = manifest.targets\n .map((t) => {\n const place =\n t.kind === \"chat\"\n ? \"inside the chat transcript\"\n : \"a named area of the app\";\n const limit = t.components\n ? `; only ${t.components.join(\", \") || \"no components\"}`\n : \"\";\n const description = t.description ? `: ${t.description}` : \"\";\n return `- \"${t.id}\" (${place}${limit})${description}`;\n })\n .join(\"\\n\");\n const components = Object.entries(manifest.components)\n .map(([name, c]) => {\n const lines = [\n `- **${name}**${c.description ? `: ${c.description}` : \"\"}`,\n ` props: ${JSON.stringify(c.props)}`,\n ];\n if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);\n if (c.slots)\n lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const functions = Object.entries(manifest.functions)\n .map(([name, f]) => {\n // A built-in function carries its short signature in the description\n // of its parameters; an app function has a JSON Schema.\n const signature = f.parameters.description;\n const args =\n typeof signature === \"string\" &&\n signature.startsWith(\"{\") &&\n Object.keys(f.parameters).length === 2\n ? signature\n : JSON.stringify(f.parameters);\n // A function is for the UI unless marked: the agent calls only what\n // the mark allows.\n const callers = functionCallers(f);\n const who =\n callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS\n ? callers.renderer\n ? \" (UI or agent)\"\n : \" (agent only)\"\n : \"\";\n return `- **${name}**${who}${f.description ? `: ${f.description}` : \"\"}\\n args: ${args}`;\n })\n .join(\"\\n\");\n const surfaces = Object.entries(manifest.surfaces)\n .map(([id, s]) => {\n const state =\n s.status === \"deleted\"\n ? \", deleted: never use this id again\"\n : s.status === \"failed\"\n ? \", not created: send a corrected createSurface with this id\"\n : \"\";\n const lines = [`- \"${id}\" (target \"${s.target}\"${state})`];\n if (s.dataModel) {\n lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);\n }\n for (const rejection of s.rejected ?? []) {\n lines.push(` rejected: ${rejection}`);\n }\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const hasSurfaceNotes = Object.values(manifest.surfaces).some(\n (s) => s.dataModel !== undefined || (s.rejected?.length ?? 0) > 0,\n );\n const surfaceNotes = hasSurfaceNotes\n ? \"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\"\n : \"\";\n\n // Rules for functions, events, and templates go only to runs whose manifest\n // has them, so the guide stays small.\n const {\n functions: hasFunctions,\n events,\n templates,\n checks,\n } = generativeUIGuideFeatures(manifest);\n // The agent calls functions only while that path is on.\n const agentCalls = hasFunctions && GENERATIVE_UI_AGENT_FUNCTION_CALLS;\n const operations = [\n '{\"version\":\"v1.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.',\n '{\"version\":\"v1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.',\n '{\"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\".',\n '{\"version\":\"v1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.',\n ...(agentCalls\n ? [\n '{\"version\":\"v1.0\",\"callRendererFunction\":{\"functionCallId\":\"<unique id>\",\"callFunction\":{\"@call\":\"<function>\",\"args\":{...}}}}: run an app function now, with no click. It needs no surface.',\n ]\n : []),\n ];\n const eventRule = hasFunctions\n ? '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.'\n : '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\".';\n const rules = [\n 'Components are flat objects: {\"id\":\"...\",\"component\":\"<Name>\", ...props}. Every surface renders from the component with id \"root\". Reference children by id in slot props.',\n 'A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component, and \"live\":\"polite\" only on text that changes by itself.',\n '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.',\n \"Updating a component replaces all of its props, so resend every prop.\",\n 'Prop values are literals or data bindings {\"@path\":\"/data/path\"}. Never write {\"path\":\"/data/path\"} as a binding.',\n ...(events ? [eventRule] : []),\n \"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.\",\n \"Never use a surfaceId again, also after deleteSurface.\",\n '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.',\n '${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}.',\n \"For a computed list (chart data, template items) use series. Its description under Functions gives the rules and an example.\",\n ...(checks\n ? [\n 'Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email. A failed check shows the message under the input and disables a Button that has the same checks.',\n ]\n : []),\n ...(templates\n ? [\n '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.',\n ]\n : []),\n ...(agentCalls\n ? [\n \"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.\",\n '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.',\n ]\n : []),\n ];\n\n return [\n `## Generative UI\nCall \\`${GENERATIVE_UI_RENDER_TOOL}\\` to show UI. Arguments: \\`target\\` first, then \\`operations\\` (A2UI v1.0 operations, applied in order).\n\n${GENERATIVE_UI_WHEN_TO_SHOW}\n\nEvery operation has \"version\":\"v1.0\" and exactly one of:\n${operations.map((op) => `- ${op}`).join(\"\\n\")}\n\nRules:\n${rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")}`,\n `### Targets\\n${targets || \"- none\"}`,\n `### Components\\n${components || \"- none\"}`,\n `### Functions\\n${functions || \"- none\"}`,\n `### Existing surfaces\\n${surfaceNotes}${surfaces || \"- none\"}`,\n ].join(\"\\n\\n\");\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"prompt.mjs","names":[],"sources":["../../src/generative-ui/prompt.ts"],"sourcesContent":["import { generativeUIGuideFeatures } from \"../a2ui-prompts\";\nimport { functionCallers } from \"./basic-functions\";\nimport {\n defaultGenerativeUIPromptSpec,\n generativeUIPromptFeatures,\n selectPromptItems,\n} from \"./prompt-spec\";\nimport type { GenerativeUIPromptSpec } from \"./prompt-spec\";\nimport { renderGenerativeUIComponentList } from \"./schema-render\";\nimport { GENERATIVE_UI_AGENT_FUNCTION_CALLS } from \"./types\";\nimport type { GenerativeUIManifest } from \"./types\";\n\nexport const GENERATIVE_UI_CONTEXT_DESCRIPTION =\n \"Generative UI guide: available components, functions, targets, and how to call render_ui.\";\n\n/** Most characters of the user values of one surface in the guide. */\nconst MAX_USER_VALUES_LENGTH = 500;\n\n/** Cuts long text and marks the cut with \"...\". */\nfunction shorten(text: string) {\n return text.length > MAX_USER_VALUES_LENGTH\n ? `${text.slice(0, MAX_USER_VALUES_LENGTH)}...`\n : text;\n}\n\n/**\n * The guide that the runtime adds as a context entry to a tool-transport run:\n * the `render_ui` rules, the targets, components, functions, and surfaces of\n * the manifest. It is in shared so that the inspector shows the same text.\n */\nexport function buildGenerativeUIPrompt(\n manifest: GenerativeUIManifest,\n spec: GenerativeUIPromptSpec = defaultGenerativeUIPromptSpec(),\n) {\n const targets = manifest.targets\n .map((t) => {\n const place =\n t.kind === \"chat\"\n ? \"inside the chat transcript\"\n : \"a named area of the app\";\n const limit = t.components\n ? `; only ${t.components.join(\", \") || \"no components\"}`\n : \"\";\n const description = t.description ? `: ${t.description}` : \"\";\n return `- \"${t.id}\" (${place}${limit})${description}`;\n })\n .join(\"\\n\");\n const components = renderGenerativeUIComponentList(\n manifest.components,\n spec.schema.tool,\n );\n const functions = Object.entries(manifest.functions)\n .map(([name, f]) => {\n // A built-in function carries its short signature in the description\n // of its parameters; an app function has a JSON Schema.\n const signature = f.parameters.description;\n const args =\n typeof signature === \"string\" &&\n signature.startsWith(\"{\") &&\n Object.keys(f.parameters).length === 2\n ? signature\n : JSON.stringify(f.parameters);\n // A function is for the UI unless marked: the agent calls only what\n // the mark allows.\n const callers = functionCallers(f);\n const who =\n callers.agent && GENERATIVE_UI_AGENT_FUNCTION_CALLS\n ? callers.renderer\n ? \" (UI or agent)\"\n : \" (agent only)\"\n : \"\";\n return `- **${name}**${who}${f.description ? `: ${f.description}` : \"\"}\\n args: ${args}`;\n })\n .join(\"\\n\");\n const surfaces = Object.entries(manifest.surfaces)\n .map(([id, s]) => {\n const state =\n s.status === \"deleted\"\n ? \", deleted: never use this id again\"\n : s.status === \"failed\"\n ? \", not created: send a corrected createSurface with this id\"\n : \"\";\n const lines = [`- \"${id}\" (target \"${s.target}\"${state})`];\n if (s.dataModel) {\n lines.push(` user values: ${shorten(JSON.stringify(s.dataModel))}`);\n }\n for (const rejection of s.rejected ?? []) {\n lines.push(` rejected: ${rejection}`);\n }\n return lines.join(\"\\n\");\n })\n .join(\"\\n\");\n const hasSurfaceNotes = Object.values(manifest.surfaces).some(\n (s) => s.dataModel !== undefined || (s.rejected?.length ?? 0) > 0,\n );\n const surfaceNotes = hasSurfaceNotes\n ? \"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\"\n : \"\";\n\n // Rules for functions, events, and templates go only to runs whose manifest\n // has them, so the guide stays small.\n const features = generativeUIPromptFeatures(\n generativeUIGuideFeatures(manifest),\n );\n const { intro, whenToShow } = spec.tool;\n const operations = selectPromptItems(spec.tool.operations ?? [], features);\n const rules = selectPromptItems(spec.tool.rules, features);\n const when = whenToShow ? `${whenToShow}\\n\\n` : \"\";\n\n return [\n `## Generative UI\n${intro}\n\n${when}Every operation has \"version\":\"v1.0\" and exactly one of:\n${operations.map((op) => `- ${op}`).join(\"\\n\")}\n\nRules:\n${rules.map((rule, index) => `${index + 1}. ${rule}`).join(\"\\n\")}`,\n `### Targets\\n${targets || \"- none\"}`,\n `### Components\\n${components || \"- none\"}`,\n `### Functions\\n${functions || \"- none\"}`,\n `### Existing surfaces\\n${surfaceNotes}${surfaces || \"- none\"}`,\n ].join(\"\\n\\n\");\n}\n"],"mappings":";;;;;;;AAYA,MAAa,oCACX;;AAGF,MAAM,yBAAyB;;AAG/B,SAAS,QAAQ,MAAc;AAC7B,QAAO,KAAK,SAAS,yBACjB,GAAG,KAAK,MAAM,GAAG,uBAAuB,CAAC,OACzC;;;;;;;AAQN,SAAgB,wBACd,UACA,OAA+B,+BAA+B,EAC9D;CACA,MAAM,UAAU,SAAS,QACtB,KAAK,MAAM;EACV,MAAM,QACJ,EAAE,SAAS,SACP,+BACA;EACN,MAAM,QAAQ,EAAE,aACZ,UAAU,EAAE,WAAW,KAAK,KAAK,IAAI,oBACrC;EACJ,MAAM,cAAc,EAAE,cAAc,KAAK,EAAE,gBAAgB;AAC3D,SAAO,MAAM,EAAE,GAAG,KAAK,QAAQ,MAAM,GAAG;GACxC,CACD,KAAK,KAAK;CACb,MAAM,aAAa,gCACjB,SAAS,YACT,KAAK,OAAO,KACb;CACD,MAAM,YAAY,OAAO,QAAQ,SAAS,UAAU,CACjD,KAAK,CAAC,MAAM,OAAO;EAGlB,MAAM,YAAY,EAAE,WAAW;EAC/B,MAAM,OACJ,OAAO,cAAc,YACrB,UAAU,WAAW,IAAI,IACzB,OAAO,KAAK,EAAE,WAAW,CAAC,WAAW,IACjC,YACA,KAAK,UAAU,EAAE,WAAW;EAGlC,MAAM,UAAU,gBAAgB,EAAE;AAOlC,SAAO,OAAO,KAAK,IALjB,QAAQ,SAAS,qCACb,QAAQ,WACN,mBACA,kBACF,KACuB,EAAE,cAAc,KAAK,EAAE,gBAAgB,GAAG,YAAY;GACnF,CACD,KAAK,KAAK;CACb,MAAM,WAAW,OAAO,QAAQ,SAAS,SAAS,CAC/C,KAAK,CAAC,IAAI,OAAO;EAChB,MAAM,QACJ,EAAE,WAAW,YACT,uCACA,EAAE,WAAW,WACX,+DACA;EACR,MAAM,QAAQ,CAAC,MAAM,GAAG,aAAa,EAAE,OAAO,GAAG,MAAM,GAAG;AAC1D,MAAI,EAAE,UACJ,OAAM,KAAK,kBAAkB,QAAQ,KAAK,UAAU,EAAE,UAAU,CAAC,GAAG;AAEtE,OAAK,MAAM,aAAa,EAAE,YAAY,EAAE,CACtC,OAAM,KAAK,eAAe,YAAY;AAExC,SAAO,MAAM,KAAK,KAAK;GACvB,CACD,KAAK,KAAK;CAIb,MAAM,eAHkB,OAAO,OAAO,SAAS,SAAS,CAAC,MACtD,MAAM,EAAE,cAAc,WAAc,EAAE,UAAU,UAAU,KAAK,EACjE,GAEG,wKACA;CAIJ,MAAM,WAAW,2BACf,0BAA0B,SAAS,CACpC;CACD,MAAM,EAAE,OAAO,eAAe,KAAK;CACnC,MAAM,aAAa,kBAAkB,KAAK,KAAK,cAAc,EAAE,EAAE,SAAS;CAC1E,MAAM,QAAQ,kBAAkB,KAAK,KAAK,OAAO,SAAS;AAG1D,QAAO;EACL;EACF,MAAM;;EAJO,aAAa,GAAG,WAAW,QAAQ,GAM3C;EACL,WAAW,KAAK,OAAO,KAAK,KAAK,CAAC,KAAK,KAAK,CAAC;;;EAG7C,MAAM,KAAK,MAAM,UAAU,GAAG,QAAQ,EAAE,IAAI,OAAO,CAAC,KAAK,KAAK;EAC5D,gBAAgB,WAAW;EAC3B,mBAAmB,cAAc;EACjC,kBAAkB,aAAa;EAC/B,0BAA0B,eAAe,YAAY;EACtD,CAAC,KAAK,OAAO"}
|
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
const require_basic_functions = require('./basic-functions.cjs');
|
|
2
|
+
const require_types = require('./types.cjs');
|
|
3
|
+
const require_compact_schema = require('./compact-schema.cjs');
|
|
4
|
+
|
|
5
|
+
//#region src/generative-ui/schema-render.ts
|
|
6
|
+
/** An own key (shared compiles to ES2017, which has no Object.hasOwn). */
|
|
7
|
+
const hasOwn = (target, key) => Object.prototype.hasOwnProperty.call(target, key);
|
|
8
|
+
function isRecord(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10
|
+
}
|
|
11
|
+
/** The props schema without the description of each prop. */
|
|
12
|
+
function withoutPropDescriptions(schema) {
|
|
13
|
+
if (!isRecord(schema.properties)) return schema;
|
|
14
|
+
return {
|
|
15
|
+
...schema,
|
|
16
|
+
properties: Object.fromEntries(Object.entries(schema.properties).map(([key, value]) => {
|
|
17
|
+
if (!isRecord(value)) return [key, value];
|
|
18
|
+
const { description: _description, ...rest } = value;
|
|
19
|
+
return [key, rest];
|
|
20
|
+
}))
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** The short signature of a function: its built-in signature, or its schema made short. */
|
|
24
|
+
function functionSignature(fn) {
|
|
25
|
+
const signature = fn.parameters.description;
|
|
26
|
+
return typeof signature === "string" && signature.startsWith("{") && Object.keys(fn.parameters).length === 2 ? signature : require_compact_schema.compactType(fn.parameters, 0);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A function name with its parameters: `pick{ id: string }`, `clearCart{}`
|
|
30
|
+
* for no arguments, `setVolume(number)` for a parameter that is not an object.
|
|
31
|
+
*/
|
|
32
|
+
function nameWithParameters(name, parameters) {
|
|
33
|
+
if (parameters.startsWith("{")) return `${name}${parameters}`;
|
|
34
|
+
if (parameters === "object") return `${name}{}`;
|
|
35
|
+
return `${name}(${parameters})`;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* One component as a TypeScript-like signature line, with its events and
|
|
39
|
+
* slots on the lines below:
|
|
40
|
+
* `- Text(text?: string // The text): Shows text`.
|
|
41
|
+
*/
|
|
42
|
+
function signatureLines(name, component, settings) {
|
|
43
|
+
const lines = [`- ${name}(${Object.entries(require_compact_schema.compactProps(component.props, settings.propDescriptions)).map(([key, type]) => `${key}: ${type}`).join(", ")})${component.description ? `: ${oneLine(component.description)}` : ""}`];
|
|
44
|
+
const events = Object.entries(component.events ?? {}).map(([event, definition]) => `${event}(${definition.description ? oneLine(definition.description) : require_compact_schema.compactType(definition.parameters, 0)})`);
|
|
45
|
+
if (events.length > 0) lines.push(` events: ${events.join(", ")}`);
|
|
46
|
+
const slots = Object.entries(component.slots ?? {}).map(([slot, kind]) => `${slot} (${kind})`);
|
|
47
|
+
if (slots.length > 0) lines.push(` slots: ${slots.join(", ")}`);
|
|
48
|
+
return lines;
|
|
49
|
+
}
|
|
50
|
+
/** The whole schema as signature text: targets, functions, components, surfaces. */
|
|
51
|
+
function signatureSchema(manifest, settings) {
|
|
52
|
+
const targets = manifest.targets.map((t) => {
|
|
53
|
+
const limit = t.components ? `; only ${t.components.join(", ")}` : "";
|
|
54
|
+
return `- ${t.id} (${t.kind}${limit})${t.description ? `: ${oneLine(t.description)}` : ""}`;
|
|
55
|
+
});
|
|
56
|
+
const functions = Object.entries(manifest.functions).map(([name, fn]) => {
|
|
57
|
+
const callers = require_basic_functions.functionCallers(fn);
|
|
58
|
+
const who = callers.agent && require_types.GENERATIVE_UI_AGENT_FUNCTION_CALLS ? callers.renderer ? " (UI or agent)" : " (agent only)" : "";
|
|
59
|
+
return `- ${nameWithParameters(name, functionSignature(fn))}${who}${fn.description ? `: ${oneLine(fn.description)}` : ""}`;
|
|
60
|
+
});
|
|
61
|
+
const components = Object.entries(manifest.components).flatMap(([name, component]) => signatureLines(name, component, settings));
|
|
62
|
+
const surfaces = Object.entries(manifest.surfaces).map(([id, s]) => `- ${id} (target ${s.target})${s.status ? ` status: ${s.status}` : ""}${s.dataModel ? ` user values: ${JSON.stringify(s.dataModel)}` : ""}${(s.rejected ?? []).map((r) => ` rejected: ${r}`).join("")}`);
|
|
63
|
+
return [
|
|
64
|
+
`Catalog: ${manifest.catalogId}`,
|
|
65
|
+
`Targets:\n${targets.join("\n") || "- none"}`,
|
|
66
|
+
`Functions:\n${functions.join("\n") || "- none"}`,
|
|
67
|
+
`Components:\n${components.join("\n") || "- none"}`,
|
|
68
|
+
`Surfaces:\n${surfaces.join("\n") || "- none"}`
|
|
69
|
+
].join("\n\n");
|
|
70
|
+
}
|
|
71
|
+
/** A description on one line, so its lines cannot read as new entries. */
|
|
72
|
+
function oneLine(text) {
|
|
73
|
+
return text.replace(/\s*\n\s*/g, " ");
|
|
74
|
+
}
|
|
75
|
+
/** Values that would read as a type or a number once their quotes are gone. */
|
|
76
|
+
const AMBIGUOUS_VALUE = /^(?:string|number|integer|boolean|true|false|null|object|array|unknown|any|-?\d[\d.]*)$/;
|
|
77
|
+
/**
|
|
78
|
+
* A compact type with bare enum values and tight unions:
|
|
79
|
+
* `"sm" | "md" | "lg"` becomes `sm|md|lg`. A union keeps its quotes when it
|
|
80
|
+
* also holds a type (`"sm" | number`) or a value that reads as a type or a
|
|
81
|
+
* number (`"number" | "currency"`, `"1" | "2"`), and so do values that are
|
|
82
|
+
* not plain words.
|
|
83
|
+
*/
|
|
84
|
+
function bareType(type) {
|
|
85
|
+
return type.replace(/"[A-Za-z0-9_#%.-]+"(?: \| "[A-Za-z0-9_#%.-]+")*(?! \|)/g, (union, offset, whole) => {
|
|
86
|
+
if (whole.slice(offset - 2, offset) === "| ") return union;
|
|
87
|
+
const values = union.split(" | ").map((v) => v.slice(1, -1));
|
|
88
|
+
if (values.some((v) => AMBIGUOUS_VALUE.test(v))) return union;
|
|
89
|
+
return values.join("|");
|
|
90
|
+
}).replace(/ \| /g, "|");
|
|
91
|
+
}
|
|
92
|
+
/** A compact prop (`type // description`) as `name: type - description`. */
|
|
93
|
+
function propLine(key, value) {
|
|
94
|
+
const name = key.endsWith("?") ? key.slice(0, -1) : `${key}*`;
|
|
95
|
+
const cut = value.indexOf(" // ");
|
|
96
|
+
const type = bareType(cut < 0 ? value : value.slice(0, cut));
|
|
97
|
+
const text = cut < 0 ? "" : value.slice(cut + 4).trim();
|
|
98
|
+
return ` ${name}: ${type}${text ? ` - ${oneLine(text)}` : ""}`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* The whole schema as plain lines: a header line per component and one
|
|
102
|
+
* indented line per prop: events are `action` props and slots `componentId`
|
|
103
|
+
* or `childList` props. Props are optional unless marked `*`, enum values
|
|
104
|
+
* are bare, and the common props are listed once. It carries the same names, types and descriptions as
|
|
105
|
+
* `compact`, in fewer tokens.
|
|
106
|
+
*/
|
|
107
|
+
function linesSchema(manifest, settings) {
|
|
108
|
+
const compact = require_compact_schema.buildCompactGenerativeUISchema(manifest, {
|
|
109
|
+
propDescriptions: settings.propDescriptions,
|
|
110
|
+
commonProps: settings.commonProps
|
|
111
|
+
});
|
|
112
|
+
const targets = compact.targets.map((t) => {
|
|
113
|
+
const limit = t.components ? `, only ${t.components.join(", ")}` : "";
|
|
114
|
+
return `${t.id} (${t.kind}${limit})${t.description ? `: ${oneLine(t.description)}` : ""}`;
|
|
115
|
+
}).join("; ");
|
|
116
|
+
const functions = Object.entries(compact.functions).map(([name, fn]) => `${nameWithParameters(name, fn.parameters)}${"callers" in fn ? ` (${fn.callers})` : ""}${fn.description ? `: ${oneLine(fn.description)}` : ""}`);
|
|
117
|
+
const common = compact.commonProps ? Object.entries(compact.commonProps).map(([k, v]) => propLine(k, v)) : [];
|
|
118
|
+
const components = Object.entries(compact.components).map(([name, c]) => ({
|
|
119
|
+
name,
|
|
120
|
+
c,
|
|
121
|
+
own: [...Object.entries(c.props).map(([k, v]) => propLine(k, v)), ...Object.entries(c.events ?? {}).map(([e, d]) => ` ${e}: action - ${oneLine(d)}`)]
|
|
122
|
+
})).flatMap(({ name, c, own }) => {
|
|
123
|
+
const lines = [`${name}${c.includesCommonProps ? " +common" : ""}${c.description ? `: ${oneLine(c.description)}` : ""}`, ...own];
|
|
124
|
+
for (const [slot, kind] of Object.entries(c.slots ?? {})) lines.push(` ${slot}: ${kind === "single" ? "componentId" : "childList"}`);
|
|
125
|
+
return lines;
|
|
126
|
+
});
|
|
127
|
+
const surfaces = Object.keys(compact.surfaces).length ? JSON.stringify(compact.surfaces) : "none";
|
|
128
|
+
return [
|
|
129
|
+
`Catalog ${compact.catalogId}. Targets: ${targets || "none"}`,
|
|
130
|
+
"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.",
|
|
131
|
+
`Functions:\n${functions.join("\n")}`,
|
|
132
|
+
...common.length ? [`Common props:\n${common.join("\n")}`] : [],
|
|
133
|
+
`Components:\n${components.join("\n")}`,
|
|
134
|
+
`Surfaces: ${surfaces}`
|
|
135
|
+
].join("\n\n");
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* The component schema of the markdown transport, as the text of its
|
|
139
|
+
* context entry, in the notation of `settings`. `compact` is the schema that
|
|
140
|
+
* ships (`buildCompactGenerativeUISchema`), `json-schema` the manifest parts
|
|
141
|
+
* as JSON, `ts-signature` one line per component, `lines` one line per
|
|
142
|
+
* prop with bare enums (the fewest tokens).
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* ```ts
|
|
146
|
+
* const value = renderGenerativeUISchema(manifest, spec.schema.markdown);
|
|
147
|
+
* ```
|
|
148
|
+
*/
|
|
149
|
+
function renderGenerativeUISchema(manifest, settings) {
|
|
150
|
+
switch (settings.notation) {
|
|
151
|
+
case "compact": return JSON.stringify(require_compact_schema.buildCompactGenerativeUISchema(manifest, {
|
|
152
|
+
propDescriptions: settings.propDescriptions,
|
|
153
|
+
commonProps: settings.commonProps
|
|
154
|
+
}));
|
|
155
|
+
case "json-schema": {
|
|
156
|
+
const components = Object.fromEntries(Object.entries(manifest.components).map(([name, c]) => [name, settings.propDescriptions ? c : {
|
|
157
|
+
...c,
|
|
158
|
+
props: withoutPropDescriptions(c.props)
|
|
159
|
+
}]));
|
|
160
|
+
return JSON.stringify({
|
|
161
|
+
catalogId: manifest.catalogId,
|
|
162
|
+
targets: manifest.targets,
|
|
163
|
+
functions: manifest.functions,
|
|
164
|
+
components,
|
|
165
|
+
surfaces: manifest.surfaces
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
case "ts-signature": return signatureSchema(manifest, settings);
|
|
169
|
+
case "lines": return linesSchema(manifest, settings);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The component list of the tool guide, one entry per component, in the
|
|
174
|
+
* notation of `settings`. `json-schema` is the list that ships.
|
|
175
|
+
*/
|
|
176
|
+
function renderGenerativeUIComponentList(components, settings) {
|
|
177
|
+
return Object.entries(components).map(([name, c]) => {
|
|
178
|
+
if (settings.notation === "ts-signature" || settings.notation === "lines") return signatureLines(name, c, settings).join("\n");
|
|
179
|
+
const props = settings.notation === "compact" ? require_compact_schema.compactProps(c.props, settings.propDescriptions) : settings.propDescriptions ? c.props : withoutPropDescriptions(c.props);
|
|
180
|
+
const lines = [`- **${name}**${c.description ? `: ${oneLine(c.description)}` : ""}`, ` props: ${JSON.stringify(props)}`];
|
|
181
|
+
if (c.events) lines.push(` event props: ${JSON.stringify(c.events)}`);
|
|
182
|
+
if (c.slots) lines.push(` slot props (component ids): ${JSON.stringify(c.slots)}`);
|
|
183
|
+
return lines.join("\n");
|
|
184
|
+
}).join("\n");
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The manifest with replaced descriptions: `"Name"` replaces the
|
|
188
|
+
* description of a component, `"Name.prop"` the description of one of its
|
|
189
|
+
* props. Keys that name no component or prop are left out of the result
|
|
190
|
+
* and listed in `unknown`. The manifest is not changed.
|
|
191
|
+
*/
|
|
192
|
+
function applyDescriptionOverrides(manifest, overrides) {
|
|
193
|
+
const components = structuredClone(manifest.components);
|
|
194
|
+
const unknown = [];
|
|
195
|
+
for (const [key, description] of Object.entries(overrides)) {
|
|
196
|
+
const [name, prop, ...rest] = key.split(".");
|
|
197
|
+
const component = hasOwn(components, name) ? components[name] : void 0;
|
|
198
|
+
if (!component || rest.length > 0) {
|
|
199
|
+
unknown.push(key);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (prop === void 0) {
|
|
203
|
+
component.description = description;
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const properties = component.props.properties;
|
|
207
|
+
const property = isRecord(properties) && hasOwn(properties, prop) ? properties[prop] : void 0;
|
|
208
|
+
if (!isRecord(property)) {
|
|
209
|
+
unknown.push(key);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
property.description = description;
|
|
213
|
+
}
|
|
214
|
+
return {
|
|
215
|
+
manifest: {
|
|
216
|
+
...manifest,
|
|
217
|
+
components
|
|
218
|
+
},
|
|
219
|
+
unknown
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* The components and props of `manifest` whose names do not appear in
|
|
224
|
+
* `rendered`. A schema notation that leaves one out would hide part of the
|
|
225
|
+
* catalog from the model.
|
|
226
|
+
*/
|
|
227
|
+
function schemaCoverage(manifest, rendered) {
|
|
228
|
+
const missing = [];
|
|
229
|
+
for (const [name, component] of Object.entries(manifest.components)) {
|
|
230
|
+
if (!rendered.includes(name)) missing.push(name);
|
|
231
|
+
const properties = isRecord(component.props.properties) ? component.props.properties : {};
|
|
232
|
+
for (const prop of Object.keys(properties)) if (!rendered.includes(prop)) missing.push(`${name}.${prop}`);
|
|
233
|
+
}
|
|
234
|
+
return { missing };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
//#endregion
|
|
238
|
+
exports.applyDescriptionOverrides = applyDescriptionOverrides;
|
|
239
|
+
exports.renderGenerativeUIComponentList = renderGenerativeUIComponentList;
|
|
240
|
+
exports.renderGenerativeUISchema = renderGenerativeUISchema;
|
|
241
|
+
exports.schemaCoverage = schemaCoverage;
|
|
242
|
+
//# sourceMappingURL=schema-render.cjs.map
|