@copilotkit/shared 2.0.0-rc.3 → 2.0.0-rc.31
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-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/attachments/types.d.cts +1 -3
- package/dist/attachments/types.d.cts.map +1 -1
- package/dist/attachments/types.d.mts +1 -3
- package/dist/attachments/types.d.mts.map +1 -1
- package/dist/attachments/utils.cjs +16 -5
- package/dist/attachments/utils.cjs.map +1 -1
- package/dist/attachments/utils.d.cts +3 -1
- package/dist/attachments/utils.d.cts.map +1 -1
- package/dist/attachments/utils.d.mts +3 -1
- package/dist/attachments/utils.d.mts.map +1 -1
- package/dist/attachments/utils.mjs +16 -5
- package/dist/attachments/utils.mjs.map +1 -1
- package/dist/finalize-events.cjs +16 -0
- package/dist/finalize-events.cjs.map +1 -1
- package/dist/finalize-events.d.cts.map +1 -1
- package/dist/finalize-events.d.mts.map +1 -1
- package/dist/finalize-events.mjs +16 -0
- package/dist/finalize-events.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/child-refs.cjs +3 -3
- package/dist/generative-ui/child-refs.cjs.map +1 -1
- package/dist/generative-ui/child-refs.d.cts.map +1 -1
- package/dist/generative-ui/child-refs.d.mts.map +1 -1
- package/dist/generative-ui/child-refs.mjs +3 -3
- package/dist/generative-ui/child-refs.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/render-ui-args.cjs +1 -0
- package/dist/generative-ui/render-ui-args.cjs.map +1 -1
- package/dist/generative-ui/render-ui-args.d.cts.map +1 -1
- package/dist/generative-ui/render-ui-args.d.mts.map +1 -1
- package/dist/generative-ui/render-ui-args.mjs +1 -0
- package/dist/generative-ui/render-ui-args.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/generative-ui/validate-operation.cjs +2 -2
- package/dist/generative-ui/validate-operation.cjs.map +1 -1
- package/dist/generative-ui/validate-operation.mjs +2 -2
- package/dist/generative-ui/validate-operation.mjs.map +1 -1
- package/dist/index.cjs +16 -15
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -10
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +10 -10
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -8
- package/dist/index.mjs.map +1 -1
- package/dist/index.umd.js +866 -455
- 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 +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 +1 -1
- package/dist/telemetry/lambda-client.mjs.map +1 -1
- package/dist/telemetry/telemetry-disabled.cjs +0 -5
- 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 +0 -5
- 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 +5 -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 +6 -41
- package/dist/utils/errors.mjs.map +1 -1
- package/dist/utils/index.cjs +0 -2
- package/dist/utils/index.cjs.map +1 -1
- package/dist/utils/index.d.cts +4 -6
- package/dist/utils/index.d.cts.map +1 -1
- package/dist/utils/index.d.mts +4 -6
- package/dist/utils/index.d.mts.map +1 -1
- package/dist/utils/index.mjs +4 -6
- package/dist/utils/index.mjs.map +1 -1
- package/dist/utils/inspector-visibility.cjs +25 -3
- package/dist/utils/inspector-visibility.cjs.map +1 -1
- package/dist/utils/inspector-visibility.d.cts +26 -3
- package/dist/utils/inspector-visibility.d.cts.map +1 -1
- package/dist/utils/inspector-visibility.d.mts +26 -3
- package/dist/utils/inspector-visibility.d.mts.map +1 -1
- package/dist/utils/inspector-visibility.mjs +25 -4
- package/dist/utils/inspector-visibility.mjs.map +1 -1
- package/dist/utils/json-schema.cjs +4 -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 +5 -78
- package/dist/utils/json-schema.mjs.map +1 -1
- 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 +10 -34
- package/scripts/verify-cjs-exports.cjs +1 -1
- 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__/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-envelope.ts +7 -6
- package/src/a2ui-prompts.ts +47 -96
- package/src/attachments/__tests__/utils.test.ts +22 -0
- package/src/attachments/types.ts +1 -3
- package/src/attachments/utils.ts +23 -5
- package/src/finalize-events.ts +16 -0
- 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/child-refs.ts +5 -4
- 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/render-ui-args.ts +3 -0
- package/src/generative-ui/schema-render.ts +377 -0
- package/src/generative-ui/types.ts +10 -7
- package/src/generative-ui/validate-operation.ts +2 -2
- package/src/index.ts +3 -16
- package/src/standard-schema.ts +24 -27
- package/src/telemetry/lambda-client.ts +8 -3
- package/src/telemetry/model-host.test.ts +2 -5
- package/src/telemetry/telemetry-disabled.ts +0 -5
- 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__/random-id.test.ts +37 -0
- package/src/utils/errors.ts +28 -85
- package/src/utils/index.ts +0 -2
- package/src/utils/inspector-visibility.test.ts +26 -0
- package/src/utils/inspector-visibility.ts +35 -3
- package/src/utils/json-schema.ts +5 -152
- package/src/utils/random-id.ts +17 -37
- package/tsconfig.json +3 -1
- 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
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompt-spec.mjs","names":[],"sources":["../../src/generative-ui/prompt-spec.ts"],"sourcesContent":["import {\n GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n GENERATIVE_UI_RENDER_TOOL,\n} from \"./types\";\n\n/**\n * A condition of a prompt block. A block is in the prompt when every one of\n * its features holds for the manifest of the run.\n * - `functions` / `noFunctions`: the app mounts a function, or none.\n * - `events`, `templates`, `checks`: a component has an event prop, a\n * multiple slot, or a \"checks\" prop.\n * - `agentCalls`: the agent may call renderer functions (`functions` and\n * `GENERATIVE_UI_AGENT_FUNCTION_CALLS`).\n */\nexport type GenerativeUIPromptFeature =\n | \"functions\"\n | \"noFunctions\"\n | \"events\"\n | \"templates\"\n | \"checks\"\n | \"agentCalls\";\n\n/** One rule, or a block of rules that is in the prompt only when its features hold. */\nexport type GenerativeUIPromptItem =\n | string\n | { when: GenerativeUIPromptFeature[]; items: string[] };\n\n/** The instruction text of one transport. */\nexport interface GenerativeUIPromptSection {\n /** The first line. */\n intro: string;\n /** When UI helps. An empty string leaves the paragraph out. */\n whenToShow: string;\n /** The operations (tool transport only). */\n operations?: GenerativeUIPromptItem[];\n /** The rules, in order. */\n rules: GenerativeUIPromptItem[];\n}\n\n/** How the component schema is written. */\nexport interface GenerativeUISchemaSettings {\n /**\n * `compact` (short types, common props once), `json-schema` (the full\n * props schema), `ts-signature` (one line per component), or `lines`\n * (one line per prop, bare enums, common props once: the fewest tokens).\n */\n notation: \"compact\" | \"json-schema\" | \"ts-signature\" | \"lines\";\n /** Write the description of each prop. */\n propDescriptions: boolean;\n /** List the props that many components share once (`commonProps`). Compact and lines notations only. */\n commonProps: boolean;\n}\n\n/**\n * Everything in the generative UI prompts that is wording, not protocol: the\n * instruction text of both transports, how the component schema is\n * written, and replacement descriptions for components and props\n * (`\"DateTimeInput\"`, `\"DateTimeInput.timeStep\"`). The builders take a spec;\n * without one they use `defaultGenerativeUIPromptSpec()`, which renders the\n * prompts that ship. The descriptions are applied to the manifest by the\n * caller (`applyDescriptionOverrides`), because the schema is built from it.\n */\nexport interface GenerativeUIPromptSpec {\n markdown: GenerativeUIPromptSection;\n tool: GenerativeUIPromptSection;\n schema: {\n markdown: GenerativeUISchemaSettings;\n tool: GenerativeUISchemaSettings;\n };\n descriptions: Record<string, string>;\n}\n\n/**\n * When UI helps the user, for both transports: a light nudge to reach for UI\n * where it conveys the answer better than prose, and to stay in prose\n * otherwise.\n */\nexport const GENERATIVE_UI_WHEN_TO_SHOW =\n \"Show UI when it conveys the answer better than prose: to illustrate a concept (a diagram, a chart of how something changes), to compare options side by side, to let the user explore or adjust values, or to collect input. A small, focused surface next to your explanation often lands better than a long description. Reply in prose alone for a quick fact, a short answer, or conversation, and never add UI only as decoration.\";\n\n/**\n * When and how to show UI in the markdown transport: the answer first, a\n * map from tasks to components, real interactivity, honest data and\n * restraint. Measured with tools/genui-eval against the earlier text.\n */\nexport const GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW =\n '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?';\n\n/** The prompts that ship, as a spec. A new object on each call. */\n/**\n * The standard components that the default markdown guide names. A guide\n * line that names one the catalog lacks is left out of the prompt.\n */\nexport const GUIDE_COMPONENTS: ReadonlySet<string> = new Set([\n \"Grid\",\n \"Card\",\n \"Tabs\",\n \"Title\",\n \"Text\",\n \"Label\",\n \"Badge\",\n \"Math\",\n \"Link\",\n \"Button\",\n \"Form\",\n \"TextField\",\n \"Select\",\n \"CheckBox\",\n \"RadioGroup\",\n \"Slider\",\n \"SegmentedControl\",\n \"ChoicePicker\",\n \"FlashcardFlip\",\n \"Table\",\n \"List\",\n \"Chart\",\n \"Map\",\n \"Image\",\n \"Svg\",\n \"Citation\",\n \"FollowUp\",\n \"EntityCard\",\n]);\n\nexport function defaultGenerativeUIPromptSpec(): GenerativeUIPromptSpec {\n return {\n markdown: {\n intro:\n \"You can show interactive UI in your reply. Write A2UI operations inside a fenced code block tagged a2ui.\",\n whenToShow: GENERATIVE_UI_MARKDOWN_WHEN_TO_SHOW,\n rules: [\n \"Write explanations as normal markdown prose outside the fences.\",\n \"Open a fence with ```a2ui to show the surface in the chat, at the place of the fence.\",\n \"Open a fence with ```a2ui target=<id> to show the surface in a named target. Use only target ids from the schema. When a target limits its components, its surfaces can use only those components.\",\n \"Inside a fence, write one JSON object per line and nothing else. No comments, no trailing commas, no pretty-printing.\",\n \"Keep each operation whole on its line.\",\n 'Give every operation \"version\":\"1.0\".',\n 'Start a surface with one createSurface. Put all the initial data in \"dataModel\" and the \"root\" component in \"components\". Then write the children in updateComponents lines, so that they show while you write:\\n ```a2ui\\n {\"version\":\"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 ```',\n 'Keep \"dataModel\" flat: top-level keys such as \"seats\" or \"form\", never one wrapper object around everything. Check that every { and [ you open in a line is closed.',\n 'Every surface renders from the component with id \"root\". Make every other component reachable from \"root\" through slots.',\n \"Send every component you reference in the same reply. If a surface gets long, make it smaller rather than leave components out.\",\n \"Use unique ids. Do not make cycles. A component cannot be its own child.\",\n 'Write a component as one flat object: {\"id\":\"title\",\"component\":\"<Name>\",\"text\":\"Hello\"}.',\n '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.',\n '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\"}}}.',\n '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.',\n 'Put the component name in \"component\" (never \"type\"). Put props next to it, never inside a \"props\" object.',\n 'A component may take \"accessibility\":{\"label\":\"<1 to 3 words>\",\"description\":\"<what it does>\"} for screen readers: on the component it describes, when nothing visible names it. Not on every component. \"live\":\"polite\" goes only inside \"accessibility\" ({\"accessibility\":{\"live\":\"polite\"}}), only on text that changes by itself, never as a prop of the component.',\n \"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.\",\n 'Give a prop a literal value, or bind it to the data model with {\"@path\":\"/x\"}. Never write {\"path\":\"/x\"} as a binding.',\n 'A prop can also be a function value that updates with the data: {\"@call\":\"formatCurrency\",\"args\":{\"value\":{\"@path\":\"/total\"},\"currency\":\"EUR\"}}. Use only the functions in the schema. Write a literal when the value never changes.',\n 'formatString interpolates ${...}: {\"@call\":\"formatString\",\"args\":{\"value\":\"${/qty} × ${formatCurrency(value: /price, currency: \\'EUR\\')}\"}}. Inside ${...}, a path has no quotes, a string has single quotes, and a function takes named args.',\n '${...} is evaluated only in the value of formatString and in the item of series; in other strings it stays literal text. Inside formatString, ${...} does not support operators. For arithmetic use calc, with the values as named args: {\"@call\":\"calc\",\"args\":{\"expression\":\"seats * 29 * (annual ? 0.8 : 1)\",\"seats\":{\"@path\":\"/seats\"},\"annual\":{\"@path\":\"/annual\"}}}. Inside formatString: ${formatCurrency(value: calc(expression: \\'seats * 29\\', seats: /seats), currency: \\'USD\\')}. The UI then follows the user\\'s input with no round trip.',\n \"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.\",\n 'To show one of two texts, let calc choose: \"text\":{\"@call\":\"calc\",\"args\":{\"expression\":\"billing == \\'yearly\\' ? \\'per year\\' : \\'per month\\'\",\"billing\":{\"@path\":\"/billing\"}}}.',\n 'For a computed list (chart data, template items) use series. Its description under Functions in the schema gives the rules and an example. Bind the \"data\" of a Chart or the \"items\" of a List to it; a template path stays a literal path.',\n 'Bind a writable prop to let the user edit it: \"value\":{\"@path\":\"/form/email\"}. The user\\'s input goes to that path.',\n '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.',\n '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\".',\n 'Set \"value\":null to delete the key at \"path\".',\n {\n when: [\"events\"],\n items: [\n 'Give an event prop an object: {\"event\":{\"name\":\"<name>\",\"userMessage\":\"<text>\",\"context\":{...}}} or {\"functionCall\":{\"@call\":\"<function>\",\"args\":{...}}}. Never a flat {\"event\":\"<name>\"}.',\n '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.',\n ],\n },\n {\n when: [\"events\", \"functions\"],\n items: [\n 'Use {\"functionCall\": ...} to run a function in the browser when the user clicks: an app function from the schema, or openUrl: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.',\n ],\n },\n {\n when: [\"events\", \"noFunctions\"],\n items: [\n 'Use {\"functionCall\": ...} to open a URL when the user clicks: {\"functionCall\":{\"@call\":\"openUrl\",\"args\":{\"url\":\"https://example.com\"}}}. You are not told about the call.',\n ],\n },\n {\n when: [\"events\"],\n items: [\n 'Use {\"event\": ...} to send the interaction back to you as a user message. Put the text of that message in \"userMessage\": {\"event\":{\"name\":\"choose\",\"userMessage\":\"Show me the Team plan\"}}. \"userMessage\" is plain text: ${...} is not interpolated in it; put values in \"context\".',\n 'To send input values with an event, bind them in the context: \"context\":{\"email\":{\"@path\":\"/form/email\"}}.',\n \"A button or other event prop without an event or functionCall does nothing.\",\n ],\n },\n {\n when: [\"checks\"],\n items: [\n 'Validate an input with \"checks\": [{\"condition\":{\"@call\":\"email\",\"args\":{\"value\":{\"@path\":\"/form/email\"}}},\"message\":\"Enter a valid email\"}]. The check functions are required, regex, length, numeric and email; a condition can also be a boolean {\"@path\"}. A failed check shows the message under the input and disables a Button that has the same checks.',\n ],\n },\n 'A prop typed componentId takes the id of another component, and a childList takes ids [\"a\",\"b\"]: \"child\":\"card\", \"children\":[\"a\",\"b\"], \"tabs\":[{\"title\":\"Specs\",\"child\":\"specs\"}].',\n {\n when: [\"templates\"],\n items: [\n 'To repeat a component for each item of a list, give a childList a template: \"children\":{\"componentId\":\"row\",\"path\":\"/items\"}.',\n 'Inside a template, paths are relative to the item (\"name\", not \"/name\").',\n 'Inside a template, {\"@call\":\"@index\"} gives the position of the item, from 0. To count from 1, write {\"@call\":\"@index\",\"args\":{\"offset\":1}}.',\n ],\n },\n \"Updating a component replaces all of its props. Send every prop again.\",\n \"To change a surface in this reply, write another fence with the same surfaceId. Do not send createSurface again. The surface changes where it already is. A surface in a target can also be changed from a later reply; a chat surface cannot, because the chat is a transcript: a later reply with the same surfaceId makes a new surface.\",\n \"Use a new surfaceId for a different view. Never use a surfaceId again, also after the surface is deleted.\",\n {\n when: [\"agentCalls\"],\n items: [\n '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.',\n \"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.\",\n '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.',\n \"Do not guess the result of a callRendererFunction. Wait for the developer message.\",\n ],\n },\n '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.',\n \"Never make a surface that is only prose. Write headings, paragraphs, lists of text, intros, and summaries as markdown outside the fences, also between two fences.\",\n \"Put in a fence only what markdown cannot show: charts, tables, maps, images, badges, inputs, buttons, cards with controls.\",\n \"Use Card only for an interactive panel (controls, a form, a configurator). Put everything else in a plain layout component.\",\n \"Never wrap the whole reply in a fence.\",\n ],\n },\n tool: {\n intro: `Call \\`${GENERATIVE_UI_RENDER_TOOL}\\` to show UI. Arguments: \\`target\\` first, then \\`operations\\` (A2UI v1.0 operations, applied in order).`,\n whenToShow: GENERATIVE_UI_WHEN_TO_SHOW,\n operations: [\n '{\"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.',\n '{\"version\":\"1.0\",\"updateComponents\":{\"surfaceId\":\"<id>\",\"components\":[<component>, ...]}}: add or replace components by id.',\n '{\"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\".',\n '{\"version\":\"1.0\",\"deleteSurface\":{\"surfaceId\":\"<id>\"}}: remove the surface.',\n {\n when: [\"agentCalls\"],\n items: [\n '{\"version\":\"1.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 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 {\n when: [\"events\", \"functions\"],\n items: [\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 ],\n },\n {\n when: [\"events\", \"noFunctions\"],\n items: [\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 ],\n },\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 {\n when: [\"checks\"],\n items: [\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 {\n when: [\"templates\"],\n items: [\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 {\n when: [\"agentCalls\"],\n items: [\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\":\"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.',\n ],\n },\n ],\n },\n schema: {\n markdown: {\n notation: \"lines\",\n propDescriptions: true,\n commonProps: true,\n },\n tool: {\n notation: \"json-schema\",\n propDescriptions: true,\n commonProps: false,\n },\n },\n descriptions: {},\n };\n}\n\n/** Which features hold for a run. */\nexport type GenerativeUIPromptFeatures = Record<\n GenerativeUIPromptFeature,\n boolean\n>;\n\n/** The rules of `items` whose block conditions hold, in order. */\nexport function selectPromptItems(\n items: readonly GenerativeUIPromptItem[],\n features: GenerativeUIPromptFeatures,\n): string[] {\n return items.flatMap((item) =>\n typeof item === \"string\"\n ? [item]\n : item.when.every((feature) => features[feature])\n ? item.items\n : [],\n );\n}\n\n/**\n * The prompt features of a run, from the guide features of its manifest\n * (`generativeUIGuideFeatures`).\n */\nexport function generativeUIPromptFeatures(guide: {\n functions: boolean;\n events: boolean;\n templates: boolean;\n checks: boolean;\n}): GenerativeUIPromptFeatures {\n return {\n functions: guide.functions,\n noFunctions: !guide.functions,\n events: guide.events,\n templates: guide.templates,\n checks: guide.checks,\n agentCalls: guide.functions && GENERATIVE_UI_AGENT_FUNCTION_CALLS,\n };\n}\n"],"mappings":";;;;;;;;AA6EA,MAAa,6BACX;;;;;;AAOF,MAAa,sCACX;;;;;;AAOF,MAAa,mBAAwC,IAAI,IAAI;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,gCAAwD;AACtE,QAAO;EACL,UAAU;GACR,OACE;GACF,YAAY;GACZ,OAAO;IACL;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;KACE,MAAM,CAAC,SAAS;KAChB,OAAO,CACL,sNACA,qOACD;KACF;IACD;KACE,MAAM,CAAC,UAAU,YAAY;KAC7B,OAAO,CACL,0PACD;KACF;IACD;KACE,MAAM,CAAC,UAAU,cAAc;KAC/B,OAAO,CACL,0LACD;KACF;IACD;KACE,MAAM,CAAC,SAAS;KAChB,OAAO;MACL;MACA;MACA;MACD;KACF;IACD;KACE,MAAM,CAAC,SAAS;KAChB,OAAO,CACL,uXACD;KACF;IACD;IACA;KACE,MAAM,CAAC,YAAY;KACnB,OAAO;MACL;MACA;MACA;MACD;KACF;IACD;IACA;IACA;IACA;KACE,MAAM,CAAC,aAAa;KACpB,OAAO;MACL;MACA;MACA;MACA;MACD;KACF;IACD;IACA;IACA;IACA;IACA;IACD;GACF;EACD,MAAM;GACJ,OAAO,UAAU,0BAA0B;GAC3C,YAAY;GACZ,YAAY;IACV;IACA;IACA;IACA;IACA;KACE,MAAM,CAAC,aAAa;KACpB,OAAO,CACL,+MACD;KACF;IACF;GACD,OAAO;IACL;IACA;IACA;IACA;IACA;IACA;KACE,MAAM,CAAC,UAAU,YAAY;KAC7B,OAAO,CACL,qdACD;KACF;IACD;KACE,MAAM,CAAC,UAAU,cAAc;KAC/B,OAAO,CACL,sSACD;KACF;IACD;IACA;IACA;IACA;IACA;IACA;KACE,MAAM,CAAC,SAAS;KAChB,OAAO,CACL,wUACD;KACF;IACD;KACE,MAAM,CAAC,YAAY;KACnB,OAAO,CACL,0VACD;KACF;IACD;KACE,MAAM,CAAC,aAAa;KACpB,OAAO,CACL,6PACA,2TACD;KACF;IACF;GACF;EACD,QAAQ;GACN,UAAU;IACR,UAAU;IACV,kBAAkB;IAClB,aAAa;IACd;GACD,MAAM;IACJ,UAAU;IACV,kBAAkB;IAClB,aAAa;IACd;GACF;EACD,cAAc,EAAE;EACjB;;;AAUH,SAAgB,kBACd,OACA,UACU;AACV,QAAO,MAAM,SAAS,SACpB,OAAO,SAAS,WACZ,CAAC,KAAK,GACN,KAAK,KAAK,OAAO,YAAY,SAAS,SAAS,GAC7C,KAAK,QACL,EAAE,CACT;;;;;;AAOH,SAAgB,2BAA2B,OAKZ;AAC7B,QAAO;EACL,WAAW,MAAM;EACjB,aAAa,CAAC,MAAM;EACpB,QAAQ,MAAM;EACd,WAAW,MAAM;EACjB,QAAQ,MAAM;EACd,YAAY,MAAM,aAAa;EAChC"}
|
|
@@ -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":"
|
|
50
|
+
${whenToShow ? `${whenToShow}\n\n` : ""}Every operation has "version":"1.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":";;;;;AAWA,MAAa,oCACX;;AAGF,MAAM,yBAAyB;;AAG/B,SAAS,QAAQ,MAAc;AAC7B,QAAO,KAAK,SAAS,yBACjB,GAAG,KAAK,MAAM,GAAG,uBAAuB,CAAC,OACzC;;;;;;;AAQN,SAAgB,wBAAwB,UAAgC;CACtE,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,OAAO,QAAQ,SAAS,WAAW,CACnD,KAAK,CAAC,MAAM,OAAO;EAClB,MAAM,QAAQ,CACZ,OAAO,KAAK,IAAI,EAAE,cAAc,KAAK,EAAE,gBAAgB,MACvD,YAAY,KAAK,UAAU,EAAE,MAAM,GACpC;AACD,MAAI,EAAE,OAAQ,OAAM,KAAK,kBAAkB,KAAK,UAAU,EAAE,OAAO,GAAG;AACtE,MAAI,EAAE,MACJ,OAAM,KAAK,iCAAiC,KAAK,UAAU,EAAE,MAAM,GAAG;AACxE,SAAO,MAAM,KAAK,KAAK;GACvB,CACD,KAAK,KAAK;CACb,MAAM,YAAY,OAAO,QAAQ,SAAS,UAAU,CACjD,KAAK,CAAC,MAAM,OAAO;EAGlB,MAAM,YAAY,EAAE,WAAW;EAC/B,MAAM,OACJ,OAAO,cAAc,YACrB,U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EACP;AAED,QAAO;EACL;SACKE,wCAA0B;;EAEjCC,gDAA2B;;;EAG3B,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
|
+
{"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\":\"1.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,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5D,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":"
|
|
50
|
+
${whenToShow ? `${whenToShow}\n\n` : ""}Every operation has "version":"1.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":";;;;;AAWA,MAAa,oC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AkB,aAAa;EAC/B,0BAA0B,eAAe,YAAY;EACtD,CAAC,KAAK,OAAO"}
|
|
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\":\"1.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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-ui-args.cjs","names":["isRecord"],"sources":["../../src/generative-ui/render-ui-args.ts"],"sourcesContent":["import { isRecord } from \"./is-record\";\nexport interface ExtractedRenderUIArgs {\n target?: string;\n /**\n * Complete elements of the `operations` array, in order. A balanced element\n * that is not a valid JSON object is returned as `null`.\n */\n operations: Array<Record<string, unknown> | null>;\n /**\n * Set when an `operations[]` element was opened but its closing brace never\n * arrived: the text ends mid-operation (still streaming, or truncated).\n */\n incompleteOperation?: boolean;\n}\n\n/**\n * Reads `target` and every complete `operations[]` element from a possibly\n * truncated `render_ui` argument string.\n */\nexport function extractRenderUIArgs(text: string) {\n return new RenderUIArgsScanner().scan(text);\n}\n\n/**\n * The parser of {@link extractRenderUIArgs}, with its state kept between\n * calls. Each call scans only the text after the text it scanned before, so\n * a streamed argument string is scanned once in total.\n */\nclass RenderUIArgsScanner {\n private readonly result: ExtractedRenderUIArgs = { operations: [] };\n private readonly stack: Array<\"{\" | \"[\"> = [];\n private inString = false;\n private escaped = false;\n private stringStart = -1;\n private pendingKey: string | null = null;\n private currentKey: string | null = null;\n private expectingValue = false;\n private inOperations = false;\n private elementStart = -1;\n private scanned = 0;\n\n /**\n * Scans `text` from where the last call stopped.\n *\n * @param text - The whole text so far. It starts with the text of the\n * last call.\n * @returns The result so far. It is the same object on each call.\n */\n scan(text: string) {\n const { result, stack } = this;\n let {\n inString,\n escaped,\n stringStart,\n pendingKey,\n currentKey,\n expectingValue,\n inOperations,\n elementStart,\n } = this;\n for (let i = this.scanned; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === \"\\\\\") {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n if (stack.length === 1) {\n const literal = text.slice(stringStart, i + 1);\n if (expectingValue) {\n if (currentKey === \"target\") {\n try {\n result.target = JSON.parse(literal);\n } catch {\n // Unreachable for a closed literal; keep scanning.\n }\n }\n expectingValue = false;\n } else {\n pendingKey = literal;\n }\n }\n }\n continue;\n }\n switch (ch) {\n case '\"':\n inString = true;\n stringStart = i;\n break;\n case \":\":\n if (stack.length === 1 && pendingKey !== null) {\n try {\n currentKey = JSON.parse(pendingKey);\n } catch {\n currentKey = null;\n }\n pendingKey = null;\n expectingValue = true;\n }\n break;\n case \",\":\n if (stack.length === 1) {\n expectingValue = false;\n currentKey = null;\n }\n break;\n case \"{\":\n if (inOperations && stack.length === 2) elementStart = i;\n stack.push(\"{\");\n break;\n case \"[\":\n if (\n stack.length === 1 &&\n expectingValue &&\n currentKey === \"operations\"\n ) {\n inOperations = true;\n }\n stack.push(\"[\");\n break;\n case \"}\":\n case \"]\":\n stack.pop();\n if (\n ch === \"}\" &&\n inOperations &&\n stack.length === 2 &&\n elementStart >= 0\n ) {\n result.operations.push(\n parseObject(text.slice(elementStart, i + 1)),\n );\n elementStart = -1;\n }\n if (ch === \"]\" && inOperations && stack.length === 1) {\n inOperations = false;\n expectingValue = false;\n }\n break;\n }\n }\n this.inString = inString;\n this.escaped = escaped;\n this.stringStart = stringStart;\n this.pendingKey = pendingKey;\n this.currentKey = currentKey;\n this.expectingValue = expectingValue;\n this.inOperations = inOperations;\n this.elementStart = elementStart;\n this.scanned = text.length;\n if (elementStart >= 0) result.incompleteOperation = true;\n else delete result.incompleteOperation;\n return result;\n }\n}\n\nfunction parseObject(raw: string) {\n try {\n const value: unknown = JSON.parse(raw);\n return isRecord(value) ? value : null;\n } catch {\n return null;\n }\n}\n\n/** Feeds streamed argument deltas and reports operations not yet seen. */\nexport class RenderUIArgsStream {\n private buffer = \"\";\n private emitted = 0;\n private incomplete = false;\n private readonly scanner = new RenderUIArgsScanner();\n\n push(delta: string) {\n this.buffer += delta;\n const { target, operations, incompleteOperation } = this.scanner.scan(\n this.buffer,\n );\n const newOperations = operations.slice(this.emitted);\n this.emitted = operations.length;\n this.incomplete = incompleteOperation === true;\n return { target, newOperations };\n }\n\n /** Every argument delta received so far, concatenated. */\n get text() {\n return this.buffer;\n }\n\n /**\n * True when the text received so far ends inside an `operations[]` element.\n * Once the tool call has ended, that element was truncated.\n */\n get hasIncompleteOperation() {\n return this.incomplete;\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,oBAAoB,MAAc;AAChD,QAAO,IAAI,qBAAqB,CAAC,KAAK,KAAK;;;;;;;AAQ7C,IAAM,sBAAN,MAA0B;;gBACyB,EAAE,YAAY,E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AAEjB,SAAI,OAAO,OAAO,gBAAgB,MAAM,WAAW,GAAG;AACpD,qBAAe;AACf,uBAAiB;;AAEnB;;;AAGN,OAAK,WAAW;AAChB,OAAK,UAAU;AACf,OAAK,cAAc;AACnB,OAAK,aAAa;AAClB,OAAK,aAAa;AAClB,OAAK,iBAAiB;AACtB,OAAK,eAAe;AACpB,OAAK,eAAe;AACpB,OAAK,UAAU,KAAK;AACpB,MAAI,gBAAgB,EAAG,QAAO,sBAAsB;MAC/C,QAAO,OAAO;AACnB,SAAO;;;AAIX,SAAS,YAAY,KAAa;AAChC,KAAI;EACF,MAAM,QAAiB,KAAK,MAAM,IAAI;AACtC,SAAOA,2BAAS,MAAM,GAAG,QAAQ;SAC3B;AACN,SAAO;;;;AAKX,IAAa,qBAAb,MAAgC;;gBACb;iBACC;oBACG;iBACM,IAAI,qBAAqB;;CAEpD,KAAK,OAAe;AAClB,OAAK,UAAU;EACf,MAAM,EAAE,QAAQ,YAAY,wBAAwB,KAAK,QAAQ,KAC/D,KAAK,OACN;EACD,MAAM,gBAAgB,WAAW,MAAM,KAAK,QAAQ;AACpD,OAAK,UAAU,WAAW;AAC1B,OAAK,aAAa,wBAAwB;AAC1C,SAAO;GAAE;GAAQ;GAAe;;;CAIlC,IAAI,OAAO;AACT,SAAO,KAAK;;;;;;CAOd,IAAI,yBAAyB;AAC3B,SAAO,KAAK"}
|
|
1
|
+
{"version":3,"file":"render-ui-args.cjs","names":["isRecord"],"sources":["../../src/generative-ui/render-ui-args.ts"],"sourcesContent":["import { isRecord } from \"./is-record\";\nexport interface ExtractedRenderUIArgs {\n target?: string;\n /**\n * Complete elements of the `operations` array, in order. A balanced element\n * that is not a valid JSON object is returned as `null`.\n */\n operations: Array<Record<string, unknown> | null>;\n /**\n * Set when an `operations[]` element was opened but its closing brace never\n * arrived: the text ends mid-operation (still streaming, or truncated).\n */\n incompleteOperation?: boolean;\n}\n\n/**\n * Reads `target` and every complete `operations[]` element from a possibly\n * truncated `render_ui` argument string.\n */\nexport function extractRenderUIArgs(text: string) {\n return new RenderUIArgsScanner().scan(text);\n}\n\n/**\n * The parser of {@link extractRenderUIArgs}, with its state kept between\n * calls. Each call scans only the text after the text it scanned before, so\n * a streamed argument string is scanned once in total.\n */\nclass RenderUIArgsScanner {\n private readonly result: ExtractedRenderUIArgs = { operations: [] };\n private readonly stack: Array<\"{\" | \"[\"> = [];\n private inString = false;\n private escaped = false;\n private stringStart = -1;\n private pendingKey: string | null = null;\n private currentKey: string | null = null;\n private expectingValue = false;\n private inOperations = false;\n private elementStart = -1;\n private scanned = 0;\n\n /**\n * Scans `text` from where the last call stopped.\n *\n * @param text - The whole text so far. It starts with the text of the\n * last call.\n * @returns The result so far. It is the same object on each call.\n */\n scan(text: string) {\n const { result, stack } = this;\n let {\n inString,\n escaped,\n stringStart,\n pendingKey,\n currentKey,\n expectingValue,\n inOperations,\n elementStart,\n } = this;\n for (let i = this.scanned; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === \"\\\\\") {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n if (stack.length === 1) {\n const literal = text.slice(stringStart, i + 1);\n if (expectingValue) {\n if (currentKey === \"target\") {\n try {\n result.target = JSON.parse(literal);\n } catch {\n // Unreachable for a closed literal; keep scanning.\n }\n }\n expectingValue = false;\n } else {\n pendingKey = literal;\n }\n }\n }\n continue;\n }\n switch (ch) {\n case '\"':\n inString = true;\n stringStart = i;\n break;\n case \":\":\n if (stack.length === 1 && pendingKey !== null) {\n try {\n currentKey = JSON.parse(pendingKey);\n } catch {\n currentKey = null;\n }\n pendingKey = null;\n expectingValue = true;\n }\n break;\n case \",\":\n if (stack.length === 1) {\n expectingValue = false;\n currentKey = null;\n }\n break;\n case \"{\":\n if (inOperations && stack.length === 2) elementStart = i;\n stack.push(\"{\");\n break;\n case \"[\":\n if (\n stack.length === 1 &&\n expectingValue &&\n currentKey === \"operations\"\n ) {\n inOperations = true;\n }\n stack.push(\"[\");\n break;\n case \"}\":\n case \"]\":\n stack.pop();\n if (\n ch === \"}\" &&\n inOperations &&\n stack.length === 2 &&\n elementStart >= 0\n ) {\n result.operations.push(\n parseObject(text.slice(elementStart, i + 1)),\n );\n elementStart = -1;\n }\n if (ch === \"]\" && inOperations && stack.length === 1) {\n inOperations = false;\n expectingValue = false;\n }\n break;\n case undefined:\n // Unreachable: `i < text.length`, so `text[i]` is always a char.\n break;\n }\n }\n this.inString = inString;\n this.escaped = escaped;\n this.stringStart = stringStart;\n this.pendingKey = pendingKey;\n this.currentKey = currentKey;\n this.expectingValue = expectingValue;\n this.inOperations = inOperations;\n this.elementStart = elementStart;\n this.scanned = text.length;\n if (elementStart >= 0) result.incompleteOperation = true;\n else delete result.incompleteOperation;\n return result;\n }\n}\n\nfunction parseObject(raw: string) {\n try {\n const value: unknown = JSON.parse(raw);\n return isRecord(value) ? value : null;\n } catch {\n return null;\n }\n}\n\n/** Feeds streamed argument deltas and reports operations not yet seen. */\nexport class RenderUIArgsStream {\n private buffer = \"\";\n private emitted = 0;\n private incomplete = false;\n private readonly scanner = new RenderUIArgsScanner();\n\n push(delta: string) {\n this.buffer += delta;\n const { target, operations, incompleteOperation } = this.scanner.scan(\n this.buffer,\n );\n const newOperations = operations.slice(this.emitted);\n this.emitted = operations.length;\n this.incomplete = incompleteOperation === true;\n return { target, newOperations };\n }\n\n /** Every argument delta received so far, concatenated. */\n get text() {\n return this.buffer;\n }\n\n /**\n * True when the text received so far ends inside an `operations[]` element.\n * Once the tool call has ended, that element was truncated.\n */\n get hasIncompleteOperation() {\n return this.incomplete;\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,oBAAoB,MAAc;AAChD,QAAO,IAAI,qBAAqB,CAAC,KAAK,KAAK;;;;;;;AAQ7C,IAAM,sBAAN,MAA0B;;gBACyB,EAAE,YAAY,EAAE,EAAE;eACxB,EAAE;kBAC1B;iBACD;qBACI;oBACc;oBACA;wBACX;sBACF;sBACA;iBACL;;;;;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B;IACF,KAAK,OAEH;;;AAGN,OAAK,WAAW;AAChB,OAAK,UAAU;AACf,OAAK,cAAc;AACnB,OAAK,aAAa;AAClB,OAAK,aAAa;AAClB,OAAK,iBAAiB;AACtB,OAAK,eAAe;AACpB,OAAK,eAAe;AACpB,OAAK,UAAU,KAAK;AACpB,MAAI,gBAAgB,EAAG,QAAO,sBAAsB;MAC/C,QAAO,OAAO;AACnB,SAAO;;;AAIX,SAAS,YAAY,KAAa;AAChC,KAAI;EACF,MAAM,QAAiB,KAAK,MAAM,IAAI;AACtC,SAAOA,2BAAS,MAAM,GAAG,QAAQ;SAC3B;AACN,SAAO;;;;AAKX,IAAa,qBAAb,MAAgC;;gBACb;iBACC;oBACG;iBACM,IAAI,qBAAqB;;CAEpD,KAAK,OAAe;AAClB,OAAK,UAAU;EACf,MAAM,EAAE,QAAQ,YAAY,wBAAwB,KAAK,QAAQ,KAC/D,KAAK,OACN;EACD,MAAM,gBAAgB,WAAW,MAAM,KAAK,QAAQ;AACpD,OAAK,UAAU,WAAW;AAC1B,OAAK,aAAa,wBAAwB;AAC1C,SAAO;GAAE;GAAQ;GAAe;;;CAIlC,IAAI,OAAO;AACT,SAAO,KAAK;;;;;;CAOd,IAAI,yBAAyB;AAC3B,SAAO,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-ui-args.d.cts","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"mappings":";UACiB,qBAAA;EACf,MAAA;EADoC;;;;EAMpC,UAAA,EAAY,KAAA,CAAM,MAAA;EAAN;;;;EAKZ,mBAAA;AAAA;;;;;iBAOc,mBAAA,CAAoB,IAAA,WAAY,qBAAA;;
|
|
1
|
+
{"version":3,"file":"render-ui-args.d.cts","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"mappings":";UACiB,qBAAA;EACf,MAAA;EADoC;;;;EAMpC,UAAA,EAAY,KAAA,CAAM,MAAA;EAAN;;;;EAKZ,mBAAA;AAAA;;;;;iBAOc,mBAAA,CAAoB,IAAA,WAAY,qBAAA;;cAyJnC,kBAAA;EAAA,QACH,MAAA;EAAA,QACA,OAAA;EAAA,QACA,UAAA;EAAA,iBACS,OAAA;EAEjB,IAAA,CAAK,KAAA;;oBANwB,MAAA;EAAA;;MAkBzB,IAAA,CAAA;EAAA;;;;EAAA,IAQA,sBAAA,CAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-ui-args.d.mts","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"mappings":";UACiB,qBAAA;EACf,MAAA;EADoC;;;;EAMpC,UAAA,EAAY,KAAA,CAAM,MAAA;EAAN;;;;EAKZ,mBAAA;AAAA;;;;;iBAOc,mBAAA,CAAoB,IAAA,WAAY,qBAAA;;
|
|
1
|
+
{"version":3,"file":"render-ui-args.d.mts","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"mappings":";UACiB,qBAAA;EACf,MAAA;EADoC;;;;EAMpC,UAAA,EAAY,KAAA,CAAM,MAAA;EAAN;;;;EAKZ,mBAAA;AAAA;;;;;iBAOc,mBAAA,CAAoB,IAAA,WAAY,qBAAA;;cAyJnC,kBAAA;EAAA,QACH,MAAA;EAAA,QACA,OAAA;EAAA,QACA,UAAA;EAAA,iBACS,OAAA;EAEjB,IAAA,CAAK,KAAA;;oBANwB,MAAA;EAAA;;MAkBzB,IAAA,CAAA;EAAA;;;;EAAA,IAQA,sBAAA,CAAA;AAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-ui-args.mjs","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"sourcesContent":["import { isRecord } from \"./is-record\";\nexport interface ExtractedRenderUIArgs {\n target?: string;\n /**\n * Complete elements of the `operations` array, in order. A balanced element\n * that is not a valid JSON object is returned as `null`.\n */\n operations: Array<Record<string, unknown> | null>;\n /**\n * Set when an `operations[]` element was opened but its closing brace never\n * arrived: the text ends mid-operation (still streaming, or truncated).\n */\n incompleteOperation?: boolean;\n}\n\n/**\n * Reads `target` and every complete `operations[]` element from a possibly\n * truncated `render_ui` argument string.\n */\nexport function extractRenderUIArgs(text: string) {\n return new RenderUIArgsScanner().scan(text);\n}\n\n/**\n * The parser of {@link extractRenderUIArgs}, with its state kept between\n * calls. Each call scans only the text after the text it scanned before, so\n * a streamed argument string is scanned once in total.\n */\nclass RenderUIArgsScanner {\n private readonly result: ExtractedRenderUIArgs = { operations: [] };\n private readonly stack: Array<\"{\" | \"[\"> = [];\n private inString = false;\n private escaped = false;\n private stringStart = -1;\n private pendingKey: string | null = null;\n private currentKey: string | null = null;\n private expectingValue = false;\n private inOperations = false;\n private elementStart = -1;\n private scanned = 0;\n\n /**\n * Scans `text` from where the last call stopped.\n *\n * @param text - The whole text so far. It starts with the text of the\n * last call.\n * @returns The result so far. It is the same object on each call.\n */\n scan(text: string) {\n const { result, stack } = this;\n let {\n inString,\n escaped,\n stringStart,\n pendingKey,\n currentKey,\n expectingValue,\n inOperations,\n elementStart,\n } = this;\n for (let i = this.scanned; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === \"\\\\\") {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n if (stack.length === 1) {\n const literal = text.slice(stringStart, i + 1);\n if (expectingValue) {\n if (currentKey === \"target\") {\n try {\n result.target = JSON.parse(literal);\n } catch {\n // Unreachable for a closed literal; keep scanning.\n }\n }\n expectingValue = false;\n } else {\n pendingKey = literal;\n }\n }\n }\n continue;\n }\n switch (ch) {\n case '\"':\n inString = true;\n stringStart = i;\n break;\n case \":\":\n if (stack.length === 1 && pendingKey !== null) {\n try {\n currentKey = JSON.parse(pendingKey);\n } catch {\n currentKey = null;\n }\n pendingKey = null;\n expectingValue = true;\n }\n break;\n case \",\":\n if (stack.length === 1) {\n expectingValue = false;\n currentKey = null;\n }\n break;\n case \"{\":\n if (inOperations && stack.length === 2) elementStart = i;\n stack.push(\"{\");\n break;\n case \"[\":\n if (\n stack.length === 1 &&\n expectingValue &&\n currentKey === \"operations\"\n ) {\n inOperations = true;\n }\n stack.push(\"[\");\n break;\n case \"}\":\n case \"]\":\n stack.pop();\n if (\n ch === \"}\" &&\n inOperations &&\n stack.length === 2 &&\n elementStart >= 0\n ) {\n result.operations.push(\n parseObject(text.slice(elementStart, i + 1)),\n );\n elementStart = -1;\n }\n if (ch === \"]\" && inOperations && stack.length === 1) {\n inOperations = false;\n expectingValue = false;\n }\n break;\n }\n }\n this.inString = inString;\n this.escaped = escaped;\n this.stringStart = stringStart;\n this.pendingKey = pendingKey;\n this.currentKey = currentKey;\n this.expectingValue = expectingValue;\n this.inOperations = inOperations;\n this.elementStart = elementStart;\n this.scanned = text.length;\n if (elementStart >= 0) result.incompleteOperation = true;\n else delete result.incompleteOperation;\n return result;\n }\n}\n\nfunction parseObject(raw: string) {\n try {\n const value: unknown = JSON.parse(raw);\n return isRecord(value) ? value : null;\n } catch {\n return null;\n }\n}\n\n/** Feeds streamed argument deltas and reports operations not yet seen. */\nexport class RenderUIArgsStream {\n private buffer = \"\";\n private emitted = 0;\n private incomplete = false;\n private readonly scanner = new RenderUIArgsScanner();\n\n push(delta: string) {\n this.buffer += delta;\n const { target, operations, incompleteOperation } = this.scanner.scan(\n this.buffer,\n );\n const newOperations = operations.slice(this.emitted);\n this.emitted = operations.length;\n this.incomplete = incompleteOperation === true;\n return { target, newOperations };\n }\n\n /** Every argument delta received so far, concatenated. */\n get text() {\n return this.buffer;\n }\n\n /**\n * True when the text received so far ends inside an `operations[]` element.\n * Once the tool call has ended, that element was truncated.\n */\n get hasIncompleteOperation() {\n return this.incomplete;\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,oBAAoB,MAAc;AAChD,QAAO,IAAI,qBAAqB,CAAC,KAAK,KAAK;;;;;;;AAQ7C,IAAM,sBAAN,MAA0B;;gBACyB,EAAE,YAAY,EAAE,EAAE;eACxB,EAAE;kBAC1B;iBACD;qBACI;oBACc;oBACA;wBACX;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Ae;AACf,uBAAiB;;AAEnB;;;AAGN,OAAK,WAAW;AAChB,OAAK,UAAU;AACf,OAAK,cAAc;AACnB,OAAK,aAAa;AAClB,OAAK,aAAa;AAClB,OAAK,iBAAiB;AACtB,OAAK,eAAe;AACpB,OAAK,eAAe;AACpB,OAAK,UAAU,KAAK;AACpB,MAAI,gBAAgB,EAAG,QAAO,sBAAsB;MAC/C,QAAO,OAAO;AACnB,SAAO;;;AAIX,SAAS,YAAY,KAAa;AAChC,KAAI;EACF,MAAM,QAAiB,KAAK,MAAM,IAAI;AACtC,SAAO,SAAS,MAAM,GAAG,QAAQ;SAC3B;AACN,SAAO;;;;AAKX,IAAa,qBAAb,MAAgC;;gBACb;iBACC;oBACG;iBACM,IAAI,qBAAqB;;CAEpD,KAAK,OAAe;AAClB,OAAK,UAAU;EACf,MAAM,EAAE,QAAQ,YAAY,wBAAwB,KAAK,QAAQ,KAC/D,KAAK,OACN;EACD,MAAM,gBAAgB,WAAW,MAAM,KAAK,QAAQ;AACpD,OAAK,UAAU,WAAW;AAC1B,OAAK,aAAa,wBAAwB;AAC1C,SAAO;GAAE;GAAQ;GAAe;;;CAIlC,IAAI,OAAO;AACT,SAAO,KAAK;;;;;;CAOd,IAAI,yBAAyB;AAC3B,SAAO,KAAK"}
|
|
1
|
+
{"version":3,"file":"render-ui-args.mjs","names":[],"sources":["../../src/generative-ui/render-ui-args.ts"],"sourcesContent":["import { isRecord } from \"./is-record\";\nexport interface ExtractedRenderUIArgs {\n target?: string;\n /**\n * Complete elements of the `operations` array, in order. A balanced element\n * that is not a valid JSON object is returned as `null`.\n */\n operations: Array<Record<string, unknown> | null>;\n /**\n * Set when an `operations[]` element was opened but its closing brace never\n * arrived: the text ends mid-operation (still streaming, or truncated).\n */\n incompleteOperation?: boolean;\n}\n\n/**\n * Reads `target` and every complete `operations[]` element from a possibly\n * truncated `render_ui` argument string.\n */\nexport function extractRenderUIArgs(text: string) {\n return new RenderUIArgsScanner().scan(text);\n}\n\n/**\n * The parser of {@link extractRenderUIArgs}, with its state kept between\n * calls. Each call scans only the text after the text it scanned before, so\n * a streamed argument string is scanned once in total.\n */\nclass RenderUIArgsScanner {\n private readonly result: ExtractedRenderUIArgs = { operations: [] };\n private readonly stack: Array<\"{\" | \"[\"> = [];\n private inString = false;\n private escaped = false;\n private stringStart = -1;\n private pendingKey: string | null = null;\n private currentKey: string | null = null;\n private expectingValue = false;\n private inOperations = false;\n private elementStart = -1;\n private scanned = 0;\n\n /**\n * Scans `text` from where the last call stopped.\n *\n * @param text - The whole text so far. It starts with the text of the\n * last call.\n * @returns The result so far. It is the same object on each call.\n */\n scan(text: string) {\n const { result, stack } = this;\n let {\n inString,\n escaped,\n stringStart,\n pendingKey,\n currentKey,\n expectingValue,\n inOperations,\n elementStart,\n } = this;\n for (let i = this.scanned; i < text.length; i++) {\n const ch = text[i];\n if (inString) {\n if (escaped) {\n escaped = false;\n } else if (ch === \"\\\\\") {\n escaped = true;\n } else if (ch === '\"') {\n inString = false;\n if (stack.length === 1) {\n const literal = text.slice(stringStart, i + 1);\n if (expectingValue) {\n if (currentKey === \"target\") {\n try {\n result.target = JSON.parse(literal);\n } catch {\n // Unreachable for a closed literal; keep scanning.\n }\n }\n expectingValue = false;\n } else {\n pendingKey = literal;\n }\n }\n }\n continue;\n }\n switch (ch) {\n case '\"':\n inString = true;\n stringStart = i;\n break;\n case \":\":\n if (stack.length === 1 && pendingKey !== null) {\n try {\n currentKey = JSON.parse(pendingKey);\n } catch {\n currentKey = null;\n }\n pendingKey = null;\n expectingValue = true;\n }\n break;\n case \",\":\n if (stack.length === 1) {\n expectingValue = false;\n currentKey = null;\n }\n break;\n case \"{\":\n if (inOperations && stack.length === 2) elementStart = i;\n stack.push(\"{\");\n break;\n case \"[\":\n if (\n stack.length === 1 &&\n expectingValue &&\n currentKey === \"operations\"\n ) {\n inOperations = true;\n }\n stack.push(\"[\");\n break;\n case \"}\":\n case \"]\":\n stack.pop();\n if (\n ch === \"}\" &&\n inOperations &&\n stack.length === 2 &&\n elementStart >= 0\n ) {\n result.operations.push(\n parseObject(text.slice(elementStart, i + 1)),\n );\n elementStart = -1;\n }\n if (ch === \"]\" && inOperations && stack.length === 1) {\n inOperations = false;\n expectingValue = false;\n }\n break;\n case undefined:\n // Unreachable: `i < text.length`, so `text[i]` is always a char.\n break;\n }\n }\n this.inString = inString;\n this.escaped = escaped;\n this.stringStart = stringStart;\n this.pendingKey = pendingKey;\n this.currentKey = currentKey;\n this.expectingValue = expectingValue;\n this.inOperations = inOperations;\n this.elementStart = elementStart;\n this.scanned = text.length;\n if (elementStart >= 0) result.incompleteOperation = true;\n else delete result.incompleteOperation;\n return result;\n }\n}\n\nfunction parseObject(raw: string) {\n try {\n const value: unknown = JSON.parse(raw);\n return isRecord(value) ? value : null;\n } catch {\n return null;\n }\n}\n\n/** Feeds streamed argument deltas and reports operations not yet seen. */\nexport class RenderUIArgsStream {\n private buffer = \"\";\n private emitted = 0;\n private incomplete = false;\n private readonly scanner = new RenderUIArgsScanner();\n\n push(delta: string) {\n this.buffer += delta;\n const { target, operations, incompleteOperation } = this.scanner.scan(\n this.buffer,\n );\n const newOperations = operations.slice(this.emitted);\n this.emitted = operations.length;\n this.incomplete = incompleteOperation === true;\n return { target, newOperations };\n }\n\n /** Every argument delta received so far, concatenated. */\n get text() {\n return this.buffer;\n }\n\n /**\n * True when the text received so far ends inside an `operations[]` element.\n * Once the tool call has ended, that element was truncated.\n */\n get hasIncompleteOperation() {\n return this.incomplete;\n }\n}\n"],"mappings":";;;;;;;AAmBA,SAAgB,oBAAoB,MAAc;AAChD,QAAO,IAAI,qBAAqB,CAAC,KAAK,KAAK;;;;;;;AAQ7C,IAAM,sBAAN,MAA0B;;gBACyB,EAAE,YAAY,EAAE,EAAE;eACxB,EAAE;kBAC1B;iBACD;qBACI;oBACc;oBACA;wBACX;sBACF;sBACA;iBACL;;;;;;;;;CASlB,KAAK,MAAc;EACjB,MAAM,EAAE,QAAQ,UAAU;EAC1B,IAAI,EAC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