{"version":3,"file":"A2UIInstructions.mjs","names":[],"sources":["../../../../src/plugins/A2UI/A2UIInstructions.ts"],"sourcesContent":["// What an agent is told to write A2UI with, and what checks it, without the A2UI packages: they\n// load when the instructions are asked for.\nimport type { AIUIComponent } from '../AIComponents/GenerativeUI/AIUIComponent';\nimport type { AIUIComponentDefinition } from '../AIComponents/GenerativeUI/AIUIComponentDefinition';\nimport { isRecord } from '../AIComponents/GenerativeUI/AIUIHelpers';\nimport type { AIUIClientToolDefinition } from '../AIComponents/GenerativeUI/AIUITools';\nimport { A2UI_VERSION } from './A2UIStream';\n\n/**\n * What an agent is told to write replies' UI in A2UI with: the basic catalog, or the part of it\n * `keep` names, with the app's components, and what the app adds. The same as the\n * `prompt.json` StreamChatA2UI's instructions are written from.\n */\nexport type A2UIInstructionsConfig = {\n  /** The id of the catalog with the app's components, as the renderer names it. */\n  catalogId?: string;\n  /** The app's components, or their portable definitions, such as a `UIComponents.json`. */\n  components?: (AIUIComponent | AIUIComponentDefinition)[];\n  /**\n   * Replies with their UI, as the agent should write them. Each block must render with the\n   * catalog, or no instructions are written: a broken example teaches the model broken UI.\n   */\n  examples?: string[];\n  /** The info string of a reply's UI block, as the agents router reads it. */\n  fence?: string;\n  /** The basic catalog's components and functions to describe; all of them when absent. */\n  keep?: string[];\n  /** Guidance on using the app's components. */\n  notes?: string[];\n  /** What the model is told first, such as which answers to write as UI. */\n  preamble?: string;\n  /** The basic catalog's components and functions to leave out, as the renderer does. */\n  remove?: string[];\n  /** Rules added after the protocol's. */\n  rules?: string[];\n  /** The app's tools the UI can call, each run on the person's device. */\n  tools?: AIUIClientToolDefinition[];\n};\n\n/** The A2UI an example holds that would not render, and why. */\nexport class A2UIInstructionsError extends Error {\n  readonly problems: string[];\n\n  constructor(problems: string[]) {\n    super(`An example's A2UI would not render:\\n${problems.join('\\n')}`);\n    this.name = 'A2UIInstructionsError';\n    this.problems = problems;\n  }\n}\n\n/** A description of the A2UI v1.0 messages and the rules that keep what they make valid. */\nexport const A2UI_PROTOCOL_OVERVIEW = `# Generating user interfaces with A2UI v1.0\n\nYou render user interfaces by emitting A2UI messages. Every message is a JSON object with a \\`\"version\": \"1.0\"\\` field plus exactly one of these keys:\n\n- \\`createSurface\\`: creates a surface. Requires \\`surfaceId\\`, and accepts \\`catalogId\\`, \\`sendDataModel\\`, \\`components\\` and \\`dataModel\\` so a complete UI can be sent in one message.\n- \\`updateComponents\\`: adds or replaces components of an existing surface. Requires \\`surfaceId\\` and \\`components\\`.\n- \\`updateDataModel\\`: writes to the surface data model. Requires \\`surfaceId\\` and \\`value\\`, and accepts a JSON Pointer \\`path\\`. Setting \\`value\\` to \\`null\\` deletes the entry at \\`path\\`.\n- \\`deleteSurface\\`: removes a surface. Requires \\`surfaceId\\`.\n- \\`callRendererFunction\\`: asks the renderer to run one of its functions.\n- \\`agentFunctionResponse\\`: answers a \\`callAgentFunction\\` request from the renderer.\n\nRules:\n\n1. Components are a flat adjacency list. Each component has a unique \\`id\\`, a \\`component\\` type, and its properties inline. Exactly one component must have the id \\`root\\`. An id is an identifier: letters, digits and underscores, not starting with a digit, such as \\`saturday_plan\\` (never \\`saturday-plan\\`).\n2. Children are referenced by id, never nested inline. Use an array of ids, or \\`{\"componentId\": \"...\", \"path\": \"/items\"}\\` to repeat a template for every item of a data model list.\n3. Any property may be a literal, a data binding \\`{\"@path\": \"/a/b\"}\\` or a function call \\`{\"@call\": \"name\", \"args\": {...}}\\`. Inside a list template, paths without a leading slash resolve relative to the current item, and \\`{\"@call\": \"@index\"}\\` returns the item's position. A literal object key that starts with \\`@\\` is written with \\`@@\\`, so \\`\"@@type\"\\` means \\`\"@type\"\\`.\n4. Put content that changes in the data model and bind to it, so you can update values with \\`updateDataModel\\` instead of resending components.\n5. Interactive components declare an \\`action\\`, which either dispatches an event to you (\\`{\"event\": {\"name\": \"...\", \"context\": {...}}}\\`) or runs a renderer function (\\`{\"functionCall\": {\"@call\": \"openUrl\", \"args\": {\"url\": \"...\"}}}\\`).\n6. Surface ids must be unique for the lifetime of the renderer. Creating a surface that already exists is an error: delete it first, or send \\`updateComponents\\` and \\`updateDataModel\\` to change it.`;\n\nexport const writing = (fence: string, catalogId: string) => `## Writing UI in A2UI\n\nWrite a reply's UI in one fenced block whose info string is \\`${fence}\\`, after one short sentence saying what it shows, which is what people read wherever the UI can't show. In the block, write A2UI messages, one JSON object per line, and nothing else:\n\n1. First a \\`createSurface\\` with a \\`surfaceId\\` new to this reply, the \\`catalogId\\` \\`${catalogId}\\`, and the \\`dataModel\\` the UI's inputs start from.\n2. Then \\`updateComponents\\` messages for that surface with a few components each, \\`root\\` first, so the UI shows as you write it.\n\nA reply's UI is shown as you wrote it: never write \\`callRendererFunction\\` or \\`agentFunctionResponse\\`, and never change an earlier reply's UI, but write a new one. What the person does in it comes back as their next message, which says what the button they tapped says. Give every event action a \\`userMessage\\` saying what it asks of you, such as \"Update the plan\", which comes back with it, and a \\`context\\` with what you need to know, bound to the data model.`;\n\n/** How the app's tools are introduced to the model, as StreamChatA2UI introduces them. */\nexport const TOOLS_INTRODUCTION = `## The app's tools\n\nThese run on the person's device. Call one as you call a function the catalog doesn't define, with \\`{\"@call\": \"<name>\", \"args\": {…}}\\`, and its output is the call's value. A read-only tool runs wherever you call it, such as in a binding that shows its output. Any other runs only from a button's \\`functionCall\\` action, when the person taps it.`;\n\n/**\n * One of the app's tools as the agent's instructions list it: its name, whether it only reads,\n * what it does, and the schema of its arguments.\n */\nexport const toolLine = ({\n  description,\n  inputSchema,\n  name,\n  readOnly,\n}: AIUIClientToolDefinition) =>\n  [\n    `- \\`${name}\\`${readOnly ? ' (read-only)' : ''}${description ? `: ${description}` : ''}`,\n    ...(inputSchema ? [`Arguments: \\`${JSON.stringify(sorted(inputSchema))}\\``] : []),\n  ].join(' ');\n\n// A JSON value with its object keys sorted, so the same catalog always reads the same.\nexport const sorted = (value: unknown): unknown =>\n  Array.isArray(value)\n    ? value.map(sorted)\n    : isRecord(value)\n      ? Object.fromEntries(\n          Object.keys(value)\n            .sort()\n            .map((key) => [key, sorted(value[key])]),\n        )\n      : value;\n\nexport const fenceOf = (fence?: string) => fence ?? `ui:a2ui@${A2UI_VERSION}`;\n\n// The A2UI blocks of an example reply.\nexport const blocksIn = (example: string, fence: string) =>\n  example\n    .split(`\\`\\`\\`${fence}\\n`)\n    .slice(1)\n    .map((block) => block.split('\\n```')[0]);\n\n/**\n * The instructions that teach an agent's model to write A2UI with the basic catalog and the\n * app's components, in Markdown, from the A2UI core's own catalog: the counterpart of\n * StreamChatA2UI's `A2UIInstructions`, from the same configuration as its `prompt.json`. Give\n * them to the agent's backend, as the part of its instructions about UI. It runs on a server or\n * in a build too, and rejects with an `A2UIInstructionsError` when an example would not render.\n */\nexport const a2uiInstructions = async (config: A2UIInstructionsConfig = {}) =>\n  (await import('./instructions')).a2uiInstructionsText(config);\n\n/**\n * What is wrong with the A2UI messages of `text`, such as an agent's example, for the catalog\n * `config` makes, or nothing when they render as written: messages the renderer can't read,\n * components it doesn't have or that don't fit their schemas, and references that lead nowhere.\n * The counterpart of StreamChatA2UI's `A2UIProgram.problems`.\n */\nexport const a2uiProblems = async (\n  text: string,\n  config: Pick<\n    A2UIInstructionsConfig,\n    'catalogId' | 'components' | 'keep' | 'remove'\n  > = {},\n) => (await import('./instructions')).a2uiProblemsIn(text, config);\n"],"mappings":";;;;AAwCA,IAAa,wBAAb,cAA2C,MAAM;CAC/C;CAEA,YAAY,UAAoB;EAC9B,MAAM,wCAAwC,SAAS,KAAK,IAAI,GAAG;EACnE,KAAK,OAAO;EACZ,KAAK,WAAW;CAClB;AACF;;AAGA,IAAa,yBAAyB;;;;;;;;;;;;;;;;;;;AAoBtC,IAAa,WAAW,OAAe,cAAsB;;gEAEG,MAAM;;2FAEqB,UAAU;;;;;AAMrG,IAAa,qBAAqB;;;;;;;AAQlC,IAAa,YAAY,EACvB,aACA,aACA,MACA,eAEA,CACE,OAAO,KAAK,IAAI,WAAW,iBAAiB,KAAK,cAAc,KAAK,gBAAgB,MACpF,GAAI,cAAc,CAAC,gBAAgB,KAAK,UAAU,OAAO,WAAW,CAAC,EAAE,GAAG,IAAI,CAAC,CACjF,CAAC,CAAC,KAAK,GAAG;AAGZ,IAAa,UAAU,UACrB,MAAM,QAAQ,KAAK,IACf,MAAM,IAAI,MAAM,IAChB,SAAS,KAAK,IACZ,OAAO,YACL,OAAO,KAAK,KAAK,CAAC,CACf,KAAK,CAAC,CACN,KAAK,QAAQ,CAAC,KAAK,OAAO,MAAM,IAAI,CAAC,CAAC,CAC3C,IACA;AAER,IAAa,WAAW,UAAmB,SAAS;AAGpD,IAAa,YAAY,SAAiB,UACxC,QACG,MAAM,SAAS,MAAM,GAAG,CAAC,CACzB,MAAM,CAAC,CAAC,CACR,KAAK,UAAU,MAAM,MAAM,OAAO,CAAC,CAAC,EAAE;;;;;;;;AAS3C,IAAa,mBAAmB,OAAO,SAAiC,CAAC,OACtE,MAAM,OAAO,sBAAA,CAAmB,qBAAqB,MAAM;;;;;;;AAQ9D,IAAa,eAAe,OAC1B,MACA,SAGI,CAAC,OACD,MAAM,OAAO,sBAAA,CAAmB,eAAe,MAAM,MAAM"}